feat(dual-screen): Send dashboard data switch on the In-game stats page

Codemasters games keep their UDP/motion output in
My Games/<game>/hardwaresettings/hardware_settings_config.xml inside the
game's Proton prefix. The page finds those files in every library's
compatdata and offers a switch per game: on points the udp (or motion) line
at 127.0.0.1:20777 with extradata 3 and keeps the file as it was beside it;
off puts that line back. Only that line changes, the file is replaced in one
rename, and a game's switch is locked while that game runs. Installed games
whose output is a menu setting only (Forza, BeamNG.drive) get a line with
what to turn on. Library.compatdataDirs shares protonPrefix's library roots.
This commit is contained in:
The412Banner committed 2026-10-31 19:49:46 +00:00
1 parent 995cbc411c
commit f896d7fa75
7 files changed
+260 -6

No files matched your search

@@ -3144,6 +3144,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
takeScreenshot = ::captureScreenshot,
fps = { if (::hud.isInitialized) hud.liveFps else null },
openSettings = ::openSettingsBelow,
runningGame = { gestureGame },
))
// A settings page opened on the bottom screen sits under the dashboard window, so the dashboard hides
@@ -101,15 +101,22 @@ object Library {
libraries: List<File> = steamLibraries(context).map { it.first },
): File? {
val ids = listOf(appId.toString(), java.lang.Integer.toString(appId.toInt())).distinct()
return prefixRoots(context, libraries, preferredLibrary).asSequence()
.flatMap { root -> ids.asSequence().map { id -> File(root, "steamapps/compatdata/$id/pfx") } }
.firstOrNull { it.isDirectory }
}
/** Every steamapps/compatdata folder, in the libraries [protonPrefix] searches. */
fun compatdataDirs(context: Context, libraries: List<File> = steamLibraries(context).map { it.first }): List<File> =
prefixRoots(context, libraries).map { File(it, "steamapps/compatdata") }.filter { it.isDirectory }
private fun prefixRoots(context: Context, libraries: List<File>, preferredLibrary: File? = null): List<File> {
val secondary = libraries.drop(1).mapNotNull { runCatching { it.canonicalPath }.getOrNull() }.toSet()
fun prefixRoot(root: File): File = if (runCatching { root.canonicalPath }.getOrNull() in secondary)
SecondaryLibrary.privateRoot(context.filesDir, root).takeIf { File(it, "steamapps/compatdata").isDirectory } ?: root
else root
val roots = (listOfNotNull(preferredLibrary) + libraries).map(::prefixRoot)
return (listOfNotNull(preferredLibrary) + libraries).map(::prefixRoot)
.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.absolutePath) }
return roots.asSequence()
.flatMap { root -> ids.asSequence().map { id -> File(root, "steamapps/compatdata/$id/pfx") } }
.firstOrNull { it.isDirectory }
}
fun steamGames(
@@ -0,0 +1,104 @@
package com.droiddeck.launcher.session
import java.io.File
/**
* Codemasters games keep their UDP / motion output in My Games/<game>/hardwaresettings/hardware_settings_config.xml
* inside the game's Proton prefix and read it when the game starts. Turning it on points that element at the
* In-game stats listener; the file as it was is kept beside it, and its element is put back when turned off.
*/
object TelemetryOutput {
data class Game(val name: String, val prefixId: String, val file: File, val on: Boolean)
data class MenuGame(val name: String, val setting: String, val port: Int)
/** Games whose output is only a setting in the game's own menus, by Steam app id. */
val MENU_GAMES: Map<Int, MenuGame> = mapOf(
1293830 to MenuGame("Forza Horizon 4", "Data Out", GameTelemetry.FORZA_PORT),
1551360 to MenuGame("Forza Horizon 5", "Data Out", GameTelemetry.FORZA_PORT),
2440510 to MenuGame("Forza Motorsport", "Data Out", GameTelemetry.FORZA_PORT),
284160 to MenuGame("BeamNG.drive", "OutGauge", GameTelemetry.OUTGAUGE_PORT),
)
internal const val ORIGINAL_SUFFIX = ".droiddeck-original"
private const val MY_GAMES = "pfx/drive_c/users/steamuser/Documents/My Games"
private const val CONFIG = "hardwaresettings/hardware_settings_config.xml"
private const val ADDRESS = "127.0.0.1"
private const val EXTRADATA = "3"
private val TAGS = listOf("udp", "motion")
// Byte-for-byte: every byte maps to one char and back, whatever the file's own encoding is.
private val BYTES = Charsets.ISO_8859_1
fun scan(compatdata: List<File>): List<Game> = compatdata.asSequence()
.flatMap { root -> root.listFiles { f -> f.isDirectory }.orEmpty().asSequence() }
.flatMap { prefix -> File(prefix, MY_GAMES).listFiles { f -> f.isDirectory }.orEmpty().asSequence().map { prefix to it } }
.mapNotNull { (prefix, game) ->
val file = File(game, CONFIG)
val text = runCatching { file.readText(BYTES) }.getOrNull() ?: return@mapNotNull null
val element = element(text) ?: return@mapNotNull null
Game(game.name, prefix.name, file, pointsHere(element.value))
}
.sortedBy { it.name.lowercase() }
.toList()
/** Turns the game's output on or off; false when the file could not be read or written. */
fun set(game: Game, on: Boolean): Boolean = runCatching {
val file = game.file
val original = File(file.path + ORIGINAL_SUFFIX)
val xml = file.readText(BYTES)
val next = if (on) {
if (!original.exists()) file.copyTo(original)
turnedOn(xml)
} else {
turnedOff(xml, original.takeIf { it.isFile }?.readText(BYTES))
}
checkNotNull(next)
val tmp = File(file.path + ".droiddeck-tmp")
tmp.writeText(next, BYTES)
check(tmp.renameTo(file))
if (!on) original.delete()
true
}.getOrDefault(false)
/** Whether [running] (the focused Steam app id, or another key for non-Steam programs) may be the game in [prefixId]. */
internal fun isRunning(prefixId: String, running: String?): Boolean {
val id = running?.toLongOrNull() ?: return running != null
return prefixId == id.toString() || prefixId == id.toInt().toString()
}
internal fun element(xml: String): MatchResult? = TAGS.firstNotNullOfOrNull { tag -> tagRegex(tag).find(xml) }
internal fun pointsHere(element: String): Boolean =
attr(element, "enabled") == "true" && attr(element, "ip") == ADDRESS &&
attr(element, "port") == GameTelemetry.CODEMASTERS_PORT.toString() &&
(attr(element, "extradata") ?: EXTRADATA) == EXTRADATA
internal fun turnedOn(xml: String): String? {
val element = element(xml) ?: return null
var on = withAttr(element.value, "enabled", "true")
on = withAttr(on, "ip", ADDRESS)
on = withAttr(on, "port", GameTelemetry.CODEMASTERS_PORT.toString())
if (attr(on, "extradata") != null) on = withAttr(on, "extradata", EXTRADATA)
return xml.replaceRange(element.range, on)
}
internal fun turnedOff(xml: String, original: String?): String? {
val element = element(xml) ?: return null
val tag = element.value.drop(1).takeWhile { !it.isWhitespace() }
val before = original?.let { tagRegex(tag).find(it)?.value }
return xml.replaceRange(element.range, before ?: withAttr(element.value, "enabled", "false"))
}
internal fun attr(element: String, name: String): String? =
Regex("\\s$name=\"([^\"]*)\"").find(element)?.groupValues?.get(1)
internal fun withAttr(element: String, name: String, value: String): String {
val existing = Regex("(\\s$name=\")[^\"]*\"")
if (existing.containsMatchIn(element)) return existing.replace(element) { it.groupValues[1] + value + "\"" }
val selfClosing = element.endsWith("/>")
val body = element.dropLast(if (selfClosing) 2 else 1).trimEnd()
return "$body $name=\"$value\"" + if (selfClosing) " />" else ">"
}
private fun tagRegex(tag: String) = Regex("<$tag\\s[^>]*>")
}
@@ -14,11 +14,13 @@ class BottomPageActions(
val fps: () -> Float? = { null },
/** Opens an Android settings page on the bottom screen; the dashboard comes back once [done] is true. */
val openSettings: ((intent: android.content.Intent, done: () -> Boolean) -> Unit)? = null,
/** The focused game's Steam app id as text (or another key for non-Steam programs); null in the Steam menus. */
val runningGame: () -> String? = { null },
)
/** The pages the bottom-screen dashboard offers during a session, in tab order. */
fun sessionBottomPages(actions: BottomPageActions): List<BottomPage> = listOf(
BottomPage("telemetry", R.string.bottom_page_telemetry, Icons.Outlined.Speed) { BottomTelemetryPage(actions.fps) },
BottomPage("telemetry", R.string.bottom_page_telemetry, Icons.Outlined.Speed) { BottomTelemetryPage(actions.fps, actions.runningGame) },
BottomPage("downloads", R.string.bottom_page_downloads, Icons.Outlined.Download) { BottomDownloadsPage() },
BottomPage("notifications", R.string.bottom_page_notifications, Icons.Outlined.Notifications) { BottomNotificationsPage(actions.openSettings) },
BottomPage("screenshots", R.string.bottom_page_screenshots, Icons.Outlined.PhotoLibrary) { BottomScreenshotsPage(actions.takeScreenshot) },
@@ -12,15 +12,19 @@ import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.selection.toggleable
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -28,11 +32,13 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.hud.HudMetrics
import com.droiddeck.launcher.hud.MangoReadings
import com.droiddeck.launcher.runtime.LinuxRuntime
@@ -40,6 +46,7 @@ import com.droiddeck.launcher.session.GameStatusFiles
import com.droiddeck.launcher.session.GameTelemetry
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.Telemetry
import com.droiddeck.launcher.session.TelemetryOutput
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
@@ -61,6 +68,7 @@ private const val THUNDER_MS = 500L
private const val THUNDER_RETRY_MS = 3_000L
private const val ELITE_MS = 1_000L
private const val ELITE_SEARCH_MS = 10_000L
private const val OUTPUT_SCAN_MS = 3_000L
/** What arrives on one telemetry port; written only by that port's listener. */
private class PortTraffic {
@@ -72,9 +80,15 @@ private class PortTraffic {
private data class UnknownTraffic(val port: Int, val packets: Long, val length: Int)
@Composable
fun BottomTelemetryPage(fps: () -> Float?) {
fun BottomTelemetryPage(fps: () -> Float?, runningGame: () -> String? = { null }) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val scope = rememberCoroutineScope()
var outputs by remember { mutableStateOf<List<TelemetryOutput.Game>>(emptyList()) }
var menuGames by remember { mutableStateOf<List<TelemetryOutput.MenuGame>>(emptyList()) }
var running by remember { mutableStateOf<String?>(null) }
var outputFailed by remember { mutableStateOf<String?>(null) }
var rescan by remember { mutableIntStateOf(0) }
val latest = remember { AtomicReference<Pair<Long, Telemetry>?>(null) }
var race by remember { mutableStateOf<Telemetry?>(null) }
var fpsNow by remember { mutableStateOf<Float?>(null) }
@@ -159,6 +173,18 @@ fun BottomTelemetryPage(fps: () -> Float?) {
delay(ELITE_MS)
}
}
LaunchedEffect(Unit) {
menuGames = withContext(Dispatchers.IO) {
runCatching { Library.steamGames(context).mapNotNull { TelemetryOutput.MENU_GAMES[it.appId] }.distinct() }.getOrDefault(emptyList())
}
}
LaunchedEffect(rescan) {
while (isActive) {
outputs = withContext(Dispatchers.IO) { runCatching { TelemetryOutput.scan(Library.compatdataDirs(context)) }.getOrDefault(emptyList()) }
running = runningGame()
delay(OUTPUT_SCAN_MS)
}
}
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(10.dp)) {
DeviceRow(fpsNow, device)
@@ -181,6 +207,32 @@ fun BottomTelemetryPage(fps: () -> Float?) {
Text(stringResource(R.string.bottom_telemetry_help),
fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp))
}
if (outputs.isNotEmpty() || menuGames.isNotEmpty()) TelemetryCard(stringResource(R.string.bottom_telemetry_send_title)) {
for (game in outputs) {
val locked = TelemetryOutput.isRunning(game.prefixId, running)
Row(
Modifier.fillMaxWidth().toggleable(game.on, enabled = !locked, role = Role.Switch) { want ->
scope.launch {
val ok = withContext(Dispatchers.IO) { TelemetryOutput.set(game, want) }
outputFailed = if (ok) null else game.name
rescan++
}
}.padding(vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f).padding(end = 12.dp)) {
Text(game.name, fontSize = 15.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (locked) Text(stringResource(R.string.bottom_telemetry_send_close, game.name), fontSize = 12.sp, color = colors.onSurfaceVariant)
}
Switch(game.on, null, enabled = !locked)
}
}
for (game in menuGames) {
Text(stringResource(R.string.bottom_telemetry_send_menu, game.name, game.setting, game.port), fontSize = 13.sp, color = colors.onSurfaceVariant)
}
if (outputs.isNotEmpty()) Text(stringResource(R.string.bottom_telemetry_send_note), fontSize = 12.sp, color = colors.onSurfaceVariant)
outputFailed?.let { Text(stringResource(R.string.bottom_telemetry_send_failed, it), fontSize = 12.sp, color = colors.error) }
}
for (u in unknown) {
Text(stringResource(R.string.bottom_telemetry_unknown_format, u.port, u.packets, u.length), fontSize = 13.sp,
color = colors.error, modifier = Modifier.padding(horizontal = 4.dp))
+5
View File
@@ -1891,6 +1891,11 @@
<string name="bottom_notifications_count">%1$d notifications</string>
<string name="bottom_notifications_clear">Clear</string>
<string name="bottom_page_screenshots">Screenshots</string>
<string name="bottom_telemetry_send_title">Send dashboard data</string>
<string name="bottom_telemetry_send_note">This changes the game\'s own data output setting. It takes effect the next time the game starts; turning it off puts the old setting back.</string>
<string name="bottom_telemetry_send_close">Close %1$s to change this.</string>
<string name="bottom_telemetry_send_failed">Could not change the settings of %1$s.</string>
<string name="bottom_telemetry_send_menu">%1$s: turn on %2$s in the game\'s settings with IP 127.0.0.1 and port %3$d.</string>
<string name="bottom_shots_where">Saved to Pictures/DroidDeck. Steam screenshots show here too.</string>
<string name="bottom_shots_take">Take screenshot</string>
<string name="bottom_shots_saved">Screenshot saved.</string>
@@ -0,0 +1,83 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
class TelemetryOutputTest {
@get:Rule val tmp = TemporaryFolder()
// DiRT Showdown's own line, as found in its prefix on the Retroid Pocket Duo.
private val showdown = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<hardware_settings_config>\n" +
"\t<audio mono=\"false\" />\n\t<motion enabled=\"true\" ip=\"dbox\" port=\"20777\" delay=\"1\" extradata=\"0\" />\n" +
"</hardware_settings_config>\n"
@Test fun turningOnPointsTheMotionLineHereAndKeepsTheRest() {
val on = TelemetryOutput.turnedOn(showdown)!!
assertTrue(on.contains("<motion enabled=\"true\" ip=\"127.0.0.1\" port=\"20777\" delay=\"1\" extradata=\"3\" />"))
assertEquals(showdown.replace("ip=\"dbox\"", "ip=\"127.0.0.1\"").replace("extradata=\"0\"", "extradata=\"3\""), on)
assertTrue(TelemetryOutput.pointsHere(TelemetryOutput.element(on)!!.value))
assertFalse(TelemetryOutput.pointsHere(TelemetryOutput.element(showdown)!!.value))
}
@Test fun theUdpLineWinsOverTheMotionLineAndLongerTagsAreIgnored() {
val xml = "<x><motion_platform><dbox enabled=\"true\" /></motion_platform>" +
"<motion enabled=\"true\" ip=\"dbox\" port=\"20777\" />" +
"<udp enabled=\"false\" extradata=\"0\" ip=\"127.0.0.1\" port=\"20777\" delay=\"1\" /></x>"
assertTrue(TelemetryOutput.element(xml)!!.value.startsWith("<udp "))
val on = TelemetryOutput.turnedOn(xml)!!
assertTrue(on.contains("<udp enabled=\"true\" extradata=\"3\" ip=\"127.0.0.1\" port=\"20777\" delay=\"1\" />"))
assertTrue(on.contains("<motion enabled=\"true\" ip=\"dbox\" port=\"20777\" />"))
assertNull(TelemetryOutput.element("<x><motion_platform enabled=\"true\" /></x>"))
}
@Test fun turningOffPutsTheOriginalLineBackOrSwitchesItOff() {
val on = TelemetryOutput.turnedOn(showdown)!!
assertEquals(showdown, TelemetryOutput.turnedOff(on, showdown))
assertTrue(TelemetryOutput.turnedOff(on, null)!!.contains("<motion enabled=\"false\" ip=\"127.0.0.1\""))
}
@Test fun missingAttributesAreAdded() {
assertEquals("<udp enabled=\"true\" ip=\"127.0.0.1\" />", TelemetryOutput.withAttr("<udp enabled=\"true\" />", "ip", "127.0.0.1"))
assertEquals("<udp a=\"1\" port=\"20777\">", TelemetryOutput.withAttr("<udp a=\"1\">", "port", "20777"))
assertTrue(TelemetryOutput.pointsHere("<udp enabled=\"true\" ip=\"127.0.0.1\" port=\"20777\" />"))
}
@Test fun scanFindsTheGameAndARoundTripRestoresTheFile() {
val compatdata = tmp.newFolder("steamapps", "compatdata")
val config = configFile(compatdata, "2848447563", "DiRT Showdown")
config.writeText(showdown)
configFile(compatdata, "12345", "Some Other Game").writeText("<hardware_settings_config />")
val games = TelemetryOutput.scan(listOf(compatdata))
assertEquals(listOf("DiRT Showdown"), games.map { it.name })
assertEquals("2848447563", games[0].prefixId)
assertFalse(games[0].on)
assertTrue(TelemetryOutput.set(games[0], true))
assertTrue(File(config.path + TelemetryOutput.ORIGINAL_SUFFIX).isFile)
assertTrue(TelemetryOutput.scan(listOf(compatdata))[0].on)
assertTrue(TelemetryOutput.set(games[0], false))
assertEquals(showdown, config.readText())
assertFalse(File(config.path + TelemetryOutput.ORIGINAL_SUFFIX).exists())
assertFalse(TelemetryOutput.scan(listOf(compatdata))[0].on)
}
@Test fun theRunningGameIsMatchedByItsPrefixId() {
assertTrue(TelemetryOutput.isRunning("2848447563", "2848447563"))
assertTrue(TelemetryOutput.isRunning("-1446519733", "2848447563"))
assertFalse(TelemetryOutput.isRunning("2848447563", "690790"))
assertFalse(TelemetryOutput.isRunning("2848447563", null))
assertTrue(TelemetryOutput.isRunning("2848447563", "program:/games/x.exe"))
}
private fun configFile(compatdata: File, id: String, game: String): File =
File(compatdata, "$id/pfx/drive_c/users/steamuser/Documents/My Games/$game/hardwaresettings/hardware_settings_config.xml")
.apply { parentFile!!.mkdirs() }
}