diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 5abbded77..f7ff85e2c 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -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 diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt b/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt index 958e1c5ae..c623e4223 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt @@ -101,15 +101,22 @@ object Library { libraries: List = 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 = steamLibraries(context).map { it.first }): List = + prefixRoots(context, libraries).map { File(it, "steamapps/compatdata") }.filter { it.isDirectory } + + private fun prefixRoots(context: Context, libraries: List, preferredLibrary: File? = null): List { 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( diff --git a/app/src/main/java/com/droiddeck/launcher/session/TelemetryOutput.kt b/app/src/main/java/com/droiddeck/launcher/session/TelemetryOutput.kt new file mode 100644 index 000000000..eba41fb9a --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/TelemetryOutput.kt @@ -0,0 +1,104 @@ +package com.droiddeck.launcher.session + +import java.io.File + +/** + * Codemasters games keep their UDP / motion output in My Games//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 = 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): List = 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[^>]*>") +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomPages.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomPages.kt index 2cc648b76..da9695cf9 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomPages.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomPages.kt @@ -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 = 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) }, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomTelemetryPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomTelemetryPage.kt index 7d69ee3fb..c599b6fd3 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomTelemetryPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomTelemetryPage.kt @@ -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>(emptyList()) } + var menuGames by remember { mutableStateOf>(emptyList()) } + var running by remember { mutableStateOf(null) } + var outputFailed by remember { mutableStateOf(null) } + var rescan by remember { mutableIntStateOf(0) } val latest = remember { AtomicReference?>(null) } var race by remember { mutableStateOf(null) } var fpsNow by remember { mutableStateOf(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)) diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 312c493e7..a2f1494df 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1891,6 +1891,11 @@ %1$d notifications Clear Screenshots + Send dashboard data + 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. + Close %1$s to change this. + Could not change the settings of %1$s. + %1$s: turn on %2$s in the game\'s settings with IP 127.0.0.1 and port %3$d. Saved to Pictures/DroidDeck. Steam screenshots show here too. Take screenshot Screenshot saved. diff --git a/app/src/test/java/com/droiddeck/launcher/session/TelemetryOutputTest.kt b/app/src/test/java/com/droiddeck/launcher/session/TelemetryOutputTest.kt new file mode 100644 index 000000000..1512ce4a1 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/TelemetryOutputTest.kt @@ -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 = "\n\n" + + "\t\n" + + @Test fun turningOnPointsTheMotionLineHereAndKeepsTheRest() { + val on = TelemetryOutput.turnedOn(showdown)!! + assertTrue(on.contains("")) + 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 = "" + + "" + + "" + assertTrue(TelemetryOutput.element(xml)!!.value.startsWith("")) + assertTrue(on.contains("")) + assertNull(TelemetryOutput.element("")) + } + + @Test fun turningOffPutsTheOriginalLineBackOrSwitchesItOff() { + val on = TelemetryOutput.turnedOn(showdown)!! + assertEquals(showdown, TelemetryOutput.turnedOff(on, showdown)) + assertTrue(TelemetryOutput.turnedOff(on, null)!!.contains("", TelemetryOutput.withAttr("", "ip", "127.0.0.1")) + assertEquals("", TelemetryOutput.withAttr("", "port", "20777")) + assertTrue(TelemetryOutput.pointsHere("")) + } + + @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("") + + 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() } +}