feat(dual-screen): bottom-screen Dashboard with downloads, notifications, screenshots, Steam chat and In-game stats (#1920)

A Dashboard mode for the second screen of dual-screen handhelds (developed on a Retroid Pocket Duo), the default on dual-screen devices. It opens on Chat at each Steam start and switches to In-game stats when a game starts.

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

About "telemetry": here it means a racing game's own live driving data (speed, gear, rpm, pedals), not app analytics. For In-game stats no information leaves the device and nothing is shared: the game sends its data to 127.0.0.1 on the same device, DroidDeck only listens there while the page is open and keeps the numbers in memory just long enough to draw them. DroidDeck sends no data about the user or their use of the app; logs leave the device only when the user taps Share logs.
This commit is contained in:
The412Banner authored and GitHub committed 2026-11-01 02:36:57 +00:00
1 parent bfa61b5139
commit 8a7022fc14
52 files changed
+4576 -63

No files matched your search

@@ -0,0 +1,215 @@
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()
})
}
@@ -0,0 +1,161 @@
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 tab picked during one session. Each Steam session starts with no pick, so the dashboard opens on Chat; reopened
* later in the same session it shows the tab picked last.
*/
internal object SessionBottomTab {
private var session: String? = null
private var tab: String? = null
@Synchronized
fun picked(sessionId: String?): String? = tab.takeIf { sessionId != null && sessionId == session }
@Synchronized
fun pick(sessionId: String?, id: String) {
session = sessionId
tab = id
}
}
/** The page a game start switches to; not remembered as the user's pick. */
internal fun pageForGameStart(ids: List<String>): String? = GAME_PAGE.takeIf { it in ids }
private const val DEFAULT_PAGE = "chat"
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)
}
}
@@ -0,0 +1,126 @@
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)
}
}
@@ -0,0 +1,117 @@
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)
}
}
@@ -0,0 +1,28 @@
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() },
)
@@ -0,0 +1,110 @@
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 },
)
}
}
}
}
}
@@ -0,0 +1,404 @@
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.input.SteamTouchConfig
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.SpeedUnit
import com.droiddeck.launcher.session.StatsDash
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 gameName by remember { mutableStateOf<String?>(null) }
val steamClient = remember { if (SessionState.mode == SessionService.MODE_STEAM) SessionPrefs.activeSteamClientArch(context) else null }
var outputFailed by remember { mutableStateOf<String?>(null) }
var rescan by remember { mutableIntStateOf(0) }
var auto by remember { mutableStateOf(SessionPrefs.telemetryAuto(context)) }
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(running) {
val id = running?.toLongOrNull()
gameName = if (id == null) null
else withContext(Dispatchers.IO) { runCatching { SteamTouchConfig.gameName(context, id.toInt()) }.getOrNull() }
}
LaunchedEffect(rescan) {
while (isActive) {
outputs = withContext(Dispatchers.IO) { runCatching { TelemetryOutput.scan(Library.compatdataDirs(context)) }.getOrDefault(emptyList()) }
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,
if (running != null) gameName else steamClient?.let { stringResource(steamClientLabel(it)) })) {
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()
}
}
/** The Steam client the session runs, shown in the strip's top line while no game runs. */
internal fun steamClientLabel(arch: String): Int = if (arch == "x86_64") R.string.stats_steam_client_x86 else R.string.stats_steam_client_arm
@Composable
private fun ChoiceRow(title: String, value: String, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
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)
}
@@ -56,9 +56,11 @@ 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 {
@@ -155,12 +157,7 @@ class SecondScreenPresentation(
menuShown = on
if (on) {
keyboardHost?.takeIf { it.shown }?.hide()
window?.decorView?.let { decor ->
decor.setViewTreeLifecycleOwner(sessionActivity)
decor.setViewTreeViewModelStoreOwner(sessionActivity)
decor.setViewTreeSavedStateRegistryOwner(sessionActivity)
decor.setViewTreeOnBackPressedDispatcherOwner(sessionActivity)
}
ownComposeViews()
val view = menuView ?: androidx.compose.ui.platform.ComposeView(context).apply {
isFocusable = true
isFocusableInTouchMode = true
@@ -179,12 +176,22 @@ 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
@@ -192,7 +199,8 @@ class SecondScreenPresentation(
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
val forward = menuShown || currentMode != SecondScreenMode.TERMINAL || PadBridge.isControllerKeyEvent(event)
val ownKeys = currentMode == SecondScreenMode.TERMINAL || currentMode == SecondScreenMode.DASHBOARD
val forward = menuShown || !ownKeys || PadBridge.isControllerKeyEvent(event)
if (forward && sessionActivity.dispatchKeyEvent(event)) return true
return super.dispatchKeyEvent(event)
}
@@ -218,19 +226,37 @@ class SecondScreenPresentation(
keyboardButton = null
keyboardPending = false
closeTerminal()
closeDashboard()
root.removeAllViews()
val mode = if (currentMode == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad) SecondScreenMode.NONE
else currentMode
val mode = when {
currentMode == SecondScreenMode.DECK_CONTROLS && !SessionState.deckPad -> SecondScreenMode.NONE
currentMode == SecondScreenMode.DASHBOARD && dashboard == null -> 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,6 +31,7 @@ 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
@@ -240,6 +241,7 @@ 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,
@@ -893,6 +895,7 @@ 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,
@@ -1190,7 +1193,8 @@ 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 (com.droiddeck.launcher.session.SessionState.deckPad) listOf(SecondScreenMode.DECK_CONTROLS) else emptyList()) +
(if (a.dashboardAvailable) listOf(SecondScreenMode.DASHBOARD) else emptyList())
SettingsGroup(stringResource(R.string.drawer_second_screen_mode)) {
Column(Modifier.fillMaxWidth().selectableGroup()) {
modes.forEach { mode ->
@@ -0,0 +1,588 @@
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))
}
}
}
@@ -0,0 +1,293 @@
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.TextAlign
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)
}
}
/** The mark and "DroidDeck" on the left, the running game's name in the middle, the clock on the right. */
@Composable
private fun LogoHeader(clock: String, game: String?) {
val colors = MaterialTheme.colorScheme
Row(Modifier.fillMaxWidth().padding(horizontal = 2.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
DroidDeckLogo(16.dp)
Text("DroidDeck", fontSize = 13.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
Text(game.orEmpty(), fontSize = 13.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, textAlign = TextAlign.Center,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
if (clock.isNotEmpty()) Text(clock, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = colors.onSurfaceVariant)
}
}
@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,
val game: String? = null,
)
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, d.game)
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
HistoryTile("FPS", accent, fpsText(d.fps), "fps", d.fpsHistory, 75f)
HistoryTile("CPU", StatsColors.cpu, s?.cpuPercent?.let { "$it%" } ?: "–", s?.cpuTempC?.let { "$it°" } ?: "", d.cpuHistory, 100f)
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, d.game)
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
RingTile("CPU", StatsColors.cpu, s?.cpuPercent?.let { it / 100f }, s?.cpuPercent?.let { "$it%" } ?: "–", s?.cpuTempC?.let { "$it °C" } ?: "")
RingTile("GPU", StatsColors.gpu, gpuPercent?.let { it / 100f }, gpuPercent?.let { "$it%" } ?: gpuTemp?.let { "$it°" } ?: "–",
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)
}
}
}