Compare commits

..
Author SHA1 Message Date
The412Banner 17b578b7cf fix: Samsung boost retries a failed connection with reasons, and "not needed" when the game keeps up
- Samsung clocks: a failed connection is tried 4 times a session (again after 5, 15 and 30 s) and
  again at the next game, instead of staying off until the app restarts. Each failed try is in
  boost.log with the step it was on and the error ("failed while reading the service's level table
  (EOFException)", "the service did not connect within 3 s ..."). The summary lists every failed try.
  Only a phone without Samsung's firmware library is not asked again.
- The socket from a failed try is closed.
- Check the boost: when the game kept up without the boost for more than half of the boost's turns,
  the verdict is "not needed for this game" instead of a percentage that reads as a loss.
2026-11-01 17:05:34 +00:00
The412Banner 0d82557957 feat: Performance boost switch for any phone, with Samsung clock floors and a boost report
Settings > Performance > Boost gets two switches.

Performance boost: the game's busiest threads are named to Android's
performance hint service (ADPF), which moves them to the fastest cores
while the game falls behind (GameThreadHints, so far Odin 3 only). Now on
any Android 12+ phone; on by default only on the Odin 3, where it was
measured. On a Samsung phone it also holds Samsung's CPU, GPU and memory
bus clock floors through the performance service in Samsung's firmware
(SamsungPerf, no Samsung library in the app), renewed every 500 ms since
Samsung holds a request for at most a second. Both let go when the game
keeps up, the phone is too hot or battery saver is on.

boost.log in each session's logs: whether each part came on and can be
seen working (threads on the fastest cores, raised minimum clocks), a
status line every 30 s of play that says why the boost is off when it is,
and a summary.

Check the boost: the boost is on and paused in one-minute windows in the
order on, paused, paused, on (so a phone warming up favours neither side),
the first minute of play and 5 s after each switch are not counted, and
the summary ends with a verdict. No verdict when heat or battery saver
held the boost back for more than a quarter of its turns.
2026-11-01 01:31:15 +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
63 changed files with 1198 additions and 4438 deletions

No files matched your search

-3
View File
@@ -274,9 +274,6 @@ jobs:
if: steps.comet.outputs.cache-hit != 'true'
run: python3 tools/components/prepare.py comet
- name: Build the DiRT 3 / DiRT Showdown ws2_32 stand-in
run: python3 tools/components/prepare.py dirt-ws2
- name: Prepare graphics driver variants
run: python3 tools/quest/build-driver.py "$ANDROID_HOME/ndk/$NDK_VERSION"
- name: Record and pack prepared components
-8
View File
@@ -69,14 +69,6 @@
</intent-filter>
<meta-data android:name="android.accessibilityservice" android:resource="@xml/home_button_service" />
</service>
<service android:name=".session.BottomNotificationListener"
android:label="@string/bottom_notifications_listener"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE"
android:exported="true">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
<receiver android:name=".core.ShortcutsListingReceiver" android:exported="false"
android:process=":shortcuts_sync">
<intent-filter>
@@ -171,6 +171,8 @@ class FrontEndActivity : ComponentActivity() {
private var zramClient by mutableStateOf(true)
private var vramCapMb by mutableStateOf(0)
private var gpuClockPin by mutableStateOf(false)
private var performanceBoost by mutableStateOf(false)
private var boostCheck by mutableStateOf(false)
private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true)
private var cursorComposite by mutableStateOf(false)
@@ -2242,6 +2244,7 @@ class FrontEndActivity : ComponentActivity() {
fsyncFirst = fsyncFirst,
gamescopeRealtime = gamescopeRealtime,
gpuClockPin = gpuClockPin,
performanceBoost = performanceBoost, boostCheck = boostCheck,
ramCapMb = ramCapMb, vramCapMb = vramCapMb, zramClient = zramClient,
deviceRamMb = (android.app.ActivityManager.MemoryInfo()
.also((getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)::getMemoryInfo).totalMem / (1024 * 1024)).toInt(),
@@ -2259,6 +2262,8 @@ class FrontEndActivity : ComponentActivity() {
onFsyncFirst = { on -> SessionPrefs.setFsyncFirst(this, on); fsyncFirst = on },
onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on },
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
onPerformanceBoost = { on -> SessionPrefs.setPerformanceBoost(this, on); performanceBoost = on },
onBoostCheck = { on -> SessionPrefs.setBoostCheck(this, on); boostCheck = on },
onRamCapMb = { mb -> SessionPrefs.setRamCapMb(this, mb); ramCapMb = mb },
onZramClient = { on -> SessionPrefs.setZramClient(this, on); zramClient = on },
onVramCapMb = { mb -> SessionPrefs.setVramCapMb(this, mb); vramCapMb = mb },
@@ -2475,6 +2480,8 @@ class FrontEndActivity : ComponentActivity() {
zramClient = SessionPrefs.zramClient(this)
vramCapMb = SessionPrefs.vramCapMb(this)
gpuClockPin = SessionPrefs.gpuClockPin(this)
performanceBoost = SessionPrefs.performanceBoost(this)
boostCheck = SessionPrefs.boostCheck(this)
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
prootFastPath = SessionPrefs.prootFastPath(this)
cursorComposite = SessionPrefs.cursorComposite(this)
@@ -120,10 +120,6 @@ import com.droiddeck.launcher.ui.LoadingOverlay
import com.droiddeck.launcher.ui.SessionDrawer
import com.droiddeck.launcher.ui.SessionPausedOverlay
import com.droiddeck.launcher.ui.SecondScreenPresentation
import com.droiddeck.launcher.ui.BottomDashboard
import com.droiddeck.launcher.ui.BottomPage
import com.droiddeck.launcher.ui.sessionBottomPages
import com.droiddeck.launcher.ui.BottomPageActions
import com.droiddeck.launcher.ui.DroidDeckTheme
import com.droiddeck.launcher.wayland.CompositorHost
import com.droiddeck.launcher.wayland.WaylandCompositor
@@ -218,7 +214,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private lateinit var touchscreenGestures: TouchscreenGestures
private var gestureConfig = com.droiddeck.launcher.input.TouchGestureConfig()
private var gestureGame: 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)
private var steamImportAnswered: String? = null
@@ -932,14 +927,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
}
if (nextGame != gestureGame) {
if (nextGame != null) gameStarts++
gestureGame = nextGame
refreshGestureConfig()
}
if (secondScreenDisplays.isNotEmpty()) kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
runCatching { com.droiddeck.launcher.session.TelemetryOutput.applyAutomatic(this@SessionActivity, nextGame) }
}
if (nextGame != gestureGame) { gestureGame = nextGame; refreshGestureConfig() }
}
LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, pipUi, SessionState.suspended) {
if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || pipUi || SessionState.suspended) {
@@ -1189,7 +1177,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
touchAuto = getString(if (usingTouchpad()) R.string.session_touch_auto_touchpad else R.string.session_touch_auto_direct),
fexPreset = fexPreset,
secondScreenMode = secondScreenMode,
dashboardAvailable = bottomPages().isNotEmpty(),
secondScreenDisplays = secondScreenDisplays,
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
@@ -3051,7 +3038,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (secondScreenDisplays.none { it.id == target.displayId }) return
SessionState.secondScreenAutoOpened = true
selectedSecondScreenDisplay = target.displayId
selectSecondScreenMode(SecondScreenMode.opening(SessionPrefs.secondScreenPanel(this), SessionState.deckPad, bottomPages().isNotEmpty()))
selectSecondScreenMode(SecondScreenMode.opening(SessionPrefs.secondScreenPanel(this), SessionState.deckPad))
dualControlsProvisional = ::loading.isInitialized && loading.visible
}
@@ -3059,7 +3046,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (!dualControlsProvisional || pipUi || !started || (::loading.isInitialized && loading.visible)) return
dualControlsProvisional = false
if (secondScreenMode == SecondScreenMode.NONE) return
val wanted = SecondScreenMode.opening(SessionPrefs.secondScreenPanel(this), SessionState.deckPad, bottomPages().isNotEmpty())
val wanted = SecondScreenMode.opening(SessionPrefs.secondScreenPanel(this), SessionState.deckPad)
if (wanted != secondScreenMode) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal()
}
@@ -3129,85 +3116,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
menu = {
DroidDeckTheme { SessionMenu(docked = true) }
},
dashboard = if (bottomPages().isEmpty()) null else ({
DroidDeckTheme {
BottomDashboard(
bottomPages(), SessionPrefs.bottomPage(this),
gameStarts = gameStarts,
onPage = { SessionPrefs.setBottomPage(this, it) },
onClose = { selectSecondScreenMode(SecondScreenMode.NONE) },
onMenu = if (dockDrawer()) ({ drawerOpen = true }) else null,
)
}
}),
)
/** Pages for the bottom-screen dashboard; the dashboard is offered only while at least one exists. */
private fun bottomPages(): List<BottomPage> = sessionBottomPages(BottomPageActions(
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
// until the setting is on; 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)
val opened = listOf(intent, android.content.Intent(android.provider.Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)).any {
runCatching { startActivity(android.content.Intent(it).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK), options.toBundle()) }
.onFailure { e -> Log.w(TAG, "could not open ${it.action} on display ${presentation.display.displayId}", e) }
.isSuccess
}
if (!opened) return
presentation.hide()
var checks = 0
uiHandler.postDelayed(object : Runnable {
override fun run() {
if (secondScreenPresentation !== presentation || presentation.isShowing) return
if (done()) {
presentation.show()
return
}
if (++checks < SETTINGS_WATCH_CHECKS) uiHandler.postDelayed(this, SETTINGS_WATCH_MS)
}
}, 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) {
onDone(false)
return
}
val bitmap = try {
android.graphics.Bitmap.createBitmap(width, height, android.graphics.Bitmap.Config.ARGB_8888)
} catch (_: OutOfMemoryError) {
onDone(false)
return
}
try {
android.view.PixelCopy.request(surfaceView, bitmap, { result ->
if (result != android.view.PixelCopy.SUCCESS) {
bitmap.recycle()
onDone(false)
return@request
}
Thread {
val saved = com.droiddeck.launcher.session.BottomScreenshots.save(applicationContext, bitmap)
bitmap.recycle()
runOnUiThread { onDone(saved) }
}.start()
}, uiHandler)
} catch (_: IllegalArgumentException) {
bitmap.recycle()
onDone(false)
}
}
private fun tapSteamButton() {
if (SessionState.mode == SessionService.MODE_STEAM) {
padBridge?.applyTouch { st -> st.press(com.droiddeck.launcher.input.PadState.GUIDE, true) }
@@ -4603,8 +4513,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private const val TEXT_FIELD_TAP_MS = 1_000L
private const val PAUSED_FRAME_MAX_EDGE = 1920f
private const val PAUSED_FRAME_REDRAW_MS = 150L
private const val SETTINGS_WATCH_MS = 1_000L
private const val SETTINGS_WATCH_CHECKS = 600
private const val TAG = "SessionActivity"
private var startedScreens = 0
@Volatile private var activeInstallWorker: Any? = null
@@ -101,22 +101,15 @@ 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
return (listOfNotNull(preferredLibrary) + libraries).map(::prefixRoot)
val roots = (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(
@@ -43,9 +43,6 @@ class DroidDeckHudHost(context: Context) {
var onPresentingWindowChanged: (() -> Unit)? = null
/** The frame rate the HUD shows; null while the HUD is off and not counting frames. */
val liveFps: Float? get() = if (polling) feed.stats.fps else null
/** The HUD itself changed a setting: a tap cycles the size, a long press locks it. */
var onConfigChanged: (() -> Unit)? = null
@@ -9,22 +9,11 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int) {
NONE("none", R.string.second_mode_none),
KEYBOARD_TRACKPAD("keyboard-trackpad", R.string.second_mode_keyboard_trackpad),
TERMINAL("terminal", R.string.second_mode_terminal),
DECK_CONTROLS("deck-controls", R.string.second_mode_deck_controls),
DASHBOARD("dashboard", R.string.second_mode_dashboard);
DECK_CONTROLS("deck-controls", R.string.second_mode_deck_controls);
companion object {
fun opening(remembered: String?, deckPad: Boolean, dashboard: Boolean = false): SecondScreenMode {
entries.firstOrNull {
it != NONE && it.id == remembered && (it != DECK_CONTROLS || deckPad) && (it != DASHBOARD || dashboard)
}?.let { return it }
// No pick yet: the dashboard. A pick that can't open right now keeps the old fallback.
val picked = entries.any { it != NONE && it.id == remembered }
return when {
dashboard && !picked -> DASHBOARD
deckPad -> DECK_CONTROLS
else -> KEYBOARD_TRACKPAD
}
}
fun opening(remembered: String?, deckPad: Boolean): SecondScreenMode =
entries.firstOrNull { it != NONE && it.id == remembered && (it != DECK_CONTROLS || deckPad) } ?: if (deckPad) DECK_CONTROLS else KEYBOARD_TRACKPAD
}
}
@@ -0,0 +1,485 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.BatteryManager
import android.os.Build
import android.os.PowerManager
import android.util.Log
import com.droiddeck.launcher.core.CpuCores
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import kotlin.math.abs
import kotlin.math.roundToInt
/**
* What the Performance boost did in a session, in boost.log in the session folder and in the app log:
* whether each part (GameThreadHints, SamsungPerf) came on and can be seen working, a status line
* every [STATUS_S] seconds of play with why a part is off, and a summary with a verdict when the
* session ends. Play is time the game presents frames.
*
* With "Check the boost" on, the boost is on and paused in [WINDOW_S]-second windows of play in the
* order on, paused, paused, on, so the frame rate with and without it is compared over the same
* stretch of game, and a steady change such as the phone warming up favours neither side. The first
* [WARMUP_S] seconds of play (loading, shader compiles) and the first [SETTLE_S] seconds after each
* switch are not counted. Seconds the boost should be on but is held back for heat or battery saver
* are counted as [Side.heldBack]; too many and there is no verdict. Seconds it is off because the
* game keeps up without it are counted as [Side.idle]; if that is most of its turns, the boost is
* not needed for the game.
*/
object BoostReport {
private const val TAG = "BoostReport"
private const val STATUS_S = 30
internal const val WARMUP_S = 60
internal const val WINDOW_S = 60
internal const val SETTLE_S = 5
internal const val CHECK_MIN_S = 120 // counted seconds on each side before there is a verdict
internal const val TOO_HOT = "too hot"
internal const val BATTERY_SAVER = "battery saver"
internal const val KEEPS_UP = "game keeps up"
private const val CONFIRM_S = 2 // held this long before the clocks are compared
private const val SAMPLES = 5
private const val SAMPLE_MS = 200L
private const val RAISED = 1.1
private val THERMAL = listOf("none", "light", "moderate", "severe", "critical", "emergency", "shutdown")
private val GPU_MIN_FILES = listOf(
"/sys/class/kgsl/kgsl-3d0/devfreq/min_freq",
"/sys/class/kgsl/kgsl-3d0/min_clock_mhz",
"/sys/kernel/gpu/gpu_min_clock",
)
/** True while Check the boost has the boost paused; GameThreadHints and SamsungPerf let go meanwhile. */
@Volatile var paused = false
private set
/** Seconds of play on one side of a comparison. */
internal class Side {
val fps = ArrayList<Int>()
val milliamps = ArrayList<Int>()
var hottest = 0
/** Seconds the boost should have been on but was held back for heat or battery saver. */
var heldBack = 0
/** Seconds the boost could have been on but was off because the game kept up without it. */
var idle = 0
val seconds get() = fps.size
val average get() = if (fps.isEmpty()) 0.0 else fps.average()
/** The frame rate of the slowest 5 % of seconds. */
val low get() = if (fps.isEmpty()) 0 else fps.sorted()[fps.size / 20]
val draw get() = if (milliamps.isEmpty()) null else milliamps.average()
fun add(f: Int, ma: Int?, thermal: Int, held: Boolean = false, idle: Boolean = false) {
fps.add(f)
ma?.let { milliamps.add(it) }
hottest = maxOf(hottest, thermal)
if (held) heldBack++
if (idle) this.idle++
}
}
/** The CPU a thread last ran on: field 39 of /proc/<tid>/stat. */
internal fun processorOf(stat: String): Int? =
stat.substringAfterLast(')').trim().split(' ').getOrNull(36)?.toIntOrNull()
/** Each core's class by top speed: 2 the fastest, 0 the slowest, 1 between. */
internal fun tiers(maxGhz: Map<Int, Double>): Map<Int, Int> {
val top = maxGhz.values.maxOrNull() ?: return emptyMap()
val bottom = maxGhz.values.minOrNull() ?: top
return maxGhz.mapValues { (_, ghz) -> if (ghz >= top) 2 else if (ghz <= bottom) 0 else 1 }
}
internal fun minutesForVerdict(): Int {
val counted = IntArray(2)
var played = 0
while (counted.any { it < CHECK_MIN_S }) {
val (pause, at) = checkWindow(++played) ?: continue
if (at >= SETTLE_S) counted[if (pause) 1 else 0]++
}
return (played + 59) / 60
}
/**
* Where second [played] of play falls in the check: null in the warm-up, else whether the boost is
* paused and the seconds since it last switched. One window on, then two paused, two on, and so on.
*/
internal fun checkWindow(played: Int): Pair<Boolean, Int>? {
if (played <= WARMUP_S) return null
val n = played - WARMUP_S - 1
if (n < WINDOW_S) return false to n
val m = n - WINDOW_S
return (m / (2 * WINDOW_S) % 2 == 0) to m % (2 * WINDOW_S)
}
/** Why neither part boosts now, from what each says (Samsung's only where the phone has its service). */
internal fun offReasons(cores: String?, samsung: String?): String =
listOfNotNull(cores, samsung).distinct().joinToString().ifEmpty { "no reason given" }
/** Seconds a part was off, by reason, most first. */
internal fun offTimes(off: Map<String, Int>): String =
off.entries.sortedByDescending { it.value }.joinToString { "${clock(it.value)} ${it.key}" }
/** From Check the boost: whether the boost made the game faster where it matters. */
internal fun verdict(on: Side, off: Side): String {
if (on.seconds > 0 && on.heldBack * 4 > on.seconds) {
return "can't tell: the phone was too hot or saving battery for ${share(on.heldBack, on.seconds)} of the time " +
"the boost should have been on, so it was off then; try again with the phone cool and not charging"
}
if (on.seconds < CHECK_MIN_S || off.seconds < CHECK_MIN_S) {
return "too short to tell: play at least ${minutesForVerdict()} minutes with Check the boost on"
}
if (off.average < 1) return "unclear: the game showed no frames while the boost was paused"
if (on.idle * 2 > on.seconds) {
return "not needed for this game: it kept up without the boost for ${share(on.idle, on.seconds)} of the boost's turns, " +
"so the boost was seldom on (${"%.1f".format(Locale.US, on.average)} fps in its turns, ${"%.1f".format(Locale.US, off.average)} fps paused)"
}
val gain = on.average / off.average - 1
val lowGain = if (off.low > 0) on.low.toDouble() / off.low - 1 else 0.0
val onDraw = on.draw
val offDraw = off.draw
val cost = if (onDraw != null && offDraw != null && offDraw > 0) ", for ${percent(onDraw / offDraw - 1)} battery draw" else ""
val numbers = "${percent(gain)} fps on average, ${percent(lowGain)} in the slowest moments$cost"
return when {
gain >= 0.05 || lowGain >= 0.10 -> "worth keeping: $numbers"
gain <= 0.02 && lowGain <= 0.05 -> "not worth keeping for this game: $numbers"
else -> "unclear, a small gain: $numbers"
}
}
private fun percent(x: Double) = (if (x >= 0) "+" else "") + (x * 100).roundToInt() + " %"
private class Run(val file: File, val check: Boolean) {
var started = false
var played = 0
var lastFrames = -1L
val boosted = Side()
val unboosted = Side()
val checkOn = Side()
val checkOff = Side()
val recent = ArrayList<Int>()
var coresBoosted = 0
val onTier = IntArray(3)
val recentTier = IntArray(3)
var samsungHeld = 0
val coresOff = LinkedHashMap<String, Int>()
val samsungOff = LinkedHashMap<String, Int>()
var heldFor = 0
var cpuBefore = emptyMap<String, Long>()
var gpuBefore: Long? = null
var cpuRaised: Map<String, Pair<Long, Long>>? = null
var gpuRaised = false
var clocks: String? = null
var fallen = false
var drops = 0
var batteryStart: Int? = null
var batteryEnd: Int? = null
var firstFrameMs = 0L
var lastFrameMs = 0L
var charging = false
var hottest = 0
val samsungTries = SamsungPerf.tries
var samsungFailures = 0
}
private val letGoCounts = LinkedHashMap<String, Int>()
private var run: Run? = null
private var worker: Thread? = null
/** SamsungPerf let go of its floors, and why. */
fun letGo(why: String) {
synchronized(letGoCounts) { letGoCounts[why] = (letGoCounts[why] ?: 0) + 1 }
}
/** At a session's start, after the boost's parts. The line is for the log. */
@Synchronized
fun start(context: Context, dir: File): String {
stop()
synchronized(letGoCounts) { letGoCounts.clear() }
if (!SessionPrefs.performanceBoost(context)) return "boost report: off"
val r = Run(File(dir, "boost.log"), SessionPrefs.boostCheck(context))
run = r
val soc = if (Build.VERSION.SDK_INT >= 31) ", ${Build.SOC_MANUFACTURER} ${Build.SOC_MODEL}" else ""
line(r, "Performance boost report: ${Build.MANUFACTURER} ${Build.MODEL}, Android ${Build.VERSION.RELEASE}$soc; " +
"Check the boost ${if (r.check) "on" else "off"}. Play is time the game shows frames.")
val app = context.applicationContext
worker = Thread({ watch(app, r) }, "boost-report").apply { isDaemon = true; start() }
return "boost report: ${r.file}"
}
/** At a session's end: the summary. */
@Synchronized
fun stop() {
val r = run ?: return
run = null
worker?.let { it.interrupt(); it.join(2000) }
worker = null
paused = false
runCatching { summary(r) }.onFailure { Log.w(TAG, "summary", it) }
}
private fun line(r: Run, text: String) {
Log.i(TAG, text)
val clock = SimpleDateFormat("HH:mm:ss", Locale.US).format(Date())
runCatching { r.file.appendText("$clock $text\n") }
}
private fun watch(context: Context, r: Run) {
val pm = context.getSystemService(PowerManager::class.java)
val bm = context.getSystemService(BatteryManager::class.java)
val tiers = tiers(CpuCores.all.associateWith { CpuCores.maxGhz(it) ?: 0.0 })
val gpuFile = GPU_MIN_FILES.map(::File).firstOrNull { readLong(it) != null }
try {
while (!Thread.currentThread().isInterrupted) {
Thread.sleep(1000)
second(r, pm, bm, tiers, gpuFile)
}
} catch (_: InterruptedException) {
} catch (t: Throwable) {
Log.w(TAG, "stopped", t)
} finally {
paused = false
}
}
private fun second(r: Run, pm: PowerManager, bm: BatteryManager?, tiers: Map<Int, Int>, gpuFile: File?) {
val frames = WaylandCompositor.gameFrameCount()
val fps = if (r.lastFrames < 0) 0 else (frames - r.lastFrames).toInt()
r.lastFrames = frames
watchClocks(r, gpuFile)
val failed = r.samsungTries.failed
while (r.samsungFailures < failed.size) {
val n = ++r.samsungFailures
line(r, "Samsung clocks: try $n of ${SamsungPerf.TRIES} to connect failed: ${failed[n - 1]}; ${SamsungPerf.retryNote(n)}")
}
if (fps < 1) return
if (!r.started) {
r.started = true
r.batteryStart = battery(bm)
r.firstFrameMs = System.currentTimeMillis()
line(r, "the game shows frames; fastest cores: ${GameThreadHints.startLine.removePrefix("game thread hints: ")}; " +
"Samsung clocks: ${SamsungPerf.state}")
if (r.check) line(r, "check: starts after the first $WARMUP_S s of play, so loading is not counted")
}
r.played++
val thermal = if (Build.VERSION.SDK_INT >= 29) pm.currentThermalStatus else 0
r.hottest = maxOf(r.hottest, thermal)
val ma = milliamps(bm)
if (bm?.isCharging == true) r.charging = true
r.batteryEnd = battery(bm)
r.lastFrameMs = System.currentTimeMillis()
val threads = GameThreadHints.boostedThreads
val samsung = SamsungPerf.holding
(if (samsung || threads.isNotEmpty()) r.boosted else r.unboosted).add(fps, ma, thermal)
if (samsung) r.samsungHeld++
// A part switching on or off can be read between its two fields, with no reason yet: not counted.
val coresWhy = GameThreadHints.offWhy
val samsungWhy = SamsungPerf.offWhy.takeIf { SamsungPerf.connected }
if (threads.isEmpty() && coresWhy != null) r.coresOff[coresWhy] = (r.coresOff[coresWhy] ?: 0) + 1
if (!samsung && samsungWhy != null) r.samsungOff[samsungWhy] = (r.samsungOff[samsungWhy] ?: 0) + 1
val off = if (samsung || threads.isNotEmpty()) null else offReasons(coresWhy, samsungWhy)
val reasons = listOfNotNull(coresWhy, samsungWhy)
val held = off != null && reasons.any { it == TOO_HOT || it == BATTERY_SAVER }
val idle = off != null && !held && reasons.any { it == KEEPS_UP }
val window = if (r.check) checkWindow(r.played) else null
if (window != null) {
val (pause, at) = window
if (at == 0) {
paused = pause
val span = if (r.played <= WARMUP_S + WINDOW_S) WINDOW_S else 2 * WINDOW_S
line(r, "check: boost ${if (pause) "paused" else "on"} for $span s")
}
if (at >= SETTLE_S) (if (pause) r.checkOff else r.checkOn).add(fps, ma, thermal, held && !pause, idle && !pause)
}
if (threads.isNotEmpty()) {
r.coresBoosted++
for (tid in threads) {
val tier = readText(File("/proc/$tid/stat"))?.let(::processorOf)?.let { tiers[it] } ?: continue
r.onTier[tier]++
r.recentTier[tier]++
}
}
r.recent.add(fps)
if (r.played % STATUS_S == 0) {
status(r, threads.size, samsung, off, thermal, bm, ma)
r.recent.clear()
r.recentTier.fill(0)
}
}
/** Whether Samsung's floors show in the kernel's minimum speeds, and whether they stay there. */
private fun watchClocks(r: Run, gpuFile: File?) {
if (!SamsungPerf.holding) {
r.heldFor = 0
r.fallen = false
r.cpuBefore = cpuMins()
r.gpuBefore = gpuFile?.let(::readLong)
return
}
r.heldFor++
if (r.heldFor == CONFIRM_S && r.clocks == null) {
val (now, gpuNow) = peakMins(gpuFile)
val raised = now.filter { (policy, khz) -> r.cpuBefore[policy]?.let { khz > it * RAISED } == true }
r.cpuRaised = raised.mapValues { (policy, khz) -> r.cpuBefore.getValue(policy) to khz }
val cpu = when {
now.isEmpty() -> "the CPU's minimum speed can't be read on this phone"
raised.isEmpty() -> "the CPU's minimum speed did not change (${mhz(now)})"
else -> "CPU minimum speed raised: " + r.cpuRaised!!.entries.joinToString { (policy, ba) ->
"$policy ${ba.first / 1000} -> ${ba.second / 1000} MHz"
}
}
val gpuThen = r.gpuBefore
r.gpuRaised = gpuNow != null && gpuThen != null && gpuNow > gpuThen * RAISED
val gpu = when {
gpuNow == null || gpuThen == null -> "the GPU's minimum speed can't be read on this phone"
r.gpuRaised -> "GPU minimum raised $gpuThen -> $gpuNow (${gpuFile?.path})"
else -> "the GPU's minimum speed did not change ($gpuNow, ${gpuFile?.path})"
}
r.clocks = "$cpu; $gpu; the memory bus can't be seen from an app"
line(r, "Samsung clocks held: library answered ${SamsungPerf.lastResults}; ${r.clocks}")
}
val raised = r.cpuRaised
if (r.heldFor > CONFIRM_S && !raised.isNullOrEmpty()) {
val now = cpuMins()
val fell = raised.any { (policy, ba) -> now[policy]?.let { it < (ba.first + ba.second) / 2 } == true }
if (fell && !r.fallen) {
r.drops++
line(r, "Samsung clocks let go early: the CPU minimum speed fell back (${mhz(now)}) while DroidDeck still asks for it")
} else if (!fell && r.fallen) {
line(r, "Samsung clocks: the CPU minimum speed is back up (${mhz(now)})")
}
r.fallen = fell
}
}
private fun status(r: Run, threads: Int, samsung: Boolean, off: String?, thermal: Int, bm: BatteryManager?, ma: Int?) {
val state = when {
paused -> "paused for the check"
off == null -> "on"
else -> "off now: $off"
}
val checks = r.recentTier.sum()
val cores = if (threads == 0) "no threads" + because(GameThreadHints.offWhy) else "$threads threads" +
if (checks > 0) ", on the fastest cores ${r.recentTier[2] * 100 / checks} % of checks" else ""
val battery = battery(bm)?.let { "$it %" + (ma?.let { m -> ", $m mA" } ?: "") + if (bm?.isCharging == true) ", charging" else "" } ?: "unknown"
line(r, "status: boost $state; fastest cores: $cores; Samsung clocks: ${if (samsung) "held" else "not held" + because(SamsungPerf.offWhy)}; " +
"CPU minimum ${mhz(cpuMins())}; game ${r.recent.average().roundToInt()} fps, slowest second ${r.recent.minOrNull() ?: 0}; " +
"heat ${THERMAL.getOrElse(thermal) { "$thermal" }}; battery $battery")
}
private fun summary(r: Run) {
if (!r.started) {
line(r, "summary: the game never showed frames, nothing to report")
return
}
val all = Side().apply { (r.boosted.fps + r.unboosted.fps).forEach { add(it, null, 0) } }
line(r, "summary: ${clock(r.played)} of play")
val checks = r.onTier.sum()
line(r, "fastest cores: ${GameThreadHints.startLine.removePrefix("game thread hints: ")}; boosted ${share(r.coresBoosted, r.played)} of play" +
(if (checks > 0) "; boosted threads were on the fastest cores in ${share(r.onTier[2], checks)} of checks, " +
"middle ${share(r.onTier[1], checks)}, slowest ${share(r.onTier[0], checks)}" else "") +
(if (GameThreadHints.refused > 0) "; Android refused a hint session ${GameThreadHints.refused} times" else "") +
(if (r.coresOff.isNotEmpty()) "; off ${offTimes(r.coresOff)}" else ""))
val counts = synchronized(letGoCounts) { letGoCounts.entries.joinToString { "${it.value}x ${it.key}" } }
line(r, "Samsung clocks: ${SamsungPerf.state}; held ${share(r.samsungHeld, r.played)} of play; " +
"${r.clocks ?: "never held long enough to look at the clocks"}; let go early ${r.drops} times" +
(if (counts.isNotEmpty()) "; DroidDeck let go: $counts" else "") +
(if (r.samsungOff.isNotEmpty()) "; off ${offTimes(r.samsungOff)}" else ""))
val failed = r.samsungTries.failed
if (failed.isNotEmpty()) {
line(r, "Samsung clocks: ${failed.size} of ${SamsungPerf.TRIES} tries to connect failed: " +
failed.mapIndexed { i, why -> "${i + 1}) $why" }.joinToString("; ") +
if (SamsungPerf.connected) "; connected after that" else "")
}
line(r, "game: ${all.average.roundToInt()} fps average, slowest 5 % of seconds ${all.low}; " +
"boosted ${r.boosted.average.roundToInt()} fps for ${clock(r.boosted.seconds)}, not boosted ${r.unboosted.average.roundToInt()} fps for ${clock(r.unboosted.seconds)} " +
"(not a fair comparison: the boost runs when the game falls behind)")
val start = r.batteryStart
val end = r.batteryEnd
val spanS = ((r.lastFrameMs - r.firstFrameMs) / 1000).toInt()
val battery = when {
r.charging -> "charging, not measured"
start == null || end == null -> "unknown"
else -> "$start % -> $end % over ${clock(spanS)}" + if (spanS >= 300) ", ${(start - end) * 3600 / spanS} % an hour" else ""
}
line(r, "heat: hottest ${THERMAL.getOrElse(r.hottest) { "${r.hottest}" }}; battery: $battery")
if (r.check) {
line(r, "check: counted ${clock(r.checkOn.seconds)} with the boost on and ${clock(r.checkOff.seconds)} paused (first $WARMUP_S s of play and first $SETTLE_S s after each switch skipped)")
line(r, "check, boost on: ${side(r.checkOn)}")
line(r, "check, paused: ${side(r.checkOff)}")
line(r, "verdict: ${verdict(r.checkOn, r.checkOff)}")
} else {
line(r, "verdict: ${working(r)}. Turn on Check the boost for one game to see whether it is worth keeping.")
}
}
private fun working(r: Run): String {
val start = GameThreadHints.startLine
val cores = when {
start != "game thread hints: watching" -> "fastest cores not on (${start.removePrefix("game thread hints: ")})"
r.coresBoosted == 0 && GameThreadHints.refused > 0 -> "fastest cores refused by Android"
r.coresBoosted == 0 -> "fastest cores never on (${mostly(r.coresOff, r.played)})"
else -> "fastest cores working"
}
val samsung = when {
SamsungPerf.state.startsWith("not available") -> "Samsung clocks not available on this phone"
!SamsungPerf.connected && r.samsungTries.failed.isNotEmpty() ->
"Samsung clocks could not connect (${r.samsungTries.failed.last()})"
r.samsungHeld == 0 -> "Samsung clocks never on (${mostly(r.samsungOff, r.played)})"
r.drops > 0 -> "Samsung clocks working, but Samsung let go early ${r.drops} times"
r.cpuRaised.isNullOrEmpty() && !r.gpuRaised -> "Samsung clocks asked for, but the phone shows no raised speed"
else -> "Samsung clocks working and stayed on"
}
return "$cores; $samsung"
}
private fun because(why: String?) = why?.let { " ($it)" } ?: ""
/** The reason a part was off longest, and for how long. */
private fun mostly(off: Map<String, Int>, played: Int) =
off.maxByOrNull { it.value }?.let { "${it.key} ${clock(it.value)} of ${clock(played)}" } ?: "no reason given"
private fun side(s: Side) = "${"%.1f".format(Locale.US, s.average)} fps, slowest 5 % ${s.low}" +
(s.draw?.let { ", battery ${it.roundToInt()} mA" } ?: "") + ", hottest ${THERMAL.getOrElse(s.hottest) { "${s.hottest}" }}" +
(if (s.heldBack > 0) ", held back for heat or battery saver ${share(s.heldBack, s.seconds)}" else "") +
(if (s.idle > 0) ", off because the game kept up ${share(s.idle, s.seconds)}" else "")
private fun share(part: Int, whole: Int) = if (whole == 0) "0 %" else "${part * 100 / whole} %"
private fun clock(seconds: Int) = "%d:%02d".format(seconds / 60, seconds % 60)
private fun mhz(mins: Map<String, Long>) = if (mins.isEmpty()) "unknown" else mins.values.joinToString("/") { "${it / 1000}" } + " MHz"
/** The highest CPU and GPU minimums over [SAMPLES] readings [SAMPLE_MS] apart, so a floor between two renewals is still seen. */
private fun peakMins(gpuFile: File?): Pair<Map<String, Long>, Long?> {
val cpu = LinkedHashMap<String, Long>()
var gpu: Long? = null
repeat(SAMPLES) { i ->
if (i > 0) Thread.sleep(SAMPLE_MS)
cpuMins().forEach { (policy, khz) -> cpu[policy] = maxOf(cpu[policy] ?: 0L, khz) }
gpuFile?.let(::readLong)?.let { g -> gpu = maxOf(gpu ?: 0L, g) }
}
return cpu to gpu
}
/** Each CPU policy's minimum speed in kHz, as the kernel holds it now. */
private fun cpuMins(): Map<String, Long> =
File("/sys/devices/system/cpu/cpufreq").listFiles { f -> f.name.startsWith("policy") }.orEmpty()
.sortedBy { it.name.removePrefix("policy").toIntOrNull() ?: 0 }
.mapNotNull { p -> readLong(File(p, "scaling_min_freq"))?.let { p.name to it } }
.toMap()
private fun battery(bm: BatteryManager?): Int? =
bm?.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)?.takeIf { it in 0..100 }
private fun milliamps(bm: BatteryManager?): Int? {
val raw = bm?.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW) ?: return null
if (raw == 0L || raw == Long.MIN_VALUE) return null
return (abs(BatteryComponent.toMicroamps(raw)) / 1000).toInt()
}
private fun readText(f: File): String? = try { f.readText() } catch (_: Exception) { null }
private fun readLong(f: File): Long? = readText(f)?.trim()?.toLongOrNull()
}
@@ -1,62 +0,0 @@
package com.droiddeck.launcher.session
import android.app.Notification
import android.content.Context
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import androidx.compose.runtime.mutableStateListOf
import androidx.core.app.NotificationManagerCompat
/** One notification for the bottom-screen list. Kept in memory only; never written to disk or logs. */
data class BottomNotification(val key: String, val app: String, val title: String, val text: String, val postedAt: Long)
/**
* Notifications from other apps for the bottom screen, so a message can be read without leaving the game.
* Works only after the user allows DroidDeck notification access in Android settings.
*/
object BottomNotifications {
val items = mutableStateListOf<BottomNotification>()
fun granted(context: Context): Boolean =
context.packageName in NotificationManagerCompat.getEnabledListenerPackages(context)
internal fun keep(own: String, pkg: String, ongoing: Boolean, groupSummary: Boolean, title: String, text: String): Boolean =
pkg != own && !ongoing && !groupSummary && (title.isNotBlank() || text.isNotBlank())
internal fun add(list: MutableList<BottomNotification>, item: BottomNotification) {
list.removeAll { it.key == item.key }
list.add(0, item)
while (list.size > MAX_ITEMS) list.removeAt(list.lastIndex)
}
fun clear() = items.clear()
internal fun post(context: Context, sbn: StatusBarNotification) {
val n = sbn.notification ?: return
val extras = n.extras
val title = extras?.getCharSequence(Notification.EXTRA_TITLE)?.toString().orEmpty()
val text = (extras?.getCharSequence(Notification.EXTRA_BIG_TEXT) ?: extras?.getCharSequence(Notification.EXTRA_TEXT))?.toString().orEmpty()
if (!keep(context.packageName, sbn.packageName, sbn.isOngoing, (n.flags and Notification.FLAG_GROUP_SUMMARY) != 0, title, text)) return
val app = runCatching {
val pm = context.packageManager
pm.getApplicationLabel(pm.getApplicationInfo(sbn.packageName, 0)).toString()
}.getOrDefault(sbn.packageName)
add(items, BottomNotification(sbn.key, app, title, text, sbn.postTime))
}
internal fun remove(key: String) {
items.removeAll { it.key == key }
}
private const val MAX_ITEMS = 30
}
class BottomNotificationListener : NotificationListenerService() {
override fun onListenerConnected() {
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)
}
@@ -1,97 +0,0 @@
package com.droiddeck.launcher.session
import android.content.ContentValues
import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/** A screenshot for the bottom-screen gallery: one DroidDeck took (a MediaStore [uri]) or one Steam saved (a [file]). */
data class BottomShot(val uri: Uri?, val file: File?, val takenAt: Long, val steam: Boolean) {
val model: Any get() = uri ?: file!!
}
/** Game frames DroidDeck saves to Pictures/DroidDeck, plus the screenshots Steam keeps under userdata. */
object BottomScreenshots {
private const val FOLDER = "DroidDeck"
private const val QUALITY = 95
private const val LIMIT = 120
internal fun fileName(at: Long): String =
"DroidDeck_" + SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date(at)) + ".jpg"
fun save(context: Context, bitmap: Bitmap, at: Long = System.currentTimeMillis()): Boolean = runCatching {
val name = fileName(at)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val resolver = context.contentResolver
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, name)
put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
put(MediaStore.Images.Media.DATE_TAKEN, at)
put(MediaStore.Images.Media.RELATIVE_PATH, "${Environment.DIRECTORY_PICTURES}/$FOLDER")
put(MediaStore.Images.Media.IS_PENDING, 1)
}
val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) ?: return false
val written = runCatching {
resolver.openOutputStream(uri)?.use { bitmap.compress(Bitmap.CompressFormat.JPEG, QUALITY, it) } == true
}.getOrDefault(false)
if (!written) {
resolver.delete(uri, null, null)
return false
}
resolver.update(uri, ContentValues().apply { put(MediaStore.Images.Media.IS_PENDING, 0) }, null, null)
true
} else {
@Suppress("DEPRECATION")
val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), FOLDER)
if (!dir.isDirectory && !dir.mkdirs()) return false
val file = File(dir, name)
file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.JPEG, QUALITY, it) }
android.media.MediaScannerConnection.scanFile(context, arrayOf(file.path), arrayOf("image/jpeg"), null)
true
}
}.getOrDefault(false)
/** Newest first, at most [LIMIT]. */
fun list(context: Context, runtimeRoot: File): List<BottomShot> =
(own(context) + steam(runtimeRoot)).sortedByDescending { it.takenAt }.take(LIMIT)
private fun own(context: Context): List<BottomShot> = runCatching {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
@Suppress("DEPRECATION")
val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), FOLDER)
return dir.listFiles { f -> f.isFile && f.name.endsWith(".jpg", true) }.orEmpty()
.map { BottomShot(null, it, it.lastModified(), steam = false) }
}
val shots = ArrayList<BottomShot>()
context.contentResolver.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.DATE_TAKEN, MediaStore.Images.Media.DATE_ADDED),
"${MediaStore.Images.Media.RELATIVE_PATH} = ?", arrayOf("${Environment.DIRECTORY_PICTURES}/$FOLDER/"),
"${MediaStore.Images.Media.DATE_ADDED} DESC",
)?.use { c ->
while (c.moveToNext() && shots.size < LIMIT) {
val taken = c.getLong(1).takeIf { it > 0L } ?: (c.getLong(2) * 1000L)
shots += BottomShot(android.content.ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, c.getLong(0)),
null, taken, steam = false)
}
}
shots
}.getOrDefault(emptyList())
/** The .jpg files in userdata/<account>/760/remote/<app>/screenshots of each Steam home; the thumbnails folder is skipped. */
internal fun steam(runtimeRoot: File): List<BottomShot> =
SteamDownloadMonitor.STEAM_HOMES.flatMap { home ->
File(runtimeRoot, "$home/userdata").listFiles { f -> f.isDirectory }.orEmpty().flatMap { account ->
File(account, "760/remote").listFiles { f -> f.isDirectory }.orEmpty().flatMap { app ->
File(app, "screenshots").listFiles { f -> f.isFile && f.name.endsWith(".jpg", true) }.orEmpty().toList()
}
}
}.map { BottomShot(null, it, it.lastModified(), steam = true) }
}
@@ -1,232 +0,0 @@
package com.droiddeck.launcher.session
import java.nio.ByteBuffer
import java.nio.ByteOrder
/** One reading from a racing game's telemetry. Fractions are 0..1; null means the game does not send it. */
data class Telemetry(
val source: String,
val speedKmh: Float? = null,
val rpm: Float? = null,
val maxRpm: Float? = null,
val gear: String? = null,
val throttle: Float? = null,
val brake: Float? = null,
val lap: Int? = null,
val laps: Int? = null,
val position: Int? = null,
val fuel: Float? = null,
val currentLapS: Float? = null,
val lastLapS: Float? = null,
val bestLapS: Float? = null,
/** G-force as the game sends it (lateral, longitudinal) and steering from -1 (left) to 1 (right). */
val gLat: Float? = null,
val gLon: Float? = null,
val steer: Float? = null,
/** Front left, front right, rear left, rear right. */
val tireTempsC: List<Float>? = null,
val turboBar: Float? = null,
val engineTempC: Float? = null,
val oilTempC: Float? = null,
/** OutGauge dashboard lights that are on, as GameTelemetry.DL_* bits. */
val lights: Int? = null,
)
/**
* Racing telemetry games send over UDP to 127.0.0.1. Each format has its own port, the one the game or
* its common tools use by default:
* - [CODEMASTERS_PORT]: DiRT Rally 1/2, DiRT 4, GRID ("extradata 3" float array), DiRT Showdown (152-byte packet).
* - [FORZA_PORT]: Forza Motorsport 7/2023 and Forza Horizon 4/5 "Data Out" (Sled and Dash).
* - [OUTGAUGE_PORT]: BeamNG.drive and Live for Speed OutGauge.
*/
object GameTelemetry {
const val CODEMASTERS_PORT = 20777
const val FORZA_PORT = 5300
const val OUTGAUGE_PORT = 4444
val PORTS = listOf(CODEMASTERS_PORT, FORZA_PORT, OUTGAUGE_PORT)
// Games send to 127.0.0.1; on Android InetAddress.getLoopbackAddress() is ::1, which IPv4 packets never reach.
val LISTEN_ADDRESS: java.net.InetAddress = java.net.InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1))
fun parse(port: Int, data: ByteArray, length: Int): Telemetry? = runCatching {
val buf = ByteBuffer.wrap(data, 0, length).order(ByteOrder.LITTLE_ENDIAN)
when (port) {
CODEMASTERS_PORT -> codemasters(buf, length)
FORZA_PORT -> forza(buf, length)
OUTGAUGE_PORT -> outGauge(buf, length)
else -> null
}
}.getOrNull()
private const val MPS_TO_KMH = 3.6f
private const val GRAVITY = 9.81f
// OutGauge DashLights / ShowLights bits (Live for Speed InSim; BeamNG uses the same values).
const val DL_SHIFT = 1
const val DL_HANDBRAKE = 4
const val DL_PITSPEED = 8
const val DL_TC = 16
const val DL_ABS = 1024
// Float indexes of the Codemasters packet; engine rpm values are sent divided by 10. Older games
// (DiRT Showdown) send only the first 38 floats, so lap count, position, fuel and max rpm are missing there.
private const val CM_LAP_TIME = 1
private const val CM_SPEED = 7
private const val CM_THROTTLE = 29
private const val CM_STEER = 30
private const val CM_BRAKE = 31
private const val CM_GEAR = 33
private const val CM_G_LAT = 34
private const val CM_G_LON = 35
private const val CM_LAP = 36
private const val CM_RPM = 37
private const val CM_POSITION = 39
private const val CM_FUEL = 45
private const val CM_FUEL_CAPACITY = 46
private const val CM_LAPS = 60
private const val CM_LAST_LAP = 62
private const val CM_MAX_RPM = 63
private const val CM_MIN_FLOATS = 38
internal fun codemasters(buf: ByteBuffer, length: Int): Telemetry? {
if (length < CM_MIN_FLOATS * 4) return null
val floats = length / 4
fun f(i: Int) = if (i < floats) buf.getFloat(i * 4) else 0f
val gear = f(CM_GEAR).toInt()
val capacity = f(CM_FUEL_CAPACITY)
return Telemetry(
source = "Codemasters",
speedKmh = f(CM_SPEED) * MPS_TO_KMH,
rpm = f(CM_RPM) * 10f,
maxRpm = (f(CM_MAX_RPM) * 10f).takeIf { it > 0f },
// Neutral is 0; DiRT Rally 2.0 reports reverse as 10, older games as -1.
gear = when {
gear == 0 -> "N"
gear < 0 || gear == 10 -> "R"
else -> gear.toString()
},
throttle = f(CM_THROTTLE).coerceIn(0f, 1f),
brake = f(CM_BRAKE).coerceIn(0f, 1f),
lap = f(CM_LAP).toInt() + 1,
laps = f(CM_LAPS).toInt().takeIf { it > 0 },
position = f(CM_POSITION).toInt().takeIf { it > 0 },
fuel = if (capacity > 0f) (f(CM_FUEL) / capacity).coerceIn(0f, 1f) else null,
currentLapS = f(CM_LAP_TIME).takeIf { it > 0f },
lastLapS = f(CM_LAST_LAP).takeIf { it > 0f },
gLat = f(CM_G_LAT),
gLon = f(CM_G_LON),
steer = f(CM_STEER).coerceIn(-1f, 1f),
)
}
// Forza "Data Out": Sled is 232 bytes; the Dash block follows it (FM7 311, FM 2023 331). Horizon 4/5 send
// 324 bytes with 12 extra bytes before the Dash block.
private const val FORZA_SLED = 232
private const val FORZA_FM7 = 311
private const val FORZA_HORIZON = 324
private const val FORZA_FM2023 = 331
private const val HORIZON_SHIFT = 12
internal fun forza(buf: ByteBuffer, length: Int): Telemetry? {
if (length < FORZA_SLED) return null
val racing = buf.getInt(0) != 0
val maxRpm = buf.getFloat(8)
val rpm = buf.getFloat(16)
val dash = when (length) {
FORZA_FM7, FORZA_FM2023 -> FORZA_SLED
FORZA_HORIZON -> FORZA_SLED + HORIZON_SHIFT
else -> -1
}
if (dash < 0) return Telemetry(source = "Forza", rpm = rpm, maxRpm = maxRpm.takeIf { it > 0f })
if (!racing) return Telemetry(source = "Forza")
val gear = buf.get(dash + 75).toInt() and 0xFF
// Tire temperatures are read as Fahrenheit, as community Data Out parsers do; not checked on a device.
val tiresF = (0 until 4).map { buf.getFloat(dash + 24 + it * 4) }
return Telemetry(
source = "Forza",
speedKmh = buf.getFloat(dash + 12) * MPS_TO_KMH,
rpm = rpm,
maxRpm = maxRpm.takeIf { it > 0f },
gear = if (gear == 0) "R" else gear.toString(),
throttle = (buf.get(dash + 71).toInt() and 0xFF) / 255f,
brake = (buf.get(dash + 72).toInt() and 0xFF) / 255f,
lap = (buf.getShort(dash + 68).toInt() and 0xFFFF) + 1,
position = (buf.get(dash + 70).toInt() and 0xFF).takeIf { it > 0 },
fuel = buf.getFloat(dash + 44).coerceIn(0f, 1f),
currentLapS = buf.getFloat(dash + 60).takeIf { it > 0f },
lastLapS = buf.getFloat(dash + 56).takeIf { it > 0f },
bestLapS = buf.getFloat(dash + 52).takeIf { it > 0f },
gLat = buf.getFloat(20) / GRAVITY,
gLon = buf.getFloat(28) / GRAVITY,
steer = (buf.get(dash + 76).toFloat() / 127f).coerceIn(-1f, 1f),
tireTempsC = tiresF.takeIf { f -> f.any { it > 0f } }?.map { (it - 32f) * 5f / 9f },
)
}
// OutGauge: 92 bytes, or 96 with the optional id at the end.
private const val OUTGAUGE_SIZE = 92
internal fun outGauge(buf: ByteBuffer, length: Int): Telemetry? {
if (length < OUTGAUGE_SIZE) return null
val gear = buf.get(10).toInt() and 0xFF
return Telemetry(
source = "OutGauge",
speedKmh = buf.getFloat(12) * MPS_TO_KMH,
rpm = buf.getFloat(16),
gear = when (gear) {
0 -> "R"
1 -> "N"
else -> (gear - 1).toString()
},
throttle = buf.getFloat(48).coerceIn(0f, 1f),
brake = buf.getFloat(52).coerceIn(0f, 1f),
fuel = buf.getFloat(28).coerceIn(0f, 1f),
turboBar = buf.getFloat(20).takeIf { it != 0f },
engineTempC = buf.getFloat(24).takeIf { it != 0f },
oilTempC = buf.getFloat(36).takeIf { it != 0f },
lights = buf.getInt(44).takeIf { buf.getInt(40) != 0 },
)
}
}
/** Games that publish their state locally without any setup: War Thunder's web page and Elite Dangerous' Status.json. */
object GameStatusFiles {
const val WAR_THUNDER_STATE = "http://127.0.0.1:8111/state"
private const val ELITE_APP = "359320"
private const val ELITE_STATUS = "pfx/drive_c/users/steamuser/Saved Games/Frontier Developments/Elite Dangerous/Status.json"
const val WAR_THUNDER_ROWS = 12
/** War Thunder's own labels (for example "TAS, km/h") with their values, while a match runs. */
internal fun warThunder(json: String): List<Pair<String, String>> {
val state = org.json.JSONObject(json)
if (!state.optBoolean("valid", false)) return emptyList()
return state.keys().asSequence().filter { it != "valid" }.mapNotNull { key ->
val value = state.opt(key) as? Number ?: return@mapNotNull null
key to if (value.toDouble() % 1.0 == 0.0) value.toLong().toString() else "%.1f".format(java.util.Locale.US, value.toDouble())
}.toList()
}
fun eliteStatusFile(runtimeRoot: java.io.File, mounts: Map<String, java.io.File>): java.io.File? {
val libraries = SteamDownloadMonitor.manifests(runtimeRoot, mounts).mapNotNull { it.parentFile } +
SteamDownloadMonitor.STEAM_HOMES.map { java.io.File(runtimeRoot, "$it/steamapps") }
return libraries.distinct().map { java.io.File(it, "compatdata/$ELITE_APP/$ELITE_STATUS") }.firstOrNull { it.isFile }
}
data class Elite(val fuelMain: Double?, val fuelReserve: Double?, val cargo: Double?, val pips: List<Int>?, val legal: String?, val balance: Long?)
/** Null while Elite is at its menus (Status.json then carries only the timestamp and flags). */
internal fun elite(json: String): Elite? {
val s = org.json.JSONObject(json)
val fuel = s.optJSONObject("Fuel")
val pips = s.optJSONArray("Pips")?.let { a -> (0 until a.length()).map { a.optInt(it) } }
if (fuel == null && pips == null && !s.has("Cargo") && !s.has("Balance")) return null
return Elite(
fuelMain = fuel?.optDouble("FuelMain")?.takeIf { !it.isNaN() },
fuelReserve = fuel?.optDouble("FuelReservoir")?.takeIf { !it.isNaN() },
cargo = s.optDouble("Cargo").takeIf { !it.isNaN() },
pips = pips,
legal = s.optString("LegalState").takeIf { it.isNotEmpty() },
balance = if (s.has("Balance")) s.optLong("Balance") else null,
)
}
}
@@ -36,6 +36,9 @@ import kotlin.math.abs
* under 90 fps against 2-7% unboosted. A game with no frames (Factorio's benchmark, a loading screen)
* or one falling behind the panel is boosted; one holding pace keeps what it has for [PACE_LEAVE_S]
* seconds and is then let go.
*
* Part of the Performance boost switch, on by default only where it was measured ([measuredHere]).
* Another phone's HAL may boost differently, or not at all.
*/
object GameThreadHints {
private const val TAG = "GameThreadHints"
@@ -46,21 +49,38 @@ object GameThreadHints {
private const val LEAVE = 0.15 // a capped game's main thread idles to ~30% on a prime core; under 0.3 it hopped back and forth
private const val MAX_THREADS = 2 // one per prime core; a third would be sped up in place instead
private const val TOP_PROCESSES = 3
private const val PACE_WINDOW_S = 3
private const val PACE_LEAVE_S = 10
internal const val PACE_WINDOW_S = 3
internal const val PACE_LEAVE_S = 10
private const val PACE_TOLERANCE = 0.08
/** Busy, but not the game: the app itself and the Steam client, whose UI would otherwise hold the prime cores. */
private val NOT_GAMES = setOf("steam", "steamwebhelper")
/** The Odin 3 (CQ8725S), where the boost was measured. */
val measuredHere: Boolean get() = Build.VERSION.SDK_INT >= 31 && Build.SOC_MODEL == "CQ8725S"
private var worker: Thread? = null
/** For BoostReport: the last start line, the threads boosted now, why none is, and hint sessions refused. */
@Volatile internal var startLine = "game thread hints: off"
@Volatile internal var boostedThreads = emptySet<Int>()
@Volatile internal var offWhy: String? = null
@Volatile internal var refused = 0
/** At a session's start. The line is for the log. */
@Synchronized
fun start(context: Context): String {
if (!SessionPrefs.gameThreadHints(context)) return "game thread hints: off"
// Measured on the Odin 3 (CQ8725S) only; another HAL may boost differently, or not at all.
if (Build.VERSION.SDK_INT < 31 || Build.SOC_MODEL != "CQ8725S") return "game thread hints: Odin 3 only"
offWhy = "starting"
return begin(context).also {
startLine = it
if (it != "game thread hints: watching") offWhy = it.removePrefix("game thread hints: ")
}
}
private fun begin(context: Context): String {
refused = 0
if (!SessionPrefs.performanceBoost(context)) return "game thread hints: off"
if (Build.VERSION.SDK_INT < 31) return "game thread hints: needs Android 12"
val hm = context.getSystemService(PerformanceHintManager::class.java)
?: return "game thread hints: no PerformanceHintManager"
val pm = context.getSystemService(PowerManager::class.java)
@@ -92,10 +112,16 @@ object GameThreadHints {
val fps = (frames.last() - frames.first()).toDouble() / (frames.size - 1).coerceAtLeast(1)
val paced = frames.size > PACE_WINDOW_S && holdsPace(fps, SessionState.refreshHz.toDouble())
pacedFor = if (paced) pacedFor + 1 else 0
// Not SEVERE: the Odin 3 reports it once its skin reaches 50 C, a couple of minutes into any game.
val spare = pm.isPowerSaveMode || pm.currentThermalStatus >= PowerManager.THERMAL_STATUS_CRITICAL
val spare = when {
BoostReport.paused -> "check pause"
pm.isPowerSaveMode -> BoostReport.BATTERY_SAVER
// Not SEVERE: the Odin 3 reports it once its skin reaches 50 C, a couple of minutes into any game.
pm.currentThermalStatus >= PowerManager.THERMAL_STATUS_CRITICAL -> BoostReport.TOO_HOT
pacedFor >= PACE_LEAVE_S -> BoostReport.KEEPS_UP
else -> null
}
val next = when {
spare || pacedFor >= PACE_LEAVE_S -> emptySet()
spare != null -> emptySet()
paced -> pick(boosted, busy.filterKeys { it in boosted })
else -> pick(boosted, busy)
}
@@ -103,10 +129,12 @@ object GameThreadHints {
session = update(hm, session, next)
// No session means a thread exited in between: tried again next second.
boosted = if (session == null) emptySet() else next
boostedThreads = boosted
Log.i(TAG, (if (session == null && next.isNotEmpty()) "no session for " else "boosting ") +
next.joinToString { "${readName("/proc/$it/comm")}/$it ${((busy[it] ?: 0.0) * 100).toInt()}%" }.ifEmpty { "nothing" } +
" (game ${fps.toInt()} fps${if (paced) ", holding pace" else ""})")
}
offWhy = offReason(spare, boosted, paced, next)
}
session?.reportActualWorkDuration(TARGET_NS * 3 / 2)
Thread.sleep(REPORT_MS)
@@ -116,17 +144,28 @@ object GameThreadHints {
Log.w(TAG, "stopped", t)
} finally {
session?.close()
boostedThreads = emptySet()
}
}
/** Why no thread is boosted, for the log; null while one is. [spare] is why the boost is held back, if it is. */
internal fun offReason(spare: String?, boosted: Set<Int>, paced: Boolean, next: Set<Int>): String? = when {
spare != null -> spare
boosted.isNotEmpty() -> null
paced -> BoostReport.KEEPS_UP
next.isEmpty() -> "no thread busy enough"
else -> "Android refused the hint"
}
/** A new session over [tids] in place of [session]; null for none. The set changes seldom, so no setThreads. */
private fun update(hm: PerformanceHintManager, session: PerformanceHintManager.Session?, tids: Set<Int>): PerformanceHintManager.Session? {
session?.close()
if (tids.isEmpty()) return null
return try {
hm.createHintSession(tids.toIntArray(), TARGET_NS)
hm.createHintSession(tids.toIntArray(), TARGET_NS).also { if (it == null) refused++ }
} catch (t: RuntimeException) {
Log.w(TAG, "createHintSession", t)
refused++
null
}
}
@@ -0,0 +1,313 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.net.LocalServerSocket
import android.net.LocalSocket
import android.os.Build
import android.os.IBinder
import android.os.Parcel
import android.os.PowerManager
import android.system.Os
import android.system.OsConstants
import android.system.StructPollfd
import android.util.Log
import com.droiddeck.launcher.wayland.WaylandCompositor
import com.samsung.sdk.sperf.Boost
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.InputStream
import java.lang.reflect.InvocationTargetException
import java.util.concurrent.CopyOnWriteArrayList
import kotlin.random.Random
/**
* Samsung's CPU, GPU and memory-bus clock floors, from the performance service in Samsung's firmware.
* DroidDeck talks to it directly, the way Samsung's Galaxy Performance SDK 1.0.0 does, so the SDK is
* not needed: the binder service [SERVICE] sends the phone's level table over a local socket, and the
* firmware library [LIBRARY] ([Boost]) holds a level. Other phones have neither, and nothing happens.
*
* The floors are those of the SDK's CPU, GPU and bus presets (the middle of five levels, at least four
* cores online), asked for with a timeout of at most [HOLD_MS], so Samsung lets go on its own if the
* app dies. Samsung may hold a request for less than asked (1 s on an SM8850 Galaxy Z Fold), so they
* are renewed every [renewMs].
*
* A phone without the firmware library is not asked again until the app restarts. Where the library
* is there, a failed connection is tried again [TRIES] times a session, each failure with its reason
* in [Tries.failed], and again at the next session.
*/
object SamsungPerf {
private const val TAG = "SamsungPerf"
private const val LIBRARY = "perfsdk.performance.samsung"
private const val SERVICE = "perfsdkservice"
private const val DESCRIPTOR = "com.samsung.android.perfsdkservice.IPerfSDKService"
private const val CALL_INIT = IBinder.FIRST_CALL_TRANSACTION // initPerfSDK(socket name): Int
private const val CALL_PACKAGE = IBinder.FIRST_CALL_TRANSACTION + 1 // getAllowedPkgName(): String
private const val ASK_LEVELS = 10
private const val SOCKET_TIMEOUT_MS = 3000
// Boost.requestBoost types
internal const val CPU_MIN = 0
internal const val GPU_MIN = 2
internal const val BUS_MIN = 4
internal const val CPU_CORES_MIN = 6
private const val LEVEL = 2
private const val CORES = 4
internal const val HOLD_MS = 5000
private const val SEEN_HOLD_MS = 1000
internal const val TRIES = 4
private val RETRY_S = intArrayOf(5, 15, 30)
/** Half the hold, and no later than half the shortest hold Samsung has been seen to use. */
internal fun renewMs(holdMs: Int): Long = (minOf(holdMs, SEEN_HOLD_MS) / 2).coerceAtLeast(100).toLong()
/** The floors the phone offers, five values each from low to high, and the longest timeout (≤ 0: none). */
internal class Levels(val cpu: IntArray, val gpu: IntArray, val bus: IntArray, val maxTimeoutMs: Int)
/** The service's answer to [ASK_LEVELS] in little-endian ints: the floors, then the ceilings, unused here. */
internal fun readLevels(stream: InputStream): Levels {
val input = DataInputStream(stream)
fun next() = Integer.reverseBytes(input.readInt())
fun five() = IntArray(5) { next() }
repeat(3) { next() }
val timeout = next()
val levels = Levels(five(), five(), five(), timeout)
repeat(3 + 1 + 15) { next() } // level counts, the ceilings' timeout, CPU, GPU and bus ceilings
return levels
}
/** One Boost.requestBoost call. */
internal data class Floor(val type: Int, val value: Int, val timeoutMs: Int)
internal fun floors(levels: Levels): List<Floor> {
val timeout = if (levels.maxTimeoutMs > 0) minOf(HOLD_MS, levels.maxTimeoutMs) else HOLD_MS
return listOf(
Floor(CPU_MIN, levels.cpu[LEVEL], timeout),
Floor(CPU_CORES_MIN, CORES, timeout),
Floor(GPU_MIN, levels.gpu[LEVEL], timeout),
Floor(BUS_MIN, levels.bus[LEVEL], timeout),
).filter { it.value > 0 }
}
/** One session's tries to connect: why each failed, and whether all [TRIES] did. */
internal class Tries {
val failed = CopyOnWriteArrayList<String>()
@Volatile var gaveUp = false
}
/** What the log says after try [n] failed. */
internal fun retryNote(n: Int): String =
if (n < TRIES) "trying again in ${RETRY_S[n - 1]} s" else "no more tries until the next game"
/** A failed try's reason: the step it was on and what went wrong there. */
internal fun failure(step: String, t: Throwable): String {
val cause = (t as? InvocationTargetException)?.targetException ?: t
return "failed while $step (${cause.javaClass.simpleName}${cause.message?.takeIf { it.isNotBlank() }?.let { ": $it" } ?: ""})"
}
private val connectLock = Any()
@Volatile private var floors: List<Floor>? = null
@Volatile private var unavailable: String? = null
private var socket: LocalSocket? = null // kept open for the process's life, as the SDK does
@Volatile internal var tries = Tries()
private class Failed(val why: String) : Exception(why)
/** Null where there is no Samsung service (the reason in [unavailable]) or this try failed (the reason in [t]). */
private fun connect(t: Tries): List<Floor>? = synchronized(connectLock) { connectLocked(t) }
private fun connectLocked(t: Tries): List<Floor>? {
floors?.let { return it }
if (unavailable != null) return null
try {
System.loadLibrary(LIBRARY)
} catch (_: UnsatisfiedLinkError) {
unavailable = "no Samsung performance library"
offWhy = unavailable
Log.i(TAG, "not available: $unavailable")
return null
}
var step = "looking up Samsung's performance service"
var client: LocalSocket? = null
try {
val service = Class.forName("android.os.ServiceManager").getMethod("getService", String::class.java)
.invoke(null, SERVICE) as IBinder? ?: throw Failed("Samsung's performance service ($SERVICE) is not running")
val name = "PERFSDK_SOC_" + Random.nextInt(36 * 36 * 36 * 36 * 36).toString(36).padStart(5, '0')
step = "opening a socket for the service"
val server = LocalServerSocket(name) // the service connects to it; Closeable only from Android 10
val accepted = try {
step = "asking the service to connect"
val init = call(service, CALL_INIT, { writeString(name) }, { readInt() })
step = "asking the service for the package name"
val pkg = call(service, CALL_PACKAGE, {}, { readString() })
if (!pkg.isNullOrEmpty()) Boost.setPkgName(pkg)
Log.i(TAG, "service: init $init, package $pkg")
step = "waiting for the service to connect"
val poll = StructPollfd().apply { fd = server.fileDescriptor; events = OsConstants.POLLIN.toShort() }
if (Os.poll(arrayOf(poll), SOCKET_TIMEOUT_MS) < 1) {
throw Failed("the service did not connect within ${SOCKET_TIMEOUT_MS / 1000} s (it answered $init, package ${pkg ?: "none"})")
}
server.accept()
} finally {
server.close()
}
client = accepted
step = "reading the service's level table"
accepted.soTimeout = SOCKET_TIMEOUT_MS
DataOutputStream(accepted.outputStream).apply { writeInt(Integer.reverseBytes(ASK_LEVELS)); flush() }
val levels = readLevels(accepted.inputStream)
Log.i(TAG, "levels: cpu ${levels.cpu.joinToString()} / gpu ${levels.gpu.joinToString()} / " +
"bus ${levels.bus.joinToString()}, max ${levels.maxTimeoutMs} ms")
val found = floors(levels)
if (found.isEmpty()) {
throw Failed("the level table has no usable floors (cpu ${levels.cpu.joinToString()} / gpu ${levels.gpu.joinToString()} / bus ${levels.bus.joinToString()})")
}
socket = accepted
client = null
floors = found
return found
} catch (e: Throwable) {
val why = (e as? Failed)?.why ?: failure(step, e)
t.failed.add(why)
offWhy = "could not connect"
Log.w(TAG, "try ${t.failed.size} of $TRIES failed: $why", e.takeIf { it !is Failed })
return null
} finally {
client?.let { runCatching { it.close() } }
}
}
private fun <T> call(service: IBinder, code: Int, write: Parcel.() -> Unit, read: Parcel.() -> T): T {
val data = Parcel.obtain()
val reply = Parcel.obtain()
try {
data.writeInterfaceToken(DESCRIPTOR)
data.write()
if (!service.transact(code, data, reply, 0)) throw Failed("the service does not take call $code")
reply.readException()
return reply.read()
} finally {
reply.recycle()
data.recycle()
}
}
private var worker: Thread? = null
/** For BoostReport: whether the floors are held now, why not, and what the library answered when they were asked for. */
@Volatile internal var holding = false
@Volatile internal var offWhy: String? = null
@Volatile internal var lastResults = emptyList<Int>()
internal val connected get() = floors != null
/** For BoostReport. */
internal val state: String
get() = unavailable?.let { "not available: $it" }
?: floors?.let { f ->
val hold = f.minOf { it.timeoutMs }
"connected, floors " + f.joinToString { "${TYPE_NAMES[it.type]} ${it.value}" } +
", asked for $hold ms at a time, renewed every ${renewMs(hold)} ms"
}
?: tries.let { t ->
when {
t.gaveUp -> "could not connect in $TRIES tries (last: ${t.failed.lastOrNull()})"
t.failed.isNotEmpty() -> "connecting, try ${t.failed.size + 1} of $TRIES"
else -> "connecting"
}
}
internal fun floorValue(type: Int): Int? = floors?.firstOrNull { it.type == type }?.value
private val TYPE_NAMES = mapOf(CPU_MIN to "CPU", GPU_MIN to "GPU", BUS_MIN to "bus", CPU_CORES_MIN to "cores")
/** At a session's start. The line is for the log. */
@Synchronized
fun start(context: Context): String {
if (!SessionPrefs.performanceBoost(context)) return "samsung boost: off"
unavailable?.let { return "samsung boost: $it" }
val app = context.applicationContext
worker?.interrupt()
offWhy = "starting"
val t = Tries()
tries = t
worker = Thread({ run(app, t) }, "samsung-boost").apply { isDaemon = true; start() }
return "samsung boost: watching"
}
/** At a session's end. */
@Synchronized
fun stop() {
worker?.interrupt()
worker = null
}
private fun run(context: Context, t: Tries) {
var boosting = false
try {
var found = connect(t)
while (found == null && unavailable == null && t.failed.size < TRIES) {
Thread.sleep(RETRY_S[t.failed.size - 1] * 1000L)
found = connect(t)
}
if (found == null) {
if (unavailable == null) {
t.gaveUp = true
offWhy = "could not connect in $TRIES tries"
}
return
}
val floors: List<Floor> = found
val renew = renewMs(floors.minOf { it.timeoutMs })
val pm = context.getSystemService(PowerManager::class.java)
val frames = ArrayDeque<Long>()
var pacedFor = 0
while (!Thread.currentThread().isInterrupted) {
frames.addLast(WaylandCompositor.gameFrameCount())
if (frames.size > GameThreadHints.PACE_WINDOW_S + 1) frames.removeFirst()
val fps = (frames.last() - frames.first()).toDouble() / (frames.size - 1).coerceAtLeast(1)
val paced = frames.size > GameThreadHints.PACE_WINDOW_S && GameThreadHints.holdsPace(fps, SessionState.refreshHz.toDouble())
pacedFor = if (paced) pacedFor + 1 else 0
val hot = Build.VERSION.SDK_INT >= 29 && pm.currentThermalStatus >= PowerManager.THERMAL_STATUS_SEVERE
val why = when {
BoostReport.paused -> "check pause"
fps < 1 -> "no frames"
pm.isPowerSaveMode -> BoostReport.BATTERY_SAVER
hot -> BoostReport.TOO_HOT
pacedFor >= GameThreadHints.PACE_LEAVE_S -> BoostReport.KEEPS_UP
else -> null
}
offWhy = why
val want = why == null
if (want) {
val results = request(floors)
holding = true
if (!boosting) {
lastResults = results
Log.i(TAG, "boosting (game ${fps.toInt()} fps, results $results)")
}
} else if (boosting) {
holding = false // first, so BoostReport does not read the release as Samsung letting go
Boost.releaseBoost()
BoostReport.letGo(why!!)
Log.i(TAG, "let go ($why, game ${fps.toInt()} fps)")
}
boosting = want
var slept = 0L
while (slept + renew < 1000) {
Thread.sleep(renew)
slept += renew
if (boosting) request(floors)
}
Thread.sleep(1000 - slept)
}
} catch (_: InterruptedException) {
} catch (e: Throwable) {
Log.w(TAG, "stopped", e)
} finally {
if (boosting) runCatching { Boost.releaseBoost() }
holding = false
}
}
private fun request(floors: List<Floor>) = floors.map { Boost.requestBoost(it.type, it.value, it.timeoutMs) }
}
@@ -170,7 +170,6 @@ 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 + msitools.map { it to it } + vr + fexPreloads).filter { (asset, _) ->
val dir = asset.substringBeforeLast('/')
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
@@ -100,44 +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) {
prefs(context).edit().putString("statsStrip", id).apply()
}
fun statsSpeedUnit(context: Context): String? = prefs(context).getString("statsSpeedUnit", null)
fun setStatsSpeedUnit(context: Context, id: String) {
prefs(context).edit().putString("statsSpeedUnit", id).apply()
}
fun statsDash(context: Context): String? = prefs(context).getString("statsDash", null)
fun setStatsDash(context: Context, id: String) {
prefs(context).edit().putString("statsDash", id).apply()
}
/** In-game stats "Send dashboard data" Automatic: on unless the user switched it off. */
fun telemetryAuto(context: Context): Boolean = prefs(context).getBoolean("telemetryAuto", true)
fun setTelemetryAuto(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("telemetryAuto", on).apply()
}
/** Games the user switched off by hand, as TelemetryOutput keys; Automatic leaves them alone. */
fun telemetryOff(context: Context): Set<String> = prefs(context).getStringSet("telemetryOff", null)?.toSet().orEmpty()
fun setTelemetryOff(context: Context, keys: Set<String>) {
prefs(context).edit().putStringSet("telemetryOff", keys.toSet()).apply()
}
fun dualScreenLauncher(context: Context): Boolean = prefs(context).getBoolean("dualScreenLauncher", true)
fun setDualScreenLauncher(context: Context, on: Boolean) {
@@ -653,8 +615,22 @@ object SessionPrefs {
prefs(context).edit().putBoolean("gpuClockPin", on).apply()
}
/** Whether the game's busiest threads are named to the power HAL for a boost (GameThreadHints). */
fun gameThreadHints(context: Context): Boolean = prefs(context).getBoolean("gameThreadHints", true)
/**
* The performance boost: the game's busiest threads named to the power HAL (GameThreadHints) and,
* on a Samsung phone, Samsung's clock floors (SamsungPerf).
*/
fun performanceBoost(context: Context): Boolean = prefs(context).getBoolean("performanceBoost", GameThreadHints.measuredHere)
fun setPerformanceBoost(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("performanceBoost", on).apply()
}
/** Check the boost: BoostReport pauses the boost every other minute of play and compares. */
fun boostCheck(context: Context): Boolean = prefs(context).getBoolean("boostCheck", false)
fun setBoostCheck(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("boostCheck", on).apply()
}
fun prootNoSeccomp(context: Context): Boolean = prefs(context).getBoolean("prootNoSeccomp", false)
@@ -73,9 +73,7 @@ class SessionService : Service() {
private var downloadMonitorTask: Runnable? = null
private var downloadActive = false
private var clientInstallActive = false
private var steamLibraryMounts: Map<String, File>
get() = SessionState.steamLibraryMounts
set(value) { SessionState.steamLibraryMounts = value }
@Volatile private var steamLibraryMounts = emptyMap<String, File>()
private var suspendDownloadNow = false
private var suspendPolicy = SessionPrefs.SUSPEND_MANUAL
private var steamDownloadsInBackground = false
@@ -501,6 +499,8 @@ class SessionService : Service() {
Log.i(TAG, GpuClockPin.start(this))
Log.i(TAG, GameThreadHints.start(this))
Log.i(TAG, SamsungPerf.start(this))
Log.i(TAG, BoostReport.start(this, sessionDir))
val size = SessionState.outputSize
val guest = ArrayList<String>()
@@ -1812,7 +1812,9 @@ class SessionService : Service() {
SessionState.program == NoSteamLaunch.BATTLENET
SessionState.stopRequested = false
GpuClockPin.stop(this)
BoostReport.stop()
GameThreadHints.stop()
SamsungPerf.stop()
suspendOperationPending = false
freezePending = false
launchWatcher?.stopWatching()
@@ -1892,7 +1894,9 @@ class SessionService : Service() {
override fun onDestroy() {
stopSession(0)
BoostReport.stop()
GameThreadHints.stop() // also when the session never got as far as running
SamsungPerf.stop()
if (screenReceiverRegistered) {
unregisterReceiver(screenReceiver)
screenReceiverRegistered = false
@@ -94,9 +94,6 @@ object SessionState {
@Volatile var secondScreenAutoOpened = false
@Volatile var secondScreenProvisional = false
/** Guest library paths on removable storage and the host folders they are mounted from, set by SessionService. */
@Volatile var steamLibraryMounts: Map<String, java.io.File> = emptyMap()
@Volatile
var mode = "steam"
@@ -19,14 +19,14 @@ object SettingsReset {
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "picturePosition", "railLabels",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "performanceBoost", "boostCheck", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "cursorComposite",
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "storageDiagnostics",
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
"bootMovieApplyNext", "bootMovieSteamSeen",
"questDefaultsV1", "telemetryAuto", "telemetryOff", "statsStrip", "statsDash", "statsSpeedUnit",
"questDefaultsV1",
)
internal val SESSION_PREFIXES = listOf(
@@ -1,50 +0,0 @@
package com.droiddeck.launcher.session
/** The In-game stats page's top strip, picked on the page (tap or the Layout row) and remembered. */
enum class StatsStrip(val id: String) {
PANEL("panel"), TILES("tiles"), RINGS("rings");
fun next(): StatsStrip = entries[(ordinal + 1) % entries.size]
companion object {
fun from(id: String?): StatsStrip = entries.firstOrNull { it.id == id } ?: PANEL
}
}
/** Speeds on the racing dashes; telemetry arrives in km/h. */
enum class SpeedUnit(val id: String, val label: String, val perKmh: Float) {
AUTO("auto", "", 1f), KMH("kmh", "km/h", 1f), MPH("mph", "mph", 0.621371f);
/** Auto is mph where road speed limits are signed in mph, by the device's region, else km/h. */
fun resolve(country: String): SpeedUnit = if (this != AUTO) this else if (country.uppercase() in MPH_REGIONS) MPH else KMH
fun next(): SpeedUnit = entries[(ordinal + 1) % entries.size]
companion object {
/** The United States and its territories, the United Kingdom and its Crown Dependencies, Liberia, the Bahamas, Belize. */
private val MPH_REGIONS = setOf("US", "PR", "GU", "VI", "AS", "MP", "GB", "IM", "JE", "GG", "LR", "BS", "BZ")
fun from(id: String?): SpeedUnit = entries.firstOrNull { it.id == id } ?: AUTO
}
}
/** The racing dash under the strip; Auto picks one by the game's data format. */
enum class StatsDash(val id: String) {
AUTO("auto"), SPEEDOMETER("speedometer"), CIRCUIT("circuit"), TRACE("trace"), DIALS("dials"), GLANCE("glance");
/** The dash to draw for data from [source] (Telemetry.source). */
fun resolve(source: String): StatsDash = if (this != AUTO) this else when (source) {
"Forza" -> CIRCUIT
"OutGauge" -> DIALS
else -> SPEEDOMETER
}
companion object {
private val DRAWN = listOf(SPEEDOMETER, CIRCUIT, TRACE, DIALS, GLANCE)
fun from(id: String?): StatsDash = entries.firstOrNull { it.id == id } ?: AUTO
/** A tap on the dash moves on from the one on screen, so Auto never looks like a tap did nothing. */
fun tapped(shown: StatsDash): StatsDash = DRAWN[(DRAWN.indexOf(shown) + 1).mod(DRAWN.size)]
}
}
@@ -101,6 +101,34 @@ internal class SteamDownloadMonitor {
now - lastContentActivityAt <= CONTENT_ACTIVITY_GRACE_MS
}
private fun manifests(runtimeRoot: File, mounts: Map<String, File>): List<File> {
val steamRoots = linkedSetOf<File>()
for (home in STEAM_HOMES) {
val primary = File(runtimeRoot, home)
steamRoots += primary
val libraryFolders = File(primary, "steamapps/libraryfolders.vdf")
runCatching {
PATH.findAll(libraryFolders.readText()).forEach { match ->
steamRoots += hostPath(runtimeRoot, match.groupValues[1], mounts)
}
}
}
return steamRoots.flatMap { root ->
File(root, "steamapps").listFiles { file ->
file.isFile && file.name.startsWith("appmanifest_") && file.name.endsWith(".acf")
}.orEmpty().toList()
}
}
private fun hostPath(runtimeRoot: File, guest: String, mounts: Map<String, File>): File {
val path = guest.trimEnd('/')
for ((mount, host) in mounts) {
if (path == mount) return host
if (path.startsWith("$mount/")) return File(host, path.removePrefix("$mount/"))
}
return File(runtimeRoot, path.removePrefix("/"))
}
private fun read(file: File): ManifestState {
val text = runCatching { file.readText() }.getOrDefault("")
val flags = value(text, "StateFlags")?.toLongOrNull() ?: 0L
@@ -109,6 +137,9 @@ internal class SteamDownloadMonitor {
return ManifestState(downloaded, flags != 4L && (total <= 0L || downloaded < total))
}
private fun value(text: String, key: String): String? =
Regex("\"$key\"\\s+\"([^\"]*)\"").find(text)?.groupValues?.get(1)
companion object {
fun clientInstallPending(runtimeRoot: File): Boolean {
val home = File(runtimeRoot, "root")
@@ -118,43 +149,12 @@ internal class SteamDownloadMonitor {
return !(stamped && File(steam, "steamrtarm64/steam").isFile) || File(home, ".bl-steam-repair").exists()
}
internal fun manifests(runtimeRoot: File, mounts: Map<String, File>): List<File> {
val steamRoots = linkedSetOf<File>()
for (home in STEAM_HOMES) {
val primary = File(runtimeRoot, home)
steamRoots += primary
val libraryFolders = File(primary, "steamapps/libraryfolders.vdf")
runCatching {
PATH.findAll(libraryFolders.readText()).forEach { match ->
steamRoots += hostPath(runtimeRoot, match.groupValues[1], mounts)
}
}
}
return steamRoots.flatMap { root ->
File(root, "steamapps").listFiles { file ->
file.isFile && file.name.startsWith("appmanifest_") && file.name.endsWith(".acf")
}.orEmpty().toList()
}
}
private fun hostPath(runtimeRoot: File, guest: String, mounts: Map<String, File>): File {
val path = guest.trimEnd('/')
for ((mount, host) in mounts) {
if (path == mount) return host
if (path.startsWith("$mount/")) return File(host, path.removePrefix("$mount/"))
}
return File(runtimeRoot, path.removePrefix("/"))
}
internal fun value(text: String, key: String): String? =
Regex("\"$key\"\\s+\"([^\"]*)\"").find(text)?.groupValues?.get(1)
private const val MANIFEST_PROGRESS_GRACE_MS = 8_000L
private const val CONTENT_ACTIVITY_GRACE_MS = 90_000L
private const val MIN_RECEIVE_BYTES_PER_SEC = 64L * 1024L
private val PATH = Regex("\"path\"\\s+\"([^\"]+)\"")
internal val STEAM_HOMES = listOf("root/.local/share/Steam", "root/.droiddeck-x64/.local/share/Steam")
internal val CONTENT_UPDATE = Regex("""AppID (\d+) (App|Workshop|Shader) update changed : (.*)""")
private val STEAM_HOMES = listOf("root/.local/share/Steam", "root/.droiddeck-x64/.local/share/Steam")
private val CONTENT_UPDATE = Regex("""AppID (\d+) (App|Workshop|Shader) update changed : (.*)""")
private val CURRENT_RATE = Regex("""Current download rate: ([\d.]+) Mbps""")
}
}
@@ -1,72 +0,0 @@
package com.droiddeck.launcher.session
import java.io.File
import java.io.RandomAccessFile
/** A Steam download or update the client is working on. [total] is 0 while Steam has not sized it yet. */
data class SteamDownload(
val appId: String,
val name: String,
val done: Long,
val total: Long,
val shader: Boolean = false,
val paused: Boolean = false,
)
/** Reads Steam's own appmanifests and content log, the same files [SteamDownloadMonitor] watches. */
object SteamDownloads {
fun read(runtimeRoot: File, mounts: Map<String, File> = emptyMap(), client: String? = null): List<SteamDownload> {
val names = HashMap<String, String>()
val apps = SteamDownloadMonitor.manifests(runtimeRoot, mounts).mapNotNull { file ->
val text = runCatching { file.readText() }.getOrNull() ?: return@mapNotNull null
val id = SteamDownloadMonitor.value(text, "appid") ?: file.name.removePrefix("appmanifest_").removeSuffix(".acf")
val name = SteamDownloadMonitor.value(text, "name") ?: id
names[id] = name
fromManifest(id, name, text)
}
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() }
val shaders = log?.let { runningShaderUpdates(tail(it)) }.orEmpty()
.map { SteamDownload(it, names[it] ?: it, 0L, 0L, shader = true) }
return apps + shaders
}
internal fun fromManifest(id: String, name: String, text: String): SteamDownload? {
val flags = SteamDownloadMonitor.value(text, "StateFlags")?.toLongOrNull() ?: 0L
if (flags == FULLY_INSTALLED) return null
val done = SteamDownloadMonitor.value(text, "BytesDownloaded")?.toLongOrNull() ?: 0L
val total = SteamDownloadMonitor.value(text, "BytesToDownload")?.toLongOrNull() ?: 0L
if (total > 0L && done >= total) return null
if ((flags and UPDATE_REQUIRED) == 0L && total <= 0L) return null
return SteamDownload(id, name, done, total, paused = (flags and UPDATE_PAUSED) != 0L)
}
/** App ids whose latest shader-cache line in the content log says the update is still running. */
internal fun runningShaderUpdates(lines: Sequence<String>): List<String> {
val state = LinkedHashMap<String, Boolean>()
for (line in lines) {
if ("Client version:" in line) state.clear()
val match = SteamDownloadMonitor.CONTENT_UPDATE.find(line) ?: continue
if (match.groupValues[2] != "Shader") continue
val running = match.groupValues[3].let { "Running Update" in it && "Stopping" !in it }
state[match.groupValues[1]] = running
}
return state.filterValues { it }.keys.toList()
}
private fun tail(file: File): Sequence<String> = runCatching {
RandomAccessFile(file, "r").use { raf ->
val start = (raf.length() - TAIL_BYTES).coerceAtLeast(0L)
raf.seek(start)
val bytes = ByteArray((raf.length() - start).toInt())
raf.readFully(bytes)
String(bytes, Charsets.ISO_8859_1).lineSequence().drop(if (start > 0L) 1 else 0).toList().asSequence()
}
}.getOrDefault(emptySequence())
private const val FULLY_INSTALLED = 4L
private const val UPDATE_REQUIRED = 2L
private const val UPDATE_PAUSED = 512L
private const val TAIL_BYTES = 256L * 1024L
}
@@ -1,81 +0,0 @@
package com.droiddeck.launcher.session
import android.database.sqlite.SQLiteDatabase
import java.io.File
import javax.crypto.Cipher
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec
/** A cookie for one https host, in the form CookieManager.setCookie takes. */
data class WebCookie(val host: String, val header: String)
/**
* The web sign-in the Steam client in the session already has, so the bottom-screen chat opens signed in.
* Steam's built-in browser keeps it in its Chromium cookie store under config/htmlcache. With no keyring
* (SteamOS and DroidDeck) Chromium encrypts values as "v10": AES-128-CBC, key PBKDF2-SHA1("peanuts",
* "saltysalt", 1 round), IV of 16 spaces. Values are never logged.
*/
object SteamWebLogin {
val HOSTS = listOf("steamcommunity.com", "steam-chat.com")
private const val COOKIES = "config/htmlcache/Default/Cookies"
private const val V10 = "v10"
// From cookie store version 24 Chromium puts the SHA-256 of the host before each value.
private const val HOST_HASH_VERSION = 24
private const val HOST_HASH_BYTES = 32
private val key: SecretKeySpec by lazy {
val spec = PBEKeySpec("peanuts".toCharArray(), "saltysalt".toByteArray(), 1, 128)
SecretKeySpec(SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec).encoded, "AES")
}
internal fun decrypt(encrypted: ByteArray, hostHashed: Boolean): String? = runCatching {
if (encrypted.size <= V10.length || String(encrypted, 0, V10.length, Charsets.US_ASCII) != V10) return null
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.DECRYPT_MODE, key, IvParameterSpec(ByteArray(16) { ' '.code.toByte() }))
val plain = cipher.doFinal(encrypted, V10.length, encrypted.size - V10.length)
val value = if (hostHashed && plain.size >= HOST_HASH_BYTES) plain.copyOfRange(HOST_HASH_BYTES, plain.size) else plain
String(value, Charsets.UTF_8)
}.getOrNull()
/** Steam's own pages send the sign-in with its "||" separator percent-encoded. */
internal fun header(name: String, value: String, httpOnly: Boolean): String {
val v = if (name == "steamLoginSecure") value.replace("||", "%7C%7C") else value
return "$name=$v; Path=/; Secure" + if (httpOnly) "; HttpOnly" else ""
}
/** Empty when the client has no web sign-in, for example before the first login. */
fun read(runtimeRoot: File, client: String?, scratch: File): List<WebCookie> {
val homes = client?.let { listOf(if (it == "x86_64") SteamDownloadMonitor.STEAM_HOMES[1] else SteamDownloadMonitor.STEAM_HOMES[0]) }
?: SteamDownloadMonitor.STEAM_HOMES
val store = homes.map { File(runtimeRoot, "$it/$COOKIES") }.filter { it.isFile }.maxByOrNull { it.lastModified() }
?: return emptyList()
// A copy, journal included: Steam keeps the store open and may be in the middle of a write.
scratch.deleteRecursively()
if (!scratch.mkdirs()) return emptyList()
return try {
val copy = File(scratch, "Cookies")
store.copyTo(copy, overwrite = true)
File(store.path + "-journal").takeIf { it.length() > 0L }?.copyTo(File(scratch, "Cookies-journal"), overwrite = true)
SQLiteDatabase.openDatabase(copy.path, null, SQLiteDatabase.OPEN_READWRITE).use { db ->
val version = db.rawQuery("SELECT value FROM meta WHERE key = 'version'", null).use { if (it.moveToFirst()) it.getString(0).toIntOrNull() else null } ?: 0
val marks = HOSTS.joinToString { "?" }
db.rawQuery("SELECT host_key, name, value, encrypted_value, is_httponly FROM cookies WHERE host_key IN ($marks)", HOSTS.toTypedArray()).use { c ->
val out = ArrayList<WebCookie>()
while (c.moveToNext()) {
val name = c.getString(1)
val value = c.getString(2).takeUnless { it.isNullOrEmpty() }
?: decrypt(c.getBlob(3) ?: continue, version >= HOST_HASH_VERSION) ?: continue
out += WebCookie(c.getString(0), header(name, value, c.getInt(4) != 0))
}
out
}
}
} catch (_: Exception) {
emptyList()
} finally {
scratch.deleteRecursively()
}
}
}
@@ -1,121 +0,0 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.frontend.Library
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)
/** Automatic: turns the output on for every found game the user has not switched off and that is not running. */
fun applyAutomatic(context: Context, running: String?) {
if (!SessionPrefs.telemetryAuto(context)) return
automaticTargets(scan(Library.compatdataDirs(context)), SessionPrefs.telemetryOff(context), running).forEach { set(it, true) }
}
internal fun key(game: Game) = "${game.prefixId}/${game.name}"
internal fun automaticTargets(games: List<Game>, off: Set<String>, running: String?): List<Game> =
games.filter { !it.on && key(it) !in off && !isRunning(it.prefixId, running) }
/** Games DroidDeck changed, which go back to their own setting when Automatic is switched off. */
internal fun restoreTargets(games: List<Game>, running: String?): List<Game> =
games.filter { File(it.file.path + ORIGINAL_SUFFIX).isFile && !isRunning(it.prefixId, running) }
/** 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[^>]*>")
}
@@ -1,215 +0,0 @@
package com.droiddeck.launcher.ui
import android.annotation.SuppressLint
import android.content.Context
import android.media.AudioManager
import android.view.ViewGroup
import android.webkit.CookieManager
import android.webkit.RenderProcessGoneDetail
import android.webkit.WebResourceRequest
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
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.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.SteamWebLogin
import com.droiddeck.launcher.runtime.LinuxRuntime
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import java.io.File
import kotlin.coroutines.resume
import kotlin.math.roundToInt
private const val STEAM_CHAT = "https://steamcommunity.com/chat"
private const val CHAT_PAGE_SCALE = 0.75f
private val STEAM_HOSTS = listOf("steamcommunity.com", "steam-chat.com", "steampowered.com", "steamstatic.com", "steamcontent.com")
/** Steam chat stays on Steam's own sites; anything else is not opened on the bottom screen. */
internal fun steamChatAllows(host: String?): Boolean =
host != null && STEAM_HOSTS.any { host == it || host.endsWith(".$it") }
/** The desktop chat fits the bottom panel better than the phone site; keep WebView's Chrome version. */
internal fun desktopUserAgent(webView: String?): String {
val chrome = webView?.let { Regex("Chrome/[\\d.]+").find(it)?.value } ?: "Chrome/127.0.6533.103"
return "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) $chrome Safari/537.36"
}
/**
* At the panel's own scale Steam's desktop chat gets about 600x300 CSS pixels and its friends list collapses, so the
* page is laid out [cssWidth] wide and drawn at [scale]. Steam's site header (the rows before .chat_main_flex; its
* class name is generated) is hidden to leave the height to the friends list and the chat. The group chat list keeps
* a fixed 114 px height and an empty-list note that cover the online friends, so it shrinks to its rows (at most a
* quarter of the panel) and the note is hidden.
*/
internal fun steamChatFitScript(cssWidth: Int, scale: Float): String {
val zoom = "%.2f".format(java.util.Locale.US, scale)
return "(function(){var m=document.querySelector('meta[name=viewport]');" +
"if(!m){m=document.createElement('meta');m.name='viewport';document.head.appendChild(m);}" +
"m.content='width=$cssWidth, initial-scale=$zoom';" +
"if(!document.getElementById('dd-chat-fit')){var s=document.createElement('style');s.id='dd-chat-fit';" +
"s.textContent='$STEAM_CHAT_FIT_CSS';document.head.appendChild(s);}" +
"window.dispatchEvent(new Event('resize'));})()"
}
internal const val STEAM_CHAT_FIT_CSS = ".chat_main>:has(~.chat_main_flex){display:none!important}" +
".ChatRoomList_Empty{display:none!important}" +
".chatRoomListContainer{height:auto!important;max-height:25vh!important}"
@Composable
fun BottomChatPage() {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
var chatOpen by remember { mutableStateOf(true) }
// Set when Android ended the page's renderer; the chat opens again once DroidDeck is back in front.
var stopped by remember { mutableStateOf(false) }
val lifecycle = LocalLifecycleOwner.current.lifecycle
DisposableEffect(lifecycle) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME && stopped) {
stopped = false
chatOpen = true
}
}
lifecycle.addObserver(observer)
onDispose { lifecycle.removeObserver(observer) }
}
// null while the Steam client's sign-in is being copied, then whether there was one.
var fromSteam by remember { mutableStateOf<Boolean?>(null) }
LaunchedEffect(chatOpen) {
if (!chatOpen) {
fromSteam = null
return@LaunchedEffect
}
val cookies = withContext(Dispatchers.IO) {
SteamWebLogin.read(LinuxRuntime.rootDir(context), SessionState.steamClientArch, File(context.cacheDir, "steam-web-login"))
}
val manager = CookieManager.getInstance()
for (c in cookies) suspendCancellableCoroutine { cont -> manager.setCookie("https://${c.host}", c.header) { cont.resume(Unit) } }
manager.flush()
fromSteam = cookies.any { it.header.startsWith("steamLoginSecure=") }
}
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
if (!chatOpen) {
VoiceRow(context)
Column(Modifier.weight(1f).fillMaxWidth().padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically)) {
if (stopped) Text(stringResource(R.string.bottom_chat_stopped), fontSize = 13.sp, color = colors.onSurfaceVariant, textAlign = TextAlign.Center)
Text(stringResource(R.string.bottom_chat_why), fontSize = 15.sp, color = colors.onBackground, textAlign = TextAlign.Center)
BottomPillButton(stringResource(R.string.bottom_chat_open), "bottom-chat-open") {
stopped = false
chatOpen = true
}
}
} else {
VoiceRow(context, onClose = { chatOpen = false },
note = if (fromSteam == false) stringResource(R.string.bottom_chat_not_signed_in) else "")
Box(Modifier.weight(1f).fillMaxWidth().clip(RoundedCornerShape(14.dp))) {
if (fromSteam != null) SteamChatView(onStopped = {
stopped = true
chatOpen = false
})
}
}
}
}
/** With [onClose] set the chat is open: the row also carries Close and leaves out the long mic hint. */
@Composable
private fun VoiceRow(context: Context, onClose: (() -> Unit)? = null, note: String = "") {
val colors = MaterialTheme.colorScheme
val audio = remember { context.getSystemService(Context.AUDIO_SERVICE) as AudioManager }
val max = remember { audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC).coerceAtLeast(1) }
var volume by remember { mutableIntStateOf(audio.getStreamVolume(AudioManager.STREAM_MUSIC)) }
fun step(direction: Int) {
// No flags: Android's volume panel would cover the game on the main screen.
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, direction, 0)
volume = audio.getStreamVolume(AudioManager.STREAM_MUSIC)
}
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (onClose != null) BottomPillButton(stringResource(R.string.bottom_chat_close), "bottom-chat-close", onClose)
if (SessionState.micAvailable) {
val on = SessionState.micEnabled
BottomPillButton(stringResource(if (on) R.string.bottom_chat_mic_on else R.string.bottom_chat_mic_off), "bottom-chat-mic") {
SessionService.setMicEnabled(context, !on)
}
}
val hint = if (onClose == null && !SessionState.micAvailable) stringResource(R.string.bottom_chat_mic_unavailable) else note
Text(hint, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 3, modifier = Modifier.weight(1f))
Text(stringResource(R.string.bottom_chat_volume, volume * 100 / max), fontSize = 14.sp, color = colors.onSurfaceVariant)
BottomPillButton("−", "bottom-chat-volume-down") { step(AudioManager.ADJUST_LOWER) }
BottomPillButton("+", "bottom-chat-volume-up") { step(AudioManager.ADJUST_RAISE) }
}
}
@SuppressLint("SetJavaScriptEnabled")
@Composable
private fun SteamChatView(onStopped: () -> Unit) {
AndroidView(factory = { ctx ->
WebView(ctx).apply {
// AndroidView's default WRAP_CONTENT height gives the page a 0 px tall viewport, which collapses Steam
// chat's full-height layout (measured on the Retroid Pocket Duo: html and every container 0 px).
layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
setBackgroundColor(0xFF0A0B0D.toInt())
settings.javaScriptEnabled = true
settings.domStorageEnabled = true
settings.allowFileAccess = false
settings.allowContentAccess = false
settings.useWideViewPort = true
settings.loadWithOverviewMode = true
settings.userAgentString = desktopUserAgent(runCatching { WebSettings.getDefaultUserAgent(ctx) }.getOrNull())
CookieManager.getInstance().setAcceptCookie(true)
webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean =
!steamChatAllows(request.url.host)
override fun onPageFinished(view: WebView, url: String) {
val scale = view.resources.displayMetrics.density * CHAT_PAGE_SCALE
if (view.width > 0) view.evaluateJavascript(steamChatFitScript((view.width / scale).roundToInt(), CHAT_PAGE_SCALE), null)
}
// Android ends the page's renderer once DroidDeck goes to picture-in-picture ("isolated not needed"
// on the Retroid Pocket Duo); the page cannot come back, so the chat closes and reopens on resume.
override fun onRenderProcessGone(view: WebView, detail: RenderProcessGoneDetail): Boolean {
onStopped()
return true
}
}
loadUrl(STEAM_CHAT)
}
}, modifier = Modifier.fillMaxSize(), onRelease = { view ->
CookieManager.getInstance().flush()
view.destroy()
})
}
@@ -1,143 +0,0 @@
package com.droiddeck.launcher.ui
import androidx.annotation.StringRes
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.Menu
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
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
/** A page the bottom screen can show while the game runs on the main screen. */
class BottomPage(
val id: String,
@StringRes val label: Int,
val icon: ImageVector,
val content: @Composable () -> Unit,
)
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. */
internal fun pageForGameStart(ids: List<String>): String? = GAME_PAGE.takeIf { it in ids }
private const val DEFAULT_PAGE = "chat"
private const val GAME_PAGE = "telemetry"
/** Tabs show their names while every tab still fits at [TAB_WIDTH]; otherwise only the open tab keeps its name. */
internal fun bottomTabsWithLabels(widthDp: Float, tabs: Int): Boolean = tabs * TAB_WIDTH + 2 * BAR_BUTTON <= widthDp
private const val TAB_WIDTH = 132f
private const val BAR_BUTTON = 56f
@Composable
fun BottomDashboard(
pages: List<BottomPage>,
remembered: String?,
onPage: (String) -> Unit,
onClose: () -> Unit,
onMenu: (() -> Unit)?,
gameStarts: Int = 0,
) {
val colors = MaterialTheme.colorScheme
var current by remember { mutableStateOf(pickBottomPage(remembered, pages.map { it.id })) }
val startsWhenOpened = remember { gameStarts }
LaunchedEffect(gameStarts) {
if (gameStarts != startsWhenOpened) pageForGameStart(pages.map { it.id })?.let { current = it }
}
val page = pages.firstOrNull { it.id == current } ?: pages.firstOrNull()
BoxWithConstraints(Modifier.fillMaxSize().background(colors.background)) {
val labels = bottomTabsWithLabels(maxWidth.value, pages.size)
Column(Modifier.fillMaxSize().padding(horizontal = 12.dp, vertical = 10.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
Row(Modifier.fillMaxWidth().height(48.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
BarButton(Icons.Outlined.Close, stringResource(R.string.deck_close), "bottom-close", onClose)
Row(Modifier.weight(1f).horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
pages.forEach { p ->
PageTab(p, p.id == page?.id, labels) {
current = p.id
onPage(p.id)
}
}
}
if (onMenu != null) BarButton(Icons.Outlined.Menu, stringResource(R.string.touch_droiddeck_menu), "bottom-menu", onMenu)
}
Box(Modifier.weight(1f).fillMaxWidth()) {
if (page != null) page.content()
else Text(stringResource(R.string.bottom_dashboard_empty), fontSize = 15.sp, color = colors.onSurfaceVariant,
modifier = Modifier.align(Alignment.Center))
}
}
}
}
@Composable
private fun BarButton(icon: ImageVector, label: String, tag: String, onClick: () -> Unit) {
val pal = LocalPalette.current
Box(
Modifier.size(44.dp).clip(RoundedCornerShape(22.dp)).background(pal.surface).border(1.dp, pal.line, RoundedCornerShape(22.dp))
.semantics { contentDescription = label }.clickable(role = Role.Button, onClick = onClick).testTag(tag),
contentAlignment = Alignment.Center,
) {
Icon(icon, contentDescription = null, tint = MaterialTheme.colorScheme.onBackground, modifier = Modifier.size(22.dp))
}
}
@Composable
private fun PageTab(page: BottomPage, selected: Boolean, label: Boolean, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val shape = RoundedCornerShape(20.dp)
val name = stringResource(page.label)
Row(
Modifier.height(44.dp).clip(shape)
.background(if (selected) pal.signal else Color.Transparent)
.border(1.dp, if (selected) pal.signal else pal.line, shape)
.semantics { contentDescription = name }
.clickable(role = Role.Tab, onClick = onClick).testTag("bottom-page-${page.id}")
.padding(horizontal = 14.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
val tint = if (selected) colors.background else colors.onBackground
Icon(page.icon, contentDescription = null, tint = tint, modifier = Modifier.size(20.dp))
if (label || selected) Text(name, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = tint, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
@@ -1,126 +0,0 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
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.runtime.LinuxRuntime
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.SteamDownload
import com.droiddeck.launcher.session.SteamDownloads
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadState
import com.droiddeck.launcher.stores.formatBytes
import com.droiddeck.launcher.stores.formatSpeed
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
/** Bytes per second between two reads of the same download; 0 when it did not move or restarted. */
internal fun downloadRate(previousDone: Long, previousAt: Long, done: Long, at: Long): Long =
if (previousDone < 0L || done <= previousDone || at <= previousAt) 0L else (done - previousDone) * 1000L / (at - previousAt)
private const val STEAM_POLL_MS = 2_000L
private class SteamRow(val download: SteamDownload, val rate: Long)
@Composable
fun BottomDownloadsPage() {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
var steam by remember { mutableStateOf<List<SteamRow>>(emptyList()) }
LaunchedEffect(Unit) {
var last = emptyMap<String, Pair<Long, Long>>()
while (true) {
val now = System.currentTimeMillis()
val read = withContext(Dispatchers.IO) {
runCatching {
SteamDownloads.read(LinuxRuntime.rootDir(context), SessionState.steamLibraryMounts, SessionState.steamClientArch)
}.getOrDefault(emptyList())
}
steam = read.map { d ->
val before = last[d.appId]
SteamRow(d, if (before == null) 0L else downloadRate(before.first, before.second, d.done, now))
}
last = read.associate { it.appId to (it.done to now) }
delay(STEAM_POLL_MS)
}
}
val store = StoresState.downloads.filter { it.isActive }
if (steam.isEmpty() && store.isEmpty()) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(stringResource(R.string.bottom_downloads_none), fontSize = 15.sp, color = colors.onSurfaceVariant)
}
return
}
LazyColumn(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
items(steam, key = { "steam:${it.download.appId}:${it.download.shader}" }) { row ->
val d = row.download
val detail = when {
d.shader -> stringResource(R.string.bottom_downloads_shader)
d.paused -> stringResource(R.string.bottom_downloads_paused)
d.total <= 0L -> stringResource(R.string.bottom_downloads_queued)
else -> listOf("${formatBytes(d.done)} / ${formatBytes(d.total)}", formatSpeed(row.rate)).filter { it.isNotEmpty() }.joinToString(" · ")
}
BottomDownloadRow(d.name, stringResource(R.string.bottom_downloads_steam), detail,
if (d.total > 0L) (d.done.toFloat() / d.total).coerceIn(0f, 1f) else null)
}
items(store, key = { "store:${it.key}" }) { entry ->
val e = StoresState.download(entry.key) ?: entry
val detail = when (e.state) {
DownloadState.PAUSED -> stringResource(R.string.bottom_downloads_paused)
DownloadState.QUEUED -> stringResource(R.string.bottom_downloads_queued)
else -> listOf(
if (e.bytesTotal > 0L) "${formatBytes(e.bytesDone)} / ${formatBytes(e.bytesTotal)}" else "",
formatSpeed(e.speedBps),
).filter { it.isNotEmpty() }.joinToString(" · ")
}
BottomDownloadRow(e.name, e.store.label, detail, e.stageFraction.takeIf { it >= 0f })
}
}
}
@Composable
private fun BottomDownloadRow(name: String, source: String, detail: String, fraction: Float?) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(
Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(pal.surface).padding(horizontal = 14.dp, vertical = 10.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
Text(source, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, modifier = Modifier.padding(start = 8.dp))
}
if (fraction != null) LinearProgressIndicator(progress = { fraction }, modifier = Modifier.fillMaxWidth(), color = pal.signal)
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth(), color = pal.signal)
if (detail.isNotEmpty()) Text(detail, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
@@ -1,117 +0,0 @@
package com.droiddeck.launcher.ui
import android.content.Intent
import android.provider.Settings
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
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.TextAlign
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.session.BottomNotifications
import kotlinx.coroutines.delay
/** DroidDeck's own switch on Android 11 and later; the list of all apps before that. */
internal fun notificationAccessIntent(context: android.content.Context): Intent =
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
Intent(Settings.ACTION_NOTIFICATION_LISTENER_DETAIL_SETTINGS).putExtra(
Settings.EXTRA_NOTIFICATION_LISTENER_COMPONENT_NAME,
android.content.ComponentName(context, com.droiddeck.launcher.session.BottomNotificationListener::class.java).flattenToString(),
)
} else Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)
@Composable
fun BottomNotificationsPage(openSettings: ((Intent, () -> Boolean) -> Unit)?) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var granted by remember { mutableStateOf(BottomNotifications.granted(context)) }
LaunchedEffect(Unit) {
while (true) {
granted = BottomNotifications.granted(context)
delay(2_000L)
}
}
if (!granted) {
Column(Modifier.fillMaxSize().padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically)) {
Text(stringResource(R.string.bottom_notifications_why), fontSize = 15.sp, color = colors.onBackground, textAlign = TextAlign.Center)
BottomPillButton(stringResource(R.string.bottom_notifications_allow), "bottom-notifications-allow") {
val intent = notificationAccessIntent(context)
if (openSettings != null) openSettings(intent) { BottomNotifications.granted(context) }
else runCatching { context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
}
}
return
}
val shown = BottomNotifications.items
if (shown.isEmpty()) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(stringResource(R.string.bottom_notifications_none), fontSize = 15.sp, color = colors.onSurfaceVariant)
}
return
}
val timeFormat = remember { android.text.format.DateFormat.getTimeFormat(context) }
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Text(stringResource(R.string.bottom_notifications_count, shown.size), fontSize = 13.sp, color = colors.onSurfaceVariant,
modifier = Modifier.weight(1f))
BottomPillButton(stringResource(R.string.bottom_notifications_clear), "bottom-notifications-clear") { BottomNotifications.clear() }
}
LazyColumn(Modifier.weight(1f).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
items(shown.toList(), key = { it.key }) { n ->
Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(pal.surface).padding(horizontal = 14.dp, vertical = 10.dp),
verticalArrangement = Arrangement.spacedBy(4.dp)) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(n.app, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1,
overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
Text(timeFormat.format(java.util.Date(n.postedAt)), fontSize = 12.sp, color = colors.onSurfaceVariant)
}
if (n.title.isNotBlank()) Text(n.title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
maxLines = 1, overflow = TextOverflow.Ellipsis)
if (n.text.isNotBlank()) Text(n.text, fontSize = 14.sp, color = colors.onBackground, maxLines = 4, overflow = TextOverflow.Ellipsis)
}
}
}
}
}
@Composable
internal fun BottomPillButton(label: String, tag: String, onClick: () -> Unit) {
val pal = LocalPalette.current
Box(
Modifier.height(40.dp).clip(RoundedCornerShape(20.dp)).background(pal.signal.copy(alpha = 0.16f))
.clickable(role = Role.Button, onClick = onClick).testTag(tag).padding(horizontal = 16.dp),
contentAlignment = Alignment.Center,
) {
Text(label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = pal.signal, maxLines = 1)
}
}
@@ -1,28 +0,0 @@
package com.droiddeck.launcher.ui
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Download
import androidx.compose.material.icons.outlined.Forum
import androidx.compose.material.icons.outlined.Speed
import androidx.compose.material.icons.outlined.Notifications
import androidx.compose.material.icons.outlined.PhotoLibrary
import com.droiddeck.launcher.R
/** What the bottom-screen pages can ask the running session to do. */
class BottomPageActions(
val takeScreenshot: ((onDone: (Boolean) -> Unit) -> Unit)? = null,
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, 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) },
BottomPage("chat", R.string.bottom_page_chat, Icons.Outlined.Forum) { BottomChatPage() },
)
@@ -1,110 +0,0 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
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.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.BottomScreenshots
import com.droiddeck.launcher.session.BottomShot
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
private const val SHOTS_POLL_MS = 5_000L
@Composable
fun BottomScreenshotsPage(takeScreenshot: ((onDone: (Boolean) -> Unit) -> Unit)?) {
val context = LocalContext.current
val colors = MaterialTheme.colorScheme
var shots by remember { mutableStateOf<List<BottomShot>>(emptyList()) }
var refresh by remember { mutableIntStateOf(0) }
var open by remember { mutableStateOf<BottomShot?>(null) }
var status by remember { mutableStateOf<Int?>(null) }
var busy by remember { mutableStateOf(false) }
LaunchedEffect(refresh) {
while (true) {
shots = withContext(Dispatchers.IO) { BottomScreenshots.list(context, LinuxRuntime.rootDir(context)) }
delay(SHOTS_POLL_MS)
}
}
LaunchedEffect(status) {
if (status != null) {
delay(3_000L)
status = null
}
}
open?.let { shot ->
Box(Modifier.fillMaxSize().clip(RoundedCornerShape(14.dp)).background(androidx.compose.ui.graphics.Color.Black)
.clickable(role = Role.Button) { open = null }.testTag("bottom-shot-full")) {
AsyncImage(ImageRequest.Builder(context).data(shot.model).build(), contentDescription = null,
contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize())
}
return
}
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Text(status?.let { stringResource(it) } ?: stringResource(R.string.bottom_shots_where), fontSize = 13.sp,
color = colors.onSurfaceVariant, maxLines = 2, modifier = Modifier.weight(1f).padding(end = 8.dp))
if (takeScreenshot != null) BottomPillButton(stringResource(R.string.bottom_shots_take), "bottom-shots-take") {
if (!busy) {
busy = true
takeScreenshot { ok ->
busy = false
status = if (ok) R.string.bottom_shots_saved else R.string.bottom_shots_failed
refresh++
}
}
}
}
if (shots.isEmpty()) {
Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
Text(stringResource(R.string.bottom_shots_none), fontSize = 15.sp, color = colors.onSurfaceVariant)
}
} else {
LazyVerticalGrid(GridCells.Adaptive(150.dp), Modifier.weight(1f).fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
items(shots, key = { it.model.toString() }) { shot ->
AsyncImage(
ImageRequest.Builder(context).data(shot.model).size(480, 270).build(), contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxWidth().aspectRatio(16f / 9f).clip(RoundedCornerShape(10.dp))
.background(LocalPalette.current.surface).clickable(role = Role.Button) { open = shot },
)
}
}
}
}
}
@@ -1,391 +0,0 @@
package com.droiddeck.launcher.ui
import android.content.res.Resources
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
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.clickable
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.SwitchDefaults
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
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
import com.droiddeck.launcher.session.GameStatusFiles
import com.droiddeck.launcher.session.GameTelemetry
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.SpeedUnit
import com.droiddeck.launcher.session.StatsDash
import com.droiddeck.launcher.session.StatsStrip
import com.droiddeck.launcher.session.Telemetry
import com.droiddeck.launcher.session.TelemetryOutput
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.HttpURLConnection
import java.net.InetSocketAddress
import java.net.SocketTimeoutException
import java.net.URL
import java.util.concurrent.atomic.AtomicReference
private const val DRAW_MS = 66L
private const val TELEMETRY_STALE_MS = 3_000L
private const val METRICS_MS = 1_000L
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
/** Top strip history: one reading a second for 30 s. */
private const val PERF_N = 30
/** What arrives on one telemetry port; written only by that port's listener. */
private class PortTraffic {
@Volatile var packets = 0L
@Volatile var length = 0
@Volatile var readable = true
}
private data class UnknownTraffic(val port: Int, val packets: Long, val length: Int)
@Composable
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) }
var auto by remember { mutableStateOf(SessionPrefs.telemetryAuto(context)) }
val latest = remember { AtomicReference<Pair<Long, Telemetry>?>(null) }
var race by remember { mutableStateOf<Telemetry?>(null) }
var fpsNow by remember { mutableStateOf<Float?>(null) }
var device by remember { mutableStateOf<HudMetrics.Snapshot?>(null) }
var thunder by remember { mutableStateOf<List<Pair<String, String>>>(emptyList()) }
var elite by remember { mutableStateOf<GameStatusFiles.Elite?>(null) }
var busyPorts by remember { mutableStateOf<Set<Int>>(emptySet()) }
val traffic = remember { GameTelemetry.PORTS.associateWith { PortTraffic() } }
var unknown by remember { mutableStateOf<List<UnknownTraffic>>(emptyList()) }
var strip by remember { mutableStateOf(StatsStrip.from(SessionPrefs.statsStrip(context))) }
var dash by remember { mutableStateOf(StatsDash.from(SessionPrefs.statsDash(context))) }
var speedUnit by remember { mutableStateOf(SpeedUnit.from(SessionPrefs.statsSpeedUnit(context))) }
val shownUnit = speedUnit.resolve(Resources.getSystem().configuration.locales[0].country)
val fpsHistory = remember { History(PERF_N) }
val cpuHistory = remember { History(PERF_N) }
val gpuHistory = remember { History(PERF_N) }
val wattsHistory = remember { History(PERF_N) }
val throttleTrace = remember { History(TRACE_N) }
val brakeTrace = remember { History(TRACE_N) }
val speedTrace = remember { History(TRACE_N) }
var perfTick by remember { mutableIntStateOf(0) }
var traceTick by remember { mutableIntStateOf(0) }
var clock by remember { mutableStateOf("") }
LaunchedEffect(Unit) {
for (port in GameTelemetry.PORTS) launch(Dispatchers.IO) {
val socket = runCatching {
DatagramSocket(null).apply {
reuseAddress = true
soTimeout = 500
bind(InetSocketAddress(GameTelemetry.LISTEN_ADDRESS, port))
}
}.getOrNull()
if (socket == null) {
withContext(Dispatchers.Main) { busyPorts = busyPorts + port }
return@launch
}
val seen = traffic.getValue(port)
socket.use {
val data = ByteArray(2048)
val packet = DatagramPacket(data, data.size)
while (isActive) {
try {
packet.length = data.size
it.receive(packet)
val t = GameTelemetry.parse(port, data, packet.length)
seen.packets++
seen.length = packet.length
seen.readable = t != null
if (t != null) latest.set(System.currentTimeMillis() to t)
} catch (_: SocketTimeoutException) {
} catch (_: java.io.IOException) {
break
}
}
}
}
while (isActive) {
val reading = latest.get()
race = reading?.takeIf { System.currentTimeMillis() - it.first < TELEMETRY_STALE_MS }?.second
race?.let { r ->
throttleTrace.add(r.throttle ?: 0f)
brakeTrace.add(r.brake ?: 0f)
speedTrace.add(r.speedKmh ?: 0f)
traceTick++
}
fpsNow = fps()
unknown = traffic.filter { (_, t) -> t.packets > 0 && !t.readable }.map { (port, t) -> UnknownTraffic(port, t.packets, t.length) }
delay(DRAW_MS)
}
}
LaunchedEffect(Unit) {
val metrics = HudMetrics(context).apply { setMangoReadings(MangoReadings(File(context.filesDir, "session"), LinuxRuntime.rootDir(context))) }
while (isActive) {
device = withContext(Dispatchers.IO) { runCatching { metrics.snapshot() }.getOrNull() }
fps()?.takeIf { it > 0f }?.let { fpsHistory.add(it) }
device?.let { s ->
s.cpuPercent?.let { cpuHistory.add(it.toFloat()) }
s.gpuPercent?.let { gpuHistory.add(it.toFloat()) }
s.battery?.watts?.takeIf { it > 0f }?.let { wattsHistory.add(it) }
}
clock = java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT).format(java.util.Date())
perfTick++
delay(METRICS_MS)
}
}
LaunchedEffect(Unit) {
while (isActive) {
val rows = withContext(Dispatchers.IO) { runCatching { GameStatusFiles.warThunder(httpGet(GameStatusFiles.WAR_THUNDER_STATE)) }.getOrNull() }
thunder = rows.orEmpty()
delay(if (rows == null) THUNDER_RETRY_MS else THUNDER_MS)
}
}
LaunchedEffect(Unit) {
var file: File? = null
var searchedAt = 0L
while (isActive) {
val now = System.currentTimeMillis()
if (file == null && now - searchedAt > ELITE_SEARCH_MS) {
searchedAt = now
file = withContext(Dispatchers.IO) {
runCatching { GameStatusFiles.eliteStatusFile(LinuxRuntime.rootDir(context), SessionState.steamLibraryMounts) }.getOrNull()
}
}
val f = file
// Status.json changes while Elite runs; one older than a minute belongs to an earlier session.
elite = if (f != null && now - f.lastModified() < 60_000L) {
withContext(Dispatchers.IO) { runCatching { GameStatusFiles.elite(f.readText()) }.getOrNull() }
} else null
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)) {
perfTick.let {
StatsStripView(strip, StripData(fpsNow, device, fpsHistory.snapshot(), cpuHistory.snapshot(), gpuHistory.snapshot(), wattsHistory.snapshot(), clock)) {
strip = strip.next()
SessionPrefs.setStatsStrip(context, strip.id)
}
}
race?.let { r ->
val shown = dash.resolve(r.source)
traceTick.let {
RaceDashView(shown, r, TraceData(throttleTrace.snapshot(), brakeTrace.snapshot(), speedTrace.snapshot()), shownUnit) {
dash = StatsDash.tapped(shown)
SessionPrefs.setStatsDash(context, dash.id)
}
}
}
if (thunder.isNotEmpty()) {
if (FlightLabels.drawable(thunder)) FlightDash(thunder)
else TelemetryCard(stringResource(R.string.bottom_telemetry_war_thunder)) { ValueGrid(thunder.take(GameStatusFiles.WAR_THUNDER_ROWS)) }
}
elite?.let { e ->
if (e.pips != null || e.fuelMain != null) ShipDash(e)
else TelemetryCard(stringResource(R.string.bottom_telemetry_elite)) {
ValueGrid(listOfNotNull(
e.fuelMain?.let { stringResource(R.string.bottom_telemetry_fuel) to "%.1f t".format(it) },
e.cargo?.let { stringResource(R.string.bottom_telemetry_cargo) to "%.0f t".format(it) },
e.pips?.takeIf { it.size == 3 }?.let { p ->
stringResource(R.string.bottom_telemetry_pips) to p.joinToString(" · ") { "%.1f".format(it / 2f) }
},
e.legal?.let { stringResource(R.string.bottom_telemetry_legal) to it },
e.balance?.let { stringResource(R.string.bottom_telemetry_balance) to "%,d CR".format(it) },
))
}
}
if (race == null && thunder.isEmpty() && elite == null) {
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)) {
if (outputs.isNotEmpty()) SwitchRow(stringResource(R.string.bottom_telemetry_send_auto), stringResource(R.string.bottom_telemetry_send_auto_hint), auto, true) { want ->
scope.launch {
withContext(Dispatchers.IO) {
SessionPrefs.setTelemetryAuto(context, want)
if (want) TelemetryOutput.applyAutomatic(context, running)
else TelemetryOutput.restoreTargets(outputs, running).forEach { TelemetryOutput.set(it, false) }
}
auto = want
rescan++
}
}
for (game in outputs) {
val locked = TelemetryOutput.isRunning(game.prefixId, running)
val hint = if (locked) stringResource(R.string.bottom_telemetry_send_close, game.name) else null
SwitchRow(game.name, hint, game.on, !locked) { want ->
scope.launch {
val ok = withContext(Dispatchers.IO) {
val key = TelemetryOutput.key(game)
val off = SessionPrefs.telemetryOff(context)
SessionPrefs.setTelemetryOff(context, if (want) off - key else off + key)
TelemetryOutput.set(game, want)
}
outputFailed = if (ok) null else game.name
rescan++
}
}
}
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))
}
if (busyPorts.isNotEmpty()) {
Text(stringResource(R.string.bottom_telemetry_port_busy, busyPorts.sorted().joinToString()), fontSize = 13.sp,
color = colors.error, modifier = Modifier.padding(horizontal = 4.dp))
}
ChoiceRow(stringResource(R.string.stats_speed_units),
if (speedUnit == SpeedUnit.AUTO) stringResource(R.string.stats_speed_units_auto, shownUnit.label) else speedUnit.label) {
speedUnit = speedUnit.next()
SessionPrefs.setStatsSpeedUnit(context, speedUnit.id)
}
Text(stringResource(R.string.stats_tap_hint), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp))
}
}
private fun httpGet(url: String): String {
val c = URL(url).openConnection() as HttpURLConnection
c.connectTimeout = 300
c.readTimeout = 500
return try {
c.inputStream.bufferedReader().use { it.readText() }
} finally {
c.disconnect()
}
}
@Composable
private fun ChoiceRow(title: String, value: String, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
Row(Modifier.fillMaxWidth().clickable(role = Role.Button, onClick = onClick).padding(horizontal = 4.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically) {
Text(title, fontSize = 15.sp, color = colors.onBackground, modifier = Modifier.weight(1f))
Text(value, fontSize = 15.sp, fontWeight = FontWeight.Bold, color = LocalPalette.current.primary)
}
}
@Composable
private fun SwitchRow(title: String, hint: String?, checked: Boolean, enabled: Boolean, onChange: (Boolean) -> Unit) {
val colors = MaterialTheme.colorScheme
Row(
Modifier.fillMaxWidth().toggleable(checked, enabled = enabled, role = Role.Switch, onValueChange = onChange).padding(vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Column(Modifier.weight(1f).padding(end = 12.dp)) {
Text(title, fontSize = 15.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (hint != null) Text(hint, fontSize = 12.sp, color = colors.onSurfaceVariant)
}
val pal = LocalPalette.current
Switch(checked, null, enabled = enabled, colors = SwitchDefaults.colors(
disabledCheckedTrackColor = pal.primary.copy(alpha = 0.45f),
disabledCheckedThumbColor = colors.background,
disabledCheckedBorderColor = pal.primary.copy(alpha = 0.45f),
))
}
}
@Composable
private fun TelemetryCard(title: String, content: @Composable () -> Unit) {
val pal = LocalPalette.current
Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(14.dp)).background(pal.surface).padding(12.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(title, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = pal.signal)
content()
}
}
@Composable
private fun ValueGrid(rows: List<Pair<String, String>>) {
val colors = MaterialTheme.colorScheme
rows.chunked(2).forEach { pair ->
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
pair.forEach { (k, v) ->
Row(Modifier.weight(1f)) {
Text(k, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
Text(v, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1)
}
}
if (pair.size == 1) Box(Modifier.weight(1f))
}
}
}
internal fun lapTime(seconds: Float): String {
val total = kotlin.math.round(seconds * 1000.0).toLong()
return "%d:%02d.%03d".format(total / 60_000, total / 1000 % 60, total % 1000)
}
@@ -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)
}
@@ -46,6 +46,8 @@ fun PerformancePage(
fsyncFirst: Boolean,
gamescopeRealtime: Boolean,
gpuClockPin: Boolean,
performanceBoost: Boolean,
boostCheck: Boolean,
ramCapMb: Int,
zramClient: Boolean,
vramCapMb: Int,
@@ -67,6 +69,8 @@ fun PerformancePage(
onFsyncFirst: (Boolean) -> Unit,
onGamescopeRealtime: (Boolean) -> Unit,
onGpuClockPin: (Boolean) -> Unit,
onPerformanceBoost: (Boolean) -> Unit,
onBoostCheck: (Boolean) -> Unit,
onRamCapMb: (Int) -> Unit,
onZramClient: (Boolean) -> Unit,
onVramCapMb: (Int) -> Unit,
@@ -126,6 +130,18 @@ fun PerformancePage(
gamescopeRealtime, onChange = onGamescopeRealtime,
)
}
SettingsGroup(stringResource(R.string.perf_boost_group)) {
ToggleRow(
host, "boost", stringResource(R.string.perf_boost),
stringResource(R.string.perf_boost_hint),
performanceBoost, onChange = onPerformanceBoost,
)
ToggleRow(
host, "boostcheck", stringResource(R.string.perf_boost_check),
stringResource(R.string.perf_boost_check_hint),
boostCheck, enabled = performanceBoost, onChange = onBoostCheck,
)
}
SettingsGroup(stringResource(R.string.perf_gpu)) {
ToggleRow(
host, "gpuclock", stringResource(R.string.perf_gpuclock),
@@ -56,11 +56,9 @@ class SecondScreenPresentation(
private val onKeyboardClosed: () -> Unit = {},
private val onMenu: (() -> Unit)? = null,
private val menu: (@androidx.compose.runtime.Composable () -> Unit)? = null,
private val dashboard: (@androidx.compose.runtime.Composable () -> Unit)? = null,
) : Presentation(sessionActivity, display) {
private val frame = FrameLayout(context)
private var menuView: androidx.compose.ui.platform.ComposeView? = null
private var dashboardView: androidx.compose.ui.platform.ComposeView? = null
var menuShown = false
private set
private val root = LinearLayout(context).apply {
@@ -157,7 +155,12 @@ class SecondScreenPresentation(
menuShown = on
if (on) {
keyboardHost?.takeIf { it.shown }?.hide()
ownComposeViews()
window?.decorView?.let { decor ->
decor.setViewTreeLifecycleOwner(sessionActivity)
decor.setViewTreeViewModelStoreOwner(sessionActivity)
decor.setViewTreeSavedStateRegistryOwner(sessionActivity)
decor.setViewTreeOnBackPressedDispatcherOwner(sessionActivity)
}
val view = menuView ?: androidx.compose.ui.platform.ComposeView(context).apply {
isFocusable = true
isFocusableInTouchMode = true
@@ -176,22 +179,12 @@ class SecondScreenPresentation(
}
}
private fun ownComposeViews() {
window?.decorView?.let { decor ->
decor.setViewTreeLifecycleOwner(sessionActivity)
decor.setViewTreeViewModelStoreOwner(sessionActivity)
decor.setViewTreeSavedStateRegistryOwner(sessionActivity)
decor.setViewTreeOnBackPressedDispatcherOwner(sessionActivity)
}
}
fun focusMenu(): Boolean = menuView?.requestFocus() == true
fun dispatchMenuKey(event: KeyEvent): Boolean = menuView?.dispatchKeyEvent(event) == true
fun closeControls() {
showMenu(false)
closeDashboard()
closeTerminal()
keyboardHost?.hide()
keyboardHost = null
@@ -199,8 +192,7 @@ class SecondScreenPresentation(
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
val ownKeys = currentMode == SecondScreenMode.TERMINAL || currentMode == SecondScreenMode.DASHBOARD
val forward = menuShown || !ownKeys || PadBridge.isControllerKeyEvent(event)
val forward = menuShown || currentMode != SecondScreenMode.TERMINAL || PadBridge.isControllerKeyEvent(event)
if (forward && sessionActivity.dispatchKeyEvent(event)) return true
return super.dispatchKeyEvent(event)
}
@@ -226,37 +218,19 @@ class SecondScreenPresentation(
keyboardButton = null
keyboardPending = false
closeTerminal()
closeDashboard()
root.removeAllViews()
val mode = when {
currentMode == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad -> SecondScreenMode.NONE
currentMode == SecondScreenMode.DASHBOARD && dashboard == null -> SecondScreenMode.NONE
else -> currentMode
}
val mode = if (currentMode == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad) SecondScreenMode.NONE
else currentMode
if (mode == SecondScreenMode.NONE) return
when (mode) {
SecondScreenMode.KEYBOARD_TRACKPAD -> renderKeyboardAndTrackpad()
SecondScreenMode.TERMINAL -> renderTerminal()
SecondScreenMode.DECK_CONTROLS -> root.addView(DeckControlsPanel(context, onClose, onSteamMenu, onQam, pad, onMenu = onMenu), weightParams())
SecondScreenMode.DASHBOARD -> renderDashboard()
SecondScreenMode.NONE -> Unit
}
}
private fun renderDashboard() {
val content = dashboard ?: return
ownComposeViews()
val view = androidx.compose.ui.platform.ComposeView(context).apply { setContent { content() } }
dashboardView = view
root.addView(view, weightParams())
}
private fun closeDashboard() {
dashboardView?.disposeComposition()
dashboardView = null
}
private fun renderKeyboardAndTrackpad() {
val panel = FrameLayout(context)
panel.addView(trackpadView(), FrameLayout.LayoutParams(-1, -1))
@@ -31,7 +31,6 @@ import androidx.compose.material.icons.Icons
import androidx.compose.foundation.layout.heightIn
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material.icons.outlined.Terminal
import androidx.compose.material.icons.outlined.Dashboard
import androidx.compose.material.icons.outlined.Keyboard
import androidx.compose.material.icons.outlined.AutoFixHigh
import androidx.compose.material.icons.outlined.ExpandMore
@@ -241,7 +240,6 @@ class DrawerActions(
val textureAnisotropy: Int? = 0,
val textureLodBias: String? = TextureFiltering.LOD_BIAS_OFF,
val secondScreenMode: SecondScreenMode,
val dashboardAvailable: Boolean = false,
val secondScreenDisplays: List<SecondScreenDisplay>,
val selectedSecondScreenDisplay: Int,
val onHud: (Boolean) -> Unit,
@@ -895,7 +893,6 @@ private fun BottomScreenModes(a: DrawerActions, modifier: Modifier, onPick: () -
if (com.droiddeck.launcher.session.SessionState.deckPad) add(SecondScreenMode.DECK_CONTROLS to Icons.Outlined.SportsEsports)
add(SecondScreenMode.KEYBOARD_TRACKPAD to Icons.Outlined.Keyboard)
add(SecondScreenMode.TERMINAL to Icons.Outlined.Terminal)
if (a.dashboardAvailable) add(SecondScreenMode.DASHBOARD to Icons.Outlined.Dashboard)
}
Row(
verticalAlignment = Alignment.CenterVertically,
@@ -1193,8 +1190,7 @@ private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String)
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val modes = listOf(SecondScreenMode.NONE, SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.TERMINAL) +
(if (com.droiddeck.launcher.session.SessionState.deckPad) listOf(SecondScreenMode.DECK_CONTROLS) else emptyList()) +
(if (a.dashboardAvailable) listOf(SecondScreenMode.DASHBOARD) else emptyList())
if (com.droiddeck.launcher.session.SessionState.deckPad) listOf(SecondScreenMode.DECK_CONTROLS) else emptyList()
SettingsGroup(stringResource(R.string.drawer_second_screen_mode)) {
Column(Modifier.fillMaxWidth().selectableGroup()) {
modes.forEach { mode ->
@@ -1,588 +0,0 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextMeasurer
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.GameStatusFiles
import com.droiddeck.launcher.session.GameTelemetry
import com.droiddeck.launcher.session.SpeedUnit
import com.droiddeck.launcher.session.StatsDash
import com.droiddeck.launcher.session.Telemetry
import kotlin.math.abs
import kotlin.math.cos
import kotlin.math.floor
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
import kotlin.math.sin
private val DASH_H = 290.dp
/** Pedal and speed trace length: 150 readings at the page's 66 ms draw rate, about 10 s. */
internal const val TRACE_N = 150
internal class TraceData(val throttle: List<Float>, val brake: List<Float>, val speed: List<Float>)
/** The racing dash in [style] with speeds in [unit] (km/h or mph); a tap moves to the next one. */
@Composable
internal fun RaceDashView(style: StatsDash, t: Telemetry, trace: TraceData, unit: SpeedUnit, onTap: () -> Unit) {
Box(Modifier.fillMaxWidth().clickable(onClick = onTap)) {
when (style) {
StatsDash.AUTO, StatsDash.SPEEDOMETER -> SpeedometerDash(t, unit)
StatsDash.CIRCUIT -> CircuitDash(t, unit)
StatsDash.TRACE -> TraceDash(t, trace, unit)
StatsDash.DIALS -> DialsDash(t, unit)
StatsDash.GLANCE -> GlanceDash(t, unit)
}
}
}
private fun polar(cx: Float, cy: Float, r: Float, deg: Float): Offset {
val a = Math.toRadians((deg - 90f).toDouble())
return Offset(cx + r * cos(a).toFloat(), cy + r * sin(a).toFloat())
}
private const val DIAL_START = -125f
private const val DIAL_SWEEP = 250f
private fun dialAngle(v: Float, max: Float) = DIAL_START + DIAL_SWEEP * (v / max).coerceIn(0f, 1f)
/** A 250° dial face: track, optional red zone from [red], ticks and numbers every [major]. */
private fun DrawScope.dialFace(
cx: Float, cy: Float, r: Float, max: Float, major: Float, label: (Float) -> String,
measurer: TextMeasurer, labelStyle: TextStyle, tick: Color, minor: Color, track: Color, red: Float?, redColor: Color,
) {
val box = Size(2 * r, 2 * r)
val tl = Offset(cx - r, cy - r)
drawArc(track, DIAL_START - 90f, DIAL_SWEEP, false, topLeft = tl, size = box, style = Stroke(6.dp.toPx(), cap = StrokeCap.Round))
if (red != null && red < max) {
drawArc(redColor, dialAngle(red, max) - 90f, dialAngle(max, max) - dialAngle(red, max), false, topLeft = tl, size = box, style = Stroke(6.dp.toPx()))
}
val steps = (max / (major / 2f)).roundToInt()
for (i in 0..steps) {
val v = i * major / 2f
val isMajor = i % 2 == 0
val deg = dialAngle(v, max)
drawLine(if (isMajor) tick else minor, polar(cx, cy, r - (if (isMajor) 14.dp else 7.dp).toPx(), deg), polar(cx, cy, r - 2.dp.toPx(), deg),
strokeWidth = (if (isMajor) 2.5f else 1.2f).dp.toPx())
if (isMajor) {
val layout = measurer.measure(label(v), labelStyle)
val p = polar(cx, cy, r - 27.dp.toPx(), deg)
drawText(layout, topLeft = Offset(p.x - layout.size.width / 2f, p.y - layout.size.height / 2f))
}
}
}
private fun DrawScope.needle(cx: Float, cy: Float, len: Float, deg: Float, color: Color, hub: Color) {
drawLine(color, Offset(cx, cy), polar(cx, cy, len, deg), strokeWidth = 4.dp.toPx(), cap = StrokeCap.Round)
drawCircle(hub, radius = 7.dp.toPx(), center = Offset(cx, cy))
}
private fun speedValue(t: Telemetry, unit: SpeedUnit): Float = (t.speedKmh ?: 0f) * unit.perKmh
private fun speedScale(speed: Float, unit: SpeedUnit): Float =
if (unit == SpeedUnit.MPH) (if (speed > 130f) 200f else 140f) else (if (speed > 210f) 320f else 220f)
private fun rpmScale(t: Telemetry): Float = max(t.maxRpm ?: 9000f, t.rpm ?: 0f)
private fun speedText(t: Telemetry, unit: SpeedUnit) = t.speedKmh?.let { "%.0f".format(it * unit.perKmh) } ?: "–"
@Composable
private fun unitAndGear(t: Telemetry, unit: SpeedUnit) = "${unit.label} · ${stringResource(R.string.stats_gear)} ${t.gear ?: "–"}"
@Composable
private fun SpeedometerDash(t: Telemetry, unit: SpeedUnit) {
val colors = MaterialTheme.colorScheme
val accent = LocalPalette.current.primary
Row(Modifier.fillMaxWidth().height(DASH_H), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
StatsCard(stringResource(R.string.stats_speed), Modifier.weight(1.55f).fillMaxHeight()) {
Box(Modifier.fillMaxWidth().weight(1f)) {
SpeedDial(t, unit, Modifier.fillMaxSize())
Column(Modifier.align(Alignment.BottomCenter), horizontalAlignment = Alignment.CenterHorizontally) {
Text(speedText(t, unit), fontSize = 44.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = accent)
Text(unitAndGear(t, unit), fontSize = 16.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = colors.onBackground)
Text(t.rpm?.let { "%,.0f rpm".format(it) } ?: "", fontSize = 11.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
}
}
}
Column(Modifier.weight(1f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
StatsCard(stringResource(R.string.stats_pedals), Modifier.fillMaxWidth().weight(1f)) { Pedals(t, Modifier.fillMaxWidth().weight(1f)) }
if (t.gLat != null && t.gLon != null) {
StatsCard(stringResource(R.string.stats_gforce), Modifier.fillMaxWidth().weight(1f)) { GForce(t, Modifier.fillMaxWidth().weight(1f)) }
}
}
}
}
@Composable
private fun SpeedDial(t: Telemetry, unit: SpeedUnit, modifier: Modifier) {
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
val measurer = rememberTextMeasurer()
val labelStyle = TextStyle(color = colors.onSurfaceVariant, fontSize = 11.sp, fontFamily = FontFamily.Monospace)
val speed = speedValue(t, unit)
val vmax = speedScale(speed, unit)
val rpmFraction = ((t.rpm ?: 0f) / rpmScale(t)).coerceIn(0f, 1f)
Canvas(modifier) {
val r = min(size.width * 0.42f, size.height * 0.47f)
val cx = size.width / 2f
val cy = r + 12.dp.toPx()
dialFace(cx, cy, r, vmax, 20f, { "%.0f".format(it) }, measurer, labelStyle, colors.onBackground, colors.onSurfaceVariant, pal.line, null, StatsColors.brake)
val rr = r + 9.dp.toPx()
val box = Size(2 * rr, 2 * rr)
val tl = Offset(cx - rr, cy - rr)
drawArc(pal.line, DIAL_START - 90f, DIAL_SWEEP, false, topLeft = tl, size = box, style = Stroke(5.dp.toPx(), cap = StrokeCap.Round))
if (rpmFraction > 0f) drawArc(if (rpmFraction > 0.9f) StatsColors.brake else pal.primary, DIAL_START - 90f, DIAL_SWEEP * rpmFraction, false,
topLeft = tl, size = box, style = Stroke(5.dp.toPx(), cap = StrokeCap.Round))
needle(cx, cy, r - 16.dp.toPx(), dialAngle(speed, vmax), colors.onBackground, pal.primary)
}
}
@Composable
private fun Pedals(t: Telemetry, modifier: Modifier) {
Row(modifier, horizontalArrangement = Arrangement.SpaceEvenly) {
PedalBar("THR", t.throttle, StatsColors.throttle)
PedalBar("BRK", t.brake, StatsColors.brake)
}
}
@Composable
private fun PedalBar(label: String, value: Float?, color: Color) {
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
Column(Modifier.fillMaxHeight(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(3.dp)) {
Text(value?.let { "${(it * 100).roundToInt()}%" } ?: "–", fontSize = 11.sp, fontFamily = FontFamily.Monospace, color = colors.onBackground)
Box(Modifier.weight(1f).width(26.dp).clip(RoundedCornerShape(6.dp)).background(pal.line)) {
Box(Modifier.fillMaxWidth().fillMaxHeight((value ?: 0f).coerceIn(0f, 1f)).align(Alignment.BottomCenter).background(color))
}
Text(label, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = colors.onSurfaceVariant)
}
}
@Composable
private fun GForce(t: Telemetry, modifier: Modifier) {
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
val g = kotlin.math.hypot(t.gLat ?: 0f, t.gLon ?: 0f)
Box(modifier) {
Canvas(Modifier.fillMaxSize()) {
val steerH = if (t.steer != null) 10.dp.toPx() else 0f
val r = min(size.width / 2f, (size.height - steerH) / 2f) - 2.dp.toPx()
val cx = size.width / 2f
val cy = (size.height - steerH) / 2f
for (k in listOf(1f, 0.62f, 0.24f)) drawCircle(pal.line, radius = r * k, center = Offset(cx, cy), style = Stroke(1.dp.toPx()))
drawLine(pal.line, Offset(cx - r, cy), Offset(cx + r, cy), strokeWidth = 1.dp.toPx())
drawLine(pal.line, Offset(cx, cy - r), Offset(cx, cy + r), strokeWidth = 1.dp.toPx())
val gx = (t.gLat ?: 0f).coerceIn(-2f, 2f) / 2f * r
val gy = (t.gLon ?: 0f).coerceIn(-2f, 2f) / 2f * r
drawCircle(colors.onBackground, radius = 6.dp.toPx(), center = Offset(cx + gx, cy - gy))
t.steer?.let { s ->
val y = size.height - 3.dp.toPx()
drawLine(pal.line, Offset(cx - r, y), Offset(cx + r, y), strokeWidth = 5.dp.toPx(), cap = StrokeCap.Round)
drawLine(pal.primary, Offset(cx, y), Offset(cx + s * r, y), strokeWidth = 5.dp.toPx(), cap = StrokeCap.Round)
}
}
Text("%.1f G".format(g), fontSize = 11.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant, modifier = Modifier.align(Alignment.TopEnd))
}
}
@Composable
private fun CircuitDash(t: Telemetry, unit: SpeedUnit) {
val colors = MaterialTheme.colorScheme
val accent = LocalPalette.current.primary
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
StatsCard(null, Modifier.fillMaxWidth()) { ShiftLights(t, Modifier.fillMaxWidth().height(20.dp)) }
Row(Modifier.fillMaxWidth().height(DASH_H - 48.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
StatsCard(stringResource(R.string.stats_timing), Modifier.weight(1f).fillMaxHeight()) {
KvRow(stringResource(R.string.bottom_telemetry_lap), t.lap?.let { lap -> t.laps?.let { "$lap / $it" } ?: "$lap" } ?: "–")
KvRow(stringResource(R.string.bottom_telemetry_position), t.position?.let { "P$it" } ?: "–")
KvRow(stringResource(R.string.bottom_telemetry_this_lap), t.currentLapS?.let { lapTime(it) } ?: "–")
KvRow(stringResource(R.string.bottom_telemetry_last_lap), t.lastLapS?.let { lapTime(it) } ?: "–")
t.bestLapS?.let { KvRow(stringResource(R.string.stats_best_lap), lapTime(it), accent) }
}
StatsCard("", Modifier.weight(1.2f).fillMaxHeight()) {
Column(Modifier.fillMaxWidth().weight(1f), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
Text(speedText(t, unit), fontSize = 72.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = accent)
Text(unitAndGear(t, unit), fontSize = 24.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = colors.onBackground)
Text(t.rpm?.let { rpm -> t.maxRpm?.let { "%,.0f / %,.0f rpm".format(rpm, it) } ?: "%,.0f rpm".format(rpm) } ?: "",
fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
}
}
val fuel = t.fuel
val tires = t.tireTempsC?.takeIf { it.size == 4 }
if (fuel != null || tires != null) Column(Modifier.weight(0.9f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
if (fuel != null) StatsCard(stringResource(R.string.bottom_telemetry_fuel), Modifier.fillMaxWidth().weight(1f)) {
Bar(fuel, colors.onBackground, Modifier.fillMaxWidth().height(14.dp))
Text("${(fuel * 100).roundToInt()}%", fontSize = 13.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
}
if (tires != null) StatsCard(stringResource(R.string.stats_tires), Modifier.fillMaxWidth().weight(1.3f)) { Tires(tires, Modifier.fillMaxWidth().weight(1f)) }
}
}
}
}
@Composable
private fun ShiftLights(t: Telemetry, modifier: Modifier) {
val pal = LocalPalette.current
val ratio = ((t.rpm ?: 0f) / rpmScale(t)).coerceIn(0f, 1f)
val lit = (((ratio - 0.6f) / 0.35f).coerceIn(0f, 1f) * 15).roundToInt()
val flash = ratio > 0.95f && (System.currentTimeMillis() / 120) % 2 == 0L
Canvas(modifier) {
val step = size.width / 15f
val r = min(size.height / 2f, step / 2f - 2.dp.toPx())
for (i in 0 until 15) {
val c = when {
flash -> pal.primary
i >= lit -> pal.line
i < 5 -> StatsColors.shiftGreen
i < 10 -> StatsColors.warn
i < 13 -> StatsColors.brake
else -> pal.primary
}
drawCircle(c, radius = r, center = Offset(step * i + step / 2f, size.height / 2f))
}
}
}
@Composable
private fun KvRow(label: String, value: String, valueColor: Color = MaterialTheme.colorScheme.onBackground) {
Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Text(label, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f), maxLines = 1)
Text(value, fontSize = 15.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = valueColor, maxLines = 1)
}
}
@Composable
private fun Bar(fraction: Float, color: Color, modifier: Modifier) {
Box(modifier.clip(RoundedCornerShape(5.dp)).background(LocalPalette.current.line)) {
Box(Modifier.fillMaxWidth(fraction.coerceIn(0f, 1f)).fillMaxHeight().background(color))
}
}
@Composable
private fun Tires(tires: List<Float>, modifier: Modifier) {
Column(modifier, verticalArrangement = Arrangement.spacedBy(6.dp)) {
Row(Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
TireBox(tires[0], Modifier.weight(1f).fillMaxHeight())
TireBox(tires[1], Modifier.weight(1f).fillMaxHeight())
}
Row(Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
TireBox(tires[2], Modifier.weight(1f).fillMaxHeight())
TireBox(tires[3], Modifier.weight(1f).fillMaxHeight())
}
}
}
@Composable
private fun TireBox(c: Float, modifier: Modifier) {
val bg = when {
c > 100f -> Color(0xFF5A2A2C)
c < 70f -> Color(0xFF1D3550)
else -> Color(0xFF23352B)
}
Box(modifier.clip(RoundedCornerShape(6.dp)).background(bg), contentAlignment = Alignment.Center) {
Text("%.0f".format(c), fontSize = 13.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = MaterialTheme.colorScheme.onBackground)
}
}
@Composable
private fun TraceDash(t: Telemetry, trace: TraceData, unit: SpeedUnit) {
val colors = MaterialTheme.colorScheme
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
StatsCard(stringResource(R.string.stats_trace), Modifier.fillMaxWidth().height(168.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
Legend(StatsColors.throttle, "${stringResource(R.string.stats_throttle)} ${t.throttle?.let { (it * 100).roundToInt() } ?: 0}%")
Legend(StatsColors.brake, "${stringResource(R.string.stats_brake)} ${t.brake?.let { (it * 100).roundToInt() } ?: 0}%")
}
TraceChart(listOf(trace.throttle to StatsColors.throttle, trace.brake to StatsColors.brake), 1f, Modifier.fillMaxWidth().weight(1f))
}
val speeds = trace.speed.map { it * unit.perKmh }
val top = max(if (unit == SpeedUnit.MPH) 125f else 200f, (speeds.maxOrNull() ?: 0f) * 1.1f)
StatsCard(stringResource(R.string.stats_speed_chart, unit.label), Modifier.fillMaxWidth().height(114.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(14.dp)) {
Legend(StatsColors.speed, "${stringResource(R.string.stats_speed)} ${speedText(t, unit)}")
Text("0 – %.0f".format(top), fontSize = 11.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
}
TraceChart(listOf(speeds to StatsColors.speed), top, Modifier.fillMaxWidth().weight(1f))
}
}
}
@Composable
private fun Legend(color: Color, text: String) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp)) {
Box(Modifier.size(8.dp).clip(CircleShape).background(color))
Text(text, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = MaterialTheme.colorScheme.onBackground, maxLines = 1)
}
}
@Composable
private fun TraceChart(series: List<Pair<List<Float>, Color>>, max: Float, modifier: Modifier) {
val pal = LocalPalette.current
Canvas(modifier) {
for (k in listOf(0f, 0.5f, 1f)) {
val y = size.height - k * size.height
drawLine(pal.line, Offset(0f, y), Offset(size.width, y), strokeWidth = 1.dp.toPx())
}
for ((values, color) in series) {
if (values.size < 2) continue
val path = Path()
val offset = TRACE_N - values.size
values.forEachIndexed { i, v ->
val x = (i + offset) / (TRACE_N - 1f) * size.width
val y = size.height - (v / max).coerceIn(0f, 1f) * size.height
if (i == 0) path.moveTo(x, y) else path.lineTo(x, y)
}
drawPath(path, color, style = Stroke(width = 2.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round))
}
}
}
@Composable
private fun DialsDash(t: Telemetry, unit: SpeedUnit) {
val colors = MaterialTheme.colorScheme
val rpmMax = (rpmScale(t) / 1000f).let { kotlin.math.ceil(it) * 1000f }
val hasExtras = t.lights != null || t.turboBar != null || t.engineTempC != null || t.oilTempC != null
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Row(Modifier.fillMaxWidth().height(if (hasExtras) DASH_H - 56.dp else DASH_H), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
StatsCard("", Modifier.weight(1f).fillMaxHeight()) {
val speed = speedValue(t, unit)
ArcDial(speed, speedScale(speed, unit), if (unit == SpeedUnit.MPH) 20f else 40f, { "%.0f".format(it) }, null,
speedText(t, unit), unit.label, Modifier.fillMaxWidth().weight(1f))
}
StatsCard("", Modifier.weight(1f).fillMaxHeight()) {
ArcDial(t.rpm ?: 0f, rpmMax, 1000f, { "%.0f".format(it / 1000f) }, t.maxRpm?.let { it * 0.9f },
t.rpm?.let { "%,.0f".format(it) } ?: "–", "rpm × 1000 · ${t.gear ?: "–"}", Modifier.fillMaxWidth().weight(1f))
}
}
if (hasExtras) StatsCard(stringResource(R.string.stats_lights), Modifier.fillMaxWidth()) {
Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
t.lights?.let { on ->
Lamp(stringResource(R.string.stats_lamp_shift), on and GameTelemetry.DL_SHIFT != 0, LocalPalette.current.primary)
Lamp(stringResource(R.string.stats_lamp_handbrake), on and GameTelemetry.DL_HANDBRAKE != 0, StatsColors.brake)
Lamp(stringResource(R.string.stats_lamp_pit), on and GameTelemetry.DL_PITSPEED != 0, StatsColors.warn)
Lamp(stringResource(R.string.stats_lamp_tc), on and GameTelemetry.DL_TC != 0, StatsColors.warn)
Lamp(stringResource(R.string.stats_lamp_abs), on and GameTelemetry.DL_ABS != 0, StatsColors.warn)
}
t.turboBar?.let { Lamp(stringResource(R.string.stats_turbo, "%.1f".format(it)), false, colors.onBackground) }
t.engineTempC?.let { Lamp(stringResource(R.string.stats_engine_temp, "%.0f".format(it)), false, colors.onBackground) }
t.oilTempC?.let { Lamp(stringResource(R.string.stats_oil_temp, "%.0f".format(it)), false, colors.onBackground) }
}
}
}
}
@Composable
private fun ArcDial(value: Float, max: Float, major: Float, label: (Float) -> String, red: Float?, readout: String, unit: String, modifier: Modifier) {
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
val measurer = rememberTextMeasurer()
val labelStyle = TextStyle(color = colors.onSurfaceVariant, fontSize = 11.sp, fontFamily = FontFamily.Monospace)
Box(modifier) {
Canvas(Modifier.fillMaxSize()) {
val r = min(size.width * 0.46f, size.height * 0.5f)
val cx = size.width / 2f
val cy = r + 6.dp.toPx()
dialFace(cx, cy, r, max, major, label, measurer, labelStyle, colors.onBackground, colors.onSurfaceVariant, pal.line, red, StatsColors.brake)
needle(cx, cy, r - 18.dp.toPx(), dialAngle(value, max), colors.onBackground, pal.primary)
}
Column(Modifier.align(Alignment.BottomCenter), horizontalAlignment = Alignment.CenterHorizontally) {
Text(readout, fontSize = 22.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = colors.onBackground)
Text(unit, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1)
}
}
}
@Composable
private fun Lamp(label: String, on: Boolean, color: Color) {
val pal = LocalPalette.current
val shape = RoundedCornerShape(8.dp)
Text(label, fontSize = 12.sp, fontFamily = FontFamily.Monospace, fontWeight = if (on) FontWeight.Bold else FontWeight.Normal,
color = if (on) MaterialTheme.colorScheme.background else MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1,
modifier = Modifier.clip(shape).background(if (on) color else Color.Transparent).border(1.dp, if (on) color else pal.line, shape)
.padding(horizontal = 10.dp, vertical = 4.dp))
}
@Composable
private fun GlanceDash(t: Telemetry, unit: SpeedUnit) {
val colors = MaterialTheme.colorScheme
val accent = LocalPalette.current.primary
val ratio = ((t.rpm ?: 0f) / rpmScale(t)).coerceIn(0f, 1f)
Row(Modifier.fillMaxWidth().height(DASH_H), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
EdgeBar(t.throttle, StatsColors.throttle)
StatsCard("", Modifier.weight(1f).fillMaxHeight()) {
Bar(ratio, if (ratio > 0.9f) StatsColors.brake else accent, Modifier.fillMaxWidth().height(14.dp))
Column(Modifier.fillMaxWidth().weight(1f), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
Text(speedText(t, unit), fontSize = 110.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = accent, lineHeight = 112.sp)
Text(unitAndGear(t, unit), fontSize = 34.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = colors.onBackground)
}
}
EdgeBar(t.brake, StatsColors.brake)
}
}
@Composable
private fun EdgeBar(value: Float?, color: Color) {
Box(Modifier.width(14.dp).fillMaxHeight().clip(RoundedCornerShape(5.dp)).background(LocalPalette.current.line)) {
Box(Modifier.fillMaxWidth().fillMaxHeight((value ?: 0f).coerceIn(0f, 1f)).align(Alignment.BottomCenter).background(color))
}
}
/** War Thunder's own labels the Flight layout places; others stay in the list. */
internal object FlightLabels {
const val IAS = "IAS, km/h"
const val ALTITUDE = "H, m"
const val G = "Ny"
const val FUEL = "Mfuel, kg"
const val THROTTLE = "throttle 1, %"
fun drawable(rows: List<Pair<String, String>>): Boolean = rows.any { it.first == IAS || it.first == ALTITUDE }
}
@Composable
internal fun FlightDash(rows: List<Pair<String, String>>) {
val colors = MaterialTheme.colorScheme
val v = rows.toMap()
fun num(key: String) = v[key]?.toFloatOrNull()
Row(Modifier.fillMaxWidth().height(DASH_H), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
StatsCard(FlightLabels.IAS, Modifier.weight(1f).fillMaxHeight()) {
num(FlightLabels.IAS)?.let { Tape(it, 10f, 50f, Modifier.fillMaxWidth().weight(1f)) } ?: Text("–", color = colors.onSurfaceVariant)
}
Column(Modifier.weight(1.3f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
StatsCard(FlightLabels.THROTTLE, Modifier.fillMaxWidth().weight(1f)) {
val thr = num(FlightLabels.THROTTLE)
Bar((thr ?: 0f) / 110f, StatsColors.throttle, Modifier.fillMaxWidth().height(16.dp))
Text(thr?.let { "%.0f%%".format(it) } ?: "–", fontSize = 13.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
}
StatsCard(FlightLabels.G, Modifier.fillMaxWidth().weight(1f)) {
Text(num(FlightLabels.G)?.let { "%.1f".format(it) } ?: "–", fontSize = 34.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace,
color = colors.onBackground)
num(FlightLabels.FUEL)?.let { Text("${FlightLabels.FUEL} %.0f".format(it), fontSize = 12.sp, color = colors.onSurfaceVariant) }
}
}
StatsCard(FlightLabels.ALTITUDE, Modifier.weight(1f).fillMaxHeight()) {
num(FlightLabels.ALTITUDE)?.let { Tape(it, 100f, 500f, Modifier.fillMaxWidth().weight(1f)) } ?: Text("–", color = colors.onSurfaceVariant)
}
}
}
@Composable
private fun Tape(value: Float, step: Float, every: Float, modifier: Modifier) {
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
val measurer = rememberTextMeasurer()
val small = TextStyle(color = colors.onSurfaceVariant, fontSize = 11.sp, fontFamily = FontFamily.Monospace)
val big = TextStyle(color = colors.onBackground, fontSize = 18.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace)
Canvas(modifier) {
val cy = size.height / 2f
val px = (size.height / 2f) / (step * 4f)
val boxH = 32.dp.toPx()
var m = floor((value - step * 5f) / step) * step
while (m < value + step * 6f) {
val y = cy - (m - value) * px
if (y in 0f..size.height) {
val labelled = abs((m / every).roundToInt() * every - m) < 0.01f
drawLine(colors.onSurfaceVariant, Offset(size.width * 0.74f, y), Offset(size.width, y), strokeWidth = (if (labelled) 2.5f else 1f).dp.toPx())
if (labelled && abs(y - cy) > boxH * 0.75f) {
val layout = measurer.measure("%.0f".format(m), small)
drawText(layout, topLeft = Offset(size.width * 0.70f - layout.size.width, y - layout.size.height / 2f))
}
}
m += step
}
drawRoundRect(pal.primary, topLeft = Offset(1.dp.toPx(), cy - boxH / 2f), size = Size(size.width - 2.dp.toPx(), boxH),
cornerRadius = CornerRadius(8.dp.toPx()), style = Stroke(2.dp.toPx()))
val layout = measurer.measure("%.0f".format(value), big)
drawText(layout, topLeft = Offset(size.width / 2f - layout.size.width / 2f, cy - layout.size.height / 2f))
}
}
@Composable
internal fun ShipDash(e: GameStatusFiles.Elite) {
val colors = MaterialTheme.colorScheme
Row(Modifier.fillMaxWidth().height(210.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
StatsCard(stringResource(R.string.stats_power), Modifier.weight(1.2f).fillMaxHeight()) {
e.pips?.takeIf { it.size == 3 }?.let { Pips(it, Modifier.fillMaxWidth().weight(1f)) } ?: Text("–", color = colors.onSurfaceVariant)
}
Column(Modifier.weight(1f).fillMaxHeight(), verticalArrangement = Arrangement.spacedBy(8.dp)) {
StatsCard(stringResource(R.string.stats_fuel_t), Modifier.fillMaxWidth().weight(1f)) {
e.fuelMain?.let { Text(stringResource(R.string.stats_fuel_main, "%.1f".format(it)), fontSize = 15.sp, fontWeight = FontWeight.Bold,
fontFamily = FontFamily.Monospace, color = colors.onBackground) }
e.fuelReserve?.let { Text(stringResource(R.string.stats_fuel_reserve, "%.2f".format(it)), fontSize = 12.sp, color = colors.onSurfaceVariant) }
}
StatsCard("", Modifier.fillMaxWidth().weight(1f)) {
e.cargo?.let { KvRow(stringResource(R.string.bottom_telemetry_cargo), "%.0f t".format(it)) }
e.legal?.let { KvRow(stringResource(R.string.bottom_telemetry_legal), it, if (it == "Clean") StatsColors.gpu else StatsColors.warn) }
e.balance?.let { KvRow(stringResource(R.string.bottom_telemetry_balance), "%,d CR".format(it)) }
}
}
}
}
@Composable
private fun Pips(pips: List<Int>, modifier: Modifier) {
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
val measurer = rememberTextMeasurer()
val style = TextStyle(color = colors.onSurfaceVariant, fontSize = 12.sp, fontWeight = FontWeight.Bold)
val names = listOf("SYS", "ENG", "WEP")
Canvas(modifier) {
val colW = size.width / 3f
val pipW = colW * 0.62f
val labelH = 18.dp.toPx()
val pipH = (size.height - labelH) / 4f - 4.dp.toPx()
for (col in 0 until 3) {
val x = col * colW + (colW - pipW) / 2f
// Status.json counts half pips: 0..8 per system.
val value = pips[col] / 2f
for (i in 0 until 4) {
val y = size.height - labelH - (i + 1) * (pipH + 4.dp.toPx())
drawRoundRect(pal.line, topLeft = Offset(x, y), size = Size(pipW, pipH), cornerRadius = CornerRadius(4.dp.toPx()))
val fill = (value - i).coerceIn(0f, 1f)
if (fill > 0f) drawRoundRect(pal.primary, topLeft = Offset(x, y), size = Size(pipW * fill, pipH), cornerRadius = CornerRadius(4.dp.toPx()))
}
val layout = measurer.measure(names[col], style)
drawText(layout, topLeft = Offset(col * colW + colW / 2f - layout.size.width / 2f, size.height - layout.size.height))
}
}
}
@@ -1,288 +0,0 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.graphics.nativeCanvas
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.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.hud.DroidDeckMark
import com.droiddeck.launcher.hud.HudMetrics
import com.droiddeck.launcher.session.StatsStrip
import kotlin.math.max
import kotlin.math.roundToInt
/** FusionHUD's metric colors, so the bottom screen reads like the HUD on the top screen. */
internal object StatsColors {
val cpu = Color(0xFF58A6FF)
val gpu = Color(0xFF5EE08A)
val ram = Color(0xFFFF7BC0)
val bat = Color(0xFFFFAB5E)
// Throttle and brake stay apart for red-green colour blindness (checked against the dark surface).
val throttle = Color(0xFF14A39A)
val brake = Color(0xFFE5484D)
val speed = Color(0xFF2E8FD6)
val warn = Color(0xFFF2C94C)
val shiftGreen = Color(0xFF2FB36A)
val badge = Color(0xFF0B0D10)
}
/** The last [capacity] readings, oldest first. */
internal class History(private val capacity: Int) {
private val values = ArrayDeque<Float>(capacity)
fun add(v: Float) {
if (values.size == capacity) values.removeFirst()
values.addLast(v)
}
fun snapshot(): List<Float> = values.toList()
}
private val MARK_RATIO = DroidDeckMark.widthFor(1f)
/** The DroidDeck mark (the split D with the blue orb), the same artwork the HUD draws. */
@Composable
internal fun DroidDeckLogo(height: Dp, modifier: Modifier = Modifier, body: Color = Color.White, orb: Color = LocalPalette.current.primary) {
Canvas(modifier.size(height * MARK_RATIO, height)) {
val b = body.toArgb()
val o = orb.toArgb()
drawIntoCanvas { DroidDeckMark.draw(it.nativeCanvas, 0f, 0f, size.height, b, o) }
}
}
@Composable
private fun LogoBadge(size: Dp) {
val shape = RoundedCornerShape(size * 0.22f)
Box(Modifier.size(size).clip(shape).background(StatsColors.badge).border(2.dp, LocalPalette.current.primary, shape), contentAlignment = Alignment.Center) {
DroidDeckLogo(size * 0.62f)
}
}
@Composable
private fun LogoHeader(clock: String) {
val colors = MaterialTheme.colorScheme
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.padding(horizontal = 2.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)
}
}
@Composable
internal fun Sparkline(values: List<Float>, min: Float, max: Float, color: Color, modifier: Modifier) {
Canvas(modifier) {
if (values.size < 2 || max <= min) return@Canvas
val path = Path()
values.forEachIndexed { i, v ->
val x = i / (values.size - 1f) * size.width
val y = size.height - ((v - min) / (max - min)).coerceIn(0f, 1f) * (size.height - 2f) - 1f
if (i == 0) path.moveTo(x, y) else path.lineTo(x, y)
}
drawPath(path, color, style = Stroke(width = 2.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round))
}
}
/** A readout card: dark surface, a thin accent edge and the DroidDeck mark before the title ("" = mark only). */
@Composable
internal fun StatsCard(title: String?, modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) {
val pal = LocalPalette.current
val shape = RoundedCornerShape(14.dp)
Column(
modifier.clip(shape).background(pal.surface).border(1.dp, pal.primary.copy(alpha = 0.22f), shape).padding(horizontal = 12.dp, vertical = 10.dp),
verticalArrangement = Arrangement.spacedBy(6.dp),
) {
if (title != null) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
DroidDeckLogo(12.dp, body = MaterialTheme.colorScheme.onSurfaceVariant)
if (title.isNotEmpty()) Text(title.uppercase(), fontSize = 11.sp, fontWeight = FontWeight.SemiBold, color = pal.primary, letterSpacing = 0.6.sp,
maxLines = 1, overflow = TextOverflow.Ellipsis)
}
content()
}
}
/** What the top strip shows; histories hold one reading a second, oldest first. */
internal class StripData(
val fps: Float?,
val device: HudMetrics.Snapshot?,
val fpsHistory: List<Float>,
val cpuHistory: List<Float>,
val gpuHistory: List<Float>,
val wattsHistory: List<Float>,
val clock: String,
)
private fun percentTemp(percent: Int?, temp: Int?): String =
listOfNotNull(percent?.let { "$it%" }, temp?.let { "$it°" }).joinToString(" · ").ifEmpty { "–" }
private fun batteryText(s: HudMetrics.Snapshot?): String =
listOfNotNull(s?.battery?.percent?.let { "$it%" }, s?.battery?.watts?.takeIf { it > 0f }?.let { "%.1f W".format(it) }).joinToString(" · ").ifEmpty { "–" }
private fun fpsText(fps: Float?): String = fps?.takeIf { it > 0f }?.let { "%.1f".format(it) } ?: "–"
/** The top strip; a tap moves to the next style. */
@Composable
internal fun StatsStripView(style: StatsStrip, d: StripData, onTap: () -> Unit) {
Box(Modifier.fillMaxWidth().clickable(onClick = onTap)) {
when (style) {
StatsStrip.PANEL -> PanelStrip(d)
StatsStrip.TILES -> TilesStrip(d)
StatsStrip.RINGS -> RingsStrip(d)
}
}
}
@Composable
private fun PanelStrip(d: StripData) {
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
val accent = pal.primary
val shape = RoundedCornerShape(18.dp)
Row(
Modifier.fillMaxWidth().clip(shape).background(pal.surface).border(2.dp, accent, shape).padding(horizontal = 12.dp, vertical = 10.dp),
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
) {
LogoBadge(40.dp)
Column(Modifier.widthIn(min = 84.dp)) {
Row(verticalAlignment = Alignment.Bottom) {
Text(fpsText(d.fps), fontSize = 30.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = accent, maxLines = 1)
Text(" fps", fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(bottom = 4.dp))
}
Text(d.fps?.takeIf { it > 0f }?.let { "%.1f ms".format(1000f / it) } ?: stringResource(R.string.stats_fps_needs_hud),
fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant, maxLines = 1)
}
Sparkline(d.fpsHistory.map { 1000f / max(it, 1f) }, 8f, 34f, lerp(accent, Color.White, 0.3f), Modifier.weight(1f).height(44.dp))
Column(verticalArrangement = Arrangement.spacedBy(1.dp)) {
MetricRow("CPU", percentTemp(d.device?.cpuPercent, d.device?.cpuTempC), StatsColors.cpu)
MetricRow("GPU", percentTemp(d.device?.gpuPercent, d.device?.gpuTempC), StatsColors.gpu)
MetricRow("RAM", d.device?.let { "${it.ramPercent.roundToInt()}%" } ?: "–", StatsColors.ram)
MetricRow("BAT", batteryText(d.device), StatsColors.bat)
}
}
}
@Composable
private fun MetricRow(label: String, value: String, color: Color) {
Row(verticalAlignment = Alignment.CenterVertically) {
Text(label, fontSize = 11.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = color, modifier = Modifier.width(36.dp))
Text(value, fontSize = 13.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = MaterialTheme.colorScheme.onBackground, maxLines = 1)
}
}
@Composable
private fun TilesStrip(d: StripData) {
val accent = LocalPalette.current.primary
val s = d.device
val gpuPercent: Int? = s?.gpuPercent
val gpuTemp: Int? = s?.gpuTempC
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
LogoHeader(d.clock)
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)
HistoryTile("GPU", StatsColors.gpu, gpuPercent?.let { "$it%" } ?: gpuTemp?.let { "$it°" } ?: "–",
if (gpuPercent != null) gpuTemp?.let { "$it°" } ?: "" else "", d.gpuHistory, 100f)
HistoryTile(stringResource(R.string.bottom_telemetry_battery).uppercase(), StatsColors.bat, s?.battery?.percent?.let { "$it%" } ?: "–",
s?.battery?.watts?.takeIf { it > 0f }?.let { "%.1fW".format(it) } ?: "", d.wattsHistory, 10f)
}
}
}
@Composable
private fun RowScope.HistoryTile(label: String, color: Color, value: String, unit: String, history: List<Float>, max: Float) {
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
Column(
Modifier.weight(1f).clip(RoundedCornerShape(12.dp)).background(pal.surface)
.drawBehind { drawRect(color, topLeft = Offset.Zero, size = Size(size.width, 3.dp.toPx())) }
.padding(start = 10.dp, end = 10.dp, top = 9.dp, bottom = 6.dp),
) {
Text(label, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = color, letterSpacing = 0.8.sp, maxLines = 1)
Row(verticalAlignment = Alignment.Bottom) {
Text(value, fontSize = 22.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = colors.onBackground, maxLines = 1)
if (unit.isNotEmpty()) Text(" $unit", fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, modifier = Modifier.padding(bottom = 3.dp))
}
Sparkline(history, 0f, max, color, Modifier.fillMaxWidth().height(24.dp))
}
}
@Composable
private fun RingsStrip(d: StripData) {
val s = d.device
val gpuPercent: Int? = s?.gpuPercent
val gpuTemp: Int? = s?.gpuTempC
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(6.dp)) {
LogoHeader(d.clock)
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°" } ?: "–",
if (gpuPercent != null) gpuTemp?.let { "$it °C" } ?: "" else "")
RingTile("RAM", StatsColors.ram, s?.ramPercent?.let { it / 100f }, s?.let { "${it.ramPercent.roundToInt()}%" } ?: "–",
s?.let { "%.1f of %.1f GB".format(it.ramUsedBytes / 1e9, it.ramTotalBytes / 1e9) } ?: "")
RingTile(stringResource(R.string.bottom_telemetry_battery).uppercase(), StatsColors.bat, s?.battery?.percent?.let { it / 100f },
s?.battery?.percent?.let { "$it%" } ?: "–", s?.battery?.watts?.takeIf { it > 0f }?.let { "%.1f W".format(it) } ?: "")
}
}
}
@Composable
private fun RowScope.RingTile(label: String, color: Color, fraction: Float?, center: String, sub: String) {
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
Row(
Modifier.weight(1f).clip(RoundedCornerShape(12.dp)).background(pal.surface).padding(8.dp),
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
Box(Modifier.size(52.dp), contentAlignment = Alignment.Center) {
Canvas(Modifier.fillMaxSize()) {
val w = 6.dp.toPx()
val tl = Offset(w / 2, w / 2)
val sz = Size(size.width - w, size.height - w)
drawArc(pal.line, 0f, 360f, false, topLeft = tl, size = sz, style = Stroke(width = w))
if (fraction != null) drawArc(color, -90f, (fraction.coerceIn(0f, 1f) * 360f).coerceAtLeast(1f), false, topLeft = tl, size = sz,
style = Stroke(width = w, cap = StrokeCap.Round))
}
Text(center, fontSize = 12.sp, fontWeight = FontWeight.Bold, fontFamily = FontFamily.Monospace, color = colors.onBackground, maxLines = 1)
}
Column {
Text(label, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = color, letterSpacing = 0.8.sp, maxLines = 1)
if (sub.isNotEmpty()) Text(sub, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
}
}
@@ -0,0 +1,20 @@
package com.samsung.sdk.sperf;
/**
* Entry points of libperfsdk.performance.samsung.so, the performance library in Samsung's firmware.
* The library binds them by this class name, so the name has to stay. Used by
* com.droiddeck.launcher.session.SamsungPerf; on other phones the library is missing.
*/
public final class Boost {
private Boost() {
}
/** Holds a resource (CPU_MIN, GPU_MIN...) at a value from the service's level table. */
public static native int requestBoost(int type, int value, int timeoutMs);
/** Lets go of everything this app holds. */
public static native int releaseBoost();
/** The package name the service gives out; the library refuses requests until it is set. */
public static native int setPkgName(String name);
}
+5 -85
View File
@@ -597,6 +597,11 @@
<string name="perf_noglerror_hint">Turns off per-call GL validation.</string>
<string name="perf_gsrealtime">gamescope: realtime GPU queue</string>
<string name="perf_gsrealtime_hint">Prioritizes the compositor\'s GPU work. Can smooth frame pacing at some cost to games.</string>
<string name="perf_boost_group">Boost</string>
<string name="perf_boost">Performance boost</string>
<string name="perf_boost_hint">Asks the phone to run the game\'s busiest threads on its fastest cores while the game falls behind. Lets go when the game keeps up, the phone is hot or battery saver is on. Android 12 or newer. Samsung phones also raise their CPU, GPU and memory clocks. More battery use and heat. What it did is in boost.log in the session\'s logs.</string>
<string name="perf_boost_check">Check the boost</string>
<string name="perf_boost_check_hint">For testing: during a game the boost takes turns on and paused (one minute on, then two paused, two on, and so on), and boost.log ends with a fair comparison and a verdict. The first minute is not counted. Play at least 7 minutes, then turn this off. A phone that gets too hot gives no verdict. A game that runs well without the boost is marked as not needing it.</string>
<string name="perf_gpu">GPU</string>
<string name="perf_memory">Memory</string>
<string name="perf_cap_off">Off</string>
@@ -1875,91 +1880,6 @@
<string name="second_mode_keyboard_trackpad">Keyboard + trackpad</string>
<string name="second_mode_terminal">Terminal</string>
<string name="second_mode_deck_controls">Deck grips + trackpads</string>
<string name="second_mode_dashboard">Dashboard</string>
<string name="bottom_dashboard_empty">Nothing to show here yet.</string>
<string name="bottom_page_downloads">Downloads</string>
<string name="bottom_downloads_none">No downloads running.</string>
<string name="bottom_downloads_steam">Steam</string>
<string name="bottom_downloads_shader">Downloading shader cache</string>
<string name="bottom_downloads_paused">Paused</string>
<string name="bottom_downloads_queued">Waiting to start</string>
<string name="bottom_page_notifications">Notifications</string>
<string name="bottom_notifications_listener">DroidDeck bottom screen</string>
<string name="bottom_notifications_why">Show messages and other notifications here while you play. They stay on this screen only and are not saved. Android asks once: its notification access page opens on this screen; turn DroidDeck on there and this page comes back by itself.</string>
<string name="bottom_notifications_allow">Allow notification access</string>
<string name="bottom_notifications_none">No notifications.</string>
<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="stats_fps_needs_hud">FPS needs the HUD on</string>
<string name="stats_speed">Speed</string>
<string name="stats_pedals">Pedals</string>
<string name="stats_gforce">G-force</string>
<string name="stats_timing">Timing</string>
<string name="stats_best_lap">Best lap</string>
<string name="stats_tires">Tires °C</string>
<string name="stats_trace">Throttle and brake, last 10 s</string>
<string name="stats_speed_chart">Speed, %1$s</string>
<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_throttle">Throttle</string>
<string name="stats_brake">Brake</string>
<string name="stats_lights">Dashboard</string>
<string name="stats_lamp_shift">Shift</string>
<string name="stats_lamp_handbrake">Handbrake</string>
<string name="stats_lamp_pit">Pit limiter</string>
<string name="stats_lamp_tc">TC</string>
<string name="stats_lamp_abs">ABS</string>
<string name="stats_turbo">Turbo %1$s bar</string>
<string name="stats_engine_temp">Engine %1$s °C</string>
<string name="stats_oil_temp">Oil %1$s °C</string>
<string name="stats_power">Power distributor</string>
<string name="stats_fuel_t">Fuel, t</string>
<string name="stats_fuel_main">Main %1$s t</string>
<string name="stats_fuel_reserve">Reserve %1$s t</string>
<string name="stats_tap_hint">Tap the top strip or the dash to change its style.</string>
<string name="bottom_telemetry_send_title">Send dashboard data</string>
<string name="bottom_telemetry_send_auto">Automatic</string>
<string name="bottom_telemetry_send_auto_hint">Turns it on for every game listed here, including games found later. Games you switch off stay off.</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>
<string name="bottom_shots_failed">Could not take a screenshot.</string>
<string name="bottom_shots_none">No screenshots yet.</string>
<string name="bottom_page_chat">Chat &amp; voice</string>
<string name="bottom_chat_why">Read and answer Steam chat here while the game keeps running on the main screen. It uses the account Steam is signed in with.</string>
<string name="bottom_chat_not_signed_in">Steam has no web sign-in to share yet, so sign in here once.</string>
<string name="bottom_chat_stopped">Android closed the chat page while DroidDeck was in the background. It opens again when you come back to DroidDeck.</string>
<string name="bottom_chat_open">Open Steam Chat</string>
<string name="bottom_chat_close">Close chat</string>
<string name="bottom_chat_mic_on">Mic on</string>
<string name="bottom_chat_mic_off">Mic off</string>
<string name="bottom_chat_mic_unavailable">Mic is off for this game. To talk, turn on Microphone in DroidDeck\'s Steam settings (Audio) and start the game again.</string>
<string name="bottom_chat_volume">Volume %1$d%%</string>
<string name="bottom_page_telemetry">In-game stats</string>
<string name="bottom_telemetry_fps">FPS</string>
<string name="bottom_telemetry_cpu">CPU</string>
<string name="bottom_telemetry_gpu">GPU</string>
<string name="bottom_telemetry_battery">Battery</string>
<string name="bottom_telemetry_lap">Lap</string>
<string name="bottom_telemetry_position">Position</string>
<string name="bottom_telemetry_this_lap">This lap</string>
<string name="bottom_telemetry_last_lap">Last lap</string>
<string name="bottom_telemetry_fuel">Fuel</string>
<string name="bottom_telemetry_cargo">Cargo</string>
<string name="bottom_telemetry_pips">Pips SYS · ENG · WEP</string>
<string name="bottom_telemetry_legal">Legal state</string>
<string name="bottom_telemetry_balance">Balance</string>
<string name="bottom_telemetry_war_thunder">War Thunder</string>
<string name="bottom_telemetry_elite">Elite Dangerous</string>
<string name="bottom_telemetry_help">Turn on a racing game\'s data output (often called telemetry or UDP) to see a live dash here. It stays on this device.</string>
<string name="bottom_telemetry_unknown_format">Port %1$d receives data (%2$d packets of %3$d bytes), but in a format this page cannot read yet.</string>
<string name="bottom_telemetry_port_busy">Another program already uses port %1$s, so that game cannot show here.</string>
<string name="rtinst_removing">Removing Linux runtime</string>
<plurals name="rtinst_removing_entries">
@@ -4,38 +4,23 @@ import org.junit.Assert.assertEquals
import org.junit.Test
class SecondScreenModeTest {
@Test fun withNothingRememberedTheDashboardOpens() {
assertEquals(SecondScreenMode.DASHBOARD, SecondScreenMode.opening(null, deckPad = true, dashboard = true))
assertEquals(SecondScreenMode.DASHBOARD, SecondScreenMode.opening(null, deckPad = false, dashboard = true))
}
@Test fun withNothingRememberedAndNoDashboardTheControllerPicksThePanel() {
@Test fun withNothingRememberedTheControllerPicksThePanel() {
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening(null, deckPad = true))
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening(null, deckPad = false))
}
@Test fun thePanelTheUserPickedLastOpensAgain() {
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("keyboard-trackpad", deckPad = true, dashboard = true))
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("deck-controls", deckPad = true, dashboard = true))
assertEquals(SecondScreenMode.TERMINAL, SecondScreenMode.opening("terminal", deckPad = true, dashboard = true))
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("keyboard-trackpad", deckPad = true))
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("deck-controls", deckPad = true))
assertEquals(SecondScreenMode.TERMINAL, SecondScreenMode.opening("terminal", deckPad = true))
}
@Test fun deckControlsNeedTheDeckPad() {
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("deck-controls", deckPad = false))
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("deck-controls", deckPad = false, dashboard = true))
}
@Test fun anUnknownOrClosedChoiceFallsBackToTheDefault() {
assertEquals(SecondScreenMode.DASHBOARD, SecondScreenMode.opening("none", deckPad = true, dashboard = true))
assertEquals(SecondScreenMode.DASHBOARD, SecondScreenMode.opening("gone", deckPad = false, dashboard = true))
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("none", deckPad = true))
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("gone", deckPad = false))
}
@Test fun theDashboardOpensAgainOnlyWhileItHasPages() {
assertEquals(SecondScreenMode.DASHBOARD, SecondScreenMode.opening("dashboard", deckPad = true, dashboard = true))
assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening("dashboard", deckPad = true, dashboard = false))
assertEquals(SecondScreenMode.KEYBOARD_TRACKPAD, SecondScreenMode.opening("dashboard", deckPad = false))
}
}
@@ -0,0 +1,120 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class BoostReportTest {
private fun side(fps: Int, seconds: Int = 200, milliamps: Int? = null, slow: Int = fps) =
BoostReport.Side().apply { repeat(seconds) { add(if (it < seconds / 10) slow else fps, milliamps, 0) } }
@Test fun `the CPU a thread ran on is field 39 of its stat, even with spaces in its name`() {
val fields = (3..52).map { if (it == 39) "7" else "0" }
assertEquals(7, BoostReport.processorOf("1234 (Main Thread) " + fields.joinToString(" ")))
assertNull(BoostReport.processorOf("1234 (short) S 1"))
}
@Test fun `cores are sorted into fastest, middle and slowest by top speed`() {
val tiers = BoostReport.tiers(mapOf(0 to 2.0, 1 to 2.0, 2 to 3.2, 3 to 3.2, 4 to 4.3))
assertEquals(mapOf(0 to 0, 1 to 0, 2 to 1, 3 to 1, 4 to 2), tiers)
assertEquals(mapOf(0 to 2, 1 to 2), BoostReport.tiers(mapOf(0 to 2.0, 1 to 2.0)))
}
@Test fun `the slowest 5 percent is the frame rate of the slowest seconds`() {
val s = BoostReport.Side().apply { (1..100).forEach { add(it, null, 0) } }
assertEquals(6, s.low)
assertEquals(50.5, s.average, 1e-9)
}
@Test fun `a clear gain is worth keeping`() {
val v = BoostReport.verdict(side(60, milliamps = 1200), side(50, milliamps = 1000))
assertTrue(v, v.startsWith("worth keeping: +20 % fps on average"))
assertTrue(v, v.endsWith("for +20 % battery draw"))
}
@Test fun `better slowest moments alone are worth keeping`() {
val v = BoostReport.verdict(side(50, slow = 40), side(50, slow = 30))
assertTrue(v, v.startsWith("worth keeping: +2 % fps on average, +33 % in the slowest moments"))
}
@Test fun `no gain is not worth keeping`() {
assertTrue(BoostReport.verdict(side(50), side(50)).startsWith("not worth keeping"))
assertTrue(BoostReport.verdict(side(45), side(50)).startsWith("not worth keeping"))
}
@Test fun `a small gain is unclear`() {
assertTrue(BoostReport.verdict(side(52), side(50)).startsWith("unclear, a small gain"))
}
@Test fun `a short check gives no verdict`() {
val v = BoostReport.verdict(side(60, seconds = 100), side(50))
assertEquals("too short to tell: play at least ${BoostReport.minutesForVerdict()} minutes with Check the boost on", v)
}
@Test fun `the switch's hint asks for as many minutes as the verdict needs`() {
assertEquals(7, BoostReport.minutesForVerdict())
}
@Test fun `the check starts after the first minute of play, then goes on, paused, paused, on`() {
(1..60).forEach { assertNull(BoostReport.checkWindow(it)) }
assertEquals(false to 0, BoostReport.checkWindow(61))
assertEquals(false to 59, BoostReport.checkWindow(120))
assertEquals(true to 0, BoostReport.checkWindow(121))
assertEquals(true to 119, BoostReport.checkWindow(240))
assertEquals(false to 0, BoostReport.checkWindow(241))
assertEquals(false to 119, BoostReport.checkWindow(360))
assertEquals(true to 0, BoostReport.checkWindow(361))
}
@Test fun `a game slowing down steadily as the phone warms favours neither side`() {
val on = BoostReport.Side()
val off = BoostReport.Side()
for (s in 1..BoostReport.WARMUP_S + 8 * BoostReport.WINDOW_S) {
val (pause, at) = BoostReport.checkWindow(s) ?: continue
if (at >= BoostReport.SETTLE_S) (if (pause) off else on).add(150 - s / 6, null, 0)
}
assertEquals(on.average, off.average, 0.5)
assertTrue(BoostReport.verdict(on, off).startsWith("not worth keeping"))
}
@Test fun `no verdict when heat held the boost back for more than a quarter of its turns`() {
val on = BoostReport.Side().apply { repeat(200) { add(80, null, 4, held = it < 60) } }
val v = BoostReport.verdict(on, side(60))
assertTrue(v, v.startsWith("can't tell: the phone was too hot or saving battery for 30 % of the time"))
assertTrue(BoostReport.verdict(BoostReport.Side().apply { repeat(200) { add(80, null, 4, held = it < 40) } }, side(60))
.startsWith("worth keeping"))
}
@Test fun `a game that keeps up without the boost does not need it`() {
val on = BoostReport.Side().apply { repeat(200) { add(58, null, 0, idle = it >= 12) } }
val v = BoostReport.verdict(on, side(59))
assertTrue(v, v.startsWith("not needed for this game: it kept up without the boost for 94 % of the boost's turns"))
assertTrue(v, v.endsWith("(58.0 fps in its turns, 59.0 fps paused)"))
val busy = BoostReport.Side().apply { repeat(200) { add(41, null, 0, idle = it < 96) } }
assertTrue(BoostReport.verdict(busy, side(40)).startsWith("unclear, a small gain"))
val short = BoostReport.Side().apply { repeat(100) { add(58, null, 0, idle = true) } }
assertTrue(BoostReport.verdict(short, side(59)).startsWith("too short to tell"))
}
@Test fun `the status names why the boost is off, once for a reason both parts give`() {
assertEquals("too hot", BoostReport.offReasons("too hot", "too hot"))
assertEquals("game keeps up, too hot", BoostReport.offReasons("game keeps up", "too hot"))
assertEquals("battery saver", BoostReport.offReasons("battery saver", null))
assertEquals("no reason given", BoostReport.offReasons(null, null))
}
@Test fun `the summary gives how long each reason kept a part off, longest first`() {
assertEquals("7:40 too hot, 0:20 game keeps up", BoostReport.offTimes(linkedMapOf("game keeps up" to 20, "too hot" to 460)))
assertEquals("", BoostReport.offTimes(emptyMap()))
}
@Test fun `the minutes asked for give both sides enough counted seconds`() {
val seconds = IntArray(2)
for (s in 1..BoostReport.minutesForVerdict() * 60) {
val (pause, at) = BoostReport.checkWindow(s) ?: continue
if (at >= BoostReport.SETTLE_S) seconds[if (pause) 1 else 0]++
}
assertTrue(seconds.joinToString(), seconds.all { it >= BoostReport.CHECK_MIN_S })
}
}
@@ -1,38 +0,0 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class BottomNotificationsTest {
private val own = "com.droiddeck.launcher"
@Test fun messagesFromOtherAppsAreKept() {
assertTrue(BottomNotifications.keep(own, "com.discord", ongoing = false, groupSummary = false, title = "Kurt", text = "ready?"))
}
@Test fun ownOngoingSummaryAndEmptyNotificationsAreSkipped() {
assertFalse(BottomNotifications.keep(own, own, ongoing = false, groupSummary = false, title = "Session", text = "running"))
assertFalse(BottomNotifications.keep(own, "com.spotify", ongoing = true, groupSummary = false, title = "Song", text = "Artist"))
assertFalse(BottomNotifications.keep(own, "com.discord", ongoing = false, groupSummary = true, title = "2 messages", text = ""))
assertFalse(BottomNotifications.keep(own, "com.discord", ongoing = false, groupSummary = false, title = " ", text = ""))
}
@Test fun anUpdatedNotificationMovesToTheTopOnce() {
val list = mutableListOf(
BottomNotification("a", "App", "one", "", 1L),
BottomNotification("b", "App", "two", "", 2L),
)
BottomNotifications.add(list, BottomNotification("b", "App", "two again", "", 3L))
assertEquals(listOf("b", "a"), list.map { it.key })
assertEquals("two again", list.first().title)
}
@Test fun theListKeepsTheNewestThirty() {
val list = mutableListOf<BottomNotification>()
repeat(35) { BottomNotifications.add(list, BottomNotification("k$it", "App", "t$it", "", it.toLong())) }
assertEquals(30, list.size)
assertEquals("k34", list.first().key)
}
}
@@ -1,32 +0,0 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
class BottomScreenshotsTest {
@get:Rule val tmp = TemporaryFolder()
@Test fun fileNamesSortByTime() {
val name = BottomScreenshots.fileName(0L)
assertTrue(name, name.startsWith("DroidDeck_") && name.endsWith(".jpg"))
assertEquals(29, name.length)
}
@Test fun steamScreenshotsAreFoundAndThumbnailsSkipped() {
val root = tmp.root
val shots = File(root, "root/.local/share/Steam/userdata/2932373/760/remote/220/screenshots")
File(shots, "thumbnails").mkdirs()
File(shots, "20261031010101_1.jpg").writeText("x")
File(shots, "thumbnails/20261031010101_1.jpg").writeText("x")
File(shots, "screenshots.vdf").writeText("x")
val x64 = File(root, "root/.droiddeck-x64/.local/share/Steam/userdata/2932373/760/remote/440/screenshots")
x64.mkdirs()
File(x64, "20261031020202_1.jpg").writeText("x")
val found = BottomScreenshots.steam(root).map { it.file!!.name }.sorted()
assertEquals(listOf("20261031010101_1.jpg", "20261031020202_1.jpg"), found)
}
}
@@ -1,226 +0,0 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.nio.ByteBuffer
import java.nio.ByteOrder
class GameTelemetryTest {
private fun packet(size: Int, fill: ByteBuffer.() -> Unit): ByteArray =
ByteBuffer.allocate(size).order(ByteOrder.LITTLE_ENDIAN).apply(fill).array()
@Test fun codemastersFloatsBecomeADash() {
val data = packet(264) {
putFloat(7 * 4, 25f) // m/s
putFloat(29 * 4, 0.8f)
putFloat(31 * 4, 0.1f)
putFloat(33 * 4, 3f)
putFloat(36 * 4, 1f)
putFloat(37 * 4, 650f) // rpm / 10
putFloat(63 * 4, 800f)
putFloat(45 * 4, 30f)
putFloat(46 * 4, 60f)
}
val t = GameTelemetry.parse(GameTelemetry.CODEMASTERS_PORT, data, data.size)!!
assertEquals(90f, t.speedKmh!!, 0.01f)
assertEquals("3", t.gear)
assertEquals(6500f, t.rpm!!, 0.01f)
assertEquals(8000f, t.maxRpm!!, 0.01f)
assertEquals(2, t.lap)
assertEquals(0.5f, t.fuel!!, 0.001f)
}
// Values from a DiRT Showdown packet recorded on a Retroid Pocket Duo (extradata 3 still sends 152 bytes there).
@Test fun codemastersShortPacketFromDirtShowdown() {
val data = packet(152) {
putFloat(1 * 4, 80.085f)
putFloat(7 * 4, 10.739f)
putFloat(29 * 4, 0.816f)
putFloat(33 * 4, 1f)
putFloat(37 * 4, 827.531f)
}
val t = GameTelemetry.parse(GameTelemetry.CODEMASTERS_PORT, data, data.size)!!
assertEquals(38.66f, t.speedKmh!!, 0.01f)
assertEquals("1", t.gear)
assertEquals(8275.31f, t.rpm!!, 0.01f)
assertEquals(0.816f, t.throttle!!, 0.001f)
assertEquals(1, t.lap)
assertEquals(80.085f, t.currentLapS!!, 0.001f)
assertNull(t.maxRpm)
assertNull(t.laps)
assertNull(t.position)
assertNull(t.fuel)
assertNull(t.lastLapS)
}
@Test fun codemastersReverseAndNeutral() {
fun gear(g: Float) = GameTelemetry.parse(GameTelemetry.CODEMASTERS_PORT, packet(264) { putFloat(33 * 4, g) }, 264)!!.gear
assertEquals("N", gear(0f))
assertEquals("R", gear(-1f))
assertEquals("R", gear(10f))
}
@Test fun forzaHorizonDashSitsTwelveBytesLater() {
val dash = 232 + 12
val data = packet(324) {
putInt(0, 1)
putFloat(8, 8000f)
putFloat(16, 5000f)
putFloat(dash + 12, 50f)
put(dash + 71, 255.toByte())
put(dash + 75, 4)
putShort(dash + 68, 2)
put(dash + 70, 5)
}
val t = GameTelemetry.parse(GameTelemetry.FORZA_PORT, data, data.size)!!
assertEquals(180f, t.speedKmh!!, 0.01f)
assertEquals("4", t.gear)
assertEquals(1f, t.throttle!!, 0.001f)
assertEquals(3, t.lap)
assertEquals(5, t.position)
}
@Test fun forzaMotorsportDashFollowsTheSled() {
val data = packet(311) {
putInt(0, 1)
putFloat(232 + 12, 10f)
put(232 + 75, 0)
}
val t = GameTelemetry.parse(GameTelemetry.FORZA_PORT, data, data.size)!!
assertEquals(36f, t.speedKmh!!, 0.01f)
assertEquals("R", t.gear)
}
@Test fun forzaInMenusHasNoDash() {
val t = GameTelemetry.parse(GameTelemetry.FORZA_PORT, packet(324) {}, 324)!!
assertNull(t.speedKmh)
}
@Test fun outGaugeGearsAreShiftedByOne() {
val data = packet(96) {
put(10, 3)
putFloat(12, 20f)
putFloat(16, 4000f)
}
val t = GameTelemetry.parse(GameTelemetry.OUTGAUGE_PORT, data, data.size)!!
assertEquals("2", t.gear)
assertEquals(72f, t.speedKmh!!, 0.01f)
assertEquals(4000f, t.rpm!!, 0.01f)
}
@Test fun listensOnIpv4Loopback() {
assertTrue(GameTelemetry.LISTEN_ADDRESS is java.net.Inet4Address)
assertEquals("127.0.0.1", GameTelemetry.LISTEN_ADDRESS.hostAddress)
}
@Test fun shortPacketsAreIgnored() {
assertNull(GameTelemetry.parse(GameTelemetry.CODEMASTERS_PORT, ByteArray(148), 148))
assertNull(GameTelemetry.parse(GameTelemetry.OUTGAUGE_PORT, ByteArray(40), 40))
assertNull(GameTelemetry.parse(1234, ByteArray(400), 400))
}
// DiRT Showdown's 38 floats already carry steering and both G-forces.
@Test fun codemastersGForceAndSteering() {
val data = packet(152) {
putFloat(30 * 4, -0.5f)
putFloat(33 * 4, 2f)
putFloat(34 * 4, 1.2f)
putFloat(35 * 4, -0.8f)
}
val t = GameTelemetry.parse(GameTelemetry.CODEMASTERS_PORT, data, data.size)!!
assertEquals(-0.5f, t.steer!!, 1e-4f)
assertEquals(1.2f, t.gLat!!, 1e-4f)
assertEquals(-0.8f, t.gLon!!, 1e-4f)
}
@Test fun forzaReadsBestLapSteeringGForceAndTires() {
val dash = 232
val data = packet(311) {
putInt(0, 1)
putFloat(20, 9.81f)
putFloat(28, -4.905f)
putFloat(dash + 24, 212f)
putFloat(dash + 28, 32f)
putFloat(dash + 32, 194f)
putFloat(dash + 36, 176f)
putFloat(dash + 52, 81.5f)
put(dash + 75, 3)
put(dash + 76, (-127).toByte())
}
val t = GameTelemetry.parse(GameTelemetry.FORZA_PORT, data, data.size)!!
assertEquals(1f, t.gLat!!, 1e-3f)
assertEquals(-0.5f, t.gLon!!, 1e-3f)
assertEquals(listOf(100f, 0f, 90f, 80f), t.tireTempsC!!.map { Math.round(it).toFloat() })
assertEquals(81.5f, t.bestLapS!!, 1e-4f)
assertEquals(-1f, t.steer!!, 1e-4f)
}
@Test fun forzaWithoutTireDataLeavesThemOut() {
val data = packet(311) { putInt(0, 1); put(232 + 75, 2) }
assertNull(GameTelemetry.parse(GameTelemetry.FORZA_PORT, data, data.size)!!.tireTempsC)
}
@Test fun outGaugeReadsTurboTemperaturesAndLights() {
val data = packet(92) {
put(10, 3)
putFloat(20, 0.8f)
putFloat(24, 92f)
putFloat(36, 104f)
putInt(40, GameTelemetry.DL_SHIFT or GameTelemetry.DL_ABS or GameTelemetry.DL_HANDBRAKE)
putInt(44, GameTelemetry.DL_SHIFT or GameTelemetry.DL_ABS)
}
val t = GameTelemetry.parse(GameTelemetry.OUTGAUGE_PORT, data, data.size)!!
assertEquals(0.8f, t.turboBar!!, 1e-4f)
assertEquals(92f, t.engineTempC!!, 1e-4f)
assertEquals(104f, t.oilTempC!!, 1e-4f)
assertEquals(GameTelemetry.DL_SHIFT or GameTelemetry.DL_ABS, t.lights)
}
// BeamNG leaves some OutGauge fields at zero; those stay hidden.
@Test fun outGaugeZeroFieldsStayHidden() {
val t = GameTelemetry.parse(GameTelemetry.OUTGAUGE_PORT, packet(92) { put(10, 2) }, 92)!!
assertNull(t.turboBar)
assertNull(t.engineTempC)
assertNull(t.lights)
}
}
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class GameStatusFilesTest {
@Test fun warThunderShowsNumbersOnlyDuringAMatch() {
assertEquals(emptyList<Pair<String, String>>(), GameStatusFiles.warThunder("""{"valid": false}"""))
val rows = GameStatusFiles.warThunder("""{"valid": true, "H, m": 1520, "TAS, km/h": 512.4, "name": "x"}""")
assertEquals(listOf("H, m" to "1520", "TAS, km/h" to "512.4"), rows)
}
@Test fun warThunderKeepsEveryNumberForTheFlightLayout() {
val json = buildString {
append("{\"valid\": true")
for (i in 0 until 20) append(", \"k$i\": $i")
append(", \"IAS, km/h\": 512, \"throttle 1, %\": 110}")
}
val rows = GameStatusFiles.warThunder(json)
assertEquals(22, rows.size)
assertTrue(com.droiddeck.launcher.ui.FlightLabels.drawable(rows))
assertEquals("110", rows.toMap()["throttle 1, %"])
}
@Test fun eliteAtTheMenusShowsNothing() {
assertNull(GameStatusFiles.elite("""{"timestamp": "2026-10-31T02:00:00Z", "event": "Status", "Flags": 0}"""))
}
@Test fun eliteInFlight() {
val e = GameStatusFiles.elite("""{"Flags": 16777240, "Pips": [4, 8, 0], "Fuel": {"FuelMain": 16.0, "FuelReservoir": 0.43},
"Cargo": 2.0, "LegalState": "Clean", "Balance": 1234567}""")!!
assertEquals(16.0, e.fuelMain!!, 0.001)
assertEquals(listOf(4, 8, 0), e.pips)
assertEquals("Clean", e.legal)
assertEquals(1234567L, e.balance)
}
}
@@ -24,6 +24,14 @@ class GameThreadHintsTest {
assertEquals(setOf(2), GameThreadHints.pick(setOf(1, 2), mapOf(2 to 0.7)))
}
@Test fun `the log is told why no thread is boosted`() {
assertEquals("too hot", GameThreadHints.offReason("too hot", emptySet(), false, emptySet()))
assertEquals(null, GameThreadHints.offReason(null, setOf(1), true, setOf(1)))
assertEquals("game keeps up", GameThreadHints.offReason(null, emptySet(), true, emptySet()))
assertEquals("no thread busy enough", GameThreadHints.offReason(null, emptySet(), false, emptySet()))
assertEquals("Android refused the hint", GameThreadHints.offReason(null, emptySet(), false, setOf(1)))
}
@Test fun `a game at the panel's rate or a fraction of it holds pace`() {
assertTrue(GameThreadHints.holdsPace(119.0, 120.0))
assertTrue(GameThreadHints.holdsPace(60.5, 120.0))
@@ -0,0 +1,87 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.session.SamsungPerf.Floor
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.EOFException
import java.lang.reflect.InvocationTargetException
import java.nio.ByteBuffer
import java.nio.ByteOrder
class SamsungPerfTest {
private val cpu = intArrayOf(300000, 691200, 1190400, 1555200, 2016000)
private val gpu = intArrayOf(220000, 350000, 490000, 600000, 680000)
private val bus = intArrayOf(547000, 1017000, 1555000, 2092000, 3196000)
/** A level table as Samsung's service sends it: 38 little-endian ints. */
private fun table(maxTimeoutMs: Int, cpu: IntArray = this.cpu, gpu: IntArray = this.gpu, bus: IntArray = this.bus): ByteArray {
val ints = intArrayOf(0, 0, 0, maxTimeoutMs) + cpu + gpu + bus + intArrayOf(5, 5, 5, maxTimeoutMs) + IntArray(15) { 3_000_000 }
return ByteBuffer.allocate(ints.size * 4).order(ByteOrder.LITTLE_ENDIAN).apply { ints.forEach { putInt(it) } }.array()
}
@Test fun `the floors are read from the table, and nothing past it`() {
val stream = ByteArrayInputStream(table(10000) + byteArrayOf(7))
val levels = SamsungPerf.readLevels(stream)
assertArrayEquals(cpu, levels.cpu)
assertArrayEquals(gpu, levels.gpu)
assertArrayEquals(bus, levels.bus)
assertEquals(10000, levels.maxTimeoutMs)
assertEquals(1, stream.available())
}
@Test fun `the middle level of each floor is held, with four cores online`() {
val floors = SamsungPerf.floors(SamsungPerf.readLevels(ByteArrayInputStream(table(-1))))
val hold = SamsungPerf.HOLD_MS
assertEquals(
listOf(
Floor(SamsungPerf.CPU_MIN, 1190400, hold),
Floor(SamsungPerf.CPU_CORES_MIN, 4, hold),
Floor(SamsungPerf.GPU_MIN, 490000, hold),
Floor(SamsungPerf.BUS_MIN, 1555000, hold),
),
floors,
)
}
@Test fun `a shorter limit from the phone shortens the hold`() {
val floors = SamsungPerf.floors(SamsungPerf.readLevels(ByteArrayInputStream(table(3000))))
assertEquals(setOf(3000), floors.map { it.timeoutMs }.toSet())
}
@Test fun `a resource the phone does not offer is left alone`() {
val floors = SamsungPerf.floors(SamsungPerf.readLevels(ByteArrayInputStream(table(-1, gpu = IntArray(5) { -1 }))))
assertEquals(listOf(SamsungPerf.CPU_MIN, SamsungPerf.CPU_CORES_MIN, SamsungPerf.BUS_MIN), floors.map { it.type })
}
@Test fun `the floors are renewed before Samsung's one-second hold runs out`() {
assertEquals(500L, SamsungPerf.renewMs(SamsungPerf.HOLD_MS))
assertEquals(500L, SamsungPerf.renewMs(1000))
assertEquals(150L, SamsungPerf.renewMs(300))
assertEquals(100L, SamsungPerf.renewMs(50))
}
@Test fun `a failed connection is tried again a few times, then at the next game`() {
assertEquals(4, SamsungPerf.TRIES)
assertEquals("trying again in 5 s", SamsungPerf.retryNote(1))
assertEquals("trying again in 15 s", SamsungPerf.retryNote(2))
assertEquals("trying again in 30 s", SamsungPerf.retryNote(3))
assertEquals("no more tries until the next game", SamsungPerf.retryNote(4))
}
@Test fun `a failed try names the step it was on and the error`() {
assertEquals(
"failed while reading the service's level table (EOFException)",
SamsungPerf.failure("reading the service's level table", EOFException()),
)
assertEquals(
"failed while looking up Samsung's performance service (SecurityException: not allowed)",
SamsungPerf.failure("looking up Samsung's performance service", InvocationTargetException(SecurityException("not allowed"))),
)
}
@Test(expected = EOFException::class) fun `a short answer is refused`() {
SamsungPerf.readLevels(ByteArrayInputStream(table(-1).copyOf(100)))
}
}
@@ -1,51 +0,0 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Test
class StatsLayoutTest {
@Test fun unknownIdsFallBackToTheDefaults() {
assertEquals(StatsStrip.PANEL, StatsStrip.from(null))
assertEquals(StatsStrip.RINGS, StatsStrip.from("rings"))
assertEquals(StatsDash.AUTO, StatsDash.from("gone"))
assertEquals(StatsDash.TRACE, StatsDash.from("trace"))
}
@Test fun tappingTheStripCyclesThroughEveryStyle() {
assertEquals(StatsStrip.TILES, StatsStrip.PANEL.next())
assertEquals(StatsStrip.RINGS, StatsStrip.TILES.next())
assertEquals(StatsStrip.PANEL, StatsStrip.RINGS.next())
}
@Test fun autoPicksTheDashByTheGamesFormat() {
assertEquals(StatsDash.SPEEDOMETER, StatsDash.AUTO.resolve("Codemasters"))
assertEquals(StatsDash.CIRCUIT, StatsDash.AUTO.resolve("Forza"))
assertEquals(StatsDash.DIALS, StatsDash.AUTO.resolve("OutGauge"))
assertEquals(StatsDash.TRACE, StatsDash.TRACE.resolve("Forza"))
}
@Test fun tappingTheDashMovesOnFromTheOneOnScreen() {
assertEquals(StatsDash.CIRCUIT, StatsDash.tapped(StatsDash.SPEEDOMETER))
assertEquals(StatsDash.SPEEDOMETER, StatsDash.tapped(StatsDash.GLANCE))
assertEquals(StatsDash.SPEEDOMETER, StatsDash.tapped(StatsDash.AUTO))
}
@Test fun automaticSpeedUnitsFollowTheRegion() {
assertEquals(SpeedUnit.MPH, SpeedUnit.AUTO.resolve("US"))
assertEquals(SpeedUnit.MPH, SpeedUnit.AUTO.resolve("gb"))
assertEquals(SpeedUnit.KMH, SpeedUnit.AUTO.resolve("DE"))
assertEquals(SpeedUnit.KMH, SpeedUnit.AUTO.resolve(""))
assertEquals(SpeedUnit.KMH, SpeedUnit.KMH.resolve("US"))
assertEquals(SpeedUnit.MPH, SpeedUnit.MPH.resolve("DE"))
}
@Test fun speedUnitsCycleAndConvert() {
assertEquals(SpeedUnit.AUTO, SpeedUnit.from(null))
assertEquals(SpeedUnit.MPH, SpeedUnit.from("mph"))
assertEquals(SpeedUnit.KMH, SpeedUnit.AUTO.next())
assertEquals(SpeedUnit.MPH, SpeedUnit.KMH.next())
assertEquals(SpeedUnit.AUTO, SpeedUnit.MPH.next())
assertEquals(62.1f, 100f * SpeedUnit.MPH.perKmh, 0.05f)
assertEquals(100f, 100f * SpeedUnit.KMH.perKmh, 0f)
}
}
@@ -1,55 +0,0 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class SteamDownloadsTest {
private fun manifest(flags: Long, done: Long, total: Long) = """
"AppState"
{
"appid" "220"
"name" "Half-Life 2"
"StateFlags" "$flags"
"BytesToDownload" "$total"
"BytesDownloaded" "$done"
}
""".trimIndent()
@Test fun anInstalledGameIsNotADownload() {
assertNull(SteamDownloads.fromManifest("220", "Half-Life 2", manifest(4, 100, 100)))
}
@Test fun aRunningUpdateShowsItsBytes() {
val d = SteamDownloads.fromManifest("220", "Half-Life 2", manifest(1026, 40, 100))!!
assertEquals(40L, d.done)
assertEquals(100L, d.total)
}
@Test fun aPausedUpdateSaysSo() {
assertTrue(SteamDownloads.fromManifest("220", "Half-Life 2", manifest(514, 40, 100))!!.paused)
}
@Test fun anUpdateNotSizedYetIsStillListed() {
assertEquals(0L, SteamDownloads.fromManifest("220", "Half-Life 2", manifest(6, 0, 0))!!.total)
}
@Test fun onlyShaderUpdatesStillRunningCount() {
val log = sequenceOf(
"[2026-10-30 06:33:02] AppID 220 Shader update changed : Running Update,Downloading,",
"[2026-10-30 06:33:02] AppID 440 Shader update changed : Running Update,",
"[2026-10-30 06:33:03] AppID 440 Shader update changed : None",
"[2026-10-30 06:33:03] AppID 570 App update changed : Running Update,",
)
assertEquals(listOf("220"), SteamDownloads.runningShaderUpdates(log))
}
@Test fun aClientRestartForgetsOlderShaderUpdates() {
val log = sequenceOf(
"[2026-10-30 06:33:02] AppID 220 Shader update changed : Running Update,",
"[2026-10-30 07:00:00] Client version: 1761000000",
)
assertEquals(emptyList<String>(), SteamDownloads.runningShaderUpdates(log))
}
}
@@ -1,31 +0,0 @@
package com.droiddeck.launcher.session
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
class SteamWebLoginTest {
private fun hex(s: String) = ByteArray(s.length / 2) { s.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
// Made with: openssl enc -aes-128-cbc -K <PBKDF2-SHA1("peanuts","saltysalt",1)> -iv <16 spaces>, prefixed "v10".
@Test fun chromiumV10ValuesDecrypt() {
val encrypted = hex("7631300b9cf0a6eee9cf1aaac601b85ca37cf9fe9e67078564f0e05835ae2aa3d9b0ab")
assertEquals("0123456789abcdef01234567", SteamWebLogin.decrypt(encrypted, hostHashed = false))
}
@Test fun newerStoresDropTheHostHash() {
val encrypted = hex("7631304d4114329f1e692e807b8b044d67460f5e14d92ffb48b9f83be318ebd0d84c727674aea32f351b8a33c8aa42553dfeb5")
assertEquals("hello", SteamWebLogin.decrypt(encrypted, hostHashed = true))
}
@Test fun otherFormatsAreSkipped() {
assertNull(SteamWebLogin.decrypt("v11garbage".toByteArray(), hostHashed = false))
assertNull(SteamWebLogin.decrypt(ByteArray(2), hostHashed = false))
}
@Test fun theSignInIsSentTheWaySteamPagesSendIt() {
assertEquals("steamLoginSecure=76561190000000000%7C%7Ca.b.c; Path=/; Secure; HttpOnly",
SteamWebLogin.header("steamLoginSecure", "76561190000000000||a.b.c", httpOnly = true))
assertEquals("sessionid=0123; Path=/; Secure", SteamWebLogin.header("sessionid", "0123", httpOnly = false))
}
}
@@ -1,116 +0,0 @@
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"))
}
@Test fun automaticSkipsGamesThatAreOnSwitchedOffOrRunning() {
val f = File("x")
val dirt4 = TelemetryOutput.Game("DiRT 4", "421020", f, on = false)
val rally = TelemetryOutput.Game("DiRT Rally 2.0", "690790", f, on = false)
val grid = TelemetryOutput.Game("GRID", "703860", f, on = true)
val games = listOf(dirt4, rally, grid)
assertEquals(listOf(dirt4, rally), TelemetryOutput.automaticTargets(games, emptySet(), null))
assertEquals(listOf(rally), TelemetryOutput.automaticTargets(games, setOf("421020/DiRT 4"), null))
assertEquals(listOf(dirt4), TelemetryOutput.automaticTargets(games, emptySet(), "690790"))
assertEquals("690790/DiRT Rally 2.0", TelemetryOutput.key(rally))
}
@Test fun switchingAutomaticOffRestoresOnlyGamesDroidDeckChanged() {
val compatdata = tmp.newFolder("steamapps", "compatdata")
val changed = configFile(compatdata, "2848447563", "DiRT Showdown").apply { writeText(showdown) }
val own = configFile(compatdata, "690790", "DiRT Rally 2.0")
.apply { writeText("<x><udp enabled=\"true\" ip=\"127.0.0.1\" port=\"20777\" /></x>") }
assertTrue(TelemetryOutput.set(TelemetryOutput.scan(listOf(compatdata)).first { it.name == "DiRT Showdown" }, true))
val targets = TelemetryOutput.restoreTargets(TelemetryOutput.scan(listOf(compatdata)), null)
assertEquals(listOf(changed), targets.map { it.file })
assertTrue(own.isFile)
assertTrue(TelemetryOutput.restoreTargets(TelemetryOutput.scan(listOf(compatdata)), "2848447563").isEmpty())
}
@Test fun automaticTurnsOnDirt3AndShowdownLikeTheOtherGames() {
val f = File("x")
val showdownGame = TelemetryOutput.Game("DiRT Showdown", "2848447563", f, on = false)
val dirt3 = TelemetryOutput.Game("DiRT3", "321040", f, on = false)
val rally = TelemetryOutput.Game("DiRT Rally 2.0", "690790", f, on = false)
assertEquals(listOf(showdownGame, dirt3, rally), TelemetryOutput.automaticTargets(listOf(showdownGame, dirt3, rally), emptySet(), null))
assertEquals(listOf(rally), TelemetryOutput.automaticTargets(listOf(showdownGame, dirt3, rally), setOf("2848447563/DiRT Showdown", "321040/DiRT3"), null))
}
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() }
}
@@ -1,42 +0,0 @@
package com.droiddeck.launcher.ui
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class BottomChatPageTest {
@Test fun steamSitesOpenOthersDoNot() {
assertTrue(steamChatAllows("steamcommunity.com"))
assertTrue(steamChatAllows("login.steampowered.com"))
assertTrue(steamChatAllows("steam-chat.com"))
assertTrue(steamChatAllows("community.cloudflare.steamstatic.com"))
assertFalse(steamChatAllows("steamcommunity.com.example.net"))
assertFalse(steamChatAllows("evilsteamcommunity.com"))
assertFalse(steamChatAllows(null))
}
@Test fun chatFitScriptUsesADotDecimalInEveryLocale() {
val before = java.util.Locale.getDefault()
try {
java.util.Locale.setDefault(java.util.Locale.GERMANY)
val js = steamChatFitScript(821, 0.75f)
assertTrue(js.contains("m.content='width=821, initial-scale=0.75'"))
assertTrue(js.contains("s.textContent='$STEAM_CHAT_FIT_CSS'"))
assertFalse(STEAM_CHAT_FIT_CSS.contains('\''))
} finally {
java.util.Locale.setDefault(before)
}
}
@Test fun theGroupChatListLeavesRoomForTheOnlineFriends() {
assertTrue(STEAM_CHAT_FIT_CSS.contains(".ChatRoomList_Empty{display:none!important}"))
assertTrue(STEAM_CHAT_FIT_CSS.contains(".chatRoomListContainer{height:auto!important;max-height:25vh!important}"))
assertTrue(STEAM_CHAT_FIT_CSS.contains(".chat_main>:has(~.chat_main_flex){display:none!important}"))
}
@Test fun desktopAgentKeepsTheWebViewChromeVersion() {
val ua = desktopUserAgent("Mozilla/5.0 (Linux; Android 15; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/141.0.7390.122 Mobile Safari/537.36")
assertEquals("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.122 Safari/537.36", ua)
}
}
@@ -1,58 +0,0 @@
package com.droiddeck.launcher.ui
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class BottomDashboardTest {
@Test fun theRememberedPageOpensAgain() {
assertEquals("shots", pickBottomPage("shots", listOf("downloads", "shots")))
}
@Test fun aGoneOrMissingPageFallsBackToTheFirst() {
assertEquals("downloads", pickBottomPage("gone", listOf("downloads", "shots")))
assertEquals("downloads", pickBottomPage(null, listOf("downloads", "shots")))
assertNull(pickBottomPage("shots", emptyList()))
}
@Test fun withNothingPickedTheChatOpens() {
val ids = listOf("telemetry", "downloads", "notifications", "screenshots", "chat")
assertEquals("chat", pickBottomPage(null, ids))
assertEquals("chat", pickBottomPage("gone", ids))
assertEquals("telemetry", pickBottomPage("telemetry", ids))
assertEquals("screenshots", pickBottomPage("screenshots", ids))
}
@Test fun aGameStartShowsTheInGameStats() {
assertEquals("telemetry", pageForGameStart(listOf("telemetry", "downloads", "chat")))
assertNull(pageForGameStart(listOf("downloads", "chat")))
}
@Test fun tabNamesShowOnlyWhileEveryTabFits() {
// Retroid Pocket Duo bottom panel: 1280x960 at 320 dpi = 640 dp wide.
assertTrue(bottomTabsWithLabels(640f, 4))
assertFalse(bottomTabsWithLabels(640f, 5))
assertFalse(bottomTabsWithLabels(360f, 3))
}
}
class BottomDownloadsRateTest {
@Test fun rateIsBytesPerSecondBetweenReads() {
assertEquals(1_000_000L, downloadRate(0L, 0L, 2_000_000L, 2_000L))
}
@Test fun noMovementOrARestartIsZero() {
assertEquals(0L, downloadRate(500L, 0L, 500L, 2_000L))
assertEquals(0L, downloadRate(500L, 0L, 100L, 2_000L))
assertEquals(0L, downloadRate(-1L, 0L, 100L, 2_000L))
}
}
class BottomTelemetryLapTimeTest {
@Test fun lapTimesReadAsMinutesSecondsMillis() {
assertEquals("1:23.456", lapTime(83.456f))
assertEquals("0:05.000", lapTime(5f))
}
}
@@ -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))
}
}
-15
View File
@@ -222,20 +222,5 @@
"cmake",
"xz-utils"
]
},
"dirt-ws2": {
"script": "tools/components/recipes/dirt-ws2.sh",
"inputs": [
"tools/dirt-ws2",
"tools/components/recipes/dirt-ws2.sh"
],
"outputs": [
"app/src/main/assets/linuxfs/usr/local/lib/droiddeck-dirt/ws2_32.dll"
],
"packages": [
"clang",
"lld",
"llvm"
]
}
}
-3
View File
@@ -1,3 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
bash tools/dirt-ws2/build.sh app/src/main/assets/linuxfs/usr/local/lib/droiddeck-dirt
-19
View File
@@ -1,19 +0,0 @@
# DiRT 3 / DiRT Showdown ws2_32 stand-in
DiRT 3 (`dirt3_game.exe`) and DiRT Showdown (`showdown.exe`, `showdown_avx.exe`) close their motion telemetry UDP
socket at the end of a race, and when leaving Joyride, but keep calling `sendto()` on it. `sendto()` fails with
WSAENOTSOCK and the game stops with "sendto failed with error 10038". The same happens on Windows.
`ws2_32.dll` here is a 32-bit stand-in: every export jumps to the same-ordinal export of Wine's own `ws2_32.dll`;
only a `sendto()` that fails with 10038 reports 0 bytes sent instead. Same behaviour as
[DiRTTelemetryErrorFix](https://github.com/RoccoC/DiRTTelemetryErrorFix) by RoccoC (MIT), based on the original fix
by Carsten Gottschling.
Wine loads `ws2_32` as a KnownDLL, so a copy beside the game is ignored. `droiddeck-game-env` puts the stand-in in
place of the prefix's `syswow64/ws2_32.dll` for these games while their telemetry output is on, adds
`WINEDLLOVERRIDES=ws2_32=n,b`, and puts Wine's file back when the game exits. It skips the swap when the game's
Proton already has the fix in its own `ws2_32.dll` (DroidDeck-Proton patch
`dirt-telemetry-sendto-closed-socket.patch`).
`build.sh OUT` builds it with clang, lld and llvm-dlltool and checks its exports against `ws2_32-exports.txt`
(taken from Wine 11's `ws2_32.dll`).
-26
View File
@@ -1,26 +0,0 @@
#!/usr/bin/env bash
# Builds the 32-bit ws2_32.dll stand-in for DiRT 3 and DiRT Showdown into the given folder.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
mkdir -p "$1"
out=$(cd "$1" && pwd)
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
tool() {
local found
found=$(command -v "$1" || ls /usr/lib/llvm-*/bin/"$1" 2>/dev/null | sort -V | tail -n1 || true)
[ -n "$found" ] || { echo "dirt-ws2: $1 not found" >&2; exit 1; }
echo "$found"
}
clang=$(tool clang)
dlltool=$(tool llvm-dlltool)
tool ld.lld > /dev/null
python3 "$here/gen.py" generate "$here" "$work"
"$dlltool" -m i386 -k -d "$here/kernel32.def" -l "$work/libkernel32.a"
"$clang" --target=i686-w64-mingw32 -O2 -Wall -Wextra -Werror -ffreestanding -fno-stack-protector -fno-builtin \
-nostdlib -shared -fuse-ld=lld -o "$work/ws2_32.dll" "$here/ws2_32.c" "$work/thunks.c" "$work/ws2_32.def" \
-L"$work" -lkernel32 -Wl,--entry,DllMain@12 -Wl,--no-insert-timestamp
python3 "$here/gen.py" verify "$here" "$work/ws2_32.dll"
install -m 644 "$work/ws2_32.dll" "$out/ws2_32.dll"
-74
View File
@@ -1,74 +0,0 @@
"""ws2_32 stand-in helpers.
gen.py generate SRC OUT writes OUT/thunks.c (one jump per export) and OUT/ws2_32.def from SRC/ws2_32-exports.txt.
gen.py verify SRC DLL checks that DLL exports exactly the ordinals and names in SRC/ws2_32-exports.txt.
"""
import struct
import sys
from pathlib import Path
def exports_list(src):
rows = []
for line in (Path(src) / 'ws2_32-exports.txt').read_text().splitlines():
ordinal, name = line.split()
rows.append((int(ordinal), name))
return rows
def generate(src, out):
rows = exports_list(src)
passed = [(o, n) for o, n in rows if n != 'sendto']
c = ['/* Generated by tools/dirt-ws2/gen.py. */',
'const unsigned short dirtfix_ordinals[%d] = {%s};' % (len(passed), ', '.join(str(o) for o, _ in passed)),
'const unsigned int dirtfix_count = %d;' % len(passed),
'void *dirtfix_real[%d];' % len(passed),
'__asm__(".text\\n"']
for i, (o, _) in enumerate(passed):
c.append(' ".globl _dirtfix_t%d\\n_dirtfix_t%d:\\n\\tjmp *_dirtfix_real+%d\\n"' % (o, o, 4 * i))
c.append(');')
(Path(out) / 'thunks.c').write_text('\n'.join(c) + '\n')
d = ['LIBRARY ws2_32.dll', 'EXPORTS']
d += [' %s=%s @%d' % (n, 'dirtfix_sendto@24' if n == 'sendto' else 'dirtfix_t%d' % o, o) for o, n in rows]
(Path(out) / 'ws2_32.def').write_text('\n'.join(d) + '\n')
def pe_exports(path):
data = Path(path).read_bytes()
pe = struct.unpack_from('<I', data, 0x3c)[0]
machine, sections = struct.unpack_from('<HH', data, pe + 4)
optional_size = struct.unpack_from('<H', data, pe + 20)[0]
optional = pe + 24
export_rva = struct.unpack_from('<I', data, optional + 96)[0]
table = [struct.unpack_from('<IIII', data, optional + optional_size + 40 * i + 8) for i in range(sections)]
def offset(rva):
for size, address, raw_size, raw in table:
if address <= rva < address + max(size, raw_size):
return rva - address + raw
raise ValueError('RVA %#x outside the sections' % rva)
base, functions, names, function_rva, name_rva, ordinal_rva = struct.unpack_from('<IIIIII', data, offset(export_rva) + 16)
named = {}
for i in range(names):
text = struct.unpack_from('<I', data, offset(name_rva) + 4 * i)[0]
index = struct.unpack_from('<H', data, offset(ordinal_rva) + 2 * i)[0]
named[index] = data[offset(text):].split(b'\0')[0].decode()
result = [(base + i, named.get(i)) for i in range(functions) if struct.unpack_from('<I', data, offset(function_rva) + 4 * i)[0]]
return machine, result
def verify(src, dll):
machine, found = pe_exports(dll)
if machine != 0x14c:
sys.exit('%s is not a 32-bit x86 DLL (machine %#x)' % (dll, machine))
expected = exports_list(src)
if found != expected:
sys.exit('%s exports differ from ws2_32-exports.txt: %d found, %d expected' % (dll, len(found), len(expected)))
if b'droiddeck-dirt-ws2_32' not in Path(dll).read_bytes():
sys.exit('%s lacks the stand-in marker' % dll)
print('%s: %d exports match, marker present' % (dll, len(found)))
if __name__ == '__main__':
{'generate': generate, 'verify': verify}[sys.argv[1]](sys.argv[2], sys.argv[3])
-7
View File
@@ -1,7 +0,0 @@
LIBRARY kernel32.dll
EXPORTS
LoadLibraryW@4
GetProcAddress@8
GetSystemDirectoryW@8
GetEnvironmentVariableW@12
GetFileAttributesW@4
-135
View File
@@ -1,135 +0,0 @@
1 accept
2 bind
3 closesocket
4 connect
5 getpeername
6 getsockname
7 getsockopt
8 htonl
9 htons
10 ioctlsocket
11 inet_addr
12 inet_ntoa
13 listen
14 ntohl
15 ntohs
16 recv
17 recvfrom
18 select
19 send
20 sendto
21 setsockopt
22 shutdown
23 socket
24 FreeAddrInfoEx
25 FreeAddrInfoExW
26 FreeAddrInfoW
27 GetAddrInfoExCancel
28 GetAddrInfoExOverlappedResult
29 GetAddrInfoExW
30 GetAddrInfoW
31 GetHostNameW
32 GetNameInfoW
33 InetNtopW
34 InetPtonW
35 WSApSetPostRoutine
36 WPUCompleteOverlappedRequest
37 WSAAccept
38 WSAAddressToStringA
39 WSAAddressToStringW
40 WSACloseEvent
41 WSAConnect
42 WSAConnectByNameA
43 WSAConnectByNameW
44 WSACreateEvent
45 WSADuplicateSocketA
46 WSADuplicateSocketW
47 WSAEnumNameSpaceProvidersA
48 WSAEnumNameSpaceProvidersW
49 WSAEnumNetworkEvents
50 WSAEnumProtocolsA
51 gethostbyaddr
52 gethostbyname
53 getprotobyname
54 getprotobynumber
55 getservbyname
56 getservbyport
57 gethostname
58 WSAEnumProtocolsW
59 WSAEventSelect
60 WSAGetOverlappedResult
61 WSAGetQOSByName
62 WSAGetServiceClassInfoA
63 WSAGetServiceClassInfoW
64 WSAGetServiceClassNameByClassIdA
65 WSAGetServiceClassNameByClassIdW
66 WSAHtonl
67 WSAHtons
68 WSAInstallServiceClassA
69 WSAInstallServiceClassW
70 WSAIoctl
71 WSAJoinLeaf
72 WSALookupServiceBeginA
73 WSALookupServiceBeginW
74 WSALookupServiceEnd
75 WSALookupServiceNextA
76 WSALookupServiceNextW
77 WSANSPIoctl
78 WSANtohl
79 WSANtohs
80 WSAPoll
81 WSAProviderConfigChange
82 WSARecv
83 WSARecvDisconnect
84 WSARecvFrom
85 WSARemoveServiceClass
86 WSAResetEvent
87 WSASend
88 WSASendDisconnect
89 WSASendMsg
90 WSASendTo
91 WSASetEvent
92 WSASetServiceA
93 WSASetServiceW
94 WSASocketA
95 WSASocketW
96 WSAStringToAddressA
97 WSAStringToAddressW
98 WSAWaitForMultipleEvents
99 WSCDeinstallProvider
100 WSCEnableNSProvider
101 WSAAsyncSelect
102 WSAAsyncGetHostByAddr
103 WSAAsyncGetHostByName
104 WSAAsyncGetProtoByNumber
105 WSAAsyncGetProtoByName
106 WSAAsyncGetServByPort
107 WSAAsyncGetServByName
108 WSACancelAsyncRequest
109 WSASetBlockingHook
110 WSAUnhookBlockingHook
111 WSAGetLastError
112 WSASetLastError
113 WSACancelBlockingCall
114 WSAIsBlocking
115 WSAStartup
116 WSACleanup
117 WSCEnumProtocols
118 WSCEnumProtocols32
119 WSCGetApplicationCategory
120 WSCGetProviderInfo
121 WSCGetProviderPath
122 WSCInstallNameSpace
123 WSCInstallProvider
124 WSCSetApplicationCategory
125 WSCUnInstallNameSpace
126 WSCUpdateProvider
127 WSCWriteNameSpaceOrder
128 WSCWriteProviderOrder
129 freeaddrinfo
130 getaddrinfo
131 getnameinfo
132 inet_ntop
133 inet_pton
151 __WSAFDIsSet
500 WEP
-103
View File
@@ -1,103 +0,0 @@
/* ws2_32.dll stand-in for DiRT 3 and DiRT Showdown (32-bit).
*
* Both games close their motion telemetry UDP socket at the end of a race (and when leaving Joyride) and keep
* calling sendto() on it; the WSAENOTSOCK (10038) failure stops the game. Every export here jumps to the
* same-ordinal export of Wine's own ws2_32.dll, except that a sendto() failing with 10038 reports 0 bytes sent.
* Same behaviour as DiRTTelemetryErrorFix by RoccoC (MIT), based on the fix by Carsten Gottschling. */
typedef unsigned short WCHAR;
typedef unsigned long DWORD;
typedef unsigned int UINT;
typedef unsigned int UINT_PTR;
typedef int BOOL;
typedef void *HMODULE;
#define WINAPI __attribute__((stdcall))
#define WSAENOTSOCK 10038
#define ORDINAL(n) ((const char *)(UINT_PTR)(n))
__attribute__((dllimport)) HMODULE WINAPI LoadLibraryW(const WCHAR *name);
__attribute__((dllimport)) void *WINAPI GetProcAddress(HMODULE module, const char *name);
__attribute__((dllimport)) UINT WINAPI GetSystemDirectoryW(WCHAR *buffer, UINT size);
__attribute__((dllimport)) DWORD WINAPI GetEnvironmentVariableW(const WCHAR *name, WCHAR *buffer, DWORD size);
__attribute__((dllimport)) DWORD WINAPI GetFileAttributesW(const WCHAR *name);
/* droiddeck-game-env recognises a swapped-in copy by this text. */
__attribute__((used)) const char dirtfix_marker[] = "droiddeck-dirt-ws2_32";
extern const unsigned short dirtfix_ordinals[];
extern const unsigned int dirtfix_count;
extern void *dirtfix_real[];
static int (WINAPI *real_sendto)(UINT_PTR, const char *, int, int, const void *, int);
static int (WINAPI *real_WSAGetLastError)(void);
static void (WINAPI *real_WSASetLastError)(int);
int WINAPI dirtfix_sendto(UINT_PTR s, const char *buf, int len, int flags, const void *to, int tolen)
{
int ret = real_sendto(s, buf, len, flags, to, tolen);
if (ret == -1 && real_WSAGetLastError() == WSAENOTSOCK)
{
real_WSASetLastError(0);
return 0;
}
return ret;
}
static void append(WCHAR *dst, const char *src)
{
while (*dst) dst++;
while ((*dst++ = (WCHAR)(unsigned char)*src++));
}
static void append_number(WCHAR *dst, UINT n)
{
char digits[12];
int i = 11;
digits[i] = 0;
do digits[--i] = (char)('0' + n % 10); while (n /= 10);
append(dst, digits + i);
}
/* When this file replaces the prefix's syswow64\ws2_32.dll, Wine's own copy is the i386-windows\ws2_32.dll in one
* of the builtin DLL folders Wine lists in WINEDLLDIR0, WINEDLLDIR1, ... as NT paths (\??\Z:\...). */
static HMODULE load_wine_ws2_32(HMODULE self)
{
WCHAR name[24], path[600];
HMODULE real;
UINT n, d;
for (d = 0; d < 16; d++)
{
name[0] = 0;
append(name, "WINEDLLDIR");
append_number(name, d);
n = GetEnvironmentVariableW(name, path, 500);
if (!n || n >= 500) continue;
if (path[0] == '\\' && path[1] == '?' && path[2] == '?' && path[3] == '\\') path[1] = '\\';
append(path, "\\i386-windows\\ws2_32.dll");
if (GetFileAttributesW(path) == (DWORD)-1) continue;
if ((real = LoadLibraryW(path)) && real != self) return real;
}
n = GetSystemDirectoryW(path, 280);
if (!n || n >= 280) return 0;
path[n] = 0;
append(path, "\\ws2_32.dll");
real = LoadLibraryW(path);
return real != self ? real : 0;
}
BOOL WINAPI DllMain(HMODULE self, DWORD reason, void *reserved)
{
HMODULE real;
UINT i;
(void)reserved;
if (reason != 1) return 1;
if (!(real = load_wine_ws2_32(self))) return 0;
for (i = 0; i < dirtfix_count; i++) dirtfix_real[i] = GetProcAddress(real, ORDINAL(dirtfix_ordinals[i]));
real_sendto = GetProcAddress(real, ORDINAL(20));
real_WSAGetLastError = GetProcAddress(real, ORDINAL(111));
real_WSASetLastError = GetProcAddress(real, ORDINAL(112));
return real_sendto && real_WSAGetLastError && real_WSASetLastError;
}
@@ -4,7 +4,6 @@ import json
import os
import re
import runpy
import signal
import subprocess
import sys
import tempfile
@@ -736,127 +735,7 @@ def directaudio_settings(env):
return env
DIRT_GAMES = {"dirt3_game": "dirt3", "showdown": "dirtshowdown", "showdown_avx": "dirtshowdown"}
DIRT_WS2 = "/usr/local/lib/droiddeck-dirt/ws2_32.dll"
DIRT_MARKER = b"droiddeck-dirt-ws2_32"
DIRT_FIXED = "showdown_avx.exe".encode("utf-16-le")
DIRT_SAVED = ".droiddeck-original"
def dirt_telemetry_on(prefix, game):
"""Whether the game's UDP/motion output is on, as In-game stats or another listener sets it ("dbox" is its default)."""
try:
folders = [f for f in (Path(prefix) / "pfx/drive_c/users/steamuser/Documents/My Games").iterdir()
if f.name.lower().replace(" ", "") == game]
except OSError:
return False
for folder in folders:
try:
text = (folder / "hardwaresettings/hardware_settings_config.xml").read_text(encoding="latin-1")
except OSError:
continue
for tag in ("udp", "motion"):
element = re.search(r"<%s\s[^>]*>" % tag, text)
if element:
attrs = dict(re.findall(r'\s(\w+)="([^"]*)"', element.group(0)))
return attrs.get("enabled") == "true" and attrs.get("ip", "").lower() not in ("", "dbox")
return False
def proton_ws2(proton):
return Path(proton).parent / "files/lib/wine/i386-windows/ws2_32.dll"
def proton_has_dirt_fix(proton):
try:
return DIRT_FIXED in proton_ws2(proton).read_bytes()
except OSError:
return False
def prefix_ws2(prefix):
return Path(prefix) / "pfx/drive_c/windows/syswow64/ws2_32.dll"
def is_dirt_stand_in(path):
try:
return not path.is_symlink() and DIRT_MARKER in path.read_bytes()
except OSError:
return False
def dirt_ws2_wanted(command, env):
"""The prefix to give the ws2_32 stand-in: a DiRT 3 / Showdown launch with telemetry on and a Proton without the fix."""
prefix = env.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
if len(command) < 3 or not prefix or not os.path.isfile(DIRT_WS2):
return None
game = DIRT_GAMES.get(os.path.splitext(os.path.basename(command[2]))[0].lower())
if not game or not dirt_telemetry_on(prefix, game) or proton_has_dirt_fix(command[0]):
return None
return prefix if os.path.lexists(prefix_ws2(prefix)) else None
def swap_dirt_ws2(prefix):
"""Puts the stand-in where the prefix's syswow64/ws2_32.dll is; that file is kept beside it."""
target = prefix_ws2(prefix)
saved = target.with_name(target.name + DIRT_SAVED)
data = Path(DIRT_WS2).read_bytes()
if not is_dirt_stand_in(target):
if os.path.lexists(saved):
os.unlink(saved)
os.replace(target, saved)
staged = target.with_name(target.name + ".droiddeck-tmp")
staged.write_bytes(data)
os.replace(staged, target)
def restore_dirt_ws2(prefix, proton):
"""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 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 the running Proton's ws2_32.dll goes back instead."""
target = prefix_ws2(prefix)
saved = target.with_name(target.name + DIRT_SAVED)
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 os.path.realpath(saved) == os.path.realpath(own):
os.replace(saved, target)
return True
os.unlink(saved)
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)
os.symlink(own, link)
os.replace(link, target)
return True
return False
def wait_forwarding_signals(process):
def forward(signum, frame):
try:
process.send_signal(signum)
except OSError:
pass
for signum in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
signal.signal(signum, forward)
code = process.wait()
return 128 - code if code < 0 else code
def start(launch, launch_env, digest, after=None):
if after:
process = subprocess.Popen(launch, env=launch_env)
try:
return wait_forwarding_signals(process)
finally:
after()
def start(launch, launch_env, digest):
if digest:
code = subprocess.run(launch, env=launch_env, check=False).returncode
if code == 0:
@@ -881,7 +760,6 @@ def main():
except OSError:
digest = None
app_id = game_id(env)
dirt_prefix = None
if app_id:
gl_default = gl_vsync(env)
waiting = len(command) > 1 and command[1] == "waitforexitandrun"
@@ -901,10 +779,6 @@ def main():
if components:
own = fixes.get("WINEDLLOVERRIDES")
fixes["WINEDLLOVERRIDES"] = components + ";" + own if own else components
dirt_prefix = dirt_ws2_wanted(command, env)
if dirt_prefix:
own = fixes.get("WINEDLLOVERRIDES")
fixes["WINEDLLOVERRIDES"] = own + ";ws2_32=n,b" if own else "ws2_32=n,b"
path = Path.home() / ".config/droiddeck/game-environment.json"
config = {}
try:
@@ -949,29 +823,16 @@ def main():
return 1
if xbox_result is not None:
return xbox_result
after = None
prefix = env.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
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])
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)
sync = load_sync()
launch, launch_env = select_sync(command, env, sync)
if launch[0] != command[0]:
try:
return start(launch, launch_env, digest, after)
return start(launch, launch_env, digest)
except OSError as error:
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)
return start(launch, launch_env, digest)
if __name__ == "__main__":
+1 -1
View File
@@ -23,7 +23,7 @@ PACK_NAMES = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'butler']
SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/assets/pulseaudio.tzst',
'tools/linuxfs', 'tools/proot', 'tools/aaudio-sink', 'tools/directaudio', 'tools/packs',
'tools/gamescope/release.env', 'tools/droiddeck-esync/release.env',
'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/dirt-ws2', 'tools/components', 'tools/ci', 'tools/build_local.sh',
'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/components', 'tools/ci', 'tools/build_local.sh',
'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal',
'tools/quest', 'tools/vr/src', 'tools/vr/driver_droiddeck', 'tools/vr/layer', 'tools/vr/build.sh',
'app/src/main/cpp/waylandcomp/src/headpose_shm.h',
-152
View File
@@ -29,158 +29,6 @@ def config_text(entries):
return '"InstallConfigStore" { "Software" { "Valve" { "Steam" { "CompatToolMapping" { %s } } } } }' % mapping
class DirtTelemetryFixTest(unittest.TestCase):
SHOWDOWN_ON = '<x><motion enabled="true" ip="127.0.0.1" port="20777" delay="1" extradata="3" /></x>'
SHOWDOWN_DEFAULT = '<x><motion enabled="true" ip="dbox" port="20777" delay="1" extradata="0" /></x>'
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
root = Path(self.tmp.name)
self.prefix = root / "compatdata/2848447563"
self.proton = root / "Proton/proton"
self.own = root / "Proton/files/lib/wine/i386-windows/ws2_32.dll"
self.own.parent.mkdir(parents=True)
self.own.write_bytes(b"MZ wine ws2_32")
self.proton.write_text("")
self.target = self.prefix / "pfx/drive_c/windows/syswow64/ws2_32.dll"
self.target.parent.mkdir(parents=True)
self.target.symlink_to(self.own)
self.stand_in = root / "droiddeck-dirt/ws2_32.dll"
self.stand_in.parent.mkdir()
self.stand_in.write_bytes(b"MZ droiddeck-dirt-ws2_32 stand-in")
self.patch = mock.patch.dict(MODULE["dirt_ws2_wanted"].__globals__, {"DIRT_WS2": str(self.stand_in)})
self.patch.start()
def tearDown(self):
self.patch.stop()
self.tmp.cleanup()
def config(self, folder, text):
path = self.prefix / "pfx/drive_c/users/steamuser/Documents/My Games" / folder / "hardwaresettings/hardware_settings_config.xml"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text)
def command(self, exe="showdown.exe"):
return [str(self.proton), "waitforexitandrun", "/root/Storage/games/DiRT Showdown/" + exe]
def env(self):
return {"STEAM_COMPAT_DATA_PATH": str(self.prefix)}
def test_telemetry_counts_as_on_when_the_game_sends_somewhere(self):
self.config("DiRT Showdown", self.SHOWDOWN_DEFAULT)
self.assertFalse(MODULE["dirt_telemetry_on"](self.prefix, "dirtshowdown"))
self.config("DiRT Showdown", self.SHOWDOWN_ON)
self.assertTrue(MODULE["dirt_telemetry_on"](self.prefix, "dirtshowdown"))
self.config("DiRT Showdown", self.SHOWDOWN_ON.replace('enabled="true"', 'enabled="false"'))
self.assertFalse(MODULE["dirt_telemetry_on"](self.prefix, "dirtshowdown"))
self.config("DiRT3", '<x><motion enabled="true" ip="192.168.1.20" port="20777" /></x>')
self.assertTrue(MODULE["dirt_telemetry_on"](self.prefix, "dirt3"))
def test_stand_in_is_wanted_only_for_the_dirt_games_with_telemetry_on_and_a_proton_without_the_fix(self):
wanted = MODULE["dirt_ws2_wanted"]
self.config("DiRT Showdown", self.SHOWDOWN_DEFAULT)
self.assertIsNone(wanted(self.command(), self.env()))
self.config("DiRT Showdown", self.SHOWDOWN_ON)
self.assertEqual(wanted(self.command(), self.env()), str(self.prefix))
self.assertEqual(wanted(self.command("Showdown_AVX.exe"), self.env()), str(self.prefix))
self.assertIsNone(wanted(self.command("DiRTRally2.exe"), self.env()))
self.own.write_bytes(b"MZ wine ws2_32 " + "showdown_avx.exe".encode("utf-16-le"))
self.assertIsNone(wanted(self.command(), self.env()))
def test_swap_keeps_the_prefix_link_and_restore_puts_it_back(self):
MODULE["swap_dirt_ws2"](self.prefix)
saved = self.target.with_name("ws2_32.dll.droiddeck-original")
self.assertFalse(self.target.is_symlink())
self.assertEqual(self.target.read_bytes(), self.stand_in.read_bytes())
self.assertEqual(os.readlink(saved), str(self.own))
self.assertEqual(self.own.read_bytes(), b"MZ wine ws2_32")
MODULE["swap_dirt_ws2"](self.prefix)
self.assertEqual(os.readlink(saved), str(self.own))
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))
self.assertFalse(MODULE["restore_dirt_ws2"](self.prefix, self.proton))
def test_restore_keeps_a_file_proton_put_back_meanwhile(self):
MODULE["swap_dirt_ws2"](self.prefix)
newer = self.own.with_name("ws2_32-newer.dll")
newer.write_bytes(b"MZ newer wine ws2_32")
self.target.unlink()
self.target.symlink_to(newer)
self.assertFalse(MODULE["restore_dirt_ws2"](self.prefix, self.proton))
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())
self.assertTrue(MODULE["restore_dirt_ws2"](self.prefix, self.proton))
self.assertEqual(os.readlink(self.target), str(self.own))
def test_launch_swaps_the_stand_in_in_for_the_game_and_back_afterwards(self):
self.config("DiRT Showdown", self.SHOWDOWN_ON)
self.proton.write_text("#!" + sys.executable + "\nimport os, sys\n"
"target = os.path.join(os.environ['STEAM_COMPAT_DATA_PATH'], 'pfx/drive_c/windows/syswow64/ws2_32.dll')\n"
"print(os.environ.get('WINEDLLOVERRIDES', ''))\n"
"print(os.path.islink(target), b'droiddeck-dirt-ws2_32' in open(target, 'rb').read())\n")
self.proton.chmod(0o755)
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.assertEqual(result.returncode, 0, result.stderr)
overrides, state = result.stdout.splitlines()[-2:]
self.assertIn("ws2_32=n,b", overrides.split(";"))
self.assertEqual(state, "False True")
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")
self.proton.chmod(0o755)
home = Path(self.tmp.name) / "home"
home.mkdir()
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), *self.command()],
env={**os.environ, "HOME": str(home), "STEAM_COMPAT_DATA_PATH": str(self.prefix)}, text=True, capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertNotIn("ws2_32=n,b", result.stdout)
self.assertEqual(os.readlink(self.target), str(self.own))
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"))
self.assertEqual(code, 3)
self.assertEqual(calls, ["restored"])
with self.assertRaises(OSError):
MODULE["start"]([str(Path(self.tmp.name) / "missing")], dict(os.environ), None, lambda: calls.append("again"))
self.assertEqual(calls, ["restored"])
class GameDebugLoggingTest(unittest.TestCase):
def test_maintenance_precision_survives_run_with_performance_game_settings(self):
with tempfile.TemporaryDirectory() as tmp: