mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-18 12:28:40 +00:00
feat: FusionHUD replaces the session HUD, with MangoHud's readings (#1743)
The session HUD is FusionHUD (Bannerlator's HUD) with every reading taken from the same source, and worked out the same way, as the MangoHud build that runs Steam's performance overlay in a DroidDeck session. - gamescope patch 0125 (gamescope-3.16.29-p19) shares the frame times that mangoapp reads (one per signalled commit of connector 0) in a ring named by DROIDDECK_HUD_FRAMES; the app reads it once per display frame and counts the compositor's frames when gamescope sends none. - MangoHud's rules: FPS over periods of at least 500 ms, frame time = 1000/FPS, 200-frame graph on a fixed 0-50 ms scale; CPU, GPU, temperatures, RAM, swap, VRAM and battery from MangoHud's sources. Zones 22/26/28 are typed as GPU and DDR sensors, so Steam's overlay CPU temperature no longer includes them. - Five sizes in a panel shaped like the DroidDeck mark, with a centred header, one left edge, neon outline and FPS; Minimal is the default size. Settings on a new "Performance HUD" drawer page, with Bannerlator's options. - The HUD reads sensors and polls frames only while it is drawn (not while hidden, in picture-in-picture or behind another app), keeps its place after picture-in-picture, and the diagnostics export has its own reader. Device-tested on the AYANEO Pocket FIT: same readings as Steam's overlay side by side in Dead Cells; the HUD updates in a game, hides in picture-in-picture and comes back in place, no crashes.
This commit is contained in:
1 parent
e871557bf2
commit
110cfc28f8
70 files changed
+7269
-320
No files matched your search
@@ -90,7 +90,8 @@ import com.droiddeck.launcher.input.TouchscreenGestures
|
||||
import com.droiddeck.launcher.input.ScrollTouchGestures
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.LoadingState
|
||||
import com.droiddeck.launcher.session.PerfHud
|
||||
import com.droiddeck.launcher.hud.FusionHudConfig
|
||||
import com.droiddeck.launcher.hud.FusionHudHost
|
||||
import com.droiddeck.launcher.session.PerfMode
|
||||
import com.droiddeck.launcher.session.SteamRepair
|
||||
import com.droiddeck.launcher.session.GameEnvironmentStore
|
||||
@@ -158,7 +159,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private lateinit var surfaceView: SurfaceView
|
||||
private lateinit var sessionOverlay: ComposeView
|
||||
private lateinit var loading: LoadingState
|
||||
private lateinit var hud: PerfHud
|
||||
private lateinit var hud: FusionHudHost
|
||||
private lateinit var memoryHud: com.droiddeck.launcher.session.MemoryHud
|
||||
private var padBridge: PadBridge? = null
|
||||
private var joyConVr: com.droiddeck.launcher.input.JoyConVr? = null
|
||||
@@ -333,9 +334,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
private var achievementsInFront by mutableStateOf<AchievementsInFront?>(null)
|
||||
private var achievementsOpen by mutableStateOf(false)
|
||||
private var hudOn by mutableStateOf(true)
|
||||
private var hudFps by mutableStateOf(true)
|
||||
private var hudBattery by mutableStateOf(true)
|
||||
private var hudGraph by mutableStateOf(true)
|
||||
private var hudConfig by mutableStateOf<Map<String, String>>(emptyMap())
|
||||
private var hudColor by mutableStateOf(SessionPrefs.HUD_COLOR_MINT)
|
||||
private var hudOpacity by mutableStateOf(SessionPrefs.HUD_OPACITY_DEFAULT)
|
||||
private var upscaler by mutableStateOf(0)
|
||||
@@ -641,7 +640,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
val needProton = protonUser && com.droiddeck.launcher.runtime.DesktopCatalog.protonSeedNeeded(this)
|
||||
if (needRuntime || needResume || needDesktop || needProton) installThenStart(needRuntime, needDesktop, needProton, needResume)
|
||||
}
|
||||
hud = PerfHud(this)
|
||||
hud = FusionHudHost(this)
|
||||
hud.onConfigChanged = { hudConfig = FusionHudConfig.load(this) }
|
||||
hud.attach(root, root.childCount)
|
||||
memoryHud = com.droiddeck.launcher.session.MemoryHud(this)
|
||||
hud.onPresentingWindowChanged = {
|
||||
if (FrameGen.engine(this) != FrameGen.ENGINE_OFF) CompositorHost.rearmFrameGen { applyFrameGen() }
|
||||
@@ -729,6 +730,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
onDispose { com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity, false) }
|
||||
}
|
||||
androidx.compose.runtime.LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, pipUi) { updatePointerCapture() }
|
||||
androidx.compose.runtime.LaunchedEffect(pipUi) { hud.setHidden(pipUi) }
|
||||
androidx.compose.runtime.LaunchedEffect(AgentGuest.steamKeyboard) { updateOnScreenControls() }
|
||||
androidx.compose.runtime.LaunchedEffect(picturePosition, SessionState.running, pipUi, cardboard.enabled) { applyGameAlignment() }
|
||||
DroidDeckTheme {
|
||||
@@ -744,9 +746,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) {
|
||||
CursorOverlay({ cursorPos }, cursorVisible, resources.displayMetrics.density,
|
||||
cursorImage, cursorHotX, cursorHotY, cursorImageScale)
|
||||
val hudLines = listOf(hud.text, memoryHud.text).filter { it.isNotEmpty() }
|
||||
if (hudLines.isNotEmpty() || hud.graph.size >= 2)
|
||||
HudText(hudLines.joinToString("\n"), hud.graph, hudColor, hudOpacity)
|
||||
if (memoryHud.text.isNotEmpty()) HudText(memoryHud.text, hudColor, hudOpacity)
|
||||
val phonePanel = glassesOutputActive && !loading.visible && !drawerOpen && !pcKeyboardOpen
|
||||
if (phonePanel) GlassesPhonePanel(glasses, steamVrStatus == SteamVr.Status.RUNNING, headTracking)
|
||||
if (trackingRecovery != null && !drawerOpen && !pcKeyboardOpen && !loading.visible) {
|
||||
@@ -943,11 +943,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
isHomeApp = isHomeApp,
|
||||
androidApps = androidApps,
|
||||
hudOn = hudOn,
|
||||
hudFps = hudFps,
|
||||
hudBattery = hudBattery,
|
||||
hudGraph = hudGraph,
|
||||
hudColor = hudColor,
|
||||
hudOpacity = hudOpacity,
|
||||
hudConfig = hudConfig,
|
||||
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
|
||||
effects = effects,
|
||||
cardboard = cardboard,
|
||||
@@ -978,11 +974,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
secondScreenDisplays = secondScreenDisplays,
|
||||
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
|
||||
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
|
||||
onHudFps = { on -> SessionPrefs.setHudShowFps(this@SessionActivity, on); hudFps = on; hud.refresh() },
|
||||
onHudBattery = { on -> SessionPrefs.setHudShowBattery(this@SessionActivity, on); hudBattery = on; hud.refresh() },
|
||||
onHudGraph = { on -> SessionPrefs.setHudShowGraph(this@SessionActivity, on); hudGraph = on; hud.refresh() },
|
||||
onHudColor = { color -> SessionPrefs.setHudColor(this@SessionActivity, color); hudColor = color },
|
||||
onHudOpacity = { percent -> SessionPrefs.setHudOpacity(this@SessionActivity, percent); hudOpacity = percent },
|
||||
onHudSetting = { key, value -> hudConfig = FusionHudConfig.set(this@SessionActivity, key, value); hud.applyConfig() },
|
||||
onHudReset = { hudConfig = FusionHudConfig.reset(this@SessionActivity); hud.applyConfig() },
|
||||
onHudExport = { exportHudDiagnostics() },
|
||||
onUpscaler = { m ->
|
||||
SessionPrefs.setUpscaler(this@SessionActivity, m); upscaler = m
|
||||
WaylandCompositor.nativeSetUpscaler(m)
|
||||
@@ -1604,6 +1598,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
else getString(R.string.load_starting_steam)
|
||||
}
|
||||
|
||||
private fun exportHudDiagnostics() {
|
||||
glassesScope.launch {
|
||||
val file = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) { hud.exportDiagnostics() }
|
||||
android.widget.Toast.makeText(this@SessionActivity,
|
||||
if (file != null) getString(R.string.hud_export_done, file.path) else getString(R.string.hud_export_failed),
|
||||
android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
|
||||
private fun shareCurrentSessionLogs() {
|
||||
val folder = SessionPaths.current() ?: SessionPaths.lastEnded()
|
||||
if (folder == null || !folder.isDirectory) {
|
||||
@@ -1629,9 +1632,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
unfoldedControlsWithController = SessionPrefs.unfoldedControlsWithController(this)
|
||||
picturePosition = SessionPrefs.picturePosition(this)
|
||||
hudOn = SessionPrefs.hudEnabled(this)
|
||||
hudFps = SessionPrefs.hudShowFps(this)
|
||||
hudBattery = SessionPrefs.hudShowBattery(this)
|
||||
hudGraph = SessionPrefs.hudShowGraph(this)
|
||||
hudConfig = FusionHudConfig.load(this)
|
||||
hudColor = SessionPrefs.hudColor(this)
|
||||
hudOpacity = SessionPrefs.hudOpacity(this)
|
||||
upscaler = SessionPrefs.upscaler(this)
|
||||
@@ -3280,6 +3281,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
super.onStart()
|
||||
if (runtimeRemovalBlocked) return
|
||||
started = true
|
||||
if (::hud.isInitialized) hud.setBackgrounded(false)
|
||||
refreshActivityDisplayId()
|
||||
displayManager.registerDisplayListener(displayListener, Handler(Looper.getMainLooper()))
|
||||
for (name in arrayOf("peak_refresh_rate", "min_refresh_rate")) {
|
||||
@@ -3297,6 +3299,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
|
||||
override fun onStop() {
|
||||
if (runtimeRemovalBlocked) { super.onStop(); return }
|
||||
started = false
|
||||
if (::hud.isInitialized) hud.setBackgrounded(true)
|
||||
updateHandCamera()
|
||||
displayManager.unregisterDisplayListener(displayListener)
|
||||
contentResolver.unregisterContentObserver(refreshSettingObserver)
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.droiddeck.launcher.hud
|
||||
|
||||
import android.graphics.Canvas
|
||||
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
|
||||
const val VIEW_H = 223.72f
|
||||
|
||||
private val body: Path by lazy {
|
||||
val d = Path().apply {
|
||||
moveTo(-31.98f, 0f)
|
||||
lineTo(63.97f, 0f)
|
||||
cubicTo(125.81f, 0f, 175.93f, 50.08f, 175.93f, 111.86f)
|
||||
cubicTo(175.93f, 173.64f, 125.81f, 223.72f, 63.97f, 223.72f)
|
||||
lineTo(-31.98f, 223.72f)
|
||||
close()
|
||||
}
|
||||
val cut = Path().apply {
|
||||
addCircle(63.98f, 111.86f, 71.81f, Path.Direction.CW)
|
||||
addRect(56.055f, 0f, 71.885f, 45f, Path.Direction.CW)
|
||||
addRect(56.055f, 178.72f, 71.885f, 223.72f, Path.Direction.CW)
|
||||
}
|
||||
d.op(cut, Path.Op.DIFFERENCE)
|
||||
d.offset(-VIEW_X, 0f)
|
||||
d
|
||||
}
|
||||
|
||||
private val scaled = Path()
|
||||
private val matrix = Matrix()
|
||||
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
|
||||
|
||||
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
|
||||
|
||||
fun draw(canvas: Canvas, left: Float, top: Float, height: Float, bodyColor: Int, orbColor: Int) {
|
||||
val s = height / VIEW_H
|
||||
matrix.setScale(s, s)
|
||||
matrix.postTranslate(left, top)
|
||||
body.transform(matrix, scaled)
|
||||
paint.color = bodyColor
|
||||
canvas.drawPath(scaled, paint)
|
||||
paint.color = orbColor
|
||||
canvas.drawCircle(left + (63.98f - VIEW_X) * s, top + 111.86f * s, 55.98f * s, paint)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.droiddeck.launcher.hud
|
||||
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
|
||||
/** FusionHUD's settings as one "key=value,…" string (FusionHudView.applyConfig), stored in SessionPrefs. */
|
||||
internal object FusionHudConfig {
|
||||
/** Bannerlator's Fusion defaults (DeckOverlaySettings), with the FPS graph from the old DroidDeck HUD. */
|
||||
val DEFAULTS: Map<String, String> = linkedMapOf(
|
||||
"hudSize" to "minimal", "hudLocked" to "0", "hudScale" to "100", "hudOpacity" to "80", "hudColor" to "mid",
|
||||
"hudOutline" to "40", "hudOutlineAccent" to "1",
|
||||
"showFPS" to "1", "showFPSGraph" to "1", "showCPUUsage" to "1", "showCPULoad" to "1", "showGPULoad" to "1",
|
||||
"showVram" to "1", "showRAM" to "1", "showPower" to "1", "showTemp" to "1", "showBatteryTemp" to "1",
|
||||
"showGpuTemp" to "0", "showBattery" to "0", "showLow001" to "1", "fpsDecimal" to "1", "showPerCore" to "1",
|
||||
"showSwap" to "1", "showNet" to "1", "showResolution" to "1", "showProton" to "1", "showSession" to "1",
|
||||
"showClock" to "1", "showEngine" to "1", "showRenderer" to "1", "showGpuModel" to "1",
|
||||
"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> {
|
||||
val values = LinkedHashMap(DEFAULTS)
|
||||
val stored = SessionPrefs.fusionHudConfig(context)
|
||||
if (stored == null) {
|
||||
values["showFPS"] = flag(SessionPrefs.hudShowFps(context))
|
||||
values["showFPSGraph"] = flag(SessionPrefs.hudShowGraph(context))
|
||||
values["hudOpacity"] = SessionPrefs.hudOpacity(context).toString()
|
||||
} else {
|
||||
for (entry in KeyValueSet(stored)) if (entry.size == 2 && entry[0] in DEFAULTS) values[entry[0]] = entry[1]
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
fun encode(values: Map<String, String>): String = values.entries.joinToString(",") { "${it.key}=${it.value}" }
|
||||
|
||||
fun set(context: Context, key: String, value: String): Map<String, String> {
|
||||
val values = load(context)
|
||||
if (key !in DEFAULTS) return values
|
||||
values[key] = value
|
||||
TWINS[key]?.let { values[it] = value }
|
||||
SessionPrefs.setFusionHudConfig(context, encode(values))
|
||||
return values
|
||||
}
|
||||
|
||||
fun reset(context: Context): Map<String, String> {
|
||||
SessionPrefs.setFusionHudConfig(context, encode(DEFAULTS))
|
||||
return DEFAULTS
|
||||
}
|
||||
|
||||
private fun flag(on: Boolean) = if (on) "1" else "0"
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package com.droiddeck.launcher.hud
|
||||
|
||||
import android.content.Context
|
||||
import android.os.Environment
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.Choreographer
|
||||
import android.view.View
|
||||
import android.view.ViewGroup
|
||||
import android.widget.FrameLayout
|
||||
import com.droiddeck.launcher.gpu.FrameGen
|
||||
import com.droiddeck.launcher.gpu.GpuInfo
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
/**
|
||||
* FusionHUD 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 FusionHudHost(context: Context) {
|
||||
private val context = context.applicationContext
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val feed = GameFrameFeed(File(LinuxRuntime.rootDir(this.context), HudFrames.PATH))
|
||||
private val readings = MangoReadings(File(this.context.filesDir, "session"), LinuxRuntime.rootDir(this.context))
|
||||
private var view: FusionHudView? = null
|
||||
private var parent: ViewGroup? = null
|
||||
private var running = false
|
||||
private var hidden = false
|
||||
private var backgrounded = false
|
||||
private var polling = false
|
||||
private var wantX = Float.NaN
|
||||
private var wantY = Float.NaN
|
||||
private var engine = ""
|
||||
private var gpuName = ""
|
||||
private var protonPid = 0
|
||||
private var proton = ""
|
||||
@Volatile private var lastWindow: String? = null
|
||||
|
||||
var onPresentingWindowChanged: (() -> Unit)? = null
|
||||
|
||||
/** The HUD itself changed a setting: a tap cycles the size, a long press locks it. */
|
||||
var onConfigChanged: (() -> Unit)? = null
|
||||
|
||||
private val listener = object : WaylandCompositor.GameListener {
|
||||
override fun onGameSurface(window: String?, gpuName: String?) {
|
||||
if (!gpuName.isNullOrBlank()) handler.post { this@FusionHudHost.gpuName = cleanGpuName(gpuName) }
|
||||
if (window != null && window != lastWindow) {
|
||||
lastWindow = window
|
||||
handler.post { onPresentingWindowChanged?.invoke() }
|
||||
}
|
||||
}
|
||||
|
||||
override fun onGameFrame() {
|
||||
feed.onCompositorFrame(System.nanoTime())
|
||||
}
|
||||
}
|
||||
|
||||
private val frameCallback = object : Choreographer.FrameCallback {
|
||||
override fun doFrame(frameTimeNanos: Long) {
|
||||
if (!running || !polling) return
|
||||
if (feed.poll(System.nanoTime())) view?.onFrames()
|
||||
Choreographer.getInstance().postFrameCallback(this)
|
||||
}
|
||||
}
|
||||
|
||||
private val enabled: Boolean
|
||||
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 = FusionHudView(root.context)
|
||||
hud.setFrameStats(feed.stats)
|
||||
hud.setMangoReadings(readings)
|
||||
hud.setGpuModel(cleanGpuName(GpuInfo.detect().displayName(context)))
|
||||
hud.onRefresh = Runnable { refreshLabels(hud) }
|
||||
hud.setOnMovedListener { x, y ->
|
||||
wantX = x; wantY = y
|
||||
keepOnScreen(hud)
|
||||
wantX = hud.x; wantY = hud.y
|
||||
SessionPrefs.setFusionHudPosition(context, hud.x, hud.y)
|
||||
}
|
||||
hud.setOnSizeCycledListener { size -> FusionHudConfig.set(context, "hudSize", size); onConfigChanged?.invoke() }
|
||||
hud.setOnLockChangedListener { locked ->
|
||||
FusionHudConfig.set(context, "hudLocked", if (locked) "1" else "0")
|
||||
onConfigChanged?.invoke()
|
||||
}
|
||||
hud.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> if (!hud.isDragging) keepOnScreen(hud) }
|
||||
hud.visibility = View.GONE
|
||||
val margin = (16 * root.resources.displayMetrics.density).roundToInt()
|
||||
root.addView(hud, index, FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply {
|
||||
leftMargin = margin
|
||||
topMargin = margin
|
||||
})
|
||||
SessionPrefs.fusionHudPosition(context)?.let { (x, y) -> wantX = x; wantY = y; hud.post { keepOnScreen(hud) } }
|
||||
view = hud
|
||||
parent = root
|
||||
applyConfig()
|
||||
}
|
||||
|
||||
fun applyConfig() {
|
||||
view?.applyConfig(FusionHudConfig.encode(FusionHudConfig.load(context)))
|
||||
}
|
||||
|
||||
fun refresh() {
|
||||
applyConfig()
|
||||
if (!enabled) stop() else if (!running) start()
|
||||
}
|
||||
|
||||
fun start() {
|
||||
if (running || !enabled || view == null) return
|
||||
running = true
|
||||
WaylandCompositor.setGameListener(listener)
|
||||
applyShown()
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
running = false
|
||||
showing = false
|
||||
polling = false
|
||||
Choreographer.getInstance().removeFrameCallback(frameCallback)
|
||||
WaylandCompositor.clearGameListener(listener)
|
||||
feed.close()
|
||||
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()
|
||||
}
|
||||
|
||||
private fun applyShown() {
|
||||
if (!running) return
|
||||
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)
|
||||
else Choreographer.getInstance().removeFrameCallback(frameCallback)
|
||||
}
|
||||
}
|
||||
|
||||
/** A sensor report (FusionHUD'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()
|
||||
Thread.sleep(500)
|
||||
val mango = metrics.snapshot()
|
||||
file.writeText(metrics.also { it.setMangoReadings(null) }.buildDiagnosticsReport(context) + "\n== As the HUD shows them (MangoHud's sources) ==\n" +
|
||||
"CPU ${mango.cpuPercent}% ${mango.cpuTempC}°C, GPU ${mango.gpuPercent}% ${mango.gpuClockMhz}MHz ${mango.gpuTempC}°C, " +
|
||||
"RAM ${mango.ramUsedText()}/${mango.ramTotalText()}, VRAM ${mango.vramText()}, battery ${mango.battery.percent}% " +
|
||||
"${mango.battery.watts}W charging=${mango.battery.charging}\n" +
|
||||
"CPU temperature zones: ${LinuxRuntime.cpuTempZones().joinToString { it.name }}\n" +
|
||||
"Frames: ${if (feed.engine.isNotEmpty() || feed.pid > 0) "gamescope (pid ${feed.pid}, ${feed.engine})" else "compositor"}, " +
|
||||
"fps ${feed.stats.fps}\n")
|
||||
file
|
||||
}.getOrNull()
|
||||
|
||||
private fun refreshLabels(hud: FusionHudView) {
|
||||
if (feed.engine.isNotBlank() && !feed.steamFocused) engine = feed.engine
|
||||
hud.setEngineLabel(engine)
|
||||
if (gpuName.isNotBlank()) hud.setGpuModel(gpuName)
|
||||
hud.setResolution(if (feed.outputWidth > 0 && feed.outputHeight > 0) buildString {
|
||||
append(feed.outputWidth).append('x').append(feed.outputHeight)
|
||||
if (feed.refreshMilliHz > 0) append(" @ ").append((feed.refreshMilliHz + 499) / 1000).append("Hz")
|
||||
} else "")
|
||||
val pid = feed.pid
|
||||
if (pid > 0 && pid != protonPid) {
|
||||
protonPid = pid
|
||||
proton = protonName(pid) ?: proton
|
||||
}
|
||||
hud.setWineVersion(proton)
|
||||
hud.setPresentedFps(presentedFps())
|
||||
}
|
||||
|
||||
private fun presentedFps(): Float {
|
||||
if (FrameGen.mode(context).engine == FrameGen.ENGINE_OFF) return 0f
|
||||
val stats = runCatching { WaylandCompositor.nativeFrameGenStats() }.getOrNull() ?: return 0f
|
||||
return if (stats.size > 3 && stats[3] > 1f) stats[3] else 0f
|
||||
}
|
||||
|
||||
// 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) {
|
||||
val p = v.parent as? View ?: return
|
||||
if (p.width <= 0 || p.height <= 0 || v.width <= 0 || v.height <= 0) return
|
||||
if (wantX.isNaN()) { wantX = v.x; wantY = v.y }
|
||||
val maxX = (p.width - v.width).toFloat().coerceAtLeast(0f)
|
||||
val maxY = (p.height - v.height).toFloat().coerceAtLeast(0f)
|
||||
val x = wantX.coerceIn(0f, maxX)
|
||||
val y = wantY.coerceIn(0f, maxY)
|
||||
if (v.x != x) v.x = x
|
||||
if (v.y != y) v.y = y
|
||||
}
|
||||
|
||||
companion object {
|
||||
/** 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
|
||||
paths.split(':').firstOrNull { it.isNotBlank() }?.trimEnd('/')?.substringAfterLast('/')
|
||||
}.getOrNull()?.takeIf { it.isNotBlank() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* FusionHUD — a lightweight in-game performance HUD for Android / Winlator overlays.
|
||||
* Copyright (C) The412Banner <https://github.com/The412Banner>
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0 (see LICENSE), with an
|
||||
* ADDITIONAL attribution requirement under GPL-3.0 §7(b) (see ATTRIBUTION.md):
|
||||
* any use, fork, or distribution must preserve credit to "The412Banner" and a
|
||||
* 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.
|
||||
*/
|
||||
|
||||
package com.droiddeck.launcher.hud
|
||||
|
||||
/**
|
||||
* Size modes for the Fusion 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 FusionSize(val token: String, val label: String) {
|
||||
FULL("full", "Full"),
|
||||
TILES("tiles", "Tiles"),
|
||||
PILL("pill", "Pill"),
|
||||
MINIMAL("minimal", "Minimal"),
|
||||
MEGA("mega", "Mega");
|
||||
|
||||
/** Next size in the tap-cycle: Full → Tiles → Pill → Minimal → Mega → Full. */
|
||||
fun next(): FusionSize {
|
||||
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
|
||||
FULL, TILES -> STANDARD_CHIPS
|
||||
MEGA -> MEGA_CHIPS
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun from(token: String?): FusionSize =
|
||||
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(
|
||||
"FPS", "FPS graph", "GPU", "GPU temp", "CPU", "VRAM", "RAM", "Power", "Temp",
|
||||
"Battery", "GPU model", "Engine", "0.01% low", "FPS .1", "Clock",
|
||||
)
|
||||
val MEGA_ONLY = setOf(
|
||||
"Per-core", "Swap", "Network", "Resolution", "Proton", "Wrapper", "DX ver", "Session",
|
||||
)
|
||||
val MEGA_CHIPS = STANDARD_CHIPS + MEGA_ONLY
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The Wayland HDR state the Fusion HUD shows on its own line, directly under the latency · display-server
|
||||
* line (the host sets it with [FusionHudView.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 FusionHdr {
|
||||
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.
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,262 @@
|
||||
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 FusionHUD's own readouts.
|
||||
*/
|
||||
internal class FrameStats {
|
||||
private val graph = FloatArray(GRAPH_FRAMES)
|
||||
private var graphHead = 0
|
||||
private var lastPresentNs = 0L
|
||||
private var lastFpsUpdateNs = 0L
|
||||
private var framesSinceUpdate = 0
|
||||
|
||||
private val lowsRing = LongArray(LOWS_FRAMES)
|
||||
private var lowsHead = 0
|
||||
private var lowsSize = 0
|
||||
private var cachedLows = Lows.EMPTY
|
||||
private var cachedLowsNs = 0L
|
||||
|
||||
private var sessionStartNs = 0L
|
||||
private var sessionFrames = 0L
|
||||
|
||||
@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
|
||||
|
||||
@Synchronized
|
||||
fun add(frametimeNs: Long, timeNs: Long) {
|
||||
if (frametimeNs <= 0L) return
|
||||
if (lastPresentNs != 0L) {
|
||||
graph[graphHead] = frametimeNs / 1e6f
|
||||
graphHead = (graphHead + 1) % GRAPH_FRAMES
|
||||
}
|
||||
val elapsed = timeNs - lastFpsUpdateNs
|
||||
if (elapsed >= FPS_PERIOD_NS) {
|
||||
fps = (1e9 * framesSinceUpdate / elapsed).toFloat()
|
||||
framesSinceUpdate = 0
|
||||
lastFpsUpdateNs = timeNs
|
||||
fpsUpdates++
|
||||
}
|
||||
lastPresentNs = timeNs
|
||||
framesSinceUpdate++
|
||||
|
||||
if (frametimeNs < PAUSE_NS) {
|
||||
lowsRing[lowsHead] = frametimeNs
|
||||
lowsHead = (lowsHead + 1) % LOWS_FRAMES
|
||||
if (lowsSize < LOWS_FRAMES) lowsSize++
|
||||
if (sessionStartNs == 0L) sessionStartNs = timeNs - frametimeNs
|
||||
sessionFrames++
|
||||
}
|
||||
count++
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun reset() {
|
||||
graph.fill(0f)
|
||||
graphHead = 0
|
||||
lastPresentNs = 0L
|
||||
lastFpsUpdateNs = 0L
|
||||
framesSinceUpdate = 0
|
||||
lowsHead = 0
|
||||
lowsSize = 0
|
||||
cachedLows = Lows.EMPTY
|
||||
cachedLowsNs = 0L
|
||||
sessionStartNs = 0L
|
||||
sessionFrames = 0L
|
||||
fps = 0f
|
||||
count++
|
||||
}
|
||||
|
||||
/** MangoHud's frame time readout: 1000 / FPS. */
|
||||
fun frametimeMs(): Float = 1000f / maxOf(fps, 1f)
|
||||
|
||||
/** The graph, oldest first, into [out] (GRAPH_FRAMES long). */
|
||||
@Synchronized
|
||||
fun graph(out: FloatArray) {
|
||||
for (i in 0 until GRAPH_FRAMES) out[i] = graph[(graphHead + i) % GRAPH_FRAMES]
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun graphMinMs(): Float = graph.min()
|
||||
|
||||
@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
|
||||
return (1e9 * sessionFrames / (lastPresentNs - sessionStartNs)).toFloat()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun sessionSeconds(nowNs: Long): Float = if (sessionStartNs == 0L) 0f else (nowNs - sessionStartNs) / 1e9f
|
||||
|
||||
class Lows(val low1Fps: Float, val low01Fps: Float, val low001Fps: Float) {
|
||||
companion object {
|
||||
val EMPTY = Lows(0f, 0f, 0f)
|
||||
}
|
||||
}
|
||||
|
||||
/** FPS at the 99th, 99.9th and 99.99th percentile frame time of the last LOWS_FRAMES frames. */
|
||||
fun lows(nowNs: Long): Lows {
|
||||
val copy: LongArray
|
||||
synchronized(this) {
|
||||
if (cachedLows !== Lows.EMPTY && nowNs - cachedLowsNs < LOWS_RECOMPUTE_NS) return cachedLows
|
||||
if (lowsSize < 2) return Lows.EMPTY
|
||||
copy = LongArray(lowsSize)
|
||||
val start = (lowsHead - lowsSize + LOWS_FRAMES) % LOWS_FRAMES
|
||||
for (i in 0 until lowsSize) copy[i] = lowsRing[(start + i) % LOWS_FRAMES]
|
||||
}
|
||||
copy.sort()
|
||||
fun at(p: Double): Float {
|
||||
val ft = copy[(p * (copy.size - 1)).roundToInt().coerceIn(0, copy.size - 1)]
|
||||
return if (ft > 0) (1e9 / ft).toFloat() else 0f
|
||||
}
|
||||
val result = Lows(at(0.99), at(0.999), at(0.9999))
|
||||
synchronized(this) {
|
||||
cachedLows = result
|
||||
cachedLowsNs = nowNs
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val GRAPH_FRAMES = 200
|
||||
const val GRAPH_MAX_MS = 50f
|
||||
const val FPS_PERIOD_NS = 500_000_000L
|
||||
const val LOWS_FRAMES = 8192
|
||||
private const val PAUSE_NS = 1_000_000_000L
|
||||
private const val LOWS_RECOMPUTE_NS = 250_000_000L
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Feeds [stats] with the frame times gamescope shares (the ones MangoHud shows). Sessions without the
|
||||
* shared file, or where gamescope stopped sending, fall back to the frames DroidDeck's compositor shows,
|
||||
* which stop at the screen's refresh rate.
|
||||
*/
|
||||
internal class GameFrameFeed(private val file: File, val stats: FrameStats = FrameStats()) {
|
||||
private var handle = 0L
|
||||
private var nextOpenNs = 0L
|
||||
private var lastRingFrameNs = 0L
|
||||
private var lastInfoNs = 0L
|
||||
private val frametimes = LongArray(HudFrames.CAPACITY)
|
||||
private val times = LongArray(HudFrames.CAPACITY)
|
||||
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
|
||||
private var seenCompositorFrames = 0L
|
||||
|
||||
@Volatile var engine = ""
|
||||
private set
|
||||
@Volatile var steamFocused = false
|
||||
private set
|
||||
@Volatile var pid = 0
|
||||
private set
|
||||
@Volatile var outputWidth = 0
|
||||
private set
|
||||
@Volatile var outputHeight = 0
|
||||
private set
|
||||
@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
|
||||
if (handle == 0L) {
|
||||
if (nowNs < nextOpenNs) return compositorAdded
|
||||
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)
|
||||
if (n > 0) {
|
||||
if (!fromGamescope) {
|
||||
stats.reset()
|
||||
fromGamescope = true
|
||||
}
|
||||
for (i in 0 until n) stats.add(frametimes[i], times[i])
|
||||
lastRingFrameNs = times[n - 1]
|
||||
} 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
|
||||
readInfo()
|
||||
}
|
||||
return n > 0 || compositorAdded
|
||||
}
|
||||
|
||||
/** Compositor thread: one frame shown on the panel. */
|
||||
fun onCompositorFrame(nowNs: Long) {
|
||||
if (fromGamescope) {
|
||||
lastCompositorNs = 0L
|
||||
return
|
||||
}
|
||||
val last = lastCompositorNs
|
||||
lastCompositorNs = nowNs
|
||||
if (last != 0L) {
|
||||
stats.add(nowNs - last, nowNs)
|
||||
compositorFrames++
|
||||
}
|
||||
}
|
||||
|
||||
fun close() {
|
||||
if (handle != 0L) HudFrames.nativeClose(handle)
|
||||
handle = 0L
|
||||
}
|
||||
|
||||
private fun readInfo() {
|
||||
val name = if (handle != 0L && fromGamescope) HudFrames.nativeInfo(handle, info) else null
|
||||
if (name == null) {
|
||||
engine = ""
|
||||
return
|
||||
}
|
||||
pid = info[0]
|
||||
outputWidth = info[1]
|
||||
outputHeight = info[2]
|
||||
refreshMilliHz = info[3]
|
||||
steamFocused = info[4] != 0
|
||||
engine = engineLabel(name)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val REOPEN_NS = 2_000_000_000L
|
||||
private const val LIVE_NS = 2_000_000_000L
|
||||
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"
|
||||
"mesa zink" -> "ZINK"
|
||||
"Damavand" -> "DAMAVAND"
|
||||
"Feral3D" -> "Feral3D"
|
||||
"gamescope", "" -> "GAMESCOPE"
|
||||
else -> "VULKAN"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
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
|
||||
|
||||
@JvmStatic external fun nativeOpen(path: String): Long
|
||||
@JvmStatic external fun nativeClose(handle: Long)
|
||||
@JvmStatic external fun nativePoll(handle: Long, frametimes: LongArray, times: LongArray): Int
|
||||
@JvmStatic external fun nativeInfo(handle: Long, info: IntArray): String?
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
/*
|
||||
* FusionHUD — a lightweight in-game performance HUD for Android / Winlator overlays.
|
||||
* Copyright (C) The412Banner <https://github.com/The412Banner>
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0 (see LICENSE), with an
|
||||
* ADDITIONAL attribution requirement under GPL-3.0 §7(b) (see ATTRIBUTION.md):
|
||||
* any use, fork, or distribution must preserve credit to "The412Banner" and a
|
||||
* 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.
|
||||
*/
|
||||
|
||||
package com.droiddeck.launcher.hud;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Path;
|
||||
import android.graphics.RectF;
|
||||
import android.os.SystemClock;
|
||||
import android.view.GestureDetector;
|
||||
import android.view.MotionEvent;
|
||||
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 Fusion 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
|
||||
* Fusion) — 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).</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 (fusion). */
|
||||
void onTap();
|
||||
/** Drag released (unlocked): persist the new (x, y). */
|
||||
void onMoved(float x, float y);
|
||||
/** Lock toggled by long-press: persist {@code hudLocked} + sync the menu chip. */
|
||||
void onLockChanged(boolean locked);
|
||||
}
|
||||
|
||||
// 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;
|
||||
private static final long FADE_OUT_MS = 420;
|
||||
private static final long FRAME_MS = 32;
|
||||
|
||||
private final View view;
|
||||
private final Callbacks cb;
|
||||
private final GestureDetector detector;
|
||||
|
||||
private boolean locked = false;
|
||||
|
||||
// Drag state
|
||||
private float downRawX, downRawY, startX, startY;
|
||||
private boolean dragging = false;
|
||||
|
||||
// Fade state
|
||||
private long fadeStart = 0;
|
||||
private long holdMs = HOLD_TOGGLE_MS;
|
||||
private boolean fadeShowLocked = false;
|
||||
|
||||
private final Paint iconFill = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private final Paint iconStroke = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
|
||||
public HudLockController(Context context, View view, Callbacks cb) {
|
||||
this.view = view;
|
||||
this.cb = cb;
|
||||
this.detector = new GestureDetector(context, new Listener());
|
||||
this.detector.setIsLongpressEnabled(true);
|
||||
iconFill.setStyle(Paint.Style.FILL);
|
||||
iconStroke.setStyle(Paint.Style.STROKE);
|
||||
iconStroke.setStrokeCap(Paint.Cap.ROUND);
|
||||
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) {
|
||||
detector.onTouchEvent(event);
|
||||
int action = event.getActionMasked();
|
||||
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
|
||||
if (dragging && !locked) cb.onMoved(view.getX(), view.getY());
|
||||
dragging = false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private final class Listener extends GestureDetector.SimpleOnGestureListener {
|
||||
@Override
|
||||
public boolean onDown(MotionEvent e) {
|
||||
downRawX = e.getRawX();
|
||||
downRawY = e.getRawY();
|
||||
startX = view.getX();
|
||||
startY = view.getY();
|
||||
dragging = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@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);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onSingleTapUp(MotionEvent e) {
|
||||
if (locked) {
|
||||
flash(true, HOLD_REFLASH_MS); // intentionally locked — remind the user
|
||||
} else {
|
||||
cb.onTap();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
|
||||
if (locked) {
|
||||
if (!dragging) flash(true, HOLD_REFLASH_MS);
|
||||
dragging = true; // mark so the blocked drag doesn't fall through to a tap
|
||||
return true;
|
||||
}
|
||||
view.setX(startX + (e2.getRawX() - downRawX));
|
||||
view.setY(startY + (e2.getRawY() - downRawY));
|
||||
dragging = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Fade badge -------------------------------------------------------
|
||||
private void flash(boolean showLocked, long hold) {
|
||||
fadeShowLocked = showLocked;
|
||||
holdMs = hold;
|
||||
fadeStart = SystemClock.elapsedRealtime();
|
||||
view.removeCallbacks(fadeTick);
|
||||
view.post(fadeTick);
|
||||
}
|
||||
|
||||
private final Runnable fadeTick = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
view.invalidate();
|
||||
if (currentAlpha() > 0f) view.postDelayed(this, FRAME_MS);
|
||||
}
|
||||
};
|
||||
|
||||
private float currentAlpha() {
|
||||
if (fadeStart == 0) return 0f;
|
||||
long e = SystemClock.elapsedRealtime() - fadeStart;
|
||||
if (e < 0) return 0f;
|
||||
if (e < FADE_IN_MS) return e / (float) FADE_IN_MS;
|
||||
long holdEnd = FADE_IN_MS + holdMs;
|
||||
if (e < holdEnd) return 1f;
|
||||
long outEnd = holdEnd + FADE_OUT_MS;
|
||||
if (e < outEnd) return 1f - (e - holdEnd) / (float) FADE_OUT_MS;
|
||||
return 0f;
|
||||
}
|
||||
|
||||
private static int withAlpha(int color, float a) {
|
||||
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;
|
||||
float d = view.getResources().getDisplayMetrics().density;
|
||||
float size = 15f * d;
|
||||
float margin = 4f * d;
|
||||
float right = view.getWidth() - margin;
|
||||
float left = right - size;
|
||||
float top = margin;
|
||||
|
||||
float cx = (left + right) / 2f;
|
||||
float bottom = top + size;
|
||||
float bodyTop = top + size * 0.46f;
|
||||
float bodyLeft = left + size * 0.14f;
|
||||
float bodyRight = right - size * 0.14f;
|
||||
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) {
|
||||
iconFill.setColor(color);
|
||||
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) {
|
||||
int prev = iconFill.getColor();
|
||||
iconFill.setColor(Color.argb(Color.alpha(color), 0, 0, 0));
|
||||
canvas.drawCircle(cx, (bodyTop + bottom) / 2f, 1.6f * d, iconFill);
|
||||
iconFill.setColor(prev);
|
||||
}
|
||||
|
||||
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
|
||||
Path p = new Path();
|
||||
p.addArc(arc, 180f, 180f);
|
||||
p.moveTo(cx - r, shackleTop + r); p.lineTo(cx - r, bodyTop); // full-length left leg
|
||||
canvas.save();
|
||||
canvas.rotate(-42f, cx + r, shackleTop + r);
|
||||
canvas.drawPath(p, iconStroke);
|
||||
canvas.restore();
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,132 @@
|
||||
/*
|
||||
* FusionHUD — a lightweight in-game performance HUD for Android / Winlator overlays.
|
||||
* Copyright (C) The412Banner <https://github.com/The412Banner>
|
||||
*
|
||||
* Licensed under the GNU General Public License v3.0 (see LICENSE), with an
|
||||
* ADDITIONAL attribution requirement under GPL-3.0 §7(b) (see ATTRIBUTION.md):
|
||||
* any use, fork, or distribution must preserve credit to "The412Banner" and a
|
||||
* 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.
|
||||
*/
|
||||
|
||||
package com.droiddeck.launcher.hud;
|
||||
|
||||
import androidx.annotation.NonNull;
|
||||
|
||||
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(",");
|
||||
if (end == -1) end = data.length();
|
||||
|
||||
while (start < end) {
|
||||
int index = data.indexOf("=", start);
|
||||
String currKey = data.substring(start, index);
|
||||
if (currKey.equals(key)) return new int[]{start, end};
|
||||
start = end + 1;
|
||||
end = data.indexOf(",", start);
|
||||
if (end == -1) end = data.length();
|
||||
}
|
||||
|
||||
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) {
|
||||
data = data.substring(0, range[0]) + key + "=" + value + data.substring(range[1]);
|
||||
} else {
|
||||
data = (!data.isEmpty() ? data + "," : "") + key + "=" + value;
|
||||
}
|
||||
}
|
||||
|
||||
// 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[]>() {
|
||||
@Override
|
||||
public boolean hasNext() {
|
||||
return start[0] < end[0];
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] next() {
|
||||
int index = data.indexOf("=", start[0]);
|
||||
item[0] = data.substring(start[0], index);
|
||||
item[1] = data.substring(index + 1, end[0]);
|
||||
start[0] = end[0] + 1;
|
||||
end[0] = data.indexOf(",", start[0]);
|
||||
if (end[0] == -1) end[0] = data.length();
|
||||
return item;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public String toString() {
|
||||
return data;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
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)
|
||||
class Battery(val percent: Int?, val watts: Float, val charging: Boolean)
|
||||
|
||||
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
|
||||
var total: Int? = null
|
||||
val cores = ArrayList<Int>()
|
||||
for (line in lines) {
|
||||
if (!line.startsWith("cpu")) break
|
||||
val parts = line.split(WHITESPACE)
|
||||
if (parts.size < 11) continue
|
||||
val values = LongArray(10) { parts[it + 1].toLongOrNull() ?: 0L }
|
||||
val percent = cpuPercent(parts[0], values)
|
||||
if (parts[0] == "cpu") total = percent else cores.add(percent)
|
||||
}
|
||||
return total?.let { Cpu(it, cores.toIntArray()) }
|
||||
}
|
||||
|
||||
private fun statFile(): File =
|
||||
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]
|
||||
val idleAll = v[3] + v[4]
|
||||
val virt = v[8] + v[9]
|
||||
val totalTime = user + nice + systemAll + idleAll + v[7] + virt
|
||||
val now = longArrayOf(user, nice, systemAll, v[7], virt, totalTime)
|
||||
val last = cpuTimes.put(key, now) ?: LongArray(6)
|
||||
fun period(i: Int) = if (now[i] > last[i]) now[i] - last[i] else 0L
|
||||
val totalPeriod = period(5).toFloat()
|
||||
if (totalPeriod == 0f) return cpuPercents[key] ?: 0
|
||||
val busy = period(1) * 100f / totalPeriod + period(0) * 100f / totalPeriod +
|
||||
period(2) * 100f / totalPeriod + (period(3) + period(4)) * 100f / totalPeriod
|
||||
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
|
||||
for (zone in LinuxRuntime.cpuTempZones()) {
|
||||
val milli = readLong(File(zone, "temp")) ?: continue
|
||||
sum += milli / 1000f
|
||||
count++
|
||||
}
|
||||
return if (count == 0) null else (sum / count).toInt()
|
||||
}
|
||||
|
||||
fun gpuPercent(): Int? {
|
||||
val feed = fresh(File(sessionDir, "sys/kgsl-3d0/perf_now"))
|
||||
val source = feed ?: LinuxRuntime.gpuLoadSource()?.let(::File) ?: return null
|
||||
return leadingNumber(source)?.toInt()?.coerceIn(0, 100)
|
||||
}
|
||||
|
||||
fun gpuClockMhz(): Int? {
|
||||
val feed = fresh(File(sessionDir, "sys/kgsl-3d0/cur_freq"))
|
||||
val source = feed ?: listOf("$KGSL/devfreq/cur_freq", "$KGSL/gpuclk").map(::File).firstOrNull { it.canRead() } ?: return null
|
||||
val hz = leadingNumber(source) ?: return null
|
||||
return (hz / 1_000_000.0).toInt().takeIf { it > 0 }
|
||||
}
|
||||
|
||||
fun gpuTempC(): Int? {
|
||||
val milli = LinuxRuntime.gpuTempSource()?.let { readLong(File(it)) } ?: return null
|
||||
return (milli / 1000.0).toInt()
|
||||
}
|
||||
|
||||
/** MemTotal - MemAvailable and SwapTotal - SwapFree from /proc/meminfo. */
|
||||
fun memory(): Memory? {
|
||||
val kb = HashMap<String, Long>()
|
||||
runCatching {
|
||||
File("/proc/meminfo").forEachLine { line ->
|
||||
val colon = line.indexOf(':')
|
||||
if (colon > 0) line.substring(colon + 1).trim().split(WHITESPACE).firstOrNull()?.toLongOrNull()
|
||||
?.let { kb[line.substring(0, colon)] = it }
|
||||
}
|
||||
}
|
||||
val total = kb["MemTotal"] ?: return null
|
||||
val available = kb["MemAvailable"] ?: return null
|
||||
val swapTotal = kb["SwapTotal"] ?: 0L
|
||||
val swapFree = kb["SwapFree"] ?: 0L
|
||||
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
|
||||
var chargeNow = 0f
|
||||
var chargeFull = 0f
|
||||
var watts = 0f
|
||||
var charging = false
|
||||
for (dir in dirs) {
|
||||
val status = runCatching { File(dir, "status").readLines().firstOrNull() }.getOrNull()
|
||||
if (status == "Charging" || status == "Unknown" || status == "Full") charging = true
|
||||
val now = File(dir, "charge_now").takeIf { it.exists() } ?: File(dir, "energy_now")
|
||||
val full = File(dir, "charge_full").takeIf { it.exists() } ?: File(dir, "energy_full")
|
||||
if (now.exists()) {
|
||||
chargeNow += (readFloat(now) ?: 0f) / 1_000_000f
|
||||
chargeFull += (readFloat(full) ?: 0f) / 1_000_000f
|
||||
} else {
|
||||
chargeNow += (readFloat(File(dir, "capacity")) ?: 0f) / 100f
|
||||
chargeFull = dirs.size.toFloat()
|
||||
}
|
||||
if (!charging) {
|
||||
val power = File(dir, "power_now")
|
||||
watts += if (power.exists()) kotlin.math.abs(readFloat(power) ?: 0f) / 1_000_000f
|
||||
else kotlin.math.abs((readFloat(File(dir, "current_now")) ?: 0f) * (readFloat(File(dir, "voltage_now")) ?: 0f)) / 1e12f
|
||||
}
|
||||
}
|
||||
val percent = if (chargeFull > 0f) Math.round(chargeNow / chargeFull * 100f) else null
|
||||
return Battery(percent, if (charging) 0f else watts, charging)
|
||||
}
|
||||
|
||||
private fun fresh(file: File, maxAgeMs: Long = FEED_FRESH_MS): File? =
|
||||
file.takeIf { it.isFile && System.currentTimeMillis() - it.lastModified() < maxAgeMs }
|
||||
|
||||
|
||||
companion object {
|
||||
private const val KGSL = "/sys/class/kgsl/kgsl-3d0"
|
||||
const val VRAM_FILE = "run/droiddeck-hud/gpu-mem"
|
||||
private const val FEED_FRESH_MS = 10_000L
|
||||
private const val VRAM_FRESH_MS = 15_000L
|
||||
private val WHITESPACE = Regex("\\s+")
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -341,9 +341,9 @@ public final class LinuxRuntime {
|
||||
}
|
||||
|
||||
public static String cpuTempSource() {
|
||||
for (java.util.Map.Entry<String, File> e : new java.util.TreeMap<>(thermalZones()).entrySet()) {
|
||||
File temp = new File(e.getValue(), "temp");
|
||||
if (e.getKey().contains("cpu") && !e.getKey().contains("gpu") && temp.canRead()) return temp.getPath();
|
||||
for (File zone : cpuTempZones()) {
|
||||
File temp = new File(zone, "temp");
|
||||
if (temp.canRead()) return temp.getPath();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -353,7 +353,7 @@ public final class LinuxRuntime {
|
||||
return firstReadable(kgsl + "temp", kgsl + "devfreq/temp", thermalZone("gpu"));
|
||||
}
|
||||
|
||||
private static String gpuLoadSource() {
|
||||
public static String gpuLoadSource() {
|
||||
String kgsl = "/sys/class/kgsl/kgsl-3d0/";
|
||||
return firstReadable(kgsl + "gpu_busy_percentage", kgsl + "devfreq/gpu_load");
|
||||
}
|
||||
@@ -367,7 +367,7 @@ public final class LinuxRuntime {
|
||||
"/sys/devices/platform/soc@0/3d00000.gpu/devfreq/3d00000.gpu/cur_freq"},
|
||||
{gpuTemp, "/sys/class/thermal/thermal_zone28/temp"},
|
||||
{gpuTemp, "/sys/class/thermal/thermal_zone26/temp"},
|
||||
{thermalZone("ddr"), "/sys/class/thermal/thermal_zone22/temp"},
|
||||
{ddrTempSource(), "/sys/class/thermal/thermal_zone22/temp"},
|
||||
};
|
||||
for (String[] stat : stats) {
|
||||
boolean fed = false;
|
||||
@@ -384,6 +384,36 @@ public final class LinuxRuntime {
|
||||
return path != null ? path : "none";
|
||||
}
|
||||
|
||||
private static String ddrTempSource() {
|
||||
return thermalZone("ddr");
|
||||
}
|
||||
|
||||
// MangoHud reads the GPU and DDR temperatures from these zone numbers (bindAdrenoStats). On phones
|
||||
// where they are CPU zones, their type follows the temperature put there, so they stay out of the
|
||||
// CPU average.
|
||||
private static java.util.Map<String, String> replacedZoneTypes() {
|
||||
java.util.Map<String, String> replaced = new java.util.HashMap<>();
|
||||
if (gpuTempSource() != null) {
|
||||
replaced.put("thermal_zone28", "gpu-thermal");
|
||||
replaced.put("thermal_zone26", "gpu-thermal");
|
||||
}
|
||||
if (ddrTempSource() != null) replaced.put("thermal_zone22", "ddr-thermal");
|
||||
return replaced;
|
||||
}
|
||||
|
||||
/** The zones the session's MangoHud averages for the CPU temperature (all typed cpuN-thermal there). */
|
||||
public static List<File> cpuTempZones() {
|
||||
java.util.Map<String, String> replaced = replacedZoneTypes();
|
||||
List<File> zones = new ArrayList<>();
|
||||
for (java.util.Map.Entry<String, File> zone : new java.util.TreeMap<>(thermalZones()).entrySet()) {
|
||||
String type = zone.getKey();
|
||||
if (type.contains("cpu") && !type.contains("gpu") && !replaced.containsKey(zone.getValue().getName())) {
|
||||
zones.add(zone.getValue());
|
||||
}
|
||||
}
|
||||
return zones;
|
||||
}
|
||||
|
||||
private static void bindCpuTemps(List<String> cmd, File root) {
|
||||
File name = new File(root, "etc/droiddeck/cpu-thermal-type");
|
||||
try {
|
||||
@@ -391,9 +421,18 @@ public final class LinuxRuntime {
|
||||
} catch (IOException e) {
|
||||
return;
|
||||
}
|
||||
java.util.Map<String, String> replaced = replacedZoneTypes();
|
||||
for (java.util.Map.Entry<String, File> zone : thermalZones().entrySet()) {
|
||||
String type = zone.getKey();
|
||||
if (type.contains("cpu") && !type.contains("gpu") && !type.matches("cpu\\d-(top-)?thermal")) {
|
||||
String other = replaced.get(zone.getValue().getName());
|
||||
if (other != null) {
|
||||
File typeFile = new File(root, "etc/droiddeck/" + other + "-type");
|
||||
try {
|
||||
if (!typeFile.isFile()) Files.write(typeFile.toPath(), (other + "\n").getBytes(StandardCharsets.US_ASCII));
|
||||
bind(cmd, typeFile.getPath() + ":" + new File(zone.getValue(), "type").getPath());
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
} else if (type.contains("cpu") && !type.contains("gpu") && !type.matches("cpu\\d-(top-)?thermal")) {
|
||||
bind(cmd, name.getPath() + ":" + new File(zone.getValue(), "type").getPath());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ class GpuMemComponent(private val file: File, private val root: File) : SessionP
|
||||
thread = Thread({
|
||||
while (running) {
|
||||
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
|
||||
if (running && OverlayShown.check(root)) sample()?.let { write(it) }
|
||||
if (running && (OverlayShown.check(root) || com.droiddeck.launcher.hud.FusionHudHost.showing)) sample()?.let { write(it) }
|
||||
}
|
||||
}, "gpu-mem").apply { isDaemon = true; start() }
|
||||
}
|
||||
|
||||
@@ -1,178 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.os.BatteryManager
|
||||
import android.os.Environment
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.os.SystemClock
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.gpu.FrameGen
|
||||
import com.droiddeck.launcher.gpu.Lossless
|
||||
import com.droiddeck.launcher.wayland.WaylandCompositor
|
||||
import java.io.File
|
||||
import java.util.Locale
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
|
||||
class PerfHud(context: Context) {
|
||||
var text by mutableStateOf("")
|
||||
private set
|
||||
var graph by mutableStateOf(FloatArray(0))
|
||||
private set
|
||||
|
||||
private val context = context.applicationContext
|
||||
private val frames = AtomicInteger()
|
||||
private var lastTick = 0L
|
||||
private var lastFps = 0f
|
||||
private var running = false
|
||||
private val handler = Handler(Looper.getMainLooper())
|
||||
private val samples = FloatArray(GRAPH)
|
||||
private var graphBase = 0L
|
||||
private var graphSeen = 0L
|
||||
|
||||
@Volatile private var showFps = true
|
||||
@Volatile private var showBattery = true
|
||||
@Volatile private var showGraph = true
|
||||
|
||||
private val enabled: Boolean
|
||||
get() = SessionPrefs.hudEnabled(context)
|
||||
&& !File(Environment.getExternalStorageDirectory(), "Download/droiddeck-no-hud").exists()
|
||||
|
||||
private val anyPart: Boolean
|
||||
get() = showFps || showBattery || showGraph
|
||||
|
||||
var onPresentingWindowChanged: (() -> Unit)? = null
|
||||
private var lastWindow: String? = null
|
||||
|
||||
private val listener = object : WaylandCompositor.GameListener {
|
||||
override fun onGameSurface(window: String?, gpuName: String?) {
|
||||
if (window != null && window != lastWindow) {
|
||||
lastWindow = window
|
||||
handler.post { onPresentingWindowChanged?.invoke() }
|
||||
}
|
||||
}
|
||||
override fun onGameFrame() {
|
||||
frames.incrementAndGet()
|
||||
}
|
||||
}
|
||||
|
||||
private val tick = object : Runnable {
|
||||
override fun run() {
|
||||
if (!running) return
|
||||
val now = SystemClock.elapsedRealtime()
|
||||
val dt = (now - lastTick).coerceAtLeast(1L) / 1000f
|
||||
lastTick = now
|
||||
lastFps = frames.getAndSet(0) / dt
|
||||
text = readout(lastFps)
|
||||
if (showGraph) publishGraph() else clearGraph()
|
||||
handler.postDelayed(this, TICK_MS)
|
||||
}
|
||||
}
|
||||
|
||||
fun refresh() {
|
||||
readOptions()
|
||||
if (!enabled || !anyPart) {
|
||||
stop()
|
||||
return
|
||||
}
|
||||
if (!running) start() else {
|
||||
if (!showGraph) clearGraph() else publishGraph()
|
||||
text = readout(lastFps)
|
||||
}
|
||||
}
|
||||
|
||||
fun start() {
|
||||
readOptions()
|
||||
if (!enabled || !anyPart || running) return
|
||||
running = true
|
||||
lastTick = SystemClock.elapsedRealtime()
|
||||
frames.set(0)
|
||||
graphBase = shownTotal()
|
||||
graphSeen = graphBase
|
||||
WaylandCompositor.setGameListener(listener)
|
||||
handler.postDelayed(tick, TICK_MS)
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
running = false
|
||||
handler.removeCallbacks(tick)
|
||||
WaylandCompositor.clearGameListener(listener)
|
||||
text = ""
|
||||
graph = FloatArray(0)
|
||||
}
|
||||
|
||||
private fun readOptions() {
|
||||
showFps = SessionPrefs.hudShowFps(context)
|
||||
showBattery = SessionPrefs.hudShowBattery(context)
|
||||
showGraph = SessionPrefs.hudShowGraph(context)
|
||||
}
|
||||
|
||||
private fun readout(fpsValue: Float): String {
|
||||
val parts = ArrayList<String>(2)
|
||||
if (showFps) parts.add(line(fpsValue))
|
||||
if (showBattery) batteryCelsius(readBatteryDeci())?.let { parts.add(it) }
|
||||
return parts.joinToString("\n")
|
||||
}
|
||||
|
||||
private fun readBatteryDeci(): Int {
|
||||
val sticky = runCatching {
|
||||
context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
|
||||
}.getOrNull() ?: return 0
|
||||
return sticky.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0)
|
||||
}
|
||||
|
||||
private fun shownTotal(): Long = try { WaylandCompositor.nativeHudFrameTimes(samples) } catch (t: Throwable) { 0L }
|
||||
|
||||
private fun clearGraph() {
|
||||
graphBase = shownTotal()
|
||||
graphSeen = graphBase
|
||||
if (graph.isNotEmpty()) graph = FloatArray(0)
|
||||
}
|
||||
|
||||
private fun publishGraph() {
|
||||
val total = shownTotal()
|
||||
if (total == graphSeen && graph.isNotEmpty()) return
|
||||
graphSeen = total
|
||||
graph = recent(samples, total, graphBase)
|
||||
}
|
||||
|
||||
private fun line(base: Float): String {
|
||||
val mode = FrameGen.mode(context)
|
||||
if (mode.engine == FrameGen.ENGINE_OFF) return fps(base)
|
||||
val lsfg = mode.engine == FrameGen.ENGINE_LSFG
|
||||
val name = if (lsfg) "LSFG" else "DD-FG"
|
||||
val label = FrameGen.label(context, mode)
|
||||
if (lsfg && Lossless.cacheFile(context)?.isFile != true) return context.getString(R.string.hud_fg_needs_lossless, name)
|
||||
val stats = try { WaylandCompositor.nativeFrameGenStats() } catch (t: Throwable) { null }
|
||||
val problem = try { WaylandCompositor.nativeFrameGenProblem() } catch (t: Throwable) { -1 }
|
||||
return when {
|
||||
problem == 1 -> context.getString(R.string.hud_fg_unsupported, name)
|
||||
problem == 2 -> context.getString(R.string.hud_fg_failed, name)
|
||||
stats != null && stats[3] > 1f -> String.format(Locale.US, "%s %.0f → %.0f fps", label, base, stats[3])
|
||||
else -> context.getString(R.string.hud_fg_starting, label, fps(base))
|
||||
}
|
||||
}
|
||||
|
||||
private fun fps(value: Float) = String.format(Locale.US, "%.0f fps", value)
|
||||
|
||||
companion object {
|
||||
private const val TICK_MS = 1_000L
|
||||
private const val GRAPH = 128
|
||||
internal const val GRAPH_MAX_MS = 50f
|
||||
|
||||
internal fun recent(samples: FloatArray, total: Long, base: Long): FloatArray {
|
||||
val filled = minOf(total, samples.size.toLong()).toInt()
|
||||
val shown = minOf(filled.toLong(), (total - base).coerceAtLeast(0L)).toInt()
|
||||
if (shown < 2) return FloatArray(0)
|
||||
return FloatArray(shown) { samples[filled - shown + it].coerceIn(0f, GRAPH_MAX_MS) }
|
||||
}
|
||||
|
||||
internal fun batteryCelsius(deci: Int): String? =
|
||||
if (deci <= 0) null else String.format(Locale.US, "%.1f°C", deci / 10f)
|
||||
}
|
||||
}
|
||||
@@ -233,6 +233,20 @@ object SessionPrefs {
|
||||
prefs(context).edit().putInt("hudOpacity", percent.coerceIn(HUD_OPACITY_RANGE)).apply()
|
||||
}
|
||||
|
||||
fun fusionHudConfig(context: Context): String? = prefs(context).getString("fusionHud", null)
|
||||
|
||||
fun setFusionHudConfig(context: Context, config: String) {
|
||||
prefs(context).edit().putString("fusionHud", config).apply()
|
||||
}
|
||||
|
||||
fun fusionHudPosition(context: Context): Pair<Float, Float>? =
|
||||
prefs(context).getString("fusionHudPos", null)?.split(',')?.mapNotNull { it.toFloatOrNull() }
|
||||
?.takeIf { it.size == 2 }?.let { it[0] to it[1] }
|
||||
|
||||
fun setFusionHudPosition(context: Context, x: Float, y: Float) {
|
||||
prefs(context).edit().putString("fusionHudPos", "$x,$y").apply()
|
||||
}
|
||||
|
||||
const val HUD_COLOR_MINT = "mint"
|
||||
val HUD_COLORS = listOf(HUD_COLOR_MINT, "white", "sky", "amber", "violet")
|
||||
val HUD_OPACITY_RANGE = 30..100
|
||||
|
||||
@@ -14,7 +14,7 @@ object SettingsReset {
|
||||
"orientation", "launcherFullscreen", "animations", "theme", "runSteamAtStartup", "addedGamesArt",
|
||||
"gameStoresEnabled", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
|
||||
"storesInstallLanguage",
|
||||
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController",
|
||||
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "fusionHud", "fusionHudPos", "backActionsInverted", "backDoubleTapMs", "touch", "osc", "shape", "steamController",
|
||||
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
|
||||
"stretch16x9", "picturePosition",
|
||||
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.hud.FusionSize
|
||||
|
||||
/** Bannerlator's Fusion HUD settings (DeckOverlaySettings): one row per key of the HUD's config string. */
|
||||
@Composable
|
||||
internal fun FusionHudSettings(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
|
||||
val cfg = a.hudConfig
|
||||
fun on(key: String) = cfg[key] == "1"
|
||||
fun int(key: String, fallback: Int) = cfg[key]?.toIntOrNull() ?: fallback
|
||||
|
||||
SettingsGroup(stringResource(R.string.drawer_hud), detail = stringResource(R.string.hud_matches_steam_overlay)) {
|
||||
ToggleRow(host, "hud", stringResource(R.string.drawer_hud), null, a.hudOn, chipModifier = track("hud"), onChange = a.onHud)
|
||||
if (!a.hudOn) return@SettingsGroup
|
||||
val size = FusionSize.from(cfg["hudSize"])
|
||||
ChoiceRow(host, "hud-size", stringResource(R.string.hud_size), stringResource(R.string.hud_size_hint),
|
||||
listOf(
|
||||
FusionSize.FULL to stringResource(R.string.hud_size_full),
|
||||
FusionSize.TILES to stringResource(R.string.hud_size_tiles),
|
||||
FusionSize.PILL to stringResource(R.string.hud_size_pill),
|
||||
FusionSize.MINIMAL to stringResource(R.string.hud_size_minimal),
|
||||
FusionSize.MEGA to stringResource(R.string.hud_size_mega),
|
||||
),
|
||||
size, chipModifier = track("hud-size")) { a.onHudSetting("hudSize", it.token) }
|
||||
ToggleRow(host, "hud-locked", stringResource(R.string.hud_locked), stringResource(R.string.hud_locked_hint), on("hudLocked"),
|
||||
chipModifier = track("hud-locked")) { a.onHudSetting("hudLocked", flag(it)) }
|
||||
}
|
||||
if (!a.hudOn) return
|
||||
|
||||
SettingsGroup(stringResource(R.string.hud_group_look)) {
|
||||
SliderRow(stringResource(R.string.hud_scale), null, int("hudScale", 100), 50..150, step = 5, format = { "$it%" },
|
||||
modifier = track("hud-scale")) { a.onHudSetting("hudScale", it.toString()) }
|
||||
SliderRow(stringResource(R.string.drawer_hud_opacity), null, int("hudOpacity", 80), 0..100, step = 5, format = { "$it%" },
|
||||
modifier = track("hud-opacity")) { a.onHudSetting("hudOpacity", it.toString()) }
|
||||
ChoiceRow(host, "hud-color", stringResource(R.string.drawer_hud_color), null,
|
||||
listOf("soft" to stringResource(R.string.hud_color_soft), "mid" to stringResource(R.string.hud_color_mid),
|
||||
"vivid" to stringResource(R.string.hud_color_vivid)),
|
||||
cfg["hudColor"] ?: "mid", chipModifier = track("hud-color")) { a.onHudSetting("hudColor", it) }
|
||||
SliderRow(stringResource(R.string.hud_outline), null, int("hudOutline", 40), 0..100, step = 10,
|
||||
modifier = track("hud-outline")) { a.onHudSetting("hudOutline", it.toString()) }
|
||||
ChoiceRow(host, "hud-outline-color", stringResource(R.string.hud_outline_color), null,
|
||||
listOf("0" to stringResource(R.string.hud_outline_gray), "1" to stringResource(R.string.hud_outline_theme)),
|
||||
if (cfg["hudOutlineAccent"] == "0") "0" else "1", chipModifier = track("hud-outline-color")) { a.onHudSetting("hudOutlineAccent", it) }
|
||||
}
|
||||
|
||||
val size = FusionSize.from(cfg["hudSize"])
|
||||
val chips = size.supportedChips() + EXTRA[size].orEmpty()
|
||||
SettingsGroup(stringResource(R.string.hud_group_metrics)) {
|
||||
for (metric in METRICS) {
|
||||
if (metric.chip !in chips || metric.chip in HIDDEN[size].orEmpty()) continue
|
||||
ToggleRow(host, "hud-${metric.key}", stringResource(metric.label), null, on(metric.key),
|
||||
chipModifier = track("hud-${metric.key}")) { a.onHudSetting(metric.key, flag(it)) }
|
||||
}
|
||||
}
|
||||
|
||||
val tempsShown = ("Temp" in chips && on("showTemp")) || ("GPU temp" in chips && on("showGpuTemp"))
|
||||
if (tempsShown) SettingsGroup(stringResource(R.string.hud_group_temps)) {
|
||||
ChoiceRow(host, "hud-temp-unit", stringResource(R.string.hud_temp_unit), null,
|
||||
listOf("c" to "°C", "f" to "°F"), if (cfg["tempUnit"].equals("f", true)) "f" else "c",
|
||||
chipModifier = track("hud-temp-unit")) { a.onHudSetting("tempUnit", it) }
|
||||
val bands = when {
|
||||
cfg["tempBands"] == "0" -> "0"
|
||||
cfg["tempAuto"] == "0" -> "2"
|
||||
else -> "1"
|
||||
}
|
||||
ChoiceRow(host, "hud-temp-bands", stringResource(R.string.hud_temp_bands), stringResource(R.string.hud_temp_bands_hint),
|
||||
listOf("0" to stringResource(R.string.hud_temp_bands_off), "1" to stringResource(R.string.hud_temp_bands_auto),
|
||||
"2" to stringResource(R.string.hud_temp_bands_manual)),
|
||||
bands, chipModifier = track("hud-temp-bands")) {
|
||||
a.onHudSetting("tempBands", if (it == "0") "0" else "1")
|
||||
a.onHudSetting("tempAuto", if (it == "2") "0" else "1")
|
||||
}
|
||||
if (bands == "2") {
|
||||
SliderRow(stringResource(R.string.hud_temp_red_cpu), null, int("tempRedCpu", 90), 50..110, format = { "$it°C" },
|
||||
modifier = track("hud-red-cpu")) { a.onHudSetting("tempRedCpu", it.toString()) }
|
||||
SliderRow(stringResource(R.string.hud_temp_red_gpu), null, int("tempRedGpu", 90), 50..110, format = { "$it°C" },
|
||||
modifier = track("hud-red-gpu")) { a.onHudSetting("tempRedGpu", it.toString()) }
|
||||
SliderRow(stringResource(R.string.hud_temp_red_battery), null, int("tempRedBat", 48), 35..60, format = { "$it°C" },
|
||||
modifier = track("hud-red-battery")) { a.onHudSetting("tempRedBat", it.toString()) }
|
||||
}
|
||||
}
|
||||
|
||||
SettingsGroup(stringResource(R.string.hud_group_more), detail = stringResource(R.string.hud_credit)) {
|
||||
ActionRow(stringResource(R.string.hud_export), stringResource(R.string.hud_export_hint),
|
||||
stringResource(R.string.hud_export_button), onClick = a.onHudExport, modifier = track("hud-export"))
|
||||
ActionRow(stringResource(R.string.hud_reset), null, stringResource(R.string.hud_reset_button),
|
||||
onClick = a.onHudReset, modifier = track("hud-reset"))
|
||||
}
|
||||
}
|
||||
|
||||
private fun flag(on: Boolean) = if (on) "1" else "0"
|
||||
|
||||
// The Pill also draws the battery temperature and watts.
|
||||
private val EXTRA = mapOf(FusionSize.PILL to setOf("Temp", "Power"))
|
||||
|
||||
private class HudMetric(val chip: String, val key: String, val label: Int)
|
||||
|
||||
// FusionSize.supportedChips() names; Wrapper and DX version have nothing to show in DroidDeck.
|
||||
private val METRICS = listOf(
|
||||
HudMetric("FPS", "showFPS", R.string.drawer_hud_fps),
|
||||
HudMetric("FPS graph", "showFPSGraph", R.string.hud_metric_graph),
|
||||
HudMetric("FPS .1", "fpsDecimal", R.string.hud_metric_decimal),
|
||||
HudMetric("0.01% low", "showLow001", R.string.hud_metric_low001),
|
||||
HudMetric("Engine", "showEngine", R.string.hud_metric_engine),
|
||||
HudMetric("GPU model", "showGpuModel", R.string.hud_metric_gpu_model),
|
||||
HudMetric("GPU", "showGPULoad", R.string.hud_metric_gpu),
|
||||
HudMetric("GPU temp", "showGpuTemp", R.string.hud_metric_gpu_temp),
|
||||
HudMetric("CPU", "showCPUUsage", R.string.hud_metric_cpu),
|
||||
HudMetric("Per-core", "showPerCore", R.string.hud_metric_per_core),
|
||||
HudMetric("Temp", "showTemp", R.string.hud_metric_temp),
|
||||
HudMetric("RAM", "showRAM", R.string.hud_metric_ram),
|
||||
HudMetric("VRAM", "showVram", R.string.hud_metric_vram),
|
||||
HudMetric("Swap", "showSwap", R.string.hud_metric_swap),
|
||||
HudMetric("Battery", "showBattery", R.string.hud_metric_battery),
|
||||
HudMetric("Power", "showPower", R.string.hud_metric_power),
|
||||
HudMetric("Network", "showNet", R.string.hud_metric_network),
|
||||
HudMetric("Resolution", "showResolution", R.string.hud_metric_resolution),
|
||||
HudMetric("Proton", "showProton", R.string.hud_metric_proton),
|
||||
HudMetric("Session", "showSession", R.string.hud_metric_session),
|
||||
HudMetric("Clock", "showClock", R.string.hud_metric_clock),
|
||||
)
|
||||
|
||||
// Switches a size lists but never draws (FusionHudView): the Pill and Minimal always show the FPS, the
|
||||
// Pill has no graph, Tiles has no graph and no 0.01% low.
|
||||
private val HIDDEN = mapOf(
|
||||
FusionSize.PILL to setOf("FPS", "FPS graph"),
|
||||
FusionSize.MINIMAL to setOf("FPS"),
|
||||
FusionSize.TILES to setOf("FPS graph", "0.01% low"),
|
||||
)
|
||||
@@ -4,7 +4,8 @@ internal enum class SessionDrawerPage(val firstControl: String) {
|
||||
CONTROLLER("touch"),
|
||||
GLASSES("glasses-game"),
|
||||
SECOND_SCREEN("second-screen:none"),
|
||||
DISPLAY("hud"),
|
||||
DISPLAY("fg"),
|
||||
HUD("hud"),
|
||||
EFFECTS("look"),
|
||||
VR("steamvr"),
|
||||
GAMES("anisotropy"),
|
||||
|
||||
@@ -18,7 +18,6 @@ import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.session.LoadingState
|
||||
import com.droiddeck.launcher.session.PerfHud
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import androidx.compose.animation.core.FastOutSlowInEasing
|
||||
@@ -81,8 +80,8 @@ import androidx.compose.ui.text.style.TextOverflow
|
||||
|
||||
|
||||
@Composable
|
||||
fun HudText(text: String, graph: FloatArray = FloatArray(0), color: String = "mint", opacity: Int = 70) {
|
||||
if (text.isEmpty() && graph.size < 2) return
|
||||
fun HudText(text: String, color: String = "mint", opacity: Int = 70) {
|
||||
if (text.isEmpty()) return
|
||||
val accent = hudInk(color)
|
||||
val wash = (opacity.coerceIn(30, 100) / 100f)
|
||||
val ink = accent.copy(alpha = (0.5f + wash * 0.5f).coerceIn(0.62f, 1f))
|
||||
@@ -99,49 +98,13 @@ fun HudText(text: String, graph: FloatArray = FloatArray(0), color: String = "mi
|
||||
)
|
||||
.padding(horizontal = 8.dp, vertical = 5.dp),
|
||||
) {
|
||||
if (text.isNotEmpty()) Text(
|
||||
Text(
|
||||
text,
|
||||
fontFamily = FontFamily.Monospace,
|
||||
fontSize = 12.sp,
|
||||
color = ink,
|
||||
textAlign = TextAlign.End,
|
||||
)
|
||||
if (graph.size >= 2) {
|
||||
if (text.isNotEmpty()) Spacer(Modifier.height(4.dp))
|
||||
HudGraph(graph, accent, wash)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun HudGraph(samples: FloatArray, accent: Color, wash: Float) {
|
||||
Canvas(Modifier.width(148.dp).height(44.dp)) {
|
||||
val maxMs = PerfHud.GRAPH_MAX_MS
|
||||
val step = size.width / (samples.size - 1)
|
||||
fun yOf(ms: Float) = size.height * (1f - (ms / maxMs).coerceIn(0f, 1f))
|
||||
val fillAlpha = wash * 0.5f
|
||||
val fill = Path().apply {
|
||||
moveTo(0f, size.height)
|
||||
samples.forEachIndexed { i, ms -> lineTo(i * step, yOf(ms)) }
|
||||
lineTo(size.width, size.height)
|
||||
close()
|
||||
}
|
||||
drawPath(
|
||||
fill,
|
||||
Brush.verticalGradient(listOf(HUD_SLOW.copy(alpha = fillAlpha), accent.copy(alpha = fillAlpha * 0.45f))),
|
||||
)
|
||||
val guide = yOf(16.7f)
|
||||
drawLine(Color.White.copy(alpha = 0.32f), Offset(0f, guide), Offset(size.width, guide), strokeWidth = 1f)
|
||||
for (i in 0 until samples.lastIndex) {
|
||||
val tone = ((samples[i] - 8f) / 25f).coerceIn(0f, 1f)
|
||||
drawLine(
|
||||
mix(accent, HUD_SLOW, tone).copy(alpha = 0.55f + wash * 0.4f),
|
||||
Offset(i * step, yOf(samples[i])),
|
||||
Offset((i + 1) * step, yOf(samples[i + 1])),
|
||||
strokeWidth = 2.5f,
|
||||
cap = StrokeCap.Round,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -156,17 +119,6 @@ private fun hudInk(color: String): Color = Color(
|
||||
}.toInt(),
|
||||
)
|
||||
|
||||
private fun mix(from: Color, to: Color, t: Float): Color {
|
||||
val u = t.coerceIn(0f, 1f)
|
||||
return Color(
|
||||
red = from.red + (to.red - from.red) * u,
|
||||
green = from.green + (to.green - from.green) * u,
|
||||
blue = from.blue + (to.blue - from.blue) * u,
|
||||
alpha = 1f,
|
||||
)
|
||||
}
|
||||
|
||||
private val HUD_SLOW = Color(0xFFFF5C6C.toInt())
|
||||
|
||||
private class LoadStage(@androidx.annotation.StringRes val label: Int, @androidx.annotation.StringRes val detail: Int)
|
||||
|
||||
|
||||
@@ -42,6 +42,7 @@ import androidx.compose.material.icons.outlined.Pause
|
||||
import androidx.compose.material.icons.outlined.PictureInPictureAlt
|
||||
import androidx.compose.material.icons.automirrored.outlined.ExitToApp
|
||||
import androidx.compose.material.icons.outlined.Settings
|
||||
import androidx.compose.material.icons.outlined.Speed
|
||||
import androidx.compose.material.icons.outlined.SportsEsports
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.material3.RadioButton
|
||||
@@ -157,6 +158,7 @@ private val SessionDrawerPage.title: Int get() = when (this) {
|
||||
SessionDrawerPage.GLASSES -> R.string.drawer_page_glasses
|
||||
SessionDrawerPage.SECOND_SCREEN -> R.string.drawer_second_screen
|
||||
SessionDrawerPage.DISPLAY -> R.string.drawer_page_display
|
||||
SessionDrawerPage.HUD -> R.string.drawer_hud
|
||||
SessionDrawerPage.VR -> R.string.vr_title
|
||||
SessionDrawerPage.EFFECTS -> R.string.drawer_page_effects
|
||||
SessionDrawerPage.GAMES -> R.string.game_settings_title
|
||||
@@ -168,6 +170,7 @@ private val SessionDrawerPage.icon get() = when (this) {
|
||||
SessionDrawerPage.GLASSES -> GlassesIcon
|
||||
SessionDrawerPage.SECOND_SCREEN -> Icons.Outlined.ScreenShare
|
||||
SessionDrawerPage.DISPLAY -> Icons.Outlined.DesktopWindows
|
||||
SessionDrawerPage.HUD -> Icons.Outlined.Speed
|
||||
SessionDrawerPage.VR -> VrHeadsetIcon
|
||||
SessionDrawerPage.EFFECTS -> Icons.Outlined.AutoFixHigh
|
||||
SessionDrawerPage.GAMES -> Icons.Outlined.Layers
|
||||
@@ -201,11 +204,7 @@ class DrawerActions(
|
||||
val isHomeApp: Boolean,
|
||||
val androidApps: List<HomeApp.LaunchableApp>,
|
||||
val hudOn: Boolean,
|
||||
val hudFps: Boolean = true,
|
||||
val hudBattery: Boolean = true,
|
||||
val hudGraph: Boolean = true,
|
||||
val hudColor: String = SessionPrefs.HUD_COLOR_MINT,
|
||||
val hudOpacity: Int = SessionPrefs.HUD_OPACITY_DEFAULT,
|
||||
val hudConfig: Map<String, String> = emptyMap(),
|
||||
val frameGen: FrameGen.Mode,
|
||||
val lossless: Lossless.State,
|
||||
val oscMode: String,
|
||||
@@ -238,11 +237,9 @@ class DrawerActions(
|
||||
val secondScreenDisplays: List<SecondScreenDisplay>,
|
||||
val selectedSecondScreenDisplay: Int,
|
||||
val onHud: (Boolean) -> Unit,
|
||||
val onHudFps: (Boolean) -> Unit = {},
|
||||
val onHudBattery: (Boolean) -> Unit = {},
|
||||
val onHudGraph: (Boolean) -> Unit = {},
|
||||
val onHudColor: (String) -> Unit = {},
|
||||
val onHudOpacity: (Int) -> Unit = {},
|
||||
val onHudSetting: (String, String) -> Unit = { _, _ -> },
|
||||
val onHudReset: () -> Unit = {},
|
||||
val onHudExport: () -> Unit = {},
|
||||
val onFrameGenPick: (FrameGen.Mode) -> Unit,
|
||||
val onImportLossless: () -> Unit,
|
||||
val onKeyboard: () -> Unit,
|
||||
@@ -495,34 +492,9 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
|
||||
modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(pageScroll.getValue(page)),
|
||||
) { CompositionLocalProvider(LocalChipMinWidth provides 96.dp, LocalCompactSettings provides true) {
|
||||
when (page) {
|
||||
SessionDrawerPage.HUD -> FusionHudSettings(host, a) { key -> focus.track(page, key) }
|
||||
SessionDrawerPage.DISPLAY -> {
|
||||
SettingsGroup(stringResource(R.string.drawer_page_display)) {
|
||||
ToggleRow(host, "hud", stringResource(R.string.drawer_hud), null, a.hudOn,
|
||||
chipModifier = focus.track(page, "hud"), onChange = a.onHud)
|
||||
if (a.hudOn) {
|
||||
ToggleRow(host, "hud-fps", stringResource(R.string.drawer_hud_fps), null, a.hudFps,
|
||||
chipModifier = focus.track(page, "hud-fps"), onChange = a.onHudFps)
|
||||
ToggleRow(host, "hud-battery", stringResource(R.string.drawer_hud_battery), null, a.hudBattery,
|
||||
chipModifier = focus.track(page, "hud-battery"), onChange = a.onHudBattery)
|
||||
ToggleRow(host, "hud-graph", stringResource(R.string.drawer_hud_graph), null, a.hudGraph,
|
||||
chipModifier = focus.track(page, "hud-graph"), onChange = a.onHudGraph)
|
||||
ChoiceRow(
|
||||
host, "hud-color", stringResource(R.string.drawer_hud_color), null,
|
||||
listOf(
|
||||
SessionPrefs.HUD_COLOR_MINT to stringResource(R.string.drawer_hud_color_mint),
|
||||
"white" to stringResource(R.string.drawer_hud_color_white),
|
||||
"sky" to stringResource(R.string.drawer_hud_color_sky),
|
||||
"amber" to stringResource(R.string.drawer_hud_color_amber),
|
||||
"violet" to stringResource(R.string.drawer_hud_color_violet),
|
||||
),
|
||||
a.hudColor, chipModifier = focus.track(page, "hud-color"), onPick = a.onHudColor,
|
||||
)
|
||||
SliderRow(
|
||||
stringResource(R.string.drawer_hud_opacity), null, a.hudOpacity,
|
||||
SessionPrefs.HUD_OPACITY_RANGE, step = 10, format = { "$it%" },
|
||||
modifier = focus.track(page, "hud-opacity"), onChange = a.onHudOpacity,
|
||||
)
|
||||
}
|
||||
val fgOpen = host.open == "fg"
|
||||
val fgLabel = FrameGen.label(LocalContext.current, a.frameGen)
|
||||
SettingsRow(stringResource(R.string.frame_gen_title), null, highlighted = fgOpen) {
|
||||
|
||||
Reference in new issue
Block a user