chore: remove source comments and unused code, translate every missing string (#1965)

* chore(i18n): translate every missing string in all locales

Adds the 87 strings the bottom-screen Dashboard and in-game stats pages
introduced to all 32 locales, plus the 51 older settings strings Japanese
and the 50 Chinese locales were still missing. Every locale now has all
3456 translatable strings with the same placeholders as English.

Also translates 36 entries that were still English where the language
does not use the English word, and makes es-419 touch_app_id use the same
%1$s placeholder as English.

* chore(patches): drop comments from the lines downstream patches add

Removes comment lines and trailing comments from lines our patches add,
with hunk headers recounted. Lines that a later patch uses as context
and the upstream backport 0123 are left as they are.

The gamescope, FEX, proot and xodus series still apply to their pinned
sources, and the patched trees differ only in those comments.
test_hud_frames now finds the HUD writer by its first declaration.

* docs: credit Greenlight, Better xCloud, viture-v2, GameNative and DiRTTelemetryErrorFix

These were credited only in source headers and NOTICE files.

* chore: remove source comments and unused functions

Removes explanatory comments from first-party Kotlin, Java, C, C++,
Rust, TypeScript, Python, shell, Gradle, CMake and workflow files.
License and attribution headers stay, and vendored third-party trees,
generated files and license files are untouched. A shellcheck directive
is kept, and udevmon's fallthrough comments became fallthrough attributes.

Syntax trees and token streams match the previous sources apart from the
comments and Python docstrings. Module docstrings that argparse prints
are kept, and device-smoke.sh prints the same --help text from a heredoc.

Also removes 37 functions and 4 fields that nothing referenced.

* chore: remove comments from the Syncthing integration and the latest main sources

* docs: credit Syncthing and the syncthing-android fork

* chore(i18n): translate the Syncthing strings in all locales

The 107 strings the Syncthing integration added are now in all 32 locales.
sync_web_path_locked names the Syncthing tab by its label.

* docs: credit @xXJSONDeruloXx for the HUD metric readers

The CPU, GPU load, thermal and battery readers come from their
PerformanceHudView pull requests #777, #877, #991, #1406 and #1573.
The FusionHUD credit line is unchanged.

* docs: credit the HUD metric readers to @xXJSONDeruloXx's work
This commit is contained in:
MaxsTechReview authored and GitHub committed 2026-11-01 16:27:27 -05:00
1 parent d730f0fa8b
commit c5577478ca
511 files changed
+6813 -4068

No files matched your search

@@ -3,12 +3,7 @@ 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", "hudSnap" to "1", "hudScale" to "100", "hudDock" to "none", "hudOpacity" to "80", "hudColor" to "mid",
"hudOutline" to "40", "hudOutlineAccent" 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> {
@@ -19,10 +19,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())
@@ -36,8 +32,6 @@ class DroidDeckHudHost(context: Context) {
private var polling = false
private var wantX = Float.NaN
private var wantY = Float.NaN
// With snapping on, the side the HUD keeps to (0 = left, 1 = right), so it stays against that side when its
// size changes. NaN = not snapped.
private var anchorX = Float.NaN
private var snaps = true
private var snapping = false
@@ -51,13 +45,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 {
@@ -86,7 +77,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)
@@ -171,13 +161,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()
@@ -188,7 +176,6 @@ class DroidDeckHudHost(context: Context) {
val show = !hidden && !backgrounded
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)
@@ -196,14 +183,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()
@@ -243,17 +227,14 @@ 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 over = overhang(v) ?: return null
return over.key.takeIf { over.value >= DOCK_OVERHANG }
}
/** The edge the HUD hangs furthest past, with how much of it does, as a share of its own size. */
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
// The Strip spans the screen and is short: measure its pull in a set distance rather than its own size.
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()
@@ -266,7 +247,6 @@ class DroidDeckHudHost(context: Context) {
).maxByOrNull { it.value }
}
/** The tab follows the finger along its edge and away from it, staying on screen. */
private fun dragTab(hud: DroidDeckHudView, x: Float, y: Float) {
val p = hud.parent as? View ?: return
stopMotion(hud)
@@ -275,7 +255,6 @@ class DroidDeckHudHost(context: Context) {
hud.y = y.coerceIn(0f, (p.height - hud.height).toFloat().coerceAtLeast(0f))
}
/** A tab pulled out by more than its own size comes out as the HUD there; a shorter pull slides it back onto its edge. */
private fun dropTab(hud: DroidDeckHudView) {
val p = hud.parent as? View ?: return
val maxX = (p.width - hud.width).toFloat().coerceAtLeast(0f)
@@ -298,13 +277,11 @@ class DroidDeckHudHost(context: Context) {
.withEndAction { snapping = false }.start()
}
/** Stops the HUD's running move, and the per-frame listener a dock animation hangs on it, which outlives a cancel. */
private fun stopMotion(hud: DroidDeckHudView) {
hud.animate().setUpdateListener(null)
hud.animate().cancel()
}
/** Glides the HUD from (fromX, fromY) to where it now is, back at full size. */
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
@@ -317,7 +294,6 @@ class DroidDeckHudHost(context: Context) {
.withEndAction { snapping = false; keepOnScreen(hud) }.start()
}
/** A drop short of docking fades the tab preview back out. */
private fun fadeDockPreview(hud: DroidDeckHudView) {
val from = hud.dockPreviewBlend
if (from <= 0f) return
@@ -331,10 +307,6 @@ class DroidDeckHudHost(context: Context) {
}
}
/**
* Dropped, the HUD glides to the nearer side of the screen at the height it was let go, as a picture-in-picture
* window does, carried to the side a fling throws it toward.
*/
private fun snapToAnchor(hud: DroidDeckHudView, vx: Float) {
val p = hud.parent as? View ?: return
val maxX = (p.width - hud.width).toFloat().coerceAtLeast(0f)
@@ -354,10 +326,6 @@ class DroidDeckHudHost(context: Context) {
.withEndAction { snapping = false; keepOnScreen(hud) }.start()
}
/**
* Dragged past an edge, the HUD shrinks around the finger toward the tab it docks as, reaching the tab's
* size where a drop would dock it, so the drop finishes a contraction the drag already started.
*/
private fun shrinkPastEdge(hud: DroidDeckHudView, rawX: Float, rawY: Float) {
if (hud.dock != DroidDeckHudDock.NONE) return
val p = hud.parent as? View ?: return
@@ -372,7 +340,6 @@ class DroidDeckHudHost(context: Context) {
hud.pivotX = rawX - at[0] - hud.x
hud.pivotY = rawY - at[1] - hud.y
if (hud.isStrip) {
// The bar draws in sideways toward the tab's width; scaled evenly it would thin to a line.
hud.scaleX = 1f + (tabW / hud.width - 1f) * e
hud.scaleY = 1f
return
@@ -382,7 +349,6 @@ class DroidDeckHudHost(context: Context) {
hud.scaleX = s; hud.scaleY = s
}
/** Tucks the HUD against [edge] as its FPS tab, or with [DroidDeckHudDock.NONE] brings it back out from where it was docked. */
private fun setDock(hud: DroidDeckHudView, edge: DroidDeckHudDock) {
if (edge == hud.dock) return
animateDock(hud, edge) { commitDock(hud, edge) }
@@ -405,10 +371,6 @@ class DroidDeckHudHost(context: Context) {
onConfigChanged?.invoke()
}
/**
* Where the HUD comes out of its tab, decided before it expands so it grows straight there: where the tab is
* (against its edge, or wherever it was pulled to), and with snapping on, against the nearer side.
*/
private fun settleOutOfTab(hud: DroidDeckHudView, tabX: Float, tabY: Float) {
val p = hud.parent as? View
val maxX = if (p == null) Float.MAX_VALUE else (p.width - hud.contentWidth).coerceAtLeast(0f)
@@ -419,11 +381,6 @@ class DroidDeckHudHost(context: Context) {
SessionPrefs.setDroidDeckHudPosition(context, wantX, wantY)
}
/**
* 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) {
stopMotion(hud)
previewFade?.cancel(); previewFade = null
@@ -436,7 +393,6 @@ class DroidDeckHudHost(context: Context) {
commit(); return
}
if (edge != DroidDeckHudDock.NONE) {
// Continue from what the drag left on screen: the shrunk HUD, and the tab where it is along the edge.
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
@@ -480,11 +436,9 @@ class DroidDeckHudHost(context: Context) {
}
}
/** 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)
@@ -498,9 +452,6 @@ 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
@@ -528,27 +479,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
/** How far ahead a fling carries the HUD when picking the spot it snaps to, as seconds of its speed. */
private const val FLING_REACH_S = 0.18f
/** How far toward docking a drag goes, as a share of the way, before the tab starts to fade in over the HUD. */
private const val PREVIEW_FROM = 0.55f
/** How far the Strip is pulled sideways, or off its edge, for its overhang to count as its whole size. */
private const val STRIP_PULL_ACROSS_DP = 600f
private const val STRIP_PULL_OFF_DP = 150f
/** The share of the expand animation over which the tab fades out to the HUD. */
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
@@ -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
@@ -232,13 +191,10 @@ class DroidDeckHudView(context: Context) : View(context) {
private var onDockChangedListener: Consumer<String>? = null
private var onScaledListener: IntConsumer? = null
private var onDraggedListener: BiConsumer<Float, Float>? = null
/** The HUD moved under the finger, at that screen point. */
fun setOnDraggedListener(l: BiConsumer<Float, Float>?) { onDraggedListener = l }
private var onFlungListener: BiConsumer<Float, Float>? = null
/** A drag ended in a fling, at this velocity (pixels per second), just before the move is reported. */
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 {
@@ -256,7 +212,6 @@ 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 brings the HUD back, a drag moves the tab.
private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop
private var tabDownRawX = 0f
private var tabDownRawY = 0f
@@ -266,10 +221,8 @@ class DroidDeckHudView(context: Context) : View(context) {
private var onTabDraggedListener: BiConsumer<Float, Float>? = null
private var onTabDroppedListener: Runnable? = null
private var onTabDragCancelledListener: Runnable? = null
/** The docked tab is dragged: where the finger would put it (x, y in the parent). */
fun setOnTabDraggedListener(l: BiConsumer<Float, Float>?) { onTabDraggedListener = l }
fun setOnTabDroppedListener(l: Runnable?) { onTabDroppedListener = l }
/** The system took the tab's drag away: the tab goes back to where it was docked. */
fun setOnTabDragCancelledListener(l: Runnable?) { onTabDragCancelledListener = l }
private fun onTabTouch(event: MotionEvent): Boolean {
@@ -296,7 +249,6 @@ class DroidDeckHudView(context: Context) : View(context) {
return true
}
// On the way into the tab or out of it, the tab fades in over the HUD at the tab's true size on screen.
private var previewEdge = DroidDeckHudDock.NONE
private var previewBlend = 0f
internal fun setDockPreview(edge: DroidDeckHudDock, blend: Float) {
@@ -307,32 +259,15 @@ class DroidDeckHudView(context: Context) : View(context) {
}
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) {
@@ -342,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)
@@ -372,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"
@@ -397,7 +328,6 @@ class DroidDeckHudView(context: Context) : View(context) {
rebuildAndInvalidate()
}
// ---- Lifecycle: self-refresh ------------------------------------------
override fun onAttachedToWindow() {
super.onAttachedToWindow()
if (isShown) startUpdates()
@@ -408,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()
@@ -438,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() {
@@ -459,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
@@ -504,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
@@ -537,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))
@@ -566,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('°')
@@ -576,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))
@@ -592,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))
@@ -605,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)
@@ -619,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
@@ -636,7 +537,6 @@ 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 spans = tabSpans()
@@ -649,7 +549,6 @@ class DroidDeckHudView(context: Context) : View(context) {
private fun tabSpans() = listOf(Span(one(fpsNow), colValue, sp(20f)), Span("fps", colDim, sp(8.5f)))
/** 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))
@@ -675,18 +574,14 @@ class DroidDeckHudView(context: Context) : View(context) {
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
@@ -714,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) {
@@ -748,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)
@@ -773,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 {
@@ -783,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
@@ -816,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
@@ -878,7 +753,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)))
@@ -902,9 +776,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)))
@@ -945,8 +816,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))
@@ -970,7 +839,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
@@ -1011,20 +880,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>()
@@ -1032,11 +893,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>) {
@@ -1049,9 +906,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)
@@ -1059,8 +913,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
@@ -1068,8 +920,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
@@ -1088,14 +938,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)
@@ -1103,22 +951,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),
@@ -1164,11 +1007,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)
@@ -1265,8 +1103,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)
@@ -1286,7 +1122,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)
@@ -1307,7 +1142,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)))
@@ -1339,7 +1173,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)))
@@ -1377,8 +1210,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)))
@@ -1387,15 +1218,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)))
@@ -1408,7 +1236,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)
@@ -1418,9 +1245,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) {
@@ -1436,12 +1260,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),
@@ -1461,7 +1283,6 @@ class DroidDeckHudView(context: Context) : View(context) {
drawTabPreview(canvas, blend)
}
/** The docked tab drawn at its own size in the middle of the view, undoing the view's scale. */
private fun drawTabPreview(canvas: Canvas, blend: Float) {
val (w, h) = dockTabSize()
if (scaleX <= 0f || scaleY <= 0f) return
@@ -1487,7 +1308,6 @@ class DroidDeckHudView(context: Context) : View(context) {
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)
@@ -1498,7 +1318,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
@@ -1509,14 +1328,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)
@@ -1528,7 +1344,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)
@@ -1538,7 +1353,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()
@@ -1560,8 +1374,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)
@@ -1575,7 +1387,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
@@ -1605,7 +1416,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)),
@@ -1616,7 +1426,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()
@@ -1657,10 +1466,8 @@ 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 onTabTouch(event)
if (event.actionMasked == MotionEvent.ACTION_DOWN && lockController.isLocked() &&
@@ -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
@@ -29,11 +22,9 @@ internal class FrameStats {
@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
@@ -81,10 +72,8 @@ internal class FrameStats {
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 +85,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
@@ -112,7 +100,6 @@ internal class FrameStats {
}
}
/** 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) {
@@ -145,11 +132,6 @@ internal class FrameStats {
}
}
/**
* 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 +142,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 +158,6 @@ 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. */
fun poll(nowNs: Long): Boolean {
val compositorAdded = compositorFrames != seenCompositorFrames
seenCompositorFrames = compositorFrames
@@ -185,7 +166,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 +179,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 +187,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 +225,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,48 +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);
/** The view moved under a drag (unlocked), with the finger at screen point (rawX, rawY). */
default void onDragged(float rawX, float rawY) {}
/** The drag ended in a fling (unlocked), in pixels per second; comes just before {@link #onMoved}. */
default void onFlung(float velocityX, float velocityY) {}
/** Lock toggled by long-press: persist {@code hudLocked} + sync the menu chip. */
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;
@@ -83,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;
@@ -110,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);
@@ -143,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);
@@ -153,7 +117,7 @@ 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();
}
@@ -171,7 +135,7 @@ public class HudLockController {
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));
@@ -203,7 +167,6 @@ public class HudLockController {
}
}
// ---- Fade badge -------------------------------------------------------
private void flash(boolean showLocked, long hold) {
fadeShowLocked = showLocked;
holdMs = hold;
@@ -236,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;
@@ -262,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) {
@@ -277,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) {
@@ -289,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[]>() {
@@ -3,12 +3,6 @@ package com.droiddeck.launcher.hud
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
/**
* 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)
@@ -17,7 +11,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
@@ -38,7 +31,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]
@@ -55,7 +47,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? {
var sum = 0f
var count = 0
@@ -85,7 +76,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 {
@@ -102,10 +92,8 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
return Memory((total - available) * 1024, total * 1024, (swapTotal - swapFree) * 1024, swapTotal * 1024)
}
/** The KGSL total DroidDeck shares with the session (GpuMemComponent). */
fun vramBytes(): Long? = fresh(File(rootDir, VRAM_FILE), VRAM_FRESH_MS)?.let(::readLong)
/** 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
@@ -149,7 +137,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()