Compare commits

..
Author SHA1 Message Date
Kurt Himebauch 62b61e64bb Merge remote-tracking branch 'origin/main' into pr-2265
# Conflicts:
#	app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt
2026-11-15 11:12:29 -05:00
Kurt Himebauch a0cd5b0cad fix: retain displayed bitmaps until rendering ends 2026-11-08 01:47:54 -05:00
Kurt Himebauch 97c6229e85 fix: bound previews and preserve skin artwork 2026-11-08 01:36:08 -05:00
Kurt Himebauch 0ff1bebdf6 fix: initialize game controls before launch 2026-11-08 01:19:16 -05:00
Kurt Himebauch e5824dabab feat: connect remote controller skin sources 2026-11-08 01:15:25 -05:00
Kurt Himebauch 8276b29b7d feat: add community on-screen controls 2026-11-08 01:01:08 -05:00
141 changed files with 2165 additions and 2730 deletions

No files matched your search

@@ -0,0 +1,39 @@
name: Community controls pack
description: Submit on-screen controls for the community catalog.
title: "[Controls]: "
body:
- type: markdown
attributes:
value: Export a ZIP from Controller settings → Community controls. Attach the ZIP and a screenshot below. Submissions are reviewed before inclusion in the catalog.
- type: input
id: name
attributes:
label: Pack name and author
validations:
required: true
- type: input
id: game
attributes:
label: Game (optional)
description: Include the store and game ID if these controls target a specific game.
- type: textarea
id: files
attributes:
label: Controls ZIP and screenshot
description: Drag the exported .ddcontrols.zip and a preview screenshot here. Describe the screen orientation and bindings.
validations:
required: true
- type: input
id: license
attributes:
label: License and artwork credits
description: Specify a license that permits redistribution, and credit any third-party artwork with its source and license.
validations:
required: true
- type: checkboxes
id: permission
attributes:
label: Distribution permission
options:
- label: I have permission to share this pack and all included artwork under the stated license.
required: true
+1 -1
View File
@@ -55,7 +55,7 @@ jobs:
jq -r --arg n "$2" '.assets // [] | .[] | select(.name == $n) | .digest // empty'
}
commit=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$BUILD_RUN" --jq .head_sha 2>/dev/null || echo "$GITHUB_SHA")
for name in proot directaudio tracking xbox comet butler powervr ubisoft rockstar dirt; do
for name in proot directaudio tracking xbox comet butler powervr ubisoft; do
file="packs/$name.tar.zst"
[ -f "$file" ] || { echo "::error::$name.tar.zst is missing from Build APK run $BUILD_RUN"; exit 1; }
sha=$(sha256sum "$file" | cut -d' ' -f1)
+1 -1
View File
@@ -36,4 +36,4 @@ __pycache__/
app/src/main/assets/directaudio/
app/src/main/assets/hybris/
/tools/vr/out/
app/src/main/assets/linuxfs/usr/local/lib/droiddeck-rockstar/
app/src/main/resources/rockstar/helpers/
+1 -2
View File
@@ -74,7 +74,6 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
- x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes.
- `WriteProcessMemory` hooks fall back to `/proc/<pid>/mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11.
- Windows programs on noexec storage get executable copies of their image pages, following [@yujikaido](https://github.com/yujikaido)'s finding in [droiddeck-rp4pro](https://github.com/yujikaido/droiddeck-rp4pro) that Wine's own processes need the noexec shim.
- Wine write watches use userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later). libblsession supplies the arm64 syscall number and answers `PAGEMAP_SCAN` from `/proc/self/pagemap`.
- libblsession runs Wine's arm64 `SIGUSR2` context handler (`dlls/ntdll/unix/signal_arm64.c`, LGPL-2.1-or-later) in place on a frame laid out like [Linux](https://github.com/torvalds/linux)'s `arch/arm64/kernel/signal.c`, and serves `fill_vm_counters` in `dlls/ntdll/unix/process.c` the kernel's own `/proc/<pid>/status`.
- droiddeck-ntsync follows the [Linux](https://github.com/torvalds/linux) ntsync semantics in `Documentation/userspace-api/ntsync.rst` (GPL-2.0).
@@ -99,7 +98,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
- Battle.net installs drive Blizzard's Agent the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) does, with requests from [wowdev.wiki](https://wowdev.wiki/Agent). Read without taking code: [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader.
- World of Warcraft addon imports replace an addon's folder from a temporary copy, as [WowUp](https://github.com/WowUp/WowUp) does, and read flavour folders the way [WoWDeck](https://github.com/sigboe/wowdeck) does. No code from either is used.
- The World of Warcraft addon Download window searches [WoWInterface](https://www.wowinterface.com) through its MMOUI API. [CurseForge](https://www.curseforge.com/wow) opens in the user's browser, with no API and no key.
- The Xbox store runs [@domsvoboda](https://github.com/domsvoboda)'s [nexus-backend](https://github.com/domsvoboda/nexus-backend) 0.2.15 (GPL-3.0, a fork of [Xodus](https://github.com/xodus-gaming/xodus)), and Xbox games load the Windows modules of his [nexus-runtime](https://github.com/domsvoboda/nexus-runtime) (LGPL-2.1-or-later), including the C++ [nexus-xgameruntime](https://github.com/domsvoboda/nexus-xgameruntime) and `wintypes.dll`. Content licensing sends delegation-compact device tickets in the licensing wire form, as nexus-backend's Store license path (commit `27c335e`) does. Minecraft's GameInput setup was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT).
- Xbox games load [@domsvoboda](https://github.com/domsvoboda)'s [xodus-nexus](https://github.com/domsvoboda/xodus-nexus) modules (LGPL-2.1-or-later), including `wintypes.dll`. Content licensing sends delegation-compact device tickets in the licensing wire form, following the [nexus-backend](https://github.com/domsvoboda/nexus-backend) commit `27c335e`. Minecraft's GameInput setup was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT).
- The Xbox Cloud Gaming player uses the WebRTC client of [@unknownskl](https://github.com/unknownskl)'s [Greenlight](https://github.com/unknownskl/greenlight) (MIT), and its offer tweaks and sharpening follow [@redphx](https://github.com/redphx)'s [Better xCloud](https://github.com/redphx/better-xcloud) (MIT). See `tools/xcloud-player/NOTICE.md`.
- The itch.io butler pack ships butler's `7z.so`, itch.io's build of [7-Zip](https://www.7-zip.org) by Igor Pavlov (LGPL-2.1, unRAR restriction on RAR code), unmodified. Other archives use Apache Commons Compress and the runtime's bsdtar (libarchive).
- The Store uses [Flatpak](https://github.com/flatpak/flatpak) (LGPL-2.1) through DroidDeck's own bubblewrap shim. Chromium and Electron apps start directly, since [zypak](https://github.com/refi64/zypak) by [@refi64](https://github.com/refi64) (BSD-3-Clause) always uses Flatpak's spawn portal.
+3 -5
View File
@@ -93,7 +93,7 @@ def trackingPack = rootProject.file('tools/packs/tracking/release.env').readLine
def prootPackPin = rootProject.file('tools/packs/proot/release.env').readLines()
.findAll { it.contains('=') && !it.startsWith('#') }
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft', 'rockstar', 'dirt'].collectEntries { name ->
def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler', 'powervr', 'ubisoft'].collectEntries { name ->
def pack = file("build/packs/${name}.tar.zst")
if (!pack.isFile()) {
if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs")
@@ -206,7 +206,7 @@ android {
}
androidResources {
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:<dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~:<dir>droiddeck-xbox:<dir>droiddeck-comet:<dir>droiddeck-ubisoft:<dir>droiddeck-rockstar:<dir>droiddeck-dirt:<dir>directaudio:<dir>hybris'
ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:<dir>_*:!CVS:!thumbs.db:!picasa.ini:!*~:<dir>droiddeck-xbox:<dir>droiddeck-comet:<dir>droiddeck-ubisoft:<dir>directaudio:<dir>hybris'
}
packagingOptions {
@@ -278,10 +278,8 @@ def stageRuntimeAssets = tasks.register('stageRuntimeAssets', Sync) {
dependsOn(stageSessionScripts)
from(layout.projectDirectory.dir('src/main/assets')) { exclude 'pulseaudio.tzst' }
from(rootProject.file('tools/linuxfs/innoextract'))
from(rootProject.file('tools')) { include 'droiddeckctl', 'droiddeck-scenario', 'adb_device.py', 'proot_profile.py'; into('agent/ctl') }
from(rootProject.file('tools/agent/AGENTS.md')) { into('agent/ctl') }
from(rootProject.file('tools')) { include 'droiddeckctl', 'adb_device.py', 'proot_profile.py'; into('agent/ctl') }
from(rootProject.file('docs/agent-control.md')) { into('agent/ctl') }
from(rootProject.file('tools/agent/skills')) { into('agent/skills') }
from(layout.buildDirectory.dir('prepared-assets'))
into(runtimeAssetsDir)
}
@@ -1,2 +0,0 @@
#!/bin/sh
exec python3 /root/.local/share/droiddeck/ctl/droiddeck-scenario "$@"
@@ -0,0 +1,15 @@
{
"version": 1,
"controls": [
{
"name": "Compact gamepad",
"author": "DroidDeck",
"game": "",
"license": "GPL-3.0",
"file": "packs/compact-gamepad.ddcontrols.zip",
"sha256": "8b747e86268a1f607e312f2c39dd67402658bd5cf9e4e4ff524a4640417c9f3e",
"screen": "BOTH",
"preview": "previews/compact-gamepad.png"
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

@@ -416,7 +416,8 @@ static void update_map(int scene_w, int scene_h) {
if (mode == VKP_MODE_FILL) aspect = sx > sy ? sx : sy;
else if (mode == VKP_MODE_INTEGER) {
float m = sx < sy ? sx : sy;
aspect = m >= 1.0f ? (float)(int)m : m;
aspect = (float)(int)m;
if (aspect < 1.0f) aspect = 1.0f;
} else aspect = sx < sy ? sx : sy;
g_map.kx = g_map.ky = aspect;
g_map.off_x = (float)(g_map.rx + (int)((g_map.rw - scene_w * aspect) * 0.5f));
@@ -84,15 +84,12 @@ class App : Application() {
if (com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app).isDirectory) {
com.droiddeck.launcher.core.AddonPack.PROOT.ensure(app)
com.droiddeck.launcher.core.AddonPack.DIRECTAUDIO.ensure(app)
com.droiddeck.launcher.session.SessionFiles.ensureDirtStandIn(app)
}
if (com.droiddeck.launcher.stores.gog.GogComet.enabled(app)) com.droiddeck.launcher.core.AddonPack.COMET.ensure(app)
if (com.droiddeck.launcher.stores.StoreAccounts.signedInAs(app, com.droiddeck.launcher.stores.Store.XBOX) != null)
com.droiddeck.launcher.core.AddonPack.XBOX.ensure(app)
if (com.droiddeck.launcher.stores.StoreAccounts.signedInAs(app, com.droiddeck.launcher.stores.Store.UBISOFT) != null)
com.droiddeck.launcher.session.SessionFiles.ensureUbisoftService(app)
if (com.droiddeck.launcher.stores.StoreAccounts.signedInAs(app, com.droiddeck.launcher.stores.Store.ROCKSTAR) != null)
com.droiddeck.launcher.session.SessionFiles.ensureRockstarService(app)
com.droiddeck.launcher.handtracking.HandTracking.load(app)
}.onFailure { android.util.Log.w("App", "add-on pack prefetch failed", it) }
}, "addon-packs").start()
@@ -130,7 +130,6 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
}
var restartBlocked: () -> Boolean = { SessionState.running }
var onRouteChanged: () -> Unit = {}
fun loadTpUbwcMode() {
tpUbwcMode = SessionPrefs.tpUbwcMode(activity)
@@ -186,7 +185,6 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
runtimePending = sessionRunning && SessionState.runtimeDriver.let { it != null && it != linuxSelected }
refreshReleaseRows()
refreshPairs()
onRouteChanged()
}
fun summary(): String {
@@ -195,7 +195,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var showPhantomGate by mutableStateOf(false)
private var directAudio by mutableStateOf(false)
private var picturePosition by mutableStateOf("center")
private var integerScaling by mutableStateOf(false)
private var stretch16x9 by mutableStateOf(false)
private var orientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
private var launcherOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER)
@@ -1199,7 +1198,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
drivers.restartBlocked = ::runtimeChangesBlocked
drivers.onRouteChanged = { ui.post { refreshSteamGpuDrawing() } }
drivers.loadTpUbwcMode()
pendingSessionLogExport = savedInstanceState?.getString(KEY_PENDING_SESSION_LOG_EXPORT)?.let(::File)
homeChoiceOpen = savedInstanceState?.getBoolean(STATE_HOME_CHOICE_OPEN) == true
@@ -1457,20 +1455,15 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onRuntime = { onRuntimeButton() },
onVkBridge = { on ->
SessionPrefs.setVkBridge(this, on); SessionPrefs.setMaliFallbackByAuto(this, ""); vkBridge = on
refreshSteamGpuDrawing()
if (!on) com.droiddeck.launcher.session.ComponentsManager.settleAutoDxvk(this)
},
onVenus = { on ->
SessionPrefs.setVenus(this, on)
SessionPrefs.setMaliFallbackByAuto(this, "")
venus = on
refreshSteamGpuDrawing()
if (on && !com.droiddeck.launcher.core.DeviceSupport.adreno()) Thread({
com.droiddeck.launcher.gpu.VulkanInfo.query()["api"]?.let { SessionPrefs.setHostVulkanApi(this, it) }
runOnUiThread {
venusHostVulkan = com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(this)
refreshSteamGpuDrawing()
}
runOnUiThread { venusHostVulkan = com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(this) }
}, "venus-host-vulkan").start()
},
onVkBridgeSafe = { on -> SessionPrefs.setVkBridgeSafe(this, on); vkBridgeSafe = on },
@@ -1532,8 +1525,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart()
},
onSteamGpuDrawing = {
SessionPrefs.setSteamGpuCompositing(this, !SessionPrefs.steamGpuDrawingShown(this))
refreshSteamGpuDrawing()
SessionPrefs.setSteamGpuCompositing(this, !SessionPrefs.steamGpuCompositing(this))
steamGpuDrawing = SessionPrefs.steamGpuCompositing(this)
},
onGraphicsLogs = {
SessionPrefs.setDetailedGraphicsLogs(this, !SessionPrefs.detailedGraphicsLogs(this))
@@ -2558,7 +2551,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
backActionsInverted = backActionsInverted,
directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null,
picturePosition = if (mode == SessionService.MODE_STEAM) picturePosition else null,
integerScaling = if (mode == SessionService.MODE_STEAM) integerScaling else null,
stretch16x9 = if (mode == SessionService.MODE_STEAM) stretch16x9 else null,
mic = if (mode == SessionService.MODE_STEAM) mic else null,
gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null,
@@ -2620,7 +2612,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
},
onDirectAudio = { on -> SessionPrefs.setDirectAudio(this, on); directAudio = on },
onPicturePosition = { value -> SessionPrefs.setPicturePosition(this, value); picturePosition = value },
onIntegerScaling = { on -> SessionPrefs.setIntegerScaling(this, on); integerScaling = on },
onStretch16x9 = { on -> SessionPrefs.setStretch16x9(this, on); stretch16x9 = on },
onMic = { on ->
SessionPrefs.setMicEnabled(this, on)
@@ -2958,7 +2949,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
backActionsInverted = SessionPrefs.backActionsInverted(this)
directAudio = SessionPrefs.directAudio(this)
picturePosition = SessionPrefs.picturePosition(this)
integerScaling = SessionPrefs.integerScaling(this)
stretch16x9 = SessionPrefs.stretch16x9(this)
mic = SessionPrefs.micEnabled(this)
refreshWifiDiscovery()
@@ -3073,10 +3063,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
.show()
}
private fun refreshSteamGpuDrawing() {
steamGpuDrawing = SessionPrefs.steamGpuDrawingShown(this)
}
private fun refresh() {
val listX64 = SessionPrefs.activeSteamClientArch(this) == "x86_64"
if (listX64 != steamGamesX64) {
@@ -3108,7 +3094,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
graphicsLogs = SessionPrefs.detailedGraphicsLogs(this)
buildWatermark = SessionPrefs.buildWatermarkEnabled(this)
refreshSteamGpuDrawing()
steamGpuDrawing = SessionPrefs.steamGpuCompositing(this)
bridgeFellBack = SessionPrefs.bridgeFellBack(this)
bridgeFellBackMemory = SessionPrefs.bridgeFellBackForMemory(this)
clearCachedApps = SessionPrefs.clearCachedApps(this)
@@ -173,12 +173,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var adaptiveSticks by mutableStateOf<Boolean?>(null)
private var quickButtons by mutableStateOf<Map<InputCommand, Boolean>>(emptyMap())
private var picturePosition by mutableStateOf("center")
private var integerScaling by mutableStateOf(false)
private fun applyGameAlignment() {
if (!CompositorHost.isStarted) return
val active = SessionState.mode == SessionService.MODE_STEAM &&
!pipUi && !isInPictureInPictureMode && !activeCardboard.enabled
!pipUi && !isInPictureInPictureMode && !cardboard.enabled
val alignment = if (!active) ALIGN_CENTER else when (picturePosition) {
"top" -> ALIGN_PICTURE_TOP
"bottom" -> ALIGN_PICTURE_BOTTOM
@@ -186,7 +185,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
"right" -> ALIGN_PICTURE_RIGHT
else -> ALIGN_CENTER
}
WaylandCompositor.nativeSetScaleMode(if (active && integerScaling) SCALE_INTEGER else SCALE_FIT, alignment)
WaylandCompositor.nativeSetScaleMode(SCALE_FIT, alignment)
}
private var unfoldedPanel by mutableStateOf<OnScreenControls?>(null)
private var unfoldedColumn: android.widget.LinearLayout? = null
@@ -295,7 +294,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private lateinit var threeFingerTap: com.droiddeck.launcher.input.ThreeFingerTap
private lateinit var touchscreenGestures: TouchscreenGestures
private var gestureConfig = com.droiddeck.launcher.input.TouchGestureConfig()
private var gestureGame: String? = null
private var gestureGame by mutableStateOf<String?>(null)
private var gameStarts by mutableIntStateOf(0)
private var gestureSettingsOpen by mutableStateOf(false)
private var steamImportAsk by mutableStateOf<com.droiddeck.launcher.session.SteamImportPrompt.Ask?>(null)
@@ -1086,7 +1085,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
secondScreenPresentation?.closeFieldKeyboard()
}
}
androidx.compose.runtime.LaunchedEffect(picturePosition, integerScaling, SessionState.running, pipUi, cardboard.enabled) { applyGameAlignment() }
androidx.compose.runtime.LaunchedEffect(picturePosition, SessionState.running, pipUi, cardboard.enabled) { applyGameAlignment() }
DroidDeckTheme {
if (pipUi) {
if (SessionState.suspended) androidx.compose.foundation.layout.Box(
@@ -1198,8 +1197,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
if (nextGame != gestureGame) {
if (nextGame != null) gameStarts++
val previousControls = com.droiddeck.launcher.input.GameInputControls.profile(this@SessionActivity, inputGameScope())
gestureGame = nextGame
refreshGestureConfig()
if (previousControls != com.droiddeck.launcher.input.GameInputControls.profile(this@SessionActivity, inputGameScope())) {
releasePads()
refreshInputProfile()
}
}
if (
SessionState.mode == SessionService.MODE_STEAM &&
@@ -2400,7 +2404,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
unfoldedControls = SessionPrefs.unfoldedControls(this)
unfoldedControlsWithController = SessionPrefs.unfoldedControlsWithController(this)
picturePosition = SessionPrefs.picturePosition(this)
integerScaling = SessionPrefs.integerScaling(this)
hudOn = SessionPrefs.hudEnabled(this)
hudConfig = DroidDeckHudConfig.load(this)
hudColor = SessionPrefs.hudColor(this)
@@ -2591,10 +2594,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
runCatching { com.droiddeck.launcher.runtime.RuntimeInstallService.start(this, release) }
val ok = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.install(this, release,
progressFor(RUNTIME_LINES, release.size / 1_000_000))
if (ok) {
com.droiddeck.launcher.session.SessionFiles.ensureDirtStandIn(this)
return null
}
if (ok) return null
SessionEvents.record("runtime.failed", mapOf("step" to "install", "reason" to com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.installError()))
return getString(R.string.session_runtime_install_failed)
}
@@ -2656,7 +2656,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
runCatching { GameEnvironmentStore.publish(this) }
.onFailure { Log.e(TAG, "Could not update game environment", it) }
}, "game-env-publish").start()
applyGameAlignment()
WaylandCompositor.nativeSetScaleMode(SCALE_FIT, ALIGN_CENTER)
val activeProfileId = currentScreenEffectsProfileId()
val activeUpscaler = SessionPrefs.screenEffectsUpscaler(this, activeProfileId)
val activeEffects = SessionPrefs.screenEffects(this, activeProfileId)
@@ -4226,9 +4226,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (started && displayId !in inputWindowDisplays && secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode)
}
fun inputGameScope(): String? = if (loadingMode() == SessionService.MODE_RUN) {
(if (SessionState.running) SessionState.gameId else null)
?: intent.getStringExtra(SessionService.EXTRA_GAME_ID) ?: gestureGame
} else gestureGame
private fun refreshInputProfile() {
val library = com.droiddeck.launcher.input.InputLibraries.read(this)
val desktop = loadingMode() == SessionService.MODE_DESKTOP
val game = inputGameScope()
val library = com.droiddeck.launcher.input.GameInputControls.resolve(this,
com.droiddeck.launcher.input.InputLibraries.read(this), desktop, game)
inputProfile = library.compileActive(desktop, secondScreenMode.panel(this))
primaryInputLayout = library.activeLayout(desktop, InputRole.PRIMARY)
adaptiveSticks = primaryInputLayout?.adaptiveSticks
@@ -4638,18 +4645,25 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
gamePictureBounds[2], gamePictureBounds[3]
)
val nativeWidth: Int
val nativeHeight: Int
if (glassesOutputActive) {
val mode = glassesScreen?.display?.mode ?: return null
nativeWidth = mode.physicalWidth.takeIf { it > 0 } ?: return null
nativeHeight = mode.physicalHeight.takeIf { it > 0 } ?: return null
} else {
val nativeSize = IntArray(2)
if (!WaylandCompositor.nativeOutputSize(nativeSize)) return null
nativeWidth = nativeSize[0].takeIf { it > 0 } ?: return null
nativeHeight = nativeSize[1].takeIf { it > 0 } ?: return null
val outputWidth = mode.physicalWidth.takeIf { it > 0 } ?: return null
val outputHeight = mode.physicalHeight.takeIf { it > 0 } ?: return null
val scaleX = width.toFloat() / outputWidth
val scaleY = height.toFloat() / outputHeight
return android.graphics.RectF(
rect.left * scaleX,
rect.top * scaleY,
rect.right * scaleX,
rect.bottom * scaleY
)
}
val nativeSize = IntArray(2)
if (!WaylandCompositor.nativeOutputSize(nativeSize)) return null
val nativeWidth = nativeSize[0].takeIf { it > 0 } ?: return null
val nativeHeight = nativeSize[1].takeIf { it > 0 } ?: return null
val scaleX = width.toFloat() / nativeWidth
val scaleY = height.toFloat() / nativeHeight
@@ -4858,8 +4872,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun dispatchDirectTouch(event: MotionEvent): Boolean {
val rect = drawnRect() ?: return false
if (event.actionMasked == MotionEvent.ACTION_DOWN)
ignoreGameTouch = topPictureMapped && !glassesOutputActive &&
!rect.contains(event.x, event.y)
ignoreGameTouch = topPictureMapped && !rect.contains(event.x, event.y)
if (ignoreGameTouch) {
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
directTouchHold.cancel()
@@ -5385,7 +5398,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
listOf(PointerGestures.BTN_LEFT, PointerGestures.BTN_RIGHT, PointerGestures.BTN_MIDDLE).forEach {
heldButtons.set(1, it, false)
}
applyGameAlignment()
WaylandCompositor.nativeSetScaleMode(SCALE_FIT, ALIGN_CENTER)
}
} else if (!isFinishing && !isDestroyed) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
@@ -5746,7 +5759,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
cardboard = c
val e = effectiveCardboard(c)
activeCardboard = e
applyGameAlignment()
if (CompositorHost.isStarted) pushCardboard(e)
if (e.enabled && !was.enabled) headTracker?.recenter()
updateHeadTracker()
@@ -6366,7 +6378,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private val steamVrWorker = java.util.concurrent.ThreadPoolExecutor(0, 1, 30, java.util.concurrent.TimeUnit.SECONDS,
java.util.concurrent.LinkedBlockingQueue()) { Thread(it, "steamvr") }
private const val SCALE_FIT = 1
private const val SCALE_INTEGER = 4
private const val ALIGN_CENTER = 0
private const val ALIGN_PICTURE_TOP = 3
private const val ALIGN_PICTURE_BOTTOM = 4
@@ -84,7 +84,6 @@ object AgentChats {
internal fun encode(entry: Entry): String = when (entry) {
is Entry.Asked -> JSONObject().put("asked", entry.text).apply { if (entry.files.isNotEmpty()) put("files", JSONArray(entry.files)) }
is Entry.Said -> JSONObject().put("said", entry.text)
is Entry.Notice -> JSONObject().put("notice", entry.text)
is Entry.Thought -> JSONObject().put("thought", entry.text)
is Entry.Result -> JSONObject().put("result", entry.id).put("output", entry.output).put("failed", entry.failed)
is Entry.Used -> JSONObject().put("used", entry.tool).put("detail", entry.detail).put("id", entry.id).put("input", entry.input)
@@ -120,7 +119,6 @@ object AgentChats {
private fun decode(o: JSONObject): Entry? = when {
o.has("asked") -> Entry.Asked(o.getString("asked"), o.optJSONArray("files")?.let { a -> (0 until a.length()).map { a.getString(it) } }.orEmpty())
o.has("said") -> Entry.Said(o.getString("said"))
o.has("notice") -> Entry.Notice(o.getString("notice"))
o.has("thought") -> Entry.Thought(o.getString("thought"))
o.has("used") -> Entry.Used(o.optString("id"), o.getString("used"), o.optString("detail"), o.optString("input"),
if (o.has("output")) o.optString("output") else null, o.optBoolean("failed"), o.optString("parent"))
@@ -5,7 +5,7 @@ import org.json.JSONArray
import org.json.JSONObject
import java.io.File
/** One coding agent CLI in the Linux userland, run one process per turn (or kept open, see [input]). */
/** One coding agent CLI in the Linux userland, run one process per turn. */
interface AgentHarness {
val id: String
val name: String
@@ -27,18 +27,8 @@ interface AgentHarness {
fun models(rootfs: File): List<Model>
/** The guest command for one turn; [conversation] is null for the first one. */
fun turn(message: String, conversation: String?, options: Options): List<String>
/**
* The line that hands [message] to a [turn] process over stdin, or null when the message is already in the
* command. A process that takes its messages this way stays open between turns, so work it started in the
* background can wake it, as it does in the CLI's own terminal.
*/
fun input(message: String): String? = null
/** One line of the CLI's output, or null when it carries nothing to show. */
fun parse(line: String): AgentEvent?
/** The folder, under the userland's root, where the CLI loads user skills (`<name>/SKILL.md`). */
val skills: String
/** The CLI's global instructions file under the userland's root, where DroidDeck keeps its rules in a marked block. */
val instructions: String
/** Sets the CLI's own defaults in the userland before it runs; [rootfs] is the userland's root. */
fun prepare(rootfs: File) {}
/** Context and plan limits the CLI keeps on disk rather than printing, read once a turn of [conversation] is done. */
@@ -66,13 +56,9 @@ data class AgentEvent(
val window: Long? = null,
val limits: List<AgentHost.Limit>? = null,
val usage: AgentHost.Usage? = null,
/** This ends a turn the CLI started itself, such as the answer to a finished background task. */
val background: Boolean = false,
/** The error a background turn ended with, if it failed. */
val backgroundError: String? = null,
)
/** Claude Code: `claude -p` with stream-json input and output, resumed by session id. */
/** Claude Code: `claude -p` with stream-json output, resumed by session id. */
object ClaudeCode : AgentHarness {
override val id = "claude"
override val name = "Claude Code"
@@ -87,8 +73,6 @@ object ClaudeCode : AgentHarness {
* Commits and pull requests the agent makes carry no Claude Code credit or co-author line by
* default. Only keys the user has not set are written, so their own choice stays.
*/
override val skills = "root/.claude/skills"
override val instructions = "root/.claude/CLAUDE.md"
override fun prepare(rootfs: File) {
val file = File(rootfs, "root/.claude/settings.json")
val settings = if (file.exists()) runCatching { JSONObject(file.readText()) }.getOrNull() ?: return else JSONObject()
@@ -113,7 +97,7 @@ object ClaudeCode : AgentHarness {
// DroidDeck runs the agent unattended on the user's own device; permission prompts have no one to answer them.
override fun turn(message: String, conversation: String?, options: AgentHarness.Options) = buildList {
addAll(listOf(binary, "-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose", "--include-partial-messages"))
addAll(listOf(binary, "-p", message, "--output-format", "stream-json", "--verbose", "--include-partial-messages"))
addAll(listOf("--permission-mode", if (options.plan) "plan" else "bypassPermissions"))
options.model?.let { addAll(listOf("--model", it)) }
options.effort?.let { addAll(listOf("--effort", it)) }
@@ -121,11 +105,6 @@ object ClaudeCode : AgentHarness {
if (conversation != null) addAll(listOf("--resume", conversation))
}
override fun input(message: String): String? = JSONObject()
.put("type", "user")
.put("message", JSONObject().put("role", "user").put("content", JSONArray().put(JSONObject().put("type", "text").put("text", message))))
.toString()
override fun parse(line: String): AgentEvent? {
val o = runCatching { JSONObject(line) }.getOrNull() ?: return null
val conversation = o.optString("session_id").takeIf { it.isNotEmpty() }
@@ -151,11 +130,7 @@ object ClaudeCode : AgentHarness {
"thinking" -> if (parent != null) null else block.optString("thinking").trim().takeIf { it.isNotEmpty() }?.let { AgentHost.Entry.Thought(it) }
"tool_use" -> {
val input = block.optJSONObject("input")
AgentHost.Entry.Used(
block.optString("id"), block.optString("name"), detail(input), fullInput(block.optString("name"), input),
parent = parent.orEmpty(),
background = input?.optBoolean("run_in_background") == true || block.optString("name") == "Monitor",
)
AgentHost.Entry.Used(block.optString("id"), block.optString("name"), detail(input), fullInput(block.optString("name"), input), parent = parent.orEmpty())
}
else -> null
}
@@ -173,25 +148,17 @@ object ClaudeCode : AgentHarness {
AgentEvent(conversation, results)
}
"rate_limit_event" -> AgentEvent(conversation, limits = limits(o.optJSONObject("rate_limit_info")))
// The CLI starts turns of its own for background tasks (a resumed session first answers the ones the last
// run left behind). Such a result is not the end of the user's turn; the host decides what it ends.
"result" -> {
val usage = AgentHost.Usage(
// A resumed session first answers background tasks the last run left behind; that result is not the turn's.
"result" -> if (o.optJSONObject("origin")?.optString("kind") == "task-notification") conversation?.let { AgentEvent(it) } else AgentEvent(
conversation,
listOf(AgentHost.Entry.Finished(if (o.optBoolean("is_error")) o.optString("result").ifEmpty { o.optString("subtype") } else null)),
window = window(o.optJSONObject("modelUsage")),
usage = AgentHost.Usage(
o.optLong("duration_ms"), o.optDouble("total_cost_usd", 0.0),
o.optJSONObject("usage")?.let { it.optLong("input_tokens") + it.optLong("cache_read_input_tokens") + it.optLong("cache_creation_input_tokens") } ?: 0,
o.optJSONObject("usage")?.optLong("output_tokens") ?: 0,
)
if (o.optJSONObject("origin")?.optString("kind") == "task-notification") AgentEvent(
conversation, usage = usage, background = true,
backgroundError = if (o.optBoolean("is_error")) o.optString("result").ifEmpty { o.optString("subtype") } else null,
)
else AgentEvent(
conversation,
listOf(AgentHost.Entry.Finished(if (o.optBoolean("is_error")) o.optString("result").ifEmpty { o.optString("subtype") } else null)),
window = window(o.optJSONObject("modelUsage")),
usage = usage,
)
}
),
)
else -> conversation?.let { AgentEvent(it) }
}
}
@@ -260,8 +227,6 @@ object Codex : AgentHarness {
override val id = "codex"
override val name = "Codex"
override val binary = "/root/.local/bin/codex"
override val skills = "root/.codex/skills"
override val instructions = "root/.codex/AGENTS.md"
// Code mode runs in a helper that each release ships as its own download.
private const val HOST = "/root/.local/bin/codex-code-mode-host"
override val files get() = listOf(binary, HOST)
@@ -21,23 +21,18 @@ import java.nio.file.Files
/**
* The launcher's agent: a coding agent CLI ([AgentHarness]) from the Linux userland, run headless
* outside any game or desktop session: one process per turn, or for a CLI that takes its messages over
* stdin one process kept open between turns, so background work can start a turn of its own. Conversations are kept on disk
* one process per turn, outside any game or desktop session. Conversations are kept on disk
* ([AgentChats]), so a restart (a Lab build, a crash) continues the same one.
*/
object AgentHost {
sealed interface Entry {
data class Asked(val text: String, val files: List<String> = emptyList()) : Entry
data class Said(val text: String) : Entry
data class Notice(val text: String) : Entry
data class Thought(val text: String) : Entry
/**
* A tool call; [output] stays null until its result arrives. [parent] is the subagent call it was made under, if any.
* [background]: the call starts work that can wake the CLI after its turn (run_in_background, Monitor).
*/
/** A tool call; [output] stays null until its result arrives. [parent] is the subagent call it was made under, if any. */
data class Used(
val id: String, val tool: String, val detail: String, val input: String = "", val output: String? = null, val failed: Boolean = false,
val parent: String = "", val background: Boolean = false,
val parent: String = "",
) : Entry
data class Result(val id: String, val output: String, val failed: Boolean) : Entry
/** [planned]: the turn ran in plan mode, so it ends on a plan that nothing has carried out yet. */
@@ -68,10 +63,18 @@ object AgentHost {
@VisibleForTesting
internal const val BRIEF = "You run inside DroidDeck on the user's handheld, in its Linux userland (Ubuntu under proot, aarch64), " +
"and the user talks to you from DroidDeck's Agent tab, often on a small screen, so keep replies short. " +
"DroidDeck's rules for working here are in your global instructions file (~/.claude/CLAUDE.md or ~/.codex/AGENTS.md); " +
"if they are not loaded, read ${AgentSetup.CTL}/AGENTS.md before acting on the device. " +
"droiddeckctl inspects and drives the app over loopback adb (\$ADB_SERIAL); its guide is ${AgentSetup.CTL}/agent-control.md. " +
"Steam, the desktop and games run in DroidDeck's session, a separate guest from yours: a program you start here is not in it and has no screen. " +
"Reach the session through droiddeckctl: state, start steam, stop, launch, quit, focus, screenshot, logs, and guest to run a command inside it. " +
"Starting, stopping or restarting a session leaves you running. " +
"Never kill by a command-line pattern (pkill -f, pgrep -f piped to kill): your own command line holds the user's message, so the pattern matches you. " +
"End a game with droiddeckctl quit, the session with droiddeckctl stop, anything else by its pid. " +
"dd-lab-build builds the checkout as a Lab build and restarts DroidDeck on it (docs/lab-builds.md). DroidDeck runs the build in a " +
"process of its own and shows the user its progress and time left; dd-lab-build follows that build's log until it is done. " +
"Run it with run_in_background and keep checking its output, so the user can talk to you meanwhile. " +
"The restart ends this process, and this conversation continues on the new build. " +
"Files the user attaches are listed at the end of their message, under /root/.cache/droiddeck/attachments. " +
"Commits and pull requests you make are the user's own: add no co-author line, AI credit or generated-by note. " +
"To have the user pick between options, end your reply with a fenced code block whose language is choices, one short option per line, " +
"and end your turn: DroidDeck shows them as buttons and sends the one picked as the next message."
@@ -123,24 +126,10 @@ object AgentHost {
var lab by mutableStateOf<LabProgress?>(null)
private set
private class Turn(val process: Process, val pid: Int, val stdin: java.io.OutputStream? = null) {
var writingGeneration: Int? = null
var exitStatus: Int? = null
var costs: AgentCostTracker? = null
var clearingCosts = false
}
private class Turn(val process: Process, val pid: Int)
private val main = Handler(Looper.getMainLooper())
private var turn: Turn? = null
/**
* The CLI process when it takes its messages over stdin. It outlives a turn, so work it started in the
* background can wake it: the answer to a finished task then arrives without a message from the user.
*/
private var session: Turn? = null
private var sessionKey: String? = null
/** The running turn is one the CLI started itself, not an answer to the user. */
private var background = false
private val reap = Runnable { if (state != State.WORKING) dropSession() }
/** Counts turns, so a process that starts after its turn was stopped is not adopted by the next one. */
private var generation = 0
private var labProcess: Process? = null
@@ -153,8 +142,6 @@ object AgentHost {
private var turnPlanned = false
private var loaded = false
private var appContext: Context? = null
/** A tool call in this CLI process started work that can wake it after its turn (run_in_background). */
private var launchedBackground = false
val turnPid: Int get() = turn?.pid ?: 0
@@ -210,7 +197,6 @@ object AgentHost {
AgentSetup.forget()
refresh(app)
}
dropSession()
load(app, id)
prefs(app).edit().putString(CHAT_KEY, id).apply()
}
@@ -299,42 +285,11 @@ object AgentHost {
live = ""
liveThinking = ""
turnStarted = SystemClock.elapsedRealtime()
AgentHostService.start(app)?.let { serviceWarning(app, it) }
AgentHostService.start(app)
val current = harness
val prompt = AgentAttachments.prompt(message, attached)
turnPlanned = plan && current.plans
val options = AgentHarness.Options(model, turnPlanned, BRIEF, effort)
val command = current.turn(prompt, conversation, options)
val line = current.input(prompt)
val key = "${current.id}|$id|$model|$turnPlanned|$effort"
background = false
val kept = session
if (kept != null && line != null && sessionKey == key && kept.process.isAlive) {
main.removeCallbacks(reap)
turn = kept
kept.writingGeneration = gen
kept.clearingCosts = prompt == "/clear"
Thread({
val written = runCatching { synchronized(kept) { kept.stdin?.apply { write((line + "\n").toByteArray()); flush() } != null } }.getOrDefault(false)
// The process died between turns: the same message goes to a new one, which resumes the conversation.
main.post {
if (kept.writingGeneration == gen) kept.writingGeneration = null
if (generation == gen && session === kept) {
if (!written) {
dropSession()
turn = null
spawn(app, gen, current, current.turn(prompt, conversation, options), line, key)
} else kept.exitStatus?.let { processExited(app, kept, current, it) }
}
}
}, "agent-input").start()
return
}
dropSession()
spawn(app, gen, current, command, line, key)
}
private fun spawn(app: Context, gen: Int, current: AgentHarness, command: List<String>, line: String?, key: String) {
val command = current.turn(prompt, conversation, AgentHarness.Options(model, turnPlanned, BRIEF, effort))
val workdir = workspace(app)
var threadConversation = conversation
Thread({
@@ -349,100 +304,40 @@ object AgentHost {
main.post { if (generation == gen) finish(app, e.message ?: "could not start") }
return@Thread
}
val started = Turn(child, AgentProcesses.pidOf(child), if (line != null) child.outputStream else null).apply {
if (current === ClaudeCode && line != null) costs = AgentCostTracker()
}
val started = Turn(child, AgentProcesses.pidOf(child))
OrphanReaper.keep(started.pid)
main.post {
if (generation == gen && state == State.WORKING && turn == null) {
turn = started
if (line != null) { session = started; sessionKey = key }
} else AgentProcesses.killTree(started.pid)
}
if (line != null) runCatching { child.outputStream.apply { write((line + "\n").toByteArray()); flush() } } else child.outputStream.close()
main.post { if (generation == gen && state == State.WORKING && turn == null) turn = started else AgentProcesses.killTree(started.pid) }
child.outputStream.close()
var ended = false
val raw = runCatching {
val log = File(app.filesDir, TURN_LOG).apply { parentFile?.mkdirs() }
log.renameTo(File(app.filesDir, "$TURN_LOG.1"))
log.bufferedWriter()
}.getOrNull()
runCatching {
child.inputStream.bufferedReader().forEachLine { output ->
runCatching { raw?.apply { write(output); newLine(); flush() } }
val parsed = current.parse(output) ?: return@forEachLine
child.inputStream.bufferedReader().forEachLine { line ->
runCatching { raw?.apply { write(line); newLine(); flush() } }
val parsed = current.parse(line) ?: return@forEachLine
parsed.conversation?.let { threadConversation = it }
val done = parsed.entries.any { it is Entry.Finished }
if (done) ended = true
val event = if (!done) parsed else runCatching { current.usage(LinuxRuntime.rootDir(app), threadConversation) }.getOrNull()
?.let { parsed.copy(context = it.context ?: parsed.context, window = it.window ?: parsed.window, limits = it.limits ?: parsed.limits) } ?: parsed
main.post { if (turn === started || session === started) handle(app, started, event) }
main.post { if (turn === started) apply(app, event) }
}
}
runCatching { raw?.close() }
val status = runCatching { child.waitFor() }.getOrDefault(-1)
OrphanReaper.release(started.pid)
main.post {
if (started.writingGeneration != null) started.exitStatus = status
else processExited(app, started, current, status)
if (turn === started) {
turn = null
if (state == State.WORKING && !ended) finish(app, app.getString(R.string.agent_exited, current.name, status))
}
}
}, "agent-output").start()
}
private fun processExited(app: Context, exited: Turn, current: AgentHarness, status: Int) {
if (session === exited) {
session = null
launchedBackground = false
main.removeCallbacks(reap)
AgentHostService.backgroundDone(app)
}
if (turn === exited) {
turn = null
if (state == State.WORKING) finish(app, app.getString(R.string.agent_exited, current.name, status))
}
}
private fun serviceWarning(app: Context, error: Throwable) {
record(app, Entry.Notice("Unable to keep the agent running in the background: ${error.message ?: error.javaClass.simpleName}"))
}
/** One event from the CLI, which may belong to a turn it started on its own once the user's has ended. */
private fun handle(app: Context, from: Turn, event: AgentEvent) {
if (event.background) {
// A leftover task answered before the user's message is not the user's turn; one the CLI started is its own.
if (background && state == State.WORKING) finish(app, event.backgroundError, usage = event.usage?.let { from.costs?.perTurn(it) ?: it })
return
}
val content = event.text != null || event.thinking != null || event.entries.any { it !is Entry.Finished }
if (content && state == State.IDLE && session === from) {
main.removeCallbacks(reap)
background = true
turn = from
turnPlanned = false
state = State.WORKING
live = ""
liveThinking = ""
turnStarted = SystemClock.elapsedRealtime()
AgentHostService.start(app)?.let { serviceWarning(app, it) }
}
val finished = event.entries.filterIsInstance<Entry.Finished>().firstOrNull()
if (finished != null && state == State.WORKING && from.clearingCosts) {
if (finished.error == null) from.costs?.reset()
from.clearingCosts = false
}
val applied = if (finished != null && state == State.WORKING && event.usage != null)
event.copy(usage = from.costs?.perTurn(event.usage) ?: event.usage) else event
apply(app, applied)
}
/** Ends the CLI process kept between turns, and with it whatever it still runs in the background. */
private fun dropSession() {
main.removeCallbacks(reap)
launchedBackground = false
appContext?.let { AgentHostService.backgroundDone(it) }
val kept = session ?: return
session = null
AgentProcesses.killTree(kept.pid)
kept.process.destroy()
}
/** Ends the turn now: its process and everything it started, a build included. */
fun stop(context: Context) {
val app = context.applicationContext
@@ -454,7 +349,6 @@ object AgentHost {
AgentProcesses.killTree(running.pid)
running.process.destroy()
}
dropSession()
if (state == State.WORKING) finish(app, null, stopped = true)
}
@@ -549,25 +443,19 @@ object AgentHost {
private fun finish(app: Context, error: String?, stopped: Boolean = false, usage: Usage? = null) {
if (state != State.WORKING) return
turn = null
val answeredTask = background
background = false
main.removeCallbacks(reap)
if (session != null) main.postDelayed(reap, LINGER_MS)
if (!stopped) labFromTurn = false
live = ""
liveThinking = ""
val held = if (context > 0) (usage ?: Usage(0, 0.0, 0, 0)).copy(context = context, window = window) else usage
record(app, Entry.Finished(error, stopped, held, planned = turnPlanned && !stopped && error == null))
state = State.IDLE
unseen = true
failed = error != null
if (session != null && launchedBackground) {
AgentHostService.waitForBackground(app)?.let { serviceWarning(app, it) }
} else AgentHostService.stop(app)
record(app, Entry.Finished(error, stopped, held, planned = turnPlanned && !stopped && error == null))
AgentHostService.stop(app)
// Claude Code now and then ends a resumed turn at once without reading the message; nothing
// happened, so the message is sent once more.
val asked = entries.lastOrNull { it is Entry.Asked } as? Entry.Asked
if (!stopped && error == null && !answeredTask && asked != null && answerless(entries) && !retrying) {
if (!stopped && error == null && asked != null && answerless(entries) && !retrying) {
retrying = true
val retryChat = chat
resend = Runnable {
@@ -605,7 +493,6 @@ object AgentHost {
private fun record(app: Context, entry: Entry) {
if (!AgentChats.merge(entries, entry)) return
if (entry is Entry.Used && entry.background) launchedBackground = true
chat?.let { AgentChats.append(AgentChats.file(app, it), entry) }
}
@@ -758,8 +645,6 @@ object AgentHost {
/** The raw output of the latest turn, for working out what a CLI did when the chat shows nothing. */
private const val TURN_LOG = "agent/turn.log"
private const val RETRY_MS = 3_000L
/** How long the CLI process stays open after a turn, waiting for background work to wake it. */
private const val LINGER_MS = 20 * 60_000L
private fun modelKey(harness: AgentHarness) = "model_${harness.id}"
private fun limitsKey(harness: AgentHarness) = "limits_${harness.id}"
@@ -809,17 +694,3 @@ internal fun choices(reply: String): Choices {
val options = lines.subList(found.first + 1, found.last).map { it.trim().removePrefix("- ").removePrefix("* ").trim() }.filter { it.isNotEmpty() }
return Choices(lines.subList(0, found.first).joinToString("\n").trimEnd(), options)
}
internal class AgentCostTracker {
private var previous = 0.0
fun reset() { previous = 0.0 }
fun perTurn(usage: AgentHost.Usage): AgentHost.Usage {
val total = usage.costUsd
if (total == 0.0 && previous > 0.0) return usage
val delta = if (total >= previous) total - previous else total
previous = total
return usage.copy(costUsd = delta)
}
}
@@ -42,37 +42,19 @@ class AgentHostService : Service() {
/** Setup steps that keep the app alive while they run, besides the agent's turn. */
private var setupSteps = 0
fun start(context: Context): Throwable? {
if (started) { update(context); return null }
fun start(context: Context) {
lastText = null
return runCatching { context.startForegroundService(Intent(context, AgentHostService::class.java)) }
.onSuccess { started = true; awaiting++ }
.exceptionOrNull()
started = true
runCatching { context.startForegroundService(Intent(context, AgentHostService::class.java)) }
.onSuccess { awaiting++ }
}
fun stop(context: Context) {
if (setupSteps > 0 || waiting) return
if (setupSteps > 0) return
started = false
if (awaiting == 0) context.stopService(Intent(context, AgentHostService::class.java))
}
/**
* The turn has ended but its CLI process stays open with background work that can wake it; the app must stay
* alive to read that answer, so the service keeps running until the process is dropped.
*/
@Volatile private var waiting = false
fun waitForBackground(context: Context): Throwable? {
waiting = true
return if (started) { update(context); null } else start(context)
}
fun backgroundDone(context: Context) {
if (!waiting) return
waiting = false
if (AgentHost.state != AgentHost.State.WORKING) stop(context)
}
fun setupStarted(context: Context) {
setupSteps++
start(context)
@@ -98,8 +80,7 @@ class AgentHostService : Service() {
AgentSetup.detail[AgentSetup.Step.GITHUB]?.takeIf {
AgentSetup.status[AgentSetup.Step.GITHUB] == AgentSetup.Status.WORKING && it.startsWith("GitHub device code:")
}?.let { return it }
if (AgentHost.state != AgentHost.State.WORKING)
return context.getString(if (waiting && setupSteps == 0) R.string.agent_waiting_background else R.string.agent_setting_up)
if (AgentHost.state != AgentHost.State.WORKING) return context.getString(R.string.agent_setting_up)
val tool = AgentHost.running()
val elapsed = minutes((SystemClock.elapsedRealtime() - AgentHost.turnStarted) / 1000)
return if (tool != null) "${tool.tool} · ${tool.detail}".take(120) + " · $elapsed" else context.getString(R.string.agent_thinking_for, elapsed)
@@ -4,7 +4,6 @@ import android.content.Context
import android.os.Handler
import android.os.Looper
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
@@ -41,9 +40,7 @@ object AgentSetup {
private val main = Handler(Looper.getMainLooper())
private const val REPO = "https://github.com/Droid-Deck/DroidDeck.git"
private const val CHECKOUT = "/root/DroidDeck"
private val HELPERS = listOf("android-open", "dd-gh-login", "droiddeckctl", "droiddeck-scenario")
/** DroidDeck's own skills (tools/agent/skills), given to every harness. */
private const val SKILLS = "agent/skills"
private val HELPERS = listOf("android-open", "dd-gh-login", "droiddeckctl")
internal const val CTL = "/root/.local/share/droiddeck/ctl"
private const val PROBE_TIMEOUT_S = 60L
@@ -190,98 +187,11 @@ object AgentSetup {
/** Written before every step, so the helpers a step relies on are there and match this DroidDeck version. */
internal fun installHelpers(app: Context) {
val root = LinuxRuntime.rootDir(app)
val failed = mutableListOf<String>()
fun attempt(what: String, block: () -> Unit) = runCatching(block).onFailure {
android.util.Log.w("AgentSetup", "could not install $what", it)
failed += what
}
val bin = File(root, "root/.local/bin").apply { mkdirs() }
for (name in HELPERS) attempt(name) { copyAsset(app, "agent/$name", File(bin, name)) }
for (name in HELPERS) copyAsset(app, "agent/$name", File(bin, name))
val ctl = File(root, CTL.removePrefix("/")).apply { mkdirs() }
for (name in app.assets.list("agent/ctl").orEmpty()) attempt("ctl/$name") { copyAsset(app, "agent/ctl/$name", File(ctl, name)) }
val skills = app.assets.list(SKILLS).orEmpty().associateWith { app.assets.list("$SKILLS/$it").orEmpty().toList() }
failed += installSkills(root, skills) { app.assets.open("$SKILLS/$it") }
attempt("AGENTS.md") {
val rules = app.assets.open("agent/ctl/AGENTS.md").use { it.readBytes().decodeToString() }
failed += installInstructions(root, rules)
}
for (name in app.assets.list("agent/ctl").orEmpty()) copyAsset(app, "agent/ctl/$name", File(ctl, name))
unpinAdbSerial(File(root, "root/.bashrc"))
main.post { problems.clear(); problems.addAll(failed.distinct()) }
}
/** What [installHelpers] could not install last time, shown in the Agent tab; empty when all is in place. */
val problems = mutableStateListOf<String>()
/**
* Writes each of DroidDeck's [skills] (name to its files) into every harness's skills folder, so
* Claude Code, Codex and any later harness load the same ones, as of this DroidDeck version.
* Skills the user added there are left alone. Returns the skills that could not be written.
*/
internal fun installSkills(root: File, skills: Map<String, List<String>>, open: (String) -> java.io.InputStream): List<String> {
val failed = mutableListOf<String>()
for (harness in AgentHarness.all) for ((name, files) in skills) runCatching {
val dir = File(root, "${harness.skills}/$name")
// A folder of that name without DroidDeck's mark is the user's own skill: keep it.
if (dir.exists() && !File(dir, SKILL_MARK).exists()) return@runCatching
dir.mkdirs()
// Marked before copying, so a copy that fails part way is retried next turn, not taken for the user's.
File(dir, SKILL_MARK).writeText("Installed by DroidDeck and replaced on every turn. Delete this file to keep your own edits.\n")
for (file in files) open("$name/$file").use { replaceFile(it, File(dir, file), executable = false) }
}.onFailure {
android.util.Log.w("AgentSetup", "could not install skill $name for ${harness.name}", it)
failed += "skill $name"
}
return failed
}
/** Marks a skill folder as DroidDeck's, so it may be replaced; one without it belongs to the user. */
internal const val SKILL_MARK = ".droiddeck"
/**
* Where [file] really is when it is a symlink, as the guest sees it: an absolute target is a
* userland path, so it is looked up under [root]. A dotfiles link keeps working that way.
*/
internal fun guestTarget(root: File, file: File): File {
var current = file
repeat(8) {
val path = current.toPath()
if (!java.nio.file.Files.isSymbolicLink(path)) return current
val target = java.nio.file.Files.readSymbolicLink(path).toString()
current = if (target.startsWith("/")) File(root, target.removePrefix("/")) else File(current.parentFile, target)
}
return current
}
internal const val BLOCK_BEGIN = "<!-- BEGIN DroidDeck: replaced on every turn. Write your own rules outside this block. -->"
internal const val BLOCK_END = "<!-- END DroidDeck -->"
/**
* Puts DroidDeck's [rules] in a marked block of every harness's global instructions file,
* keeping whatever the user wrote around it. Returns the files that could not be written.
*/
internal fun installInstructions(root: File, rules: String): List<String> {
val failed = mutableListOf<String>()
for (harness in AgentHarness.all) runCatching {
val file = guestTarget(root, File(root, harness.instructions)).apply { parentFile?.mkdirs() }
val existing = if (file.exists()) file.readText() else null
val merged = withBlock(existing, rules)
if (merged != existing) replaceFile(merged.byteInputStream(), file, executable = false)
}.onFailure {
android.util.Log.w("AgentSetup", "could not write ${harness.instructions}", it)
failed += harness.instructions.substringAfterLast("root/")
}
return failed
}
/** [existing] with DroidDeck's block set to [rules]: replaced in place, or put first when there is none yet. */
internal fun withBlock(existing: String?, rules: String): String {
val block = "$BLOCK_BEGIN\n${rules.trim()}\n$BLOCK_END\n"
if (existing.isNullOrBlank()) return block
val start = existing.indexOf(BLOCK_BEGIN)
val end = existing.indexOf(BLOCK_END, start.coerceAtLeast(0))
if (start < 0 || end < 0) return "$block\n$existing"
val after = existing.substring(end + BLOCK_END.length).removePrefix("\n")
return existing.substring(0, start) + block + after
}
/** Older tools/agent/setup pinned the adb port in .bashrc, which overrides the live port DroidDeck passes. */
@@ -291,24 +201,8 @@ object AgentSetup {
if (fixed != text) runCatching { bashrc.writeText(fixed) }
}
/**
* Written beside [target] and renamed over it, so a symlink left there by a hand-made setup is
* replaced rather than followed: its absolute target is a userland path the app cannot reach,
* and the failed write stopped every helper after it, the droiddeckctl guide included.
*/
private fun copyAsset(app: Context, asset: String, target: File) {
app.assets.open(asset).use { replaceFile(it, target) }
}
/** Replaces [target], or the symlink at it, with [input]. */
internal fun replaceFile(input: java.io.InputStream, target: File, executable: Boolean = true) {
// A unique name, since an agent turn and a setup step can install at the same time.
val staged = File.createTempFile(".${target.name}.", ".part", target.parentFile)
staged.outputStream().use { input.copyTo(it) }
if (executable) staged.setExecutable(true, false)
if (!staged.renameTo(target)) {
staged.delete()
throw java.io.IOException("could not replace $target")
}
app.assets.open(asset).use { input -> target.outputStream().use { input.copyTo(it) } }
target.setExecutable(true, false)
}
}
@@ -172,8 +172,5 @@ internal class AddonPack(
listOf("runtime.tzst", "version.txt"))
val UBISOFT = AddonPack("ubisoft", BuildConfig.PACK_UBISOFT_SHA256, BuildConfig.PACK_UBISOFT_SIZE,
listOf("droiddeck-upc.exe"))
val ROCKSTAR = AddonPack("rockstar", BuildConfig.PACK_ROCKSTAR_SHA256, BuildConfig.PACK_ROCKSTAR_SIZE,
listOf("Launcher32.exe", "Launcher64.exe"))
val DIRT = AddonPack("dirt", BuildConfig.PACK_DIRT_SHA256, BuildConfig.PACK_DIRT_SIZE, listOf("ws2_32.dll"))
}
}
@@ -1,39 +0,0 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
object SteamInputOverride {
private const val CONFIG_KEY = "UseSteamControllerConfig"
private const val DEFAULT_VALUE = "1"
enum class Mode(val value: String?) {
DEFAULT(null), ENABLED("2"), DISABLED("0");
companion object {
fun from(value: String): Mode? = when (value) {
DEFAULT_VALUE -> DEFAULT
"2" -> ENABLED
"0" -> DISABLED
else -> null
}
}
}
enum class Saved { YES, NO, RUNNING }
fun current(context: Context, appId: Int): Mode? =
SteamLaunchOptions.steamAppSetting(
SessionPrefs.activeSteamRoot(context), appId, CONFIG_KEY, DEFAULT_VALUE,
)?.let(Mode::from)
fun set(context: Context, appId: Int, mode: Mode, shown: Mode): Saved {
if (SessionState.running) return Saved.RUNNING
val saved = SteamLaunchOptions.writeSteamAppSetting(
SessionPrefs.activeSteamRoot(context), appId, CONFIG_KEY,
shown.value ?: DEFAULT_VALUE, mode.value, DEFAULT_VALUE,
)
return if (saved) Saved.YES else Saved.NO
}
}
@@ -13,8 +13,6 @@ import java.nio.file.StandardCopyOption
object SteamLaunchOptions {
private const val TAG = "SteamLaunchOptions"
private val STEAM = listOf("UserLocalConfigStore", "Software", "Valve", "Steam")
// Steam keeps per-game settings such as UseSteamControllerConfig in the root apps section, and launch options under Software/Valve/Steam.
private val ROOT = listOf("UserLocalConfigStore")
fun current(context: Context, appId: Int): String? =
SteamLiveShortcuts.launchOptions(context, appId.toLong()) ?: steam(SessionPrefs.activeSteamRoot(context), appId)
@@ -38,38 +36,13 @@ object SteamLaunchOptions {
val config = AddedGames.accountConfig(steamHome) ?: return null
val text = runCatching { File(config, "localconfig.vdf").readText() }.getOrNull() ?: return null
if (section(text, STEAM) == null) return null
return appValue(text, appId, "LaunchOptions").orEmpty()
return launchOptions(text, appId).orEmpty()
}
internal fun write(steamHome: File, appId: Int, options: String): Boolean {
val config = AddedGames.accountConfig(steamHome)?.let { File(it, "localconfig.vdf") } ?: return false
val text = runCatching { config.readText() }.getOrNull() ?: return false
val updated = withLaunchOptions(text, appId, options) ?: return false
return writeConfig(config, text, updated)
}
internal fun steamAppSetting(steamHome: File, appId: Int, key: String, default: String): String? {
val config = AddedGames.accountConfig(steamHome) ?: return null
val text = runCatching { File(config, "localconfig.vdf").readText() }.getOrNull() ?: return null
if (section(text, ROOT) == null) return null
return settingValue(text, appId, key) ?: default
}
private fun settingValue(text: String, appId: Int, key: String): String? =
appValue(text, appId, key, ROOT) ?: appValue(text, appId, key, STEAM)
internal fun writeSteamAppSetting(
steamHome: File, appId: Int, key: String, expected: String, value: String?, default: String,
): Boolean {
val config = AddedGames.accountConfig(steamHome)?.let { File(it, "localconfig.vdf") } ?: return false
val text = runCatching { config.readText() }.getOrNull() ?: return false
if (section(text, ROOT) == null || (settingValue(text, appId, key) ?: default) != expected) return false
val updated = (if (value == null) withoutAppValue(text, appId, key, ROOT) else withAppValue(text, appId, key, value, ROOT))
?.let { withoutAppValue(it, appId, key, STEAM) } ?: return false
return writeConfig(config, text, updated)
}
private fun writeConfig(config: File, text: String, updated: String): Boolean {
if (updated == text) return true
val staged = File(config.parentFile, config.name + ".staged")
return try {
@@ -82,57 +55,36 @@ object SteamLaunchOptions {
true
} catch (e: Exception) {
staged.delete()
Log.w(TAG, "could not write Steam app settings to ${config.path}", e)
Log.w(TAG, "could not write launch options to ${config.path}", e)
false
}
}
internal fun launchOptions(text: String, appId: Int): String? {
return appValue(text, appId, "LaunchOptions")
}
private fun appValue(text: String, appId: Int, key: String, base: List<String> = STEAM): String? {
val app = section(text, base + "apps" + appId.toString()) ?: return null
return entries(text, app.valueStart, app.end).firstOrNull { !it.section && it.key.equals(key, true) }
val app = section(text, STEAM + "apps" + appId.toString()) ?: return null
return entries(text, app.valueStart, app.end).firstOrNull { !it.section && it.key.equals("LaunchOptions", true) }
?.let { unescape(text.substring(it.valueStart + 1, it.end)) }
}
internal fun withLaunchOptions(text: String, appId: Int, options: String): String? =
withAppValue(text, appId, "LaunchOptions", options)
private fun withAppValue(text: String, appId: Int, key: String, rawValue: String, base: List<String> = STEAM): String? {
internal fun withLaunchOptions(text: String, appId: Int, options: String): String? {
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
var updated = text
var path = base
for (pathPart in listOf("apps", appId.toString())) {
updated = withSection(updated, section(updated, path) ?: return null, pathPart, newline) ?: return null
path = path + pathPart
var path = STEAM
for (key in listOf("apps", appId.toString())) {
updated = withSection(updated, section(updated, path) ?: return null, key, newline) ?: return null
path = path + key
}
val app = section(updated, path) ?: return null
val value = "\"" + escape(rawValue) + "\""
entries(updated, app.valueStart, app.end).firstOrNull { !it.section && it.key.equals(key, true) }?.let {
val value = "\"" + escape(options) + "\""
entries(updated, app.valueStart, app.end).firstOrNull { !it.section && it.key.equals("LaunchOptions", true) }?.let {
return updated.replaceRange(it.valueStart, it.end + 1, value)
}
val lineStart = closingLine(updated, app) ?: return null
val indent = updated.substring(lineStart, app.end) + "\t"
return updated.substring(0, lineStart) + indent + "\"${escape(key)}\"\t\t" + value + newline + updated.substring(lineStart)
return updated.substring(0, lineStart) + indent + "\"LaunchOptions\"\t\t" + value + newline + updated.substring(lineStart)
}
private fun withoutAppValue(text: String, appId: Int, key: String, base: List<String> = STEAM): String {
val app = section(text, base + "apps" + appId.toString()) ?: return text
val entry = entries(text, app.valueStart, app.end).firstOrNull { !it.section && it.key.equals(key, true) } ?: return text
val lineStart = text.lastIndexOf('\n', entry.start - 1) + 1
val lineEnd = text.indexOf('\n', entry.end + 1).let { if (it < 0) text.length else it }
val onlyEntryOnLine = text.substring(lineStart, entry.start).all(Char::isWhitespace) &&
text.substring(entry.end + 1, lineEnd).all(Char::isWhitespace)
return if (onlyEntryOnLine) {
text.removeRange(lineStart, if (lineEnd < text.length) lineEnd + 1 else lineEnd)
} else {
text.removeRange(entry.start, entry.end + 1)
}
}
private class Entry(val key: String, val start: Int, val valueStart: Int, val end: Int, val section: Boolean)
private class Entry(val key: String, val valueStart: Int, val end: Int, val section: Boolean)
private fun section(text: String, path: List<String>): Entry? {
var found: Entry? = null
@@ -146,27 +98,18 @@ object SteamLaunchOptions {
private fun entries(text: String, open: Int, close: Int): List<Entry> {
val found = ArrayList<Entry>()
var key: String? = null
var keyStart = -1
var i = open + 1
while (i < close) {
when {
text[i] == '"' -> {
val end = stringEnd(text, i) ?: return found
if (key == null) {
key = unescape(text.substring(i + 1, end))
keyStart = i
} else {
found += Entry(key, keyStart, i, end, false)
key = null
keyStart = -1
}
if (key == null) key = unescape(text.substring(i + 1, end)) else { found += Entry(key, i, end, false); key = null }
i = end + 1
}
text[i] == '{' -> {
val end = sectionEnd(text, i) ?: return found
key?.let { found += Entry(it, keyStart, i, end, true) }
key?.let { found += Entry(it, i, end, true) }
key = null
keyStart = -1
i = end + 1
}
text.startsWith("//", i) -> i = text.indexOf('\n', i).let { if (it < 0) close else it }
@@ -0,0 +1,115 @@
package com.droiddeck.launcher.input
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.util.zip.ZipInputStream
internal object ArmsControlSkins {
private val buttons = mapOf(
InputControl.A to "cross", InputControl.B to "circle", InputControl.X to "square", InputControl.Y to "triangle",
InputControl.LB to "l1", InputControl.RB to "r1", InputControl.LT to "l2", InputControl.RT to "r2",
InputControl.L3 to "l3", InputControl.R3 to "r3", InputControl.SELECT to "select", InputControl.START to "start",
InputControl.UP to "up", InputControl.DOWN to "down", InputControl.LEFT to "left", InputControl.RIGHT to "right")
private val keys = buttons.values.toSet() + setOf("analog_base", "analog_stick", "analog_base_left", "analog_base_right",
"analog_stick_left", "analog_stick_right")
fun parse(context: android.content.Context, bytes: ByteArray, original: SavedInputLayout, actions: SavedInputBindings, name: String, nativeFailure: Exception? = null): CommunityControls.Pack {
require(bytes.size <= 32 * 1024 * 1024 && original.editable && actions.compatible(original))
val art = linkedMapOf<String, ByteArray>()
var total = 0
var entries = 0
ZipInputStream(ByteArrayInputStream(bytes)).use { zip ->
while (true) {
val entry = zip.nextEntry ?: break
require(++entries <= 256 && ControlSources.validPath(entry.name.trimEnd('/'))) { "Invalid skin archive path or file count." }
if (entry.isDirectory) continue
val data = CommunityControls.readLimited(zip, minOf(8 * 1024 * 1024, 64 * 1024 * 1024 - total))
total += data.size
if (entry.name == "controls.json") throw (nativeFailure ?: IllegalArgumentException("Import this file as a DroidDeck controls pack."))
val file = entry.name.substringAfterLast('/').lowercase()
if (file.startsWith("._") || !file.endsWith(".png")) continue
val key = file.removeSuffix(".png").removePrefix("ic_controller_").removeSuffix("_button")
if (key !in keys) continue
require(key !in art) { "Duplicate skin button artwork." }
art[key] = normalize(data)
}
}
require(art.isNotEmpty()) { "No supported controller PNGs found in this skin." }
val used = linkedMapOf<String, ByteArray>()
fun image(key: String): String? = art[key]?.let { data ->
val file = "skin_$key.png"
used[file] = data
file
}
var matched = 0
val elements = original.elements.map { e ->
val action = actions.action(e) as? InputAction.Native ?: return@map e
val control = action.target ?: e.control
if (e.kind == InputElementKind.STICK && (control == InputControl.LS || control == InputControl.RS)) {
val side = if (control == InputControl.LS) "left" else "right"
val base = image("analog_base_$side") ?: image("analog_base")
val stick = image("analog_stick_$side") ?: image("analog_stick")
if (base == null && stick == null) e else {
matched++
e.copy(image = base ?: e.image, stickImage = stick ?: e.stickImage, showLabel = false)
}
} else if (e.kind == InputElementKind.BUTTON || e.kind == InputElementKind.TRIGGER) {
val file = buttons[control]?.let(::image)
if (file == null) e else { matched++; e.copy(image = file, icon = 0, showLabel = false) }
} else e
}
require(matched > 0) { "This layout has no matching gamepad controls. Choose a gamepad profile and screen." }
val id = newInputId()
val label = name.trim().take(80).ifBlank { "Imported controller skin" }
val layout = original.copy(id = id, name = label, origin = null, elements = elements)
for (file in elements.flatMap { listOf(it.image, it.stickImage) }.filter { it.isNotEmpty() }.distinct()) {
if (file !in used) used[file] = requireNotNull(InputButtonImages.file(context, file)).inputStream().use {
CommunityControls.readLimited(it, 1024 * 1024)
}
}
return CommunityControls.Pack(layout, actions.copy(id = newInputId(), name = label, layoutId = id), used)
}
fun export(context: android.content.Context, layout: SavedInputLayout, actions: SavedInputBindings): ByteArray {
val images = linkedMapOf<String, String>()
for (element in layout.elements) {
val action = actions.action(element) as? InputAction.Native ?: continue
val control = action.target ?: element.control
if (element.kind == InputElementKind.STICK && (control == InputControl.LS || control == InputControl.RS)) {
val side = if (control == InputControl.LS) "left" else "right"
if (element.image.isNotEmpty()) images["ic_controller_analog_base_$side.png"] = element.image
if (element.stickImage.isNotEmpty()) images["ic_controller_analog_stick_$side.png"] = element.stickImage
} else if (element.image.isNotEmpty()) {
buttons[control]?.let { images["ic_controller_${it}_button.png"] = element.image }
}
}
require(images.isNotEmpty()) { "This layout has no controller skin artwork to export." }
val output = ByteArrayOutputStream()
java.util.zip.ZipOutputStream(output).use { zip ->
for ((name, local) in images) {
val bytes = requireNotNull(InputButtonImages.file(context, local)).inputStream().use {
CommunityControls.readLimited(it, 1024 * 1024)
}
zip.putNextEntry(java.util.zip.ZipEntry(name)); zip.write(bytes); zip.closeEntry()
}
}
return output.toByteArray().also { require(it.size <= 32 * 1024 * 1024) }
}
private fun normalize(data: ByteArray): ByteArray {
require(data.take(8) == listOf<Byte>(-119, 80, 78, 71, 13, 10, 26, 10)) { "Invalid skin PNG." }
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(data, 0, data.size, bounds)
require(bounds.outWidth in 1..8192 && bounds.outHeight in 1..8192) { "Invalid skin image dimensions." }
val options = BitmapFactory.Options().apply {
inSampleSize = 1
while (maxOf(bounds.outWidth, bounds.outHeight) / inSampleSize > 512) inSampleSize *= 2
}
val bitmap = requireNotNull(BitmapFactory.decodeByteArray(data, 0, data.size, options)) { "Unreadable skin image." }
return try {
ByteArrayOutputStream().also { check(bitmap.compress(Bitmap.CompressFormat.PNG, 100, it)) }.toByteArray()
} finally { bitmap.recycle() }
}
}
@@ -0,0 +1,197 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.BitmapFactory
import org.json.JSONObject
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
import java.security.MessageDigest
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
import java.util.zip.ZipOutputStream
internal object CommunityControls {
const val MAX_BYTES = 16 * 1024 * 1024
const val BASE = "https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/community/controls/"
const val SUBMIT = "https://github.com/Droid-Deck/DroidDeck/issues/new?template=community-controls.yml"
data class Pack(val layout: SavedInputLayout, val bindings: SavedInputBindings, val images: Map<String, ByteArray>)
data class Entry(val name: String, val author: String, val game: String, val license: String,
val path: String, val sha256: String, val screen: InputLayoutScreen, val preview: String? = null, val bundled: Boolean = false,
val source: ControlSources.Source = ControlSources.DROIDDECK, val skin: Boolean = false) {
val key get() = source.id + "/" + path
}
fun readLimited(input: InputStream, limit: Int = MAX_BYTES): ByteArray {
val output = ByteArrayOutputStream()
val buffer = ByteArray(8192)
while (true) {
val count = input.read(buffer)
if (count < 0) break
require(output.size() + count <= limit) { "Controls file is too large." }
output.write(buffer, 0, count)
}
return output.toByteArray()
}
fun export(context: Context, layout: SavedInputLayout, bindings: SavedInputBindings): ByteArray {
require(layout.editable && bindings.compatible(layout))
val library = InputLibraries.read(context).withLayout(layout).withPreset(bindings)
val doc = JSONObject(InputLibraries.encode(library))
fun item(key: String, id: String): JSONObject {
val array = doc.getJSONArray(key)
return (0 until array.length()).map { array.getJSONObject(it) }.first { it.getString("id") == id }
}
val manifest = JSONObject().put("format", "droiddeck-controls").put("version", 1)
.put("layout", item("layouts", layout.id)).put("bindings", item("bindings", bindings.id))
val output = ByteArrayOutputStream()
ZipOutputStream(output).use { zip ->
fun add(name: String, bytes: ByteArray) {
zip.putNextEntry(ZipEntry(name)); zip.write(bytes); zip.closeEntry()
}
add("controls.json", manifest.toString().toByteArray(Charsets.UTF_8))
for (name in layout.elements.flatMap { listOf(it.image, it.stickImage) }.filter { it.isNotEmpty() }.distinct()) {
val file = requireNotNull(InputButtonImages.file(context, name))
add("images/$name", file.inputStream().use { readLimited(it, 1024 * 1024) })
}
}
return output.toByteArray().also { parse(context, it) }
}
fun parse(context: Context, bytes: ByteArray): Pack {
require(bytes.size <= MAX_BYTES)
val files = linkedMapOf<String, ByteArray>()
var total = 0
ZipInputStream(ByteArrayInputStream(bytes)).use { zip ->
while (true) {
val entry = zip.nextEntry ?: break
require(!entry.isDirectory && files.size < 65 && entry.name !in files)
require(entry.name == "controls.json" || entry.name.matches(Regex("images/[A-Za-z0-9_-][A-Za-z0-9_.-]{0,127}")))
val data = readLimited(zip, minOf(if (entry.name == "controls.json") 2_000_000 else 1024 * 1024, MAX_BYTES - total))
total += data.size
files[entry.name] = data
}
}
val manifest = JSONObject(requireNotNull(files.remove("controls.json")).toString(Charsets.UTF_8))
require(manifest.getString("format") == "droiddeck-controls" && manifest.getInt("version") == 1)
val layout = manifest.getJSONObject("layout")
val bindings = manifest.getJSONObject("bindings")
val layoutId = newInputId()
val bindingId = newInputId()
layout.put("id", layoutId).remove("origin")
require(layout.getString("template") == InputLayoutTemplate.CUSTOM.name)
bindings.put("id", bindingId).put("layout", layoutId)
require(!bindings.getBoolean("physical") && bindings.getJSONArray("keys").length() == 0)
val doc = JSONObject(InputLibraries.encode(InputLibraries.read(context)))
doc.getJSONArray("layouts").put(layout)
doc.getJSONArray("bindings").put(bindings)
val decoded = requireNotNull(InputLibraries.decode(doc.toString())) { "Invalid controls or bindings." }
val saved = decoded.layouts.first { it.id == layoutId }
val names = saved.elements.flatMap { listOf(it.image, it.stickImage) }.filter { it.isNotEmpty() }.toSet()
require(files.keys == names.map { "images/$it" }.toSet()) { "Missing or unexpected button images." }
var pixels = 0L
val images = names.associateWith { name ->
val data = files.getValue("images/$name")
require(data.take(8) == listOf<Byte>(-119, 80, 78, 71, 13, 10, 26, 10))
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(data, 0, data.size, bounds)
require(bounds.outWidth in 1..1024 && bounds.outHeight in 1..1024)
pixels += bounds.outWidth.toLong() * bounds.outHeight
require(pixels <= 16_777_216)
val bitmap = requireNotNull(BitmapFactory.decodeByteArray(data, 0, data.size))
bitmap.recycle()
data
}
return Pack(saved, decoded.preset(bindingId), images)
}
fun importFile(context: Context, bytes: ByteArray, layout: SavedInputLayout, bindings: SavedInputBindings): Pack =
try { parse(context, bytes) } catch (nativeFailure: Exception) {
ArmsControlSkins.parse(context, bytes, layout, bindings, "Imported skin", nativeFailure)
}
fun install(context: Context, pack: Pack, profile: String, role: InputRole): InputLibrary {
require(pack.layout.supports(role))
val written = mutableListOf<java.io.File>()
try {
val names = pack.images.mapValues { (_, bytes) ->
val name = "key_${newInputId()}.png"
val file = requireNotNull(InputButtonImages.file(context, name))
file.parentFile!!.mkdirs()
written += file
file.writeBytes(bytes)
name
}
val layout = pack.layout.copy(elements = pack.layout.elements.map { e -> e.copy(image = names[e.image] ?: "", stickImage = names[e.stickImage] ?: "") })
return InputLibraries.update(context) {
it.withLayout(layout).withPreset(pack.bindings).chooseLayout(profile, role, layout.id)
}
} catch (e: Exception) {
written.forEach { it.delete() }
throw e
}
}
fun catalog(raw: String, source: ControlSources.Source = ControlSources.DROIDDECK): List<Entry> {
require(raw.length <= 1_000_000)
val doc = JSONObject(raw)
val skin = doc.has("skins") && !doc.has("controls")
require(skin || doc.getInt("version") == 1)
val list = doc.getJSONArray(if (skin) "skins" else "controls")
require(list.length() <= 256)
return (0 until list.length()).map { index ->
val e = list.getJSONObject(index)
fun text(key: String) = e.getString(key).also { require(it.isNotBlank() && it.length <= 160) }
val path = text("file")
require(ControlSources.validPath(path) && path.endsWith(".zip", ignoreCase = true))
val sha = e.optString("sha256").also { require(if (skin) it.isEmpty() || it.matches(Regex("[a-f0-9]{64}")) else it.matches(Regex("[a-f0-9]{64}"))) }
Entry(text("name"), e.optString("author").take(160), e.optString("game").take(160), e.optString("license").take(160), path, sha,
if (skin) InputLayoutScreen.BOTH else InputLayoutScreen.valueOf(e.getString("screen")), e.optString("preview").takeIf { it.isNotEmpty() }?.also {
require(ControlSources.validPath(it) && it.endsWith(".png", ignoreCase = true))
}, source = source, skin = skin)
}.also { require(it.map { e -> e.path }.distinct().size == it.size) }
}
fun bundled(context: Context): List<Entry> = context.assets.open("community-controls/catalog.json").use {
catalog(readLimited(it, 1_000_000).toString(Charsets.UTF_8)).map { e -> e.copy(bundled = true) }
}
fun fetchCatalog(source: ControlSources.Source = ControlSources.DROIDDECK): List<Entry> =
catalog(get(source.manifest, 1_000_000).toString(Charsets.UTF_8), source)
fun preview(context: Context, entry: Entry): android.graphics.Bitmap? {
val path = entry.preview ?: return null
val bytes = if (entry.bundled) context.assets.open("community-controls/$path").use { readLimited(it, 512 * 1024) }
else get(entry.source.url(path), 2 * 1024 * 1024)
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
require(bounds.outWidth in 1..4096 && bounds.outHeight in 1..4096)
val options = BitmapFactory.Options().apply {
inSampleSize = 1
while (maxOf(bounds.outWidth, bounds.outHeight) / inSampleSize > 256) inSampleSize *= 2
}
return BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
}
fun download(context: Context, entry: Entry, layout: SavedInputLayout? = null, bindings: SavedInputBindings? = null): Pack {
val bytes = if (entry.bundled) context.assets.open("community-controls/${entry.path}").use { readLimited(it) }
else get(entry.source.url(entry.path), if (entry.skin) 32 * 1024 * 1024 else MAX_BYTES)
val sha = MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }
require(entry.sha256.isEmpty() && entry.skin || sha == entry.sha256) { "Controls download failed verification." }
return if (entry.skin) ArmsControlSkins.parse(context, bytes, requireNotNull(layout), requireNotNull(bindings), entry.name)
else parse(context, bytes).also { require(it.layout.screen == entry.screen) }
}
private fun get(url: String, limit: Int): ByteArray {
val connection = URL(url).openConnection() as HttpURLConnection
connection.connectTimeout = 15_000
connection.readTimeout = 30_000
connection.instanceFollowRedirects = false
return try {
require(connection.responseCode == 200) { "Could not download community controls (${connection.responseCode})." }
require(connection.contentLengthLong <= limit)
connection.inputStream.use { readLimited(it, limit) }
} finally { connection.disconnect() }
}
}
@@ -0,0 +1,78 @@
package com.droiddeck.launcher.input
import android.content.Context
import org.json.JSONArray
import java.net.URI
import java.net.URLEncoder
internal object ControlSources {
data class Source(val name: String, val manifest: String, val submit: String? = null, val builtIn: Boolean = false) {
val id get() = manifest
fun url(path: String): String {
require(validPath(path)) { "Invalid controls source path." }
return manifest.substringBeforeLast('/') + "/" + path.split('/').joinToString("/") {
URLEncoder.encode(it, "UTF-8").replace("+", "%20")
}
}
}
val DROIDDECK = Source("DroidDeck", CommunityControls.BASE + "catalog.json", CommunityControls.SUBMIT, true)
val ARMSX2 = Source("ARMSX2 community", "https://raw.githubusercontent.com/bagasromadon/ARMSX2-CustomControllerSkins/main/manifest.json",
"https://github.com/bagasromadon/ARMSX2-CustomControllerSkins/issues/new", true)
private fun prefs(context: Context) = context.getSharedPreferences("community-control-sources", Context.MODE_PRIVATE)
fun validPath(path: String) = path.length in 1..512 && path.split('/').all { it.isNotBlank() && it != "." && it != ".." } &&
path.none { it.isISOControl() || it in "\\:%?#" } && !path.startsWith('/')
private fun https(raw: String): URI {
require(raw.length <= 2048)
val uri = URI(raw.trim())
require(uri.scheme == "https" && !uri.host.isNullOrBlank() && uri.userInfo == null && uri.fragment == null && uri.query == null && !uri.path.isNullOrBlank() && !uri.path.endsWith('/')) {
"Enter an HTTPS catalog URL or a GitHub repository URL."
}
return uri
}
fun candidates(raw: String): List<Source> {
val uri = https(raw)
val parts = uri.path.trim('/').split('/')
if (uri.host.equals("github.com", true)) {
require(parts.size == 2 || parts.size >= 5 && parts[2] == "blob") { "Use a GitHub repository or manifest file URL." }
require(parts.take(2).all { it.matches(Regex("[A-Za-z0-9_.-]+")) && it != "." && it != ".." })
val repo = parts.take(2).joinToString("/")
val submit = "https://github.com/$repo/issues/new"
val base = "https://raw.githubusercontent.com/$repo/"
return if (parts.size == 2) listOf("catalog.json", "manifest.json").map { Source(repo, base + "main/" + it, submit) }
else listOf(Source(repo, base + parts.drop(3).joinToString("/"), submit))
}
val submit = if (uri.host.equals("raw.githubusercontent.com", true) && parts.size >= 4)
"https://github.com/${parts[0]}/${parts[1]}/issues/new" else null
return listOf(Source(if (submit != null) parts.take(2).joinToString("/") else uri.host, uri.toASCIIString(), submit))
}
fun read(context: Context): List<Source> {
val custom = runCatching {
val raw = prefs(context).getString("sources", "[]")!!
require(raw.length <= 32_000)
val array = JSONArray(raw)
require(array.length() <= 16)
(0 until array.length()).map { candidates(array.getString(it)).single() }
}.getOrDefault(emptyList())
return (listOf(DROIDDECK, ARMSX2) + custom).distinctBy { it.id }
}
fun add(context: Context, source: Source) {
val list = read(context)
require(list.none { it.id == source.id }) { "This source is already connected." }
require(list.size < 18) { "Remove a source before adding another." }
save(context, list + source)
}
fun remove(context: Context, source: Source) {
require(!source.builtIn)
save(context, read(context).filterNot { it.id == source.id })
}
private fun save(context: Context, sources: List<Source>) {
check(prefs(context).edit().putString("sources", JSONArray(sources.filterNot { it.builtIn }.map { it.manifest }).toString()).commit()) {
"Could not save controls sources."
}
}
}
@@ -0,0 +1,25 @@
package com.droiddeck.launcher.input
import android.content.Context
object GameInputControls {
private fun prefs(context: Context) = context.getSharedPreferences("input-game-controls", Context.MODE_PRIVATE)
fun profile(context: Context, game: String?): String? = game?.let { prefs(context).getString(it, null) }
fun set(context: Context, game: String, profile: String?) {
require(game.isNotBlank() && game.length <= 512)
require(profile == null || InputLibraries.read(context).profiles.any { it.id == profile })
val edit = prefs(context).edit()
if (profile == null) edit.remove(game) else edit.putString(game, profile)
check(edit.commit()) { "Could not save game controls." }
}
fun resolve(context: Context, library: InputLibrary, desktop: Boolean, game: String?): InputLibrary {
val selection = library.selection(desktop)
if (game == null || selection.profile != InputProfiles.AUTO) return library
val target = profile(context, game)?.let { id -> library.profiles.firstOrNull { it.id == id } } ?: return library
var result = library
for (role in listOf(InputRole.PRIMARY, InputRole.SECONDARY)) {
if (role !in selection.parts) result = result.selectPart(desktop, role, target.binding(role))
}
return result
}
}
@@ -10,7 +10,7 @@ import org.json.JSONObject
import java.util.UUID
object InputLibraries {
private const val VERSION = 14
private const val VERSION = 15
private const val KEY = "library"
private const val RECOVERY = "library-recovery."
const val OVERLAY = "builtin.overlay"
@@ -304,7 +304,7 @@ object InputLibraries {
for (e in layout.elements) elements.put(JSONObject().put("id", e.id).put("kind", e.kind.name)
.put("control", e.control.id).put("name", e.name).put("x", e.x.toDouble()).put("y", e.y.toDouble())
.put("width", e.width.toDouble()).put("height", e.height.toDouble()).put("floating", e.floating).put("hideWhenIdle", e.hideWhenIdle).put("mouseGestures", e.mouseGestures).put("toggle", e.toggle).put("icon", e.icon).put("image", e.image)
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown))
.put("elementOpacity", e.opacity.toDouble()).put("buttonShape", e.buttonShape.name).put("showLabel", e.showLabel).put("alwaysShown", e.alwaysShown).put("stickImage", e.stickImage))
layouts.put(JSONObject().put("id", layout.id).put("name", layout.name).put("template", layout.template.name).put("elements", elements)
.put("tint", layout.style.tint ?: JSONObject.NULL).put("opacity", layout.style.opacity).put("screen", layout.screen.name).put("aspect", layout.aspect.toDouble()).put("scale", layout.scale.toDouble())
.put("hidden", JSONArray(layout.style.hidden.map { it.name }.sorted())).put("origin", layout.origin ?: JSONObject.NULL))
@@ -345,7 +345,7 @@ object InputLibraries {
e.getDouble("y").toFloat(), e.getDouble("width").toFloat(), e.getDouble("height").toFloat(),
e.getString("id"), InputElementKind.valueOf(e.getString("kind")), e.getString("name"),
e.optBoolean("floating", true), e.optBoolean("hideWhenIdle", false), e.optBoolean("mouseGestures", false), e.optBoolean("toggle", false), e.optInt("icon", 0), e.optString("image", ""),
e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false))
e.optDouble("elementOpacity", 1.0).toFloat(), InputButtonShape.valueOf(e.optString("buttonShape", InputButtonShape.ROUNDED.name)), e.optBoolean("showLabel", true), e.optBoolean("alwaysShown", false), e.optString("stickImage", ""))
}
SavedInputLayout(layout.getString("id"), layout.getString("name"), elements, InputLayoutTemplate.valueOf(layout.getString("template")),
InputSurfaceStyle(if (!layout.has("tint")) ControllerPrefs.STEAM_BLUE else if (layout.isNull("tint")) null else layout.getInt("tint"), layout.optInt("opacity", 100),
@@ -244,7 +244,8 @@ data class InputLibrary(
for (e in layout.elements) {
inputName(e.name)
require(e.icon == 0 || InputButtonIcons.has(e.icon))
require(e.image.isEmpty() || e.image.matches(Regex("[A-Za-z0-9_.-]{1,128}")) && e.image != "." && e.image != "..")
for (image in listOf(e.image, e.stickImage))
require(image.isEmpty() || image.matches(Regex("[A-Za-z0-9_.-]{1,128}")) && image != "." && image != "..")
require(e.opacity.isFinite() && e.opacity in 0.01f..1f)
require(!e.toggle || e.kind == InputElementKind.BUTTON || e.kind == InputElementKind.TRIGGER)
require(listOf(e.x, e.y, e.width, e.height).all { it.isFinite() })
@@ -35,6 +35,7 @@ data class InputSurfaceElement(
val buttonShape: InputButtonShape = InputButtonShape.ROUNDED,
val showLabel: Boolean = true,
val alwaysShown: Boolean = false,
val stickImage: String = "",
) {
val hasClick get() = kind == InputElementKind.STICK || kind == InputElementKind.TRACKPAD
@@ -20,6 +20,7 @@ object GameProfileManager {
}
clear("Proton") { ProtonDefault.requestGame(context, scope, null) }
clear("component packages") { ComponentsManager.clearGameComponents(context, scope) }
clear("on-screen controls") { com.droiddeck.launcher.input.GameInputControls.set(context, scope, null) }
clear("texture filtering") { SessionPrefs.clearGameTextureFiltering(context, scope) }
clear("Windows components") { WinComponents.setPicks(context, scope, emptyList()) }
@@ -36,60 +36,35 @@ object SessionFiles {
"etc/xdg/autostart/droiddeck-clipboard.desktop" to "etc/xdg/autostart/droiddeck-clipboard.desktop",
)
private val SERVICE_PACKS = mapOf(
AddonPack.UBISOFT to "usr/local/lib/droiddeck-ubisoft",
AddonPack.ROCKSTAR to "usr/local/lib/droiddeck-rockstar",
AddonPack.DIRT to "usr/local/lib/droiddeck-dirt",
)
private const val UBISOFT_SERVICE = "usr/local/lib/droiddeck-ubisoft/droiddeck-upc.exe"
/** Fetches the Ubisoft pack and, once it lands, stages the service so a running session gets it without restarting. */
fun ensureUbisoftService(context: Context) = ensureStoreService(context, AddonPack.UBISOFT)
fun ensureRockstarService(context: Context) = ensureStoreService(context, AddonPack.ROCKSTAR)
/** The DiRT 3 / DiRT Showdown ws2_32 stand-in; droiddeck-game-env applies it only when it is staged. */
fun ensureDirtStandIn(context: Context) = ensureStoreService(context, AddonPack.DIRT)
private fun ensureStoreService(context: Context, pack: AddonPack) {
pack.ensure(context) { app ->
fun ensureUbisoftService(context: Context) {
AddonPack.UBISOFT.ensure(context) { app ->
com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app).takeIf { it.isDirectory }
?.let { stageStoreService(app, it, pack, null) }
?.let { stageUbisoftService(app, it, null) }
}
}
/** Blocks until the store's service pack is installed and staged in [root]; false when it could not be fetched. */
fun awaitStoreService(context: Context, store: String, root: File): Boolean {
val pack = SERVICE_PACKS.keys.firstOrNull { it.name == store } ?: return false
if (!pack.await(context)) return false
return stageStoreService(context, root, pack, null)
}
@Synchronized
private fun stageStoreService(context: Context, root: File, pack: AddonPack, ledger: StageLedger?): Boolean {
val dir = pack.takeIf { it.installed(context) }?.dir(context) ?: return false
val base = SERVICE_PACKS.getValue(pack)
var all = true
for (file in dir.listFiles().orEmpty().filter { it.isFile && it.name != AddonPack.COMPLETE }.sortedBy { it.name }) {
val relative = "$base/${file.name}"
val target = File(root, relative)
if (ledger?.current(relative, target) == true) continue
val staged = File(target.parentFile, target.name + ".staged")
var installed = false
try {
target.parentFile?.mkdirs()
file.inputStream().use { input ->
staged.outputStream().use { output -> FileUtils.copy(input, output) }
}
installed = staged.setExecutable(true, false) && staged.renameTo(target)
} catch (e: Exception) {
Log.w(TAG, "could not stage the ${pack.name} pack", e)
} finally {
if (!installed) staged.delete()
private fun stageUbisoftService(context: Context, root: File, ledger: StageLedger?) {
val pack = AddonPack.UBISOFT.takeIf { it.installed(context) }?.dir(context) ?: return
val target = File(root, UBISOFT_SERVICE)
if (ledger?.current(UBISOFT_SERVICE, target) == true) return
val staged = File(target.parentFile, target.name + ".staged")
var installed = false
try {
target.parentFile?.mkdirs()
File(pack, "droiddeck-upc.exe").inputStream().use { input ->
staged.outputStream().use { output -> FileUtils.copy(input, output) }
}
if (installed) ledger?.staged(relative, target) else Log.e(TAG, "$relative NOT staged")
all = all && installed
installed = staged.setExecutable(true, false) && staged.renameTo(target)
} catch (e: Exception) {
Log.w(TAG, "could not stage the Ubisoft launcher service", e)
} finally {
if (!installed) staged.delete()
}
return all
if (installed) ledger?.staged(UBISOFT_SERVICE, target) else Log.e(TAG, "$UBISOFT_SERVICE NOT staged")
}
fun stage(context: Context, root: File, startsSession: Boolean = false) {
@@ -98,6 +73,8 @@ object SessionFiles {
GameEnvironmentStore.publish(context)
WinComponents.publish(context)
val files = arrayOf(
"rockstar/helpers/Launcher32.exe" to "usr/local/lib/droiddeck-rockstar/Launcher32.exe",
"rockstar/helpers/Launcher64.exe" to "usr/local/lib/droiddeck-rockstar/Launcher64.exe",
"usr/local/bin/droiddeck-game-env" to "usr/local/bin/droiddeck-game-env",
"usr/local/bin/droiddeck-game-debug" to "usr/local/bin/droiddeck-game-debug",
"usr/local/bin/droiddeck-game-gpu" to "usr/local/bin/droiddeck-game-gpu",
@@ -257,6 +234,7 @@ object SessionFiles {
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
"usr/local/lib/droiddeck-dirt/ws2_32.dll" to "usr/local/lib/droiddeck-dirt/ws2_32.dll",
) + mangoapp + xclipse.map { it to it } + maliCompat + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) ->
val dir = asset.substringBeforeLast('/')
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
@@ -270,7 +248,7 @@ object SessionFiles {
var installed = false
try {
target.parentFile?.mkdirs()
context.assets.open("linuxfs/$asset").use { input ->
(if (asset.startsWith("rockstar/")) requireNotNull(javaClass.getResourceAsStream("/$asset")) else context.assets.open("linuxfs/$asset")).use { input ->
staged.outputStream().use { output -> FileUtils.copy(input, output) }
}
installed = staged.setExecutable(true, false) && staged.renameTo(target)
@@ -312,7 +290,7 @@ object SessionFiles {
}
if (installed) ledger.staged(key, target) else Log.e(TAG, "DirectAudio $set/$relative NOT staged")
}
for (pack in SERVICE_PACKS.keys) stageStoreService(context, root, pack, ledger)
stageUbisoftService(context, root, ledger)
ledger.save()
for (old in arrayOf("aarch64-unix", "aarch64-windows", "i386-windows")) File(root, "$DIRECTAUDIO_DIR/lib/wine/$old").deleteRecursively()
val preload = StringBuilder("/usr/local/lib/libblsession.so\n")
@@ -641,13 +641,6 @@ object SessionPrefs {
position.takeIf { it in listOf("top", "bottom", "left", "right", "center") } ?: "center").apply()
}
fun integerScaling(context: Context): Boolean =
prefs(context).getBoolean("integerScaling", false)
fun setIntegerScaling(context: Context, enabled: Boolean) {
prefs(context).edit().putBoolean("integerScaling", enabled).apply()
}
fun returnAfterGame(context: Context): Boolean = prefs(context).getBoolean("returnAfterGame", true)
fun setReturnAfterGame(context: Context, on: Boolean) {
@@ -946,19 +939,9 @@ object SessionPrefs {
prefs(context).edit().putBoolean("steamGpuCompositing", false).apply()
return false
}
return prefs(context).getBoolean("steamGpuCompositing", true)
return prefs(context).getBoolean("steamGpuCompositing", false)
}
fun steamGpuDrawingShown(context: Context, systemDriverPath: Boolean = systemDriverSteamPath(context)): Boolean =
steamGpuCompositing(context) && (!systemDriverPath || prefs(context).contains("steamGpuCompositing"))
fun steamGpuCompositingChosen(context: Context, mode: String): Boolean =
mode == SessionService.MODE_STEAM && steamGpuDrawingShown(context, true)
fun systemDriverSteamPath(context: Context): Boolean =
!com.droiddeck.launcher.core.DeviceSupport.vkBridge(context) && !VenusComponent.wanted(context) &&
com.droiddeck.launcher.gpu.SystemVulkanDriver.usesDefault(linuxDriver(context))
fun steamGpuCompositingAllowed(): Boolean =
!com.droiddeck.launcher.core.DeviceSupport.adreno() && !com.droiddeck.launcher.core.DeviceSupport.mali()
@@ -971,9 +971,8 @@ class SessionService : Service() {
linuxDriverId,
)
val bridge = com.droiddeck.launcher.core.DeviceSupport.vkBridge(this)
if (SessionPrefs.systemDriverSteamPath(this)) {
if (!bridge && !venus && SystemVulkanDriver.usesDefault(linuxDriverId)) {
SystemVulkanDriver.addEnvironment(this, guest)
if (SessionPrefs.steamGpuCompositingChosen(this, SessionState.mode)) guest.add("BL_STEAM_GPU_COMPOSITING=1")
}
(if (bridge || venus) null else LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId))
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
@@ -18,7 +18,7 @@ object SettingsReset {
"storesInstallLanguage",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController",
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "picturePosition", "integerScaling", "railLabels", "agentTab", "navTabOrder", "navTabShelved", "navTabHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"stretch16x9", "picturePosition", "railLabels", "agentTab", "navTabOrder", "navTabShelved", "navTabHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores", "ramCapMb", "vramCapMb", "zramClient", "zramIdle",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
@@ -80,11 +80,6 @@ object StoreLaunchRequests {
lastLaunched = Store.ROCKSTAR to request.optString("id")
com.droiddeck.launcher.stores.rockstar.RockstarLaunch.prepare(app, request.optString("id"))
}.getOrElse { JSONObject().put("ok", false).put("reason", "error-" + it.javaClass.simpleName) }
"store-service" -> runCatching {
val root = com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app)
if (com.droiddeck.launcher.session.SessionFiles.awaitStoreService(app, request.optString("store"), root)) JSONObject().put("ok", true)
else JSONObject().put("ok", false).put("reason", "service-unavailable")
}.getOrElse { JSONObject().put("ok", false).put("reason", "error-" + it.javaClass.simpleName) }
"rockstar-exited" -> {
if (lastLaunched == (Store.ROCKSTAR to request.optString("id"))) lastLaunched = null
JSONObject().put("ok", true)
@@ -141,7 +141,6 @@ object RockstarAuth {
StoreAccounts.clear(context.applicationContext, Store.ROCKSTAR)
return "ticket"
}
com.droiddeck.launcher.session.SessionFiles.ensureRockstarService(context)
return null
}
@@ -61,7 +61,7 @@ internal object XboxRuntime {
val view = result.get(90, java.util.concurrent.TimeUnit.SECONDS)
check(renew(app, id, token) && synchronized(state) { generation == current }) { "Xbox launch was cancelled" }
return JSONObject().put("ok", true).put("socket", socket.path).put("lease", token)
.put("exe", view.getString("exe")).put("playfab", view.opt("playfab")).put("mountRoot", view.opt("mountRoot"))
.put("exe", view.getString("exe")).put("playfab", view.opt("playfab"))
} catch (e: Exception) { released(token); throw e }
}
@@ -33,7 +33,6 @@ import androidx.compose.runtime.key
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.produceState
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
@@ -74,10 +73,8 @@ import com.droiddeck.launcher.frontend.LogoPosition
import com.droiddeck.launcher.frontend.SoundtrackCollectionArt
import com.droiddeck.launcher.frontend.SteamGameArt
import com.droiddeck.launcher.frontend.SteamGridDb
import com.droiddeck.launcher.frontend.SteamInputOverride
import com.droiddeck.launcher.frontend.SteamLaunchOptions
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@@ -339,107 +336,6 @@ internal fun SteamLaunchOptionsPanel(appId: Int) {
}
}
@Composable
internal fun SteamInputOverridePanel(appId: Int) {
val app = LocalContext.current.applicationContext
val colors = MaterialTheme.colorScheme
val scope = rememberCoroutineScope()
var selected by remember(appId) { mutableStateOf<SteamInputOverride.Mode?>(null) }
var version by remember(appId) { mutableIntStateOf(0) }
var saving by remember(appId) { mutableStateOf(false) }
var loading by remember(appId) { mutableStateOf(true) }
var error by remember(appId) { mutableStateOf<Int?>(null) }
var saves by remember(appId) { mutableIntStateOf(0) }
// SessionState.running is not snapshot state, so the panel polls it while shown.
val sessionRunning by produceState(SessionState.running) {
while (true) {
value = SessionState.running
kotlinx.coroutines.delay(1000)
}
}
LaunchedEffect(appId, version) {
val savesAtStart = saves
val read = withContext(Dispatchers.IO) { SteamInputOverride.current(app, appId) }
// A save that finished while this read ran already set the selection; the read may predate it.
if (!saving && saves == savesAtStart) selected = read
loading = false
}
var wasRunning by remember(appId) { mutableStateOf(SessionState.running) }
LaunchedEffect(sessionRunning) {
// Steam may have changed the override while it ran, so every stop reloads it.
if (wasRunning && !sessionRunning) {
if (error == R.string.edit_steam_input_running) error = null
loading = true
version++
}
wasRunning = sessionRunning
}
val lifecycle = LocalLifecycleOwner.current.lifecycle
DisposableEffect(lifecycle, appId) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME && !saving) {
loading = true
version++
}
}
lifecycle.addObserver(observer)
onDispose { lifecycle.removeObserver(observer) }
}
val choices = listOf(
SteamInputOverride.Mode.DEFAULT to R.string.edit_steam_input_default,
SteamInputOverride.Mode.ENABLED to R.string.edit_steam_input_enable,
SteamInputOverride.Mode.DISABLED to R.string.edit_steam_input_disable,
)
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
stringResource(R.string.edit_steam_input_override),
fontSize = 13.sp,
fontWeight = FontWeight.SemiBold,
color = colors.onSurfaceVariant,
modifier = Modifier.padding(start = 4.dp, bottom = 2.dp),
)
choices.forEach { (mode, label) ->
MenuItem(
stringResource(label),
checked = selected == mode,
enabled = selected != null && !saving && !loading && !sessionRunning && selected != mode,
) {
val before = selected ?: return@MenuItem
saving = true
scope.launch {
try {
val saved = withContext(Dispatchers.IO) { SteamInputOverride.set(app, appId, mode, before) }
error = when (saved) {
SteamInputOverride.Saved.YES -> null
SteamInputOverride.Saved.NO -> R.string.edit_steam_input_not_saved
SteamInputOverride.Saved.RUNNING -> R.string.edit_steam_input_running
}
if (saved == SteamInputOverride.Saved.YES) {
saves++
selected = mode
} else version++
} finally {
saving = false
}
}
}
}
val message = error ?: when {
sessionRunning -> R.string.edit_steam_input_running
selected == null && !loading -> R.string.edit_steam_input_unavailable
else -> R.string.edit_steam_input_hint
}
Text(
stringResource(message),
fontSize = 12.sp,
color = if (error == null) colors.onSurfaceVariant else colors.error,
modifier = Modifier.padding(start = 4.dp),
)
}
}
private class LoadedPosition(val value: LogoPosition.Value?)
@Composable
@@ -82,7 +82,6 @@ internal fun AgentEntry(
if (reply.options.isNotEmpty()) AgentChoices(reply.options, answerable, onSent)
}
}
is Entry.Notice -> Text(entry.text, color = colors.error, modifier = Modifier.padding(horizontal = 4.dp))
is Entry.Thought -> AgentThought(entry.text, live = false)
is Entry.Used -> if (entry.tool == "TodoWrite") AgentTodos(entry.input) else AgentToolCall(entry, running, children)
is Entry.Result -> Unit
@@ -567,8 +567,7 @@ private fun labStage(lab: com.droiddeck.launcher.agent.LabProgress) = when (lab.
else -> stringResource(R.string.agent_lab_stage_starting)
}
private fun hasActivity() = AgentHost.lab != null || AgentHost.queue.isNotEmpty() || currentTodo() != null ||
com.droiddeck.launcher.agent.AgentSetup.problems.isNotEmpty()
private fun hasActivity() = AgentHost.lab != null || AgentHost.queue.isNotEmpty() || currentTodo() != null
/** The todo item in progress and how many are done, while the agent works through a list. */
private fun currentTodo(): String? {
@@ -595,11 +594,6 @@ private fun AgentActivity(labOpen: Boolean, onLab: () -> Unit) {
Text(todo, fontSize = 12.5.sp, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.widthIn(max = 220.dp))
}
}
val problems = com.droiddeck.launcher.agent.AgentSetup.problems
if (problems.isNotEmpty()) AgentChip(warn = true, tag = "agent-tools-missing") {
Text(stringResource(R.string.agent_tools_missing, problems.joinToString(", ")), fontSize = 12.5.sp, color = AttentionAmber,
maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.widthIn(max = 260.dp))
}
for (queued in AgentHost.queue) AgentChip(warn = true) {
Text(stringResource(R.string.agent_queued, queued.text), fontSize = 12.5.sp, color = AttentionAmber, maxLines = 1,
overflow = TextOverflow.Ellipsis, modifier = Modifier.widthIn(max = 180.dp))
@@ -911,7 +911,15 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
val ready = current != null && !state.saving
val launcher = game.library == com.droiddeck.launcher.frontend.Library.EPIC_LAUNCHER
fun save(change: (android.content.Context) -> com.droiddeck.launcher.core.GameEnvironment.Config?) = state.save(change)
var controlsProfile by remember(scope) { mutableStateOf(com.droiddeck.launcher.input.GameInputControls.profile(appContext, scope)) }
val controlsKey = "game-settings-controls"
val key = GAME_SETTINGS_MENU
val controlsMenuOpen = host.open == key || host.open == controlsKey
val inputLibrary by androidx.compose.runtime.produceState<com.droiddeck.launcher.input.InputLibrary?>(null, controlsMenuOpen) {
value = if (controlsMenuOpen) kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
com.droiddeck.launcher.input.InputLibraries.read(appContext)
} else null
}
val fexKey = "game-settings-fex"
val syncKey = "game-settings-sync"
val syncLabels = mapOf(
@@ -978,10 +986,13 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
trailing = { Text("›", fontSize = 16.sp, color = colors.onSurfaceVariant) },
) { host.open = syncKey }
}
MenuItem(stringResource(R.string.community_game_controls), checked = false,
detail = inputLibrary?.profiles?.firstOrNull { it.id == controlsProfile }?.name ?: useDefault) { host.open = controlsKey }
MenuItem(stringResource(R.string.game_settings_default), checked = false, enabled = ready,
detail = stringResource(R.string.game_settings_default_detail)) {
save {
val failure = runCatching { com.droiddeck.launcher.session.GameProfileManager.reset(it, scope) }.exceptionOrNull()
if (failure == null) controlsProfile = null
com.droiddeck.launcher.stores.StoresState.post {
android.widget.Toast.makeText(
it,
@@ -993,6 +1004,20 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
}
}
}
AnchoredMenu(host.open == controlsKey, onDismiss = { if (host.open == controlsKey) host.open = null },
title = stringResource(R.string.community_game_controls)) { first ->
MenuItem(useDefault, checked = controlsProfile == null, focusRequester = first) {
runCatching { com.droiddeck.launcher.input.GameInputControls.set(appContext, scope, null) }
.onSuccess { controlsProfile = null; host.open = key }
.onFailure { android.widget.Toast.makeText(appContext, it.message, android.widget.Toast.LENGTH_SHORT).show() }
}
for (profile in inputLibrary?.profiles.orEmpty()) MenuItem(profile.name, checked = profile.id == controlsProfile,
detail = stringResource(R.string.community_game_controls_hint)) {
runCatching { com.droiddeck.launcher.input.GameInputControls.set(appContext, scope, profile.id) }
.onSuccess { controlsProfile = profile.id; host.open = key }
.onFailure { android.widget.Toast.makeText(appContext, it.message, android.widget.Toast.LENGTH_SHORT).show() }
}
}
AnchoredMenu(host.open == resKey, onDismiss = { if (host.open == resKey) host.open = null }, title = stringResource(R.string.game_res_title)) { first ->
MenuItem(matchScreen, checked = resolution == null, enabled = ready, focusRequester = first) { pickResolution(null) }
com.droiddeck.launcher.core.GameResolution.scales.forEach { scale ->
@@ -835,7 +835,6 @@ private fun LaunchTab(game: Library.SteamGame, s: FrontEndState, a: FrontEndActi
LaunchSettings(s, a, host, game, hopRail ?: GameRef.key(game))
if (canEditSteamLaunchOptions(game, s.shortcutPicker)) {
SteamLaunchOptionsPanel(game.appId)
SteamInputOverridePanel(game.appId)
}
val folder = game.gameFiles
if (game.library == Library.ADDED && game.source == Library.ADDED && !s.shortcutPicker && folder != null) ShortcutFields(game, folder)
@@ -0,0 +1,202 @@
package com.droiddeck.launcher.ui
import android.content.Intent
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.Image
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@Composable
internal fun InputCommunityPage(library: InputLibrary, profile: String, initialRole: InputRole, initialEntries: List<CommunityControls.Entry>? = null,
onInstalled: (InputLibrary) -> Unit) {
val context = LocalContext.current
var targetProfile by remember { mutableStateOf(profile) }
val scope = rememberCoroutineScope()
val host = rememberMenuHost()
var role by remember { mutableStateOf(initialRole.takeUnless { it == InputRole.PHYSICAL } ?: InputRole.PRIMARY) }
var sources by remember { mutableStateOf(ControlSources.read(context)) }
var selectedSource by remember { mutableStateOf(sources.first()) }
var addingSource by remember { mutableStateOf(false) }
var sourceUrl by remember { mutableStateOf("") }
var entries by remember { mutableStateOf(initialEntries ?: CommunityControls.bundled(context)) }
var busy by remember { mutableStateOf(false) }
var status by remember { mutableStateOf<String?>(null) }
var pending by remember { mutableStateOf<CommunityControls.Pack?>(null) }
var exporting by remember { mutableStateOf<ByteArray?>(null) }
var search by remember { mutableStateOf("") }
val filtered = remember(entries, search, role) { entries.filter { it.screen.supports(role) &&
(search.isBlank() || "${it.name} ${it.author} ${it.game}".contains(search, ignoreCase = true)) } }
var page by remember(selectedSource.id, entries, search, role) { mutableIntStateOf(0) }
val pageCount = ((filtered.size + 11) / 12).coerceAtLeast(1)
val pageEntries = filtered.drop(page * 12).take(12)
val previews = remember(selectedSource.id, pageEntries) { mutableStateMapOf<String, android.graphics.Bitmap>() }
LaunchedEffect(previews, pageEntries) {
for (entry in pageEntries) {
if (entry.preview == null || entry.key in previews) continue
var decoded: android.graphics.Bitmap? = null
try {
withContext(Dispatchers.IO) { decoded = runCatching { CommunityControls.preview(context, entry) }.getOrNull() }
decoded?.let { previews[entry.key] = it; decoded = null }
} finally { decoded?.recycle() }
}
}
fun task(action: suspend () -> Unit) {
if (busy) return
busy = true
status = null
scope.launch {
try { action() } catch (e: kotlinx.coroutines.CancellationException) { throw e }
catch (e: Exception) { status = e.message ?: context.getString(R.string.community_failed) }
finally { busy = false }
}
}
fun load(source: ControlSources.Source) {
task {
val remote = withContext(Dispatchers.IO) { CommunityControls.fetchCatalog(source) }
val bundled = if (source.id == ControlSources.DROIDDECK.id) CommunityControls.bundled(context) else emptyList()
entries = (remote + bundled).distinctBy { it.path }
status = context.getString(R.string.community_refreshed)
}
}
val importer = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
if (uri != null) task {
pending = withContext(Dispatchers.IO) {
val bytes = requireNotNull(context.contentResolver.openInputStream(uri)).use { CommunityControls.readLimited(it, 32 * 1024 * 1024) }
CommunityControls.importFile(context, bytes, requireNotNull(library.layout(targetProfile, role)),
library.preset(library.profile(targetProfile).binding(role)))
}
}
}
val exporter = rememberLauncherForActivityResult(ActivityResultContracts.CreateDocument("application/zip")) { uri ->
val bytes = exporting
exporting = null
if (uri != null && bytes != null) task {
withContext(Dispatchers.IO) {
requireNotNull(context.contentResolver.openOutputStream(uri, "wt")).use { it.write(bytes) }
}
status = context.getString(R.string.community_exported)
}
}
InputHint(stringResource(R.string.community_description))
SettingsGroup(stringResource(R.string.community_sources)) {
ChoiceRow(host, "community-source", stringResource(R.string.community_source), null,
sources.map { it.id to it.name }, selectedSource.id) { id ->
if (!busy) {
selectedSource = sources.first { it.id == id }
entries = if (id == ControlSources.DROIDDECK.id) CommunityControls.bundled(context) else emptyList()
load(selectedSource)
}
}
PadTextButton(enabled = !busy, onClick = { sourceUrl = ""; addingSource = true }, modifier = Modifier.padding(8.dp).testTag("community-add-source")) {
Text(stringResource(R.string.community_add_source))
}
if (!selectedSource.builtIn) PadTextButton(enabled = !busy, onClick = { task {
ControlSources.remove(context, selectedSource)
sources = ControlSources.read(context)
selectedSource = sources.first()
entries = CommunityControls.bundled(context)
} }, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.community_remove_source)) }
}
SettingsGroup(stringResource(R.string.community_target)) {
ChoiceRow(host, "community-profile", stringResource(R.string.input_profile), null,
library.profiles.map { it.id to it.name }, targetProfile) { if (!busy) targetProfile = it }
ChoiceRow(host, "community-screen", stringResource(R.string.community_screen), null,
listOf(InputRole.PRIMARY, InputRole.SECONDARY).map { it to roleLabel(it) }, role) { if (!busy) role = it }
}
SettingsGroup(stringResource(R.string.community_title)) {
OutlinedTextField(search, { search = it.take(160) }, singleLine = true,
label = { Text(stringResource(R.string.community_search)) }, modifier = Modifier.fillMaxWidth().padding(12.dp))
for (entry in pageEntries) {
InputNavigationRow(entry.name, listOf(entry.author, entry.game, entry.license).filter { it.isNotEmpty() }.joinToString(" · "),
Modifier.testTag("community-pack-${entry.path}"), leading = {
previews[entry.key]?.let { Image(it.asImageBitmap(), null, Modifier.width(112.dp).height(76.dp).testTag("community-preview-${entry.path}"), contentScale = ContentScale.Fit) }
}) {
task { pending = withContext(Dispatchers.IO) { CommunityControls.download(context, entry, library.layout(targetProfile, role),
library.preset(library.profile(targetProfile).binding(role))) } }
}
}
if (pageCount > 1) Row(Modifier.fillMaxWidth().padding(8.dp), horizontalArrangement = Arrangement.SpaceBetween) {
PadTextButton(enabled = page > 0 && !busy, onClick = { page-- }, modifier = Modifier.testTag("community-previous")) { Text(stringResource(R.string.community_previous)) }
Text(stringResource(R.string.community_page, page + 1, pageCount), Modifier.align(androidx.compose.ui.Alignment.CenterVertically))
PadTextButton(enabled = page + 1 < pageCount && !busy, onClick = { page++ }, modifier = Modifier.testTag("community-next")) { Text(stringResource(R.string.community_next)) }
}
if (filtered.isEmpty())
InputHint(stringResource(R.string.community_empty))
PadTextButton(enabled = !busy, onClick = { load(selectedSource) }, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.community_refresh)) }
PadTextButton(enabled = !busy, onClick = { importer.launch(arrayOf("application/zip", "application/octet-stream", "application/x-zip-compressed")) },
modifier = Modifier.padding(8.dp).testTag("community-import")) { Text(stringResource(R.string.community_import)) }
}
SettingsGroup(stringResource(R.string.community_share)) {
InputHint(stringResource(R.string.community_submit_hint))
val layout = library.layout(targetProfile, role)
if (layout?.editable == true) PadTextButton(enabled = !busy, onClick = { task {
exporting = withContext(Dispatchers.IO) { CommunityControls.export(context, layout, library.preset(library.profile(targetProfile).binding(role))) }
exporter.launch(layout.name.replace(Regex("[^A-Za-z0-9_-]"), "_").take(60) + ".ddcontrols.zip")
} }, modifier = Modifier.padding(8.dp).testTag("community-export")) { Text(stringResource(R.string.community_export)) }
if (layout?.editable == true && layout.elements.any { it.image.isNotEmpty() || it.stickImage.isNotEmpty() })
PadTextButton(enabled = !busy, onClick = { task {
exporting = withContext(Dispatchers.IO) { ArmsControlSkins.export(context, layout,
library.preset(library.profile(targetProfile).binding(role))) }
exporter.launch(layout.name.replace(Regex("[^A-Za-z0-9_-]"), "_").take(60) + ".skin.zip")
} }, modifier = Modifier.padding(8.dp).testTag("community-export-skin")) { Text(stringResource(R.string.community_export_skin)) }
PadTextButton(onClick = {
runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(selectedSource.submit ?: selectedSource.manifest))) }
.onFailure { status = context.getString(R.string.community_failed) }
}, modifier = Modifier.padding(8.dp)) { Text(stringResource(R.string.community_submit)) }
}
if (busy) LinearProgressIndicator(Modifier.fillMaxWidth().padding(12.dp))
status?.let { InputHint(it) }
if (addingSource) AlertDialog(onDismissRequest = { if (!busy) addingSource = false },
title = { Text(stringResource(R.string.community_add_source)) }, text = { Column {
Text(stringResource(R.string.community_source_hint))
OutlinedTextField(sourceUrl, { sourceUrl = it.take(2048) }, singleLine = true,
label = { Text(stringResource(R.string.community_source_url)) }, modifier = Modifier.testTag("community-source-url"))
status?.let { Text(it) }
} }, confirmButton = {
PadTextButton(enabled = !busy && sourceUrl.isNotBlank(), onClick = { task {
val (source, remote) = withContext(Dispatchers.IO) {
var failure: Exception? = null
var found: Pair<ControlSources.Source, List<CommunityControls.Entry>>? = null
for (candidate in ControlSources.candidates(sourceUrl)) {
try { found = candidate to CommunityControls.fetchCatalog(candidate); break }
catch (e: Exception) { failure = e }
}
found ?: throw (failure ?: IllegalArgumentException(context.getString(R.string.community_failed)))
}
ControlSources.add(context, source)
sources = ControlSources.read(context)
selectedSource = sources.first { it.id == source.id }
entries = remote
addingSource = false
} }) { Text(stringResource(R.string.community_connect)) }
}, dismissButton = { PadTextButton(enabled = !busy, onClick = { addingSource = false }) { Text(stringResource(R.string.common_cancel)) } })
pending?.let { pack ->
AlertDialog(onDismissRequest = { if (!busy) pending = null }, title = { Text(pack.layout.name) },
text = { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
InputLayoutThumbnail(pack.layout, role, pack.images, Modifier.fillMaxWidth().height(180.dp))
Text(stringResource(R.string.community_apply_hint, pack.layout.elements.size, library.profile(targetProfile).name, roleLabel(role)))
} }, confirmButton = {
PadTextButton(enabled = !busy && pack.layout.supports(role), onClick = { task {
val installed = withContext(Dispatchers.IO) { CommunityControls.install(context, pack, targetProfile, role) }
onInstalled(installed)
pending = null
status = context.getString(R.string.community_installed)
} }) { Text(stringResource(R.string.community_apply)) }
}, dismissButton = { PadTextButton(enabled = !busy, onClick = { pending = null }) { Text(stringResource(R.string.common_cancel)) } })
}
}
@@ -36,13 +36,17 @@ internal fun InputLayoutRow(layout: SavedInputLayout, role: InputRole, detail: S
}
@Composable
internal fun InputLayoutThumbnail(layout: SavedInputLayout, role: InputRole) {
AndroidView(factory = { InputLayoutPreviewView(it) }, modifier = Modifier.width(112.dp).height(76.dp).testTag("layout-preview-${layout.id}"),
update = { it.update(layout, role) })
internal fun InputLayoutThumbnail(layout: SavedInputLayout, role: InputRole, images: Map<String, ByteArray> = emptyMap(),
modifier: Modifier = Modifier.width(112.dp).height(76.dp)) {
val bitmaps = remember(images) { images.mapValues { (_, bytes) -> android.graphics.BitmapFactory.decodeByteArray(bytes, 0, bytes.size) } }
key(bitmaps) {
AndroidView(factory = { InputLayoutPreviewView(it, bitmaps.filterValues { it != null }.mapValues { it.value!! }) },
modifier = modifier.testTag("layout-preview-${layout.id}"), update = { it.update(layout, role) })
}
}
internal class InputLayoutPreviewView(context: Context) : View(context) {
private val renderer = InputSurfaceView(context)
internal class InputLayoutPreviewView(context: Context, images: Map<String, android.graphics.Bitmap> = emptyMap()) : View(context) {
private val renderer = InputSurfaceView(context, previewImages = images)
private var sourceHeight = 563
fun update(layout: SavedInputLayout, role: InputRole) {
sourceHeight = if (role == InputRole.PRIMARY) 563 else 870
@@ -33,7 +33,10 @@ internal fun InputQuickSettings(host: MenuHost, desktop: Boolean, onChanged: (In
runCatching { InputLibraries.update(context, change) }.onSuccess { library = it; onChanged(role) }
.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) }
}
val selection = library.selection(desktop)
val game = (context.findActivity() as? com.droiddeck.launcher.SessionActivity)?.inputGameScope()
fun effective(value: InputLibrary) = GameInputControls.resolve(context, value, desktop, game)
val resolved = effective(library)
val selection = resolved.selection(desktop)
val mixed = selection.parts.isNotEmpty()
val active = library.profile(library.activeId(desktop))
val profiles = listOf(InputProfiles.AUTO to stringResource(R.string.input_quick_auto, if (desktop) library.profile(library.desktop).name else library.profile(library.steam).name)) +
@@ -61,7 +64,7 @@ internal fun InputQuickSettings(host: MenuHost, desktop: Boolean, onChanged: (In
if (role == InputRole.PHYSICAL) binding.physical
else !binding.physical && library.layouts.any { it.id == binding.layoutId && it.supports(role) }
}.map { it.id to it.name }
ChoiceRow(host, "input-part-${role.name}", roleLabel(role), null, options, library.activePart(desktop, role).bindings,
ChoiceRow(host, "input-part-${role.name}", roleLabel(role), null, options, resolved.activePart(desktop, role).bindings,
chipModifier = track("input-part-${role.name}")) { id -> update(role) { it.selectPart(desktop, role, id) } }
}
if (mixed) SecondaryButton(stringResource(R.string.input_save_combination)) { naming = true }
@@ -73,7 +76,7 @@ internal fun InputQuickSettings(host: MenuHost, desktop: Boolean, onChanged: (In
var name by remember { mutableStateOf("") }
AlertDialog(onDismissRequest = { naming = false }, title = { Text(stringResource(R.string.input_save_combination)) },
text = { OutlinedTextField(name, { name = it.take(80) }, singleLine = true, label = { Text(stringResource(R.string.input_name)) }) },
confirmButton = { PadTextButton(enabled = name.isNotBlank(), onClick = { update(null) { it.saveSelection(desktop, name) }; naming = false }) { Text(stringResource(R.string.gesture_save_changes)) } },
confirmButton = { PadTextButton(enabled = name.isNotBlank(), onClick = { update(null) { effective(it).saveSelection(desktop, name) }; naming = false }) { Text(stringResource(R.string.gesture_save_changes)) } },
dismissButton = { PadTextButton(onClick = { naming = false }) { Text(stringResource(R.string.common_cancel)) } })
}
failure?.let { message -> AlertDialog(onDismissRequest = { failure = null }, title = { Text(stringResource(R.string.input_save_failed)) },
@@ -65,7 +65,7 @@ private fun InputSettingsPane(onBack: () -> Unit, onChanged: () -> Unit) {
}
}
private enum class InputPage { HOME, PROFILE, SOURCE, LAYOUTS, REUSE }
private enum class InputPage { HOME, PROFILE, SOURCE, LAYOUTS, REUSE, COMMUNITY }
private data class InputBindingEdit(val preset: String, val control: InputControl, val element: InputSurfaceElement? = null, val key: PhysicalInputKey? = null, val click: Boolean = false)
private data class InputNameRequest(val title: Int, val initial: String, val sources: List<Pair<String, String>> = emptyList(),
val source: String = "", val offerSharing: Boolean = false, val save: (String, String, Boolean) -> Unit)
@@ -85,6 +85,7 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
val host = rememberMenuHost()
var library by remember { mutableStateOf(InputLibraries.read(context)) }
var page by remember { mutableStateOf(InputPage.HOME) }
var communityBack by remember { mutableStateOf(InputPage.HOME) }
var bindingsTab by remember { mutableIntStateOf(0) }
var profileId by remember { mutableStateOf(InputProfile.GAME) }
var role by remember { mutableStateOf(InputRole.PHYSICAL) }
@@ -104,12 +105,13 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
var oscMode by remember { mutableStateOf(SessionPrefs.oscMode(context)) }
fun update(change: (InputLibrary) -> InputLibrary): Boolean = runCatching { InputLibraries.update(context, change) }
.onSuccess { library = it; onChanged() }.onFailure { error = it.message ?: context.getString(R.string.input_save_failed) }.isSuccess
fun go(next: InputPage) { page = next; host.open = null }
fun go(next: InputPage) { if (next == InputPage.COMMUNITY) communityBack = page; page = next; host.open = null }
fun back() {
when {
edit != null -> edit = null
page == InputPage.HOME -> onBack()
page == InputPage.PROFILE -> go(InputPage.HOME)
page == InputPage.COMMUNITY -> go(communityBack)
page == InputPage.SOURCE -> go(InputPage.PROFILE)
else -> go(InputPage.SOURCE)
}
@@ -191,6 +193,7 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
InputPage.SOURCE -> roleLabel(role)
InputPage.LAYOUTS -> stringResource(R.string.input_saved_layouts)
InputPage.REUSE -> stringResource(R.string.input_use_settings_from)
InputPage.COMMUNITY -> stringResource(R.string.community_title)
}, eyebrow = when (page) {
InputPage.SOURCE -> profile.name
InputPage.LAYOUTS, InputPage.REUSE -> "${profile.name} · ${roleLabel(role)}"
@@ -198,7 +201,12 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
},
onBack = ::back, showBack = !(embedded && page == InputPage.HOME), compactLayout = true) {
when (page) {
InputPage.COMMUNITY -> InputCommunityPage(library, profileId, role) { installed -> library = installed; onChanged() }
InputPage.HOME -> {
SettingsGroup(stringResource(R.string.community_title)) {
InputNavigationRow(stringResource(R.string.community_title), stringResource(R.string.community_home_hint),
Modifier.testTag("input-community")) { go(InputPage.COMMUNITY) }
}
SettingsGroup(stringResource(R.string.input_default_profiles)) {
ChoiceRow(host, "auto-desktop", stringResource(R.string.input_desktop_mode), null,
library.profiles.map { it.id to it.name }, library.desktop) { id -> update { it.copy(desktop = id) } }
@@ -284,6 +292,7 @@ private fun InputSettingsContent(onBack: () -> Unit, onChanged: () -> Unit, embe
for (button in layout.quickButtons) ToggleRow(host, "quick-${button.name.lowercase()}", stringResource(quickButtonLabel(button)), null,
button !in layout.style.hidden) { on -> update { it.withLayout(layout.withQuickButton(button, on)) } }
}
InputNavigationRow(stringResource(R.string.community_title), stringResource(R.string.community_home_hint)) { go(InputPage.COMMUNITY) }
if (role == InputRole.SECONDARY) InputHint(stringResource(R.string.input_second_screen_enable))
}
SettingsGroup(stringResource(R.string.input_assign_actions)) {
@@ -449,7 +458,7 @@ private fun InputControlGrid(preset: SavedInputBindings, available: List<InputCo
}
@Composable
private fun InputNavigationRow(title: String, detail: String?, modifier: Modifier = Modifier, leading: (@Composable () -> Unit)? = null, onClick: () -> Unit) {
internal fun InputNavigationRow(title: String, detail: String?, modifier: Modifier = Modifier, leading: (@Composable () -> Unit)? = null, onClick: () -> Unit) {
Row(modifier.fillMaxWidth().focusRow(RoundedCornerShape(0.dp), onClick = onClick).heightIn(min = 64.dp).padding(14.dp),
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
leading?.invoke()
@@ -499,6 +508,6 @@ internal fun roleLabel(role: InputRole) = stringResource(when (role) {
})
@Composable
private fun InputHint(text: String) {
internal fun InputHint(text: String) {
Text(text, Modifier.padding(14.dp), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
}
@@ -51,6 +51,7 @@ class InputSurfaceView(
private val inputRole: InputRole = InputRole.SECONDARY,
private var surfaceStyle: InputSurfaceStyle = InputSurfaceStyle(),
private val haptics: Boolean = inputRole != InputRole.PRIMARY,
private val previewImages: Map<String, android.graphics.Bitmap> = emptyMap(),
) : FrameLayout(context) {
private val content = FrameLayout(context)
private val elementSources = ArrayList<InputSurfaceSource>()
@@ -326,13 +327,7 @@ class InputSurfaceView(
protected fun textColor(lit: Boolean) = if (lit) Color.WHITE else tint?.let { light(it, 210, 0.75f) } ?: TEXT
}
private inner class HoldButton(context: Context, private val element: InputSurfaceElement, private val source: InputSurfaceSource?) : Surface(context) {
private var down = false
private val pointers = HashSet<Int>()
val round get() = element.buttonShape == InputButtonShape.CIRCLE
val gamepad get() = round || element.buttonShape == InputButtonShape.PILL
private val symbol = InputButtonIcons.drawable(context, element.icon)
private val bitmap = InputButtonImages.file(context, element.image)?.let { file ->
private fun imageBitmap(name: String): android.graphics.Bitmap? = previewImages[name] ?: InputButtonImages.file(context, name)?.let { file ->
val size = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeFile(file.path, size)
val options = BitmapFactory.Options().apply {
@@ -341,6 +336,14 @@ class InputSurfaceView(
}
if (file.isFile) BitmapFactory.decodeFile(file.path, options) else null
}
private inner class HoldButton(context: Context, private val element: InputSurfaceElement, private val source: InputSurfaceSource?) : Surface(context) {
private var down = false
private val pointers = HashSet<Int>()
val round get() = element.buttonShape == InputButtonShape.CIRCLE
val gamepad get() = round || element.buttonShape == InputButtonShape.PILL
private val symbol = InputButtonIcons.drawable(context, element.icon)
private val bitmap = imageBitmap(element.image)
private val imageRect = RectF()
override fun onDraw(canvas: Canvas) {
@@ -511,6 +514,17 @@ class InputSurfaceView(
private var knobY = 0f
private val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
private val knob = Paint(Paint.ANTI_ALIAS_FLAG)
private val baseImage = imageBitmap(element.image)
private val stickImage = imageBitmap(element.stickImage)
private val imagePaint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
private val imageBounds = RectF()
private fun drawImage(canvas: Canvas, image: android.graphics.Bitmap, x: Float, y: Float, radius: Float) {
val scale = min(radius * 2 / image.width, radius * 2 / image.height)
imageBounds.set(x - image.width * scale / 2, y - image.height * scale / 2,
x + image.width * scale / 2, y + image.height * scale / 2)
canvas.drawBitmap(image, null, imageBounds, imagePaint)
}
val adaptive get() = adaptive(element)
@@ -534,6 +548,14 @@ class InputSurfaceView(
val cx = if (touching) originX else centreX()
val cy = if (touching) originY else height / 2f
val color = tint
if (baseImage != null || stickImage != null) {
val radius = min(width, height) / 2f - .75f * density
if (baseImage != null) drawImage(canvas, baseImage, cx, cy, radius)
else { ring.color = LINE; ring.strokeWidth = 2 * density; canvas.drawCircle(cx, cy, radius, ring) }
if (stickImage != null) drawImage(canvas, stickImage, cx + knobX, cy + knobY, radius * .46f)
else { knob.color = if (touching) ACCENT else KNOB; canvas.drawCircle(cx + knobX, cy + knobY, radius * .46f, knob) }
return
}
if (classic(element) && color != null) {
val radius = min(width, height) / 2f - 0.75f * density
drawCircle(canvas, cx, cy, radius,
@@ -83,7 +83,6 @@ class ModeSettings(
val forceSsbs: Boolean = false,
val syncBackend: String? = null,
val picturePosition: String? = null,
val integerScaling: Boolean? = null,
val stretch16x9: Boolean? = null,
val steamClientArch: String? = null,
val returnAfterGame: Boolean? = null,
@@ -140,7 +139,6 @@ class ModeSettingsActions(
val onForceSsbs: (Boolean) -> Unit = {},
val onSyncBackend: (String) -> Unit = {},
val onPicturePosition: (String) -> Unit = {},
val onIntegerScaling: (Boolean) -> Unit = {},
val onStretch16x9: (Boolean) -> Unit = {},
val onSteamRepair: () -> Unit = {},
val onSteamClientArch: (String) -> Unit = {},
@@ -244,18 +242,6 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
}
}
SettingsGroup(stringResource(R.string.display_image_scaling)) {
s.integerScaling?.let { enabled ->
ChoiceRow(
host, "integer-scaling",
stringResource(R.string.display_integer_scaling),
stringResource(R.string.display_integer_scaling_hint),
listOf(
false to stringResource(R.string.display_scaling_fit),
true to stringResource(R.string.display_scaling_auto),
),
enabled, onPick = a.onIntegerScaling,
)
}
ChoiceRow(
host, "upscaler", stringResource(R.string.display_filter), null,
SessionPrefs.upscalerChoices(LocalContext.current), s.upscaler,
@@ -306,8 +306,12 @@ class SecondScreenPresentation(
}
}
private fun panelLayout(mode: SecondScreenMode) = com.droiddeck.launcher.input.InputLibraries.read(context)
.panelLayout(SessionState.mode == SessionService.MODE_DESKTOP, mode.panel(context))
private fun panelLayout(mode: SecondScreenMode): com.droiddeck.launcher.input.SavedInputLayout? {
val desktop = SessionState.mode == SessionService.MODE_DESKTOP
return com.droiddeck.launcher.input.GameInputControls.resolve(context,
com.droiddeck.launcher.input.InputLibraries.read(context), desktop, sessionActivity.inputGameScope())
.panelLayout(desktop, mode.panel(context))
}
private fun bar(mode: SecondScreenMode) {
val first = barModel(mode) ?: return
-4
View File
@@ -1195,7 +1195,6 @@
<string name="agent_hint_working">اكتب لإضافة الرسالة التالية إلى الانتظار</string>
<string name="agent_queue">إضافة إلى الانتظار</string>
<string name="agent_queued">التالي: %1$s</string>
<string name="agent_tools_missing">أدوات الوكيل غير مثبتة: %1$s</string>
<string name="agent_unqueue">لا تُرسل</string>
<string name="agent_attach">إرفاق</string>
<string name="agent_remove_attachment">إزالة</string>
@@ -4267,7 +4266,4 @@
<string name="hud_readings_shown">المعروض</string>
<string name="hud_readings_count">%1$d من %2$d</string>
<string name="exit_hint_back">اضغط زر الرجوع مرة أخرى للخروج</string>
<string name="display_integer_scaling">تحجيم صحيح بالأعداد الصحيحة</string>
<string name="display_integer_scaling_hint">يستخدم أكبر معامل تحجيم صحيح يناسب الشاشة. إذا كان المصدر كبيرًا جدًا، يتم تصغير الصورة كاملة لتجنب الاقتصاص. يتم ضبط الدقة بشكل منفصل.</string>
</resources>
@@ -1213,7 +1213,6 @@
<string name="agent_hint_working">Escribe para encolar el siguiente mensaje</string>
<string name="agent_queue">Encolar</string>
<string name="agent_queued">Siguiente: %1$s</string>
<string name="agent_tools_missing">Herramientas del agente sin instalar: %1$s</string>
<string name="agent_unqueue">No enviar</string>
<string name="agent_attach">Adjuntar</string>
<string name="agent_remove_attachment">Quitar</string>
@@ -4118,7 +4117,4 @@
<string name="hud_readings_shown">Mostrados</string>
<string name="hud_readings_count">%1$d de %2$d</string>
<string name="exit_hint_back">Presiona atrás una vez más para salir</string>
<string name="display_integer_scaling">Escalado de píxeles enteros</string>
<string name="display_integer_scaling_hint">Usa el mayor factor de escala entero que quepa. Si la imagen de origen es demasiado grande, ajusta la imagen completa para evitar recortes. La resolución se configura por separado.</string>
</resources>
-4
View File
@@ -1183,7 +1183,6 @@
<string name="agent_hint_working">Въведете, за да наредите следващото съобщение</string>
<string name="agent_queue">В опашката</string>
<string name="agent_queued">Следващо: %1$s</string>
<string name="agent_tools_missing">Инструментите на агента не са инсталирани: %1$s</string>
<string name="agent_unqueue">Не изпращай</string>
<string name="agent_attach">Прикачи</string>
<string name="agent_remove_attachment">Премахни</string>
@@ -4107,7 +4106,4 @@
<string name="hud_readings_shown">Показани</string>
<string name="hud_readings_count">%1$d от %2$d</string>
<string name="exit_hint_back">Натиснете отново „Назад“, за да излезете</string>
<string name="display_integer_scaling">Целочислено мащабиране</string>
<string name="display_integer_scaling_hint">Използва най-големия цял коефициент на мащабиране, който се побира. Ако източникът е твърде голям, побира цялото изображение, за да избегне изрязване. Разделителната способност се настройва отделно.</string>
</resources>
-4
View File
@@ -1189,7 +1189,6 @@
<string name="agent_hint_working">Psaním zařadíte další zprávu do fronty</string>
<string name="agent_queue">Zařadit do fronty</string>
<string name="agent_queued">Další: %1$s</string>
<string name="agent_tools_missing">Nástroje agenta nejsou nainstalované: %1$s</string>
<string name="agent_unqueue">Neposílat</string>
<string name="agent_attach">Přiložit</string>
<string name="agent_remove_attachment">Odebrat</string>
@@ -4187,7 +4186,4 @@
<string name="hud_readings_shown">Zobrazeno</string>
<string name="hud_readings_count">%1$d z %2$d</string>
<string name="exit_hint_back">Stiskněte znovu zpět pro ukončení</string>
<string name="display_integer_scaling">Celočíselné škálování</string>
<string name="display_integer_scaling_hint">Použije největší celočíselný násobek měřítka, který se vejde. Pokud je zdroj příliš velký, přizpůsobí celý obraz, aby nedošlo k oříznutí. Rozlišení se nastavuje samostatně.</string>
</resources>
-4
View File
@@ -1183,7 +1183,6 @@
<string name="agent_hint_working">Skriv for at sætte den næste besked i kø</string>
<string name="agent_queue">Sæt i kø</string>
<string name="agent_queued">Næste: %1$s</string>
<string name="agent_tools_missing">Agentens værktøjer er ikke installeret: %1$s</string>
<string name="agent_unqueue">Send ikke</string>
<string name="agent_attach">Vedhæft</string>
<string name="agent_remove_attachment">Fjern</string>
@@ -4107,7 +4106,4 @@
<string name="hud_readings_shown">Vist</string>
<string name="hud_readings_count">%1$d af %2$d</string>
<string name="exit_hint_back">Tryk tilbage igen for at afslutte</string>
<string name="display_integer_scaling">Heltalsskalering</string>
<string name="display_integer_scaling_hint">Bruger den største hele skaleringsfaktor, der kan være der. Hvis kilden er for stor, tilpasses hele billedet for at undgå beskæring. Opløsningen indstilles separat.</string>
</resources>
-4
View File
@@ -1175,7 +1175,6 @@
<string name="agent_hint_working">Tippen, um die nächste Nachricht einzureihen</string>
<string name="agent_queue">Einreihen</string>
<string name="agent_queued">Als Nächstes: %1$s</string>
<string name="agent_tools_missing">Agent-Werkzeuge nicht installiert: %1$s</string>
<string name="agent_unqueue">Nicht senden</string>
<string name="agent_attach">Anhängen</string>
<string name="agent_remove_attachment">Entfernen</string>
@@ -4107,7 +4106,4 @@
<string name="hud_readings_shown">Angezeigt</string>
<string name="hud_readings_count">%1$d von %2$d</string>
<string name="exit_hint_back">Noch einmal zurück drücken zum Beenden</string>
<string name="display_integer_scaling">Ganzzahlige Skalierung</string>
<string name="display_integer_scaling_hint">Verwendet den größten ganzzahligen Skalierungsfaktor, der passt. Ist die Quelle zu groß, wird das gesamte Bild eingepasst, um Beschneidung zu vermeiden. Die Auflösung wird separat eingestellt.</string>
</resources>
-4
View File
@@ -1183,7 +1183,6 @@
<string name="agent_hint_working">Γράψτε για να προσθέσετε το επόμενο μήνυμα στην ουρά</string>
<string name="agent_queue">Στην ουρά</string>
<string name="agent_queued">Επόμενο: %1$s</string>
<string name="agent_tools_missing">Τα εργαλεία του πράκτορα δεν εγκαταστάθηκαν: %1$s</string>
<string name="agent_unqueue">Να μην σταλεί</string>
<string name="agent_attach">Επισύναψη</string>
<string name="agent_remove_attachment">Αφαίρεση</string>
@@ -4107,7 +4106,4 @@
<string name="hud_readings_shown">Εμφανίζονται</string>
<string name="hud_readings_count">%1$d από %2$d</string>
<string name="exit_hint_back">Πατήστε ξανά πίσω για έξοδο</string>
<string name="display_integer_scaling">Ακέραια κλιμάκωση</string>
<string name="display_integer_scaling_hint">Χρησιμοποιεί τον μεγαλύτερο ακέραιο συντελεστή κλιμάκωσης που χωράει. Αν η πηγή είναι πολύ μεγάλη, προσαρμόζει ολόκληρη την εικόνα ώστε να αποφευχθεί η περικοπή. Η ανάλυση ρυθμίζεται ξεχωριστά.</string>
</resources>
-4
View File
@@ -1186,7 +1186,6 @@
<string name="agent_hint_working">Escribe para encolar el siguiente mensaje</string>
<string name="agent_queue">Encolar</string>
<string name="agent_queued">Siguiente: %1$s</string>
<string name="agent_tools_missing">Herramientas del agente sin instalar: %1$s</string>
<string name="agent_unqueue">No enviar</string>
<string name="agent_attach">Adjuntar</string>
<string name="agent_remove_attachment">Quitar</string>
@@ -4147,7 +4146,4 @@
<string name="hud_readings_shown">Mostrados</string>
<string name="hud_readings_count">%1$d de %2$d</string>
<string name="exit_hint_back">Pulsa atrás una vez más para salir</string>
<string name="display_integer_scaling">Escalado de píxeles enteros</string>
<string name="display_integer_scaling_hint">Usa el mayor factor de escala entero que quepa. Si la imagen de origen es demasiado grande, ajusta la imagen completa para evitar recortes. La resolución se configura por separado.</string>
</resources>
-4
View File
@@ -1183,7 +1183,6 @@
<string name="agent_hint_working">Kirjoita lisätäksesi seuraavan viestin jonoon</string>
<string name="agent_queue">Jono</string>
<string name="agent_queued">Seuraava: %1$s</string>
<string name="agent_tools_missing">Agentin työkaluja ei ole asennettu: %1$s</string>
<string name="agent_unqueue">Älä lähetä</string>
<string name="agent_attach">Liitä</string>
<string name="agent_remove_attachment">Poista</string>
@@ -4107,7 +4106,4 @@
<string name="hud_readings_shown">Näkyvissä</string>
<string name="hud_readings_count">%1$d / %2$d</string>
<string name="exit_hint_back">Paina takaisin vielä kerran poistuaksesi</string>
<string name="display_integer_scaling">Kokonaislukuskaalaus</string>
<string name="display_integer_scaling_hint">Käyttää suurinta mahtuvaa kokonaislukukerrointa. Jos lähdekuva on liian suuri, koko kuva sovitetaan rajauksen välttämiseksi. Tarkkuus määritetään erikseen.</string>
</resources>
-4
View File
@@ -1186,7 +1186,6 @@
<string name="agent_hint_working">Tapez pour mettre le prochain message en attente</string>
<string name="agent_queue">Mettre en attente</string>
<string name="agent_queued">Suivant : %1$s</string>
<string name="agent_tools_missing">Outils de l’agent non installés : %1$s</string>
<string name="agent_unqueue">Ne pas envoyer</string>
<string name="agent_attach">Joindre</string>
<string name="agent_remove_attachment">Supprimer</string>
@@ -4146,7 +4145,4 @@
<string name="hud_readings_shown">Affichés</string>
<string name="hud_readings_count">%1$d sur %2$d</string>
<string name="exit_hint_back">Appuyez à nouveau sur retour pour quitter</string>
<string name="display_integer_scaling">Mise à l’échelle entière</string>
<string name="display_integer_scaling_hint">Utilise le plus grand facteur d’échelle entier possible. Si la source est trop grande, l’image entière est ajustée pour éviter le recadrage. La résolution se règle séparément.</string>
</resources>
-4
View File
@@ -1183,7 +1183,6 @@
<string name="agent_hint_working">अगला संदेश कतार में जोड़ने के लिए टाइप करें</string>
<string name="agent_queue">कतार में जोड़ें</string>
<string name="agent_queued">अगला: %1$s</string>
<string name="agent_tools_missing">एजेंट टूल इंस्टॉल नहीं हुए: %1$s</string>
<string name="agent_unqueue">न भेजें</string>
<string name="agent_attach">संलग्न करें</string>
<string name="agent_remove_attachment">हटाएँ</string>
@@ -4107,7 +4106,4 @@
<string name="hud_readings_shown">दिखाए गए</string>
<string name="hud_readings_count">%2$d में से %1$d</string>
<string name="exit_hint_back">बाहर निकलने के लिए फिर से बैक दबाएँ</string>
<string name="display_integer_scaling">पूर्णांक स्केलिंग</string>
<string name="display_integer_scaling_hint">फिट होने वाले सबसे बड़े पूर्णांक स्केल का उपयोग करता है। स्रोत बहुत बड़ा होने पर काटने से बचाने के लिए पूरी छवि को फिट करता है। रिज़ॉल्यूशन अलग से सेट किया जाता है।</string>
</resources>
-4
View File
@@ -1183,7 +1183,6 @@
<string name="agent_hint_working">Gépelj a következő üzenet sorba állításához</string>
<string name="agent_queue">Sorba állítás</string>
<string name="agent_queued">Következő: %1$s</string>
<string name="agent_tools_missing">Az ügynök eszközei nincsenek telepítve: %1$s</string>
<string name="agent_unqueue">Ne küldd el</string>
<string name="agent_attach">Csatolás</string>
<string name="agent_remove_attachment">Eltávolítás</string>
@@ -4107,7 +4106,4 @@
<string name="hud_readings_shown">Megjelenítve</string>
<string name="hud_readings_count">%1$d / %2$d</string>
<string name="exit_hint_back">Nyomd meg még egyszer a visszát a kilépéshez</string>
<string name="display_integer_scaling">Egész számú méretezés</string>
<string name="display_integer_scaling_hint">A legnagyobb elférő egész számú méretezési tényezőt használja. Ha a forrás túl nagy, a teljes képet hozzáigazítja a levágás elkerüléséhez. A felbontás külön állítható.</string>
</resources>
-4
View File
@@ -1180,7 +1180,6 @@
<string name="agent_hint_working">Ketik untuk mengantrekan pesan berikutnya</string>
<string name="agent_queue">Antrekan</string>
<string name="agent_queued">Berikutnya: %1$s</string>
<string name="agent_tools_missing">Alat agen tidak terpasang: %1$s</string>
<string name="agent_unqueue">Jangan kirim</string>
<string name="agent_attach">Lampirkan</string>
<string name="agent_remove_attachment">Hapus</string>
@@ -4077,7 +4076,4 @@
<string name="hud_readings_shown">Ditampilkan</string>
<string name="hud_readings_count">%1$d dari %2$d</string>
<string name="exit_hint_back">Tekan kembali sekali lagi untuk keluar</string>
<string name="display_integer_scaling">Penskalaan bilangan bulat</string>
<string name="display_integer_scaling_hint">Menggunakan faktor skala bilangan bulat terbesar yang muat. Jika sumber terlalu besar, seluruh gambar disesuaikan agar tidak terpotong. Resolusi diatur secara terpisah.</string>
</resources>
-4
View File
@@ -1178,7 +1178,6 @@
<string name="agent_hint_working">Digita per mettere in coda il messaggio successivo</string>
<string name="agent_queue">Metti in coda</string>
<string name="agent_queued">Prossimo: %1$s</string>
<string name="agent_tools_missing">Strumenti dell’agente non installati: %1$s</string>
<string name="agent_unqueue">Non inviare</string>
<string name="agent_attach">Allega</string>
<string name="agent_remove_attachment">Rimuovi</string>
@@ -4146,7 +4145,4 @@
<string name="hud_readings_shown">Mostrati</string>
<string name="hud_readings_count">%1$d di %2$d</string>
<string name="exit_hint_back">Premi di nuovo indietro per uscire</string>
<string name="display_integer_scaling">Ridimensionamento intero</string>
<string name="display_integer_scaling_hint">Usa il più grande fattore di scala intero che entra nello schermo. Se la sorgente è troppo grande, adatta l’intera immagine per evitare ritagli. La risoluzione si configura separatamente.</string>
</resources>
-4
View File
@@ -1180,7 +1180,6 @@
<string name="agent_hint_working">入力すると次のメッセージをキューに追加できます</string>
<string name="agent_queue">キューに追加</string>
<string name="agent_queued">次: %1$s</string>
<string name="agent_tools_missing">エージェントのツールが未インストール: %1$s</string>
<string name="agent_unqueue">送信しない</string>
<string name="agent_attach">添付</string>
<string name="agent_remove_attachment">削除</string>
@@ -4077,7 +4076,4 @@
<string name="hud_readings_shown">表示中</string>
<string name="hud_readings_count">%2$d 中 %1$d</string>
<string name="exit_hint_back">もう一度戻るを押すと終了します</string>
<string name="display_integer_scaling">整数スケーリング</string>
<string name="display_integer_scaling_hint">収まる最大の整数倍率を使用します。元の画像が大きすぎる場合は、切り抜きを避けるため画像全体を収めます。解像度は別途設定します。</string>
</resources>
-4
View File
@@ -1180,7 +1180,6 @@
<string name="agent_hint_working">입력하면 다음 메시지가 대기열에 추가됩니다</string>
<string name="agent_queue">대기열에 추가</string>
<string name="agent_queued">다음: %1$s</string>
<string name="agent_tools_missing">에이전트 도구가 설치되지 않음: %1$s</string>
<string name="agent_unqueue">보내지 않기</string>
<string name="agent_attach">첨부</string>
<string name="agent_remove_attachment">제거</string>
@@ -4077,7 +4076,4 @@
<string name="hud_readings_shown">표시됨</string>
<string name="hud_readings_count">%2$d 중 %1$d</string>
<string name="exit_hint_back">한 번 더 뒤로를 누르면 종료됩니다</string>
<string name="display_integer_scaling">정수 배율 조정</string>
<string name="display_integer_scaling_hint">화면에 맞는 가장 큰 정수 배율을 사용합니다. 원본이 너무 크면 잘림을 방지하기 위해 전체 이미지를 맞춥니다. 해상도는 별도로 설정합니다.</string>
</resources>
-4
View File
@@ -1180,7 +1180,6 @@
<string name="agent_hint_working">Taip untuk membariskan mesej seterusnya</string>
<string name="agent_queue">Baris gilir</string>
<string name="agent_queued">Seterusnya: %1$s</string>
<string name="agent_tools_missing">Alat ejen tidak dipasang: %1$s</string>
<string name="agent_unqueue">Jangan hantar</string>
<string name="agent_attach">Lampirkan</string>
<string name="agent_remove_attachment">Alih keluar</string>
@@ -4077,7 +4076,4 @@
<string name="hud_readings_shown">Dipaparkan</string>
<string name="hud_readings_count">%1$d daripada %2$d</string>
<string name="exit_hint_back">Tekan kembali sekali lagi untuk keluar</string>
<string name="display_integer_scaling">Penskalaan integer</string>
<string name="display_integer_scaling_hint">Menggunakan faktor skala integer terbesar yang muat. Jika sumber terlalu besar, keseluruhan imej disesuaikan untuk mengelakkan pemotongan. Resolusi ditetapkan secara berasingan.</string>
</resources>
-4
View File
@@ -1183,7 +1183,6 @@
<string name="agent_hint_working">Skriv for å legge neste melding i kø</string>
<string name="agent_queue">Legg i kø</string>
<string name="agent_queued">Neste: %1$s</string>
<string name="agent_tools_missing">Agentverktøy er ikke installert: %1$s</string>
<string name="agent_unqueue">Ikke send</string>
<string name="agent_attach">Legg ved</string>
<string name="agent_remove_attachment">Fjern</string>
@@ -4107,7 +4106,4 @@
<string name="hud_readings_shown">Vist</string>
<string name="hud_readings_count">%1$d av %2$d</string>
<string name="exit_hint_back">Trykk tilbake én gang til for å avslutte</string>
<string name="display_integer_scaling">Heltallsskalering</string>
<string name="display_integer_scaling_hint">Bruker den største hele skaleringsfaktoren som får plass. Hvis kilden er for stor, tilpasses hele bildet for å unngå beskjæring. Oppløsningen stilles inn separat.</string>
</resources>
-4
View File
@@ -1183,7 +1183,6 @@
<string name="agent_hint_working">Typ om het volgende bericht in de wachtrij te zetten</string>
<string name="agent_queue">In wachtrij</string>
<string name="agent_queued">Volgende: %1$s</string>
<string name="agent_tools_missing">Agenttools niet geïnstalleerd: %1$s</string>
<string name="agent_unqueue">Niet verzenden</string>
<string name="agent_attach">Bijvoegen</string>
<string name="agent_remove_attachment">Verwijderen</string>
@@ -4107,7 +4106,4 @@
<string name="hud_readings_shown">Getoond</string>
<string name="hud_readings_count">%1$d van %2$d</string>
<string name="exit_hint_back">Druk nog één keer op terug om af te sluiten</string>
<string name="display_integer_scaling">Gehele-getallenschaal</string>
<string name="display_integer_scaling_hint">Gebruikt de grootste gehele schaalfactor die past. Als de bron te groot is, wordt de volledige afbeelding passend gemaakt om bijsnijden te voorkomen. De resolutie wordt apart ingesteld.</string>
</resources>
-4
View File
@@ -1189,7 +1189,6 @@
<string name="agent_hint_working">Wpisz, aby zakolejkować następną wiadomość</string>
<string name="agent_queue">Zakolejkuj</string>
<string name="agent_queued">Następna: %1$s</string>
<string name="agent_tools_missing">Narzędzia agenta nie są zainstalowane: %1$s</string>
<string name="agent_unqueue">Nie wysyłaj</string>
<string name="agent_attach">Załącz</string>
<string name="agent_remove_attachment">Usuń</string>
@@ -4187,7 +4186,4 @@
<string name="hud_readings_shown">Pokazane</string>
<string name="hud_readings_count">%1$d z %2$d</string>
<string name="exit_hint_back">Naciśnij wstecz jeszcze raz, aby wyjść</string>
<string name="display_integer_scaling">Skalowanie całkowite</string>
<string name="display_integer_scaling_hint">Używa największego całkowitego współczynnika skalowania, który się mieści. Jeśli źródło jest zbyt duże, dopasowuje cały obraz, aby uniknąć przycinania. Rozdzielczość ustawia się osobno.</string>
</resources>
@@ -1178,7 +1178,6 @@
<string name="agent_hint_working">Escreva para pôr a mensagem seguinte na fila</string>
<string name="agent_queue">Pôr na fila</string>
<string name="agent_queued">Seguinte: %1$s</string>
<string name="agent_tools_missing">Ferramentas do agente não instaladas: %1$s</string>
<string name="agent_unqueue">Não enviar</string>
<string name="agent_attach">Anexar</string>
<string name="agent_remove_attachment">Remover</string>
@@ -4146,7 +4145,4 @@
<string name="hud_readings_shown">Mostrados</string>
<string name="hud_readings_count">%1$d de %2$d</string>
<string name="exit_hint_back">Prima novamente o botão Voltar para sair</string>
<string name="display_integer_scaling">Escala por números inteiros</string>
<string name="display_integer_scaling_hint">Utiliza o maior fator de escala inteiro que couber. Se a imagem de origem for demasiado grande, ajusta a imagem completa para evitar cortes. A resolução é configurada separadamente.</string>
</resources>
-4
View File
@@ -1185,7 +1185,6 @@
<string name="agent_hint_working">Digite para enfileirar a próxima mensagem</string>
<string name="agent_queue">Enfileirar</string>
<string name="agent_queued">Próxima: %1$s</string>
<string name="agent_tools_missing">Ferramentas do agente não instaladas: %1$s</string>
<string name="agent_unqueue">Não enviar</string>
<string name="agent_attach">Anexar</string>
<string name="agent_remove_attachment">Remover</string>
@@ -4154,7 +4153,4 @@
<string name="hud_readings_shown">Exibidos</string>
<string name="hud_readings_count">%1$d de %2$d</string>
<string name="exit_hint_back">Pressione o botão Voltar novamente para sair</string>
<string name="display_integer_scaling">Escala por números inteiros</string>
<string name="display_integer_scaling_hint">Usa o maior fator de escala inteiro que couber. Se a imagem de origem for grande demais, ajusta a imagem completa para evitar cortes. A resolução é configurada separadamente.</string>
</resources>
-4
View File
@@ -1186,7 +1186,6 @@
<string name="agent_hint_working">Scrie pentru a pune următorul mesaj în coadă</string>
<string name="agent_queue">Pune în coadă</string>
<string name="agent_queued">Următorul: %1$s</string>
<string name="agent_tools_missing">Instrumentele agentului nu sunt instalate: %1$s</string>
<string name="agent_unqueue">Nu trimite</string>
<string name="agent_attach">Atașează</string>
<string name="agent_remove_attachment">Elimină</string>
@@ -4147,7 +4146,4 @@
<string name="hud_readings_shown">Afișate</string>
<string name="hud_readings_count">%1$d din %2$d</string>
<string name="exit_hint_back">Apasă din nou înapoi pentru a ieși</string>
<string name="display_integer_scaling">Scalare cu numere întregi</string>
<string name="display_integer_scaling_hint">Folosește cel mai mare factor întreg de scalare care încape. Dacă sursa este prea mare, adaptează întreaga imagine pentru a evita decuparea. Rezoluția se configurează separat.</string>
</resources>
-4
View File
@@ -1189,7 +1189,6 @@
<string name="agent_hint_working">Введите текст, чтобы поставить следующее сообщение в очередь</string>
<string name="agent_queue">В очередь</string>
<string name="agent_queued">Далее: %1$s</string>
<string name="agent_tools_missing">Инструменты агента не установлены: %1$s</string>
<string name="agent_unqueue">Не отправлять</string>
<string name="agent_attach">Прикрепить</string>
<string name="agent_remove_attachment">Удалить</string>
@@ -4187,7 +4186,4 @@
<string name="hud_readings_shown">Показано</string>
<string name="hud_readings_count">%1$d из %2$d</string>
<string name="exit_hint_back">Нажмите «Назад» ещё раз, чтобы выйти</string>
<string name="display_integer_scaling">Целочисленное масштабирование</string>
<string name="display_integer_scaling_hint">Использует наибольший целочисленный коэффициент масштабирования, который помещается. Если исходное изображение слишком велико, оно уменьшается целиком, чтобы избежать обрезки. Разрешение настраивается отдельно.</string>
</resources>
-4
View File
@@ -1183,7 +1183,6 @@
<string name="agent_hint_working">Skriv för att köa nästa meddelande</string>
<string name="agent_queue">Köa</string>
<string name="agent_queued">Nästa: %1$s</string>
<string name="agent_tools_missing">Agentens verktyg är inte installerade: %1$s</string>
<string name="agent_unqueue">Skicka inte</string>
<string name="agent_attach">Bifoga</string>
<string name="agent_remove_attachment">Ta bort</string>
@@ -4107,7 +4106,4 @@
<string name="hud_readings_shown">Visade</string>
<string name="hud_readings_count">%1$d av %2$d</string>
<string name="exit_hint_back">Tryck tillbaka igen för att avsluta</string>
<string name="display_integer_scaling">Heltalsskalning</string>
<string name="display_integer_scaling_hint">Använder den största hela skalningsfaktorn som får plats. Om källbilden är för stor anpassas hela bilden för att undvika beskärning. Upplösningen ställs in separat.</string>
</resources>
-4
View File
@@ -1180,7 +1180,6 @@
<string name="agent_hint_working">พิมพ์เพื่อเข้าคิวข้อความถัดไป</string>
<string name="agent_queue">เข้าคิว</string>
<string name="agent_queued">ถัดไป: %1$s</string>
<string name="agent_tools_missing">ยังไม่ได้ติดตั้งเครื่องมือของเอเจนต์: %1$s</string>
<string name="agent_unqueue">ไม่ต้องส่ง</string>
<string name="agent_attach">แนบ</string>
<string name="agent_remove_attachment">นำออก</string>
@@ -4077,7 +4076,4 @@
<string name="hud_readings_shown">ที่แสดง</string>
<string name="hud_readings_count">%1$d จาก %2$d</string>
<string name="exit_hint_back">กดกลับอีกครั้งเพื่อออก</string>
<string name="display_integer_scaling">การปรับขนาดจำนวนเต็ม</string>
<string name="display_integer_scaling_hint">ใช้ตัวคูณการปรับขนาดจำนวนเต็มที่ใหญ่ที่สุดที่พอดี หากภาพต้นฉบับใหญ่เกินไป จะปรับภาพทั้งหมดให้พอดีเพื่อหลีกเลี่ยงการตัดภาพ โดยตั้งค่าความละเอียดแยกต่างหาก</string>
</resources>
-4
View File
@@ -1175,7 +1175,6 @@
<string name="agent_hint_working">Sonraki mesajı sıraya almak için yazın</string>
<string name="agent_queue">Sıraya ekle</string>
<string name="agent_queued">Sıradaki: %1$s</string>
<string name="agent_tools_missing">Ajan araçları yüklenmedi: %1$s</string>
<string name="agent_unqueue">Gönderme</string>
<string name="agent_attach">Ekle</string>
<string name="agent_remove_attachment">Kaldır</string>
@@ -4107,7 +4106,4 @@
<string name="hud_readings_shown">Gösterilen</string>
<string name="hud_readings_count">%1$d / %2$d</string>
<string name="exit_hint_back">Çıkmak için bir kez daha geri basın</string>
<string name="display_integer_scaling">Tam sayı ölçeklendirme</string>
<string name="display_integer_scaling_hint">Sığan en büyük tam sayı ölçekleme katsayısını kullanır. Kaynak çok büyükse kırpmayı önlemek için görüntünün tamamını sığdırır. Çözünürlük ayrı ayarlanır.</string>
</resources>
-4
View File
@@ -1189,7 +1189,6 @@
<string name="agent_hint_working">Введіть текст, щоб поставити наступне повідомлення в чергу</string>
<string name="agent_queue">Поставити в чергу</string>
<string name="agent_queued">Далі: %1$s</string>
<string name="agent_tools_missing">Інструменти агента не встановлено: %1$s</string>
<string name="agent_unqueue">Не надсилати</string>
<string name="agent_attach">Прикріпити</string>
<string name="agent_remove_attachment">Видалити</string>
@@ -4187,7 +4186,4 @@
<string name="hud_readings_shown">Показано</string>
<string name="hud_readings_count">%1$d з %2$d</string>
<string name="exit_hint_back">Натисніть «Назад» ще раз, щоб вийти</string>
<string name="display_integer_scaling">Цілочисельне масштабування</string>
<string name="display_integer_scaling_hint">Використовує найбільший цілий коефіцієнт масштабування, який поміщається. Якщо вихідне зображення завелике, воно вміщується повністю без обрізання. Роздільна здатність налаштовується окремо.</string>
</resources>
-4
View File
@@ -1180,7 +1180,6 @@
<string name="agent_hint_working">Nhập để xếp tin nhắn tiếp theo vào hàng đợi</string>
<string name="agent_queue">Xếp hàng</string>
<string name="agent_queued">Tiếp theo: %1$s</string>
<string name="agent_tools_missing">Chưa cài công cụ của tác tử: %1$s</string>
<string name="agent_unqueue">Không gửi</string>
<string name="agent_attach">Đính kèm</string>
<string name="agent_remove_attachment">Xóa</string>
@@ -4077,7 +4076,4 @@
<string name="hud_readings_shown">Đang hiển thị</string>
<string name="hud_readings_count">%1$d trên %2$d</string>
<string name="exit_hint_back">Nhấn lại để thoát</string>
<string name="display_integer_scaling">Tỷ lệ nguyên</string>
<string name="display_integer_scaling_hint">Sử dụng hệ số tỷ lệ nguyên lớn nhất có thể vừa màn hình. Nếu nguồn quá lớn, toàn bộ hình ảnh sẽ được thu vừa để tránh bị cắt. Độ phân giải được thiết lập riêng.</string>
</resources>
@@ -1263,7 +1263,6 @@
<string name="agent_hint_working">输入以排队下一条消息</string>
<string name="agent_queue">排队</string>
<string name="agent_queued">下一条:%1$s</string>
<string name="agent_tools_missing">智能体工具未安装:%1$s</string>
<string name="agent_unqueue">不发送</string>
<string name="agent_attach">添加附件</string>
<string name="agent_remove_attachment">移除</string>
@@ -4077,7 +4076,4 @@
<string name="hud_readings_shown">已显示</string>
<string name="hud_readings_count">%1$d / %2$d</string>
<string name="exit_hint_back">再按一次返回键退出</string>
<string name="display_integer_scaling">整数缩放</string>
<string name="display_integer_scaling_hint">使用能够容纳的最大整数缩放倍数。如果源图像过大,则缩放整张图像以避免裁切。分辨率单独设置。</string>
</resources>
@@ -1179,7 +1179,6 @@
<string name="agent_hint_working">輸入即可排入下一則訊息</string>
<string name="agent_queue">排入</string>
<string name="agent_queued">下一則:%1$s</string>
<string name="agent_tools_missing">智能體工具未安裝:%1$s</string>
<string name="agent_unqueue">不要傳送</string>
<string name="agent_attach">附加</string>
<string name="agent_remove_attachment">移除</string>
@@ -4077,7 +4076,4 @@
<string name="hud_readings_shown">已顯示</string>
<string name="hud_readings_count">%1$d / %2$d</string>
<string name="exit_hint_back">再按一次返回鍵退出</string>
<string name="display_integer_scaling">整數縮放</string>
<string name="display_integer_scaling_hint">使用可容納的最大整數縮放倍數。如果來源圖像太大,便縮放整張圖像以避免裁切。解像度會另外設定。</string>
</resources>
@@ -1179,7 +1179,6 @@
<string name="agent_hint_working">輸入以排入下一則訊息</string>
<string name="agent_queue">排入佇列</string>
<string name="agent_queued">下一則:%1$s</string>
<string name="agent_tools_missing">智慧代理工具未安裝:%1$s</string>
<string name="agent_unqueue">不要傳送</string>
<string name="agent_attach">附加</string>
<string name="agent_remove_attachment">移除</string>
@@ -4077,7 +4076,4 @@
<string name="hud_readings_shown">已顯示</string>
<string name="hud_readings_count">%1$d / %2$d</string>
<string name="exit_hint_back">再按一次返回鍵退出</string>
<string name="display_integer_scaling">整數縮放</string>
<string name="display_integer_scaling_hint">使用可容納的最大整數縮放倍數。如果來源影像太大,會縮放整張影像以避免裁切。解析度會另外設定。</string>
</resources>
@@ -0,0 +1,34 @@
<resources>
<string name="community_title">Community controls</string>
<string name="community_home_hint">Browse, import, and share on-screen controls</string>
<string name="community_description">Discover controls made by the community. Packs include button artwork, layout, and actions. Review a pack before applying it to a profile.</string>
<string name="community_target">Apply to</string>
<string name="community_search">Search name, author, or game</string>
<string name="community_empty">No controls match this screen and search.</string>
<string name="community_refresh">Check for community packs</string>
<string name="community_refreshed">Community catalog updated.</string>
<string name="community_import">Import controls or skin (.zip)</string>
<string name="community_export">Export this layout and actions</string>
<string name="community_share">Share your controls</string>
<string name="community_submit_hint">Export your controls and share the ZIP directly, or submit it through the selected source’s website. Each source manages its own uploads and catalog. GitHub sources require a GitHub account.</string>
<string name="community_submit">Open source submissions</string>
<string name="community_exported">Pack exported. You can share the ZIP directly or attach it to a community submission.</string>
<string name="community_apply_hint">%1$d controls. Apply layout and actions to %2$s · %3$s? This selects a new local copy. Other profiles keep their controls.</string>
<string name="community_apply">Apply controls</string>
<string name="community_installed">Controls installed and selected for this profile.</string>
<string name="community_failed">Could not load or save community controls.</string>
<string name="community_game_controls">On-screen controls profile</string>
<string name="community_game_controls_hint">Use this profile’s screen layouts and actions. Physical controls follow your general settings.</string>
<string name="community_sources">Sources</string>
<string name="community_source">Source</string>
<string name="community_screen">Screen</string>
<string name="community_add_source">Connect another source</string>
<string name="community_remove_source">Remove source</string>
<string name="community_source_url">Repository or catalog URL</string>
<string name="community_source_hint">Enter a public GitHub repository or an HTTPS catalog.json or manifest.json URL. Supports DroidDeck controls packs and ARMSX2 controller skins. Downloads come directly from the source.</string>
<string name="community_connect">Connect</string>
<string name="community_export_skin">Export skin artwork (.zip)</string>
<string name="community_previous">Previous</string>
<string name="community_next">Next</string>
<string name="community_page">Page %1$d of %2$d</string>
</resources>
-14
View File
@@ -1269,7 +1269,6 @@
<string name="agent_no_reply">Ended without a reply</string>
<string name="agent_retry">Retry</string>
<string name="agent_setting_up">Setting up the agent</string>
<string name="agent_waiting_background">Waiting for background work</string>
<string name="agent_rebuild_lab">Rebuild my Lab build %1$s for the installed version of DroidDeck and restart on it.</string>
<string name="agent_tokens">%1$s in · %2$s out</string>
<string name="agent_thinking">Thinking</string>
@@ -1284,7 +1283,6 @@
<string name="agent_hint_working">Type to queue the next message</string>
<string name="agent_queue">Queue</string>
<string name="agent_queued">Next: %1$s</string>
<string name="agent_tools_missing">Agent tools not installed: %1$s</string>
<string name="agent_unqueue">Don\'t send</string>
<string name="agent_attach">Attach</string>
<string name="agent_remove_attachment">Remove</string>
@@ -2660,10 +2658,6 @@
<string name="display_preserve">Keep proportions</string>
<string name="display_stretch">Stretch to display</string>
<string name="display_image_scaling">Image scaling</string>
<string name="display_integer_scaling">Integer scaling</string>
<string name="display_integer_scaling_hint">Uses the largest whole-number scale that fits. If the source is too large, fits the full image to avoid cropping. Resolution is configured separately.</string>
<string name="display_scaling_fit">Fit</string>
<string name="display_scaling_auto">Auto</string>
<string name="display_filter">Scaling filter</string>
<string name="display_filter_hint">Shared by Steam and Desktop.</string>
<string name="display_filter_live">Applies live. Shared by Steam and Desktop.</string>
@@ -2982,14 +2976,6 @@
<string name="edit_launch_options_steam_hint">Shared with Steam\'s Properties: a change in either one shows in both.</string>
<string name="edit_launch_options_not_saved">Could not save the launch options to Steam. Try again.</string>
<string name="edit_launch_options_desktop">Steam may be open in the desktop session. Change the launch options in its Properties, or close the session first.</string>
<string name="edit_steam_input_override">Steam Input</string>
<string name="edit_steam_input_default">Use Steam\'s default</string>
<string name="edit_steam_input_enable">Enable Steam Input</string>
<string name="edit_steam_input_disable">Disable Steam Input</string>
<string name="edit_steam_input_hint">Same as the game\'s Controller setting in Steam Properties.</string>
<string name="edit_steam_input_running">Close the Steam or desktop session before changing this setting.</string>
<string name="edit_steam_input_not_saved">Could not save the Steam Input setting. Close Steam and try again.</string>
<string name="edit_steam_input_unavailable">Could not read this game\'s Steam Input setting.</string>
<string name="edit_artwork">Artwork</string>
<string name="edit_other_exe">Other exe…</string>
<string name="edit_remove">Remove</string>
@@ -117,52 +117,4 @@ class DriverMenusAutoTest {
menus.refreshDrivers()
assertTrue(menus.tpUbwcRestartRequired())
}
private fun menusRecordingRouteChanges(activity: Activity, seen: MutableList<String>) =
DriverMenus(activity, Handler(Looper.getMainLooper())).also {
it.onRouteChanged = { seen += SessionPrefs.linuxDriver(activity) + "|" + SessionPrefs.androidDriver(activity) }
}
@Test fun selectingALinuxDriverReportsTheRouteAfterItIsSaved() {
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
SessionPrefs.setGpuDriverMode(activity, SessionPrefs.GPU_DRIVERS_MIX)
val seen = mutableListOf<String>()
menusRecordingRouteChanges(activity, seen).selectDriver("chosen-linux", linux = true)
assertEquals("chosen-linux", seen.last().substringBefore("|"))
}
@Test fun selectingTheSystemRuntimeReportsTheRouteAfterItIsSaved() {
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
SessionPrefs.setGpuDriverMode(activity, SessionPrefs.GPU_DRIVERS_MIX)
SessionPrefs.setLinuxDriver(activity, "chosen-linux")
val seen = mutableListOf<String>()
menusRecordingRouteChanges(activity, seen).selectDriver("", linux = true)
assertEquals("", seen.last().substringBefore("|"))
}
@Test fun selectingADisplayDriverReportsTheRouteAfterItIsSaved() {
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
SessionPrefs.setGpuDriverMode(activity, SessionPrefs.GPU_DRIVERS_MIX)
val seen = mutableListOf<String>()
menusRecordingRouteChanges(activity, seen).selectDriver("chosen-display", linux = false)
assertEquals("chosen-display", seen.last().substringAfter("|"))
}
@Test fun pickingTheAutoDisplayReportsTheRouteAfterAutoOwnsIt() {
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
SessionPrefs.setGpuDriverMode(activity, SessionPrefs.GPU_DRIVERS_MIX)
SessionPrefs.setLinuxDriver(activity, "chosen-linux")
val seen = mutableListOf<String>()
menusRecordingRouteChanges(activity, seen).selectDriver(TurnipDriver.AUTO, linux = false)
assertEquals("|${QuestExperimental.DRIVER}", seen.last())
}
@Test fun turningAutoOnReportsTheRouteAutoChose() {
val activity = Robolectric.buildActivity(Activity::class.java).setup().get()
SessionPrefs.setGpuDriverMode(activity, SessionPrefs.GPU_DRIVERS_MANUAL)
SessionPrefs.setLinuxDriver(activity, "chosen-linux")
val seen = mutableListOf<String>()
menusRecordingRouteChanges(activity, seen).setMode(true)
assertEquals("|${QuestExperimental.DRIVER}", seen.last())
}
}
@@ -1,117 +0,0 @@
package com.droiddeck.launcher.agent
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
import java.nio.file.Files
class AgentHelpersTest {
@get:Rule val tmp = TemporaryFolder()
@Test fun aSymlinkLeftByAHandMadeSetupIsReplacedNotFollowed() {
val bin = tmp.newFolder("bin")
val old = tmp.newFile("old-droiddeckctl").apply { writeText("old") }
val target = File(bin, "droiddeckctl")
Files.createSymbolicLink(target.toPath(), old.toPath())
AgentSetup.replaceFile("new".byteInputStream(), target)
assertFalse(Files.isSymbolicLink(target.toPath()))
assertEquals("new", target.readText())
assertEquals("old", old.readText())
assertTrue(target.canExecute())
}
@Test fun aDanglingSymlinkIsReplaced() {
val bin = tmp.newFolder("bin")
val target = File(bin, "droiddeckctl")
Files.createSymbolicLink(target.toPath(), File("/no/such/userland/path").toPath())
AgentSetup.replaceFile("new".byteInputStream(), target)
assertEquals("new", target.readText())
assertEquals(listOf("droiddeckctl"), bin.list()!!.toList())
}
@Test fun skillsGoToEveryHarnessAndLeaveTheUsersOwnAlone() {
val root = tmp.newFolder("rootfs")
val mine = File(root, "root/.claude/skills/my-skill/SKILL.md").apply { parentFile!!.mkdirs(); writeText("mine") }
val stale = File(root, "root/.codex/skills/diagnose-game/SKILL.md").apply { parentFile!!.mkdirs(); writeText("old") }
File(stale.parentFile, AgentSetup.SKILL_MARK).writeText("")
val failed = AgentSetup.installSkills(root, mapOf("diagnose-game" to listOf("SKILL.md"))) { "new $it".byteInputStream() }
assertEquals(emptyList<String>(), failed)
for (harness in AgentHarness.all) {
assertEquals("new diagnose-game/SKILL.md", File(root, "${harness.skills}/diagnose-game/SKILL.md").readText())
}
assertEquals("mine", mine.readText())
assertFalse(File(root, "${ClaudeCode.skills}/diagnose-game/SKILL.md").canExecute())
}
@Test fun aSkillTheUserMadeWithTheSameNameIsKept() {
val root = tmp.newFolder("rootfs3")
val own = File(root, "${ClaudeCode.skills}/diagnose-game/SKILL.md").apply { parentFile!!.mkdirs(); writeText("my version") }
AgentSetup.installSkills(root, mapOf("diagnose-game" to listOf("SKILL.md"))) { "new".byteInputStream() }
assertEquals("my version", own.readText())
assertFalse(File(own.parentFile, AgentSetup.SKILL_MARK).exists())
assertEquals("new", File(root, "${Codex.skills}/diagnose-game/SKILL.md").readText())
}
@Test fun aSkillThatFailedPartWayIsRetriedNextTurn() {
val root = tmp.newFolder("rootfs5")
val skills = mapOf("diagnose-game" to listOf("SKILL.md"))
val failed = AgentSetup.installSkills(root, skills) { throw java.io.IOException("asset unreadable") }
assertEquals(AgentHarness.all.size, failed.size)
assertEquals(emptyList<String>(), AgentSetup.installSkills(root, skills) { "new".byteInputStream() })
for (harness in AgentHarness.all) assertEquals("new", File(root, "${harness.skills}/diagnose-game/SKILL.md").readText())
}
@Test fun instructionsBehindAGuestSymlinkAreWrittenWhereItPoints() {
val root = tmp.newFolder("rootfs4")
val dotfile = File(root, "root/dotfiles/CLAUDE.md").apply { parentFile!!.mkdirs(); writeText("my rule\n") }
val link = File(root, ClaudeCode.instructions).apply { parentFile!!.mkdirs() }
Files.createSymbolicLink(link.toPath(), File("/root/dotfiles/CLAUDE.md").toPath())
AgentSetup.installInstructions(root, "rules")
assertTrue(Files.isSymbolicLink(link.toPath()))
assertTrue(dotfile.readText().contains("rules"))
assertTrue(dotfile.readText().endsWith("\nmy rule\n"))
}
@Test fun theRulesGoFirstInAFileThatHasNoBlockYetAndKeepTheUsersOwn() {
val text = AgentSetup.withBlock("# Mine\nAlways answer in French.\n", "rules v1")
assertEquals("${AgentSetup.BLOCK_BEGIN}\nrules v1\n${AgentSetup.BLOCK_END}\n\n# Mine\nAlways answer in French.\n", text)
}
@Test fun onlyTheBlockIsReplacedOnTheNextTurn() {
val first = AgentSetup.withBlock("before\n", "rules v1") + "after\n"
val second = AgentSetup.withBlock(first, "rules v2")
assertEquals(first.replace("rules v1", "rules v2"), second)
assertEquals(second, AgentSetup.withBlock(second, "rules v2"))
}
@Test fun anEmptyOrMissingFileGetsJustTheBlock() {
assertEquals("${AgentSetup.BLOCK_BEGIN}\nrules\n${AgentSetup.BLOCK_END}\n", AgentSetup.withBlock(null, "rules\n"))
assertEquals(AgentSetup.withBlock(null, "rules"), AgentSetup.withBlock(" \n", "rules"))
}
@Test fun everyHarnessGetsTheRules() {
val root = tmp.newFolder("rootfs2")
val claude = File(root, ClaudeCode.instructions).apply { parentFile!!.mkdirs(); writeText("my rule\n") }
assertEquals(emptyList<String>(), AgentSetup.installInstructions(root, "rules"))
for (harness in AgentHarness.all) assertTrue(File(root, harness.instructions).readText().contains("rules"))
assertTrue(claude.readText().endsWith("\nmy rule\n"))
}
}
@@ -1,51 +0,0 @@
package com.droiddeck.launcher.agent
import android.content.ComponentName
import android.content.ContextWrapper
import android.content.Intent
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class AgentHostServiceTest {
private class ServiceContext : ContextWrapper(RuntimeEnvironment.getApplication()) {
var stops = 0
var reject = false
override fun startForegroundService(service: Intent): ComponentName {
if (reject) throw IllegalStateException("start rejected")
return ComponentName(packageName, AgentHostService::class.java.name)
}
override fun stopService(service: Intent): Boolean { stops++; return true }
}
@Test fun setupCompletionKeepsBackgroundWaitUntilItEnds() {
val context = ServiceContext()
AgentHostService.setupStarted(context)
val service = Robolectric.buildService(AgentHostService::class.java).create().get()
service.onStartCommand(Intent(context, AgentHostService::class.java), 0, 1)
assertNull(AgentHostService.waitForBackground(context))
AgentHostService.setupEnded(context)
assertEquals(0, context.stops)
AgentHostService.backgroundDone(context)
assertEquals(1, context.stops)
}
@Test fun rejectedForegroundStartIsReportedAndCanBeRetried() {
val context = ServiceContext()
context.reject = true
assertNotNull(AgentHostService.start(context))
context.reject = false
assertNull(AgentHostService.start(context))
val service = Robolectric.buildService(AgentHostService::class.java).create().get()
service.onStartCommand(Intent(context, AgentHostService::class.java), 0, 1)
AgentHostService.stop(context)
}
}
@@ -80,52 +80,6 @@ class AgentHostTest {
assertTrue(event == null || event.entries.none { it is Entry.Finished })
}
@Test fun claudeTakesItsMessagesOverStdinSoItStaysOpen() {
val command = ClaudeCode.turn("hello there", null, AgentHarness.Options())
assertEquals("stream-json", command[command.indexOf("--input-format") + 1])
assertFalse("hello there" in command)
val line = org.json.JSONObject(ClaudeCode.input("hello there")!!)
assertEquals("user", line.getString("type"))
assertEquals("hello there", line.getJSONObject("message").getJSONArray("content").getJSONObject(0).getString("text"))
assertNull(Codex.input("hi"))
}
@Test fun aTaskNotificationResultIsMarkedBackgroundAndCarriesItsUsage() {
val event = ClaudeCode.parse("""{"type":"result","is_error":false,"session_id":"s","duration_ms":900,"total_cost_usd":0.01,"usage":{"input_tokens":3,"output_tokens":4},"origin":{"kind":"task-notification"}}""")!!
assertTrue(event.background)
assertTrue(event.entries.isEmpty())
assertEquals(4L, event.usage?.outputTokens)
assertNull(event.backgroundError)
}
@Test fun retainedClaudeCostsAreRecordedOncePerProcess() {
val costs = AgentCostTracker()
fun usage(cost: Double) = AgentHost.Usage(1, cost, 1, 1)
assertEquals(0.05, costs.perTurn(usage(0.05)).costUsd, 0.000001)
assertEquals(0.02, costs.perTurn(usage(0.07)).costUsd, 0.000001)
assertEquals(0.0, costs.perTurn(usage(0.07)).costUsd, 0.000001)
costs.reset()
assertEquals(0.0, costs.perTurn(usage(0.0)).costUsd, 0.000001)
assertEquals(0.07, costs.perTurn(usage(0.07)).costUsd, 0.000001)
assertEquals(0.01, costs.perTurn(usage(0.01)).costUsd, 0.000001)
assertEquals(0.07, AgentCostTracker().perTurn(usage(0.07)).costUsd, 0.000001)
}
@Test fun aFailedTaskNotificationResultKeepsItsError() {
val event = ClaudeCode.parse("""{"type":"result","is_error":true,"result":"API Error: overloaded","session_id":"s","usage":{"input_tokens":0,"output_tokens":0},"origin":{"kind":"task-notification"}}""")!!
assertTrue(event.background)
assertEquals("API Error: overloaded", event.backgroundError)
}
@Test fun aToolCallThatRunsInTheBackgroundIsMarked() {
fun used(tool: String, input: String) = ClaudeCode.parse(
"""{"type":"assistant","session_id":"s","message":{"content":[{"type":"tool_use","id":"t","name":"$tool","input":$input}]}}"""
)!!.entries.single() as Entry.Used
assertTrue(used("Bash", """{"command":"./gradlew test","run_in_background":true}""").background)
assertFalse(used("Bash", """{"command":"ls"}""").background)
assertTrue(used("Monitor", """{"command":"tail -f log"}""").background)
}
@Test fun claudeTurnsBypassPermissionsOrPlanAndTakeAModel() {
val first = ClaudeCode.turn("hi", null, AgentHarness.Options())
assertTrue("bypassPermissions" in first && "--resume" !in first && "--model" !in first && "--include-partial-messages" in first)
@@ -225,7 +179,7 @@ class AgentHostTest {
AgentChats.start(file, "claude")
AgentChats.appendConversation(file, "abc")
val written = listOf(
Entry.Asked("hi", listOf("/root/x.png")), Entry.Said("hello"), Entry.Notice("service unavailable"), Entry.Thought("hm"), Entry.Used("t1", "Read", "/root/x", "{}"),
Entry.Asked("hi", listOf("/root/x.png")), Entry.Said("hello"), Entry.Thought("hm"), Entry.Used("t1", "Read", "/root/x", "{}"),
Entry.Result("t1", "contents", false), Entry.Finished(null, usage = AgentHost.Usage(1, 0.5, 2, 3)), Entry.Finished("boom", stopped = true),
Entry.Finished(null, usage = AgentHost.Usage(1, 0.5, 2, 3, context = 40_000, window = 200_000), planned = true),
)
@@ -235,7 +189,7 @@ class AgentHostTest {
assertEquals("claude", loaded.harness)
assertEquals("abc", loaded.conversation)
assertEquals(listOf(
Entry.Asked("hi", listOf("/root/x.png")), Entry.Said("hello"), Entry.Notice("service unavailable"), Entry.Thought("hm"), Entry.Used("t1", "Read", "/root/x", "{}", "contents", false),
Entry.Asked("hi", listOf("/root/x.png")), Entry.Said("hello"), Entry.Thought("hm"), Entry.Used("t1", "Read", "/root/x", "{}", "contents", false),
Entry.Finished(null, usage = AgentHost.Usage(1, 0.5, 2, 3)), Entry.Finished("boom", stopped = true),
Entry.Finished(null, usage = AgentHost.Usage(1, 0.5, 2, 3, context = 40_000, window = 200_000), planned = true),
), loaded.entries)
@@ -244,7 +198,6 @@ class AgentHostTest {
@Test fun aTurnThatEndsWithNothingIsAnswerless() {
assertTrue(AgentHost.answerless(listOf(Entry.Said("x"), Entry.Asked("go on"), Entry.Finished(null))))
assertTrue(AgentHost.answerless(listOf(Entry.Asked("go on"), Entry.Notice("service unavailable"), Entry.Finished(null))))
assertFalse(AgentHost.answerless(listOf(Entry.Asked("go on"), Entry.Said("ok"), Entry.Finished(null))))
assertFalse(AgentHost.answerless(listOf(Entry.Asked("go on"), Entry.Finished("boom"))))
assertFalse(AgentHost.answerless(listOf(Entry.Asked("go on"), Entry.Finished(null, stopped = true))))
@@ -100,36 +100,6 @@ class SteamLaunchOptionsTest {
private fun localConfig(home: File, account: String) = File(home, "userdata/$account/config/localconfig.vdf").apply { parentFile!!.mkdirs() }
private fun withRootApp(text: String, appId: Int, key: String, value: String) = text.replaceFirst(
"{\n\t\"Software\"",
"{\n\t\"apps\"\n\t{\n\t\t\"$appId\"\n\t\t{\n\t\t\t\"$key\"\t\t\"$value\"\n\t\t}\n\t}\n\t\"Software\"",
)
@Test fun steamInputIsReadFromTheRootAppsSection() {
val home = steamHome()
localConfig(home, "60974196").writeText(withRootApp(config(apps(*sparking)), 1790600, "UseSteamControllerConfig", "2"))
assertEquals("2", SteamLaunchOptions.steamAppSetting(home, 1790600, "UseSteamControllerConfig", "1"))
assertEquals("1", SteamLaunchOptions.steamAppSetting(home, 400, "UseSteamControllerConfig", "1"))
}
@Test fun steamInputIsWrittenToTheRootAppsSectionAndAnOldCopyIsDropped() {
val home = steamHome()
val legacy = arrayOf(
"\t\t\t\t\t\"1790600\"", "\t\t\t\t\t{", "\t\t\t\t\t\t\"LaunchOptions\"\t\t\"-dx11\"",
"\t\t\t\t\t\t\"UseSteamControllerConfig\"\t\t\"0\"", "\t\t\t\t\t}",
)
val file = localConfig(home, "60974196").apply { writeText(config(apps(*legacy))) }
assertEquals("0", SteamLaunchOptions.steamAppSetting(home, 1790600, "UseSteamControllerConfig", "1"))
assertTrue(SteamLaunchOptions.writeSteamAppSetting(home, 1790600, "UseSteamControllerConfig", "0", "2", "1"))
val written = file.readText()
assertEquals("2", SteamLaunchOptions.steamAppSetting(home, 1790600, "UseSteamControllerConfig", "1"))
assertEquals(1, Regex("UseSteamControllerConfig").findAll(written).count())
assertFalse(written.substring(written.indexOf("\"Software\""), written.indexOf("\"WebStorage\"")).contains("UseSteamControllerConfig"))
assertEquals("-dx11", SteamLaunchOptions.launchOptions(written, 1790600))
assertTrue(SteamLaunchOptions.writeSteamAppSetting(home, 1790600, "UseSteamControllerConfig", "2", null, "1"))
assertFalse(file.readText().contains("UseSteamControllerConfig"))
}
@Test fun aChangeGoesToTheSignedInAccountOnly() {
val home = steamHome()
val signedIn = localConfig(home, "60974196").apply { writeText(config(apps(*sparking))) }
@@ -1,43 +0,0 @@
package com.droiddeck.launcher.gpu
import com.droiddeck.launcher.session.SessionPrefs
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], application = android.app.Application::class)
class SteamGpuDrawingRouteTest {
private val context get() = RuntimeEnvironment.getApplication()
@Before fun clear() {
context.getSharedPreferences("session", 0).edit().clear().commit()
}
@Test fun selectingTheSystemDriverFlipsTheUntouchedRowToSoftware() {
assertFalse(SessionPrefs.steamGpuDrawingShown(context, SystemVulkanDriver.usesDefault(true, "")))
}
@Test fun selectingAnOpenDriverFlipsTheUntouchedRowToGpu() {
assertTrue(SessionPrefs.steamGpuDrawingShown(context, SystemVulkanDriver.usesDefault(true, "custom-driver")))
}
@Test fun otherGpusKeepTheGpuRowWhateverDriverIsSelected() {
assertTrue(SessionPrefs.steamGpuDrawingShown(context, SystemVulkanDriver.usesDefault(false, "")))
assertTrue(SessionPrefs.steamGpuDrawingShown(context, SystemVulkanDriver.usesDefault(false, "custom-driver")))
}
@Test fun savedChoiceSurvivesDriverRouteChanges() {
SessionPrefs.setSteamGpuCompositing(context, false)
assertFalse(SessionPrefs.steamGpuDrawingShown(context, SystemVulkanDriver.usesDefault(true, "")))
assertFalse(SessionPrefs.steamGpuDrawingShown(context, SystemVulkanDriver.usesDefault(true, "custom-driver")))
SessionPrefs.setSteamGpuCompositing(context, true)
assertTrue(SessionPrefs.steamGpuDrawingShown(context, SystemVulkanDriver.usesDefault(true, "")))
assertTrue(SessionPrefs.steamGpuDrawingShown(context, SystemVulkanDriver.usesDefault(true, "custom-driver")))
}
}
@@ -0,0 +1,99 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
import java.io.ByteArrayOutputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
@GraphicsMode(GraphicsMode.Mode.NATIVE)
class ArmsControlSkinsTest {
private val context get() = RuntimeEnvironment.getApplication()
@Before fun reset() { context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE).edit().clear().commit() }
private fun base() = CommunityControls.parse(context, context.assets.open("community-controls/packs/compact-gamepad.ddcontrols.zip").use { it.readBytes() })
private fun png(color: Int, size: Int = 16): ByteArray {
val bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888).apply { eraseColor(color) }
return ByteArrayOutputStream().also { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it); bitmap.recycle() }.toByteArray()
}
private fun zip(vararg files: Pair<String, ByteArray>): ByteArray {
val bytes = ByteArrayOutputStream()
ZipOutputStream(bytes).use { z -> files.forEach { (name, data) -> z.putNextEntry(ZipEntry(name)); z.write(data); z.closeEntry() } }
return bytes.toByteArray()
}
@Test fun skinAppliesToNativeTargetsAndPreservesBindingsAndGeometry() {
val old = base()
val skin = ArmsControlSkins.parse(context, zip("folder/ic_controller_cross_button.png" to png(Color.RED),
"square.png" to png(Color.BLUE)), old.layout, old.bindings, "Community skin")
assertEquals(old.bindings.elements, skin.bindings.elements)
assertEquals(old.layout.elements.map { it.x to it.y }, skin.layout.elements.map { it.x to it.y })
assertEquals("skin_cross.png", skin.layout.elements.first { it.id == "a" }.image)
assertEquals("skin_square.png", skin.layout.elements.first { it.id == "x" }.image)
assertEquals("", skin.layout.elements.first { it.id == "b" }.image)
assertNotEquals(old.layout.id, skin.layout.id)
}
@Test fun separateStickArtworkSurvivesInstallExportAndReimport() {
val old = base()
val skin = ArmsControlSkins.parse(context, zip("analog_base.png" to png(Color.RED),
"analog_stick_left.png" to png(Color.GREEN), "analog_stick_right.png" to png(Color.BLUE)), old.layout, old.bindings, "Stick skin")
val left = skin.layout.elements.first { it.id == "left-stick" }
val right = skin.layout.elements.first { it.id == "right-stick" }
assertEquals(left.image, right.image)
assertNotEquals(left.stickImage, right.stickImage)
val installed = CommunityControls.install(context, skin, InputProfile.GAME, InputRole.PRIMARY)
val layout = installed.layout(InputProfile.GAME, InputRole.PRIMARY)!!
val bindings = installed.preset(installed.profile(InputProfile.GAME).binding(InputRole.PRIMARY))
val pack = CommunityControls.parse(context, CommunityControls.export(context, layout, bindings))
assertEquals(3, pack.images.size)
assertNotEquals("", pack.layout.elements.first { it.id == "left-stick" }.stickImage)
val artwork = ArmsControlSkins.export(context, layout, bindings)
val imported = ArmsControlSkins.parse(context, artwork, old.layout, old.bindings, "Shared skin")
assertEquals(4, imported.images.size)
assertEquals(old.bindings.elements, imported.bindings.elements)
}
@Test fun partialStickSkinsKeepExistingBaseOrThumbArtwork() {
val old = base()
val full = ArmsControlSkins.parse(context, zip("analog_base.png" to png(Color.RED),
"analog_stick.png" to png(Color.GREEN)), old.layout, old.bindings, "Full skin")
val library = CommunityControls.install(context, full, InputProfile.GAME, InputRole.PRIMARY)
val layout = library.layout(InputProfile.GAME, InputRole.PRIMARY)!!
val bindings = library.preset(library.profile(InputProfile.GAME).binding(InputRole.PRIMARY))
val original = layout.elements.first { it.id == "left-stick" }
for (thumbOnly in listOf(true, false)) {
val key = if (thumbOnly) "analog_stick.png" else "analog_base.png"
val partial = ArmsControlSkins.parse(context, zip(key to png(Color.BLUE)), layout, bindings, "Partial skin")
val element = partial.layout.elements.first { it.id == "left-stick" }
val retained = if (thumbOnly) original.image else original.stickImage
assertEquals(retained, if (thumbOnly) element.image else element.stickImage)
assertArrayEquals(InputButtonImages.file(context, retained)!!.readBytes(), partial.images.getValue(retained))
assertEquals(bindings.elements, partial.bindings.elements)
}
}
@Test fun downsamplesLargeImagesBeforeStoringThem() {
val old = base()
val skin = ArmsControlSkins.parse(context, zip("cross.png" to png(Color.RED, 2048)), old.layout, old.bindings, "Large skin")
val bytes = skin.images.values.single()
val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
assertTrue(bitmap.width <= 512 && bitmap.height <= 512)
bitmap.recycle()
}
@Test fun rejectsTraversalDuplicateButtonsAndArchivesWithoutMatchingImages() {
val old = base()
for (files in listOf(arrayOf("../cross.png" to png(Color.RED)),
arrayOf("cross.png" to png(Color.RED), "ic_controller_cross_button.png" to png(Color.RED)),
arrayOf("readme.txt" to byteArrayOf()), arrayOf("cross.png" to byteArrayOf(1, 2))))
assertThrows(IllegalArgumentException::class.java) { ArmsControlSkins.parse(context, zip(*files), old.layout, old.bindings, "Invalid") }
}
}
@@ -0,0 +1,140 @@
package com.droiddeck.launcher.input
import android.content.Context
import android.graphics.Bitmap
import org.json.JSONObject
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
import java.util.zip.ZipOutputStream
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
class CommunityControlsTest {
private val context get() = RuntimeEnvironment.getApplication()
private fun starter() = context.assets.open("community-controls/packs/compact-gamepad.ddcontrols.zip").use { it.readBytes() }
@Before fun reset() {
context.getSharedPreferences("input-profiles", Context.MODE_PRIVATE).edit().clear().commit()
}
private fun archive(vararg entries: Pair<String, ByteArray>): ByteArray {
val out = ByteArrayOutputStream()
ZipOutputStream(out).use { zip -> entries.forEach { (name, data) ->
zip.putNextEntry(ZipEntry(name)); zip.write(data); zip.closeEntry()
} }
return out.toByteArray()
}
private fun manifest(): JSONObject = ZipInputStream(ByteArrayInputStream(starter())).use {
it.nextEntry; JSONObject(it.readBytes().toString(Charsets.UTF_8))
}
private fun rejects(action: () -> Unit) {
try { action(); fail("Expected rejected controls") } catch (_: IllegalArgumentException) { }
}
@Test fun starterInstallsIndependentNativeGamepadWithoutChangingOtherParts() {
val original = InputLibraries.read(context)
val pack = CommunityControls.parse(context, starter())
val second = CommunityControls.parse(context, starter())
assertNotEquals(pack.layout.id, second.layout.id)
assertNotEquals(pack.bindings.id, second.bindings.id)
val changed = CommunityControls.install(context, pack, InputProfile.GAME, InputRole.PRIMARY)
assertEquals(pack.layout, changed.layout(InputProfile.GAME, InputRole.PRIMARY))
assertEquals(InputAction.Native(InputControl.A), changed.preset(changed.profile(InputProfile.GAME).binding(InputRole.PRIMARY)).elements["a"])
assertEquals(original.profile(InputProfile.DESKTOP), changed.profile(InputProfile.DESKTOP))
assertEquals(original.profile(InputProfile.GAME).parts[InputRole.PHYSICAL], changed.profile(InputProfile.GAME).parts[InputRole.PHYSICAL])
assertEquals(original.profile(InputProfile.GAME).parts[InputRole.SECONDARY], changed.profile(InputProfile.GAME).parts[InputRole.SECONDARY])
assertEquals(changed, InputLibraries.read(context))
}
@Test fun packRoundTripPreservesImagesStyleActionsAndClicks() {
val base = CommunityControls.parse(context, starter())
val imageName = "roundtrip.png"
val bitmap = Bitmap.createBitmap(8, 8, Bitmap.Config.ARGB_8888)
val png = ByteArrayOutputStream().also { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }.toByteArray()
bitmap.recycle()
val layout = base.layout.copy(elements = base.layout.elements.map { if (it.id == "a") it.copy(image = imageName, showLabel = false, toggle = true) else it })
val bindings = base.bindings.copy(elements = base.bindings.elements + ("a" to InputAction.Keys(listOf(29, 30))),
clicks = mapOf("left-stick" to InputAction.MouseButton(272)))
val installed = CommunityControls.install(context, CommunityControls.Pack(layout, bindings, mapOf(imageName to png)), InputProfile.GAME, InputRole.PRIMARY)
val saved = installed.layout(InputProfile.GAME, InputRole.PRIMARY)!!
val exported = CommunityControls.export(context, saved, installed.preset(installed.profile(InputProfile.GAME).binding(InputRole.PRIMARY)))
val imported = CommunityControls.parse(context, exported)
assertEquals(saved.copy(id = imported.layout.id), imported.layout)
assertEquals(bindings.elements, imported.bindings.elements)
assertEquals(bindings.clicks, imported.bindings.clicks)
assertArrayEquals(png, imported.images.values.single())
assertNotEquals(imageName, saved.elements.first { it.id == "a" }.image)
}
@Test fun parserDoesNotChangePreferences() {
val before = InputLibraries.read(context)
CommunityControls.parse(context, starter())
assertEquals(before, InputLibraries.read(context))
}
@Test fun rejectsTraversalAndUnexpectedEntries() {
rejects { CommunityControls.parse(context, archive("../controls.json" to byteArrayOf())) }
rejects { CommunityControls.parse(context, archive("images/../x.png" to byteArrayOf())) }
rejects { CommunityControls.parse(context, archive("unrelated" to byteArrayOf())) }
}
@Test fun rejectsMissingAndUnreferencedImages() {
val doc = manifest()
doc.getJSONObject("layout").getJSONArray("elements").getJSONObject(0).put("image", "missing.png")
rejects { CommunityControls.parse(context, archive("controls.json" to doc.toString().toByteArray())) }
rejects { CommunityControls.parse(context, archive("controls.json" to manifest().toString().toByteArray(), "images/unused.png" to byteArrayOf())) }
}
@Test fun rejectsFutureFormatsAndInvalidActions() {
val doc = manifest().put("version", 99)
rejects { CommunityControls.parse(context, archive("controls.json" to doc.toString().toByteArray())) }
doc.put("version", 1).getJSONObject("bindings").getJSONObject("elements").put("a", JSONObject().put("type", "shell").put("command", "bad"))
rejects { CommunityControls.parse(context, archive("controls.json" to doc.toString().toByteArray())) }
}
@Test fun importingInvalidNativePackPreservesItsOriginalError() {
val doc = manifest()
doc.getJSONObject("layout").getJSONArray("elements").getJSONObject(0).put("image", "missing.png")
val old = CommunityControls.parse(context, starter())
val error = assertThrows(IllegalArgumentException::class.java) {
CommunityControls.importFile(context, archive("controls.json" to doc.toString().toByteArray()), old.layout, old.bindings)
}
assertEquals("Missing or unexpected button images.", error.message)
}
@Test fun rejectsCorruptImages() {
val doc = manifest()
doc.getJSONObject("layout").getJSONArray("elements").getJSONObject(0).put("image", "invalid.png")
rejects { CommunityControls.parse(context, archive("controls.json" to doc.toString().toByteArray(), "images/invalid.png" to byteArrayOf(0, 1, 2))) }
}
@Test fun boundedReaderRejectsOversizeBeforeBufferingAllInput() {
rejects { CommunityControls.readLimited(ByteArrayInputStream(ByteArray(8192)), 16) }
assertEquals(16, CommunityControls.readLimited(ByteArrayInputStream(ByteArray(16)), 16).size)
rejects { CommunityControls.parse(context, archive("controls.json" to ByteArray(2_000_001))) }
}
@Test fun bundledCatalogMatchesPackAndRejectsExternalPaths() {
val entries = CommunityControls.bundled(context)
assertTrue(entries.isNotEmpty())
entries.forEach {
assertEquals(it.name, CommunityControls.download(context, it).layout.name)
val preview = requireNotNull(CommunityControls.preview(context, it))
assertTrue(maxOf(preview.width, preview.height) <= 256)
preview.recycle()
}
rejects { CommunityControls.download(context, entries.first().copy(sha256 = "0".repeat(64))) }
val doc = JSONObject(context.assets.open("community-controls/catalog.json").bufferedReader().use { it.readText() })
doc.getJSONArray("controls").getJSONObject(0).put("file", "https://example.com/pack.zip")
rejects { CommunityControls.catalog(doc.toString()) }
doc.getJSONArray("controls").getJSONObject(0).put("file", "packs/../../other.ddcontrols.zip")
rejects { CommunityControls.catalog(doc.toString()) }
}
}
@@ -0,0 +1,53 @@
package com.droiddeck.launcher.input
import android.content.Context
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
class ControlSourcesTest {
private val context get() = RuntimeEnvironment.getApplication()
@Before fun reset() { context.getSharedPreferences("community-control-sources", Context.MODE_PRIVATE).edit().clear().commit() }
@Test fun hasRemoteArmsSourceWithoutBundlingItsArtwork() {
assertEquals(listOf(ControlSources.DROIDDECK, ControlSources.ARMSX2), ControlSources.read(context))
assertTrue(ControlSources.ARMSX2.manifest.contains("bagasromadon/ARMSX2-CustomControllerSkins"))
}
@Test fun githubRepositoriesAndFileLinksResolveToManifests() {
val repo = ControlSources.candidates("https://github.com/example/controls")
assertEquals(listOf("https://raw.githubusercontent.com/example/controls/main/catalog.json",
"https://raw.githubusercontent.com/example/controls/main/manifest.json"), repo.map { it.manifest })
assertEquals("https://raw.githubusercontent.com/example/controls/dev/skins/manifest.json",
ControlSources.candidates("https://github.com/example/controls/blob/dev/skins/manifest.json").single().manifest)
}
@Test fun customSourcesPersistAndCanBeRemovedWithoutLosingDefaults() {
val source = ControlSources.candidates("https://example.com/controls/catalog.json").single()
ControlSources.add(context, source)
assertEquals(source, ControlSources.read(context).last())
assertThrows(IllegalArgumentException::class.java) { ControlSources.add(context, source) }
ControlSources.remove(context, source)
assertEquals(2, ControlSources.read(context).size)
}
@Test fun pathsStayWithinSourceAndEncodeSpaces() {
assertEquals("https://raw.githubusercontent.com/bagasromadon/ARMSX2-CustomControllerSkins/main/Skins/Black%20Gold.zip",
ControlSources.ARMSX2.url("Skins/Black Gold.zip"))
for (path in listOf("../other.zip", "packs/../x.zip", "https://other.com/x", "/x", "x%2f..zip", "x?bad", "x\\bad"))
assertThrows(IllegalArgumentException::class.java) { ControlSources.ARMSX2.url(path) }
for (url in listOf("http://example.com/catalog.json", "https://user:secret@example.com/catalog.json", "file:///tmp/catalog.json", "https://example.com"))
assertThrows(IllegalArgumentException::class.java) { ControlSources.candidates(url) }
}
@Test fun parsesArmsCatalogAndKeepsSourceAndOptionalLicenseSeparate() {
val raw = """{"skins":[{"name":"Black Gold", "author":"maker", "file":"Skins/Black Gold.zip", "preview":"Previews/Black_Gold.png"}]}"""
val entry = CommunityControls.catalog(raw, ControlSources.ARMSX2).single()
assertTrue(entry.skin)
assertEquals("", entry.license)
assertEquals("", entry.sha256)
assertEquals(ControlSources.ARMSX2, entry.source)
assertNotEquals(entry.key, entry.copy(source = ControlSources.DROIDDECK).key)
}
}
@@ -0,0 +1,80 @@
package com.droiddeck.launcher.input
import android.content.Context
import org.junit.Assert.*
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
class GameInputControlsTest {
private val context get() = RuntimeEnvironment.getApplication()
@Before fun reset() {
for (name in listOf("input-profiles", "input-game-controls"))
context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit()
}
private fun library(): InputLibrary {
val result = InputLibraries.update(context) { it.duplicateProfile(InputProfile.GAME, "My game", "my-game") }
GameInputControls.set(context, "42", "my-game")
return result
}
@Test fun directLaunchResolvesTheGameBeforeSessionServiceStarts() {
val original = library()
val state = com.droiddeck.launcher.session.SessionState
val previousRunning = state.running
val previousMode = state.mode
val previousGame = state.gameId
try {
state.running = false
state.mode = com.droiddeck.launcher.session.SessionService.MODE_STEAM
state.gameId = null
val intent = android.content.Intent(context, com.droiddeck.launcher.SessionActivity::class.java)
.putExtra(com.droiddeck.launcher.session.SessionService.EXTRA_MODE, com.droiddeck.launcher.session.SessionService.MODE_RUN)
.putExtra(com.droiddeck.launcher.session.SessionService.EXTRA_GAME_ID, "42")
val activity = org.robolectric.Robolectric.buildActivity(com.droiddeck.launcher.SessionActivity::class.java, intent).get()
assertEquals("42", activity.inputGameScope())
assertEquals(original.profile("my-game").binding(InputRole.PRIMARY),
GameInputControls.resolve(context, original, false, activity.inputGameScope()).activePart(false, InputRole.PRIMARY).bindings)
} finally { state.running = previousRunning; state.mode = previousMode; state.gameId = previousGame }
}
@Test fun gameOverridesOnlyScreenPartsAndRestoresGeneralControlsOnExit() {
val original = library()
val game = GameInputControls.resolve(context, original, false, "42")
for (role in listOf(InputRole.PRIMARY, InputRole.SECONDARY))
assertEquals(original.profile("my-game").binding(role), game.activePart(false, role).bindings)
assertEquals(original.activePart(false, InputRole.PHYSICAL), game.activePart(false, InputRole.PHYSICAL))
assertEquals(original, GameInputControls.resolve(context, original, false, null))
assertEquals(original, GameInputControls.resolve(context, original, false, "43"))
assertEquals(original, InputLibraries.read(context))
}
@Test fun manualProfileAndScreenChoicesTakePriority() {
val original = library()
val manual = original.selectProfile(false, InputProfile.DESKTOP)
assertEquals(manual, GameInputControls.resolve(context, manual, false, "42"))
val role = InputRole.PRIMARY
val chosen = original.profile(InputProfile.DESKTOP).binding(role)
val mixed = original.selectPart(false, role, chosen)
val effective = GameInputControls.resolve(context, mixed, false, "42")
assertEquals(chosen, effective.activePart(false, role).bindings)
assertEquals(original.profile("my-game").binding(InputRole.SECONDARY), effective.activePart(false, InputRole.SECONDARY).bindings)
}
@Test fun gameResetClearsOnlyTheSelectedControlsMapping() {
library()
GameInputControls.set(context, "43", InputProfile.DESKTOP)
com.droiddeck.launcher.session.GameProfileManager.reset(context, "42")
assertNull(GameInputControls.profile(context, "42"))
assertEquals(InputProfile.DESKTOP, GameInputControls.profile(context, "43"))
}
@Test fun deletedProfileAndClearedOverridesFallBackToGeneral() {
val original = library()
val removed = original.removeProfile("my-game")
assertEquals(removed, GameInputControls.resolve(context, removed, false, "42"))
GameInputControls.set(context, "42", null)
assertNull(GameInputControls.profile(context, "42"))
assertEquals(original, GameInputControls.resolve(context, original, false, "42"))
}
}
@@ -1,97 +0,0 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], application = android.app.Application::class)
class SteamGpuCompositingTest {
private val context get() = RuntimeEnvironment.getApplication()
@Before fun clear() {
context.getSharedPreferences("session", 0).edit().clear().commit()
assertTrue(SessionPrefs.steamGpuCompositingAllowed())
}
@Test fun eligibleRendererUsesGpuCompositingByDefault() {
assertTrue(SessionPrefs.steamGpuCompositing(context))
}
@Test fun savedSoftwareChoiceIsPreserved() {
context.getSharedPreferences("session", 0).edit()
.putBoolean("steamGpuCompositing", false).commit()
assertFalse(SessionPrefs.steamGpuCompositing(context))
}
@Test fun savedGpuChoiceIsPreserved() {
context.getSharedPreferences("session", 0).edit()
.putBoolean("steamGpuCompositing", true).commit()
assertTrue(SessionPrefs.steamGpuCompositing(context))
}
@Test fun preferenceCanStillBeToggled() {
SessionPrefs.setSteamGpuCompositing(context, false)
assertFalse(SessionPrefs.steamGpuCompositing(context))
SessionPrefs.setSteamGpuCompositing(context, true)
assertTrue(SessionPrefs.steamGpuCompositing(context))
}
@Test fun untouchedPreferenceIsNotAChoice() {
assertFalse(SessionPrefs.steamGpuCompositingChosen(context, SessionService.MODE_STEAM))
}
@Test fun savedGpuChoiceIsAChoice() {
SessionPrefs.setSteamGpuCompositing(context, true)
assertTrue(SessionPrefs.steamGpuCompositingChosen(context, SessionService.MODE_STEAM))
}
@Test fun savedSoftwareChoiceIsNotChosenGpu() {
SessionPrefs.setSteamGpuCompositing(context, false)
assertFalse(SessionPrefs.steamGpuCompositingChosen(context, SessionService.MODE_STEAM))
}
@Test fun desktopSessionNeverReceivesChosenGpuCompositing() {
SessionPrefs.setSteamGpuCompositing(context, true)
assertFalse(SessionPrefs.steamGpuCompositingChosen(context, SessionService.MODE_DESKTOP))
}
@Test fun runSessionNeverReceivesChosenGpuCompositing() {
SessionPrefs.setSteamGpuCompositing(context, true)
assertFalse(SessionPrefs.steamGpuCompositingChosen(context, SessionService.MODE_RUN))
}
@Test fun untouchedPreferenceShowsSoftwareOnSystemDriverPath() {
assertFalse(SessionPrefs.steamGpuDrawingShown(context, true))
}
@Test fun untouchedPreferenceShowsGpuOnOpenDriverPath() {
assertTrue(SessionPrefs.steamGpuDrawingShown(context, false))
}
@Test fun savedGpuChoiceIsShownOnBothPaths() {
SessionPrefs.setSteamGpuCompositing(context, true)
assertTrue(SessionPrefs.steamGpuDrawingShown(context, true))
assertTrue(SessionPrefs.steamGpuDrawingShown(context, false))
}
@Test fun savedSoftwareChoiceIsShownOnBothPaths() {
SessionPrefs.setSteamGpuCompositing(context, false)
assertFalse(SessionPrefs.steamGpuDrawingShown(context, true))
assertFalse(SessionPrefs.steamGpuDrawingShown(context, false))
}
@Test fun firstToggleFromUntouchedSystemDriverRowSavesGpu() {
SessionPrefs.setSteamGpuCompositing(context, !SessionPrefs.steamGpuDrawingShown(context, true))
assertTrue(SessionPrefs.steamGpuCompositingChosen(context, SessionService.MODE_STEAM))
}
@Test fun systemDriverPathIsOffOnDevicesWithoutThePowerVrDriver() {
assertFalse(SessionPrefs.systemDriverSteamPath(context))
}
}
@@ -0,0 +1,106 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.view.View
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.ui.Modifier
import androidx.compose.material3.Surface
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.test.*
import androidx.compose.ui.unit.dp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.input.*
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], qualifiers = "w1000dp-h900dp")
@GraphicsMode(GraphicsMode.Mode.NATIVE)
class InputCommunityPageTest {
@get:Rule val compose = createRobolectricComposeRule()
private val context get() = RuntimeEnvironment.getApplication()
private lateinit var root: View
@Before fun reset() {
for (name in listOf("input-profiles", "input-surfaces", "controller", "input-game-controls"))
context.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().commit()
}
private fun open() {
compose.setContent { root = LocalView.current; DroidDeckTheme { Surface { BoxWithConstraints {
CompositionLocalProvider(LocalNarrowPane provides (maxWidth < 600.dp)) { InputSettingsPage({}) }
} } } }
compose.onNodeWithTag("input-community").performScrollTo().performClick()
}
@Test fun communityRequiresReviewBeforeApplyingAndPreservesOtherProfiles() {
val before = InputLibraries.read(context)
open()
compose.onNodeWithText("Compact gamepad").performScrollTo().performClick()
compose.waitUntil(10_000) { compose.onAllNodesWithText(context.getString(R.string.community_apply)).fetchSemanticsNodes().isNotEmpty() }
assertEquals(before, InputLibraries.read(context))
screenshot("community-review", org.robolectric.shadows.ShadowDialog.getLatestDialog().window!!.decorView)
compose.onNodeWithText(context.getString(R.string.community_apply)).performClick()
compose.waitUntil(10_000) { InputLibraries.read(context).layout(InputProfile.GAME, InputRole.PRIMARY)?.name == "Compact gamepad" }
val after = InputLibraries.read(context)
assertEquals(before.profile(InputProfile.DESKTOP), after.profile(InputProfile.DESKTOP))
compose.onNodeWithText(context.getString(R.string.community_export)).performScrollTo().assertIsDisplayed()
}
@Test @Config(qualifiers = "w360dp-h800dp")
fun phoneCanBrowseSearchAndReachImportAndSubmission() {
open()
compose.waitUntil(10_000) { compose.onAllNodesWithTag("community-preview-packs/compact-gamepad.ddcontrols.zip", useUnmergedTree = true).fetchSemanticsNodes().isNotEmpty() }
screenshot("community-phone")
compose.onNodeWithText(context.getString(R.string.community_search)).performTextInput("absent-game")
compose.onNodeWithText(context.getString(R.string.community_empty)).performScrollTo().assertIsDisplayed()
compose.onNodeWithTag("community-import").performScrollTo().assertIsDisplayed()
compose.onNodeWithText(context.getString(R.string.community_submit)).performScrollTo().assertIsDisplayed()
}
@Test fun largeCatalogIsPagedAndSearchResetsToMatchingResults() {
val library = InputLibraries.read(context)
val starter = CommunityControls.bundled(context).first()
val entries = (1..25).map { starter.copy(name = "Pack $it", path = "packs/pack-$it.ddcontrols.zip", preview = null) }
compose.setContent { DroidDeckTheme { Column(Modifier.verticalScroll(rememberScrollState())) {
InputCommunityPage(library, InputProfile.GAME, InputRole.PRIMARY, initialEntries = entries, onInstalled = {})
} } }
compose.onNodeWithText("Pack 1").assertExists()
compose.onNodeWithText("Pack 13").assertDoesNotExist()
compose.onNodeWithTag("community-next").performScrollTo().performClick()
compose.onNodeWithText("Pack 13").performScrollTo().assertIsDisplayed()
compose.onNodeWithText("Pack 1").assertDoesNotExist()
compose.onNodeWithText(context.getString(R.string.community_search)).performScrollTo().performTextInput("Pack 25")
compose.onNodeWithTag("community-pack-packs/pack-25.ddcontrols.zip").performScrollTo().assertIsDisplayed()
compose.onNodeWithTag("community-next").assertDoesNotExist()
compose.onNodeWithTag("community-import").performScrollTo().assertIsDisplayed()
}
@Test fun starterPreviewUsesTheSameRendererAsInstalledControls() {
val bytes = context.assets.open("community-controls/packs/compact-gamepad.ddcontrols.zip").use { it.readBytes() }
val pack = CommunityControls.parse(context, bytes)
val view = InputLayoutPreviewView(context)
view.update(pack.layout, InputRole.PRIMARY)
view.measure(View.MeasureSpec.makeMeasureSpec(640, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(360, View.MeasureSpec.EXACTLY))
view.layout(0, 0, 640, 360)
screenshot("compact-gamepad", view)
}
private fun screenshot(name: String, view: View = root) {
compose.runOnIdle {
val image = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
view.draw(Canvas(image))
val file = File("build/reports/community-controls/$name.png").apply { parentFile?.mkdirs() }
file.outputStream().use { image.compress(Bitmap.CompressFormat.PNG, 100, it) }
image.recycle()
}
}
}
+25
View File
@@ -0,0 +1,25 @@
# Community controls
Controller settings → Community controls browses source catalogs and imports or exports `.ddcontrols.zip` packs and controller-skin ZIPs. A DroidDeck starter gamepad is bundled for offline use. The ARMSX2 community catalog is a remote source: none of its artwork is shipped in this repository or the APK. Selecting it fetches its manifest and previews; selecting a skin downloads it directly from that source for local installation.
## Sources and sharing
The Source selector includes DroidDeck and [bagasromadon/ARMSX2-CustomControllerSkins](https://github.com/bagasromadon/ARMSX2-CustomControllerSkins). **Connect another source** accepts a public GitHub repository URL, a GitHub manifest file link, or a direct HTTPS catalog URL. Repository URLs try `main/catalog.json`, then `main/manifest.json`; use a file URL for another branch or a catalog in a subdirectory. Connected sources persist locally and can be removed. Results are filtered before pagination, with at most 12 entries and their previews loaded per page. Previews are sampled to at most 256 pixels. Page/filter/source changes discard the old cache; Android reclaims displayed bitmaps after rendering references are released. Native manifests use `controls`; ARMSX2 manifests use `skins`. Relative paths stay within the manifest directory, with spaces encoded when downloading. No account credentials are stored in DroidDeck.
**Export this layout and actions** creates a portable DroidDeck pack. **Export skin artwork** creates an ARMSX2-compatible PNG-only ZIP when the selected layout has suitable artwork. Share either ZIP directly, or use **Open source submissions** to visit the selected source's issue page and attach it there. GitHub requires an account. Source owners manage submissions and publication; the app does not automatically publish uploads. For other HTTPS hosts, the button opens the catalog URL; use that host's own upload process. A native controls pack includes layouts and bindings, while an artwork ZIP includes only controller images.
The DroidDeck issue template accepts exported packs and screenshots for review. Maintainers add approved packs to `packs/` and entries to `catalog.json`, with name, author, optional game, license, relative file path, SHA-256, optional preview path, and screen (`MAIN`, `SECONDARY`, or `BOTH`). Keep the bundled starter copies under `app/src/main/assets/community-controls` in sync. Remote entries are namespaced by source. Native pack downloads require the manifest's SHA-256; ARMSX2 manifests may omit it, so their files are obtained over HTTPS and validated as bounded PNG archives. Do not infer artwork redistribution rights from the application's code license.
## Applying controls
Native controls packs create an independent copy for the chosen profile and screen. ARMSX2/iOS skin archives match image names to the selected layout's native controller actions (cross → A, circle → B, square → X, triangle → Y, shoulders, triggers, system and directional buttons). Positions, actions, and stick-click bindings are preserved. Generic and separate left/right analog base/thumb images are supported. Unsupported images are ignored, missing artwork keeps the existing appearance, and a skin with no matching controls is rejected. Source images are sampled to at most 512 pixels before storage. Skin ZIPs can also be imported locally.
For game-specific controls, create a named input profile and apply the pack or skin to it. Select that profile in the game's settings under **On-screen controls profile**. Automatic selection follows the focused Steam game, or the launched game for direct launches. Returning to Steam restores general controls. Explicit quick-menu profile or screen choices take priority until Auto is restored. Physical controller bindings follow the general selection. Missing/deleted profiles fall back to general controls. Use Profile controls mode for the second display.
## Native pack format
A ZIP contains `controls.json` and the exact `images/<filename>` PNGs referenced by the layout. The JSON has `format: "droiddeck-controls"`, `version: 1`, and `layout` / `bindings` objects using the input library serialization. All supported actions, stick clicks, geometry, style, and artwork (including separate moving-stick images) are retained. Local IDs and image names are regenerated on import. Import validates the library, image dimensions, file count, byte limits, and entry paths before offering Apply; saving uses the library recovery path. Legacy `.icp` import/export remains in Saved layouts.
## Upstream inspiration
The source catalog flow and controller-skin filename conventions were researched directly from [ARMSX2](https://github.com/ARMSX2/ARMSX2) commit `9144e4ff1fed43756809d8e68b3efc2505a51078`, particularly `SkinRepo.kt`, `ControllerSkinStore.kt`, and `ui/settings/SkinsTab.kt`. ARMSX2's `COPYING.GPLv3` and `pcsx2/Docs/License.txt` license its program under GPLv3 or later, compatible with DroidDeck's GPLv3. This implementation uses DroidDeck's input model and renderer. No upstream source or artwork files are copied into the source tree. The bundled starter is original DroidDeck data under GPL-3.0.
+15
View File
@@ -0,0 +1,15 @@
{
"version": 1,
"controls": [
{
"name": "Compact gamepad",
"author": "DroidDeck",
"game": "",
"license": "GPL-3.0",
"file": "packs/compact-gamepad.ddcontrols.zip",
"sha256": "8b747e86268a1f607e312f2c39dd67402658bd5cf9e4e4ff524a4640417c9f3e",
"screen": "BOTH",
"preview": "previews/compact-gamepad.png"
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

-12
View File
@@ -22,18 +22,6 @@ and reports every run.
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.
## On the device
The agent in DroidDeck's Agent tab gets its working rules from `tools/agent/AGENTS.md` and its
skills from `tools/agent/skills`. Both ship in the APK; before every turn the app writes the rules
as a marked block into each harness's global instructions (`~/.claude/CLAUDE.md`,
`~/.codex/AGENTS.md`) and the skills into its skills folder (`~/.claude/skills`, `~/.codex/skills`).
Only DroidDeck's own block and skills (folders holding a `.droiddeck` file) are replaced: rules
the user writes outside the block, and skills they add, stay. A symlinked instructions file is
followed, so the block lands in the file it points to. `droiddeckctl`, `droiddeck-scenario` and this guide are installed in
`~/.local/share/droiddeck/ctl` (with `droiddeckctl` and `droiddeck-scenario` on PATH). If any of
these cannot be installed, the Agent tab shows which.
## Access
Player controls and observations work over authorized ADB on any build: `state`, `start`, `stop`,
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff. Show more