Merge latest origin/main and resolve conflicts

This commit is contained in:
DroidDeck Merge committed 2026-11-02 10:44:24 +08:00
commit 8171bf20fd
581 files changed
+14773 -4227

No files matched your search

@@ -0,0 +1,15 @@
package com.droiddeck.launcher.hud
import android.os.SystemClock
internal object BottomHudPresence {
private const val STALE_MS = 2_500L
@Volatile private var seenAt = 0L
fun beat() {
seenAt = SystemClock.elapsedRealtime()
}
val showing: Boolean get() = seenAt != 0L && SystemClock.elapsedRealtime() - seenAt < STALE_MS
}
@@ -3,14 +3,9 @@ package com.droiddeck.launcher.hud
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
/** DroidDeck HUD's settings as one "key=value,…" string (DroidDeckHudView.applyConfig), stored in SessionPrefs. */
internal object DroidDeckHudConfig {
/**
* Bannerlator's defaults (DeckOverlaySettings), with the FPS graph from the old DroidDeck HUD. The HUD starts
* locked, so like the old HUD it lets touches through until it is unlocked to move it.
*/
val DEFAULTS: Map<String, String> = linkedMapOf(
"hudSize" to "minimal", "hudLocked" to "1", "hudScale" to "100", "hudDock" to "none", "hudOpacity" to "80", "hudColor" to "mid",
"hudSize" to "minimal", "hudLocked" to "1", "hudSnap" to "1", "hudScale" to "100", "hudDock" to "none", "hudOpacity" to "80", "hudColor" to "mid",
"hudOutline" to "40", "hudOutlineAccent" to "1",
"showFPS" to "1", "showFPSGraph" to "1", "showCPUUsage" to "1", "showCPULoad" to "1", "showGPULoad" to "1",
"showVram" to "1", "showRAM" to "1", "showPower" to "1", "showTemp" to "1", "showBatteryTemp" to "1",
@@ -20,7 +15,6 @@ internal object DroidDeckHudConfig {
"tempUnit" to "c", "tempBands" to "1", "tempAuto" to "1", "tempRedCpu" to "90", "tempRedGpu" to "90", "tempRedBat" to "48",
)
/** Switches Bannerlator sets together (DeckOverlaySettings twins). */
private val TWINS = mapOf("showCPUUsage" to "showCPULoad", "showTemp" to "showBatteryTemp", "showEngine" to "showRenderer")
fun load(context: Context): MutableMap<String, String> {
@@ -4,6 +4,7 @@ import android.content.Context
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.animation.ValueAnimator
import android.view.Choreographer
import android.view.View
import android.view.animation.PathInterpolator
@@ -21,10 +22,6 @@ import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import kotlin.math.roundToInt
/**
* DroidDeck HUD on the session screen, in place of the old text HUD: the view, the frame feed from gamescope
* (MangoHud's frame times) and MangoHud's readings, started with the session's first frame.
*/
class DroidDeckHudHost(context: Context) {
private val context = context.applicationContext
private val handler = Handler(Looper.getMainLooper())
@@ -38,6 +35,11 @@ class DroidDeckHudHost(context: Context) {
private var polling = false
private var wantX = Float.NaN
private var wantY = Float.NaN
private var anchorX = Float.NaN
private var snaps = true
private var snapping = false
private var previewFade: ValueAnimator? = null
private var flingX = 0f
private var engine = ""
private var gpuName = ""
private var protonPid = 0
@@ -46,13 +48,10 @@ 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
/** Screen point → whether an on-screen control takes a touch there; a locked HUD lets those through. */
var passesTouchAt: ((rawX: Float, rawY: Float) -> Boolean)? = null
private val listener = object : WaylandCompositor.GameListener {
@@ -84,7 +83,6 @@ class DroidDeckHudHost(context: Context) {
get() = SessionPrefs.hudEnabled(context) &&
!File(Environment.getExternalStorageDirectory(), "Download/droiddeck-no-hud").exists()
/** Adds the HUD to [root] at [index] (above the game surface, under the session overlay). */
fun attach(root: FrameLayout, index: Int) {
if (view != null) return
val hud = DroidDeckHudView(root.context)
@@ -92,12 +90,29 @@ class DroidDeckHudHost(context: Context) {
hud.setMangoReadings(readings)
hud.setGpuModel(cleanGpuName(GpuInfo.detect().displayName(context)))
hud.onRefresh = Runnable { refreshLabels(hud) }
hud.setOnDraggedListener { rawX, rawY ->
anchorX = Float.NaN; snapping = false
previewFade?.cancel(); previewFade = null
stopMotion(hud)
shrinkPastEdge(hud, rawX, rawY)
}
hud.setOnFlungListener { vx, _ -> flingX = vx }
hud.setOnTabDraggedListener { x, y -> dragTab(hud, x, y) }
hud.setOnTabDroppedListener { dropTab(hud) }
hud.setOnTabDragCancelledListener { snapping = false; keepOnScreen(hud) }
hud.setOnMovedListener { x, y ->
wantX = x; wantY = y
if (!hud.isStrip) dockEdgeFor(hud)?.let { edge -> setDock(hud, edge); return@setOnMovedListener }
val vx = flingX
flingX = 0f
dockEdgeFor(hud)?.let { edge -> setDock(hud, edge); return@setOnMovedListener }
stopMotion(hud)
fadeDockPreview(hud)
if (snaps && !hud.isStrip) { snapToAnchor(hud, vx); return@setOnMovedListener }
val fromX = hud.x; val fromY = hud.y
keepOnScreen(hud)
wantX = hud.x; wantY = hud.y
SessionPrefs.setDroidDeckHudPosition(context, hud.x, hud.y)
glideFrom(hud, fromX, fromY)
}
hud.setOnSizeCycledListener { size -> DroidDeckHudConfig.set(context, "hudSize", size); onConfigChanged?.invoke() }
hud.setOnDockChangedListener { token -> setDock(hud, DroidDeckHudDock.from(token)) }
@@ -124,7 +139,10 @@ class DroidDeckHudHost(context: Context) {
}
fun applyConfig() {
view?.applyConfig(DroidDeckHudConfig.encode(DroidDeckHudConfig.load(context)))
val config = DroidDeckHudConfig.load(context)
snaps = config["hudSnap"] != "0"
if (!snaps) anchorX = Float.NaN
view?.applyConfig(DroidDeckHudConfig.encode(config))
}
fun refresh() {
@@ -149,13 +167,11 @@ class DroidDeckHudHost(context: Context) {
view?.visibility = View.GONE
}
/** Picture-in-picture and similar: keep running, draw nothing. */
fun setHidden(hide: Boolean) {
hidden = hide
applyShown()
}
/** The session screen is stopped (another app in front): draw nothing and stop reading sensors. */
fun setBackgrounded(stopped: Boolean) {
backgrounded = stopped
applyShown()
@@ -166,7 +182,6 @@ class DroidDeckHudHost(context: Context) {
val show = !hidden && !backgrounded && SessionState.mode != SessionService.MODE_DESKTOP
view?.visibility = if (show) View.VISIBLE else View.GONE
showing = show
// Frames are read once per display frame only while the HUD is drawn.
if (show != polling) {
polling = show
if (show) Choreographer.getInstance().postFrameCallback(frameCallback)
@@ -174,14 +189,11 @@ class DroidDeckHudHost(context: Context) {
}
}
/** A sensor report (DroidDeck HUD's diagnostics) in Downloads/DroidDeck; null when it can't be written. */
fun exportDiagnostics(): File? = runCatching {
val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "DroidDeck")
dir.mkdirs()
val stamp = java.text.SimpleDateFormat("yyyyMMdd-HHmmss", java.util.Locale.US).format(java.util.Date())
val file = File(dir, "HUD-diagnostics-$stamp.txt")
// Its own reader: the HUD's CPU load is the change since its previous sample, which an export must
// not move. Two samples half a second apart, MangoHud's sampling period.
val metrics = HudMetrics(context)
metrics.setMangoReadings(MangoReadings(File(context.filesDir, "session"), LinuxRuntime.rootDir(context)))
metrics.snapshot()
@@ -191,6 +203,7 @@ class DroidDeckHudHost(context: Context) {
"CPU ${mango.cpuPercent}% ${mango.cpuTempC}°C, GPU ${mango.gpuPercent}% ${mango.gpuClockMhz}MHz ${mango.gpuTempC}°C, " +
"RAM ${mango.ramUsedText()}/${mango.ramTotalText()}, VRAM ${mango.vramText()}, battery ${mango.battery.percent}% " +
"${mango.battery.watts}W charging=${mango.battery.charging}\n" +
"GPU feeds: ${com.droiddeck.launcher.session.GpuStatsComponent.sources.ifEmpty { "none (no session, or kgsl absent)" }}\n" +
"CPU temperature zones: ${LinuxRuntime.cpuTempZones().joinToString { it.name }}\n" +
"Frames: ${if (feed.engine.isNotEmpty() || feed.pid > 0) "gamescope (pid ${feed.pid}, ${feed.engine})" else "compositor"}, " +
"fps ${feed.stats.fps}\n")
@@ -228,35 +241,136 @@ class DroidDeckHudHost(context: Context) {
return if (stats.size > 3 && stats[3] > 1f) stats[3] else 0f
}
/** The edge the HUD was dropped over, once a good part of it hangs past that edge; null when it stays. */
private fun dockEdgeFor(v: View): DroidDeckHudDock? {
val p = v.parent as? View ?: return null
if (p.width <= 0 || p.height <= 0 || v.width <= 0 || v.height <= 0) return null
val over = mapOf(
DroidDeckHudDock.LEFT to -v.x / v.width,
DroidDeckHudDock.RIGHT to (v.x + v.width - p.width) / v.width,
DroidDeckHudDock.TOP to -v.y / v.height,
DroidDeckHudDock.BOTTOM to (v.y + v.height - p.height) / v.height,
).maxByOrNull { it.value } ?: return null
val over = overhang(v) ?: return null
return over.key.takeIf { over.value >= DOCK_OVERHANG }
}
/** Tucks the HUD against [edge] as its FPS tab, or with [DroidDeckHudDock.NONE] brings it back out from where it was docked. */
private fun overhang(v: View): Map.Entry<DroidDeckHudDock, Float>? {
val p = v.parent as? View ?: return null
if (p.width <= 0 || p.height <= 0 || v.width <= 0 || v.height <= 0) return null
val strip = (v as? DroidDeckHudView)?.isStrip == true
val density = v.resources.displayMetrics.density
val w = if (strip) minOf(v.width.toFloat(), STRIP_PULL_ACROSS_DP * density) else v.width.toFloat()
val h = if (strip) maxOf(v.height.toFloat(), STRIP_PULL_OFF_DP * density) else v.height.toFloat()
return mapOf(
DroidDeckHudDock.LEFT to -v.x / w,
DroidDeckHudDock.RIGHT to (v.x + v.width - p.width) / w,
DroidDeckHudDock.TOP to -v.y / h,
DroidDeckHudDock.BOTTOM to (v.y + v.height - p.height) / h,
).maxByOrNull { it.value }
}
private fun dragTab(hud: DroidDeckHudView, x: Float, y: Float) {
val p = hud.parent as? View ?: return
stopMotion(hud)
snapping = false
hud.x = x.coerceIn(0f, (p.width - hud.width).toFloat().coerceAtLeast(0f))
hud.y = y.coerceIn(0f, (p.height - hud.height).toFloat().coerceAtLeast(0f))
}
private fun dropTab(hud: DroidDeckHudView) {
val p = hud.parent as? View ?: return
val maxX = (p.width - hud.width).toFloat().coerceAtLeast(0f)
val maxY = (p.height - hud.height).toFloat().coerceAtLeast(0f)
val pulled = when (hud.dock) {
DroidDeckHudDock.LEFT -> hud.x / hud.width
DroidDeckHudDock.RIGHT -> (maxX - hud.x) / hud.width
DroidDeckHudDock.TOP -> hud.y / hud.height
DroidDeckHudDock.BOTTOM -> (maxY - hud.y) / hud.height
DroidDeckHudDock.NONE -> 0f
}
if (pulled >= 1f) { setDock(hud, DroidDeckHudDock.NONE); return }
wantX = hud.x; wantY = hud.y
val (x, y) = settled(p, hud.dock, hud.width.toFloat(), hud.height.toFloat())
wantX = x; wantY = y
SessionPrefs.setDroidDeckHudPosition(context, x, y)
if (Motion.scale == 0f) { hud.x = x; hud.y = y; return }
snapping = true
hud.animate().x(x).y(y).setDuration(Motion.ms(220).toLong()).setInterpolator(EASE)
.withEndAction { snapping = false }.start()
}
private fun stopMotion(hud: DroidDeckHudView) {
hud.animate().setUpdateListener(null)
hud.animate().cancel()
}
private fun glideFrom(hud: DroidDeckHudView, fromX: Float, fromY: Float) {
if (Motion.scale == 0f || (fromX == hud.x && fromY == hud.y && hud.scaleX == 1f && hud.scaleY == 1f)) {
hud.scaleX = 1f; hud.scaleY = 1f
return
}
val toX = hud.x; val toY = hud.y
hud.x = fromX; hud.y = fromY
snapping = true
hud.animate().x(toX).y(toY).scaleX(1f).scaleY(1f).setDuration(Motion.ms(220).toLong()).setInterpolator(EASE)
.withEndAction { snapping = false; keepOnScreen(hud) }.start()
}
private fun fadeDockPreview(hud: DroidDeckHudView) {
val from = hud.dockPreviewBlend
if (from <= 0f) return
val edge = overhang(hud)?.key ?: DroidDeckHudDock.NONE
if (Motion.scale == 0f) { hud.setDockPreview(DroidDeckHudDock.NONE, 0f); return }
previewFade?.cancel()
previewFade = ValueAnimator.ofFloat(from, 0f).apply {
duration = Motion.ms(200).toLong()
addUpdateListener { hud.setDockPreview(edge, it.animatedValue as Float) }
start()
}
}
private fun snapToAnchor(hud: DroidDeckHudView, vx: Float) {
val p = hud.parent as? View ?: return
val maxX = (p.width - hud.width).toFloat().coerceAtLeast(0f)
val maxY = (p.height - hud.height).toFloat().coerceAtLeast(0f)
anchorX = if (hud.x + vx * FLING_REACH_S < maxX / 2f) 0f else 1f
wantX = anchorX * maxX
wantY = hud.y.coerceIn(0f, maxY)
SessionPrefs.setDroidDeckHudPosition(context, wantX, wantY)
stopMotion(hud)
if (Motion.scale == 0f) {
hud.scaleX = 1f; hud.scaleY = 1f
hud.x = wantX; hud.y = wantY
return
}
snapping = true
hud.animate().x(wantX).y(wantY).scaleX(1f).scaleY(1f).setDuration(Motion.ms(260).toLong()).setInterpolator(EASE)
.withEndAction { snapping = false; keepOnScreen(hud) }.start()
}
private fun shrinkPastEdge(hud: DroidDeckHudView, rawX: Float, rawY: Float) {
if (hud.dock != DroidDeckHudDock.NONE) return
val p = hud.parent as? View ?: return
val edge = overhang(hud) ?: return
val over = edge.value
val t = (over / DOCK_OVERHANG).coerceIn(0f, 1f)
val fade = ((t - PREVIEW_FROM) / (1f - PREVIEW_FROM)).coerceIn(0f, 1f)
hud.setDockPreview(edge.key, fade * fade * (3f - 2f * fade))
val (tabW, tabH) = hud.dockTabSize()
val e = t * t * (3f - 2f * t)
val at = IntArray(2).also { p.getLocationOnScreen(it) }
hud.pivotX = rawX - at[0] - hud.x
hud.pivotY = rawY - at[1] - hud.y
if (hud.isStrip) {
hud.scaleX = 1f + (tabW / hud.width - 1f) * e
hud.scaleY = 1f
return
}
val tabScale = maxOf(tabW / hud.width, tabH / hud.height).coerceAtMost(1f)
val s = 1f + (tabScale - 1f) * e
hud.scaleX = s; hud.scaleY = s
}
private fun setDock(hud: DroidDeckHudView, edge: DroidDeckHudDock) {
if (edge == hud.dock) return
animateDock(hud, edge) { commitDock(hud, edge) }
}
private fun commitDock(hud: DroidDeckHudView, edge: DroidDeckHudDock) {
if (edge == DroidDeckHudDock.NONE) {
when (hud.dock) {
DroidDeckHudDock.LEFT -> wantX = 0f
DroidDeckHudDock.RIGHT -> wantX = Float.MAX_VALUE
DroidDeckHudDock.TOP -> wantY = 0f
DroidDeckHudDock.BOTTOM -> wantY = Float.MAX_VALUE
DroidDeckHudDock.NONE -> {}
}
} else {
val tabX = hud.x; val tabY = hud.y
if (edge != DroidDeckHudDock.NONE) {
val p = hud.parent as? View
if (p != null) {
wantX = wantX.coerceIn(0f, p.width.toFloat())
@@ -266,35 +380,55 @@ class DroidDeckHudHost(context: Context) {
}
DroidDeckHudConfig.set(context, "hudDock", edge.token)
applyConfig()
if (edge == DroidDeckHudDock.NONE) settleOutOfTab(hud, tabX, tabY)
hud.post { keepOnScreen(hud) }
onConfigChanged?.invoke()
}
/**
* One shape contracts into the tab, and the tab expands back out to the HUD: the view is scaled onto the
* tab's exact rectangle, and the layouts swap at that same size and place. Timing and curve are the
* launcher's own ([Motion]), and off when animations are off.
*/
private fun animateDock(hud: DroidDeckHudView, edge: DroidDeckHudDock, commit: () -> Unit) {
hud.animate().cancel()
hud.scaleX = 1f; hud.scaleY = 1f; hud.alpha = 1f
private fun settleOutOfTab(hud: DroidDeckHudView, tabX: Float, tabY: Float) {
val p = hud.parent as? View
if (Motion.scale == 0f || p == null || !hud.isLaidOut || hud.width <= 0) { commit(); return }
val maxX = if (p == null) Float.MAX_VALUE else (p.width - hud.contentWidth).coerceAtLeast(0f)
val maxY = if (p == null) Float.MAX_VALUE else (p.height - hud.contentHeight).coerceAtLeast(0f)
wantX = tabX.coerceIn(0f, maxX); wantY = tabY.coerceIn(0f, maxY)
anchorX = if (snaps && !hud.isStrip && p != null) (if (wantX < maxX / 2f) 0f else 1f) else Float.NaN
if (!anchorX.isNaN()) wantX = anchorX * maxX
SessionPrefs.setDroidDeckHudPosition(context, wantX, wantY)
}
private fun animateDock(hud: DroidDeckHudView, edge: DroidDeckHudDock, commit: () -> Unit) {
stopMotion(hud)
previewFade?.cancel(); previewFade = null
snapping = false
hud.alpha = 1f
val p = hud.parent as? View
if (Motion.scale == 0f || p == null || !hud.isLaidOut || hud.width <= 0) {
hud.scaleX = 1f; hud.scaleY = 1f
hud.setDockPreview(DroidDeckHudDock.NONE, 0f)
commit(); return
}
if (edge != DroidDeckHudDock.NONE) {
val left = hud.x + hud.pivotX * (1f - hud.scaleX); val top = hud.y + hud.pivotY * (1f - hud.scaleY)
val shownW = hud.width * hud.scaleX; val shownH = hud.height * hud.scaleY
hud.pivotX = 0f; hud.pivotY = 0f
hud.x = left; hud.y = top
val (tabW, tabH) = hud.dockTabSize()
wantX = left + (shownW - tabW) / 2f
wantY = top + (shownH - tabH) / 2f
val (tabX, tabY) = settled(p, edge, tabW, tabH)
val sx = tabW / hud.width; val sy = tabH / hud.height
hud.pivotX = pivotFor(hud.x, tabX, sx) - hud.x
hud.pivotY = pivotFor(hud.y, tabY, sy) - hud.y
hud.animate().scaleX(sx).scaleY(sy).setDuration(Motion.ms(300).toLong()).setInterpolator(EASE)
val from = hud.dockPreviewBlend
hud.animate().x(tabX).y(tabY).scaleX(sx).scaleY(sy).setDuration(Motion.ms(220).toLong()).setInterpolator(EASE)
.setUpdateListener { hud.setDockPreview(edge, from + (1f - from) * it.animatedFraction) }
.withEndAction {
hud.animate().setUpdateListener(null)
commit()
hud.setDockPreview(DroidDeckHudDock.NONE, 0f)
hud.scaleX = 1f; hud.scaleY = 1f
hud.x = tabX; hud.y = tabY
hud.alpha = 0.5f
hud.animate().alpha(1f).setDuration(Motion.ms(120).toLong()).start()
}.start()
} else {
hud.scaleX = 1f; hud.scaleY = 1f
val was = hud.dock
val tabX = hud.x; val tabY = hud.y
val tabW = hud.width.toFloat(); val tabH = hud.height.toFloat()
commit()
@@ -305,15 +439,20 @@ class DroidDeckHudHost(context: Context) {
hud.pivotX = pivotFor(x, tabX, sx) - x
hud.pivotY = pivotFor(y, tabY, sy) - y
hud.scaleX = sx; hud.scaleY = sy
hud.animate().scaleX(1f).scaleY(1f).setDuration(Motion.ms(360).toLong()).setInterpolator(EASE).start()
hud.setDockPreview(was, 1f)
hud.animate().scaleX(1f).scaleY(1f).setDuration(Motion.ms(360).toLong()).setInterpolator(EASE)
.setUpdateListener {
val f = (1f - it.animatedFraction / EXPAND_FADE).coerceIn(0f, 1f)
hud.setDockPreview(was, f * f * (3f - 2f * f))
}
.withEndAction { hud.animate().setUpdateListener(null); hud.setDockPreview(DroidDeckHudDock.NONE, 0f) }
.start()
}
}
/** The pivot, in parent coordinates, that scaling by [scale] takes a span starting at [from] onto one starting at [to]. */
private fun pivotFor(from: Float, to: Float, scale: Float): Float =
if (scale > 0.999f) from else (to - from * scale) / (1f - scale)
/** Where a [w] x [h] HUD or tab sits once [keepOnScreen] has settled it against [dock]. */
private fun settled(p: View, dock: DroidDeckHudDock, w: Float, h: Float): Pair<Float, Float> {
val maxX = (p.width - w).coerceAtLeast(0f); val maxY = (p.height - h).coerceAtLeast(0f)
var x = wantX.coerceIn(0f, maxX); var y = wantY.coerceIn(0f, maxY)
@@ -327,15 +466,18 @@ class DroidDeckHudHost(context: Context) {
return Pair(x, y)
}
// The HUD is clamped from where the user left it (wantX/wantY, set on a drop or restore), not from where
// it is drawn: a window that shrinks and grows back (picture-in-picture, a fold) must not leave it in the
// corner the small window pushed it to.
private fun keepOnScreen(v: View) {
if (snapping) return
val p = v.parent as? View ?: return
if (p.width <= 0 || p.height <= 0 || v.width <= 0 || v.height <= 0) return
if (wantX.isNaN()) { wantX = v.x; wantY = v.y }
val maxX = (p.width - v.width).toFloat().coerceAtLeast(0f)
val maxY = (p.height - v.height).toFloat().coerceAtLeast(0f)
val anchored = (v as? DroidDeckHudView)?.let { it.dock == DroidDeckHudDock.NONE && !it.isStrip } == true
if (snaps && anchored && anchorX.isNaN()) {
anchorX = if (wantX.coerceIn(0f, maxX) < maxX / 2f) 0f else 1f
}
if (snaps && anchored && !anchorX.isNaN()) wantX = anchorX * maxX
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
@@ -351,18 +493,19 @@ class DroidDeckHudHost(context: Context) {
}
companion object {
/** How much of the HUD, as a share of its own size, must hang past a screen edge for it to dock there. */
private const val DOCK_OVERHANG = 0.4f
private const val FLING_REACH_S = 0.18f
private const val PREVIEW_FROM = 0.55f
private const val STRIP_PULL_ACROSS_DP = 600f
private const val STRIP_PULL_OFF_DP = 150f
private const val EXPAND_FADE = 0.5f
private val EASE = PathInterpolator(0.2f, 0.8f, 0.2f, 1f)
/** True while the HUD is on screen; DroidDeck keeps sampling VRAM for it (GpuMemComponent). */
@Volatile @JvmStatic var showing = false
private set
/** "Adreno (TM) 750" as the driver names it, "Adreno 750" as DroidDeck does elsewhere. */
internal fun cleanGpuName(name: String): String = name.replace("(TM)", "").replace(Regex("\\s+"), " ").trim()
/** The Proton build of a game process: the first STEAM_COMPAT_TOOL_PATHS entry's folder. */
internal fun protonName(pid: Int): String? = runCatching {
val environ = File("/proc/$pid/environ").readBytes().toString(Charsets.UTF_8).split('\u0000')
val paths = environ.firstOrNull { it.startsWith("STEAM_COMPAT_TOOL_PATHS=") }?.substringAfter('=') ?: return null
@@ -8,16 +8,11 @@
* link to https://github.com/The412Banner/FusionHUD in the project documentation
* AND in the in-app credits/about screen.
*
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code.
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD) and modified for DroidDeck.
*/
package com.droiddeck.launcher.hud
/**
* Size modes for the DroidDeck HUD (the 4th selectable in-game overlay style). One shared color-coded
* visual language, four amounts of detail — see the approved mockup. The config value is the lower-case
* token stored under the `hudSize` key; the label is the user-facing string.
*/
enum class DroidDeckHudSize(val token: String, val label: String) {
FULL("full", "Full"),
TILES("tiles", "Tiles"),
@@ -26,18 +21,11 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
MEGA("mega", "Mega"),
STRIP("strip", "Strip");
/** 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]
}
/**
* The metric toggle chips this size actually renders — the SINGLE source of truth queried by BOTH
* config surfaces ({@code FpsCounterConfigDialog} + in-game {@code XServerDrawer} HudContent) so the
* chip list can't drift from what the view draws. Chip ids are the chip LABELS used in the UI.
* (Hiding a chip is purely UI; buildConfig() still emits every key — strip-invariant.)
*/
fun supportedChips(): Set<String> = when (this) {
MINIMAL -> MINIMAL_CHIPS
PILL -> PILL_CHIPS
@@ -49,11 +37,6 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
fun from(token: String?): DroidDeckHudSize =
values().firstOrNull { it.token.equals(token, ignoreCase = true) } ?: FULL
// Chip-label ids (must match the labels the config UIs build). "Clock" is a small subtle
// corner readout available in EVERY size, so it's in all sets.
// The API/engine label ("Engine" chip) shows on the FPS row in EVERY size, so it's in all sets.
// "Wrapper" and "DX ver" are Mega-only: the wrapper appears solely below Mega's frametime graph,
// and "DX ver" gates the DX-version suffix on Mega's FPS-row engine label.
val MINIMAL_CHIPS = setOf("FPS", "FPS graph", "0.01% low", "FPS .1", "Engine", "Clock")
val PILL_CHIPS = setOf("FPS", "FPS graph", "GPU", "CPU", "VRAM", "RAM", "Battery", "GPU model", "FPS .1", "Engine", "Clock")
val STANDARD_CHIPS = setOf(
@@ -67,7 +50,6 @@ enum class DroidDeckHudSize(val token: String, val label: String) {
}
}
/** The screen edge the HUD is tucked against, where only its FPS tab shows ([NONE] = floating free). */
enum class DroidDeckHudDock(val token: String) {
NONE("none"), LEFT("left"), RIGHT("right"), TOP("top"), BOTTOM("bottom");
@@ -76,21 +58,12 @@ enum class DroidDeckHudDock(val token: String) {
}
}
/**
* The Wayland HDR state the DroidDeck HUD shows on its own line, directly under the latency · display-server
* line (the host sets it with [DroidDeckHudView.setHdrState]). [NONE] = no line at all: every session whose
* HDR gate is closed (X11, SDR screens, HDR off) keeps the HUD exactly as it was.
*/
object DroidDeckHudHdr {
const val NONE = 0
const val ON = 1 // HDR frames on screen with HDR headroom
const val NO_HEADROOM = 2 // HDR frames on screen, but the display gives them no headroom (5 s+)
const val OFF = 3 // the drawer's HDR output switch is off (tone-mapped to SDR)
const val READY = 4 // HDR open for the session, no HDR frames on screen right now
const val TONEMAPPED = 5 // HDR output on, but the frames are shown tone-mapped (frame generation
// on a screen that offers no HDR10 swapchain)
const val NOT_ON_THIS_SCREEN = 6 // HDR open for the session, but the screen the game is on NOW
// reports no HDR10 (the TV was unplugged mid-game). The offer to the
// game cannot be withdrawn once made, so the gate stays open for the
// session — but "ready" would be a lie on a panel that cannot show it.
const val ON = 1
const val NO_HEADROOM = 2
const val OFF = 3
const val READY = 4
const val TONEMAPPED = 5
const val NOT_ON_THIS_SCREEN = 6
}
@@ -8,7 +8,7 @@
* link to https://github.com/The412Banner/FusionHUD in the project documentation
* AND in the in-app credits/about screen.
*
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code.
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD) and modified for DroidDeck.
*/
package com.droiddeck.launcher.hud
@@ -24,9 +24,9 @@ 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 android.view.ViewConfiguration
import androidx.annotation.VisibleForTesting
import androidx.compose.ui.graphics.toArgb
import com.droiddeck.launcher.session.SessionPrefs
@@ -53,28 +53,12 @@ import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeoutOrNull
/**
* DroidDeck HUD — the 4th selectable in-game overlay. One color-coded visual language rendered at four
* SIZE modes (Full / Tiles / Pill / Minimal / Mega), all driven by [FrameStats] (gamescope's frame times
* read by MangoHud's rules) + a single cached [HudMetrics.Snapshot]. Pure Canvas drawing.
*
* DroidDeck: the readouts refresh every 500 ms (MangoHud's sampling period) on a Main-dispatcher
* coroutine, collecting the snapshot on Dispatchers.IO; the frame graph is redrawn whenever new frames
* arrive ([onFrames]), as MangoHud draws it.
*
* Gestures go through [HudLockController]: long-press toggles the position lock (with a lock/unlock
* badge fade), a tap cycles the size (Full→Tiles→Pill→Minimal→Full), and a drag repositions — tap +
* drag are frozen while locked. A locked HUD lets a touch through where an on-screen control under it
* takes it ([passesTouchAt]); everywhere else it keeps the touch, so a long press there unlocks it.
*/
class DroidDeckHudView(context: Context) : View(context) {
private var frames: FrameStats? = null
internal fun setFrameStats(stats: FrameStats?) { frames = stats }
internal fun setMangoReadings(readings: MangoReadings?) { metrics.setMangoReadings(readings) }
// Frames per second actually reaching the panel while DroidDeck's frame generation adds frames the
// game never made; 0 = nothing is adding frames, and the readout is the game's rate alone.
private var presentedFps = 0f
fun setPresentedFps(fps: Float) { presentedFps = fps }
@@ -85,7 +69,6 @@ class DroidDeckHudView(context: Context) : View(context) {
private val density = resources.displayMetrics.density
// ---- Config -----------------------------------------------------------
private var size = DroidDeckHudSize.FULL
private var scale = 1f
private var bgOpacity = 0.8f
@@ -109,8 +92,7 @@ class DroidDeckHudView(context: Context) : View(context) {
private var showGraph = false
private var showLow001 = true
private var fpsDecimal = true
private var showClockTime = true // subtle corner/footer clock, available in EVERY size
// Mega-only rows
private var showClockTime = true
private var showPerCore = true
private var showSwap = true
private var showNet = true
@@ -121,21 +103,15 @@ class DroidDeckHudView(context: Context) : View(context) {
private var showSession = true
private var engineLabel = ""
private var displayServer = "" // "X11" / "Wayland": which display server the game runs on
private var hdrState = DroidDeckHudHdr.NONE // Wayland HDR, on its own line under latency · display server
private var displayServer = ""
private var hdrState = DroidDeckHudHdr.NONE
private var gpuModel = ""
// The GPU name a Wayland session reports to games instead of the real adapter ("" = none). It has
// to travel separately from gpuModel: Wayland hands the spoof to DXVK and leaves the Vulkan device
// alone, so everything the host reads back is still the real chip. On X11 the driver wrapper renames
// the device itself, so there gpuModel already IS the spoofed name and this stays empty.
private var gpuSpoofName = ""
// Stack-layer version strings (Mega bottom band + DX version on the engine row); fed by the host.
private var wineVersion = "" // "Proton 10.0-4"
private var graphicsWrapper = "" // graphics-driver wrapper package, e.g. "GameNative", "bcn_layer 20260719"
private var dxvkVersion = "" // DXVK version, appended to a DXVK engine row
private var vkd3dVersion = "" // VKD3D version, appended to a VKD3D engine row
private var wineVersion = ""
private var graphicsWrapper = ""
private var dxvkVersion = ""
private var vkd3dVersion = ""
// ---- Live data (updated on the refresh coroutine, read on draw) --------
private var snap: HudMetrics.Snapshot? = null
private var fpsNow = 0f
private var fpsAvg = 0f
@@ -146,25 +122,17 @@ class DroidDeckHudView(context: Context) : View(context) {
private val graphPath = Path()
private var resolution = ""
// DroidDeck look: the theme's main colour for the FPS label, graph and accent outline, the theme's
// surface behind the readouts, a DroidDeck header (wordmark) on Full/Tiles/Minimal/Mega and the logo
// chip on the Pill.
private var accent = 0xFF1A9FFF.toInt()
private var surfaceRgb = 0x121417
private var headerMark: RectF? = null
private var chipRect: RectF? = null
// Pushed past a screen edge, the HUD shrinks to a tab with the FPS that stays at that edge.
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
// right. Its fixed layers (fill, header band, watermark, glowing outline) go into a bitmap, because
// Android before 9 skips glow on shapes drawn with hardware acceleration.
private var dPanel: RectF? = null
private var dRadius = 0f
private var dDividerTop = -1f
@@ -172,7 +140,6 @@ class DroidDeckHudView(context: Context) : View(context) {
private var dFrameKey = ""
private val glowPaint = Paint(Paint.ANTI_ALIAS_FLAG)
// ---- Colors (mockup) --------------------------------------------------
private val colGpu = 0xFF5EE08A.toInt()
private val colCpu = 0xFF58A6FF.toInt()
private val colVram = 0xFFC98BFF.toInt()
@@ -183,10 +150,9 @@ class DroidDeckHudView(context: Context) : View(context) {
private val colValue = 0xFFF2F5F9.toInt()
private val colDim = 0xFF9AA4B2.toInt()
private val colLo = 0xFFE4E8EE.toInt()
private val colDisp = 0xFF4DD0E1.toInt() // display server (X11 / Wayland)
private val colHdr = 0xFFFFD54F.toInt() // HDR on screen
private val colDisp = 0xFF4DD0E1.toInt()
private val colHdr = 0xFFFFD54F.toInt()
// ---- Paints -----------------------------------------------------------
private val measurePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
typeface = Typeface.create(Typeface.MONOSPACE, Typeface.BOLD)
}
@@ -205,16 +171,10 @@ class DroidDeckHudView(context: Context) : View(context) {
typeface = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD)
}
// ---- Built geometry ---------------------------------------------------
private class Glyph(val x: Float, val baseline: Float, val text: String, val color: Int, val sizePx: Float, val sans: Boolean = false, val glow: Boolean = false) {
fun moved(dx: Float, dy: Float) = Glyph(x + dx, baseline + dy, text, color, sizePx, sans, glow)
}
private class Span(val text: String, val color: Int, val sizePx: Float, val glow: Boolean = false)
/**
* A "label + value-run" row for the aligned grid sizes (Full / Mega). When [inline] is true the row
* opts OUT of the shared label column — its value run is placed directly after the label — so a long
* label (the graphics-wrapper on the FPS row) can't widen the column and shove every value right.
*/
private class HudRow(val label: Span, val vals: List<Span>, val inline: Boolean = false)
private val glyphs = ArrayList<Glyph>()
private val tileRects = ArrayList<RectF>()
@@ -222,7 +182,6 @@ class DroidDeckHudView(context: Context) : View(context) {
private var contentW = 0f
private var contentH = 0f
// ---- Listeners --------------------------------------------------------
private var onMovedListener: BiConsumer<Float, Float>? = null
private var onSizeCycledListener: Consumer<String>? = null
private var onLockChangedListener: Consumer<Boolean>? = null
@@ -231,13 +190,18 @@ class DroidDeckHudView(context: Context) : View(context) {
fun setOnLockChangedListener(l: Consumer<Boolean>?) { onLockChangedListener = l }
private var onDockChangedListener: Consumer<String>? = null
private var onScaledListener: IntConsumer? = null
private var onDraggedListener: BiConsumer<Float, Float>? = null
fun setOnDraggedListener(l: BiConsumer<Float, Float>?) { onDraggedListener = l }
private var onFlungListener: BiConsumer<Float, Float>? = null
fun setOnFlungListener(l: BiConsumer<Float, Float>?) { onFlungListener = l }
fun setOnDockChangedListener(l: Consumer<String>?) { onDockChangedListener = l }
/** A pinch settled on this size, in percent. */
fun setOnScaledListener(l: IntConsumer?) { onScaledListener = l }
private val lockController = HudLockController(context, this, object : HudLockController.Callbacks {
override fun onTap() { cycleSize() }
override fun onMoved(x: Float, y: Float) { onMovedListener?.accept(x, y) }
override fun onDragged(rawX: Float, rawY: Float) { onDraggedListener?.accept(rawX, rawY) }
override fun onFlung(velocityX: Float, velocityY: Float) { onFlungListener?.accept(velocityX, velocityY) }
override fun onLockChanged(locked: Boolean) { onLockChangedListener?.accept(locked) }
override fun onPinch(factor: Float) {
val next = (scale * factor).coerceIn(MIN_SCALE, MAX_SCALE)
@@ -248,50 +212,62 @@ class DroidDeckHudView(context: Context) : View(context) {
override fun onPinchEnd() { onScaledListener?.accept((scale * 100f).roundToInt()) }
})
// A docked tab always takes touches, locked or not: a tap or a pull away from the edge brings the HUD back.
private val dockDetector = GestureDetector(context, object : GestureDetector.SimpleOnGestureListener() {
override fun onDown(e: MotionEvent): Boolean = true
override fun onSingleTapUp(e: MotionEvent): Boolean { onDockChangedListener?.accept(DroidDeckHudDock.NONE.token); return true }
override fun onScroll(e1: MotionEvent?, e2: MotionEvent, distanceX: Float, distanceY: Float): Boolean {
if (e1 == null) return false
val inward = when (dock) {
DroidDeckHudDock.LEFT -> e2.rawX - e1.rawX
DroidDeckHudDock.RIGHT -> e1.rawX - e2.rawX
DroidDeckHudDock.TOP -> e2.rawY - e1.rawY
DroidDeckHudDock.BOTTOM -> e1.rawY - e2.rawY
DroidDeckHudDock.NONE -> 0f
private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop
private var tabDownRawX = 0f
private var tabDownRawY = 0f
private var tabStartX = 0f
private var tabStartY = 0f
private var tabDragging = false
private var onTabDraggedListener: BiConsumer<Float, Float>? = null
private var onTabDroppedListener: Runnable? = null
private var onTabDragCancelledListener: Runnable? = null
fun setOnTabDraggedListener(l: BiConsumer<Float, Float>?) { onTabDraggedListener = l }
fun setOnTabDroppedListener(l: Runnable?) { onTabDroppedListener = l }
fun setOnTabDragCancelledListener(l: Runnable?) { onTabDragCancelledListener = l }
private fun onTabTouch(event: MotionEvent): Boolean {
when (event.actionMasked) {
MotionEvent.ACTION_DOWN -> {
tabDownRawX = event.rawX; tabDownRawY = event.rawY
tabStartX = x; tabStartY = y
tabDragging = false
}
if (inward > 12f * density) onDockChangedListener?.accept(DroidDeckHudDock.NONE.token)
return true
MotionEvent.ACTION_MOVE -> {
val dx = event.rawX - tabDownRawX; val dy = event.rawY - tabDownRawY
if (!tabDragging && dx * dx + dy * dy > touchSlop * touchSlop) tabDragging = true
if (tabDragging) onTabDraggedListener?.accept(tabStartX + dx, tabStartY + dy)
}
MotionEvent.ACTION_UP -> {
if (tabDragging) { tabDragging = false; onTabDroppedListener?.run() }
else onDockChangedListener?.accept(DroidDeckHudDock.NONE.token)
}
MotionEvent.ACTION_CANCEL -> if (tabDragging) {
tabDragging = false
onTabDragCancelledListener?.run()
}
}
})
return true
}
private var previewEdge = DroidDeckHudDock.NONE
private var previewBlend = 0f
internal fun setDockPreview(edge: DroidDeckHudDock, blend: Float) {
val b = blend.coerceIn(0f, 1f)
if (edge == previewEdge && b == previewBlend) return
previewEdge = edge; previewBlend = b
invalidate()
}
internal val dockPreviewBlend: Float get() = previewBlend
// ---- Public surface (symmetric with the other overlays) ---------------
fun setEngineLabel(s: String?) { if ((s ?: "") != engineLabel) { engineLabel = s ?: ""; post { rebuildAndInvalidate() } } }
fun setGpuModel(s: String?) { if ((s ?: "") != gpuModel) { gpuModel = s ?: ""; post { rebuildAndInvalidate() } } }
/** This session's Wayland GPU-name spoof (null / empty = none, the default): the GPU row names it
* in place of the real model, marked so it can't be read as the chip that is really rendering. */
fun setGpuSpoofName(s: String?) { gpuSpoofName = s ?: ""; post { rebuildAndInvalidate() } }
fun setDisplayServer(s: String?) { displayServer = s ?: ""; post { rebuildAndInvalidate() } }
/** [DroidDeckHudHdr] code; [DroidDeckHudHdr.NONE] (the default) draws no HDR line anywhere. Any thread. */
fun setHdrState(state: Int) {
val v = if (state in DroidDeckHudHdr.ON..DroidDeckHudHdr.NOT_ON_THIS_SCREEN) state else DroidDeckHudHdr.NONE
post { if (v != hdrState) { hdrState = v; rebuildAndInvalidate() } }
}
fun setWineVersion(s: String?) { if ((s ?: "") != wineVersion) { wineVersion = s ?: ""; post { rebuildAndInvalidate() } } }
fun setGraphicsWrapper(s: String?) { graphicsWrapper = s ?: ""; post { rebuildAndInvalidate() } }
fun setDxWrapper(dxvk: String?, vkd3d: String?) {
dxvkVersion = dxvk ?: ""; vkd3dVersion = vkd3d ?: ""; post { rebuildAndInvalidate() }
}
/** The game's output from gamescope ("1280x720 @ 144Hz"), as MangoHud shows it; "" = this display. */
fun setResolution(s: String?) { resolution = s ?: "" }
private val periodDone = Channel<Unit>(Channel.CONFLATED)
private var seenFpsUpdates = 0L
/** New frames arrived: redraw the graph (MangoHud redraws it every frame), and the readouts when a
* sampling period completed, at the moment MangoHud redraws its own. */
fun onFrames() {
val updates = frames?.fpsUpdates ?: 0L
if (updates != seenFpsUpdates) {
@@ -301,10 +277,6 @@ class DroidDeckHudView(context: Context) : View(context) {
if (graphRect != null) invalidate()
}
/** The HUD has no orientation (tap cycles size instead); kept for a symmetric host surface. */
fun setVertical(vertical: Boolean) { /* no-op */ }
fun isVertical(): Boolean = false
private fun cycleSize() {
size = size.next()
onSizeCycledListener?.accept(size.token)
@@ -331,7 +303,7 @@ class DroidDeckHudView(context: Context) : View(context) {
showGraph = cfg.get("showFPSGraph", "0") == "1"
showLow001 = cfg.get("showLow001", "1") == "1"
fpsDecimal = cfg.get("fpsDecimal", "1") == "1"
showClockTime = cfg.get("showClock", "1") == "1" // the clock defaults ON
showClockTime = cfg.get("showClock", "1") == "1"
showPerCore = cfg.get("showPerCore", "1") == "1"
showSwap = cfg.get("showSwap", "1") == "1"
showNet = cfg.get("showNet", "1") == "1"
@@ -356,7 +328,6 @@ class DroidDeckHudView(context: Context) : View(context) {
rebuildAndInvalidate()
}
// ---- Lifecycle: self-refresh ------------------------------------------
override fun onAttachedToWindow() {
super.onAttachedToWindow()
if (isShown) startUpdates()
@@ -367,8 +338,6 @@ class DroidDeckHudView(context: Context) : View(context) {
super.onDetachedFromWindow()
}
// The host hides the HUD with GONE (HUD off, picture-in-picture) and keeps it attached: read the
// sensors only while it shows.
override fun onVisibilityChanged(changedView: View, visibility: Int) {
super.onVisibilityChanged(changedView, visibility)
if (isAttachedToWindow && isShown) startUpdates() else stopUpdates()
@@ -397,13 +366,11 @@ class DroidDeckHudView(context: Context) : View(context) {
graphMaxMs = stats?.graphMaxMs() ?: 0f
onRefresh?.run()
rebuildAndInvalidate()
// Without frames (a still screen) MangoHud redraws nothing; the HUD keeps refreshing.
withTimeoutOrNull(REFRESH_MS) { periodDone.receive() }
}
}
}
/** Runs on the main thread just before each readout refresh, for the host's labels. */
var onRefresh: Runnable? = null
private fun applyTheme() {
@@ -418,10 +385,6 @@ class DroidDeckHudView(context: Context) : View(context) {
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
@@ -463,7 +426,6 @@ class DroidDeckHudView(context: Context) : View(context) {
invalidate()
}
// ---- Text helpers -----------------------------------------------------
private fun blend(color: Int): Int {
val i = colorIntensity.coerceIn(0f, 1f)
if (i >= 0.999f) return color
@@ -496,27 +458,19 @@ class DroidDeckHudView(context: Context) : View(context) {
private fun one(v: Float): String =
if (fpsDecimal) String.format(Locale.US, "%.1f", v) else v.roundToInt().toString()
// Shows "30->118" while something downstream of the game is adding frames.
// The game's own rate stays visible next to the panel rate, because the gap
// between the two is precisely what frame generation is doing.
private fun fpsText(v: Float): String =
if (differs(v)) "${one(v)}\u2192${one(presentedFps)}" else one(v)
// Either direction: up = frames added (LSFG Native), down = frames lost
// between the guest and the panel, which is the failure win-fg can hit
// and which a single number hides completely.
private fun differs(v: Float): Boolean =
presentedFps > 0f && kotlin.math.abs(presentedFps - v) > maxOf(1f, v * 0.10f)
private fun fmt1(v: Float): String = String.format(Locale.US, "%.1f", v)
private fun lowText(v: Float): String? = if (v <= 0f) null else fmt1(v)
// number (white, or "—" muted when null) + unit (muted, smaller)
private fun numUnit(num: String?, unit: String, numPx: Float, unitPx: Float): List<Span> =
if (num == null) listOf(Span("—", colDim, numPx), Span(unit, colDim, unitPx))
else listOf(Span(num, colValue, numPx), Span(unit, colDim, unitPx))
// "0.2GiB"/"75%"/"1938MHz" → white number + muted suffix
private fun valueUnit(text: String, numPx: Float, unitPx: Float): List<Span> {
val i = text.indexOfFirst { !(it.isDigit() || it == '.' || it == '-') }
return if (i <= 0) listOf(Span(text, colValue, numPx))
@@ -525,7 +479,7 @@ class DroidDeckHudView(context: Context) : View(context) {
private fun tempSpans(c: Int?, sensor: HudMetrics.TempSensor, numPx: Float, unitPx: Float): List<Span> {
if (c == null) return emptyList()
val txt = HudMetrics.formatTemp(c.toFloat(), tempDisplay, false) // "81°C"
val txt = HudMetrics.formatTemp(c.toFloat(), tempDisplay, false)
val col = HudMetrics.tempColor(
c.toFloat(), metrics.resolveThresholds(sensor, tempDisplay), tempDisplay, colValue)
val i = txt.indexOf('°')
@@ -535,13 +489,9 @@ class DroidDeckHudView(context: Context) : View(context) {
private fun gap(unitPx: Float) = Span(" ", colDim, unitPx)
/** The frame-rate number in neon, as on Minimal. */
private fun glowing(spans: List<Span>): List<Span> =
spans.mapIndexed { i, s -> if (i == 0) Span(s.text, s.color, s.sizePx, glow = true) else s }
// ---- Wayland HDR state (one line of its own; nothing at all for DroidDeckHudHdr.NONE) ----
/** The state as a full line: "HDR", "HDR (no headroom)", "HDR off", "HDR ready", "HDR tone-mapped",
* "HDR not on this screen". */
private fun hdrLine(px: Float): List<Span> = when (hdrState) {
DroidDeckHudHdr.ON -> listOf(Span("HDR", colHdr, px))
DroidDeckHudHdr.NO_HEADROOM -> listOf(Span("HDR", colHdr, px), Span(" (no headroom)", colBat, px))
@@ -551,8 +501,6 @@ class DroidDeckHudView(context: Context) : View(context) {
DroidDeckHudHdr.NOT_ON_THIS_SCREEN -> listOf(Span("HDR", colDim, px), Span(" not on this screen", colBat, px))
else -> emptyList()
}
/** The value after an "HDR" label (Full / Mega): "on", "no headroom", "off", "ready", "tone-mapped",
* "not on this screen". */
private fun hdrValue(px: Float): List<Span> = when (hdrState) {
DroidDeckHudHdr.ON -> listOf(Span("on", colHdr, px))
DroidDeckHudHdr.NO_HEADROOM -> listOf(Span("no headroom", colBat, px))
@@ -564,12 +512,7 @@ class DroidDeckHudView(context: Context) : View(context) {
}
private fun hdrText(): String = hdrLine(1f).joinToString("") { it.text }
// ---- GPU model (with the Wayland GPU-name spoof) ----
/** What the GPU row names: the spoofed GPU when this session reports one, else the real model. */
private fun gpuNameText(): String = gpuSpoofName.ifBlank { gpuModel }
/** The GPU row's value run. A spoofed name carries a marker in the same warning colour the HDR line
* qualifies its state with, so the row can't be read as the chip that is really rendering:
* "GeForce GTX 1080 (spoof)", and where the line is tightest (the pill) "GeForce GTX 1080 spoof". */
private fun gpuModelSpans(px: Float, color: Int, compact: Boolean = false): List<Span> {
val name = Span(gpuNameText(), color, px)
if (gpuSpoofName.isBlank()) return listOf(name)
@@ -578,7 +521,6 @@ class DroidDeckHudView(context: Context) : View(context) {
private val inkRect = android.graphics.Rect()
// ---- Layout builders --------------------------------------------------
private fun rebuild() {
glyphs.clear(); tileRects.clear(); graphRect = null
headerMark = null; chipRect = null; dPanel = null; dDividerTop = -1f; tabRect = null; stripRect = null
@@ -595,27 +537,25 @@ class DroidDeckHudView(context: Context) : View(context) {
}
}
/** The docked tab: the FPS alone, in a box square on the edge it sits against. */
private fun buildDockTab() {
val numPx = sp(20f)
val numPx = sp(TAB_NUM_SP)
val spans = tabSpans()
val padX = sp(9f); val padY = sp(7f)
val padX = sp(TAB_PAD_X_SP); val padY = sp(TAB_PAD_Y_SP)
placeRun(padX, padY + capHeight(numPx), spans)
val (w, h) = dockTabSize()
contentW = w; contentH = h
tabRect = RectF(0f, 0f, contentW, contentH)
}
private fun tabSpans() = listOf(Span(one(fpsNow), colValue, sp(20f)), Span("fps", colDim, sp(8.5f)))
private fun tabSpans() = listOf(Span(one(fpsNow), colValue, sp(TAB_NUM_SP)), Span("fps", colDim, sp(TAB_LABEL_SP)))
/** The size the docked tab has, so the HUD can contract to exactly that shape before the tab replaces it. */
internal fun dockTabSize(): Pair<Float, Float> =
Pair(runWidth(tabSpans()) + 2f * sp(9f), capHeight(sp(20f)) + 2f * sp(7f))
Pair(runWidth(tabSpans()) + 2f * sp(TAB_PAD_X_SP), capHeight(sp(TAB_NUM_SP)) + 2f * sp(TAB_PAD_Y_SP))
private fun drawTab(canvas: Canvas, rect: RectF) {
val r = sp(8f); val stroke = max(outlineWidth(), sp(1.5f)); val h = stroke / 2f
private fun drawTab(canvas: Canvas, rect: RectF, edgeOf: DroidDeckHudDock = dock) {
val r = sp(8f); val stroke = outlineWidth(); val h = stroke / 2f
val round = floatArrayOf(r, r, r, r, r, r, r, r)
val edge = when (dock) {
val edge = when (edgeOf) {
DroidDeckHudDock.LEFT -> intArrayOf(0, 3)
DroidDeckHudDock.RIGHT -> intArrayOf(1, 2)
DroidDeckHudDock.TOP -> intArrayOf(0, 1)
@@ -628,23 +568,20 @@ class DroidDeckHudView(context: Context) : View(context) {
headerPaint.shader = null
headerPaint.color = withAlpha(panelColor(), max(Color.alpha(panelColor()), 200))
canvas.drawPath(tabPath, headerPaint)
if (stroke <= 0f) return
strokePaint.strokeWidth = stroke
strokePaint.color = outlineColor()
canvas.drawPath(tabPath, strokePaint)
}
// ---- DroidDeck panel, header and chip -----------------------------------
/** The clock sits in the header on every size but the Pill, which keeps it under the FPS. */
private fun footerClock(): Boolean = showClockTime && size == DroidDeckHudSize.PILL
private fun measureSans(text: String, sizePx: Float): Float { wordmarkPaint.textSize = sizePx; return wordmarkPaint.measureText(text) }
private fun panelInset() = sp(8f) // room for the glow around the panel
private fun panelLeft() = sp(13f) // the outline's glow sticks out of the left side
private fun panelInset() = sp(8f)
private fun panelLeft() = sp(13f)
private fun contentLeft() = panelLeft() + sp(16f)
/** The DroidDeck mark, "DroidDeck" and the clock across the top, starting on [left], with the same
* space above and below the mark. Returns the header's bottom edge and its right end. */
private fun addPanelHeader(left: Float, inner: Float): Pair<Float, Float> {
val wordPx = sp(10f); val clockPx = sp(9.5f); val gapH = sp(7f)
wordmarkPaint.textSize = wordPx
@@ -672,11 +609,6 @@ class DroidDeckHudView(context: Context) : View(context) {
return Pair(dDividerTop + max(1f, density), x)
}
/**
* Moves a size's content, laid out from [pad] at the origin, into the panel: under the header, or after
* the logo chip on the Pill. Lines that start on the content's left edge are lined up by their ink, so
* the logo, labels and numbers share one edge.
*/
private fun intoPanel(pad: Float, header: Boolean) {
if (contentW <= 0f || contentH <= 0f) return
for (i in glyphs.indices) {
@@ -706,8 +638,6 @@ class DroidDeckHudView(context: Context) : View(context) {
finishPanel(panel, halfRound = !header)
}
/** Closes the panel around everything placed so far, widened until no line, tile or graph reaches the
* round side: a half circle on the short sizes (Pill, Minimal), large round corners on the tall ones. */
private fun finishPanel(panel: RectF, halfRound: Boolean) {
val r = if (halfRound) panel.height() / 2f else min(panel.height() / 2f, sp(56f))
val margin = outlineWidth() + sp(4f)
@@ -731,7 +661,6 @@ class DroidDeckHudView(context: Context) : View(context) {
contentH = panel.bottom + panelInset()
}
// ---- Shared small-info helpers ----------------------------------------
private fun clockTimeString(): String = DateFormat.getTimeFormat(context).format(Date())
private fun elapsedString(): String {
@@ -741,31 +670,21 @@ class DroidDeckHudView(context: Context) : View(context) {
else String.format(Locale.US, "%02d:%02d", m, s)
}
/**
* The FPS row's API/engine label — the DX→Vulkan translator ([engineLabel]: "DXVK"/"VKD3D"/"Zink"),
* gated by the "Engine" chip. This is short and shows in EVERY size. Falls back to a bare "FPS" when
* the toggle is off or no engine label is set. (The graphics WRAPPER is separate — Mega-only, drawn
* below the frametime graph — not on the FPS row.)
*/
private fun apiLabel(): String =
if (showEngine && engineLabel.isNotBlank()) engineLabel else "FPS"
/** The DX-wrapper version WITH its engine name (e.g. "DXVK 2.4.1", "VKD3D 2.14"), or "" if none.
* Used for the Mega stack line below the graph. */
private fun dxVersionLabeled(): String = when {
engineLabel.contains("VKD3D", true) && vkd3dVersion.isNotBlank() -> "VKD3D $vkd3dVersion"
engineLabel.contains("DXVK", true) && dxvkVersion.isNotBlank() -> "DXVK $dxvkVersion"
else -> ""
}
/** The DX-wrapper version for the current engine, or "" (used for the Tiles "API" tile sub-line). */
private fun dxVersion(): String = when {
engineLabel.contains("VKD3D", true) -> vkd3dVersion
engineLabel.contains("DXVK", true) -> dxvkVersion
else -> ""
}
/** Resolution + refresh, e.g. "1280x720 @ 120Hz". Read from the current display (Main thread). */
private fun resolutionString(): String {
if (resolution.isNotBlank()) return resolution
val dm = resources.displayMetrics
@@ -774,15 +693,13 @@ class DroidDeckHudView(context: Context) : View(context) {
return if (hz >= 1f) "$base @ ${hz.roundToInt()}Hz" else base
}
/** A subtle, low-emphasis time-of-day tucked into the bottom-right of any size. Grows contentH slightly. */
private fun addSubtleClock(pad: Float, leftAligned: Boolean = false) {
if (!footerClock()) return
val px = sp(9.5f)
val t = clockTimeString()
val w = measure(t, px)
val footerTop = contentH - pad // reuse the bottom padding band as the footer line
val footerTop = contentH - pad
val baseline = footerTop - ascent(px)
// Right-aligned footer; on the Pill it sits on the left edge, under the FPS.
val x = if (leftAligned) pad else (contentW - pad - w).coerceAtLeast(pad)
glyphs.add(Glyph(x, baseline, t, blend(colDim), px))
contentH = footerTop + lineH(px) + pad * 0.5f
@@ -839,7 +756,6 @@ class DroidDeckHudView(context: Context) : View(context) {
val v = ArrayList<Span>()
v += glowing(numUnit(fpsText(fpsNow), "FPS", rowPx, unitPx))
v += gap(unitPx); v += numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", rowPx, unitPx)
// Short API/engine label ("DXVK"/"VKD3D"/"Zink", else "FPS") — a normal aligned row.
rows.add(HudRow(Span(apiLabel(), colFps, rowPx), v))
rows.add(HudRow(Span("AVG", colLo, rowPx), numUnit(fmt1(fpsAvg), "FPS", rowPx, unitPx)))
rows.add(HudRow(Span("1%", colLo, rowPx), numUnit(lowText(lows.low1Fps), "FPS", rowPx, unitPx)))
@@ -863,9 +779,6 @@ class DroidDeckHudView(context: Context) : View(context) {
}
if (showFPS && showGraph) {
// Frametime min/max line + green graph. "Frametime" is far wider than the short-label grid
// column, so place the stat AFTER the ACTUAL label width (not labelCol) — otherwise the two
// overlap and render as "Frametimemin:.. max:..".
val ftPx = unitPx * 1.15f
val baseline = y - asc
placeRun(pad, baseline, listOf(Span("Frametime", colFps, ftPx)))
@@ -907,8 +820,6 @@ class DroidDeckHudView(context: Context) : View(context) {
if (showVram && s.vramText() != null) tiles.add(Tile("VRAM", colVram, valueUnit(s.vramText()!!, valPx, unitPx), null, false))
if (showRAM) tiles.add(Tile("RAM", colRam, numUnit(s.ramPercent.roundToInt().toString(), "%", valPx, unitPx),
"${s.ramUsedText()} / ${s.ramTotalText()}", false))
// API/engine tile — short translator name (DXVK/VKD3D/Zink) with the DX version on the sub-line;
// a normal half-width tile that naturally fills the empty slot beside RAM. Gated by "Engine".
if (showEngine && engineLabel.isNotBlank())
tiles.add(Tile("API", colFps, listOf(Span(engineLabel, colValue, valPx)),
dxVersion().ifBlank { null }, false))
@@ -932,7 +843,7 @@ class DroidDeckHudView(context: Context) : View(context) {
var normalW = 0f
for (t in tiles) if (!t.wide) normalW = max(normalW, tileW(t))
if (normalW == 0f) for (t in tiles) normalW = max(normalW, tileW(t) / 2f)
val tileH = innerPad * 2 + keyH + lineGap + valH + lineGap + subH // uniform (room for a sub line)
val tileH = innerPad * 2 + keyH + lineGap + valH + lineGap + subH
val fullW = normalW * 2 + tileGap
var x = pad; var y = pad; var col = 0
@@ -973,20 +884,12 @@ class DroidDeckHudView(context: Context) : View(context) {
val pad = sp(10f); val midGap = sp(12f); val stkLineGap = sp(3f)
val left = ArrayList<Span>()
// "30->118" is roughly three times the width of "30", and the pill's
// number is set at 30sp precisely because it is the one big thing on a
// small overlay. Shrink it while it carries both figures so the pill
// does not balloon across the screen; it is still the largest element.
val generating = differs(fpsNow)
val fpsPx = if (generating) bigPx * 0.55f else bigPx
left += Span(fpsText(fpsNow), colValue, fpsPx, glow = true)
left += Span("fps", colDim, if (generating) bigUnitPx * 0.8f else bigUnitPx)
val stack = ArrayList<List<Span>>()
// The GPU name normally heads the stack. A name wider than every stat under it (a Wayland spoof
// such as "Radeon RX 6800/6800 XT / 6900 XT spoof") would set the stack's width and stretch the
// whole capsule around empty space, so that name gets its own line across the top of the pill
// instead, starting over the API caption (see nameOnTop below).
val gpuName = if (showGpuModel && gpuNameText().isNotBlank()) gpuModelSpans(stkPx, colDim, compact = true) else null
run {
val l = ArrayList<Span>()
@@ -994,11 +897,7 @@ class DroidDeckHudView(context: Context) : View(context) {
if (showCPU) { if (l.isNotEmpty()) l += Span(" · ", colDim, stkPx); l += Span("CPU ${s.cpuPercent ?: "—"}%", colCpu, stkPx) }
if (l.isNotEmpty()) stack.add(l)
}
// RAM % (system-wide) takes the slot the latency row used to occupy, matching the GPU/CPU idiom
// on the row above it. colRam keeps RAM's identity colour consistent with the Full/Tiles sizes.
if (showRAM) stack.add(listOf(Span("RAM ${s.ramPercent.roundToInt()}%", colRam, stkPx)))
// One battery row, as on the other sizes: each part shows on its own switch, so the battery
// temperature no longer goes with the RAM switch and watts show without the battery level.
if (showBattery || showPower || showBatteryTemp) {
val l = ArrayList<Span>()
fun part(spans: List<Span>) {
@@ -1011,9 +910,6 @@ class DroidDeckHudView(context: Context) : View(context) {
if (showPower && s.battery.watts > 0f) part(listOf(Span("${fmt1(s.battery.watts)}W", colDim, stkPx)))
if (l.isNotEmpty()) stack.add(l)
}
// Latency (+ the display server, + optional VRAM) drops to the bottom of the stack, under the
// battery row. The display server sits here, not on the GPU-model line: that line is the
// pill's widest and ran into the capsule's rounded edge.
run {
val l = ArrayList<Span>()
l += Span("${fmt1(1000f / max(fpsNow, 1f))}ms", colDim, stkPx)
@@ -1021,8 +917,6 @@ class DroidDeckHudView(context: Context) : View(context) {
if (showVram && s.vramText() != null) { l += Span(" · ", colDim, stkPx); l += Span("${s.vramText()} vram", colDim, stkPx) }
stack.add(l)
}
// Wayland HDR state on its OWN line directly under the latency · display-server line (it ran off
// the capsule's right edge as "40.3ms · Wayland · HDR (no headroom)"). Only in HDR sessions.
if (hdrState != DroidDeckHudHdr.NONE) stack.add(hdrLine(stkPx))
var statsW = 0f
@@ -1030,8 +924,6 @@ class DroidDeckHudView(context: Context) : View(context) {
val nameOnTop = gpuName != null && runWidth(gpuName) > statsW
if (gpuName != null && !nameOnTop) stack.add(0, gpuName)
// Left column: a small API/engine caption (DXVK/VKD3D/Zink) above the big FPS and the clock below
// it, all on the left edge, so the left reads API · FPS · clock top-to-bottom.
val apiStr = apiLabel()
val hasApi = apiStr != "FPS"
val apiH = if (hasApi) lineH(stkPx) else 0f
@@ -1050,14 +942,12 @@ class DroidDeckHudView(context: Context) : View(context) {
contentW = pad + leftBlockW + midGap + stackW + pad
contentH = pad + topLineH + innerH + pad
// left column (API caption + big FPS), vertically centered as a block
var ly = pad + topLineH + (innerH - leftColH) / 2f
if (hasApi) {
placeRun(pad, ly - ascent(stkPx), listOf(Span(apiStr, colFps, stkPx)))
ly += apiH + apiGap
}
placeRun(pad, ly - ascent(bigPx), left)
// stack, vertically centered
var sy = pad + topLineH + (innerH - stackTotalH) / 2f
for (l in stack) {
placeRun(pad + leftBlockW + midGap, sy - ascent(stkPx), l)
@@ -1065,22 +955,17 @@ class DroidDeckHudView(context: Context) : View(context) {
}
addSubtleClock(pad, leftAligned = true)
if (nameOnTop && gpuName != null) {
// Left-aligned over the API caption; the pill only widens if the name is wider than the
// API/FPS column + stats.
val end = placeRun(pad, pad - ascent(stkPx), gpuName)
contentW = max(contentW, end + pad)
}
}
// One column as wide as the widest row: the logo, FPS, lows, graph and engine line start on its left
// edge (ink, not advance), and the header keeps the same space above and below the logo.
private fun buildMinimal(s: HudMetrics.Snapshot) {
val bigPx = sp(34f); val bigUnitPx = bigPx * 0.32f; val subPx = sp(11.5f); val footPx = sp(9.5f)
val stroke = outlineWidth()
val left = contentLeft()
val inner = panelInset() + stroke
// Same reasoning as the pill: 34sp is sized for one number, not two.
val minGenerating = differs(fpsNow)
val big = listOf(
Span(fpsText(fpsNow), colValue, if (minGenerating) bigPx * 0.55f else bigPx),
@@ -1126,11 +1011,6 @@ 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)
@@ -1227,8 +1107,6 @@ class DroidDeckHudView(context: Context) : View(context) {
return inkRect.left.toFloat()
}
/** Places a column of "label + value" rows; returns (bottomY, rightX). Appends glyphs. Rows flagged
* [HudRow.inline] opt out of the shared label column (value follows the label directly). */
private fun layoutColumn(rows: List<HudRow>, x: Float, y0: Float,
rowPx: Float, lineGap: Float, lvGap: Float): Pair<Float, Float> {
if (rows.isEmpty()) return Pair(y0, x)
@@ -1248,7 +1126,6 @@ class DroidDeckHudView(context: Context) : View(context) {
return Pair(y - lineGap, right)
}
/** Places wrapping " · "-separated info fragments within maxWidth; returns (bottomY, rightX). */
private fun layoutWrap(fragments: List<List<Span>>, x: Float, y0: Float, maxWidth: Float,
px: Float, lineGap: Float): Pair<Float, Float> {
if (fragments.isEmpty()) return Pair(y0, x)
@@ -1269,7 +1146,6 @@ class DroidDeckHudView(context: Context) : View(context) {
val rowPx = sp(11.5f); val unitPx = rowPx * 0.62f; val bandPx = sp(9.5f)
val pad = sp(10f); val lineGap = sp(3.5f); val lvGap = sp(7f); val gutter = sp(16f)
// ---- LEFT column: GPU, aggregate CPU, then per-core rows ----
val left = ArrayList<HudRow>()
if (showGpuModel && gpuNameText().isNotBlank())
left.add(HudRow(Span("GPU", colGpu, rowPx), gpuModelSpans(rowPx, colValue)))
@@ -1301,7 +1177,6 @@ class DroidDeckHudView(context: Context) : View(context) {
}
}
// ---- RIGHT column: VRAM, RAM, SWP, NET, BAT, engine, lows ----
val right = ArrayList<HudRow>()
if (showVram && s.vramText() != null)
right.add(HudRow(Span("VRAM", colVram, rowPx), valueUnit(s.vramText()!!, rowPx, unitPx)))
@@ -1339,8 +1214,6 @@ class DroidDeckHudView(context: Context) : View(context) {
val v = ArrayList<Span>()
v += glowing(numUnit(fpsText(fpsNow), "FPS", rowPx, unitPx))
v += gap(unitPx); v += numUnit(fmt1(1000f / max(fpsNow, 1f)), "ms", rowPx, unitPx)
// FPS/engine row: just the short API label. The DX version moved to the stack lines
// below the frametime graph (see below), so this row stays compact.
right.add(HudRow(Span(apiLabel(), colFps, rowPx), v))
right.add(HudRow(Span("AVG", colLo, rowPx), numUnit(fmt1(fpsAvg), "FPS", rowPx, unitPx)))
right.add(HudRow(Span("1%", colLo, rowPx), numUnit(lowText(lows.low1Fps), "FPS", rowPx, unitPx)))
@@ -1349,15 +1222,12 @@ class DroidDeckHudView(context: Context) : View(context) {
right.add(HudRow(Span("0.01%", colLo, rowPx), numUnit(lowText(lows.low001Fps), "FPS", rowPx, unitPx)))
}
// ---- Two columns side by side (each reflows independently) ----
val (leftBottom, leftRight) = layoutColumn(left, pad, pad, rowPx, lineGap, lvGap)
val rightX = (if (left.isEmpty()) pad else leftRight + gutter)
val (rightBottom, rightRight) = layoutColumn(right, rightX, pad, rowPx, lineGap, lvGap)
var y = max(leftBottom, rightBottom)
var maxRight = max(leftRight, rightRight)
// ---- Bottom band spanning both columns: res · Proton · elapsed ----
// (The graphics wrapper moved to the FPS-row label above, so it's no longer in this band.)
val band = ArrayList<List<Span>>()
if (showResolution) band.add(listOf(Span("RES ", colDim, bandPx), Span(resolutionString(), colValue, bandPx)))
if (displayServer.isNotBlank()) band.add(listOf(Span("DISP ", colDim, bandPx), Span(displayServer, colDisp, bandPx)))
@@ -1370,7 +1240,6 @@ class DroidDeckHudView(context: Context) : View(context) {
y = bBottom; maxRight = max(maxRight, bRight)
}
// ---- Full-width frametime graph ----
if (showGraph) {
y += sp(3f)
val gh = sp(22f)
@@ -1380,9 +1249,6 @@ class DroidDeckHudView(context: Context) : View(context) {
y += gh
}
// ---- Stack-layer lines BELOW the frametime graph, subtle (same size/style as the bottom
// band): the DX-wrapper version first (e.g. "DXVK 2.4.1-…", gated by "DX ver"), then the
// graphics wrapper beneath it (e.g. "Original", gated by "Wrapper"). ----
val dxLine = dxVersionLabeled()
val hasDx = showDxVer && dxLine.isNotBlank()
if (hasDx) {
@@ -1398,12 +1264,10 @@ class DroidDeckHudView(context: Context) : View(context) {
contentW = maxRight + pad
contentH = y + pad
addSubtleClock(pad) // subtle time-of-day, consistent with the other sizes
addSubtleClock(pad)
}
// ---- 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),
@@ -1413,10 +1277,41 @@ class DroidDeckHudView(context: Context) : View(context) {
override fun onDraw(canvas: Canvas) {
if (contentW <= 0f || contentH <= 0f) { lockController.drawBadge(canvas); return }
val blend = if (dock == DroidDeckHudDock.NONE && previewEdge != DroidDeckHudDock.NONE) previewBlend else 0f
if (blend <= 0f) { drawContent(canvas); return }
if (blend < 1f) {
canvas.saveLayerAlpha(0f, 0f, width.toFloat(), height.toFloat(), ((1f - blend) * 255f).roundToInt())
drawContent(canvas)
canvas.restore()
}
drawTabPreview(canvas, blend)
}
private fun drawTabPreview(canvas: Canvas, blend: Float) {
val (w, h) = dockTabSize()
if (scaleX <= 0f || scaleY <= 0f) return
canvas.save()
canvas.translate(width / 2f, height / 2f)
canvas.scale(1f / scaleX, 1f / scaleY)
canvas.translate(-w / 2f, -h / 2f)
canvas.saveLayerAlpha(0f, 0f, w, h, (blend * 255f).roundToInt())
drawTab(canvas, RectF(0f, 0f, w, h), previewEdge)
var x = sp(TAB_PAD_X_SP)
val baseline = sp(TAB_PAD_Y_SP) + capHeight(sp(TAB_NUM_SP))
for (span in tabSpans()) {
drawPaint.textSize = span.sizePx
drawPaint.color = blend(span.color)
canvas.drawText(span.text, x, baseline, drawPaint)
x += measure(span.text, span.sizePx)
}
canvas.restore()
canvas.restore()
}
private fun drawContent(canvas: Canvas) {
dPanel?.let { panel -> panelFrame(panel)?.let { canvas.drawBitmap(it, 0f, 0f, null) } }
// Tile backings
if (tileRects.isNotEmpty()) {
tilePaint.color = Color.argb((14 * bgOpacity).roundToInt().coerceIn(8, 40), 255, 255, 255)
val tr = sp(6f)
@@ -1427,7 +1322,6 @@ class DroidDeckHudView(context: Context) : View(context) {
tabRect?.let { drawTab(canvas, it) }
stripRect?.let { drawStrip(canvas, it) }
// Text
for (g in glyphs) {
val paint = if (g.sans) wordmarkPaint else drawPaint
paint.textSize = g.sizePx
@@ -1438,14 +1332,11 @@ class DroidDeckHudView(context: Context) : View(context) {
}
headerMark?.let { DroidDeckMark.draw(canvas, it.left, it.top, it.height(), blend(colValue), accent) }
// Frametime graph
graphRect?.let { drawGraph(canvas, it) }
lockController.drawBadge(canvas)
}
// MangoHud's frametime graph: the last 200 frames on a fixed 0-50 ms scale, longer frames clipped
// to 49.9 ms (hud_elements.cpp TransformForward_Custom).
private fun drawGraph(canvas: Canvas, rect: RectF) {
val stats = frames ?: return
stats.graph(graphBuf)
@@ -1457,7 +1348,6 @@ class DroidDeckHudView(context: Context) : View(context) {
if (i == 0) graphPath.moveTo(px, py) else graphPath.lineTo(px, py)
}
if (dPanel != null) {
// Neon without a blur: a blur would be redrawn with every frame.
graphPaint.strokeWidth = sp(4.5f)
graphPaint.color = withAlpha(blend(colGraph), 56)
canvas.drawPath(graphPath, graphPaint)
@@ -1467,7 +1357,6 @@ 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()
@@ -1489,8 +1378,6 @@ class DroidDeckHudView(context: Context) : View(context) {
private fun withAlpha(color: Int, alpha: Int): Int =
Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color))
/** The D: straight left side with small corners, round on the right with radius [rad] (a half circle
* when it is half the height). */
private fun dShape(l: Float, t: Float, r: Float, b: Float, rad: Float, corner: Float): Path {
return Path().apply {
moveTo(l, t + corner)
@@ -1504,7 +1391,6 @@ class DroidDeckHudView(context: Context) : View(context) {
}
}
/** Where the inside of the outline's round side is at height [y]. */
private fun roundEdgeX(p: RectF, y: Float, stroke: Float): Float {
val r = dRadius - stroke
val cx = p.right - dRadius
@@ -1534,7 +1420,6 @@ class DroidDeckHudView(context: Context) : View(context) {
headerPaint.color = withAlpha(accent, 90)
c.drawRect(panel.left, dDividerTop, roundEdgeX(panel, dDividerTop, stroke), dividerBottom, headerPaint)
}
// The watermark fills the half circle on the short sizes and sits on the right of the tall ones.
val halfRound = dRadius >= panel.height() / 2f - 0.5f
val wmH = if (halfRound) panel.height() * 0.92f else min(panel.height(), panel.width()) * 0.55f
DroidDeckMark.draw(c, panel.right - DroidDeckMark.widthFor(wmH) - (if (halfRound) panel.height() * 0.02f else sp(10f)),
@@ -1545,7 +1430,6 @@ class DroidDeckHudView(context: Context) : View(context) {
val outline = dShape(panel.left + h, panel.top + h, panel.right - h, panel.bottom - h, dRadius - h, corner)
val blur = BlurMaskFilter((sp(3.2f) - 0.5f).coerceAtLeast(0.5f) / 0.57735f, BlurMaskFilter.Blur.NORMAL)
glowPaint.strokeWidth = stroke
// Two blurred passes under the sharp one, as the 4-in-1 preview's neon.
for (pass in 0..2) {
glowPaint.maskFilter = if (pass < 2) blur else null
glowPaint.style = Paint.Style.STROKE; glowPaint.color = outlineColor()
@@ -1586,12 +1470,10 @@ class DroidDeckHudView(context: Context) : View(context) {
DroidDeckMark.draw(canvas, rect.centerX() - markW / 2f, rect.centerY() - markH / 2f, markH, blend(colValue), accent)
}
/** Screen point → whether an on-screen control under the HUD takes a touch there. */
internal var passesTouchAt: ((rawX: Float, rawY: Float) -> Boolean)? = null
// Declining the down event hands the whole gesture to the views under the HUD.
override fun onTouchEvent(event: MotionEvent): Boolean {
if (dock != DroidDeckHudDock.NONE) return dockDetector.onTouchEvent(event)
if (dock != DroidDeckHudDock.NONE) return onTabTouch(event)
if (event.actionMasked == MotionEvent.ACTION_DOWN && lockController.isLocked() &&
passesTouchAt?.invoke(event.rawX, event.rawY) == true) return false
return lockController.onTouchEvent(event)
@@ -1602,9 +1484,13 @@ class DroidDeckHudView(context: Context) : View(context) {
internal val contentWidth: Float get() = contentW
internal val contentHeight: Float get() = contentH
internal val isDragging: Boolean get() = lockController.isDragging()
internal val isDragging: Boolean get() = lockController.isDragging() || tabDragging
private companion object {
const val TAB_NUM_SP = 10f
const val TAB_LABEL_SP = 6f
const val TAB_PAD_X_SP = 5f
const val TAB_PAD_Y_SP = 4f
const val REFRESH_MS = 500L
private const val HUE_IDLE_MS = 500L
const val MIN_SCALE = 0.5f
@@ -5,7 +5,6 @@ import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.Path
/** artwork/droiddeck-mark.svg: the split D with its circular cut-out and the blue orb. */
internal object DroidDeckMark {
private const val VIEW_X = -55.98f
const val VIEW_W = 239.92f
@@ -36,7 +35,6 @@ internal object DroidDeckMark {
fun widthFor(height: Float): Float = height * VIEW_W / VIEW_H
/** Where the drawn mark starts and ends inside [widthFor]: the artwork has empty space on both sides. */
fun inkLeftFor(height: Float): Float = (-31.98f - VIEW_X) * height / VIEW_H
fun inkRightFor(height: Float): Float = (175.93f - VIEW_X) * height / VIEW_H
@@ -3,13 +3,6 @@ package com.droiddeck.launcher.hud
import java.io.File
import kotlin.math.roundToInt
/**
* Frame statistics by MangoHud's rules, so the HUD and Steam's performance overlay agree: MangoHud
* overlay.cpp update_hud_info_with_frametime and hud_elements.cpp fps() / frame_timing(). The FPS is the
* frames counted over a sampling period of at least 500 ms, the frame time next to it is 1000 / FPS, and
* the graph holds the last 200 frame times (zeros until filled) on a fixed 0-50 ms scale, min and max
* taken over those 200. Average and lows are DroidDeck HUD's own readouts.
*/
internal class FrameStats {
private val graph = FloatArray(GRAPH_FRAMES)
private var graphHead = 0
@@ -26,14 +19,16 @@ internal class FrameStats {
private var sessionStartNs = 0L
private var sessionFrames = 0L
private val slowTimes = LongArray(SLOW_FRAMES)
private var slowHead = 0
private var slowSize = 0
@Volatile var fps = 0f
private set
/** Completed sampling periods; MangoHud redraws its readouts when one completes. */
@Volatile var fpsUpdates = 0L
private set
/** Frames added so far; the HUD redraws its graph when this moves. */
@Volatile var count = 0L
private set
@@ -60,6 +55,11 @@ internal class FrameStats {
if (lowsSize < LOWS_FRAMES) lowsSize++
if (sessionStartNs == 0L) sessionStartNs = timeNs - frametimeNs
sessionFrames++
if (frametimeNs > SLOW_NS) {
slowTimes[slowHead] = timeNs
slowHead = (slowHead + 1) % SLOW_FRAMES
if (slowSize < SLOW_FRAMES) slowSize++
}
}
count++
}
@@ -77,14 +77,14 @@ internal class FrameStats {
cachedLowsNs = 0L
sessionStartNs = 0L
sessionFrames = 0L
slowHead = 0
slowSize = 0
fps = 0f
count++
}
/** MangoHud's frame time readout: 1000 / FPS. */
fun frametimeMs(): Float = 1000f / maxOf(fps, 1f)
/** The graph, oldest first, into [out] (GRAPH_FRAMES long). */
@Synchronized
fun graph(out: FloatArray) {
for (i in 0 until GRAPH_FRAMES) out[i] = graph[(graphHead + i) % GRAPH_FRAMES]
@@ -96,7 +96,6 @@ internal class FrameStats {
@Synchronized
fun graphMaxMs(): Float = graph.max()
/** Average over the frames this session, from the first frame to [nowNs]'s last frame. */
@Synchronized
fun averageFps(): Float {
if (sessionFrames < 2 || lastPresentNs <= sessionStartNs) return 0f
@@ -106,13 +105,22 @@ internal class FrameStats {
@Synchronized
fun sessionSeconds(nowNs: Long): Float = if (sessionStartNs == 0L) 0f else (nowNs - sessionStartNs) / 1e9f
@Synchronized
fun slowFrames(nowNs: Long, windowNs: Long): Int {
var n = 0
for (i in 0 until slowSize) {
if (nowNs - slowTimes[(slowHead - 1 - i + SLOW_FRAMES) % SLOW_FRAMES] > windowNs) break
n++
}
return n
}
class Lows(val low1Fps: Float, val low01Fps: Float, val low001Fps: Float) {
companion object {
val EMPTY = Lows(0f, 0f, 0f)
}
}
/** FPS at the 99th, 99.9th and 99.99th percentile frame time of the last LOWS_FRAMES frames. */
fun lows(nowNs: Long): Lows {
val copy: LongArray
synchronized(this) {
@@ -141,15 +149,12 @@ internal class FrameStats {
const val FPS_PERIOD_NS = 500_000_000L
const val LOWS_FRAMES = 8192
private const val PAUSE_NS = 1_000_000_000L
const val SLOW_NS = 33_333_334L
private const val SLOW_FRAMES = 2048
private const val LOWS_RECOMPUTE_NS = 250_000_000L
}
}
/**
* Feeds [stats] with the frame times gamescope shares (the ones MangoHud shows). Sessions without the
* shared file, or where gamescope stopped sending, fall back to the frames DroidDeck's compositor shows,
* which stop at the screen's refresh rate.
*/
internal class GameFrameFeed(private val file: File, val stats: FrameStats = FrameStats()) {
private var handle = 0L
private var nextOpenNs = 0L
@@ -160,7 +165,7 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
private val info = IntArray(5)
@Volatile private var fromGamescope = false
private var lastCompositorNs = 0L
@Volatile private var compositorFrames = 0L // written by the compositor thread only
@Volatile private var compositorFrames = 0L
private var seenCompositorFrames = 0L
@Volatile var engine = ""
@@ -176,7 +181,8 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
@Volatile var refreshMilliHz = 0
private set
/** Main thread, once per display frame. True when new frames arrived. */
val live: Boolean get() = fromGamescope
fun poll(nowNs: Long): Boolean {
val compositorAdded = compositorFrames != seenCompositorFrames
seenCompositorFrames = compositorFrames
@@ -185,7 +191,6 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
nextOpenNs = nowNs + REOPEN_NS
handle = runCatching { HudFrames.nativeOpen(file.path) }.getOrDefault(0L)
if (handle == 0L) return compositorAdded
// Frames already in the file were written before this reader started.
HudFrames.nativePoll(handle, frametimes, times)
}
val n = HudFrames.nativePoll(handle, frametimes, times)
@@ -199,7 +204,6 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
} else if (lastRingFrameNs != 0L && nowNs - lastRingFrameNs > LIVE_NS) {
fromGamescope = false
}
// A new session writes the file again from the start; reopen when gamescope has gone quiet.
if (n <= 0 && nowNs - maxOf(lastRingFrameNs, nextOpenNs - REOPEN_NS) > STALE_NS) close()
if (nowNs - lastInfoNs >= INFO_NS) {
lastInfoNs = nowNs
@@ -208,7 +212,6 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
return n > 0 || compositorAdded
}
/** Compositor thread: one frame shown on the panel. */
fun onCompositorFrame(nowNs: Long) {
if (fromGamescope) {
lastCompositorNs = 0L
@@ -247,8 +250,6 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
private const val STALE_NS = 5_000_000_000L
private const val INFO_NS = 500_000_000L
/** DroidDeck's mangoapp's names for gamescope's engine field (Valve's 20260902.1 build, app/main.cpp
* engine_type_from_str and overlay.h engines); gamescope sends "gamescope" when it knows none. */
fun engineLabel(name: String): String = when (name) {
"DXVK" -> "DXVK"
"vkd3d" -> "VKD3D"
@@ -1,12 +1,10 @@
package com.droiddeck.launcher.hud
/** Reader for the frame-times file gamescope patch 0125 writes (hudframes.c). */
internal object HudFrames {
init {
System.loadLibrary("droiddeckwayland")
}
/** Under the Linux root: the session exports /run/droiddeck-hud/frames to gamescope. */
const val PATH = "run/droiddeck-hud/frames"
const val CAPACITY = 1024
@@ -8,7 +8,7 @@
* link to https://github.com/The412Banner/FusionHUD in the project documentation
* AND in the in-app credits/about screen.
*
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code.
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD) and modified for DroidDeck.
*/
package com.droiddeck.launcher.hud;
@@ -28,44 +28,18 @@ import android.view.View;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
/**
* Shared touch + lock behaviour for every in-game performance HUD (classic FrameRating(+Horizontal),
* GameHub PerfHudView, GameNative PerformanceHudView, and the DroidDeck HUD). One place so the four
* overlays can't drift:
*
* <ul>
* <li><b>tap</b> → {@link Callbacks#onTap()} (orientation-toggle for the first three; size-cycle for
* the DroidDeck HUD) — a no-op that only re-flashes the lock badge while locked.</li>
* <li><b>drag</b> → moves the host view and, on release, {@link Callbacks#onMoved} to persist the
* position — disabled (frozen) while locked.</li>
* <li><b>long-press</b> → toggles {@code hudLocked}, persisted via {@link Callbacks#onLockChanged}
* and kept in sync with the "Lock in place" menu chip. Works locked or unlocked (so a long-press
* always unlocks); a locked {@code DroidDeckHudView} passes touches on only over on-screen controls.</li>
* </ul>
*
* <p>On every lock/unlock (and on a blocked gesture while locked) a small padlock badge fades in →
* holds → fades out in a corner of the panel. The fade is driven by a self-reposting Runnable that
* invalidates only while visible — nothing runs on the present path, nothing animates at rest.
*
* <p>All methods are Main-thread only (touch + draw), matching the epoll-thread rule: the views feed
* this from {@code onTouchEvent}/{@code dispatchDraw}, never from a present tick.
*/
public class HudLockController {
public interface Callbacks {
/** Unlocked single tap: orientation-toggle (classic/gamehub/gamenative) or size-cycle (DroidDeck HUD). */
void onTap();
/** Drag released (unlocked): persist the new (x, y). */
void onMoved(float x, float y);
/** Lock toggled by long-press: persist {@code hudLocked} + sync the menu chip. */
default void onDragged(float rawX, float rawY) {}
default void onFlung(float velocityX, float velocityY) {}
void onLockChanged(boolean locked);
/** Two-finger pinch (unlocked): the change since the previous event, above 1 when the fingers spread. */
default void onPinch(float factor) {}
/** The fingers came off a pinch: persist the new size. */
default void onPinchEnd() {}
}
// Fade timing (ms): in → hold → out. Lock/unlock hold ~1.5 s; a blocked-gesture re-flash is shorter.
private static final long FADE_IN_MS = 160;
private static final long HOLD_TOGGLE_MS = 1500;
private static final long HOLD_REFLASH_MS = 750;
@@ -79,13 +53,10 @@ public class HudLockController {
private boolean locked = false;
// Drag state
private float downRawX, downRawY, startX, startY;
private boolean dragging = false;
// A pinch ends the gesture's drag and tap: the finger left down after it must not move the HUD.
private boolean pinched = false;
// Fade state
private long fadeStart = 0;
private long holdMs = HOLD_TOGGLE_MS;
private boolean fadeShowLocked = false;
@@ -106,14 +77,12 @@ public class HudLockController {
iconStroke.setStrokeJoin(Paint.Join.ROUND);
}
/** Set lock state from config (applyConfig) WITHOUT firing the persist callback. */
public void setLocked(boolean locked) { this.locked = locked; }
public boolean isLocked() { return locked; }
public boolean isDragging() { return dragging; }
/** Feed from the host view's onTouchEvent. Always consumes (mirrors the legacy manual handlers). */
public boolean onTouchEvent(MotionEvent event) {
scaleDetector.onTouchEvent(event);
detector.onTouchEvent(event);
@@ -139,7 +108,6 @@ public class HudLockController {
@Override
public void onLongPress(MotionEvent e) {
// Long-press always toggles — this is the only gesture that still works while locked.
locked = !locked;
cb.onLockChanged(locked);
flash(locked, HOLD_TOGGLE_MS);
@@ -149,24 +117,31 @@ public class HudLockController {
public boolean onSingleTapUp(MotionEvent e) {
if (pinched) return true;
if (locked) {
flash(true, HOLD_REFLASH_MS); // intentionally locked — remind the user
flash(true, HOLD_REFLASH_MS);
} else {
cb.onTap();
}
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (dragging && !locked && !pinched) cb.onFlung(velocityX, velocityY);
return true;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (pinched) return true;
if (locked) {
if (!dragging) flash(true, HOLD_REFLASH_MS);
dragging = true; // mark so the blocked drag doesn't fall through to a tap
dragging = true;
return true;
}
view.setX(startX + (e2.getRawX() - downRawX));
view.setY(startY + (e2.getRawY() - downRawY));
dragging = true;
cb.onDragged(e2.getRawX(), e2.getRawY());
return true;
}
}
@@ -192,7 +167,6 @@ public class HudLockController {
}
}
// ---- Fade badge -------------------------------------------------------
private void flash(boolean showLocked, long hold) {
fadeShowLocked = showLocked;
holdMs = hold;
@@ -225,14 +199,6 @@ public class HudLockController {
return Color.argb(Math.round(255 * a), Color.red(color), Color.green(color), Color.blue(color));
}
/**
* Draw the padlock badge in the top-right of the panel if a fade is in progress. Call from the
* host's onDraw (plain View) or dispatchDraw (ViewGroup), after the content.
*
* <p>No background box: the glyph is drawn twice — a slightly expanded, thicker semi-transparent
* black "halo" pass for legibility on any game frame, then the white glyph on top — so it reads as
* a floating icon, not an opaque tile.
*/
public void drawBadge(Canvas canvas) {
float a = currentAlpha();
if (a <= 0f) return;
@@ -251,14 +217,12 @@ public class HudLockController {
float r = size * 0.2f;
float shackleTop = top + size * 0.08f;
// Pass 1: dark halo (expanded body, thicker shackle) for contrast; Pass 2: white glyph.
drawLock(canvas, cx, bodyTop, bodyLeft, bodyRight, bottom, r, shackleTop, d,
Color.argb(Math.round(150 * a), 0, 0, 0), 3.0f * d, 0.9f * d, false);
drawLock(canvas, cx, bodyTop, bodyLeft, bodyRight, bottom, r, shackleTop, d,
withAlpha(0xFFFFFFFF, a), 1.7f * d, 0f, true);
}
/** One padlock pass. {@code halo} inflates the body/shackle in dark; the white pass punches the keyhole. */
private void drawLock(Canvas canvas, float cx, float bodyTop, float bodyLeft, float bodyRight,
float bottom, float r, float shackleTop, float d,
int color, float strokeW, float expand, boolean punchKeyhole) {
@@ -266,7 +230,6 @@ public class HudLockController {
iconStroke.setColor(color);
iconStroke.setStrokeWidth(strokeW);
// Body
canvas.drawRoundRect(bodyLeft - expand, bodyTop - expand, bodyRight + expand, bottom + expand,
2.4f * d, 2.4f * d, iconFill);
if (punchKeyhole) {
@@ -278,19 +241,16 @@ public class HudLockController {
RectF arc = new RectF(cx - r, shackleTop, cx + r, shackleTop + 2f * r);
if (fadeShowLocked) {
// Closed: both legs run straight down into the body.
Path p = new Path();
p.addArc(arc, 180f, 180f);
p.moveTo(cx - r, shackleTop + r); p.lineTo(cx - r, bodyTop);
p.moveTo(cx + r, shackleTop + r); p.lineTo(cx + r, bodyTop);
canvas.drawPath(p, iconStroke);
} else {
// Open, clearly to the LEFT: the RIGHT leg stays seated in the body; the arc + LEFT leg
// hinge up-and-left off the right attachment so the left leg lifts well clear of the body.
canvas.drawLine(cx + r, shackleTop + r, cx + r, bodyTop, iconStroke); // fixed right leg
canvas.drawLine(cx + r, shackleTop + r, cx + r, bodyTop, iconStroke);
Path p = new Path();
p.addArc(arc, 180f, 180f);
p.moveTo(cx - r, shackleTop + r); p.lineTo(cx - r, bodyTop); // full-length left leg
p.moveTo(cx - r, shackleTop + r); p.lineTo(cx - r, bodyTop);
canvas.save();
canvas.rotate(-42f, cx + r, shackleTop + r);
canvas.drawPath(p, iconStroke);
@@ -8,7 +8,8 @@
* link to https://github.com/The412Banner/FusionHUD in the project documentation
* AND in the in-app credits/about screen.
*
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code.
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD) and modified for DroidDeck.
* Metric readers from @xXJSONDeruloXx's work.
*/
package com.droiddeck.launcher.hud;
@@ -32,50 +33,17 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
/**
* Shared live-metric collector for every performance HUD overlay. This is the single, device-complete
* implementation of the sysfs / Android readers — no overlay should re-read sysfs itself, so the GPU
* discovery / thermal / battery logic never diverges.
*
* <p>Ported and hardened from GameNative's {@code PerformanceHudView} readers, which are far more
* device-complete than the two-fixed-path versions previously inlined in the classic overlays:
* <ul>
* <li>GPU load — ~10 static candidates plus a dynamic {@code /sys/class/devfreq} +
* {@code /sys/devices/virtual/devfreq} walk for gpu/mali/g3d/kgsl nodes; handles gpubusy
* (busy/total), Mali gpuinfo (delta-ms/wall-ms, needs state between calls) and generic percent
* nodes. Discovery cached.</li>
* <li>CPU usage — {@code /proc/stat} aggregate delta with a scaling-frequency fallback for devices
* where {@code /proc/stat} is restricted.</li>
* <li>Thermal — prioritized CPU zone discovery (cpu-silicon &gt; cpu-0 &gt; cpu &gt; soc &gt;
* s5p-tmu &gt; cputop &gt; tsens &gt; cluster &gt; big/little) and a separate prioritized GPU zone
* discovery plus kgsl/mali direct paths. milli-°C normalization + 1..150 sanity clamp.</li>
* <li>Battery — % capacity, power W, runtime-left estimate (charge_counter / current_now, smoothed),
* battery temperature, plus the dual-battery current-sum for the classic overlays.</li>
* </ul>
*
* <p>Every getter is null / absent-safe: nullable getters return {@code null} when a metric cannot be
* read (the overlay hides that row, matching GameNative behavior); the legacy non-null getters return
* 0 in that case. Not thread-safe; call from a single refresh thread per instance.
*/
public class HudMetrics {
private final Context context;
public HudMetrics(Context context) { this.context = context; }
// DroidDeck: the readings Steam's performance overlay shows come from MangoReadings, so both agree.
private MangoReadings mango;
public void setMangoReadings(MangoReadings readings) { mango = readings; }
// =======================================================================
// CPU usage
// =======================================================================
private Long lastCpuTotal = null;
private Long lastCpuIdle = null;
/**
* Overall device CPU usage 0..100 computed from the /proc/stat delta since the last call, with a
* scaling-frequency fallback. Returns null only when neither source is readable.
*/
public Integer getCpuUsagePercent() {
String line = readFirstLine("/proc/stat");
if (line != null) {
@@ -104,8 +72,6 @@ public class HudMetrics {
return clampPercent((int) usage);
}
}
// First sample seeds the delta — fall through to the frequency estimate so the
// very first read still returns something.
}
}
}
@@ -127,20 +93,10 @@ public class HudMetrics {
return clampPercent((int) ((currentTotal * 100L) / maxTotal));
}
/** Legacy non-null accessor (0 when unavailable). Kept for {@code PerfHudView}. */
public float getCPUUsage() {
Integer p = getCpuUsagePercent();
return p == null ? 0f : p;
}
// =======================================================================
// GPU load
// =======================================================================
private List<String> gpuUsagePathsCache = null;
private Long lastMaliGpuInfoMs = null;
private long lastMaliGpuInfoWallMs = 0L;
/** GPU utilisation 0..100, or null when no readable source is found on this device. */
public Integer getGpuUsagePercent() {
for (String path : discoverGpuUsagePaths()) {
Integer p = readGpuUsageSample(path);
@@ -149,12 +105,6 @@ public class HudMetrics {
return null;
}
/** Legacy non-null accessor (0 when unavailable). Kept for {@code PerfHudView}. */
public int getGPULoad() {
Integer p = getGpuUsagePercent();
return p == null ? 0 : p;
}
private List<String> discoverGpuUsagePaths() {
if (gpuUsagePathsCache != null) return gpuUsagePathsCache;
LinkedHashSet<String> candidates = new LinkedHashSet<>();
@@ -163,8 +113,6 @@ public class HudMetrics {
if (new File(p).canRead()) candidates.add(p);
}
// Vendor platform nodes with hashed/addressed names we can't hard-code (e.g.
// /sys/devices/platform/13000000.mali/utilisation, .../gpusysfs/gpu_busy, panfrost, sgpu).
File platformDir = new File("/sys/devices/platform");
File[] platformNodes = platformDir.listFiles(File::isDirectory);
if (platformNodes != null) {
@@ -211,9 +159,6 @@ public class HudMetrics {
return gpuUsagePathsCache;
}
// Ordered, world-readable-when-present GPU utilisation nodes across the vendors we've seen:
// Adreno KGSL, Mali (misc + Exynos vendor), PowerVR, and amdgpu-style sysfs (Samsung Xclipse /
// "sgpu", AMD-on-Exynos). readGpuUsageSample() knows how to parse each filename shape.
private static final String[] GPU_USAGE_STATIC_PATHS = {
"/sys/class/kgsl/kgsl-3d0/gpubusy",
"/sys/class/kgsl/kgsl-3d0/gpu_busy_percentage",
@@ -223,23 +168,19 @@ public class HudMetrics {
"/sys/class/misc/mali0/device/gpuinfo",
"/sys/devices/platform/mali/utilization",
"/sys/kernel/gpu/gpu_busy",
"/sys/devices/platform/gpusysfs/gpu_busy", // Exynos Mali vendor node
"/sys/devices/platform/gpusysfs/gpu_busy",
"/sys/class/misc/pvrsrvkm/device/utilisation",
"/sys/class/pvr/utilisation", // PowerVR (Rogue) sysfs
"/sys/class/pvr/utilisation",
"/sys/class/pvr/gpu_utilisation",
"/sys/class/drm/card0/device/gpu_busy_percent", // amdgpu / Xclipse (sgpu), 0..100
"/sys/class/drm/card0/device/gpu_busy_percent",
"/sys/class/devfreq/gpu/load",
// ── Additive cross-vendor fallbacks (appended LAST: tried only after every path above
// misses, so a device that already resolves — e.g. Adreno kgsl — never reaches these). ──
"/sys/kernel/ged/hal/gpu_utilization", // MediaTek GED: "<loading> <block> <idle>" → loading%
"/sys/module/ged/parameters/gpu_loading", // MediaTek GED module param, plain percent
"/sys/kernel/ged/hal/gpu_utilization",
"/sys/module/ged/parameters/gpu_loading",
};
// Percent-bearing filenames scanned under each devfreq / platform GPU node.
private static final String[] GPU_USAGE_FILES = {
"gpu_busy_percentage", "gpu_busy_percent", "gpu_load", "utilisation", "utilization",
"load", "gpu_busy", "gpuinfo",
};
// Substrings that mark a devfreq / platform node as the GPU, across vendors.
private static final String[] GPU_NODE_TOKENS = {
"gpu", "mali", "g3d", "kgsl", "panfrost", "pvr", "powervr", "xclipse", "sgpu",
};
@@ -258,8 +199,6 @@ public class HudMetrics {
return clampPercent((int) ((busy * 100L) / total));
}
case "gpuinfo": {
// Mali multi-line node: the GPU busy time (ms) is the last token of line 1. Utilisation
// is the delta over wall-clock delta between two reads, so it needs state.
String line = readNthLine(path, 1);
if (line == null) return null;
String[] toks = line.trim().split("\\s+");
@@ -294,46 +233,12 @@ public class HudMetrics {
return null;
}
// =======================================================================
// RAM
// =======================================================================
public float getRAMPercent() {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
am.getMemoryInfo(mi);
if (mi.totalMem <= 0) return 0;
return (mi.totalMem - mi.availMem) * 100f / mi.totalMem;
}
private List<String[]> thermalZonesCache = null;
/** Used RAM as "x.xGB" (or "yMB" below 1 GB), matching GameNative's HUD text. */
public String getUsedRamText() {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (am == null) return "—";
ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
am.getMemoryInfo(mi);
long usedBytes = Math.max(0L, mi.totalMem - mi.availMem);
double usedGb = usedBytes / (1024.0 * 1024.0 * 1024.0);
if (usedGb >= 1.0) return String.format(Locale.US, "%.1fGB", usedGb);
return (usedBytes / (1024L * 1024L)) + "MB";
}
// =======================================================================
// Temperature
// =======================================================================
private List<String[]> thermalZonesCache = null; // each entry: {type, tempPath}
/** Legacy non-null CPU-temperature accessor in °C (0 when unavailable). Kept for {@code PerfHudView}. */
public float getTemperature() {
Integer t = getCpuTempC();
return t == null ? 0f : t;
}
/** Hottest representative CPU temperature in °C, or null when no CPU zone is readable. */
public Integer getCpuTempC() {
return readTemperatureC(discoverPrioritizedCpuTempPaths());
}
/** GPU temperature in °C, or null when no GPU sensor is readable. */
public Integer getGpuTempC() {
ArrayList<String> paths = new ArrayList<>();
paths.add("/sys/class/kgsl/kgsl-3d0/temp");
@@ -346,16 +251,16 @@ public class HudMetrics {
private List<String> discoverPrioritizedCpuTempPaths() {
return prioritizePaths(type -> {
if (type.contains("gpu")) return null; // never mistake a GPU zone for CPU
if (type.contains("gpu")) return null;
if (type.contains("cpu-silicon")) return 0;
if (type.contains("cpu-0")) return 1;
if (type.contains("cpuss")) return 2; // Qualcomm cpuss composite
if (type.contains("mtktscpu")) return 2; // MediaTek CPU thermal
if (type.contains("cpu")) return 2; // cpu, cpu-*-usr, cpu_thermal, cpu_center
if (type.contains("s5p-tmu")) return 3; // Exynos TMU
if (type.contains("cpuss")) return 2;
if (type.contains("mtktscpu")) return 2;
if (type.contains("cpu")) return 2;
if (type.contains("s5p-tmu")) return 3;
if (type.contains("soc")) return 4;
if (type.contains("cputop")) return 5;
if (type.contains("tsens")) return 6; // Qualcomm tsens aggregate
if (type.contains("tsens")) return 6;
if (type.contains("cluster")) return 7;
if (type.contains("big") || type.contains("little")) return 8;
return null;
@@ -365,11 +270,11 @@ public class HudMetrics {
private List<String> discoverPrioritizedGpuTempPaths() {
return prioritizePaths(type -> {
if (type.contains("gpu-silicon")) return 0;
if (type.contains("gpuss")) return 1; // Qualcomm gpuss
if (type.contains("mtktsgpu")) return 1; // MediaTek GPU thermal
if (type.contains("gpuss")) return 1;
if (type.contains("mtktsgpu")) return 1;
if (type.contains("gpu-virt")) return 2;
if (type.contains("gpu")) return 2;
if (type.contains("g3d")) return 3; // Exynos Mali (g3d)
if (type.contains("g3d")) return 3;
if (type.contains("kgsl")) return 4;
if (type.contains("mali")) return 5;
if (type.contains("xclipse") || type.contains("sgpu")) return 6;
@@ -381,12 +286,11 @@ public class HudMetrics {
private List<String> prioritizePaths(Ranker ranker) {
List<String[]> zones = discoverAllThermalZones();
ArrayList<int[]> order = new ArrayList<>(); // {index, rank}
ArrayList<int[]> order = new ArrayList<>();
for (int i = 0; i < zones.size(); i++) {
Integer r = ranker.rank(zones.get(i)[0]);
if (r != null) order.add(new int[]{i, r});
}
// Sort by rank, then by path for determinism.
order.sort((a, b) -> {
if (a[1] != b[1]) return Integer.compare(a[1], b[1]);
return zones.get(a[0])[1].compareTo(zones.get(b[0])[1]);
@@ -426,14 +330,12 @@ public class HudMetrics {
if (!seen.add(path)) continue;
Integer raw = readIntFromLine(path);
if (raw == null) continue;
// Round to nearest degree for milli-°C sources; sanity-clamp to reject offline sensors.
int celsius = raw > 1000 ? (raw + 500) / 1000 : raw;
if (celsius >= 1 && celsius <= 150) return celsius;
}
return null;
}
/** The first path in {@code paths} that yields a plausible reading, or null. */
private String resolveTempPath(List<String> paths) {
LinkedHashSet<String> seen = new LinkedHashSet<>();
for (String path : paths) {
@@ -446,13 +348,8 @@ public class HudMetrics {
return null;
}
// =======================================================================
// Temperature danger bands (green / amber / red)
// =======================================================================
public enum TempSensor { CPU, GPU, BATTERY }
/** Amber and red onset in °C. Always °C internally — conversion happens at format time only. */
public static final class Thresholds {
public final int amberC;
public final int redC;
@@ -463,19 +360,14 @@ public class HudMetrics {
public static final int TEMP_COLOR_AMBER = 0xFFFFB74D;
public static final int TEMP_COLOR_RED = 0xFFEF5350;
// Tier-2 fallbacks, used when the device declares no usable trip points. Battery is the only one
// with a well-grounded number (Li-ion); CPU/GPU vary enough between parts that these are a
// deliberately conservative guess — which is exactly why trip points are preferred.
private static final int DEFAULT_RED_CPU = 90;
private static final int DEFAULT_RED_GPU = 90;
private static final int DEFAULT_RED_BAT = 48;
/** Amber sits a proportional step below red, which scales sensibly across both CPU/GPU and battery ranges. */
public static int amberForRed(int redC) {
return Math.round(redC * 0.88f);
}
/** Parsed temperature display options, shared by every overlay so they can't disagree. */
public static final class TempDisplay {
public final boolean fahrenheit;
public final boolean colorBands;
@@ -518,17 +410,11 @@ public class HudMetrics {
}
}
// Trip points are a device constant — resolve once per sensor and keep it.
private final java.util.EnumMap<TempSensor, Thresholds> autoThresholdCache =
new java.util.EnumMap<>(TempSensor.class);
private final java.util.EnumSet<TempSensor> autoThresholdResolved =
java.util.EnumSet.noneOf(TempSensor.class);
/**
* Bands for a sensor. Manual mode uses the user's red point; Auto prefers the device's OWN
* declared thermal trip points (per-device truth — a handheld with active cooling and a phone on
* the same SoC throttle at very different points) and falls back to {@link #DEFAULT_RED_CPU} etc.
*/
public Thresholds resolveThresholds(TempSensor sensor, TempDisplay display) {
if (display != null && !display.auto) {
int red = display.manualRedFor(sensor);
@@ -547,15 +433,6 @@ public class HudMetrics {
return new Thresholds(amberForRed(red), red);
}
/**
* Bands from the kernel's declared trip points for the zone we actually read this sensor from:
* amber ← the lowest sane {@code passive} trip, red ← the lowest sane {@code hot}/{@code critical}.
*
* <p>Returns null unless a usable red point is found. Two real traps this guards against: some
* zones aren't temperature sensors at all (a Snapdragon's {@code pm8550-bcl-lvl0} battery-current
* limiter reports {@code trip_point_0_temp = 1} with type {@code passive}), and the GPU is often
* read from a non-thermal_zone node ({@code /sys/class/kgsl/...}) that has no trip points.
*/
private Thresholds readTripPointThresholds(TempSensor sensor) {
String tempPath;
switch (sensor) {
@@ -563,7 +440,7 @@ public class HudMetrics {
tempPath = resolveTempPath(discoverPrioritizedGpuTempPaths());
break;
case BATTERY:
return null; // battery temp comes from BatteryManager, not a thermal zone
return null;
default:
tempPath = resolveTempPath(discoverPrioritizedCpuTempPaths());
}
@@ -580,8 +457,6 @@ public class HudMetrics {
Integer raw = readIntFromLine(tripTemp.getPath());
if (raw == null) continue;
int celsius = raw > 1000 ? (raw + 500) / 1000 : raw;
// Reject anything that isn't plausibly a thermal trip — this is what filters out the
// battery-current-limiter zones whose "trip point" is a level index, not a temperature.
if (celsius < 20 || celsius > 120) continue;
String typePath = tripTemp.getPath().replaceAll("_temp$", "_type");
@@ -600,7 +475,6 @@ public class HudMetrics {
return new Thresholds(amber, red);
}
/** Band colour for a reading, or {@code fallbackColor} when banding is off or the value is unusable. */
public static int tempColor(Float celsius, Thresholds t, TempDisplay display, int fallbackColor) {
if (celsius == null || t == null || display == null || !display.colorBands) return fallbackColor;
if (celsius >= t.redC) return TEMP_COLOR_RED;
@@ -608,7 +482,6 @@ public class HudMetrics {
return TEMP_COLOR_OK;
}
/** Formats a °C reading in the user's unit. Thresholds stay °C; only display converts. */
public static String formatTemp(float celsius, TempDisplay display, boolean oneDecimal) {
boolean f = display != null && display.fahrenheit;
float value = f ? celsius * 9f / 5f + 32f : celsius;
@@ -618,15 +491,12 @@ public class HudMetrics {
: String.format(Locale.ENGLISH, "%d%s", Math.round(value), unit);
}
// =======================================================================
// Battery
// =======================================================================
public static final class Battery {
public final float watts;
public final boolean charging;
public final Integer percent; // 0..100 or null
public final Integer tempC; // rounded °C or null
public final String runtimeText; // "LEFT 2h 5m" / "LEFT CHG" / null
public final Integer percent;
public final Integer tempC;
public final String runtimeText;
Battery(float watts, boolean charging) {
this(watts, charging, null, null, null);
@@ -640,29 +510,23 @@ public class HudMetrics {
}
}
/** power_supply current_now channels (µA) for the dual-battery sum. */
private static final String[] CURRENT_CHANNELS = {
"/sys/class/power_supply/battery/current_now",
"/sys/class/power_supply/bms/current_now",
"/sys/class/power_supply/main/current_now",
};
/** power_supply voltage_now channels (µV) — fallback when {@code EXTRA_VOLTAGE} reads 0 on some
* OEM firmwares (e.g. HONOR Magic), which otherwise leaves wattage stuck at 0.0W. */
private static final String[] VOLTAGE_CHANNELS = {
"/sys/class/power_supply/battery/voltage_now",
"/sys/class/power_supply/bms/voltage_now",
"/sys/class/power_supply/main/voltage_now",
};
/** power_supply power_now channels (µW) — last-resort direct power reading when neither the
* BatteryManager voltage nor {@code voltage_now} is available. */
private static final String[] POWER_CHANNELS = {
"/sys/class/power_supply/battery/power_now",
"/sys/class/power_supply/bms/power_now",
"/sys/class/power_supply/main/power_now",
};
/** First readable long across a channel list, or null. */
private static Long readLongFromChannels(String[] paths) {
for (String p : paths) {
Long v = readLongFromLine(p);
@@ -671,15 +535,6 @@ public class HudMetrics {
return null;
}
/**
* ADDITIVE charging fallback from {@code /sys/class/power_supply/*}, consulted ONLY when the
* framework gave no usable charge state ({@code EXTRA_STATUS == UNKNOWN} or a null battery intent).
* A charger/input supply reporting {@code online == 1} — or the battery's own {@code status} reading
* "Charging"/"Full" — means charging. Returns TRUE when charging is positively detected, FALSE when a
* status/online node is readable but not charging, or null when nothing usable exists (so the caller
* keeps its own default). Never reached on devices whose BatteryManager reports a real status
* (e.g. Adreno phones/handhelds), so it cannot change their reading.
*/
private static Boolean readChargingFromPowerSupply() {
File[] supplies = new File("/sys/class/power_supply").listFiles();
if (supplies == null || supplies.length == 0) return null;
@@ -690,14 +545,12 @@ public class HudMetrics {
type = type == null ? "" : type.trim().toLowerCase(Locale.US);
boolean isBattery = type.equals("battery") || name.equals("battery") || name.equals("bms");
if (isBattery) {
// The battery's own status string is the most direct charge-state signal.
String st = readFirstLine(new File(supply, "status").getPath());
if (st == null) continue;
st = st.trim().toLowerCase(Locale.US);
sawSignal = Boolean.FALSE; // "discharging"/"not charging" both land here
sawSignal = Boolean.FALSE;
if (st.equals("charging") || st.equals("full")) return Boolean.TRUE;
} else {
// A charger / power-input supply (ac/usb/wireless/mains/dc): online==1 → external power in.
Long online = readLongFromLine(new File(supply, "online").getPath());
if (online == null) continue;
sawSignal = Boolean.FALSE;
@@ -712,55 +565,6 @@ public class HudMetrics {
private static final double RUNTIME_SMOOTHING_OLD_WEIGHT = 0.65;
private static final double RUNTIME_SMOOTHING_NEW_WEIGHT = 0.35;
/**
* Legacy discharge-only power reading used by the classic overlays + {@code PerfHudView}:
* watts are reported only while discharging (0 when charging). When {@code dualBattery} is set the
* per-cell current channels are summed to correct devices that report only one cell's current.
*/
public Battery getBattery(boolean dualBattery) {
Intent status = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
boolean charging = false;
int voltageMv = 0;
if (status != null) {
charging = status.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0;
voltageMv = status.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
} else {
// ADDITIVE: no battery intent → best-effort power_supply charge probe (default stays false).
// Never reached on devices that deliver ACTION_BATTERY_CHANGED (e.g. Adreno).
Boolean sysCharging = readChargingFromPowerSupply();
if (sysCharging != null) charging = sysCharging;
}
long microAmps;
if (dualBattery) {
long sum = 0; int n = 0;
for (String path : CURRENT_CHANNELS) {
Long v = readLongFromLine(path);
if (v != null) { sum += Math.abs(v); n++; }
}
microAmps = n > 0 ? -sum : readCurrentNowFallback();
} else {
microAmps = readCurrentNowFallback();
}
// current_now's SIGN convention is device-dependent — many OEMs (Xiaomi/Poco especially)
// report discharge as POSITIVE, the opposite of the AOSP convention. Gating wattage on the
// sign therefore reads 0W on battery on those devices (and only shows a value while charging).
// Use the magnitude for the power figure; the reliable charge DIRECTION is EXTRA_PLUGGED (the
// `charging` flag), which the HUD already uses for the PWR/CHG label.
// EXTRA_VOLTAGE reads 0 on some OEM firmwares even though current is fine — fall back to the
// power_supply voltage_now (µV → mV) so wattage isn't stuck at 0.
if (voltageMv <= 0) {
Long uv = readLongFromChannels(VOLTAGE_CHANNELS);
if (uv != null && uv > 0) voltageMv = (int) (Math.abs(uv) / 1000L);
}
// current unit auto-detected (mA vs µA) — see currentRawToAmps.
float watts = (voltageMv / 1000f) * currentRawToAmps(microAmps);
return new Battery(watts, charging);
}
/**
* Full GameNative-parity battery snapshot for the GameNative-style HUD: %, power W (magnitude,
* regardless of charge/discharge), smoothed runtime-left estimate, and temperature.
*/
public Battery collectBattery() {
BatteryManager bm = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
if (bm == null) return new Battery(0f, false);
@@ -771,15 +575,12 @@ public class HudMetrics {
Intent status = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
if (status == null) {
// No battery intent at all → additive power_supply charge probe (default stays false).
Boolean sysCharging = readChargingFromPowerSupply();
return new Battery(0f, sysCharging != null && sysCharging, percent, null, null);
}
int st = status.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN);
boolean charging = st == BatteryManager.BATTERY_STATUS_CHARGING || st == BatteryManager.BATTERY_STATUS_FULL;
// ADDITIVE: only when the framework reports no usable charge state do we consult power_supply.
// A device that reports CHARGING/DISCHARGING/FULL/NOT_CHARGING (e.g. Adreno) never enters this.
if (st == BatteryManager.BATTERY_STATUS_UNKNOWN) {
Boolean sysCharging = readChargingFromPowerSupply();
if (sysCharging != null) charging = sysCharging;
@@ -792,23 +593,16 @@ public class HudMetrics {
int rawTemp = status.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);
if (rawTemp > 0) tempC = Math.round(rawTemp / 10f);
// EXTRA_VOLTAGE reads 0 on some OEM firmwares (e.g. HONOR Magic) even though capacity, temp
// and current all work — which left wattage stuck at 0.0W. Fall back to the power_supply
// voltage_now (µV → mV); if voltage is still unavailable, use power_now (µW) directly.
if (voltageMv <= 0) {
Long uv = readLongFromChannels(VOLTAGE_CHANNELS);
if (uv != null && uv > 0) voltageMv = (int) (Math.abs(uv) / 1000L);
}
// Wattage = current × voltage, with current UNIT auto-detected (CURRENT_NOW is nominally µA but
// many OEMs — e.g. this HONOR — report mA; see batteryCurrentAmps). currentMicroAmps above stays
// as-is for the runtime estimate (a ratio, so unit-independent). If neither current nor voltage
// resolves, fall back to power_now (µW) directly.
float amps = batteryCurrentAmps(bm);
float watts = 0f;
if (amps > 0f && voltageMv > 0) {
watts = (voltageMv / 1000f) * amps;
} else {
Long uw = readLongFromChannels(POWER_CHANNELS); // µW
Long uw = readLongFromChannels(POWER_CHANNELS);
if (uw != null && uw != 0L) watts = (float) (Math.abs(uw) / 1_000_000.0);
}
@@ -842,24 +636,12 @@ public class HudMetrics {
return minutes + "m";
}
private long readCurrentNowFallback() {
BatteryManager bm = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
return bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW);
}
/** Raw battery current reading → AMPS, with unit AUTO-DETECT. {@code BATTERY_PROPERTY_CURRENT_NOW}
* (and {@code current_now}) are nominally µA, but many OEMs report mA — a small number, whereas a
* real µA reading is always huge. So a magnitude &lt; 20000 means the device gave mA. Without this,
* wattage on mA-reporting devices came out ~1000× too small → 0.0W even though current & voltage are
* fine. Sentinel/zero → 0. (Heuristic mirrors Ludashi-plus WinlatorHUD.getBatteryCurrentAmps().) */
private static float currentRawToAmps(long raw) {
if (raw == 0L || raw == Long.MIN_VALUE) return 0f;
long a = Math.abs(raw);
return a < 20000L ? a / 1000f : a / 1_000_000f; // mA → A, else µA → A
return a < 20000L ? a / 1000f : a / 1_000_000f;
}
/** Battery current in AMPS for the wattage calc: framework property first, then power_supply
* {@code current_now} sysfs (battery/bms/main) when it's unsupported ({@code Long.MIN_VALUE}) or 0. */
private float batteryCurrentAmps(BatteryManager bm) {
long raw = (bm != null) ? bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW) : 0L;
if (raw == 0L || raw == Long.MIN_VALUE) {
@@ -869,11 +651,6 @@ public class HudMetrics {
return currentRawToAmps(raw);
}
// =======================================================================
// Clock frequencies (best-effort, nullable)
// =======================================================================
/** Peak CPU core clock in MHz (max scaling_cur_freq across cores), or null when unreadable. */
public Integer getCpuClockMhz() {
int cores = Runtime.getRuntime().availableProcessors();
long maxKhz = 0;
@@ -882,29 +659,26 @@ public class HudMetrics {
if (cur != null && cur > maxKhz) maxKhz = cur;
}
if (maxKhz <= 0) return null;
return (int) (maxKhz / 1000L); // kHz → MHz
return (int) (maxKhz / 1000L);
}
private List<String> gpuClockPathsCache = null;
private static final String[] GPU_CLOCK_PATHS = {
"/sys/class/kgsl/kgsl-3d0/gpuclk", // Adreno, Hz
"/sys/class/kgsl/kgsl-3d0/devfreq/cur_freq", // Adreno devfreq, Hz
"/sys/class/kgsl/kgsl-3d0/clock_mhz", // some kernels, already MHz
"/sys/kernel/gpu/gpu_clock", // Mali vendor node, MHz
"/sys/devices/platform/gpusysfs/gpu_clock", // Exynos Mali vendor node, MHz
"/sys/class/misc/mali0/device/clock", // Mali, kHz/MHz
"/sys/class/devfreq/gpu/cur_freq", // generic devfreq gpu, Hz
// ── Additive cross-vendor fallbacks (appended LAST: only reached when every node above
// is unreadable, so Adreno/Mali devices that already resolve are unaffected). ──
"/sys/kernel/ged/hal/current_freqency", // MediaTek GED (vendor's spelling), kHz
"/sys/kernel/ged/hal/gpu_clock", // MediaTek GED alt, MHz
"/sys/class/kgsl/kgsl-3d0/gpuclk",
"/sys/class/kgsl/kgsl-3d0/devfreq/cur_freq",
"/sys/class/kgsl/kgsl-3d0/clock_mhz",
"/sys/kernel/gpu/gpu_clock",
"/sys/devices/platform/gpusysfs/gpu_clock",
"/sys/class/misc/mali0/device/clock",
"/sys/class/devfreq/gpu/cur_freq",
"/sys/kernel/ged/hal/current_freqency",
"/sys/kernel/ged/hal/gpu_clock",
};
private List<String> discoverGpuClockPaths() {
if (gpuClockPathsCache != null) return gpuClockPathsCache;
LinkedHashSet<String> found = new LinkedHashSet<>();
for (String p : GPU_CLOCK_PATHS) if (new File(p).canRead()) found.add(p);
// Vendor-agnostic devfreq walk: any gpu/mali/panfrost/xclipse/sgpu node's cur_freq (Hz).
File[] devfreqRoots = {
new File("/sys/class/devfreq"),
new File("/sys/devices/virtual/devfreq"),
@@ -928,49 +702,31 @@ public class HudMetrics {
return gpuClockPathsCache;
}
/** GPU clock in MHz (Adreno KGSL / devfreq / Mali nodes), or null when no source reports it. */
public Integer getGpuClockMhz() {
for (String p : discoverGpuClockPaths()) {
Long raw = readLongFromLine(p);
if (raw == null || raw <= 0) continue;
long mhz;
if (raw >= 1_000_000L) mhz = raw / 1_000_000L; // Hz
else if (raw >= 10_000L) mhz = raw / 1_000L; // kHz (defensive)
else mhz = raw; // already MHz
if (raw >= 1_000_000L) mhz = raw / 1_000_000L;
else if (raw >= 10_000L) mhz = raw / 1_000L;
else mhz = raw;
if (mhz >= 1 && mhz <= 3000) return (int) mhz;
}
return null;
}
// =======================================================================
// VRAM (best-effort, Java-only sysfs — no native rebuild)
// =======================================================================
// Covered here in pure Java: Adreno KGSL (bytes mapped/allocated) and amdgpu-style drm nodes
// (Samsung Xclipse / "sgpu", AMD-on-Exynos), which expose mem_info_vram_used/_total directly.
// TODO(native): VK_EXT_memory_budget as a vendor-agnostic fallback for Mali/PowerVR, which expose
// no world-readable VRAM node. FEASIBILITY (checked 2026-07): the compositor's Vulkan layer
// (app/src/main/cpp/winlator/vulkan.c) creates an EPHEMERAL VkInstance/VkPhysicalDevice inside
// getRenderer() and destroys it every call — it holds no reusable device and loads only the
// properties/extension entrypoints, not vkGetPhysicalDeviceMemoryProperties2. Wiring the budget
// query therefore means a new JNI method + enabling VK_KHR_get_physical_device_properties2 /
// VK_EXT_memory_budget at instance create + an NDK rebuild — out of scope for a source-only pass.
// CAVEAT to document if/when added: this HUD is an app-side overlay, NOT in the game's Vulkan
// device, so an app-created instance reports the DEVICE-WIDE heap budget (a GPU-memory-pressure
// proxy), not the game's per-process VRAM. Devices with no readable node return null → HUD hides VRAM.
private List<String> vramUsedPathsCache = null;
private static final String[] VRAM_USED_PATHS = {
"/sys/class/kgsl/kgsl-3d0/gpumem_mapped", // bytes currently mapped to the GPU
"/sys/class/kgsl/kgsl-3d0/page_alloc", // bytes allocated to the KGSL page pool
"/sys/class/kgsl/kgsl-3d0/mapped", // alt name on some kernels
"/sys/class/drm/card0/device/mem_info_vram_used",// amdgpu / Xclipse (sgpu), bytes
"/sys/class/kgsl/kgsl-3d0/page_alloc_max", // high-water fallback
"/sys/class/kgsl/kgsl-3d0/gpumem_mapped",
"/sys/class/kgsl/kgsl-3d0/page_alloc",
"/sys/class/kgsl/kgsl-3d0/mapped",
"/sys/class/drm/card0/device/mem_info_vram_used",
"/sys/class/kgsl/kgsl-3d0/page_alloc_max",
};
// Total-VRAM companions (amdgpu exposes one; used only by the diagnostics report).
private static final String[] VRAM_TOTAL_PATHS = {
"/sys/class/drm/card0/device/mem_info_vram_total",
};
/** Used GPU memory in bytes from Adreno KGSL sysfs, or null when this device exposes nothing readable. */
public Long getVramUsedBytes() {
if (vramUsedPathsCache == null) {
ArrayList<String> found = new ArrayList<>();
@@ -986,50 +742,33 @@ public class HudMetrics {
private static Long sanitizeVramBytes(Long v) {
if (v == null) return null;
if (v < (1L << 20)) return null; // < 1 MiB → idle-zero / not a byte count
if (v > 64L * (1L << 30)) return null; // > 64 GiB → not bytes
if (v < (1L << 20)) return null;
if (v > 64L * (1L << 30)) return null;
return v;
}
/** Used GPU memory as "x.xGiB" (or "yMiB"), or null when no VRAM source is readable. */
public String getVramUsedText() {
Long b = getVramUsedBytes();
return b == null ? null : formatGiB(b);
}
private static String formatGiB(long bytes) {
return String.format(Locale.US, "%.1fGiB", bytes / (1024.0 * 1024.0 * 1024.0));
}
// =======================================================================
// Single cached snapshot — read EVERYTHING once per HUD refresh
// =======================================================================
/**
* Immutable point-in-time reading of every metric the DroidDeck HUD draws. Collected in one pass by
* {@link #snapshot()} so the view never touches sysfs / BatteryManager during draw (the user's
* explicit ask: one collection pass, cached, so gameplay isn't strained). All numeric fields are
* raw (nullable when unreadable); the view formats + colours them.
*/
public static final class Snapshot {
public final Integer cpuPercent; // 0..100 or null
public final Integer gpuPercent; // 0..100 or null
public final Integer cpuClockMhz; // MHz or null
public final Integer gpuClockMhz; // MHz or null
public final Integer cpuTempC; // °C or null
public final Integer gpuTempC; // °C or null
public final Integer cpuPercent;
public final Integer gpuPercent;
public final Integer cpuClockMhz;
public final Integer gpuClockMhz;
public final Integer cpuTempC;
public final Integer gpuTempC;
public final long ramUsedBytes;
public final long ramTotalBytes;
public final float ramPercent; // 0..100
public final Long vramUsedBytes; // bytes or null
public final Battery battery; // never null
// ---- Mega-only extras ----
public final int[] perCorePercent; // per-core 0..100, -1 unknown (never null; may be empty)
public final int[] perCoreClockMhz; // per-core MHz, 0 unknown (never null; may be empty)
public final Long swapUsedBytes; // bytes or null (no swap)
public final Long swapTotalBytes; // bytes or null
public final Long netDownBps; // bytes/sec down, or null (first sample / unreadable)
public final Long netUpBps; // bytes/sec up, or null
public final float ramPercent;
public final Long vramUsedBytes;
public final Battery battery;
public final int[] perCorePercent;
public final int[] perCoreClockMhz;
public final Long swapUsedBytes;
public final Long swapTotalBytes;
public final Long netDownBps;
public final Long netUpBps;
Snapshot(Integer cpuPercent, Integer gpuPercent, Integer cpuClockMhz, Integer gpuClockMhz,
Integer cpuTempC, Integer gpuTempC, long ramUsedBytes, long ramTotalBytes,
@@ -1066,7 +805,6 @@ public class HudMetrics {
}
}
/** One collection pass over every metric. Call from the HUD's own ~1 s refresh thread, never draw. */
public Snapshot snapshot() {
if (mango != null) return mangoSnapshot(mango);
Integer cpu = getCpuUsagePercent();
@@ -1102,7 +840,6 @@ public class HudMetrics {
net == null ? null : net[0], net == null ? null : net[1]);
}
// DroidDeck: the same snapshot with MangoHud's sources and rounding (see MangoReadings).
private Snapshot mangoSnapshot(MangoReadings m) {
MangoReadings.Cpu cpu = m.cpu();
MangoReadings.Memory mem = m.memory();
@@ -1121,11 +858,6 @@ public class HudMetrics {
net == null ? null : net[0], net == null ? null : net[1]);
}
// =======================================================================
// Mega-view extras: per-core CPU, swap, network (best-effort, nullable)
// =======================================================================
/** Per-core clock in MHz (each core's {@code scaling_cur_freq}); 0 for a core that can't be read. */
public int[] getPerCoreClockMhz() {
int cores = Runtime.getRuntime().availableProcessors();
int[] out = new int[Math.max(0, cores)];
@@ -1136,11 +868,9 @@ public class HudMetrics {
return out;
}
// Per-core /proc/stat deltas — one prev sample per core, seeded on the first read.
private long[] lastCoreTotal = null;
private long[] lastCoreIdle = null;
/** Per-core CPU usage 0..100 from the {@code cpuN} /proc/stat deltas; -1 for a core not yet sampled. */
public int[] readPerCorePercent() {
int cores = Runtime.getRuntime().availableProcessors();
int[] out = new int[Math.max(0, cores)];
@@ -1153,8 +883,8 @@ public class HudMetrics {
try (BufferedReader r = new BufferedReader(new FileReader("/proc/stat"))) {
String line;
while ((line = r.readLine()) != null) {
if (!line.startsWith("cpu")) break; // cpu lines are first; stop at the block end
if (line.length() < 4 || !Character.isDigit(line.charAt(3))) continue; // skip aggregate "cpu "
if (!line.startsWith("cpu")) break;
if (line.length() < 4 || !Character.isDigit(line.charAt(3))) continue;
String[] parts = line.trim().split("\\s+");
int core;
try { core = Integer.parseInt(parts[0].substring(3)); } catch (Exception e) { continue; }
@@ -1165,8 +895,8 @@ public class HudMetrics {
try {
long v = Long.parseLong(parts[i]);
total += v;
if (i == 4) idle = v; // idle
else if (i == 5) idle += v; // + iowait
if (i == 4) idle = v;
else if (i == 5) idle += v;
} catch (NumberFormatException e) { ok = false; break; }
}
if (!ok) continue;
@@ -1179,10 +909,6 @@ public class HudMetrics {
}
}
} catch (Exception ignored) {}
// Frequency fallback for any core /proc/stat couldn't give us — restricted on some firmwares
// (e.g. HONOR / Android 16), which is also why the aggregate getCpuUsagePercent() falls back.
// scaling_cur_freq / cpuinfo_max_freq is a load proxy (per-core clocks ARE readable there), and
// it also seeds the very first sample. Cores with a real /proc/stat delta keep it (no regression).
for (int i = 0; i < out.length; i++) {
if (out[i] >= 0) continue;
Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq");
@@ -1193,7 +919,6 @@ public class HudMetrics {
return out;
}
/** Swap {used, total} in bytes from /proc/meminfo, or null when there is no swap. */
public long[] getSwapBytes() {
long totalKb = -1, freeKb = -1;
try (BufferedReader r = new BufferedReader(new FileReader("/proc/meminfo"))) {
@@ -1215,10 +940,8 @@ public class HudMetrics {
return v == null ? -1 : v;
}
// Net rate: cumulative rx/tx bytes + the wall-clock of the previous read → bytes/sec.
private long lastNetRx = -1, lastNetTx = -1, lastNetWallMs = 0;
/** Network {down, up} in bytes/sec (all interfaces except loopback), or null on the first/failed read. */
public long[] readNetRateBps() {
long rx = 0, tx = 0;
boolean any = false;
@@ -1241,7 +964,7 @@ public class HudMetrics {
long now = SystemClock.elapsedRealtime();
long prevRx = lastNetRx, prevTx = lastNetTx, prevWall = lastNetWallMs;
lastNetRx = rx; lastNetTx = tx; lastNetWallMs = now;
if (prevRx < 0 || prevWall <= 0) return null; // seed
if (prevRx < 0 || prevWall <= 0) return null;
long dt = now - prevWall;
if (dt <= 0) return null;
long down = Math.max(0L, (rx - prevRx) * 1000L / dt);
@@ -1249,20 +972,8 @@ public class HudMetrics {
return new long[]{down, up};
}
// =======================================================================
// Diagnostics report (invoked ONLY on user tap — never on the HUD refresh path)
// =======================================================================
/**
* One-tap plain-text device report for the "Export HUD diagnostics" action: for every metric it
* lists the resolved source path/API + current value, or MISS + the exact candidates it tried,
* followed by an "exists on this device" dump (thermal zone types, devfreq/kgsl/mali nodes) so a
* device owner can send back the real path for anything that missed. Does a short prime+sample so
* delta-based readers (CPU%/GPU%/net) report a live value. Run OFF the main thread.
*/
public String buildDiagnosticsReport(Context ctxIn) {
final Context ctx = ctxIn != null ? ctxIn : this.context;
// Prime the delta-based readers, wait, then take a live sample.
snapshot();
try { Thread.sleep(350L); } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); }
Snapshot s = snapshot();
@@ -1281,7 +992,6 @@ public class HudMetrics {
sb.append("\n== Metrics ==\n");
// ---- CPU ----
boolean procStat = new File("/proc/stat").canRead();
if (s.cpuPercent != null) {
metricHit(sb, "CPU %", s.cpuPercent + "%",
@@ -1292,7 +1002,6 @@ public class HudMetrics {
"/sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq");
}
// Per-core %
StringBuilder cores = new StringBuilder();
for (int i = 0; i < s.perCorePercent.length; i++) {
if (i > 0) cores.append(' ');
@@ -1304,7 +1013,6 @@ public class HudMetrics {
else
metricMiss(sb, "Per-core %", "/proc/stat");
// Per-core clock
StringBuilder coreClk = new StringBuilder();
for (int i = 0; i < s.perCoreClockMhz.length; i++) {
if (i > 0) coreClk.append(' ');
@@ -1317,7 +1025,6 @@ public class HudMetrics {
else
metricMiss(sb, "CPU clock", "/sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq");
// CPU temp
String cpuTempPath = resolveTempPath(discoverPrioritizedCpuTempPaths());
if (s.cpuTempC != null && cpuTempPath != null)
metricHit(sb, "CPU temp", s.cpuTempC + "°C", cpuTempPath);
@@ -1325,7 +1032,6 @@ public class HudMetrics {
metricMiss(sb, "CPU temp",
"/sys/class/thermal/thermal_zone*/temp (types: cpu*/cpuss/tsens/mtktscpu/s5p-tmu/soc)");
// ---- GPU ----
String gpuUsagePath = firstReadableGpuUsagePath();
if (s.gpuPercent != null && gpuUsagePath != null)
metricHit(sb, "GPU %", s.gpuPercent + "%", gpuUsagePath);
@@ -1347,7 +1053,6 @@ public class HudMetrics {
"/sys/class/kgsl/kgsl-3d0/temp", "/sys/class/misc/mali0/device/temp",
"/sys/class/thermal/thermal_zone*/temp (types: gpu*/gpuss/g3d/kgsl/mali/mtktsgpu)");
// ---- Memory ----
metricHit(sb, "RAM", s.ramUsedText() + " / " + s.ramTotalText()
+ " (" + Math.round(s.ramPercent) + "%)", "ActivityManager.MemoryInfo");
if (s.swapUsedBytes != null)
@@ -1355,7 +1060,6 @@ public class HudMetrics {
else
metricMiss(sb, "SWAP", "/proc/meminfo (SwapTotal=0 or unreadable)");
// VRAM
String vramPath = firstReadableVramUsedPath();
if (s.vramUsedBytes != null && vramPath != null) {
Long total = readFirstReadableLong(VRAM_TOTAL_PATHS);
@@ -1366,14 +1070,12 @@ public class HudMetrics {
new ArrayList<>(), VRAM_USED_PATHS);
}
// ---- Net ----
if (s.netDownBps != null)
metricHit(sb, "NET", formatRate(s.netDownBps) + " down / " + formatRate(s.netUpBps) + " up",
"/proc/net/dev");
else
metricMiss(sb, "NET", "/proc/net/dev (first sample or unreadable)");
// ---- Battery ----
Battery b = s.battery;
StringBuilder bat = new StringBuilder();
bat.append(b.percent != null ? b.percent + "%" : "?%")
@@ -1383,7 +1085,6 @@ public class HudMetrics {
.append(b.runtimeText != null ? ", " + b.runtimeText : "");
metricHit(sb, "Battery", bat.toString(), "BatteryManager + /sys/class/power_supply");
// ---- Exists-on-device dump ----
appendExistsDump(sb);
return sb.toString();
}
@@ -1415,7 +1116,7 @@ public class HudMetrics {
}
private String firstReadableVramUsedPath() {
if (vramUsedPathsCache == null) getVramUsedBytes(); // builds the cache
if (vramUsedPathsCache == null) getVramUsedBytes();
if (vramUsedPathsCache == null) return null;
for (String p : vramUsedPathsCache) if (sanitizeVramBytes(readLongFromLine(p)) != null) return p;
return null;
@@ -1479,12 +1180,6 @@ public class HudMetrics {
appendGpuNoRootProbes(sb);
}
/** Probes for a ROOT-FREE GPU-load path on locked-sysfs Adreno devices (SM8750/HONOR etc.):
* (1) can the app open the KGSL device node? The sysfs mirror (/sys/class/kgsl) is SELinux-blocked
* (vendor_sysfs_kgsl), but /dev/kgsl-3d0 is labeled gpu_device and is normally app-openable —
* that's the door for reading GPU busy via ioctl perf-counters instead of sysfs.
* (2) is there an app-readable devfreq node under /sys/devices/platform that bypasses the blocked
* /sys/class/kgsl symlink (a free win for at least the clock). */
private void appendGpuNoRootProbes(StringBuilder sb) {
sb.append("-- GPU no-root reachability probes --\n");
sb.append(" /dev/kgsl-3d0 open O_RDWR: ")
@@ -1516,8 +1211,6 @@ public class HudMetrics {
if (!found) sb.append(" devfreq (platform kgsl): (no app-readable node found)\n");
}
/** open()+close() a path with the given flags, reporting OK or the errno class — used to test
* whether the app's sandbox can reach a device node without root. */
private static String probeOpen(String path, int flags) {
java.io.FileDescriptor fd = null;
try {
@@ -1530,8 +1223,6 @@ public class HudMetrics {
}
}
/** Battery-wattage inputs: which power_supply nodes this app can actually READ, and their raw
* values. Confirms the voltage_now / power_now fallback for devices where EXTRA_VOLTAGE is 0. */
private void appendPowerSupplyDump(StringBuilder sb) {
sb.append("-- /sys/class/power_supply (battery watts inputs) --\n");
File[] nodes = new File("/sys/class/power_supply").listFiles();
@@ -1582,9 +1273,6 @@ public class HudMetrics {
return names.length() == 0 ? "(no readable files)" : names.toString();
}
// =======================================================================
// Low-level helpers
// =======================================================================
private static int clampPercent(int v) { return v < 0 ? 0 : (v > 100 ? 100 : v); }
private static String readFirstLine(String path) {
@@ -8,7 +8,7 @@
* link to https://github.com/The412Banner/FusionHUD in the project documentation
* AND in the in-app credits/about screen.
*
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code.
* Ported to DroidDeck from FusionHUD (Bannerlator's HUD) and modified for DroidDeck.
*/
package com.droiddeck.launcher.hud;
@@ -20,17 +20,14 @@ import java.util.Iterator;
public class KeyValueSet implements Iterable<String[]> {
private String data = "";
// Default constructor for an empty KeyValueSet
public KeyValueSet() {
this.data = "";
}
// Constructor to initialize with a string representation of key-value pairs
public KeyValueSet(String data) {
this.data = data != null && !data.isEmpty() ? data : "";
}
// Helper method to find the start and end indices of a key in the data string
private int[] indexOfKey(String key) {
int start = 0;
int end = data.indexOf(",");
@@ -48,37 +45,31 @@ public class KeyValueSet implements Iterable<String[]> {
return null;
}
// Method to get the value associated with a key, or an empty string if the key is not present
public String get(String key) {
for (String[] keyValue : this) if (keyValue[0].equals(key)) return keyValue[1];
return "";
}
// Method to get the value associated with a key, or a fallback value if the key is not present
public String get(String key, String fallback) {
for (String[] keyValue : this) if (keyValue[0].equals(key)) return keyValue[1];
return fallback;
}
// Method to get a boolean value associated with a key, or a fallback value if the key is not present
public boolean getBoolean(String key, boolean fallback) {
String value = get(key);
if (value.isEmpty()) return fallback;
return value.equals("1") || value.equals("t") || value.equalsIgnoreCase("true");
}
// Method to get a float value associated with a key, or a fallback value if the key is not present
public float getFloat(String key, float fallback) {
String value = get(key);
try {
if (!value.isEmpty()) return Float.parseFloat(value);
} catch (NumberFormatException e) {
// Ignore exception and return fallback
}
return fallback;
}
// Method to set a value for a key in the key-value data
public void put(String key, Object value) {
int[] range = indexOfKey(key);
if (range != null) {
@@ -88,21 +79,15 @@ public class KeyValueSet implements Iterable<String[]> {
}
}
// Method to set a float value for a key in the key-value data
public void put(String key, float value) {
put(key, String.valueOf(value));
}
// Iterator implementation for key-value pairs in the format [key, value]
@NonNull
@Override
public Iterator<String[]> iterator() {
final int[] start = {0};
final int[] end = {data.indexOf(",")};
// A single-item config (no comma) gives indexOf == -1, making hasNext() (start < end)
// immediately false so the sole pair was never iterated (get() then returned the
// fallback). Guard it exactly as next() already does. An empty string still yields
// end == 0 → no iteration, which is correct.
if (end[0] == -1) end[0] = data.length();
final String[] item = new String[2];
return new Iterator<String[]>() {
@@ -5,12 +5,6 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import kotlin.math.roundToInt
/**
* The readings Steam's performance overlay shows in a DroidDeck session (Valve's mangohud 20260902.1,
* tools/mangoapp), taken from the files the session hands it and computed the same way, so the two
* overlays agree. Sources and formulas follow that build: cpu.cpp calculateCPUData, deckard_temp.cpp,
* msm.cpp getQcomGpuInfo, memory.cpp update_meminfo and battery.cpp getPercent / getPower.
*/
internal class MangoReadings(private val sessionDir: File, private val rootDir: File) {
class Cpu(val percent: Int, val perCore: IntArray)
class Memory(val usedBytes: Long, val totalBytes: Long, val swapUsedBytes: Long, val swapTotalBytes: Long)
@@ -19,7 +13,6 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
private val cpuTimes = HashMap<String, LongArray>()
private val cpuPercents = HashMap<String, Int>()
/** Total and per-core load from the session's /proc/stat (DroidDeck's stand-in when the app can't read it). */
@JvmOverloads
fun cpu(stat: File = statFile()): Cpu? {
val lines = runCatching { stat.readLines() }.getOrNull() ?: return null
@@ -40,7 +33,6 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
File(sessionDir, "proc-stat").takeIf { !File("/proc/stat").canRead() && it.isFile } ?: File("/proc/stat")
private fun cpuPercent(key: String, v: LongArray): Int {
// user nice system idle iowait irq softirq steal guest guest_nice; guest time is already in user.
val user = v[0] - v[8]
val nice = v[1] - v[9]
val systemAll = v[2] + v[5] + v[6]
@@ -57,7 +49,6 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
return busy.coerceIn(0f, 100f).toInt().also { cpuPercents[key] = it }
}
/** Average of the zones the session types cpuN-thermal, truncated. */
fun cpuTempC(): Int? {
externalCpuTemp()?.let { return it }
var sum = 0f
@@ -95,7 +86,6 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
return (milli / 1000.0).toInt()
}
/** MemTotal - MemAvailable and SwapTotal - SwapFree from /proc/meminfo. */
fun memory(): Memory? {
val kb = HashMap<String, Long>()
runCatching {
@@ -115,7 +105,6 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
/** The KGSL total DroidDeck shares with the session (GpuMemComponent). */
fun vramBytes(): Long? = fresh(File(rootDir, VRAM_FILE), VRAM_FRESH_MS)?.let(::readLong)?.takeIf { it > 0 }
/** BAT* under the session's power_supply (BatteryComponent): no watts while charging, full or unknown. */
fun battery(): Battery? {
val dirs = File(sessionDir, "sys/power_supply").listFiles { f -> f.name.contains("BAT") }?.sortedBy { it.name }
if (dirs.isNullOrEmpty()) return null
@@ -160,7 +149,6 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
private fun readLong(file: File): Long? = runCatching { file.readText().trim().toLong() }.getOrNull()
private fun readFloat(file: File): Float? = runCatching { file.readLines().first().trim().toFloat() }.getOrNull()
/** std::stod on the first line: the leading number, "6 %" -> 6. */
fun leadingNumber(file: File): Double? = runCatching {
Regex("^\\s*-?\\d+(\\.\\d+)?").find(file.readLines().first())?.value?.trim()?.toDouble()
}.getOrNull()