Merge origin/main into feat/malibridge-v25

This commit is contained in:
DroidDeck Merge committed 2026-11-01 19:59:31 +08:00
commit a2a5f84711
132 files changed
+7212 -156

No files matched your search

@@ -18,6 +18,7 @@ class App : Application() {
super.onCreate()
com.droiddeck.launcher.ui.Themes.loadGradient(this)
com.droiddeck.launcher.ui.BuildWatermark.install(this)
HomeApp.trackRecents(this)
// Helper processes must not initialize the main USB provider or guest graphics context.
val process = if (android.os.Build.VERSION.SDK_INT >= 28) Application.getProcessName()
else (getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)
@@ -1588,6 +1588,22 @@ class FrontEndActivity : ComponentActivity() {
startSession(Intent(this, SessionActivity::class.java).putExtra(SessionActivity.EXTRA_STEAMVR, steamVr), steamSession = true)
}
@Suppress("OVERRIDE_DEPRECATION")
override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) {
val outside = com.droiddeck.launcher.ui.DualScreenPanel.shownOn >= 0 &&
com.droiddeck.launcher.ui.DualScreenPanel.opensOutside(packageName, intent.component?.packageName ?: intent.`package` ?: intent.resolveActivity(packageManager)?.packageName)
if (outside) {
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, true)
window.decorView.postDelayed({ if (hasWindowFocus()) com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false) }, 1500)
}
try {
super.startActivityForResult(intent, requestCode, options)
} catch (e: RuntimeException) {
if (outside) com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
throw e
}
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) {
@@ -147,6 +147,52 @@ object HomeApp {
.getShortcutIconDrawable(info, context.resources.displayMetrics.densityDpi)?.toBitmap(px, px)
}.getOrNull()
fun trackRecents(app: android.app.Application) {
app.registerActivityLifecycleCallbacks(object : android.app.Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: android.app.Activity, savedInstanceState: android.os.Bundle?) = Unit
override fun onActivityStarted(activity: android.app.Activity) = Unit
override fun onActivityResumed(activity: android.app.Activity) = syncRecents(activity)
override fun onActivityPaused(activity: android.app.Activity) { if (activity is FrontEndActivity) syncRecents(activity) }
override fun onActivityStopped(activity: android.app.Activity) = Unit
override fun onActivitySaveInstanceState(activity: android.app.Activity, outState: android.os.Bundle) = Unit
override fun onActivityDestroyed(activity: android.app.Activity) = Unit
})
}
private fun syncRecents(activity: android.app.Activity) =
keepOutOfRecents(activity, activity is FrontEndActivity && !SessionState.running && isDefault(activity))
internal enum class RecentsStep { HIDE, SHOW, FORGET, NONE }
internal fun recentsStep(hidden: Boolean, owned: Boolean, excluded: Boolean): RecentsStep = when {
hidden && !excluded -> RecentsStep.HIDE
!hidden && owned && excluded -> RecentsStep.SHOW
!hidden && owned -> RecentsStep.FORGET
else -> RecentsStep.NONE
}
fun keepOutOfRecents(activity: android.app.Activity, hidden: Boolean) {
val prefs = activity.getSharedPreferences("home-recents", Context.MODE_PRIVATE)
val owned = prefs.getStringSet("tasks", null).orEmpty()
val id = activity.taskId.toString()
if (!hidden && id !in owned) return
runCatching {
@Suppress("DEPRECATION")
fun idOf(task: android.app.ActivityManager.AppTask) =
if (Build.VERSION.SDK_INT >= 29) task.taskInfo.taskId else task.taskInfo.persistentId
val tasks = activity.getSystemService(android.app.ActivityManager::class.java).appTasks
val task = tasks.firstOrNull { idOf(it) == activity.taskId } ?: return
val excluded = task.taskInfo.baseIntent.flags and Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS != 0
val step = recentsStep(hidden, id in owned, excluded)
if (step == RecentsStep.NONE) return
if (step != RecentsStep.FORGET) task.setExcludeFromRecents(step == RecentsStep.HIDE)
val live = tasks.map { idOf(it).toString() }.toSet()
val next = owned.filter { it in live && it != id }.toMutableSet()
if (step == RecentsStep.HIDE) next += id
prefs.edit().putStringSet("tasks", next).apply()
}
}
fun startShortcut(context: Context, info: ShortcutInfo) {
val task = generateSequence(context) { (it as? android.content.ContextWrapper)?.baseContext }
.filterIsInstance<android.app.Activity>().firstOrNull()?.taskId
@@ -120,6 +120,10 @@ import com.droiddeck.launcher.ui.LoadingOverlay
import com.droiddeck.launcher.ui.SessionDrawer
import com.droiddeck.launcher.ui.SessionPausedOverlay
import com.droiddeck.launcher.ui.SecondScreenPresentation
import com.droiddeck.launcher.ui.BottomDashboard
import com.droiddeck.launcher.ui.BottomPage
import com.droiddeck.launcher.ui.sessionBottomPages
import com.droiddeck.launcher.ui.BottomPageActions
import com.droiddeck.launcher.ui.DroidDeckTheme
import com.droiddeck.launcher.wayland.CompositorHost
import com.droiddeck.launcher.wayland.WaylandCompositor
@@ -214,6 +218,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private lateinit var touchscreenGestures: TouchscreenGestures
private var gestureConfig = com.droiddeck.launcher.input.TouchGestureConfig()
private var gestureGame: String? = null
private var gameStarts by mutableIntStateOf(0)
private var gestureSettingsOpen by mutableStateOf(false)
private var steamImportAsk by mutableStateOf<com.droiddeck.launcher.session.SteamImportPrompt.Ask?>(null)
private var steamImportAnswered: String? = null
@@ -358,11 +363,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var drawerGameProfileId by mutableStateOf<Long?>(null)
private var fpsLimit by mutableStateOf(SessionState.fpsLimit)
private fun noSteamSession(): Boolean = SessionState.mode == SessionService.MODE_RUN &&
private fun noSteamSession(): Boolean = (SessionState.mode == SessionService.MODE_RUN &&
SessionState.program in setOf(
com.droiddeck.launcher.session.NoSteamLaunch.PROTON_RUN, com.droiddeck.launcher.session.NoSteamLaunch.EPIC,
com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET,
)
)) || SessionState.mode == SessionService.MODE_DESKTOP
private val drawerGameInventory = GameProfileInventoryCache<Library.SteamGame>()
private var drawerGameInventoryRevision = 0L
private var drawerGameFexPresetSaving by mutableStateOf(false)
@@ -576,6 +581,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val mode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
SessionEvents.begin(this, mode, SessionPaths.label(mode, intent.getStringExtra(SessionService.EXTRA_PROGRAM)))
// begin() moves the phase on, so the block below never runs for a new session; reset per-session flags here.
SessionState.secondScreenAutoOpened = false
SessionState.secondScreenProvisional = false
}
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
SessionState.program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
@@ -583,8 +591,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionState.steamUi = intent.getStringExtra(SessionService.EXTRA_STEAM_UI)
SessionState.steamUrl = intent.getStringExtra(SessionService.EXTRA_STEAM_URL)
SessionState.steamVr = intent.getBooleanExtra(EXTRA_STEAMVR, false)
SessionState.secondScreenAutoOpened = false
SessionState.secondScreenProvisional = false
} else if (intent.getBooleanExtra(EXTRA_STEAMVR, false) && SessionState.mode == SessionService.MODE_STEAM) {
SessionState.steamVr = true
}
@@ -728,9 +734,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
})
scrollTouch = ScrollTouchGestures(PointerGestures.slop(this),
android.view.ViewConfiguration.get(this).scaledMinimumFlingVelocity.toFloat(), scrollListener)
val noCursor = android.view.PointerIcon.getSystemIcon(this, android.view.PointerIcon.TYPE_NULL)
root.pointerIcon = noCursor
surfaceView.pointerIcon = noCursor
applyPlatformPointer(appUiOwnsPointer())
loading = LoadingState(this, steam = loadingMode() == SessionService.MODE_STEAM)
if (!SessionState.running) {
@@ -829,10 +833,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
isFocusableInTouchMode = true
defaultFocusHighlightEnabled = false
setContent {
val uiPointer = appUiOwnsPointer()
androidx.compose.runtime.SideEffect {
com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity,
(drawerOpen || achievementsOpen || pcKeyboardOpen) && !pipUi && steamVrStatus != SteamVr.Status.RUNNING)
}
androidx.compose.runtime.SideEffect { applyPlatformPointer(uiPointer) }
androidx.compose.runtime.DisposableEffect(Unit) {
onDispose { com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity, false) }
}
@@ -874,7 +880,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
} else {
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) {
CursorOverlay({ cursorPos }, cursorVisible, resources.displayMetrics.density,
CursorOverlay({ cursorPos }, cursorVisible && !uiPointer,
resources.displayMetrics.density,
cursorImage, cursorHotX, cursorHotY, cursorImageScale)
if (memoryHud.text.isNotEmpty()) HudText(memoryHud.text, hudColor, hudOpacity)
val phonePanel = glassesOutputActive && !loading.visible && !drawerOpen && !pcKeyboardOpen
@@ -914,7 +921,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
window.setBackgroundDrawable(android.graphics.drawable.ColorDrawable(android.graphics.Color.BLACK))
},
)
LaunchedEffect(AgentGuest.focusRevision) {
// Also runs when a second screen appears, so Automatic applies then with the running game known.
LaunchedEffect(AgentGuest.focusRevision, secondScreenDisplays.isNotEmpty()) {
val nextGame = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
if (SessionState.mode == SessionService.MODE_RUN) SessionState.program?.let { "program:$it" }
else {
@@ -927,7 +935,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}
}
}
if (nextGame != gestureGame) { gestureGame = nextGame; refreshGestureConfig() }
if (nextGame != gestureGame) {
if (nextGame != null) gameStarts++
gestureGame = nextGame
refreshGestureConfig()
}
if (secondScreenDisplays.isNotEmpty()) kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
runCatching { com.droiddeck.launcher.session.TelemetryOutput.applyAutomatic(this@SessionActivity, nextGame) }
}
}
LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, pipUi, SessionState.suspended) {
if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || pipUi || SessionState.suspended) {
@@ -1177,6 +1192,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
touchAuto = getString(if (usingTouchpad()) R.string.session_touch_auto_touchpad else R.string.session_touch_auto_direct),
fexPreset = fexPreset,
secondScreenMode = secondScreenMode,
dashboardAvailable = bottomPages().isNotEmpty(),
secondScreenDisplays = secondScreenDisplays,
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
@@ -2189,6 +2205,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
surfaceW = 0
surfaceH = 0
glassesOutputActive = false
if (CompositorHost.isStarted) WaylandCompositor.nativeSetCursorComposite(false)
CompositorHost.detach(holder.surface)
}
@@ -2622,7 +2639,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (joyConVr?.onMotionEvent(event) == true) return true
if (PadBridge.isControllerMotionEvent(event) && padMouseMode() && padMouse.onMotion(event)) return true
if (padBridge?.onMotionEvent(event) == true) return true
if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE) && !drawerOpen && onMouse(event)) return true
if (event.isFromSource(android.view.InputDevice.SOURCE_MOUSE) && !drawerOpen) {
/* The app's own controls get the pointer first. With the picture on the glasses the
* phone shows its panel, and hovering or clicking a control there must reach it
* instead of moving and clicking the guest pointer on the glasses. Whatever the UI
* leaves alone — the rest of the screen — still drives the guest pointer. */
if (appUiOwnsPointer()) {
if (super.dispatchGenericMotionEvent(event)) return true
if (onMouse(event)) return true
return false
}
if (onMouse(event)) return true
}
return super.dispatchGenericMotionEvent(event)
}
@@ -2836,6 +2864,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun onWheel(steps: Int) { sendSceneWheel(steps) }
override fun onScroll(dx: Float, dy: Float) = fingerScroll(dx, dy)
override fun onScrollEnd() = fingerScrollEnd()
override fun onThreeFingerTap(): Boolean {
uiHandler.post { togglePcKeyboard() }
return true
}
override fun onZoom(steps: Int) {
WaylandCompositor.nativeSendKey(KEY_LEFTCTRL, 1)
sendSceneWheel(steps)
@@ -3034,7 +3066,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (secondScreenDisplays.none { it.id == target.displayId }) return
SessionState.secondScreenAutoOpened = true
selectedSecondScreenDisplay = target.displayId
selectSecondScreenMode(SecondScreenMode.opening(SessionPrefs.secondScreenPanel(this), SessionState.deckPad))
selectSecondScreenMode(SecondScreenMode.opening(SessionPrefs.secondScreenPanel(this), SessionState.deckPad, bottomPages().isNotEmpty()))
dualControlsProvisional = ::loading.isInitialized && loading.visible
}
@@ -3042,7 +3074,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (!dualControlsProvisional || pipUi || !started || (::loading.isInitialized && loading.visible)) return
dualControlsProvisional = false
if (secondScreenMode == SecondScreenMode.NONE) return
val wanted = SecondScreenMode.opening(SessionPrefs.secondScreenPanel(this), SessionState.deckPad)
val wanted = SecondScreenMode.opening(SessionPrefs.secondScreenPanel(this), SessionState.deckPad, bottomPages().isNotEmpty())
if (wanted != secondScreenMode) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal()
}
@@ -3112,8 +3144,97 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
menu = {
DroidDeckTheme { SessionMenu(docked = true) }
},
dashboard = if (bottomPages().isEmpty()) null else ({
DroidDeckTheme {
BottomDashboard(
bottomPages(), com.droiddeck.launcher.ui.SessionBottomTab.picked(SessionState.sessionId),
gameStarts = gameStarts,
onPage = { com.droiddeck.launcher.ui.SessionBottomTab.pick(SessionState.sessionId, it) },
onClose = { selectSecondScreenMode(SecondScreenMode.NONE) },
onMenu = if (dockDrawer()) ({ drawerOpen = true }) else null,
)
}
}),
)
/** Pages for the bottom-screen dashboard; the dashboard is offered only while at least one exists. */
private fun bottomPages(): List<BottomPage> = sessionBottomPages(BottomPageActions(
takeScreenshot = ::captureScreenshot,
fps = { if (::hud.isInitialized) hud.liveFps else null },
openSettings = ::openSettingsBelow,
runningGame = { gestureGame },
))
// A settings page opened on the bottom screen sits under the dashboard window, so the dashboard hides
// until the setting is on, or for at most SETTINGS_WATCH_CHECKS seconds when it is left off (another
// app's page closing cannot be seen); choosing Dashboard in the menu again shows it sooner.
private fun openSettingsBelow(intent: android.content.Intent, done: () -> Boolean) {
val presentation = secondScreenPresentation ?: return
val options = android.app.ActivityOptions.makeBasic().setLaunchDisplayId(presentation.display.displayId)
val opened = listOf(intent, android.content.Intent(android.provider.Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)).any {
runCatching { startActivity(android.content.Intent(it).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK), options.toBundle()) }
.onFailure { e -> Log.w(TAG, "could not open ${it.action} on display ${presentation.display.displayId}", e) }
.isSuccess
}
if (!opened) return
presentation.hide()
var checks = 0
// Show throws if the display went away while the settings page was open, as in showSecondScreen.
fun showAgain() {
try {
presentation.show()
} catch (e: Exception) {
Log.w(TAG, "could not show the dashboard again", e)
if (secondScreenPresentation === presentation) closeSecondScreen(reset = true)
}
}
uiHandler.postDelayed(object : Runnable {
override fun run() {
if (secondScreenPresentation !== presentation || presentation.isShowing) return
if (done()) {
showAgain()
return
}
if (++checks < SETTINGS_WATCH_CHECKS) uiHandler.postDelayed(this, SETTINGS_WATCH_MS) else showAgain()
}
}, SETTINGS_WATCH_MS)
}
/** Copies the game frame (no overlay) at the size it is shown and saves it to Pictures/DroidDeck. */
private fun captureScreenshot(onDone: (Boolean) -> Unit) {
// With the glasses as the output the game is drawn on their surface; the phone's surface is hidden then.
val source = if (glassesOutputActive) glassesScreen?.surfaceView else if (::surfaceView.isInitialized) surfaceView else null
val width = source?.width ?: 0
val height = source?.height ?: 0
if (source == null || width <= 0 || height <= 0 || source.holder.surface?.isValid != true) {
onDone(false)
return
}
val bitmap = try {
android.graphics.Bitmap.createBitmap(width, height, android.graphics.Bitmap.Config.ARGB_8888)
} catch (_: OutOfMemoryError) {
onDone(false)
return
}
try {
android.view.PixelCopy.request(source, bitmap, { result ->
if (result != android.view.PixelCopy.SUCCESS) {
bitmap.recycle()
onDone(false)
return@request
}
Thread {
val saved = com.droiddeck.launcher.session.BottomScreenshots.save(applicationContext, bitmap)
bitmap.recycle()
runOnUiThread { onDone(saved) }
}.start()
}, uiHandler)
} catch (_: IllegalArgumentException) {
bitmap.recycle()
onDone(false)
}
}
private fun tapSteamButton() {
if (SessionState.mode == SessionService.MODE_STEAM) {
padBridge?.applyTouch { st -> st.press(com.droiddeck.launcher.input.PadState.GUIDE, true) }
@@ -3523,6 +3644,33 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (want) view.requestPointerCapture() else view.releasePointerCapture()
}
/** Null until the first application, so the initial state is applied rather than skipped. */
private var platformPointerShown: Boolean? = null
/**
* The app's own UI is what the mouse is over, so it needs a pointer of its own: the drawer,
* keyboard, achievements and PiP controls, and — once the glasses own the picture — the whole
* phone, which then shows [GlassesPhonePanel] instead of the game.
*/
private fun appUiOwnsPointer(): Boolean =
drawerOpen || pcKeyboardOpen || achievementsOpen || pipUi || glassesOutputActive
/**
* Over the game neither this app nor Android draws a pointer: the compositor's cursor is the
* only one (Compose's on the phone, inside the picture on the glasses). Over the app's own UI
* the game gets no pointer events at all, so without this nothing visible follows the mouse
* while buttons still highlight and click.
*/
private fun applyPlatformPointer(shown: Boolean) {
if (!::sessionRoot.isInitialized || !::surfaceView.isInitialized) return
if (shown == platformPointerShown) return
platformPointerShown = shown
val icon = if (shown) null
else android.view.PointerIcon.getSystemIcon(this, android.view.PointerIcon.TYPE_NULL)
sessionRoot.pointerIcon = icon
surfaceView.pointerIcon = icon
}
private fun onCapturedPointer(event: MotionEvent): Boolean {
if (!pointerLocked || !event.isFromSource(InputDevice.SOURCE_MOUSE_RELATIVE)) return false
notePress(event)
@@ -4209,6 +4357,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun onOutputAttached(holder: SurfaceHolder) {
if (holder !== outputHolder()) return
glassesOutputActive = glassesScreen?.holder === holder
if (CompositorHost.isStarted) WaylandCompositor.nativeSetCursorComposite(glassesOutputActive)
// Keep the phone's layout for touch/controller coordinates, but remove
// its SurfaceView so it cannot retain the last game frame under the hint.
surfaceView.visibility = if (glassesOutputActive) View.INVISIBLE else View.VISIBLE
@@ -4509,6 +4658,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private const val TEXT_FIELD_TAP_MS = 1_000L
private const val PAUSED_FRAME_MAX_EDGE = 1920f
private const val PAUSED_FRAME_REDRAW_MS = 150L
private const val SETTINGS_WATCH_MS = 1_000L
private const val SETTINGS_WATCH_CHECKS = 600
private const val TAG = "SessionActivity"
private var startedScreens = 0
@Volatile private var activeInstallWorker: Any? = null
@@ -22,6 +22,7 @@ import java.io.FileInputStream
internal class AddonPack(
val name: String, private val sha256: String, val size: Long, private val required: List<String>,
private val reuseDeviceCopy: Boolean = sha256.isEmpty() && !BuildConfig.CI_BUILD,
private val bundle: (Context) -> java.io.InputStream = { it.assets.open("packs/$name.tar.zst") },
) {
sealed interface State {
data object Missing : State
@@ -104,7 +105,7 @@ internal class AddonPack(
}
val root = root(context).apply { mkdirs() }
val archive = File(root, "$sha256.tar.zst")
val downloaded = urls.any { url ->
val downloaded = bundled(context, archive) || urls.any { url ->
Downloader.downloadFile(url, archive, true, sha256) { p -> mutableState.value = State.Downloading(p.coerceIn(0f, 1f)) }
.also { if (!it) archive.delete() }
}
@@ -126,6 +127,17 @@ internal class AddonPack(
return true
}
// A local build pins the packs it compiled, which no release hosts, so it ships them as assets.
internal fun bundled(context: Context, archive: File): Boolean {
val copied = runCatching {
bundle(context).use { input -> archive.outputStream().use { input.copyTo(it) } }
}.isSuccess
if (copied && Hashes.sha256(archive).equals(sha256, ignoreCase = true)) return true
if (copied) Log.w(TAG, "$name: the bundled pack does not match the pinned digest")
archive.delete()
return false
}
companion object {
private const val TAG = "AddonPack"
private const val REPO = "Droid-Deck/DroidDeck-Components"
@@ -287,14 +287,17 @@ object AddedGameArt {
var sgdbDown = false
var changed = false
for (game in games) {
if (forgetOtherAppsArt(context, game)) changed = true
val cache = cacheDir(context, game)
val start = missing(context, game)
val again = refetch(cache) intersect start
if (again.isEmpty()) File(cache, REFETCH).delete()
val full = Slot.COVER in start
val allowed = if (full) Slot.values().toSet() else EXTRAS
val allowed = if (full) Slot.values().toSet() else EXTRAS + again
var need = start intersect allowed
if (need.isEmpty() || (need == setOf(Slot.ICON) && sgdbKey.isEmpty())) continue
val cache = cacheDir(context, game)
val tried = File(cache, EXTRAS_TRIED)
if (!full && tried.isFile && tried.lastModified() >= keyChangedAt && System.currentTimeMillis() - tried.lastModified() < RETRY_AFTER_MS) continue
if (!full && again.isEmpty() && tried.isFile && tried.lastModified() >= keyChangedAt && System.currentTimeMillis() - tried.lastModified() < RETRY_AFTER_MS) continue
cache.mkdirs()
if (Slot.LOGO in need && game.source != Library.ADDED && runCatching { sources.storeLogo(game) }.getOrDefault(false)) {
changed = true
@@ -324,11 +327,42 @@ object AddedGameArt {
asked = false
}
}
if ((missing(context, game) intersect EXTRAS).isEmpty()) tried.delete() else if (asked) tried.writeText("")
val left = missing(context, game)
if (again.isNotEmpty()) keepRefetch(cache, again intersect left)
if ((left intersect EXTRAS).isEmpty()) tried.delete() else if (asked) tried.writeText("")
}
return changed
}
internal const val REFETCH = "refetch"
private fun refetch(cache: File): Set<Slot> =
runCatching { File(cache, REFETCH).readText() }.getOrDefault("").split(',').mapNotNull { key -> Slot.values().firstOrNull { it.key == key } }.toSet()
private fun keepRefetch(cache: File, slots: Set<Slot>) {
if (slots.isEmpty()) File(cache, REFETCH).delete() else File(cache, REFETCH).writeText(slots.joinToString(",") { it.key })
}
internal fun forgetOtherAppsArt(context: Context, game: AddedGames.Game): Boolean {
val cache = cacheDir(context, game)
val recorded = SteamMatch.get(context, game.folder.path)?.takeIf { it.appId != null }
val legacy = runCatching { File(cache, "steam-appid").readText().trim().toInt() }.getOrNull()?.takeIf { it > 0 }
val before = recorded?.appId ?: legacy ?: return false
val identity = runCatching { GameIdentifier.identify(game.exe) }.getOrNull()
val now = identity?.appId
val fromFiles = recorded?.certainty == SteamMatch.Certainty.FILES || before == GameIdentifier.SPACEWAR
if (now == before || (now == null && !fromFiles)) return false
SteamMatch.put(context, game.folder.path,
if (identity != null && now != null) SteamMatch.Match(now, SteamMatch.Certainty.FILES, identity.source.name.lowercase(), System.currentTimeMillis())
else SteamMatch.Match(null, SteamMatch.Certainty.NONE, "", 0))
val dropped = Slot.values().filter { File(cache, SteamGridDb.cacheName(it)).delete() }.toSet()
Slot.values().forEach { File(cache, SteamGridDb.cacheName(it) + ".src").delete() }
listOf("sgdb-id", "steam-appid", EXTRAS_TRIED).forEach { File(cache, it).delete() }
keepRefetch(cache, refetch(cache) + dropped)
Log.i(TAG, "${game.name}: its files no longer name Steam app $before; its art is fetched again")
return dropped.isNotEmpty()
}
internal fun steamMatch(context: Context, game: AddedGames.Game, search: (String) -> Int?): SteamMatch.Match {
if (game.source == Store.BATTLENET.id) {
val id = game.storeId?.let(BattleNet::title)?.steam
@@ -5,6 +5,7 @@ import java.io.File
object GameIdentifier {
private const val MAX_PARENT_DEPTH = 6
internal const val SPACEWAR = 480
enum class Source { STEAM_APPID_TXT, STEAM_MANIFEST_ACF, STEAM_EMU_INI, GOG_INFO, PE_VERSION, FILENAME, NONE }
enum class Confidence { HIGH, MEDIUM, LOW }
@@ -92,7 +93,7 @@ object GameIdentifier {
for (candidate in arrayOf(File(dir, "steam_appid.txt"), File(dir, "steam_settings/steam_appid.txt"))) {
val id = readSmallTextFile(candidate)?.removePrefix("\uFEFF")?.trim()
?.takeWhile { it.isDigit() }?.toIntOrNull()
if (id != null && id > 0) return id
if (id != null && id > 0 && id != SPACEWAR) return id
}
return null
}
@@ -111,7 +112,7 @@ object GameIdentifier {
for (f in candidates) {
val text = readSmallTextFile(f) ?: continue
val id = re.find(text)?.groupValues?.getOrNull(1)?.toIntOrNull()
if (id != null && id > 0) return id
if (id != null && id > 0 && id != SPACEWAR) return id
}
return null
}
@@ -133,7 +134,8 @@ object GameIdentifier {
val match = manifests.firstOrNull { m ->
val text = readSmallTextFile(m) ?: return@firstOrNull false
val installdir = vdfValue(text, "installdir")
gameFolder != null && installdir != null && installdir.equals(gameFolder, ignoreCase = true)
gameFolder != null && installdir != null && installdir.equals(gameFolder, ignoreCase = true) &&
vdfValue(text, "appid")?.toIntOrNull() != SPACEWAR
} ?: return null
val text = readSmallTextFile(match) ?: return null
@@ -101,15 +101,22 @@ object Library {
libraries: List<File> = steamLibraries(context).map { it.first },
): File? {
val ids = listOf(appId.toString(), java.lang.Integer.toString(appId.toInt())).distinct()
return prefixRoots(context, libraries, preferredLibrary).asSequence()
.flatMap { root -> ids.asSequence().map { id -> File(root, "steamapps/compatdata/$id/pfx") } }
.firstOrNull { it.isDirectory }
}
/** Every steamapps/compatdata folder, in the libraries [protonPrefix] searches. */
fun compatdataDirs(context: Context, libraries: List<File> = steamLibraries(context).map { it.first }): List<File> =
prefixRoots(context, libraries).map { File(it, "steamapps/compatdata") }.filter { it.isDirectory }
private fun prefixRoots(context: Context, libraries: List<File>, preferredLibrary: File? = null): List<File> {
val secondary = libraries.drop(1).mapNotNull { runCatching { it.canonicalPath }.getOrNull() }.toSet()
fun prefixRoot(root: File): File = if (runCatching { root.canonicalPath }.getOrNull() in secondary)
SecondaryLibrary.privateRoot(context.filesDir, root).takeIf { File(it, "steamapps/compatdata").isDirectory } ?: root
else root
val roots = (listOfNotNull(preferredLibrary) + libraries).map(::prefixRoot)
return (listOfNotNull(preferredLibrary) + libraries).map(::prefixRoot)
.distinctBy { runCatching { it.canonicalPath }.getOrDefault(it.absolutePath) }
return roots.asSequence()
.flatMap { root -> ids.asSequence().map { id -> File(root, "steamapps/compatdata/$id/pfx") } }
.firstOrNull { it.isDirectory }
}
fun steamGames(
@@ -0,0 +1,162 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.SteamLiveShortcuts
import java.io.File
import java.nio.file.Files
import java.nio.file.StandardCopyOption
object SteamLaunchOptions {
private const val TAG = "SteamLaunchOptions"
private val STEAM = listOf("UserLocalConfigStore", "Software", "Valve", "Steam")
fun current(context: Context, appId: Int): String =
SteamLiveShortcuts.launchOptions(context, appId.toLong()) ?: steam(SessionPrefs.activeSteamRoot(context), appId).orEmpty()
enum class Saved { YES, NO, DESKTOP }
fun set(context: Context, appId: Int, options: String, shown: String): Saved {
val value = options.trim()
if (SessionState.running && SessionState.mode == SessionService.MODE_DESKTOP) return Saved.DESKTOP
if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) {
val live = SteamLiveShortcuts.launchOptions(context, appId.toLong()) ?: return Saved.NO
if (live.trim() != shown.trim()) return Saved.NO
return if (SteamLiveShortcuts.setLaunchOptions(context, appId.toLong(), value)) Saved.YES else Saved.NO
}
val home = SessionPrefs.activeSteamRoot(context)
if (steam(home, appId).orEmpty().trim() != shown.trim()) return Saved.NO
return if (write(home, appId, value)) Saved.YES else Saved.NO
}
internal fun steam(steamHome: File, appId: Int): String? {
val config = AddedGames.accountConfig(steamHome) ?: return null
val text = runCatching { File(config, "localconfig.vdf").readText() }.getOrNull() ?: return null
return launchOptions(text, appId)
}
internal fun write(steamHome: File, appId: Int, options: String): Boolean {
val config = AddedGames.accountConfig(steamHome)?.let { File(it, "localconfig.vdf") } ?: return false
val text = runCatching { config.readText() }.getOrNull() ?: return false
val updated = withLaunchOptions(text, appId, options) ?: return false
if (updated == text) return true
val staged = File(config.parentFile, config.name + ".staged")
return try {
staged.writeText(updated)
if (config.readText() != text) {
staged.delete()
return false
}
Files.move(staged.toPath(), config.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
true
} catch (e: Exception) {
staged.delete()
Log.w(TAG, "could not write launch options to ${config.path}", e)
false
}
}
internal fun launchOptions(text: String, appId: Int): String? {
val app = section(text, STEAM + "apps" + appId.toString()) ?: return null
return entries(text, app.valueStart, app.end).firstOrNull { !it.section && it.key.equals("LaunchOptions", true) }
?.let { unescape(text.substring(it.valueStart + 1, it.end)) }
}
internal fun withLaunchOptions(text: String, appId: Int, options: String): String? {
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
var updated = text
var path = STEAM
for (key in listOf("apps", appId.toString())) {
updated = withSection(updated, section(updated, path) ?: return null, key, newline) ?: return null
path = path + key
}
val app = section(updated, path) ?: return null
val value = "\"" + escape(options) + "\""
entries(updated, app.valueStart, app.end).firstOrNull { !it.section && it.key.equals("LaunchOptions", true) }?.let {
return updated.replaceRange(it.valueStart, it.end + 1, value)
}
val lineStart = closingLine(updated, app) ?: return null
val indent = updated.substring(lineStart, app.end) + "\t"
return updated.substring(0, lineStart) + indent + "\"LaunchOptions\"\t\t" + value + newline + updated.substring(lineStart)
}
private class Entry(val key: String, val valueStart: Int, val end: Int, val section: Boolean)
private fun section(text: String, path: List<String>): Entry? {
var found: Entry? = null
for (key in path) {
found = entries(text, found?.valueStart ?: -1, found?.end ?: text.length)
.firstOrNull { it.section && it.key.equals(key, true) } ?: return null
}
return found
}
private fun entries(text: String, open: Int, close: Int): List<Entry> {
val found = ArrayList<Entry>()
var key: String? = null
var i = open + 1
while (i < close) {
when {
text[i] == '"' -> {
val end = stringEnd(text, i) ?: return found
if (key == null) key = unescape(text.substring(i + 1, end)) else { found += Entry(key, i, end, false); key = null }
i = end + 1
}
text[i] == '{' -> {
val end = sectionEnd(text, i) ?: return found
key?.let { found += Entry(it, i, end, true) }
key = null
i = end + 1
}
text.startsWith("//", i) -> i = text.indexOf('\n', i).let { if (it < 0) close else it }
else -> i++
}
}
return found
}
private fun stringEnd(text: String, open: Int): Int? {
var i = open + 1
while (i < text.length) {
when (text[i]) {
'\\' -> i += 2
'"' -> return i
else -> i++
}
}
return null
}
private fun sectionEnd(text: String, open: Int): Int? {
var depth = 0
var i = open
while (i < text.length) {
when (text[i]) {
'"' -> i = stringEnd(text, i) ?: return null
'{' -> depth++
'}' -> if (--depth == 0) return i
}
i++
}
return null
}
private fun withSection(text: String, parent: Entry, key: String, newline: String): String? {
if (entries(text, parent.valueStart, parent.end).any { it.section && it.key.equals(key, true) }) return text
val lineStart = closingLine(text, parent) ?: return null
val indent = text.substring(lineStart, parent.end) + "\t"
return text.substring(0, lineStart) + "$indent\"$key\"$newline$indent{$newline$indent}$newline" + text.substring(lineStart)
}
private fun closingLine(text: String, section: Entry): Int? {
val lineStart = text.lastIndexOf('\n', section.end - 1) + 1
return lineStart.takeIf { lineStart > section.valueStart && text.substring(lineStart, section.end).all { it == '\t' || it == ' ' } }
}
private fun escape(value: String) = value.replace("\\", "\\\\").replace("\"", "\\\"")
private fun unescape(value: String) = value.replace(Regex("\\\\(.)"), "$1")
}
@@ -45,15 +45,15 @@ object SteamMatch {
identity?.appId?.let { id ->
return Match(id, Certainty.FILES, identity.source.name.lowercase(), now).also { put(context, key, it) }
}
val known = get(context, key)
val known = get(context, key)?.takeUnless { it.appId == GameIdentifier.SPACEWAR }
if (known != null && known.certainty == Certainty.NAME) return known
if (known != null && known.certainty == Certainty.NONE && now - known.checkedAt < RETRY_AFTER_MS) return known
legacy?.takeIf { it.isFile }?.let { runCatching { it.readText().trim().toInt() }.getOrNull() }?.takeIf { it > 0 }?.let { id ->
legacy?.takeIf { it.isFile }?.let { runCatching { it.readText().trim().toInt() }.getOrNull() }?.takeIf { it > 0 && it != GameIdentifier.SPACEWAR }?.let { id ->
return Match(id, Certainty.NAME, "store search", now).also { put(context, key, it) }
}
if (search == null) return known?.takeIf { it.certainty != Certainty.FILES } ?: Match(null, Certainty.NONE, "", 0)
val id = runCatching { search(name) }.getOrNull()
val match = if (id != null && id > 0) Match(id, Certainty.NAME, "store search", now) else Match(null, Certainty.NONE, "", now)
val match = if (id != null && id > 0 && id != GameIdentifier.SPACEWAR) Match(id, Certainty.NAME, "store search", now) else Match(null, Certainty.NONE, "", now)
put(context, key, match)
return match
}
@@ -46,6 +46,9 @@ class DroidDeckHudHost(context: Context) {
var onPresentingWindowChanged: (() -> Unit)? = null
/** The frame rate the HUD shows; null while the HUD is off and not counting frames. */
val liveFps: Float? get() = if (polling) feed.stats.fps else null
/** The HUD itself changed a setting: a tap cycles the size, a long press locks it. */
var onConfigChanged: (() -> Unit)? = null
@@ -91,7 +94,7 @@ class DroidDeckHudHost(context: Context) {
hud.onRefresh = Runnable { refreshLabels(hud) }
hud.setOnMovedListener { x, y ->
wantX = x; wantY = y
dockEdgeFor(hud)?.let { edge -> setDock(hud, edge); return@setOnMovedListener }
if (!hud.isStrip) dockEdgeFor(hud)?.let { edge -> setDock(hud, edge); return@setOnMovedListener }
keepOnScreen(hud)
wantX = hud.x; wantY = hud.y
SessionPrefs.setDroidDeckHudPosition(context, hud.x, hud.y)
@@ -335,6 +338,7 @@ class DroidDeckHudHost(context: Context) {
val maxY = (p.height - v.height).toFloat().coerceAtLeast(0f)
var x = wantX.coerceIn(0f, maxX)
var y = wantY.coerceIn(0f, maxY)
if ((v as? DroidDeckHudView)?.isStrip == true) y = if (y + v.height / 2f < p.height / 2f) 0f else maxY
when (v.let { it as? DroidDeckHudView }?.dock) {
DroidDeckHudDock.LEFT -> x = 0f
DroidDeckHudDock.RIGHT -> x = maxX
@@ -23,9 +23,10 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
TILES("tiles", "Tiles"),
PILL("pill", "Pill"),
MINIMAL("minimal", "Minimal"),
MEGA("mega", "Mega");
MEGA("mega", "Mega"),
STRIP("strip", "Strip");
/** Next size in the tap-cycle: Full → Tiles → Pill → Minimal → Mega → Full. */
/** Next size in the tap-cycle: Full → Tiles → Pill → Minimal → Mega → Strip → Full. */
fun next(): DroidDeckHudSize {
val all = values()
return all[(ordinal + 1) % all.size]
@@ -40,7 +41,7 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
fun supportedChips(): Set<String> = when (this) {
MINIMAL -> MINIMAL_CHIPS
PILL -> PILL_CHIPS
FULL, TILES -> STANDARD_CHIPS
FULL, TILES, STRIP -> STANDARD_CHIPS
MEGA -> MEGA_CHIPS
}
@@ -22,12 +22,16 @@ import android.graphics.Paint
import android.graphics.Path
import android.graphics.RectF
import android.graphics.Typeface
import android.os.SystemClock
import android.text.format.DateFormat
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import androidx.annotation.VisibleForTesting
import androidx.compose.ui.graphics.toArgb
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.ui.Motion
import com.droiddeck.launcher.ui.Palette
import com.droiddeck.launcher.ui.Themes
import java.util.Date
import java.util.Locale
@@ -43,6 +47,7 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@@ -75,6 +80,7 @@ class DroidDeckHudView(context: Context) : View(context) {
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)
private var updateJob: Job? = null
private var hueJob: Job? = null
private val metrics = HudMetrics(context)
private val density = resources.displayMetrics.density
@@ -152,6 +158,8 @@ class DroidDeckHudView(context: Context) : View(context) {
var dock = DroidDeckHudDock.NONE
private set
private var tabRect: RectF? = null
// The Strip is a bar across the whole screen, kept against the top or bottom edge.
private var stripRect: RectF? = null
private val tabPath = Path()
// Every size sits in the DroidDeck mark's D: a straight left side, round on the
@@ -368,9 +376,11 @@ class DroidDeckHudView(context: Context) : View(context) {
private fun stopUpdates() {
updateJob?.cancel(); updateJob = null
hueJob?.cancel(); hueJob = null
}
private fun startUpdates() {
startHueCycle()
if (updateJob?.isActive == true) return
updateJob = scope.launch {
while (isActive) {
@@ -397,13 +407,50 @@ class DroidDeckHudView(context: Context) : View(context) {
var onRefresh: Runnable? = null
private fun applyTheme() {
val palette = Themes.current(context)
applyPalette(Themes.current(context))
if (isAttachedToWindow && isShown) startHueCycle()
}
private fun applyPalette(palette: Palette) {
accent = palette.primary.toArgb()
surfaceRgb = palette.surface.toArgb() and 0xFFFFFF
colFps = accent
colGraph = lighten(accent, 0.3f)
}
/**
* Inner Gamer turns the colour wheel inside the app's Compose UI, which is not running while the drawer is
* closed, so the HUD turns it here and shares the hue so the drawer picks up where the HUD is.
*/
private fun startHueCycle() {
if (hueJob?.isActive == true) return
if (SessionPrefs.theme(context) != Themes.INNER_GAMER) return
hueJob = scope.launch {
var hue = Themes.rgbHue
var shown = Float.NaN
var last = SystemClock.uptimeMillis()
while (isActive && SessionPrefs.theme(context) == Themes.INNER_GAMER) {
val now = SystemClock.uptimeMillis()
val cycle = Themes.rgbCycleMillis(Themes.rgbSpeed).toFloat()
if (Motion.scale == 0f) {
last = now
delay(HUE_IDLE_MS)
continue
}
hue = (hue + (now - last) / cycle * 360f) % 360f
last = now
val stepped = (hue / Themes.RGB_HUE_STEP).toInt() * Themes.RGB_HUE_STEP
if (stepped != shown) {
shown = stepped
Themes.moveRgbHue(stepped)
applyPalette(Themes.innerGamer(stepped))
rebuildAndInvalidate()
}
delay((cycle * Themes.RGB_HUE_STEP / 360f).toLong().coerceAtLeast(16L))
}
}
}
private fun lighten(color: Int, amount: Float): Int = Color.rgb(
(Color.red(color) + (255 - Color.red(color)) * amount).roundToInt(),
(Color.green(color) + (255 - Color.green(color)) * amount).roundToInt(),
@@ -534,7 +581,7 @@ class DroidDeckHudView(context: Context) : View(context) {
// ---- Layout builders --------------------------------------------------
private fun rebuild() {
glyphs.clear(); tileRects.clear(); graphRect = null
headerMark = null; chipRect = null; dPanel = null; dDividerTop = -1f; tabRect = null
headerMark = null; chipRect = null; dPanel = null; dDividerTop = -1f; tabRect = null; stripRect = null
val s = snap
if (s == null) { contentW = 0f; contentH = 0f; return }
if (dock != DroidDeckHudDock.NONE) { buildDockTab(); return }
@@ -544,6 +591,7 @@ class DroidDeckHudView(context: Context) : View(context) {
DroidDeckHudSize.PILL -> { buildPill(s); intoPanel(sp(10f), header = false) }
DroidDeckHudSize.MINIMAL -> buildMinimal(s)
DroidDeckHudSize.MEGA -> { buildMega(s); intoPanel(sp(10f), header = true) }
DroidDeckHudSize.STRIP -> buildStrip(s)
}
}
@@ -1078,6 +1126,94 @@ class DroidDeckHudView(context: Context) : View(context) {
finishPanel(panel, halfRound = true)
}
/**
* Full's readouts on one line across the screen: the mark, the FPS, the graph, the lows, then GPU, CPU,
* memory, battery, display server and GPU model, with the clock on the right end. Groups that no longer
* fit before the clock are left off, from the end.
*/
private fun buildStrip(s: HudMetrics.Snapshot) {
val rowPx = sp(11.5f); val unitPx = rowPx * 0.8f; val fpsPx = sp(15f)
val padX = sp(10f); val groupGap = sp(13f)
val h = sp(26f)
val w = ((parent as? View)?.width?.takeIf { it > 0 } ?: resources.displayMetrics.widthPixels).toFloat()
val mid = h / 2f
val baseline = mid + capHeight(fpsPx) / 2f
val markH = sp(13f)
val markLeft = padX - DroidDeckMark.inkLeftFor(markH)
headerMark = RectF(markLeft, mid - markH / 2f, markLeft + DroidDeckMark.widthFor(markH), mid + markH / 2f)
var x = markLeft + DroidDeckMark.inkRightFor(markH) + sp(8f)
var right = w - padX
if (showClockTime) {
val t = clockTimeString()
right -= measure(t, rowPx)
glyphs.add(Glyph(right, baseline, t, blend(colDim), rowPx))
right -= groupGap
}
val generating = differs(fpsNow)
val fps = ArrayList<Span>()
if (apiLabel() != "FPS") fps += Span("${apiLabel()} ", colDim, rowPx)
fps += Span(fpsText(fpsNow), colValue, if (generating) fpsPx * 0.8f else fpsPx, glow = true)
fps += Span("fps", colDim, unitPx)
x = placeRun(x, baseline, fps) + groupGap
if (showGraph) {
val gw = sp(72f); val gh = h * 0.55f
if (x + gw <= right) {
graphRect = RectF(x, mid - gh / 2f, x + gw, mid + gh / 2f)
x += gw + groupGap
}
}
val groups = ArrayList<List<Span>>()
run {
val l = ArrayList<Span>()
l += Span("1% ", colDim, rowPx); l += Span(lowText(lows.low1Fps) ?: "—", colFps, rowPx)
l += Span(" 0.1% ", colDim, rowPx); l += Span(lowText(lows.low01Fps) ?: "—", colFps, rowPx)
if (showLow001) { l += Span(" 0.01% ", colDim, rowPx); l += Span(lowText(lows.low001Fps) ?: "—", colFps, rowPx) }
groups += l
}
if (showGPU || showGpuTemp) {
val l = arrayListOf(Span("GPU", colGpu, rowPx))
if (showGPU) l += Span(" ${s.gpuPercent ?: "—"}%", colGpu, rowPx)
if (showGpuTemp && s.gpuTempC != null) { l += Span(" ", colDim, rowPx); l += tempSpans(s.gpuTempC, HudMetrics.TempSensor.GPU, rowPx, unitPx) }
groups += l
}
if (showCPU || showCpuTemp) {
val l = arrayListOf(Span("CPU", colCpu, rowPx))
if (showCPU) l += Span(" ${s.cpuPercent ?: "—"}%", colCpu, rowPx)
if (showCpuTemp && s.cpuTempC != null) { l += Span(" ", colDim, rowPx); l += tempSpans(s.cpuTempC, HudMetrics.TempSensor.CPU, rowPx, unitPx) }
groups += l
}
if (showVram) s.vramText()?.let { groups += listOf(Span("VRAM $it", colVram, rowPx)) }
if (showRAM) groups += listOf(Span("RAM ${s.ramPercent.roundToInt()}%", colRam, rowPx))
if (showBattery || showPower || showBatteryTemp) {
val l = ArrayList<Span>()
fun part(spans: List<Span>) {
l += if (l.isEmpty()) Span("BAT ", colBat, rowPx) else Span(" ", colDim, rowPx)
l += spans
}
if (showBattery && s.battery.percent != null) part(listOf(Span("${s.battery.percent}%", colBat, rowPx)))
if (showBatteryTemp && s.battery.tempC != null)
part(tempSpans(s.battery.tempC, HudMetrics.TempSensor.BATTERY, rowPx, unitPx))
if (showPower && s.battery.watts > 0f) part(listOf(Span("${fmt1(s.battery.watts)}W", colDim, rowPx)))
if (l.isNotEmpty()) groups += l
}
if (displayServer.isNotBlank()) groups += listOf(Span(displayServer, colDisp, rowPx))
if (hdrState != DroidDeckHudHdr.NONE) groups += hdrLine(rowPx)
if (showGpuModel && gpuNameText().isNotBlank()) groups += gpuModelSpans(rowPx, colDim, compact = true)
for (g in groups) {
if (x + runWidth(g) > right) break
x = placeRun(x, baseline, g) + groupGap
}
stripRect = RectF(0f, 0f, w, h)
contentW = w; contentH = h
}
private fun capHeight(px: Float): Float {
measurePaint.textSize = px
measurePaint.getTextBounds("0", 0, 1, inkRect)
@@ -1267,6 +1403,8 @@ class DroidDeckHudView(context: Context) : View(context) {
// ---- Measure / draw ---------------------------------------------------
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
// The Strip spans the parent, past the side margin the floating sizes keep.
if (stripRect != null) { setMeasuredDimension(contentW.roundToInt(), resolveSize(contentH.roundToInt(), heightMeasureSpec)); return }
setMeasuredDimension(
resolveSize(contentW.roundToInt(), widthMeasureSpec),
resolveSize(contentH.roundToInt(), heightMeasureSpec),
@@ -1287,6 +1425,7 @@ class DroidDeckHudView(context: Context) : View(context) {
chipRect?.let { drawChip(canvas, it) }
tabRect?.let { drawTab(canvas, it) }
stripRect?.let { drawStrip(canvas, it) }
// Text
for (g in glyphs) {
@@ -1328,6 +1467,21 @@ class DroidDeckHudView(context: Context) : View(context) {
canvas.drawPath(graphPath, graphPaint)
}
/** The bar, with the accent line on the side that faces the game (under it at the top, over it at the bottom). */
private fun drawStrip(canvas: Canvas, rect: RectF) {
headerPaint.shader = null
headerPaint.color = panelColor()
canvas.drawRect(rect, headerPaint)
val stroke = outlineWidth()
if (stroke <= 0f) return
val line = max(stroke / 2f, density)
val p = parent as? View
val atBottom = p != null && p.height > 0 && y + height / 2f > p.height / 2f
headerPaint.color = withAlpha(outlineColor(), (110 + 145 * outlineIntensity).roundToInt().coerceAtMost(255))
if (atBottom) canvas.drawRect(rect.left, rect.top, rect.right, rect.top + line, headerPaint)
else canvas.drawRect(rect.left, rect.bottom - line, rect.right, rect.bottom, headerPaint)
}
private fun outlineWidth(): Float = if (outlineIntensity > 0f) outlineIntensity * sp(3.5f) else 0f
private fun outlineColor(): Int = if (outlineFollowAccent) accent else Color.rgb(200, 200, 200)
private fun panelColor(): Int = Color.argb((bgOpacity.coerceIn(0f, 1f) * 255f).roundToInt(),
@@ -1443,6 +1597,8 @@ class DroidDeckHudView(context: Context) : View(context) {
return lockController.onTouchEvent(event)
}
internal val isStrip: Boolean get() = stripRect != null
internal val contentWidth: Float get() = contentW
internal val contentHeight: Float get() = contentH
@@ -1450,6 +1606,7 @@ class DroidDeckHudView(context: Context) : View(context) {
private companion object {
const val REFRESH_MS = 500L
private const val HUE_IDLE_MS = 500L
const val MIN_SCALE = 0.5f
const val MAX_SCALE = 2f
const val GRAPH_CLIP_MS = 49.9f
@@ -11,6 +11,7 @@ class PointerGestures {
fun onScroll(dx: Float, dy: Float) {}
fun onScrollEnd() {}
fun onZoom(steps: Int) {}
fun onThreeFingerTap(): Boolean = false
}
companion object {
@@ -9,11 +9,22 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int) {
NONE("none", R.string.second_mode_none),
KEYBOARD_TRACKPAD("keyboard-trackpad", R.string.second_mode_keyboard_trackpad),
TERMINAL("terminal", R.string.second_mode_terminal),
DECK_CONTROLS("deck-controls", R.string.second_mode_deck_controls);
DECK_CONTROLS("deck-controls", R.string.second_mode_deck_controls),
DASHBOARD("dashboard", R.string.second_mode_dashboard);
companion object {
fun opening(remembered: String?, deckPad: Boolean): SecondScreenMode =
entries.firstOrNull { it != NONE && it.id == remembered && (it != DECK_CONTROLS || deckPad) } ?: if (deckPad) DECK_CONTROLS else KEYBOARD_TRACKPAD
fun opening(remembered: String?, deckPad: Boolean, dashboard: Boolean = false): SecondScreenMode {
entries.firstOrNull {
it != NONE && it.id == remembered && (it != DECK_CONTROLS || deckPad) && (it != DASHBOARD || dashboard)
}?.let { return it }
// No pick yet: the dashboard. A pick that can't open right now keeps the old fallback.
val picked = entries.any { it != NONE && it.id == remembered }
return when {
dashboard && !picked -> DASHBOARD
deckPad -> DECK_CONTROLS
else -> KEYBOARD_TRACKPAD
}
}
}
}
@@ -240,7 +240,8 @@ class TouchpadGestures(
}
if (desktop && scrolled && event.pointerCount == 2) listener.onScrollEnd()
if (fingers >= 3) {
if (event.pointerCount == 2 && secondWasTap && !scrolled && event.eventTime - downAt < TouchTiming.TAP_MS * 2)
if (event.pointerCount == 2 && secondWasTap && !scrolled && event.eventTime - downAt < TouchTiming.TAP_MS * 2 &&
!listener.onThreeFingerTap())
click(PointerGestures.BTN_MIDDLE)
if (event.pointerCount == 2) secondWasTap = false
} else if (twoFingers && secondWasTap && event.eventTime - secondDownAt < TouchTiming.TAP_MS && !scrolled) {
@@ -0,0 +1,65 @@
package com.droiddeck.launcher.session
import android.app.Notification
import android.content.Context
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import androidx.compose.runtime.mutableStateListOf
import androidx.core.app.NotificationManagerCompat
/** One notification for the bottom-screen list. Kept in memory only; never written to disk or logs. */
data class BottomNotification(val key: String, val app: String, val title: String, val text: String, val postedAt: Long)
/**
* Notifications from other apps for the bottom screen, so a message can be read without leaving the game.
* Works only after the user allows DroidDeck notification access in Android settings.
*/
object BottomNotifications {
val items = mutableStateListOf<BottomNotification>()
fun granted(context: Context): Boolean =
context.packageName in NotificationManagerCompat.getEnabledListenerPackages(context)
internal fun keep(own: String, pkg: String, ongoing: Boolean, groupSummary: Boolean, title: String, text: String): Boolean =
pkg != own && !ongoing && !groupSummary && (title.isNotBlank() || text.isNotBlank())
internal fun add(list: MutableList<BottomNotification>, item: BottomNotification) {
list.removeAll { it.key == item.key }
list.add(0, item)
while (list.size > MAX_ITEMS) list.removeAt(list.lastIndex)
}
fun clear() = items.clear()
internal fun post(context: Context, sbn: StatusBarNotification) {
val n = sbn.notification ?: return
val extras = n.extras
val title = extras?.getCharSequence(Notification.EXTRA_TITLE)?.toString().orEmpty()
val text = (extras?.getCharSequence(Notification.EXTRA_BIG_TEXT) ?: extras?.getCharSequence(Notification.EXTRA_TEXT))?.toString().orEmpty()
if (!keep(context.packageName, sbn.packageName, sbn.isOngoing, (n.flags and Notification.FLAG_GROUP_SUMMARY) != 0, title, text)) return
val app = runCatching {
val pm = context.packageManager
pm.getApplicationLabel(pm.getApplicationInfo(sbn.packageName, 0)).toString()
}.getOrDefault(sbn.packageName)
add(items, BottomNotification(sbn.key, app, title, text, sbn.postTime))
}
internal fun remove(key: String) {
items.removeAll { it.key == key }
}
private const val MAX_ITEMS = 30
}
class BottomNotificationListener : NotificationListenerService() {
override fun onListenerConnected() {
BottomNotifications.clear()
runCatching { activeNotifications }.getOrNull()?.sortedBy { it.postTime }?.forEach { BottomNotifications.post(this, it) }
}
override fun onNotificationPosted(sbn: StatusBarNotification) = BottomNotifications.post(this, sbn)
override fun onNotificationRemoved(sbn: StatusBarNotification) = BottomNotifications.remove(sbn.key)
override fun onListenerDisconnected() = BottomNotifications.clear()
}
@@ -0,0 +1,97 @@
package com.droiddeck.launcher.session
import android.content.ContentValues
import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
/** A screenshot for the bottom-screen gallery: one DroidDeck took (a MediaStore [uri]) or one Steam saved (a [file]). */
data class BottomShot(val uri: Uri?, val file: File?, val takenAt: Long, val steam: Boolean) {
val model: Any get() = uri ?: file!!
}
/** Game frames DroidDeck saves to Pictures/DroidDeck, plus the screenshots Steam keeps under userdata. */
object BottomScreenshots {
private const val FOLDER = "DroidDeck"
private const val QUALITY = 95
private const val LIMIT = 120
internal fun fileName(at: Long): String =
"DroidDeck_" + SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date(at)) + ".jpg"
fun save(context: Context, bitmap: Bitmap, at: Long = System.currentTimeMillis()): Boolean = runCatching {
val name = fileName(at)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val resolver = context.contentResolver
val values = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, name)
put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
put(MediaStore.Images.Media.DATE_TAKEN, at)
put(MediaStore.Images.Media.RELATIVE_PATH, "${Environment.DIRECTORY_PICTURES}/$FOLDER")
put(MediaStore.Images.Media.IS_PENDING, 1)
}
val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) ?: return false
val written = runCatching {
resolver.openOutputStream(uri)?.use { bitmap.compress(Bitmap.CompressFormat.JPEG, QUALITY, it) } == true
}.getOrDefault(false)
if (!written) {
resolver.delete(uri, null, null)
return false
}
resolver.update(uri, ContentValues().apply { put(MediaStore.Images.Media.IS_PENDING, 0) }, null, null)
true
} else {
@Suppress("DEPRECATION")
val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), FOLDER)
if (!dir.isDirectory && !dir.mkdirs()) return false
val file = File(dir, name)
file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.JPEG, QUALITY, it) }
android.media.MediaScannerConnection.scanFile(context, arrayOf(file.path), arrayOf("image/jpeg"), null)
true
}
}.getOrDefault(false)
/** Newest first, at most [LIMIT]. */
fun list(context: Context, runtimeRoot: File): List<BottomShot> =
(own(context) + steam(runtimeRoot)).sortedByDescending { it.takenAt }.take(LIMIT)
private fun own(context: Context): List<BottomShot> = runCatching {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
@Suppress("DEPRECATION")
val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), FOLDER)
return dir.listFiles { f -> f.isFile && f.name.endsWith(".jpg", true) }.orEmpty()
.map { BottomShot(null, it, it.lastModified(), steam = false) }
}
val shots = ArrayList<BottomShot>()
context.contentResolver.query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.DATE_TAKEN, MediaStore.Images.Media.DATE_ADDED),
"${MediaStore.Images.Media.RELATIVE_PATH} = ?", arrayOf("${Environment.DIRECTORY_PICTURES}/$FOLDER/"),
"${MediaStore.Images.Media.DATE_ADDED} DESC",
)?.use { c ->
while (c.moveToNext() && shots.size < LIMIT) {
val taken = c.getLong(1).takeIf { it > 0L } ?: (c.getLong(2) * 1000L)
shots += BottomShot(android.content.ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, c.getLong(0)),
null, taken, steam = false)
}
}
shots
}.getOrDefault(emptyList())
/** The .jpg files in userdata/<account>/760/remote/<app>/screenshots of each Steam home; the thumbnails folder is skipped. */
internal fun steam(runtimeRoot: File): List<BottomShot> =
SteamDownloadMonitor.STEAM_HOMES.flatMap { home ->
File(runtimeRoot, "$home/userdata").listFiles { f -> f.isDirectory }.orEmpty().flatMap { account ->
File(account, "760/remote").listFiles { f -> f.isDirectory }.orEmpty().flatMap { app ->
File(app, "screenshots").listFiles { f -> f.isFile && f.name.endsWith(".jpg", true) }.orEmpty().toList()
}
}
}.map { BottomShot(null, it, it.lastModified(), steam = true) }
}
@@ -0,0 +1,232 @@
package com.droiddeck.launcher.session
import java.nio.ByteBuffer
import java.nio.ByteOrder
/** One reading from a racing game's telemetry. Fractions are 0..1; null means the game does not send it. */
data class Telemetry(
val source: String,
val speedKmh: Float? = null,
val rpm: Float? = null,
val maxRpm: Float? = null,
val gear: String? = null,
val throttle: Float? = null,
val brake: Float? = null,
val lap: Int? = null,
val laps: Int? = null,
val position: Int? = null,
val fuel: Float? = null,
val currentLapS: Float? = null,
val lastLapS: Float? = null,
val bestLapS: Float? = null,
/** G-force as the game sends it (lateral, longitudinal) and steering from -1 (left) to 1 (right). */
val gLat: Float? = null,
val gLon: Float? = null,
val steer: Float? = null,
/** Front left, front right, rear left, rear right. */
val tireTempsC: List<Float>? = null,
val turboBar: Float? = null,
val engineTempC: Float? = null,
val oilTempC: Float? = null,
/** OutGauge dashboard lights that are on, as GameTelemetry.DL_* bits. */
val lights: Int? = null,
)
/**
* Racing telemetry games send over UDP to 127.0.0.1. Each format has its own port, the one the game or
* its common tools use by default:
* - [CODEMASTERS_PORT]: DiRT Rally 1/2, DiRT 4, GRID ("extradata 3" float array), DiRT Showdown (152-byte packet).
* - [FORZA_PORT]: Forza Motorsport 7/2023 and Forza Horizon 4/5 "Data Out" (Sled and Dash).
* - [OUTGAUGE_PORT]: BeamNG.drive and Live for Speed OutGauge.
*/
object GameTelemetry {
const val CODEMASTERS_PORT = 20777
const val FORZA_PORT = 5300
const val OUTGAUGE_PORT = 4444
val PORTS = listOf(CODEMASTERS_PORT, FORZA_PORT, OUTGAUGE_PORT)
// Games send to 127.0.0.1; on Android InetAddress.getLoopbackAddress() is ::1, which IPv4 packets never reach.
val LISTEN_ADDRESS: java.net.InetAddress = java.net.InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1))
fun parse(port: Int, data: ByteArray, length: Int): Telemetry? = runCatching {
val buf = ByteBuffer.wrap(data, 0, length).order(ByteOrder.LITTLE_ENDIAN)
when (port) {
CODEMASTERS_PORT -> codemasters(buf, length)
FORZA_PORT -> forza(buf, length)
OUTGAUGE_PORT -> outGauge(buf, length)
else -> null
}
}.getOrNull()
private const val MPS_TO_KMH = 3.6f
private const val GRAVITY = 9.81f
// OutGauge DashLights / ShowLights bits (Live for Speed InSim; BeamNG uses the same values).
const val DL_SHIFT = 1
const val DL_HANDBRAKE = 4
const val DL_PITSPEED = 8
const val DL_TC = 16
const val DL_ABS = 1024
// Float indexes of the Codemasters packet; engine rpm values are sent divided by 10. Older games
// (DiRT Showdown) send only the first 38 floats, so lap count, position, fuel and max rpm are missing there.
private const val CM_LAP_TIME = 1
private const val CM_SPEED = 7
private const val CM_THROTTLE = 29
private const val CM_STEER = 30
private const val CM_BRAKE = 31
private const val CM_GEAR = 33
private const val CM_G_LAT = 34
private const val CM_G_LON = 35
private const val CM_LAP = 36
private const val CM_RPM = 37
private const val CM_POSITION = 39
private const val CM_FUEL = 45
private const val CM_FUEL_CAPACITY = 46
private const val CM_LAPS = 60
private const val CM_LAST_LAP = 62
private const val CM_MAX_RPM = 63
private const val CM_MIN_FLOATS = 38
internal fun codemasters(buf: ByteBuffer, length: Int): Telemetry? {
if (length < CM_MIN_FLOATS * 4) return null
val floats = length / 4
fun f(i: Int) = if (i < floats) buf.getFloat(i * 4) else 0f
val gear = f(CM_GEAR).toInt()
val capacity = f(CM_FUEL_CAPACITY)
return Telemetry(
source = "Codemasters",
speedKmh = f(CM_SPEED) * MPS_TO_KMH,
rpm = f(CM_RPM) * 10f,
maxRpm = (f(CM_MAX_RPM) * 10f).takeIf { it > 0f },
// Neutral is 0; DiRT Rally 2.0 reports reverse as 10, older games as -1.
gear = when {
gear == 0 -> "N"
gear < 0 || gear == 10 -> "R"
else -> gear.toString()
},
throttle = f(CM_THROTTLE).coerceIn(0f, 1f),
brake = f(CM_BRAKE).coerceIn(0f, 1f),
lap = f(CM_LAP).toInt() + 1,
laps = f(CM_LAPS).toInt().takeIf { it > 0 },
position = f(CM_POSITION).toInt().takeIf { it > 0 },
fuel = if (capacity > 0f) (f(CM_FUEL) / capacity).coerceIn(0f, 1f) else null,
currentLapS = f(CM_LAP_TIME).takeIf { it > 0f },
lastLapS = f(CM_LAST_LAP).takeIf { it > 0f },
gLat = f(CM_G_LAT),
gLon = f(CM_G_LON),
steer = f(CM_STEER).coerceIn(-1f, 1f),
)
}
// Forza "Data Out": Sled is 232 bytes; the Dash block follows it (FM7 311, FM 2023 331). Horizon 4/5 send
// 324 bytes with 12 extra bytes before the Dash block.
private const val FORZA_SLED = 232
private const val FORZA_FM7 = 311
private const val FORZA_HORIZON = 324
private const val FORZA_FM2023 = 331
private const val HORIZON_SHIFT = 12
internal fun forza(buf: ByteBuffer, length: Int): Telemetry? {
if (length < FORZA_SLED) return null
val racing = buf.getInt(0) != 0
val maxRpm = buf.getFloat(8)
val rpm = buf.getFloat(16)
val dash = when (length) {
FORZA_FM7, FORZA_FM2023 -> FORZA_SLED
FORZA_HORIZON -> FORZA_SLED + HORIZON_SHIFT
else -> -1
}
if (dash < 0) return Telemetry(source = "Forza", rpm = rpm, maxRpm = maxRpm.takeIf { it > 0f })
if (!racing) return Telemetry(source = "Forza")
val gear = buf.get(dash + 75).toInt() and 0xFF
// Tire temperatures are read as Fahrenheit, as community Data Out parsers do; not checked on a device.
val tiresF = (0 until 4).map { buf.getFloat(dash + 24 + it * 4) }
return Telemetry(
source = "Forza",
speedKmh = buf.getFloat(dash + 12) * MPS_TO_KMH,
rpm = rpm,
maxRpm = maxRpm.takeIf { it > 0f },
gear = if (gear == 0) "R" else gear.toString(),
throttle = (buf.get(dash + 71).toInt() and 0xFF) / 255f,
brake = (buf.get(dash + 72).toInt() and 0xFF) / 255f,
lap = (buf.getShort(dash + 68).toInt() and 0xFFFF) + 1,
position = (buf.get(dash + 70).toInt() and 0xFF).takeIf { it > 0 },
fuel = buf.getFloat(dash + 44).coerceIn(0f, 1f),
currentLapS = buf.getFloat(dash + 60).takeIf { it > 0f },
lastLapS = buf.getFloat(dash + 56).takeIf { it > 0f },
bestLapS = buf.getFloat(dash + 52).takeIf { it > 0f },
gLat = buf.getFloat(20) / GRAVITY,
gLon = buf.getFloat(28) / GRAVITY,
steer = (buf.get(dash + 76).toFloat() / 127f).coerceIn(-1f, 1f),
tireTempsC = tiresF.takeIf { f -> f.any { it > 0f } }?.map { (it - 32f) * 5f / 9f },
)
}
// OutGauge: 92 bytes, or 96 with the optional id at the end.
private const val OUTGAUGE_SIZE = 92
internal fun outGauge(buf: ByteBuffer, length: Int): Telemetry? {
if (length < OUTGAUGE_SIZE) return null
val gear = buf.get(10).toInt() and 0xFF
return Telemetry(
source = "OutGauge",
speedKmh = buf.getFloat(12) * MPS_TO_KMH,
rpm = buf.getFloat(16),
gear = when (gear) {
0 -> "R"
1 -> "N"
else -> (gear - 1).toString()
},
throttle = buf.getFloat(48).coerceIn(0f, 1f),
brake = buf.getFloat(52).coerceIn(0f, 1f),
fuel = buf.getFloat(28).coerceIn(0f, 1f),
turboBar = buf.getFloat(20).takeIf { it != 0f },
engineTempC = buf.getFloat(24).takeIf { it != 0f },
oilTempC = buf.getFloat(36).takeIf { it != 0f },
lights = buf.getInt(44).takeIf { buf.getInt(40) != 0 },
)
}
}
/** Games that publish their state locally without any setup: War Thunder's web page and Elite Dangerous' Status.json. */
object GameStatusFiles {
const val WAR_THUNDER_STATE = "http://127.0.0.1:8111/state"
private const val ELITE_APP = "359320"
private const val ELITE_STATUS = "pfx/drive_c/users/steamuser/Saved Games/Frontier Developments/Elite Dangerous/Status.json"
const val WAR_THUNDER_ROWS = 12
/** War Thunder's own labels (for example "TAS, km/h") with their values, while a match runs. */
internal fun warThunder(json: String): List<Pair<String, String>> {
val state = org.json.JSONObject(json)
if (!state.optBoolean("valid", false)) return emptyList()
return state.keys().asSequence().filter { it != "valid" }.mapNotNull { key ->
val value = state.opt(key) as? Number ?: return@mapNotNull null
key to if (value.toDouble() % 1.0 == 0.0) value.toLong().toString() else "%.1f".format(java.util.Locale.US, value.toDouble())
}.toList()
}
fun eliteStatusFile(runtimeRoot: java.io.File, mounts: Map<String, java.io.File>): java.io.File? {
val libraries = SteamDownloadMonitor.manifests(runtimeRoot, mounts).mapNotNull { it.parentFile } +
SteamDownloadMonitor.STEAM_HOMES.map { java.io.File(runtimeRoot, "$it/steamapps") }
return libraries.distinct().map { java.io.File(it, "compatdata/$ELITE_APP/$ELITE_STATUS") }.firstOrNull { it.isFile }
}
data class Elite(val fuelMain: Double?, val fuelReserve: Double?, val cargo: Double?, val pips: List<Int>?, val legal: String?, val balance: Long?)
/** Null while Elite is at its menus (Status.json then carries only the timestamp and flags). */
internal fun elite(json: String): Elite? {
val s = org.json.JSONObject(json)
val fuel = s.optJSONObject("Fuel")
val pips = s.optJSONArray("Pips")?.let { a -> (0 until a.length()).map { a.optInt(it) } }
if (fuel == null && pips == null && !s.has("Cargo") && !s.has("Balance")) return null
return Elite(
fuelMain = fuel?.optDouble("FuelMain")?.takeIf { !it.isNaN() },
fuelReserve = fuel?.optDouble("FuelReservoir")?.takeIf { !it.isNaN() },
cargo = s.optDouble("Cargo").takeIf { !it.isNaN() },
pips = pips,
legal = s.optString("LegalState").takeIf { it.isNotEmpty() },
balance = if (s.has("Balance")) s.optLong("Balance") else null,
)
}
}
@@ -173,6 +173,7 @@ object SessionFiles {
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
"usr/local/lib/droiddeck-dirt/ws2_32.dll" to "usr/local/lib/droiddeck-dirt/ws2_32.dll",
) + mangoapp + msitools.map { it to it } + vr + fexPreloads).filter { (asset, _) ->
val dir = asset.substringBeforeLast('/')
runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false)
@@ -100,6 +100,38 @@ object SessionPrefs {
prefs(context).edit().putString("secondScreenPanel", mode).apply()
}
fun statsStrip(context: Context): String? = prefs(context).getString("statsStrip", null)
fun setStatsStrip(context: Context, id: String) {
prefs(context).edit().putString("statsStrip", id).apply()
}
fun statsSpeedUnit(context: Context): String? = prefs(context).getString("statsSpeedUnit", null)
fun setStatsSpeedUnit(context: Context, id: String) {
prefs(context).edit().putString("statsSpeedUnit", id).apply()
}
fun statsDash(context: Context): String? = prefs(context).getString("statsDash", null)
fun setStatsDash(context: Context, id: String) {
prefs(context).edit().putString("statsDash", id).apply()
}
/** In-game stats "Send dashboard data" Automatic: on unless the user switched it off. */
fun telemetryAuto(context: Context): Boolean = prefs(context).getBoolean("telemetryAuto", true)
fun setTelemetryAuto(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("telemetryAuto", on).apply()
}
/** Games the user switched off by hand, as TelemetryOutput keys; Automatic leaves them alone. */
fun telemetryOff(context: Context): Set<String> = prefs(context).getStringSet("telemetryOff", null)?.toSet().orEmpty()
fun setTelemetryOff(context: Context, keys: Set<String>) {
prefs(context).edit().putStringSet("telemetryOff", keys.toSet()).apply()
}
fun dualScreenLauncher(context: Context): Boolean = prefs(context).getBoolean("dualScreenLauncher", true)
fun setDualScreenLauncher(context: Context, on: Boolean) {
@@ -1133,7 +1165,7 @@ object SessionPrefs {
/** The drawer's frame limit slider: its first stop is Off. */
const val FPS_LIMIT_OFF = 15
const val FPS_LIMIT_MAX = 120
const val FPS_LIMIT_MAX = 165
/**
* Buffers go back to the game as soon as they are replaced instead of once per refresh;
@@ -73,7 +73,9 @@ class SessionService : Service() {
private var downloadMonitorTask: Runnable? = null
private var downloadActive = false
private var clientInstallActive = false
@Volatile private var steamLibraryMounts = emptyMap<String, File>()
private var steamLibraryMounts: Map<String, File>
get() = SessionState.steamLibraryMounts
set(value) { SessionState.steamLibraryMounts = value }
private var suspendDownloadNow = false
private var suspendPolicy = SessionPrefs.SUSPEND_MANUAL
private var steamDownloadsInBackground = false
@@ -728,6 +730,20 @@ class SessionService : Service() {
))
}
},
readBackAllowed = { SessionPrefs.ramCapMb(this) == 0 },
pagedIn = { processes, swapKb, swapBeforeKb, availableKb, millis ->
if (processes == 0) {
Log.i(TAG, "left ${swapBeforeKb / 1024} MB in zram after resume (RAM cap, or ${availableKb / 1024} MB available is too little)")
} else {
Log.i(TAG, "read back $processes processes in $millis ms: zram ${swapBeforeKb / 1024} -> ${swapKb / 1024} MB")
}
mainHandler.post {
SessionEvents.record("session.paged_in", mapOf(
"processes" to processes, "swapMb" to swapKb / 1024, "swapBeforeMb" to swapBeforeKb / 1024,
"availableMb" to availableKb / 1024, "ms" to millis,
))
}
},
)
updateDownloadMonitoring()
mainHandler.post { updateSuspendPolicy() }
@@ -94,6 +94,9 @@ object SessionState {
@Volatile var secondScreenAutoOpened = false
@Volatile var secondScreenProvisional = false
/** Guest library paths on removable storage and the host folders they are mounted from, set by SessionService. */
@Volatile var steamLibraryMounts: Map<String, java.io.File> = emptyMap()
@Volatile
var mode = "steam"
@@ -26,6 +26,11 @@ internal class SessionSuspendController(
private val nowNanos: () -> Long = System::nanoTime,
private val pagedOut: (processes: Int, unacknowledged: Int, residentKb: Long, swapKb: Long, swapBeforeKb: Long, millis: Long) -> Unit =
{ _, _, _, _, _, _ -> },
// False with a RAM cap set: the user asked for the session to use less memory, so nothing is read back.
private val readBackAllowed: () -> Boolean = { true },
// processes is 0 when the read-back was skipped: a RAM cap, or MemAvailable could not take it.
private val pagedIn: (processes: Int, swapKb: Long, swapBeforeKb: Long, availableKb: Long, millis: Long) -> Unit =
{ _, _, _, _, _ -> },
) {
private enum class Role { SESSION_ROOT, SESSION_CHILD, HELPER_ROOT, HELPER_CHILD }
@@ -49,6 +54,7 @@ internal class SessionSuspendController(
@Volatile private var cancelled = false
private var frozen = emptyList<ProcessRecord>()
private var frozenSince: Long? = null
private var pagedOutTargets = emptyList<ProcessRecord>()
fun freeze(pageOut: Boolean = false, completion: (Boolean) -> Unit) {
cancelled = false
@@ -107,6 +113,8 @@ internal class SessionSuspendController(
if (interrupted) Thread.currentThread().interrupt()
}
completion(complete)
// A cancelled or failed freeze leaves the game running with whatever the page-out already moved.
if (!complete && frozen.isEmpty() && !interrupted) readBack()
}, { completion(false) })
}
@@ -123,6 +131,7 @@ internal class SessionSuspendController(
val resumed = restoreSafely(records)
if (resumed) frozen = emptyList()
completion(resumed)
if (resumed) readBack()
}, { completion(false) })
}
@@ -289,6 +298,7 @@ internal class SessionSuspendController(
}
}
if (targets.isEmpty()) return
pagedOutTargets = (pagedOutTargets + targets).distinct()
val acks = targets.associateWith { File(control.parentFile, "${control.name}.ack.${it.pid}") }
acks.values.forEach { it.delete() }
val start = nowMillis()
@@ -309,6 +319,69 @@ internal class SessionSuspendController(
pagedOut(targets.size, unacknowledged, after.first, after.second, before.second, nowMillis() - start)
}
// Left in zram, the paged-out memory comes back one major fault at a time while the game runs; in a heavy
// game that is hundreds of faults per frame and stalls of a quarter second and more, long after the resume.
// libblsession's handler reads back only the swapped pages (mode 0, as the session script does for the client).
// The handler runs on whichever thread takes the signal, so that thread pauses for the read-back,
// once and right after the resume instead of mid-game.
// It signals even with nothing in zram yet: after a cancelled freeze a page-out handler may not have started,
// and it reads the mode only when it starts, so it reads back instead of paging out.
private fun readBack() {
val targets = pagedOutTargets.filterNot { isGone(it) }
pagedOutTargets = emptyList()
val control = zramControl?.takeIf { it.isFile } ?: return
if (targets.isEmpty() || closing) return
val before = memoryKb(targets).second
val (total, available) = meminfoKb()
if (!readBackAllowed() || !canTake(before, total, available)) {
pagedIn(0, before, before, available, 0)
return
}
try {
control.writeText("0")
} catch (_: IOException) {
return
}
val start = nowMillis()
for (record in targets) send(record, SIGURG)
var swap = before
var unchanged = 0
try {
while (!closing && nowMillis() - start < READ_BACK_TIMEOUT_MS) {
sleep(READ_BACK_POLL_MS)
val current = memoryKb(targets).second
unchanged = if (current == swap) unchanged + 1 else 0
swap = current
if (swap == 0L || unchanged >= READ_BACK_STABLE_POLLS) break
}
} catch (_: InterruptedException) {
Thread.currentThread().interrupt()
}
pagedIn(targets.size, swap, before, available, nowMillis() - start)
}
// Reading back moves the swap into resident memory, out of MemAvailable. On a device short on memory that
// could push Android's low-memory killer onto DroidDeck itself, so the memory comes back only when
// MemAvailable is at least twice the swap and keeps 1 GB or a tenth of MemTotal, whichever is more, after it.
// Otherwise it stays in zram and faults back in as the game touches it, as before.
private fun canTake(swapKb: Long, totalKb: Long, availableKb: Long): Boolean =
availableKb >= swapKb * READ_BACK_AVAILABLE_FACTOR &&
availableKb - swapKb >= maxOf(READ_BACK_HEADROOM_KB, totalKb / READ_BACK_TOTAL_SHARE)
// MemTotal and MemAvailable, 0 when unreadable (which skips the read-back).
private fun meminfoKb(): Pair<Long, Long> = try {
val values = HashMap<String, Long>()
File(procRoot, "meminfo").forEachLine { line ->
val name = line.substringBefore(':')
if (name == "MemTotal" || name == "MemAvailable") {
line.substringAfter(':').trim().substringBefore(' ').toLongOrNull()?.let { values[name] = it }
}
}
(values["MemTotal"] ?: 0L) to (values["MemAvailable"] ?: 0L)
} catch (_: IOException) {
0L to 0L
}
private fun isGone(record: ProcessRecord): Boolean =
try { readProcess(record.pid)?.started != record.started } catch (_: Exception) { false }
@@ -410,6 +483,12 @@ internal class SessionSuspendController(
const val PAGE_OUT_POLL_MS = 100L
const val PAGE_OUT_START_MS = 2_000L
const val PAGE_OUT_TIMEOUT_MS = 12_000L
const val READ_BACK_POLL_MS = 100L
const val READ_BACK_STABLE_POLLS = 5
const val READ_BACK_TIMEOUT_MS = 5_000L
const val READ_BACK_HEADROOM_KB = 1_048_576L
const val READ_BACK_AVAILABLE_FACTOR = 2L
const val READ_BACK_TOTAL_SHARE = 10L
const val RESTORE_CHECKS = 80
const val FREEZE_TIMEOUT_MS = 8_000L
const val FREEZE_MAX_PASSES = 256
@@ -26,7 +26,7 @@ object SettingsReset {
"upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias",
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds",
"bootMovieApplyNext", "bootMovieSteamSeen",
"questDefaultsV1",
"questDefaultsV1", "telemetryAuto", "telemetryOff", "statsStrip", "statsDash", "statsSpeedUnit",
)
internal val SESSION_PREFIXES = listOf(
@@ -0,0 +1,50 @@
package com.droiddeck.launcher.session
/** The In-game stats page's top strip, picked on the page (tap or the Layout row) and remembered. */
enum class StatsStrip(val id: String) {
PANEL("panel"), TILES("tiles"), RINGS("rings");
fun next(): StatsStrip = entries[(ordinal + 1) % entries.size]
companion object {
fun from(id: String?): StatsStrip = entries.firstOrNull { it.id == id } ?: PANEL
}
}
/** Speeds on the racing dashes; telemetry arrives in km/h. */
enum class SpeedUnit(val id: String, val label: String, val perKmh: Float) {
AUTO("auto", "", 1f), KMH("kmh", "km/h", 1f), MPH("mph", "mph", 0.621371f);
/** Auto is mph where road speed limits are signed in mph, by the device's region, else km/h. */
fun resolve(country: String): SpeedUnit = if (this != AUTO) this else if (country.uppercase() in MPH_REGIONS) MPH else KMH
fun next(): SpeedUnit = entries[(ordinal + 1) % entries.size]
companion object {
/** The United States and its territories, the United Kingdom and its Crown Dependencies, Liberia, the Bahamas, Belize. */
private val MPH_REGIONS = setOf("US", "PR", "GU", "VI", "AS", "MP", "GB", "IM", "JE", "GG", "LR", "BS", "BZ")
fun from(id: String?): SpeedUnit = entries.firstOrNull { it.id == id } ?: AUTO
}
}
/** The racing dash under the strip; Auto picks one by the game's data format. */
enum class StatsDash(val id: String) {
AUTO("auto"), SPEEDOMETER("speedometer"), CIRCUIT("circuit"), TRACE("trace"), DIALS("dials"), GLANCE("glance");
/** The dash to draw for data from [source] (Telemetry.source). */
fun resolve(source: String): StatsDash = if (this != AUTO) this else when (source) {
"Forza" -> CIRCUIT
"OutGauge" -> DIALS
else -> SPEEDOMETER
}
companion object {
private val DRAWN = listOf(SPEEDOMETER, CIRCUIT, TRACE, DIALS, GLANCE)
fun from(id: String?): StatsDash = entries.firstOrNull { it.id == id } ?: AUTO
/** A tap on the dash moves on from the one on screen, so Auto never looks like a tap did nothing. */
fun tapped(shown: StatsDash): StatsDash = DRAWN[(DRAWN.indexOf(shown) + 1).mod(DRAWN.size)]
}
}
@@ -101,34 +101,6 @@ internal class SteamDownloadMonitor {
now - lastContentActivityAt <= CONTENT_ACTIVITY_GRACE_MS
}
private fun manifests(runtimeRoot: File, mounts: Map<String, File>): List<File> {
val steamRoots = linkedSetOf<File>()
for (home in STEAM_HOMES) {
val primary = File(runtimeRoot, home)
steamRoots += primary
val libraryFolders = File(primary, "steamapps/libraryfolders.vdf")
runCatching {
PATH.findAll(libraryFolders.readText()).forEach { match ->
steamRoots += hostPath(runtimeRoot, match.groupValues[1], mounts)
}
}
}
return steamRoots.flatMap { root ->
File(root, "steamapps").listFiles { file ->
file.isFile && file.name.startsWith("appmanifest_") && file.name.endsWith(".acf")
}.orEmpty().toList()
}
}
private fun hostPath(runtimeRoot: File, guest: String, mounts: Map<String, File>): File {
val path = guest.trimEnd('/')
for ((mount, host) in mounts) {
if (path == mount) return host
if (path.startsWith("$mount/")) return File(host, path.removePrefix("$mount/"))
}
return File(runtimeRoot, path.removePrefix("/"))
}
private fun read(file: File): ManifestState {
val text = runCatching { file.readText() }.getOrDefault("")
val flags = value(text, "StateFlags")?.toLongOrNull() ?: 0L
@@ -137,9 +109,6 @@ internal class SteamDownloadMonitor {
return ManifestState(downloaded, flags != 4L && (total <= 0L || downloaded < total))
}
private fun value(text: String, key: String): String? =
Regex("\"$key\"\\s+\"([^\"]*)\"").find(text)?.groupValues?.get(1)
companion object {
fun clientInstallPending(runtimeRoot: File): Boolean {
val home = File(runtimeRoot, "root")
@@ -149,12 +118,43 @@ internal class SteamDownloadMonitor {
return !(stamped && File(steam, "steamrtarm64/steam").isFile) || File(home, ".bl-steam-repair").exists()
}
internal fun manifests(runtimeRoot: File, mounts: Map<String, File>): List<File> {
val steamRoots = linkedSetOf<File>()
for (home in STEAM_HOMES) {
val primary = File(runtimeRoot, home)
steamRoots += primary
val libraryFolders = File(primary, "steamapps/libraryfolders.vdf")
runCatching {
PATH.findAll(libraryFolders.readText()).forEach { match ->
steamRoots += hostPath(runtimeRoot, match.groupValues[1], mounts)
}
}
}
return steamRoots.flatMap { root ->
File(root, "steamapps").listFiles { file ->
file.isFile && file.name.startsWith("appmanifest_") && file.name.endsWith(".acf")
}.orEmpty().toList()
}
}
private fun hostPath(runtimeRoot: File, guest: String, mounts: Map<String, File>): File {
val path = guest.trimEnd('/')
for ((mount, host) in mounts) {
if (path == mount) return host
if (path.startsWith("$mount/")) return File(host, path.removePrefix("$mount/"))
}
return File(runtimeRoot, path.removePrefix("/"))
}
internal fun value(text: String, key: String): String? =
Regex("\"$key\"\\s+\"([^\"]*)\"").find(text)?.groupValues?.get(1)
private const val MANIFEST_PROGRESS_GRACE_MS = 8_000L
private const val CONTENT_ACTIVITY_GRACE_MS = 90_000L
private const val MIN_RECEIVE_BYTES_PER_SEC = 64L * 1024L
private val PATH = Regex("\"path\"\\s+\"([^\"]+)\"")
private val STEAM_HOMES = listOf("root/.local/share/Steam", "root/.droiddeck-x64/.local/share/Steam")
private val CONTENT_UPDATE = Regex("""AppID (\d+) (App|Workshop|Shader) update changed : (.*)""")
internal val STEAM_HOMES = listOf("root/.local/share/Steam", "root/.droiddeck-x64/.local/share/Steam")
internal val CONTENT_UPDATE = Regex("""AppID (\d+) (App|Workshop|Shader) update changed : (.*)""")
private val CURRENT_RATE = Regex("""Current download rate: ([\d.]+) Mbps""")
}
}
@@ -0,0 +1,76 @@
package com.droiddeck.launcher.session
import java.io.File
import java.io.RandomAccessFile
/** A Steam download or update the client is working on. [total] is 0 while Steam has not sized it yet. */
data class SteamDownload(
val appId: String,
val name: String,
val done: Long,
val total: Long,
val shader: Boolean = false,
val paused: Boolean = false,
)
/** Reads Steam's own appmanifests and content log, the same files [SteamDownloadMonitor] watches. */
object SteamDownloads {
fun read(runtimeRoot: File, mounts: Map<String, File> = emptyMap(), client: String? = null): List<SteamDownload> {
val names = HashMap<String, String>()
val apps = SteamDownloadMonitor.manifests(runtimeRoot, mounts).mapNotNull { file ->
val text = runCatching { file.readText() }.getOrNull() ?: return@mapNotNull null
val id = SteamDownloadMonitor.value(text, "appid") ?: file.name.removePrefix("appmanifest_").removeSuffix(".acf")
val name = SteamDownloadMonitor.value(text, "name") ?: id
names[id] = name
fromManifest(id, name, text)
}.let(::onePerApp)
val homes = client?.let { listOf(if (it == "x86_64") SteamDownloadMonitor.STEAM_HOMES[1] else SteamDownloadMonitor.STEAM_HOMES[0]) }
?: SteamDownloadMonitor.STEAM_HOMES
val log = homes.map { File(runtimeRoot, "$it/logs/content_log.txt") }.filter { it.isFile }.maxByOrNull { it.lastModified() }
val shaders = log?.let { runningShaderUpdates(tail(it)) }.orEmpty()
.map { SteamDownload(it, names[it] ?: it, 0L, 0L, shader = true) }
return apps + shaders
}
/** The arm64 and x86-64 Steam homes can both hold an unfinished manifest of one app; the page keys rows by app. */
internal fun onePerApp(downloads: List<SteamDownload>): List<SteamDownload> =
downloads.groupBy { it.appId }.values.map { same -> same.maxBy { it.done } }
internal fun fromManifest(id: String, name: String, text: String): SteamDownload? {
val flags = SteamDownloadMonitor.value(text, "StateFlags")?.toLongOrNull() ?: 0L
if (flags == FULLY_INSTALLED) return null
val done = SteamDownloadMonitor.value(text, "BytesDownloaded")?.toLongOrNull() ?: 0L
val total = SteamDownloadMonitor.value(text, "BytesToDownload")?.toLongOrNull() ?: 0L
if (total > 0L && done >= total) return null
if ((flags and UPDATE_REQUIRED) == 0L && total <= 0L) return null
return SteamDownload(id, name, done, total, paused = (flags and UPDATE_PAUSED) != 0L)
}
/** App ids whose latest shader-cache line in the content log says the update is still running. */
internal fun runningShaderUpdates(lines: Sequence<String>): List<String> {
val state = LinkedHashMap<String, Boolean>()
for (line in lines) {
if ("Client version:" in line) state.clear()
val match = SteamDownloadMonitor.CONTENT_UPDATE.find(line) ?: continue
if (match.groupValues[2] != "Shader") continue
val running = match.groupValues[3].let { "Running Update" in it && "Stopping" !in it }
state[match.groupValues[1]] = running
}
return state.filterValues { it }.keys.toList()
}
private fun tail(file: File): Sequence<String> = runCatching {
RandomAccessFile(file, "r").use { raf ->
val start = (raf.length() - TAIL_BYTES).coerceAtLeast(0L)
raf.seek(start)
val bytes = ByteArray((raf.length() - start).toInt())
raf.readFully(bytes)
String(bytes, Charsets.ISO_8859_1).lineSequence().drop(if (start > 0L) 1 else 0).toList().asSequence()
}
}.getOrDefault(emptySequence())
private const val FULLY_INSTALLED = 4L
private const val UPDATE_REQUIRED = 2L
private const val UPDATE_PAUSED = 512L
private const val TAIL_BYTES = 256L * 1024L
}
@@ -0,0 +1,81 @@
package com.droiddeck.launcher.session
import android.database.sqlite.SQLiteDatabase
import java.io.File
import javax.crypto.Cipher
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec
/** A cookie for one https host, in the form CookieManager.setCookie takes. */
data class WebCookie(val host: String, val header: String)
/**
* The web sign-in the Steam client in the session already has, so the bottom-screen chat opens signed in.
* Steam's built-in browser keeps it in its Chromium cookie store under config/htmlcache. With no keyring
* (SteamOS and DroidDeck) Chromium encrypts values as "v10": AES-128-CBC, key PBKDF2-SHA1("peanuts",
* "saltysalt", 1 round), IV of 16 spaces. Values are never logged.
*/
object SteamWebLogin {
val HOSTS = listOf("steamcommunity.com", "steam-chat.com")
private const val COOKIES = "config/htmlcache/Default/Cookies"
private const val V10 = "v10"
// From cookie store version 24 Chromium puts the SHA-256 of the host before each value.
private const val HOST_HASH_VERSION = 24
private const val HOST_HASH_BYTES = 32
private val key: SecretKeySpec by lazy {
val spec = PBEKeySpec("peanuts".toCharArray(), "saltysalt".toByteArray(), 1, 128)
SecretKeySpec(SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec).encoded, "AES")
}
internal fun decrypt(encrypted: ByteArray, hostHashed: Boolean): String? = runCatching {
if (encrypted.size <= V10.length || String(encrypted, 0, V10.length, Charsets.US_ASCII) != V10) return null
val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")
cipher.init(Cipher.DECRYPT_MODE, key, IvParameterSpec(ByteArray(16) { ' '.code.toByte() }))
val plain = cipher.doFinal(encrypted, V10.length, encrypted.size - V10.length)
val value = if (hostHashed && plain.size >= HOST_HASH_BYTES) plain.copyOfRange(HOST_HASH_BYTES, plain.size) else plain
String(value, Charsets.UTF_8)
}.getOrNull()
/** Steam's own pages send the sign-in with its "||" separator percent-encoded. */
internal fun header(name: String, value: String, httpOnly: Boolean): String {
val v = if (name == "steamLoginSecure") value.replace("||", "%7C%7C") else value
return "$name=$v; Path=/; Secure" + if (httpOnly) "; HttpOnly" else ""
}
/** Empty when the client has no web sign-in, for example before the first login. */
fun read(runtimeRoot: File, client: String?, scratch: File): List<WebCookie> {
val homes = client?.let { listOf(if (it == "x86_64") SteamDownloadMonitor.STEAM_HOMES[1] else SteamDownloadMonitor.STEAM_HOMES[0]) }
?: SteamDownloadMonitor.STEAM_HOMES
val store = homes.map { File(runtimeRoot, "$it/$COOKIES") }.filter { it.isFile }.maxByOrNull { it.lastModified() }
?: return emptyList()
// A copy, journal included: Steam keeps the store open and may be in the middle of a write.
scratch.deleteRecursively()
if (!scratch.mkdirs()) return emptyList()
return try {
val copy = File(scratch, "Cookies")
store.copyTo(copy, overwrite = true)
File(store.path + "-journal").takeIf { it.length() > 0L }?.copyTo(File(scratch, "Cookies-journal"), overwrite = true)
SQLiteDatabase.openDatabase(copy.path, null, SQLiteDatabase.OPEN_READWRITE).use { db ->
val version = db.rawQuery("SELECT value FROM meta WHERE key = 'version'", null).use { if (it.moveToFirst()) it.getString(0).toIntOrNull() else null } ?: 0
val marks = HOSTS.joinToString { "?" }
db.rawQuery("SELECT host_key, name, value, encrypted_value, is_httponly FROM cookies WHERE host_key IN ($marks)", HOSTS.toTypedArray()).use { c ->
val out = ArrayList<WebCookie>()
while (c.moveToNext()) {
val name = c.getString(1)
val value = c.getString(2).takeUnless { it.isNullOrEmpty() }
?: decrypt(c.getBlob(3) ?: continue, version >= HOST_HASH_VERSION) ?: continue
out += WebCookie(c.getString(0), header(name, value, c.getInt(4) != 0))
}
out
}
}
} catch (_: Exception) {
emptyList()
} finally {
scratch.deleteRecursively()
}
}
}
@@ -0,0 +1,121 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.frontend.Library
import java.io.File
/**
* Codemasters games keep their UDP / motion output in My Games/<game>/hardwaresettings/hardware_settings_config.xml
* inside the game's Proton prefix and read it when the game starts. Turning it on points that element at the
* In-game stats listener; the file as it was is kept beside it, and its element is put back when turned off.
*/
object TelemetryOutput {
data class Game(val name: String, val prefixId: String, val file: File, val on: Boolean)
data class MenuGame(val name: String, val setting: String, val port: Int)
/** Games whose output is only a setting in the game's own menus, by Steam app id. */
val MENU_GAMES: Map<Int, MenuGame> = mapOf(
1293830 to MenuGame("Forza Horizon 4", "Data Out", GameTelemetry.FORZA_PORT),
1551360 to MenuGame("Forza Horizon 5", "Data Out", GameTelemetry.FORZA_PORT),
2440510 to MenuGame("Forza Motorsport", "Data Out", GameTelemetry.FORZA_PORT),
284160 to MenuGame("BeamNG.drive", "OutGauge", GameTelemetry.OUTGAUGE_PORT),
)
internal const val ORIGINAL_SUFFIX = ".droiddeck-original"
private const val MY_GAMES = "pfx/drive_c/users/steamuser/Documents/My Games"
private const val CONFIG = "hardwaresettings/hardware_settings_config.xml"
private const val ADDRESS = "127.0.0.1"
private const val EXTRADATA = "3"
private val TAGS = listOf("udp", "motion")
// Byte-for-byte: every byte maps to one char and back, whatever the file's own encoding is.
private val BYTES = Charsets.ISO_8859_1
fun scan(compatdata: List<File>): List<Game> = compatdata.asSequence()
.flatMap { root -> root.listFiles { f -> f.isDirectory }.orEmpty().asSequence() }
.flatMap { prefix -> File(prefix, MY_GAMES).listFiles { f -> f.isDirectory }.orEmpty().asSequence().map { prefix to it } }
.mapNotNull { (prefix, game) ->
val file = File(game, CONFIG)
val text = runCatching { file.readText(BYTES) }.getOrNull() ?: return@mapNotNull null
val element = element(text) ?: return@mapNotNull null
Game(game.name, prefix.name, file, pointsHere(element.value))
}
.sortedBy { it.name.lowercase() }
.toList()
/** Turns the game's output on or off; false when the file could not be read or written. */
fun set(game: Game, on: Boolean): Boolean = runCatching {
val file = game.file
val original = File(file.path + ORIGINAL_SUFFIX)
val xml = file.readText(BYTES)
val next = if (on) {
if (!original.exists()) file.copyTo(original)
turnedOn(xml)
} else {
turnedOff(xml, original.takeIf { it.isFile }?.readText(BYTES))
}
checkNotNull(next)
val tmp = File(file.path + ".droiddeck-tmp")
tmp.writeText(next, BYTES)
check(tmp.renameTo(file))
if (!on) original.delete()
true
}.getOrDefault(false)
/** Automatic: turns the output on for every found game the user has not switched off and that is not running. */
fun applyAutomatic(context: Context, running: String?) {
if (!SessionPrefs.telemetryAuto(context)) return
automaticTargets(scan(Library.compatdataDirs(context)), SessionPrefs.telemetryOff(context), running).forEach { set(it, true) }
}
internal fun key(game: Game) = "${game.prefixId}/${game.name}"
internal fun automaticTargets(games: List<Game>, off: Set<String>, running: String?): List<Game> =
games.filter { !it.on && key(it) !in off && !isRunning(it.prefixId, running) }
/** Games DroidDeck changed, which go back to their own setting when Automatic is switched off. */
internal fun restoreTargets(games: List<Game>, running: String?): List<Game> =
games.filter { File(it.file.path + ORIGINAL_SUFFIX).isFile && !isRunning(it.prefixId, running) }
/** Whether [running] (the focused Steam app id, or another key for non-Steam programs) may be the game in [prefixId]. */
internal fun isRunning(prefixId: String, running: String?): Boolean {
val id = running?.toLongOrNull() ?: return running != null
return prefixId == id.toString() || prefixId == id.toInt().toString()
}
internal fun element(xml: String): MatchResult? = TAGS.firstNotNullOfOrNull { tag -> tagRegex(tag).find(xml) }
internal fun pointsHere(element: String): Boolean =
attr(element, "enabled") == "true" && attr(element, "ip") == ADDRESS &&
attr(element, "port") == GameTelemetry.CODEMASTERS_PORT.toString() &&
(attr(element, "extradata") ?: EXTRADATA) == EXTRADATA
internal fun turnedOn(xml: String): String? {
val element = element(xml) ?: return null
var on = withAttr(element.value, "enabled", "true")
on = withAttr(on, "ip", ADDRESS)
on = withAttr(on, "port", GameTelemetry.CODEMASTERS_PORT.toString())
if (attr(on, "extradata") != null) on = withAttr(on, "extradata", EXTRADATA)
return xml.replaceRange(element.range, on)
}
internal fun turnedOff(xml: String, original: String?): String? {
val element = element(xml) ?: return null
val tag = element.value.drop(1).takeWhile { !it.isWhitespace() }
val before = original?.let { tagRegex(tag).find(it)?.value }
return xml.replaceRange(element.range, before ?: withAttr(element.value, "enabled", "false"))
}
internal fun attr(element: String, name: String): String? =
Regex("\\s$name=\"([^\"]*)\"").find(element)?.groupValues?.get(1)
internal fun withAttr(element: String, name: String, value: String): String {
val existing = Regex("(\\s$name=\")[^\"]*\"")
if (existing.containsMatchIn(element)) return existing.replace(element) { it.groupValues[1] + value + "\"" }
val selfClosing = element.endsWith("/>")
val body = element.dropLast(if (selfClosing) 2 else 1).trimEnd()
return "$body $name=\"$value\"" + if (selfClosing) " />" else ">"
}
private fun tagRegex(tag: String) = Regex("<$tag\\s[^>]*>")
}
@@ -92,6 +92,28 @@ object SteamLiveShortcuts {
if (evaluate(context, js) != null) Log.i(TAG, "live shortcuts: updated $id")
}
fun launchOptions(context: Context, appId: Long): String? {
if (!clientRunning()) return null
val js = """
new Promise(done => {
let handle = null, answer;
const finish = d => { clearTimeout(timer); try { handle?.unregister(); } catch (e) {} done(d); };
const timer = setTimeout(() => finish(null), 4000);
handle = SteamClient.Apps.RegisterForAppDetails(${appId and 0xFFFFFFFFL}, d => { answer = d; if (handle) finish(d); });
if (answer !== undefined) finish(answer);
}).then(d => typeof d?.strLaunchOptions === 'string' ? d.strLaunchOptions : null)
""".trimIndent()
return evaluate(context, js)
}
fun setLaunchOptions(context: Context, appId: Long, options: String): Boolean {
if (!clientRunning()) return false
val id = appId and 0xFFFFFFFFL
val done = evaluate(context, "(async () => { SteamClient.Apps.SetAppLaunchOptions($id, ${JSONObject.quote(options)}); return 1; })()") != null
if (done) Log.i(TAG, "live: launch options for $id")
return done
}
fun setArt(context: Context, appId: Long, assetType: Int?, file: java.io.File?, iconPath: String? = null) {
if (!clientRunning()) return
val id = appId and 0xFFFFFFFFL
@@ -68,6 +68,7 @@ import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.frontend.LogoPosition
import com.droiddeck.launcher.frontend.SteamGameArt
import com.droiddeck.launcher.frontend.SteamGridDb
import com.droiddeck.launcher.frontend.SteamLaunchOptions
import com.droiddeck.launcher.session.SessionPrefs
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@@ -191,7 +192,7 @@ internal fun SteamGameArtEditor(
game: com.droiddeck.launcher.frontend.Library.SteamGame, onClose: () -> Unit, onChanged: () -> Unit,
) {
val target = remember(game.appId) { ArtTarget.of(game) }
ArtOnlyEditor(game.name, target, game, { SteamGameArt.describe(it, game) }, onClose, onChanged)
ArtOnlyEditor(game.name, target, game, { SteamGameArt.describe(it, game) }, onClose, onChanged, launchAppId = game.appId)
}
@Composable
@@ -207,18 +208,25 @@ internal fun StoreGameArtEditor(folder: String, name: String, onClose: () -> Uni
@Composable
private fun ArtOnlyEditor(
name: String, target: ArtTarget?, refresh: Any?, describe: (Context) -> List<AddedGameArt.SlotState>,
onClose: () -> Unit, onChanged: () -> Unit,
onClose: () -> Unit, onChanged: () -> Unit, launchAppId: Int? = null,
) {
val app = LocalContext.current.applicationContext
val colors = MaterialTheme.colorScheme
val scope = rememberCoroutineScope()
val shown = rememberShown(onClose)
val close = { shown.targetState = false }
var version by remember { mutableIntStateOf(0) }
var arts by remember { mutableStateOf<List<AddedGameArt.SlotState>>(emptyList()) }
var artSlot by remember { mutableStateOf<AddedGameArt.Slot?>(null) }
var logoOpen by remember { mutableStateOf(false) }
var launchOptions by remember { mutableStateOf<String?>(null) }
var launchVersion by remember { mutableIntStateOf(0) }
var editingLaunch by remember { mutableStateOf<String?>(null) }
var launchSaving by remember { mutableStateOf(false) }
var launchError by remember { mutableStateOf<Int?>(null) }
val position = rememberLogoPosition(target, version)
LaunchedEffect(version, refresh) { if (target != null) arts = withContext(Dispatchers.IO) { describe(app) } }
LaunchedEffect(launchAppId, launchVersion) { if (launchAppId != null) launchOptions = withContext(Dispatchers.IO) { SteamLaunchOptions.current(app, launchAppId) } }
val first = remember { FocusRequester() }
LaunchedEffect(Unit) { focusWithinFrames({ false }) { first } }
AppDialog(shown, close, "artEditor", wide = false, maxWidth = 460.dp) {
@@ -228,10 +236,19 @@ private fun ArtOnlyEditor(
verticalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.fillMaxWidth().heightIn(max = maxHeight).verticalScroll(rememberScrollState()),
) {
Text(stringResource(R.string.edit_artwork), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 4.dp, top = 2.dp))
if (launchAppId != null) {
FieldRow(stringResource(R.string.edit_launch_options), focus = first, onClick = { if (!launchSaving) launchOptions?.let { editingLaunch = it } }) {
val options = launchOptions
if (options == null || launchSaving) Loading() else ValueText(options.ifEmpty { "—" }, muted = options.isEmpty())
}
val error = launchError
if (error != null) Text(stringResource(error), fontSize = 12.sp, color = colors.error, modifier = Modifier.padding(start = 4.dp))
else Text(stringResource(R.string.edit_launch_options_steam_hint), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 4.dp))
}
Text(stringResource(R.string.edit_artwork), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 4.dp, top = if (launchAppId != null) 8.dp else 2.dp))
for (slot in AddedGameArt.Slot.values()) key(slot) {
val state = arts.firstOrNull { it.slot == slot }
FieldRow(slot.label(), focus = if (slot == AddedGameArt.Slot.COVER) first else null, onClick = { if (target != null) artSlot = slot }) {
FieldRow(slot.label(), focus = if (slot == AddedGameArt.Slot.COVER && launchAppId == null) first else null, onClick = { if (target != null) artSlot = slot }) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
SlotThumb(slot, state?.file)
if (state != null) ValueText(artSourceLabel(state.source), muted = true) else Loading()
@@ -241,6 +258,27 @@ private fun ArtOnlyEditor(
PickerRow(Icons.Outlined.Tune, stringResource(R.string.art_adjust_logo), logoPositionSummary(position?.value), enabled = target != null && position != null) { logoOpen = true }
}
}
val before = editingLaunch
if (before != null && launchAppId != null) TextEntryDialog(stringResource(R.string.edit_launch_options), before, onDismiss = { editingLaunch = null }) { value ->
if (launchSaving || value == before.trim()) return@TextEntryDialog
launchSaving = true
scope.launch {
try {
val saved = withContext(Dispatchers.IO) { SteamLaunchOptions.set(app, launchAppId, value, before) }
launchError = when (saved) {
SteamLaunchOptions.Saved.YES -> null
SteamLaunchOptions.Saved.DESKTOP -> R.string.edit_launch_options_desktop
SteamLaunchOptions.Saved.NO -> R.string.edit_launch_options_not_saved
}
if (saved == SteamLaunchOptions.Saved.YES) launchOptions = value else {
launchOptions = null
launchVersion++
}
} finally {
launchSaving = false
}
}
}
val chosen = target ?: return
artSlot?.let { slot ->
ArtChooserDialog(chosen, slot, arts.firstOrNull { it.slot == slot }, onBack = { artSlot = null }, onCloseAll = { artSlot = null; close() }) { version++; onChanged() }
@@ -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)
}
@@ -24,6 +24,7 @@ internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (Stri
DroidDeckHudSize.PILL to stringResource(R.string.hud_size_pill),
DroidDeckHudSize.MINIMAL to stringResource(R.string.hud_size_minimal),
DroidDeckHudSize.MEGA to stringResource(R.string.hud_size_mega),
DroidDeckHudSize.STRIP to stringResource(R.string.hud_size_strip),
),
size, chipModifier = track("hud-size")) { a.onHudSetting("hudSize", it.token) }
ToggleRow(host, "hud-locked", stringResource(R.string.hud_locked), stringResource(R.string.hud_locked_hint), on("hudLocked"),
@@ -125,9 +126,10 @@ private val METRICS = listOf(
)
// Switches a size lists but never draws (DroidDeckHudView): the Pill and Minimal always show the FPS, the
// Pill has no graph, Tiles has no graph and no 0.01% low.
// Pill has no graph, Tiles has no graph and no 0.01% low, the Strip always shows the FPS.
private val HIDDEN = mapOf(
DroidDeckHudSize.PILL to setOf("FPS", "FPS graph"),
DroidDeckHudSize.MINIMAL to setOf("FPS"),
DroidDeckHudSize.TILES to setOf("FPS graph", "0.01% low"),
DroidDeckHudSize.STRIP to setOf("FPS"),
)
@@ -64,10 +64,12 @@ class DualPanelModel(
object DualScreenPanel {
var model by mutableStateOf<DualPanelModel?>(null)
private var displayId = -1
private var presentation: DualScreenPresentation? = null
set(value) { field = value; available = value != null || activity != null || launching }
private var activity: DualScreenActivity? = null
set(value) { field = value; available = value != null || launching }
set(value) { field = value; available = value != null || presentation != null || launching }
private var launching = false
set(value) { field = value; available = value || activity != null }
set(value) { field = value; available = value || activity != null || presentation != null }
private var ownerTask = -1
private var ownerYielded = false
private var ownerPaused = false
@@ -77,8 +79,8 @@ object DualScreenPanel {
var typingShown by mutableStateOf(false)
private set
val shownOn: Int get() = if (activity != null || launching) displayId else -1
val attached: Boolean get() = activity != null
val shownOn: Int get() = if (presentation != null || activity != null || launching) displayId else -1
val attached: Boolean get() = presentation != null || activity != null
var available by mutableStateOf(false)
private set
@@ -123,6 +125,20 @@ object DualScreenPanel {
ownerYielded = false
ownerPaused = false
launching = true
val host = context as? ComponentActivity
val target = host?.getSystemService(Context.DISPLAY_SERVICE)
?.let { (it as android.hardware.display.DisplayManager).getDisplay(display) }
// A second-display activity makes the system launcher treat its bottom home as lost and bring itself forward;
// a presentation belongs to this task and leaves that home alone.
if (host != null && target != null) {
val shown = runCatching { DualScreenPresentation(host, target).also { it.show() } }
if (shown.isSuccess) {
presentation = shown.getOrThrow()
launching = false
return
}
android.util.Log.w("DualScreenPanel", "bottom panel presentation failed; falling back to an activity", shown.exceptionOrNull())
}
val intent = Intent(context, DualScreenActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION)
runCatching {
@@ -134,6 +150,8 @@ object DualScreenPanel {
stopTyping()
launching = false
displayId = -1
presentation?.dismiss()
presentation = null
activity?.finishAndRemoveTask()
activity = null
}
@@ -144,6 +162,8 @@ object DualScreenPanel {
internal fun attach(host: DualScreenActivity): Boolean {
if (!launching && activity == null) return false
presentation?.dismiss()
presentation = null
if (activity !== host) activity?.finishAndRemoveTask()
activity = host
launching = false
@@ -155,6 +175,8 @@ object DualScreenPanel {
if (ownerTask == task) ownerYielded = app
}
fun opensOutside(own: String, target: String?): Boolean = target != null && target != own
fun ownerPaused(task: Int, paused: Boolean) {
if (ownerTask == task) ownerPaused = paused
}
@@ -164,18 +186,13 @@ object DualScreenPanel {
return ownerTask.takeIf { it >= 0 }
}
internal fun tookFocus(fresh: Boolean, touchedAt: Long, now: Long): Boolean =
fresh || now - touchedAt in 0..TOUCH_FOCUS_MS
private const val TOUCH_FOCUS_MS = 1000L
internal fun returnFocus(context: Context, fromPanel: Boolean = false) {
val task = focusTask(fromPanel) ?: return
runCatching { (context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager).moveTaskToFront(task, 0) }
}
internal fun reclaimFocus(context: Context) {
val task = focusTask(false) ?: return
val task = focusTask(true) ?: return
val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
runCatching {
manager.appTasks.firstOrNull {
@@ -191,6 +208,13 @@ object DualScreenPanel {
displayId = -1
}
}
internal fun detach(host: DualScreenPresentation) {
if (presentation === host) {
presentation = null
displayId = -1
}
}
}
class DualScreenActivity : ComponentActivity() {
@@ -243,21 +267,16 @@ class DualScreenActivity : ComponentActivity() {
}
private var topResumed = false
private var fresh = true
private var touchedAt = Long.MIN_VALUE
override fun onTopResumedActivityChanged(isTopResumedActivity: Boolean) {
super.onTopResumedActivityChanged(isTopResumedActivity)
topResumed = isTopResumedActivity
val took = DualScreenPanel.tookFocus(fresh, touchedAt, android.os.SystemClock.uptimeMillis())
fresh = false
if (isTopResumedActivity && !DualScreenPanel.typingShown) DualScreenPanel.returnFocus(this, fromPanel = took)
if (isTopResumedActivity && !DualScreenPanel.typingShown) DualScreenPanel.returnFocus(this, fromPanel = true)
}
override fun dispatchTouchEvent(event: android.view.MotionEvent): Boolean {
if (event.actionMasked == android.view.MotionEvent.ACTION_DOWN) {
touchedAt = event.downTime
if (topResumed && !DualScreenPanel.typingShown) DualScreenPanel.returnFocus(this, fromPanel = true)
if (event.actionMasked == android.view.MotionEvent.ACTION_DOWN && topResumed && !DualScreenPanel.typingShown) {
DualScreenPanel.returnFocus(this, fromPanel = true)
}
return super.dispatchTouchEvent(event)
}
@@ -0,0 +1,99 @@
package com.droiddeck.launcher.ui
import android.app.Presentation
import android.os.Bundle
import android.view.Display
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.setViewTreeOnBackPressedDispatcherOwner
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ComposeView
import androidx.lifecycle.setViewTreeLifecycleOwner
import androidx.lifecycle.setViewTreeViewModelStoreOwner
import androidx.savedstate.setViewTreeSavedStateRegistryOwner
import com.droiddeck.launcher.core.AppUiPrefs
internal class DualScreenPresentation(
private val host: ComponentActivity,
display: Display,
) : Presentation(host, display) {
private var content: ComposeView? = null
init {
setCancelable(false)
setCanceledOnTouchOutside(false)
setOnDismissListener { DualScreenPanel.detach(this) }
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
applyImmersiveMode()
val decor = window?.decorView ?: return
decor.setViewTreeLifecycleOwner(host)
decor.setViewTreeViewModelStoreOwner(host)
decor.setViewTreeSavedStateRegistryOwner(host)
decor.setViewTreeOnBackPressedDispatcherOwner(host)
val view = ComposeView(context)
content = view
view.setContent {
val model = DualScreenPanel.model
val request = DualScreenPanel.typing
val typingOn = request != null && DualScreenPanel.typingShown
LaunchedEffect(typingOn) { acceptFocus(typingOn) }
DroidDeckTheme(model?.theme, appScale = model?.appScale ?: AppUiPrefs.DEFAULT_SCALE) {
Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background)) {
if (request != null && typingOn) TypingPanel(request) {
if (DualScreenPanel.typing === request) DualScreenPanel.finishTyping()
} else if (model != null) DualPanelContent(model)
}
}
}
setContentView(view)
}
private fun acceptFocus(on: Boolean) {
val window = window ?: return
if (on) {
window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
content?.requestFocus()
} else {
window.addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
host.window?.decorView?.requestFocus()
}
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus) applyImmersiveMode()
}
@Suppress("OVERRIDE_DEPRECATION")
override fun onBackPressed() {
if (DualScreenPanel.typingShown) DualScreenPanel.finishTyping()
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (DualScreenPanel.typingShown && event.keyCode == KeyEvent.KEYCODE_BUTTON_B) {
if (event.action == KeyEvent.ACTION_UP && !event.isCanceled) DualScreenPanel.finishTyping()
return true
}
return super.dispatchKeyEvent(event)
}
private fun applyImmersiveMode() {
@Suppress("DEPRECATION")
window?.decorView?.systemUiVisibility = (View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
}
}
@@ -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)
}
}
}
@@ -163,6 +163,8 @@ public final class WaylandCompositor {
public static native int nativeCursorSerial();
public static native void nativeSetCursorComposite(boolean on);
public static final int CURSOR_BUF_INTS = 6 + 256 * 256;
public static native void nativeSendKey(int evdev, int state);