Compare commits

..
Author SHA1 Message Date
Kurt Himebauch 97ab26cb31 fix: stale runtime reuse accepts restaged scripts and rejects tracking pin changes 2026-11-01 00:18:02 -04:00
Kurt Himebauch 69d303873c chore: quick_deploy reuses runtime assets prepared on another branch 2026-10-31 23:59:39 -04:00
The412Banner 8a7022fc14 feat(dual-screen): bottom-screen Dashboard with downloads, notifications, screenshots, Steam chat and In-game stats (#1920)
A Dashboard mode for the second screen of dual-screen handhelds (developed on a Retroid Pocket Duo), the default on dual-screen devices. It opens on Chat at each Steam start and switches to In-game stats when a game starts.

- Downloads: Steam downloads and updates (SD-card libraries too), shader caches and DroidDeck store downloads.
- Notifications: other apps' notifications once access is allowed, kept in memory only.
- Screenshots: a game screenshot without the overlay, and a gallery of DroidDeck's and Steam's screenshots.
- Chat & voice: mic and game volume buttons, and Steam's web chat signed in with the Steam client's own session.
- In-game stats: FPS, CPU, GPU, RAM and battery plus the running game or Steam client type, and a racing dash from Codemasters, Forza and OutGauge games' data output, with War Thunder and Elite Dangerous layouts; speed in km/h or mph.
- Send dashboard data: turns a Codemasters game's data output on for the dash (per game or Automatic) and keeps the original setting to put back.
- DiRT 3 / DiRT Showdown: with their data output on they stop with error 10038 at race end; a ws2_32.dll stand-in (tools/dirt-ws2) is swapped into the prefix while the game runs, skipped on DroidDeck-Proton 11-11.10 which has the fix built in. Same behaviour as DiRTTelemetryErrorFix by RoccoC, based on Carsten Gottschling's fix.

About "telemetry": here it means a racing game's own live driving data (speed, gear, rpm, pedals), not app analytics. For In-game stats no information leaves the device and nothing is shared: the game sends its data to 127.0.0.1 on the same device, DroidDeck only listens there while the page is open and keeps the numbers in memory just long enough to draw them. DroidDeck sends no data about the user or their use of the app; logs leave the device only when the user taps Share logs.
2026-11-01 02:36:57 +00:00
MaxsTechReview bfa61b5139 fix: "DroidDeck isn't responding" on dual-screen handhelds after the bottom screen sits idle (#1917)
The bottom-screen panel handed focus back to the main screen only when it opened or was touched within the last second. When the panel became the active screen later, the paused launcher kept no focused window, so controller input waited until Android reported the app as not responding. The panel now hands focus back whenever it becomes the active screen or gains window focus, unless bottom-screen typing is open or an app the launcher opened is in front.
2026-10-31 20:40:57 -04:00
18 changed files with 305 additions and 65 deletions

No files matched your search

+3 -1
View File
@@ -303,7 +303,9 @@ tasks.named('preBuild').configure { dependsOn(stageGogNotices) }
def verifyRuntimeInputs = tasks.register('verifyRuntimeInputs', Exec) {
mustRunAfter(stageSessionScripts, stageRuntimeAssets)
workingDir rootProject.projectDir
commandLine pythonExecutable, 'tools/release/runtime_inputs.py', 'verify'
def allowStale = (project.findProperty('allowStaleRuntime')
?: localBuildOptions.getProperty('droiddeck.allowStaleRuntime', 'false')).toString().toBoolean()
commandLine([pythonExecutable, 'tools/release/runtime_inputs.py', 'verify'] + (allowStale ? ['--allow-stale-sources'] : []))
}
tasks.configureEach { task ->
if (task.name in ['packageDebug', 'packageRelease']) task.dependsOn(verifyRuntimeInputs)
@@ -919,7 +919,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(android.graphics.Color.BLACK))
},
)
LaunchedEffect(AgentGuest.focusRevision) {
// Also runs when a second screen appears, so Automatic applies then with the running game known.
LaunchedEffect(AgentGuest.focusRevision, secondScreenDisplays.isNotEmpty()) {
val nextGame = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
if (SessionState.mode == SessionService.MODE_RUN) SessionState.program?.let { "program:$it" }
else {
@@ -3132,9 +3133,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
dashboard = if (bottomPages().isEmpty()) null else ({
DroidDeckTheme {
BottomDashboard(
bottomPages(), SessionPrefs.bottomPage(this),
bottomPages(), com.droiddeck.launcher.ui.SessionBottomTab.picked(SessionState.sessionId),
gameStarts = gameStarts,
onPage = { SessionPrefs.setBottomPage(this, it) },
onPage = { com.droiddeck.launcher.ui.SessionBottomTab.pick(SessionState.sessionId, it) },
onClose = { selectSecondScreenMode(SecondScreenMode.NONE) },
onMenu = if (dockDrawer()) ({ drawerOpen = true }) else null,
)
@@ -3151,7 +3152,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
))
// A settings page opened on the bottom screen sits under the dashboard window, so the dashboard hides
// until the setting is on; choosing Dashboard in the menu again shows it sooner.
// until the setting is on, or for at most SETTINGS_WATCH_CHECKS seconds when it is left off (another
// app's page closing cannot be seen); choosing Dashboard in the menu again shows it sooner.
private fun openSettingsBelow(intent: android.content.Intent, done: () -> Boolean) {
val presentation = secondScreenPresentation ?: return
val options = android.app.ActivityOptions.makeBasic().setLaunchDisplayId(presentation.display.displayId)
@@ -3163,23 +3165,34 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (!opened) return
presentation.hide()
var checks = 0
// Show throws if the display went away while the settings page was open, as in showSecondScreen.
fun showAgain() {
try {
presentation.show()
} catch (e: Exception) {
Log.w(TAG, "could not show the dashboard again", e)
if (secondScreenPresentation === presentation) closeSecondScreen(reset = true)
}
}
uiHandler.postDelayed(object : Runnable {
override fun run() {
if (secondScreenPresentation !== presentation || presentation.isShowing) return
if (done()) {
presentation.show()
showAgain()
return
}
if (++checks < SETTINGS_WATCH_CHECKS) uiHandler.postDelayed(this, SETTINGS_WATCH_MS)
if (++checks < SETTINGS_WATCH_CHECKS) uiHandler.postDelayed(this, SETTINGS_WATCH_MS) else showAgain()
}
}, SETTINGS_WATCH_MS)
}
/** Copies the game frame (no overlay) at the size it is shown and saves it to Pictures/DroidDeck. */
private fun captureScreenshot(onDone: (Boolean) -> Unit) {
val width = if (::surfaceView.isInitialized) surfaceView.width else 0
val height = if (::surfaceView.isInitialized) surfaceView.height else 0
if (width <= 0 || height <= 0 || surfaceView.holder.surface?.isValid != true) {
// With the glasses as the output the game is drawn on their surface; the phone's surface is hidden then.
val source = if (glassesOutputActive) glassesScreen?.surfaceView else if (::surfaceView.isInitialized) surfaceView else null
val width = source?.width ?: 0
val height = source?.height ?: 0
if (source == null || width <= 0 || height <= 0 || source.holder.surface?.isValid != true) {
onDone(false)
return
}
@@ -3190,7 +3203,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return
}
try {
android.view.PixelCopy.request(surfaceView, bitmap, { result ->
android.view.PixelCopy.request(source, bitmap, { result ->
if (result != android.view.PixelCopy.SUCCESS) {
bitmap.recycle()
onDone(false)
@@ -53,10 +53,13 @@ object BottomNotifications {
class BottomNotificationListener : NotificationListenerService() {
override fun onListenerConnected() {
BottomNotifications.clear()
runCatching { activeNotifications }.getOrNull()?.sortedBy { it.postTime }?.forEach { BottomNotifications.post(this, it) }
}
override fun onNotificationPosted(sbn: StatusBarNotification) = BottomNotifications.post(this, sbn)
override fun onNotificationRemoved(sbn: StatusBarNotification) = BottomNotifications.remove(sbn.key)
override fun onListenerDisconnected() = BottomNotifications.clear()
}
@@ -100,12 +100,6 @@ object SessionPrefs {
prefs(context).edit().putString("secondScreenPanel", mode).apply()
}
fun bottomPage(context: Context): String? = prefs(context).getString("bottomPage", null)
fun setBottomPage(context: Context, page: String) {
prefs(context).edit().putString("bottomPage", page).apply()
}
fun statsStrip(context: Context): String? = prefs(context).getString("statsStrip", null)
fun setStatsStrip(context: Context, id: String) {
@@ -23,7 +23,7 @@ object SteamDownloads {
val name = SteamDownloadMonitor.value(text, "name") ?: id
names[id] = name
fromManifest(id, name, text)
}
}.let(::onePerApp)
val homes = client?.let { listOf(if (it == "x86_64") SteamDownloadMonitor.STEAM_HOMES[1] else SteamDownloadMonitor.STEAM_HOMES[0]) }
?: SteamDownloadMonitor.STEAM_HOMES
val log = homes.map { File(runtimeRoot, "$it/logs/content_log.txt") }.filter { it.isFile }.maxByOrNull { it.lastModified() }
@@ -32,6 +32,10 @@ object SteamDownloads {
return apps + shaders
}
/** The arm64 and x86-64 Steam homes can both hold an unfinished manifest of one app; the page keys rows by app. */
internal fun onePerApp(downloads: List<SteamDownload>): List<SteamDownload> =
downloads.groupBy { it.appId }.values.map { same -> same.maxBy { it.done } }
internal fun fromManifest(id: String, name: String, text: String): SteamDownload? {
val flags = SteamDownloadMonitor.value(text, "StateFlags")?.toLongOrNull() ?: 0L
if (flags == FULLY_INSTALLED) return null
@@ -56,7 +56,25 @@ class BottomPage(
internal fun pickBottomPage(remembered: String?, ids: List<String>): String? =
ids.firstOrNull { it == remembered } ?: ids.firstOrNull { it == DEFAULT_PAGE } ?: ids.firstOrNull()
/** The page a game start switches to; not saved, so the page the user picked still opens next time. */
/**
* The tab picked during one session. Each Steam session starts with no pick, so the dashboard opens on Chat; reopened
* later in the same session it shows the tab picked last.
*/
internal object SessionBottomTab {
private var session: String? = null
private var tab: String? = null
@Synchronized
fun picked(sessionId: String?): String? = tab.takeIf { sessionId != null && sessionId == session }
@Synchronized
fun pick(sessionId: String?, id: String) {
session = sessionId
tab = id
}
}
/** The page a game start switches to; not remembered as the user's pick. */
internal fun pageForGameStart(ids: List<String>): String? = GAME_PAGE.takeIf { it in ids }
private const val DEFAULT_PAGE = "chat"
@@ -47,7 +47,9 @@ import com.droiddeck.launcher.hud.MangoReadings
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStatusFiles
import com.droiddeck.launcher.session.GameTelemetry
import com.droiddeck.launcher.input.SteamTouchConfig
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.SpeedUnit
import com.droiddeck.launcher.session.StatsDash
@@ -96,6 +98,8 @@ fun BottomTelemetryPage(fps: () -> Float?, runningGame: () -> String? = { null }
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 gameName by remember { mutableStateOf<String?>(null) }
val steamClient = remember { if (SessionState.mode == SessionService.MODE_STEAM) SessionPrefs.activeSteamClientArch(context) else null }
var outputFailed by remember { mutableStateOf<String?>(null) }
var rescan by remember { mutableIntStateOf(0) }
var auto by remember { mutableStateOf(SessionPrefs.telemetryAuto(context)) }
@@ -216,6 +220,11 @@ fun BottomTelemetryPage(fps: () -> Float?, runningGame: () -> String? = { null }
runCatching { Library.steamGames(context).mapNotNull { TelemetryOutput.MENU_GAMES[it.appId] }.distinct() }.getOrDefault(emptyList())
}
}
LaunchedEffect(running) {
val id = running?.toLongOrNull()
gameName = if (id == null) null
else withContext(Dispatchers.IO) { runCatching { SteamTouchConfig.gameName(context, id.toInt()) }.getOrNull() }
}
LaunchedEffect(rescan) {
while (isActive) {
outputs = withContext(Dispatchers.IO) { runCatching { TelemetryOutput.scan(Library.compatdataDirs(context)) }.getOrDefault(emptyList()) }
@@ -226,7 +235,8 @@ fun BottomTelemetryPage(fps: () -> Float?, runningGame: () -> String? = { null }
Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(10.dp)) {
perfTick.let {
StatsStripView(strip, StripData(fpsNow, device, fpsHistory.snapshot(), cpuHistory.snapshot(), gpuHistory.snapshot(), wattsHistory.snapshot(), clock)) {
StatsStripView(strip, StripData(fpsNow, device, fpsHistory.snapshot(), cpuHistory.snapshot(), gpuHistory.snapshot(), wattsHistory.snapshot(), clock,
if (running != null) gameName else steamClient?.let { stringResource(steamClientLabel(it)) })) {
strip = strip.next()
SessionPrefs.setStatsStrip(context, strip.id)
}
@@ -325,6 +335,9 @@ private fun httpGet(url: String): String {
}
/** The Steam client the session runs, shown in the strip's top line while no game runs. */
internal fun steamClientLabel(arch: String): Int = if (arch == "x86_64") R.string.stats_steam_client_x86 else R.string.stats_steam_client_arm
@Composable
private fun ChoiceRow(title: String, value: String, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -166,18 +166,13 @@ object DualScreenPanel {
return ownerTask.takeIf { it >= 0 }
}
internal fun tookFocus(fresh: Boolean, touchedAt: Long, now: Long): Boolean =
fresh || now - touchedAt in 0..TOUCH_FOCUS_MS
private const val TOUCH_FOCUS_MS = 1000L
internal fun returnFocus(context: Context, fromPanel: Boolean = false) {
val task = focusTask(fromPanel) ?: return
runCatching { (context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager).moveTaskToFront(task, 0) }
}
internal fun reclaimFocus(context: Context) {
val task = focusTask(false) ?: return
val task = focusTask(true) ?: return
val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
runCatching {
manager.appTasks.firstOrNull {
@@ -245,21 +240,16 @@ class DualScreenActivity : ComponentActivity() {
}
private var topResumed = false
private var fresh = true
private var touchedAt = Long.MIN_VALUE
override fun onTopResumedActivityChanged(isTopResumedActivity: Boolean) {
super.onTopResumedActivityChanged(isTopResumedActivity)
topResumed = isTopResumedActivity
val took = DualScreenPanel.tookFocus(fresh, touchedAt, android.os.SystemClock.uptimeMillis())
fresh = false
if (isTopResumedActivity && !DualScreenPanel.typingShown) DualScreenPanel.returnFocus(this, fromPanel = took)
if (isTopResumedActivity && !DualScreenPanel.typingShown) DualScreenPanel.returnFocus(this, fromPanel = true)
}
override fun dispatchTouchEvent(event: android.view.MotionEvent): Boolean {
if (event.actionMasked == android.view.MotionEvent.ACTION_DOWN) {
touchedAt = event.downTime
if (topResumed && !DualScreenPanel.typingShown) DualScreenPanel.returnFocus(this, fromPanel = true)
if (event.actionMasked == android.view.MotionEvent.ACTION_DOWN && topResumed && !DualScreenPanel.typingShown) {
DualScreenPanel.returnFocus(this, fromPanel = true)
}
return super.dispatchTouchEvent(event)
}
@@ -39,6 +39,7 @@ import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
@@ -95,13 +96,16 @@ private fun LogoBadge(size: Dp) {
}
}
/** The mark and "DroidDeck" on the left, the running game's name in the middle, the clock on the right. */
@Composable
private fun LogoHeader(clock: String) {
private fun LogoHeader(clock: String, game: String?) {
val colors = MaterialTheme.colorScheme
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.padding(horizontal = 2.dp)) {
Row(Modifier.fillMaxWidth().padding(horizontal = 2.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
DroidDeckLogo(16.dp)
Text("DroidDeck", fontSize = 13.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
if (clock.isNotEmpty()) Text("· $clock", fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
Text(game.orEmpty(), fontSize = 13.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, textAlign = TextAlign.Center,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
if (clock.isNotEmpty()) Text(clock, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
}
}
@@ -146,6 +150,7 @@ internal class StripData(
val gpuHistory: List<Float>,
val wattsHistory: List<Float>,
val clock: String,
val game: String? = null,
)
private fun percentTemp(percent: Int?, temp: Int?): String =
@@ -212,7 +217,7 @@ private fun TilesStrip(d: StripData) {
val gpuPercent: Int? = s?.gpuPercent
val gpuTemp: Int? = s?.gpuTempC
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
LogoHeader(d.clock)
LogoHeader(d.clock, d.game)
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
HistoryTile("FPS", accent, fpsText(d.fps), "fps", d.fpsHistory, 75f)
HistoryTile("CPU", StatsColors.cpu, s?.cpuPercent?.let { "$it%" } ?: "–", s?.cpuTempC?.let { "$it°" } ?: "", d.cpuHistory, 100f)
@@ -248,7 +253,7 @@ private fun RingsStrip(d: StripData) {
val gpuPercent: Int? = s?.gpuPercent
val gpuTemp: Int? = s?.gpuTempC
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
LogoHeader(d.clock)
LogoHeader(d.clock, d.game)
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
RingTile("CPU", StatsColors.cpu, s?.cpuPercent?.let { it / 100f }, s?.cpuPercent?.let { "$it%" } ?: "–", s?.cpuTempC?.let { "$it °C" } ?: "")
RingTile("GPU", StatsColors.gpu, gpuPercent?.let { it / 100f }, gpuPercent?.let { "$it%" } ?: gpuTemp?.let { "$it°" } ?: "–",
+2
View File
@@ -1903,6 +1903,8 @@
<string name="stats_gear">Gear</string>
<string name="stats_speed_units">Speed units</string>
<string name="stats_speed_units_auto">Automatic (%1$s)</string>
<string name="stats_steam_client_arm">Steam Client ARM</string>
<string name="stats_steam_client_x86">Steam Client x86</string>
<string name="stats_throttle">Throttle</string>
<string name="stats_brake">Brake</string>
<string name="stats_lights">Dashboard</string>
@@ -17,6 +17,13 @@ class SteamDownloadsTest {
}
""".trimIndent()
@Test fun anAppUnfinishedInBothSteamHomesIsListedOnce() {
val arm = SteamDownload("220", "Half-Life 2", 10L, 100L)
val x86 = SteamDownload("220", "Half-Life 2", 60L, 100L)
val other = SteamDownload("440", "Team Fortress 2", 5L, 50L)
assertEquals(listOf(x86, other), SteamDownloads.onePerApp(listOf(arm, x86, other)))
}
@Test fun anInstalledGameIsNotADownload() {
assertNull(SteamDownloads.fromManifest("220", "Half-Life 2", manifest(4, 100, 100)))
}
@@ -55,4 +55,17 @@ class BottomTelemetryLapTimeTest {
assertEquals("1:23.456", lapTime(83.456f))
assertEquals("0:05.000", lapTime(5f))
}
@Test fun eachSessionStartsWithoutAPickedTab() {
SessionBottomTab.pick("2026-11-01-01-steam", "screenshots")
assertEquals("screenshots", SessionBottomTab.picked("2026-11-01-01-steam"))
assertNull(SessionBottomTab.picked("2026-11-01-02-steam"))
assertNull(SessionBottomTab.picked(null))
assertEquals("chat", pickBottomPage(SessionBottomTab.picked("2026-11-01-02-steam"), listOf("telemetry", "chat", "screenshots")))
}
@Test fun theStripNamesTheSteamClient() {
assertEquals(com.droiddeck.launcher.R.string.stats_steam_client_x86, steamClientLabel("x86_64"))
assertEquals(com.droiddeck.launcher.R.string.stats_steam_client_arm, steamClientLabel("arm64"))
}
}
@@ -81,13 +81,4 @@ class DualScreenPanelOwnerTest {
DualScreenPanel.show(app, 2, 10)
assertEquals(10, DualScreenPanel.focusTask(fromPanel = false))
}
@Test fun thePanelTookFocusWhenItJustOpenedOrWasJustTouched() {
assertTrue(DualScreenPanel.tookFocus(fresh = true, touchedAt = Long.MIN_VALUE, now = 5_000L))
assertTrue(DualScreenPanel.tookFocus(fresh = false, touchedAt = 4_700L, now = 5_000L))
assertTrue(DualScreenPanel.tookFocus(fresh = false, touchedAt = 5_000L, now = 5_000L))
assertFalse(DualScreenPanel.tookFocus(fresh = false, touchedAt = 3_500L, now = 5_000L))
assertFalse(DualScreenPanel.tookFocus(fresh = false, touchedAt = Long.MIN_VALUE, now = 5_000L))
assertFalse(DualScreenPanel.tookFocus(fresh = false, touchedAt = 6_000L, now = 5_000L))
}
}
@@ -774,6 +774,18 @@ def proton_has_dirt_fix(proton):
return False
WINE_DLL_DIRS = ("/lib/wine/i386-windows", "/lib/wine/x86_64-windows", "/lib/wine/aarch64-windows", "/lib/wine",
"/lib/wine/fakedlls", "/lib64/wine", "/lib64/wine/fakedlls", "/lib64/wine/x86_64-windows")
def is_wine_dll_link(path):
"""A link into a Wine DLL folder: the rule Proton uses to tell its own DLLs in a prefix (file_is_wine_builtin_dll)."""
try:
return os.path.islink(path) and os.path.dirname(os.readlink(path)).endswith(WINE_DLL_DIRS)
except OSError:
return False
def prefix_ws2(prefix):
return Path(prefix) / "pfx/drive_c/windows/syswow64/ws2_32.dll"
@@ -811,17 +823,24 @@ def swap_dirt_ws2(prefix):
def restore_dirt_ws2(prefix, proton):
"""Puts the prefix's own syswow64/ws2_32.dll back if the stand-in is still there; true when it changed something."""
"""Puts a Wine syswow64/ws2_32.dll back if the stand-in is still there; true when it changed something.
That is the prefix's own one, unless it was a link to a Wine DLL folder and the game ran on another Proton since
the swap: Proton then relinked the prefix's other DLLs to itself but left the stand-in, so a link to the running
Proton's ws2_32.dll goes back instead. Anything else (a native file, a link to a mod's DLL) goes back as it was."""
target = prefix_ws2(prefix)
saved = target.with_name(target.name + DIRT_SAVED)
if os.path.lexists(saved):
if is_dirt_stand_in(target) or not os.path.lexists(target):
own = proton_ws2(proton)
had_saved = os.path.lexists(saved)
if had_saved:
if os.path.lexists(target) and not is_dirt_stand_in(target):
os.unlink(saved)
return False
if not own.is_file() or not is_wine_dll_link(saved) or os.path.realpath(saved) == os.path.realpath(own):
os.replace(saved, target)
return True
os.unlink(saved)
return False
own = proton_ws2(proton)
if is_dirt_stand_in(target) and own.is_file():
if own.is_file() and (is_dirt_stand_in(target) or (had_saved and not os.path.lexists(target))):
link = target.with_name(target.name + ".droiddeck-tmp")
if os.path.lexists(link):
os.unlink(link)
@@ -838,9 +857,12 @@ def wait_forwarding_signals(process):
except OSError:
pass
for signum in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
signal.signal(signum, forward)
code = process.wait()
previous = {signum: signal.signal(signum, forward) for signum in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP)}
try:
code = process.wait()
finally:
for signum, handler in previous.items():
signal.signal(signum, handler)
return 128 - code if code < 0 else code
@@ -850,7 +872,11 @@ def start(launch, launch_env, digest, after=None):
try:
return wait_forwarding_signals(process)
finally:
after()
try:
after()
except OSError as error:
print("droiddeck-game-env: DiRT telemetry fix: prefix ws2_32 not put back (%s); the next launch does it" % error,
file=sys.stderr)
if digest:
code = subprocess.run(launch, env=launch_env, check=False).returncode
if code == 0:
@@ -948,14 +974,21 @@ def main():
if app_id and prefix and len(command) > 1 and command[1] == "waitforexitandrun":
try:
if dirt_prefix:
swap_dirt_ws2(dirt_prefix)
after = lambda: restore_dirt_ws2(dirt_prefix, command[0])
swap_dirt_ws2(dirt_prefix)
print("droiddeck-game-env: DiRT telemetry fix: ws2_32 stand-in in the prefix until the game exits",
file=sys.stderr)
elif restore_dirt_ws2(prefix, command[0]):
print("droiddeck-game-env: DiRT telemetry fix: put the prefix's own ws2_32 back", file=sys.stderr)
except OSError as error:
print("droiddeck-game-env: DiRT telemetry fix not applied (%s)" % error, file=sys.stderr)
if after:
after = None
try:
restore_dirt_ws2(dirt_prefix, command[0])
except OSError as undo:
print("droiddeck-game-env: DiRT telemetry fix: prefix ws2_32 not put back (%s); Wine uses its own copy "
"and the next launch puts the file back" % undo, file=sys.stderr)
sync = load_sync()
launch, launch_env = select_sync(command, env, sync)
if launch[0] != command[0]:
@@ -965,7 +998,16 @@ def main():
print("droiddeck-game-env: %s could not start (%s); stock launch" % (launch[0], error), file=sys.stderr)
launch, launch_env = command, without_pack(launch_env, env)
record_stock(sync, launch, launch_env)
return start(launch, launch_env, digest, after)
try:
return start(launch, launch_env, digest, after)
except OSError:
if after:
try:
after()
except OSError as error:
print("droiddeck-game-env: DiRT telemetry fix: prefix ws2_32 not put back (%s); the next launch does it" % error,
file=sys.stderr)
raise
if __name__ == "__main__":
+2 -1
View File
@@ -23,7 +23,8 @@ while IFS= read -r dir; do
done < <(ls -d "${sdk_dir}"/build-tools/* 2>/dev/null | sort -rV)
[[ -n "${build_tools}" ]] || { echo "No build-tools with aapt, zipalign and apksigner under ${sdk_dir}." >&2; exit 1; }
./gradlew -q :app:assembleRelease
# Runtime assets from another branch are fine for a Kotlin/UI loop; CI and releases stay strict.
./gradlew -q -PallowStaleRuntime=true :app:assembleRelease
(
cd "$(dirname "${signing_env}")"
set -a; . "${signing_env}"; set +a
+26 -4
View File
@@ -31,6 +31,16 @@ SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app
'app/src/main/cpp/waylandcomp/src/spatialpose_shm.h',
'app/src/main/cpp/adrenotools/src/hook/kgsl.h',
'app/src/main/assets/graphics_driver/adrenotools-turnip25.1.0.tzst']
# Gradle reads these pins directly, so prepared assets built from other pins cannot be reused.
STRICT_SOURCE_PREFIXES = ('tools/packs/tracking/',)
def staged_scripts(root):
"""Outputs Gradle's stageSessionScripts copies from source on every build."""
overlay = root / 'tools/linuxfs/overlay'
patterns = ['usr/local/bin/droiddeck-*', 'usr/local/bin/steam-compatibility', 'usr/bin/**/*']
return {'assets/linuxfs/' + path.relative_to(overlay).as_posix()
for pattern in patterns for path in overlay.glob(pattern) if path.is_file()}
def digest(path):
@@ -149,19 +159,31 @@ def record(root=ROOT):
(root / MANIFEST).write_text(json.dumps(data, sort_keys=True, indent=2) + '\n')
def verify(root=ROOT):
def verify(root=ROOT, stale_sources_ok=False):
try:
data = json.loads((root / MANIFEST).read_text())
except (OSError, ValueError):
raise ValueError('Runtime inputs have not been prepared. Run tools/build_local.sh.')
if data.get('version') != 1 or data.get('sources') != sources(root):
if data.get('version') != 1:
raise ValueError('Runtime sources changed since preparation. Run tools/build_local.sh.')
current = sources(root)
if data.get('sources') != current:
if not stale_sources_ok:
raise ValueError('Runtime sources changed since preparation. Run tools/build_local.sh.')
recorded = data.get('sources') or {}
changed = sorted(name for name in recorded.keys() | current.keys() if recorded.get(name) != current.get(name))
pinned = [name for name in changed if name.startswith(STRICT_SOURCE_PREFIXES)]
if pinned:
raise ValueError('Runtime pins changed since preparation (' + ', '.join(pinned) + '). Run tools/build_local.sh.')
print('Warning: reusing runtime assets prepared from other sources (run tools/build_local.sh if these matter):\n '
+ '\n '.join(changed[:20]) + ('\n ...' if len(changed) > 20 else ''), file=sys.stderr)
for name in required():
if name not in data['outputs']:
raise ValueError('Runtime manifest missing ' + name)
restaged = staged_scripts(root) if stale_sources_ok else set()
for name, output in data['outputs'].items():
path = root / output['path']
if not path.is_file() or digest(path) != output['sha256']:
if not path.is_file() or (digest(path) != output['sha256'] and name not in restaged):
raise ValueError('Missing or changed runtime input: ' + name + '. Run tools/build_local.sh.')
if outputs(root) != {name: output['path'] for name, output in data['outputs'].items()}:
raise ValueError('Runtime file set changed. Run tools/build_local.sh.')
@@ -224,7 +246,7 @@ if __name__ == '__main__':
if sys.argv[1] == 'record':
record()
elif sys.argv[1] == 'verify':
verify()
verify(stale_sources_ok='--allow-stale-sources' in sys.argv[2:])
elif sys.argv[1] == 'apk':
check_apk(sys.argv[2])
else:
+84
View File
@@ -111,6 +111,26 @@ class DirtTelemetryFixTest(unittest.TestCase):
self.assertEqual(os.readlink(self.target), str(newer))
self.assertFalse(os.path.lexists(self.target.with_name("ws2_32.dll.droiddeck-original")))
def test_after_a_proton_switch_the_running_protons_file_goes_back(self):
MODULE["swap_dirt_ws2"](self.prefix)
other = Path(self.tmp.name) / "GE-Proton/proton"
other_own = other.parent / "files/lib/wine/i386-windows/ws2_32.dll"
other_own.parent.mkdir(parents=True)
other_own.write_bytes(b"MZ GE wine ws2_32")
other.write_text("")
self.assertTrue(MODULE["restore_dirt_ws2"](self.prefix, other))
self.assertEqual(os.readlink(self.target), str(other_own))
self.assertFalse(os.path.lexists(self.target.with_name("ws2_32.dll.droiddeck-original")))
def test_restore_follows_a_proton_reached_through_a_linked_folder(self):
MODULE["swap_dirt_ws2"](self.prefix)
pack = Path(self.tmp.name) / "pack"
(pack / "files/lib/wine").mkdir(parents=True)
(pack / "files/lib/wine/i386-windows").symlink_to(self.own.parent)
(pack / "proton").write_text("")
self.assertTrue(MODULE["restore_dirt_ws2"](self.prefix, pack / "proton"))
self.assertEqual(os.readlink(self.target), str(self.own))
def test_a_stand_in_left_without_the_saved_link_is_replaced_by_protons_own_file(self):
self.target.unlink()
self.target.write_bytes(self.stand_in.read_bytes())
@@ -139,6 +159,22 @@ class DirtTelemetryFixTest(unittest.TestCase):
self.assertEqual(os.readlink(self.target), str(self.own))
self.assertFalse(os.path.lexists(self.target.with_name("ws2_32.dll.droiddeck-original")))
def test_a_proton_that_cannot_start_leaves_the_prefix_as_it_was(self):
self.config("DiRT Showdown", self.SHOWDOWN_ON)
self.proton.write_text("not a program")
self.proton.chmod(0o644)
runner = Path(self.tmp.name) / "run.py"
runner.write_text("import runpy, sys\nmain = runpy.run_path(sys.argv[1])['main']\nmain.__globals__['DIRT_WS2'] = sys.argv[2]\n"
"sys.argv = [sys.argv[1]] + sys.argv[3:]\nsys.exit(main())\n")
home = Path(self.tmp.name) / "home"
home.mkdir()
result = subprocess.run([sys.executable, str(runner), str(BIN / "droiddeck-game-env"), str(self.stand_in), *self.command()],
env={**os.environ, "HOME": str(home), "STEAM_COMPAT_DATA_PATH": str(self.prefix)}, text=True, capture_output=True)
self.assertNotEqual(result.returncode, 0)
self.assertIn("DiRT telemetry fix: ws2_32 stand-in", result.stderr)
self.assertEqual(os.readlink(self.target), str(self.own))
self.assertFalse(os.path.lexists(self.target.with_name("ws2_32.dll.droiddeck-original")))
def test_launch_with_telemetry_off_leaves_the_prefix_alone(self):
self.config("DiRT Showdown", self.SHOWDOWN_DEFAULT)
self.proton.write_text("#!" + sys.executable + "\nimport os\nprint(os.environ.get('WINEDLLOVERRIDES', ''))\n")
@@ -151,6 +187,54 @@ class DirtTelemetryFixTest(unittest.TestCase):
self.assertNotIn("ws2_32=n,b", result.stdout)
self.assertEqual(os.readlink(self.target), str(self.own))
def test_a_failed_put_back_does_not_end_the_launch_with_an_error(self):
def fail():
raise OSError(28, "No space left on device")
stderr = io.StringIO()
with mock.patch("sys.stderr", stderr):
code = MODULE["start"]([sys.executable, "-c", "raise SystemExit(0)"], dict(os.environ), None, fail)
self.assertEqual(code, 0)
self.assertIn("not put back", stderr.getvalue())
def test_a_half_done_swap_is_put_back(self):
saved = self.target.with_name("ws2_32.dll.droiddeck-original")
os.replace(self.target, saved)
self.assertTrue(MODULE["restore_dirt_ws2"](self.prefix, self.proton))
self.assertEqual(os.readlink(self.target), str(self.own))
self.assertFalse(os.path.lexists(saved))
def test_a_native_ws2_32_goes_back_as_it_was_after_a_proton_switch(self):
self.target.unlink()
self.target.write_bytes(b"MZ a mod's own ws2_32")
MODULE["swap_dirt_ws2"](self.prefix)
other = Path(self.tmp.name) / "GE-Proton/proton"
(other.parent / "files/lib/wine/i386-windows").mkdir(parents=True)
(other.parent / "files/lib/wine/i386-windows/ws2_32.dll").write_bytes(b"MZ GE wine ws2_32")
other.write_text("")
self.assertTrue(MODULE["restore_dirt_ws2"](self.prefix, other))
self.assertFalse(self.target.is_symlink())
self.assertEqual(self.target.read_bytes(), b"MZ a mod's own ws2_32")
def test_a_link_to_a_mods_ws2_32_goes_back_as_it_was(self):
mod = Path(self.tmp.name) / "mods/ws2_32.dll"
mod.parent.mkdir()
mod.write_bytes(b"MZ a mod's ws2_32")
self.target.unlink()
self.target.symlink_to(mod)
MODULE["swap_dirt_ws2"](self.prefix)
other = Path(self.tmp.name) / "GE-Proton/proton"
(other.parent / "files/lib/wine/i386-windows").mkdir(parents=True)
(other.parent / "files/lib/wine/i386-windows/ws2_32.dll").write_bytes(b"MZ GE wine ws2_32")
other.write_text("")
self.assertTrue(MODULE["restore_dirt_ws2"](self.prefix, other))
self.assertEqual(os.readlink(self.target), str(mod))
def test_start_gives_the_signal_handlers_back(self):
import signal
before = {s: signal.getsignal(s) for s in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP)}
MODULE["start"]([sys.executable, "-c", "pass"], dict(os.environ), None, lambda: None)
self.assertEqual(before, {s: signal.getsignal(s) for s in before})
def test_start_puts_the_file_back_after_the_game_exits(self):
calls = []
code = MODULE["start"]([sys.executable, "-c", "raise SystemExit(3)"], dict(os.environ), None, lambda: calls.append("restored"))
+36
View File
@@ -88,6 +88,42 @@ class RuntimeInputsTest(unittest.TestCase):
with self.assertRaisesRegex(ValueError, 'sources changed'):
runtime.verify(self.root)
def test_dev_loop_can_reuse_assets_from_other_sources(self):
runtime.record(self.root)
self.source.write_text('new implementation')
with mock.patch('sys.stderr', new_callable=io.StringIO) as stderr:
runtime.verify(self.root, stale_sources_ok=True)
self.assertIn('tools/linuxfs/preload/test.c', stderr.getvalue())
def test_dev_loop_still_rejects_changed_outputs(self):
runtime.record(self.root)
(self.root / 'app/src/main/jniLibs/arm64-v8a/libproot.so').write_bytes(b'old APK binary')
with self.assertRaisesRegex(ValueError, 'changed runtime input'):
runtime.verify(self.root, stale_sources_ok=True)
def test_dev_loop_accepts_restaged_session_scripts(self):
script = self.root / 'tools/linuxfs/overlay/usr/local/bin/droiddeck-test'
staged = self.root / 'app/src/main/assets/linuxfs/usr/local/bin/droiddeck-test'
for path in (script, staged):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text('old script')
runtime.record(self.root)
script.write_text('new script')
staged.write_text('new script')
with mock.patch('sys.stderr', new_callable=io.StringIO):
runtime.verify(self.root, stale_sources_ok=True)
with self.assertRaisesRegex(ValueError, 'sources changed'):
runtime.verify(self.root)
def test_dev_loop_rejects_changed_tracking_pins(self):
pins = self.root / 'tools/packs/tracking/release.env'
pins.parent.mkdir(parents=True)
pins.write_text('OPENCV_VERSION=4.10.0')
runtime.record(self.root)
pins.write_text('OPENCV_VERSION=4.11.0')
with self.assertRaisesRegex(ValueError, 'pins changed'):
runtime.verify(self.root, stale_sources_ok=True)
def test_changed_quest_source_rejects_old_outputs(self):
source = self.root / 'tools/quest/kgsl_compat.c'
source.parent.mkdir(parents=True)