= 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.
-}
diff --git a/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt b/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt
index fcca0aaa2e..98dc35074f 100644
--- a/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt
+++ b/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt
@@ -3,13 +3,6 @@ package com.droiddeck.launcher.hud
import java.io.File
import kotlin.math.roundToInt
-/**
- * Frame statistics by MangoHud's rules, so the HUD and Steam's performance overlay agree: MangoHud
- * overlay.cpp update_hud_info_with_frametime and hud_elements.cpp fps() / frame_timing(). The FPS is the
- * frames counted over a sampling period of at least 500 ms, the frame time next to it is 1000 / FPS, and
- * the graph holds the last 200 frame times (zeros until filled) on a fixed 0-50 ms scale, min and max
- * taken over those 200. Average and lows are FusionHUD's own readouts.
- */
internal class FrameStats {
private val graph = FloatArray(GRAPH_FRAMES)
private var graphHead = 0
@@ -26,14 +19,16 @@ internal class FrameStats {
private var sessionStartNs = 0L
private var sessionFrames = 0L
+ private val slowTimes = LongArray(SLOW_FRAMES)
+ private var slowHead = 0
+ private var slowSize = 0
+
@Volatile var fps = 0f
private set
- /** Completed sampling periods; MangoHud redraws its readouts when one completes. */
@Volatile var fpsUpdates = 0L
private set
- /** Frames added so far; the HUD redraws its graph when this moves. */
@Volatile var count = 0L
private set
@@ -60,6 +55,11 @@ internal class FrameStats {
if (lowsSize < LOWS_FRAMES) lowsSize++
if (sessionStartNs == 0L) sessionStartNs = timeNs - frametimeNs
sessionFrames++
+ if (frametimeNs > SLOW_NS) {
+ slowTimes[slowHead] = timeNs
+ slowHead = (slowHead + 1) % SLOW_FRAMES
+ if (slowSize < SLOW_FRAMES) slowSize++
+ }
}
count++
}
@@ -77,14 +77,14 @@ internal class FrameStats {
cachedLowsNs = 0L
sessionStartNs = 0L
sessionFrames = 0L
+ slowHead = 0
+ slowSize = 0
fps = 0f
count++
}
- /** MangoHud's frame time readout: 1000 / FPS. */
fun frametimeMs(): Float = 1000f / maxOf(fps, 1f)
- /** The graph, oldest first, into [out] (GRAPH_FRAMES long). */
@Synchronized
fun graph(out: FloatArray) {
for (i in 0 until GRAPH_FRAMES) out[i] = graph[(graphHead + i) % GRAPH_FRAMES]
@@ -96,7 +96,6 @@ internal class FrameStats {
@Synchronized
fun graphMaxMs(): Float = graph.max()
- /** Average over the frames this session, from the first frame to [nowNs]'s last frame. */
@Synchronized
fun averageFps(): Float {
if (sessionFrames < 2 || lastPresentNs <= sessionStartNs) return 0f
@@ -106,13 +105,22 @@ internal class FrameStats {
@Synchronized
fun sessionSeconds(nowNs: Long): Float = if (sessionStartNs == 0L) 0f else (nowNs - sessionStartNs) / 1e9f
+ @Synchronized
+ fun slowFrames(nowNs: Long, windowNs: Long): Int {
+ var n = 0
+ for (i in 0 until slowSize) {
+ if (nowNs - slowTimes[(slowHead - 1 - i + SLOW_FRAMES) % SLOW_FRAMES] > windowNs) break
+ n++
+ }
+ return n
+ }
+
class Lows(val low1Fps: Float, val low01Fps: Float, val low001Fps: Float) {
companion object {
val EMPTY = Lows(0f, 0f, 0f)
}
}
- /** FPS at the 99th, 99.9th and 99.99th percentile frame time of the last LOWS_FRAMES frames. */
fun lows(nowNs: Long): Lows {
val copy: LongArray
synchronized(this) {
@@ -141,15 +149,12 @@ internal class FrameStats {
const val FPS_PERIOD_NS = 500_000_000L
const val LOWS_FRAMES = 8192
private const val PAUSE_NS = 1_000_000_000L
+ const val SLOW_NS = 33_333_334L
+ private const val SLOW_FRAMES = 2048
private const val LOWS_RECOMPUTE_NS = 250_000_000L
}
}
-/**
- * Feeds [stats] with the frame times gamescope shares (the ones MangoHud shows). Sessions without the
- * shared file, or where gamescope stopped sending, fall back to the frames DroidDeck's compositor shows,
- * which stop at the screen's refresh rate.
- */
internal class GameFrameFeed(private val file: File, val stats: FrameStats = FrameStats()) {
private var handle = 0L
private var nextOpenNs = 0L
@@ -160,7 +165,7 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
private val info = IntArray(5)
@Volatile private var fromGamescope = false
private var lastCompositorNs = 0L
- @Volatile private var compositorFrames = 0L // written by the compositor thread only
+ @Volatile private var compositorFrames = 0L
private var seenCompositorFrames = 0L
@Volatile var engine = ""
@@ -176,7 +181,8 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
@Volatile var refreshMilliHz = 0
private set
- /** Main thread, once per display frame. True when new frames arrived. */
+ val live: Boolean get() = fromGamescope
+
fun poll(nowNs: Long): Boolean {
val compositorAdded = compositorFrames != seenCompositorFrames
seenCompositorFrames = compositorFrames
@@ -185,7 +191,6 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
nextOpenNs = nowNs + REOPEN_NS
handle = runCatching { HudFrames.nativeOpen(file.path) }.getOrDefault(0L)
if (handle == 0L) return compositorAdded
- // Frames already in the file were written before this reader started.
HudFrames.nativePoll(handle, frametimes, times)
}
val n = HudFrames.nativePoll(handle, frametimes, times)
@@ -199,7 +204,6 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
} else if (lastRingFrameNs != 0L && nowNs - lastRingFrameNs > LIVE_NS) {
fromGamescope = false
}
- // A new session writes the file again from the start; reopen when gamescope has gone quiet.
if (n <= 0 && nowNs - maxOf(lastRingFrameNs, nextOpenNs - REOPEN_NS) > STALE_NS) close()
if (nowNs - lastInfoNs >= INFO_NS) {
lastInfoNs = nowNs
@@ -208,7 +212,6 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
return n > 0 || compositorAdded
}
- /** Compositor thread: one frame shown on the panel. */
fun onCompositorFrame(nowNs: Long) {
if (fromGamescope) {
lastCompositorNs = 0L
@@ -247,8 +250,6 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
private const val STALE_NS = 5_000_000_000L
private const val INFO_NS = 500_000_000L
- /** DroidDeck's mangoapp's names for gamescope's engine field (Valve's 20260902.1 build, app/main.cpp
- * engine_type_from_str and overlay.h engines); gamescope sends "gamescope" when it knows none. */
fun engineLabel(name: String): String = when (name) {
"DXVK" -> "DXVK"
"vkd3d" -> "VKD3D"
diff --git a/app/src/main/java/com/droiddeck/launcher/hud/HudFrames.kt b/app/src/main/java/com/droiddeck/launcher/hud/HudFrames.kt
index 63a9a7945d..ca13e7a3eb 100644
--- a/app/src/main/java/com/droiddeck/launcher/hud/HudFrames.kt
+++ b/app/src/main/java/com/droiddeck/launcher/hud/HudFrames.kt
@@ -1,12 +1,10 @@
package com.droiddeck.launcher.hud
-/** Reader for the frame-times file gamescope patch 0125 writes (hudframes.c). */
internal object HudFrames {
init {
System.loadLibrary("droiddeckwayland")
}
- /** Under the Linux root: the session exports /run/droiddeck-hud/frames to gamescope. */
const val PATH = "run/droiddeck-hud/frames"
const val CAPACITY = 1024
diff --git a/app/src/main/java/com/droiddeck/launcher/hud/HudLockController.java b/app/src/main/java/com/droiddeck/launcher/hud/HudLockController.java
index 3266e85fee..98c34df7ce 100644
--- a/app/src/main/java/com/droiddeck/launcher/hud/HudLockController.java
+++ b/app/src/main/java/com/droiddeck/launcher/hud/HudLockController.java
@@ -8,7 +8,7 @@
* link to https://github.com/The412Banner/FusionHUD in the project documentation
* AND in the in-app credits/about screen.
*
- * Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code.
+ * Ported to DroidDeck from FusionHUD (Bannerlator's HUD) and modified for DroidDeck.
*/
package com.droiddeck.launcher.hud;
@@ -22,45 +22,24 @@ import android.graphics.RectF;
import android.os.SystemClock;
import android.view.GestureDetector;
import android.view.MotionEvent;
+import android.view.ScaleGestureDetector;
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:
- *
- *
- * - tap → {@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.
- * - drag → moves the host view and, on release, {@link Callbacks#onMoved} to persist the
- * position — disabled (frozen) while locked.
- * - long-press → toggles {@code hudLocked}, persisted via {@link Callbacks#onLockChanged}
- * and kept in sync with the "Lock in place" menu chip. Works locked or unlocked (so a long-press
- * always unlocks); a locked {@code FusionHudView} passes touches on only over on-screen controls.
- *
- *
- * 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.
- *
- *
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. */
+ default void onDragged(float rawX, float rawY) {}
+ default void onFlung(float velocityX, float velocityY) {}
void onLockChanged(boolean locked);
+ default void onPinch(float factor) {}
+ default void onPinchEnd() {}
}
- // Fade timing (ms): in → hold → out. Lock/unlock hold ~1.5 s; a blocked-gesture re-flash is shorter.
private static final long FADE_IN_MS = 160;
private static final long HOLD_TOGGLE_MS = 1500;
private static final long HOLD_REFLASH_MS = 750;
@@ -70,14 +49,14 @@ public class HudLockController {
private final View view;
private final Callbacks cb;
private final GestureDetector detector;
+ private final ScaleGestureDetector scaleDetector;
private boolean locked = false;
- // Drag state
private float downRawX, downRawY, startX, startY;
private boolean dragging = false;
+ private boolean pinched = false;
- // Fade state
private long fadeStart = 0;
private long holdMs = HOLD_TOGGLE_MS;
private boolean fadeShowLocked = false;
@@ -90,21 +69,22 @@ public class HudLockController {
this.cb = cb;
this.detector = new GestureDetector(context, new Listener());
this.detector.setIsLongpressEnabled(true);
+ this.scaleDetector = new ScaleGestureDetector(context, new PinchListener());
+ this.scaleDetector.setQuickScaleEnabled(false);
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) {
+ scaleDetector.onTouchEvent(event);
detector.onTouchEvent(event);
int action = event.getActionMasked();
if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
@@ -122,12 +102,12 @@ public class HudLockController {
startX = view.getX();
startY = view.getY();
dragging = false;
+ pinched = 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);
@@ -135,29 +115,58 @@ public class HudLockController {
@Override
public boolean onSingleTapUp(MotionEvent e) {
+ if (pinched) return true;
if (locked) {
- flash(true, HOLD_REFLASH_MS); // intentionally locked — remind the user
+ flash(true, HOLD_REFLASH_MS);
} else {
cb.onTap();
}
return true;
}
+ @Override
+ public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
+ if (dragging && !locked && !pinched) cb.onFlung(velocityX, velocityY);
+ return true;
+ }
+
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
+ if (pinched) return true;
if (locked) {
if (!dragging) flash(true, HOLD_REFLASH_MS);
- dragging = true; // mark so the blocked drag doesn't fall through to a tap
+ dragging = true;
return true;
}
view.setX(startX + (e2.getRawX() - downRawX));
view.setY(startY + (e2.getRawY() - downRawY));
dragging = true;
+ cb.onDragged(e2.getRawX(), e2.getRawY());
return true;
}
}
- // ---- Fade badge -------------------------------------------------------
+ private final class PinchListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
+ @Override
+ public boolean onScaleBegin(ScaleGestureDetector d) {
+ if (locked) return false;
+ pinched = true;
+ dragging = false;
+ return true;
+ }
+
+ @Override
+ public boolean onScale(ScaleGestureDetector d) {
+ cb.onPinch(d.getScaleFactor());
+ return true;
+ }
+
+ @Override
+ public void onScaleEnd(ScaleGestureDetector d) {
+ cb.onPinchEnd();
+ }
+ }
+
private void flash(boolean showLocked, long hold) {
fadeShowLocked = showLocked;
holdMs = hold;
@@ -190,14 +199,6 @@ public class HudLockController {
return Color.argb(Math.round(255 * a), Color.red(color), Color.green(color), Color.blue(color));
}
- /**
- * Draw the padlock badge in the top-right of the panel if a fade is in progress. Call from the
- * host's onDraw (plain View) or dispatchDraw (ViewGroup), after the content.
- *
- *
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;
@@ -216,14 +217,12 @@ public class HudLockController {
float r = size * 0.2f;
float shackleTop = top + size * 0.08f;
- // Pass 1: dark halo (expanded body, thicker shackle) for contrast; Pass 2: white glyph.
drawLock(canvas, cx, bodyTop, bodyLeft, bodyRight, bottom, r, shackleTop, d,
Color.argb(Math.round(150 * a), 0, 0, 0), 3.0f * d, 0.9f * d, false);
drawLock(canvas, cx, bodyTop, bodyLeft, bodyRight, bottom, r, shackleTop, d,
withAlpha(0xFFFFFFFF, a), 1.7f * d, 0f, true);
}
- /** One padlock pass. {@code halo} inflates the body/shackle in dark; the white pass punches the keyhole. */
private void drawLock(Canvas canvas, float cx, float bodyTop, float bodyLeft, float bodyRight,
float bottom, float r, float shackleTop, float d,
int color, float strokeW, float expand, boolean punchKeyhole) {
@@ -231,7 +230,6 @@ public class HudLockController {
iconStroke.setColor(color);
iconStroke.setStrokeWidth(strokeW);
- // Body
canvas.drawRoundRect(bodyLeft - expand, bodyTop - expand, bodyRight + expand, bottom + expand,
2.4f * d, 2.4f * d, iconFill);
if (punchKeyhole) {
@@ -243,19 +241,16 @@ public class HudLockController {
RectF arc = new RectF(cx - r, shackleTop, cx + r, shackleTop + 2f * r);
if (fadeShowLocked) {
- // Closed: both legs run straight down into the body.
Path p = new Path();
p.addArc(arc, 180f, 180f);
p.moveTo(cx - r, shackleTop + r); p.lineTo(cx - r, bodyTop);
p.moveTo(cx + r, shackleTop + r); p.lineTo(cx + r, bodyTop);
canvas.drawPath(p, iconStroke);
} else {
- // Open, clearly to the LEFT: the RIGHT leg stays seated in the body; the arc + LEFT leg
- // hinge up-and-left off the right attachment so the left leg lifts well clear of the body.
- canvas.drawLine(cx + r, shackleTop + r, cx + r, bodyTop, iconStroke); // fixed right leg
+ canvas.drawLine(cx + r, shackleTop + r, cx + r, bodyTop, iconStroke);
Path p = new Path();
p.addArc(arc, 180f, 180f);
- p.moveTo(cx - r, shackleTop + r); p.lineTo(cx - r, bodyTop); // full-length left leg
+ p.moveTo(cx - r, shackleTop + r); p.lineTo(cx - r, bodyTop);
canvas.save();
canvas.rotate(-42f, cx + r, shackleTop + r);
canvas.drawPath(p, iconStroke);
diff --git a/app/src/main/java/com/droiddeck/launcher/hud/HudMetrics.java b/app/src/main/java/com/droiddeck/launcher/hud/HudMetrics.java
index 88cbc87074..51a4e42608 100644
--- a/app/src/main/java/com/droiddeck/launcher/hud/HudMetrics.java
+++ b/app/src/main/java/com/droiddeck/launcher/hud/HudMetrics.java
@@ -8,7 +8,8 @@
* link to https://github.com/The412Banner/FusionHUD in the project documentation
* AND in the in-app credits/about screen.
*
- * Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code.
+ * Ported to DroidDeck from FusionHUD (Bannerlator's HUD) and modified for DroidDeck.
+ * Metric readers from @xXJSONDeruloXx's work.
*/
package com.droiddeck.launcher.hud;
@@ -32,50 +33,17 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
-/**
- * Shared live-metric collector for every performance HUD overlay. This is the single, device-complete
- * implementation of the sysfs / Android readers — no overlay should re-read sysfs itself, so the GPU
- * discovery / thermal / battery logic never diverges.
- *
- *
Ported and hardened from GameNative's {@code PerformanceHudView} readers, which are far more
- * device-complete than the two-fixed-path versions previously inlined in the classic overlays:
- *
- * - GPU load — ~10 static candidates plus a dynamic {@code /sys/class/devfreq} +
- * {@code /sys/devices/virtual/devfreq} walk for gpu/mali/g3d/kgsl nodes; handles gpubusy
- * (busy/total), Mali gpuinfo (delta-ms/wall-ms, needs state between calls) and generic percent
- * nodes. Discovery cached.
- * - CPU usage — {@code /proc/stat} aggregate delta with a scaling-frequency fallback for devices
- * where {@code /proc/stat} is restricted.
- * - Thermal — prioritized CPU zone discovery (cpu-silicon > cpu-0 > cpu > soc >
- * s5p-tmu > cputop > tsens > cluster > big/little) and a separate prioritized GPU zone
- * discovery plus kgsl/mali direct paths. milli-°C normalization + 1..150 sanity clamp.
- * - Battery — % capacity, power W, runtime-left estimate (charge_counter / current_now, smoothed),
- * battery temperature, plus the dual-battery current-sum for the classic overlays.
- *
- *
- * Every getter is null / absent-safe: nullable getters return {@code null} when a metric cannot be
- * read (the overlay hides that row, matching GameNative behavior); the legacy non-null getters return
- * 0 in that case. Not thread-safe; call from a single refresh thread per instance.
- */
public class HudMetrics {
private final Context context;
public HudMetrics(Context context) { this.context = context; }
- // DroidDeck: the readings Steam's performance overlay shows come from MangoReadings, so both agree.
private MangoReadings mango;
public void setMangoReadings(MangoReadings readings) { mango = readings; }
- // =======================================================================
- // CPU usage
- // =======================================================================
private Long lastCpuTotal = null;
private Long lastCpuIdle = null;
- /**
- * Overall device CPU usage 0..100 computed from the /proc/stat delta since the last call, with a
- * scaling-frequency fallback. Returns null only when neither source is readable.
- */
public Integer getCpuUsagePercent() {
String line = readFirstLine("/proc/stat");
if (line != null) {
@@ -104,8 +72,6 @@ public class HudMetrics {
return clampPercent((int) usage);
}
}
- // First sample seeds the delta — fall through to the frequency estimate so the
- // very first read still returns something.
}
}
}
@@ -127,20 +93,10 @@ public class HudMetrics {
return clampPercent((int) ((currentTotal * 100L) / maxTotal));
}
- /** Legacy non-null accessor (0 when unavailable). Kept for {@code PerfHudView}. */
- public float getCPUUsage() {
- Integer p = getCpuUsagePercent();
- return p == null ? 0f : p;
- }
-
- // =======================================================================
- // GPU load
- // =======================================================================
private List gpuUsagePathsCache = null;
private Long lastMaliGpuInfoMs = null;
private long lastMaliGpuInfoWallMs = 0L;
- /** GPU utilisation 0..100, or null when no readable source is found on this device. */
public Integer getGpuUsagePercent() {
for (String path : discoverGpuUsagePaths()) {
Integer p = readGpuUsageSample(path);
@@ -149,12 +105,6 @@ public class HudMetrics {
return null;
}
- /** Legacy non-null accessor (0 when unavailable). Kept for {@code PerfHudView}. */
- public int getGPULoad() {
- Integer p = getGpuUsagePercent();
- return p == null ? 0 : p;
- }
-
private List discoverGpuUsagePaths() {
if (gpuUsagePathsCache != null) return gpuUsagePathsCache;
LinkedHashSet candidates = new LinkedHashSet<>();
@@ -163,8 +113,6 @@ public class HudMetrics {
if (new File(p).canRead()) candidates.add(p);
}
- // Vendor platform nodes with hashed/addressed names we can't hard-code (e.g.
- // /sys/devices/platform/13000000.mali/utilisation, .../gpusysfs/gpu_busy, panfrost, sgpu).
File platformDir = new File("/sys/devices/platform");
File[] platformNodes = platformDir.listFiles(File::isDirectory);
if (platformNodes != null) {
@@ -211,9 +159,6 @@ public class HudMetrics {
return gpuUsagePathsCache;
}
- // Ordered, world-readable-when-present GPU utilisation nodes across the vendors we've seen:
- // Adreno KGSL, Mali (misc + Exynos vendor), PowerVR, and amdgpu-style sysfs (Samsung Xclipse /
- // "sgpu", AMD-on-Exynos). readGpuUsageSample() knows how to parse each filename shape.
private static final String[] GPU_USAGE_STATIC_PATHS = {
"/sys/class/kgsl/kgsl-3d0/gpubusy",
"/sys/class/kgsl/kgsl-3d0/gpu_busy_percentage",
@@ -223,23 +168,19 @@ public class HudMetrics {
"/sys/class/misc/mali0/device/gpuinfo",
"/sys/devices/platform/mali/utilization",
"/sys/kernel/gpu/gpu_busy",
- "/sys/devices/platform/gpusysfs/gpu_busy", // Exynos Mali vendor node
+ "/sys/devices/platform/gpusysfs/gpu_busy",
"/sys/class/misc/pvrsrvkm/device/utilisation",
- "/sys/class/pvr/utilisation", // PowerVR (Rogue) sysfs
+ "/sys/class/pvr/utilisation",
"/sys/class/pvr/gpu_utilisation",
- "/sys/class/drm/card0/device/gpu_busy_percent", // amdgpu / Xclipse (sgpu), 0..100
+ "/sys/class/drm/card0/device/gpu_busy_percent",
"/sys/class/devfreq/gpu/load",
- // ── Additive cross-vendor fallbacks (appended LAST: tried only after every path above
- // misses, so a device that already resolves — e.g. Adreno kgsl — never reaches these). ──
- "/sys/kernel/ged/hal/gpu_utilization", // MediaTek GED: " " → loading%
- "/sys/module/ged/parameters/gpu_loading", // MediaTek GED module param, plain percent
+ "/sys/kernel/ged/hal/gpu_utilization",
+ "/sys/module/ged/parameters/gpu_loading",
};
- // Percent-bearing filenames scanned under each devfreq / platform GPU node.
private static final String[] GPU_USAGE_FILES = {
"gpu_busy_percentage", "gpu_busy_percent", "gpu_load", "utilisation", "utilization",
"load", "gpu_busy", "gpuinfo",
};
- // Substrings that mark a devfreq / platform node as the GPU, across vendors.
private static final String[] GPU_NODE_TOKENS = {
"gpu", "mali", "g3d", "kgsl", "panfrost", "pvr", "powervr", "xclipse", "sgpu",
};
@@ -258,8 +199,6 @@ public class HudMetrics {
return clampPercent((int) ((busy * 100L) / total));
}
case "gpuinfo": {
- // Mali multi-line node: the GPU busy time (ms) is the last token of line 1. Utilisation
- // is the delta over wall-clock delta between two reads, so it needs state.
String line = readNthLine(path, 1);
if (line == null) return null;
String[] toks = line.trim().split("\\s+");
@@ -294,46 +233,12 @@ public class HudMetrics {
return null;
}
- // =======================================================================
- // RAM
- // =======================================================================
- public float getRAMPercent() {
- ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
- ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
- am.getMemoryInfo(mi);
- if (mi.totalMem <= 0) return 0;
- return (mi.totalMem - mi.availMem) * 100f / mi.totalMem;
- }
+ private List thermalZonesCache = null;
- /** Used RAM as "x.xGB" (or "yMB" below 1 GB), matching GameNative's HUD text. */
- public String getUsedRamText() {
- ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
- if (am == null) return "—";
- ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
- am.getMemoryInfo(mi);
- long usedBytes = Math.max(0L, mi.totalMem - mi.availMem);
- double usedGb = usedBytes / (1024.0 * 1024.0 * 1024.0);
- if (usedGb >= 1.0) return String.format(Locale.US, "%.1fGB", usedGb);
- return (usedBytes / (1024L * 1024L)) + "MB";
- }
-
- // =======================================================================
- // Temperature
- // =======================================================================
- private List thermalZonesCache = null; // each entry: {type, tempPath}
-
- /** Legacy non-null CPU-temperature accessor in °C (0 when unavailable). Kept for {@code PerfHudView}. */
- public float getTemperature() {
- Integer t = getCpuTempC();
- return t == null ? 0f : t;
- }
-
- /** Hottest representative CPU temperature in °C, or null when no CPU zone is readable. */
public Integer getCpuTempC() {
return readTemperatureC(discoverPrioritizedCpuTempPaths());
}
- /** GPU temperature in °C, or null when no GPU sensor is readable. */
public Integer getGpuTempC() {
ArrayList paths = new ArrayList<>();
paths.add("/sys/class/kgsl/kgsl-3d0/temp");
@@ -346,16 +251,16 @@ public class HudMetrics {
private List discoverPrioritizedCpuTempPaths() {
return prioritizePaths(type -> {
- if (type.contains("gpu")) return null; // never mistake a GPU zone for CPU
+ if (type.contains("gpu")) return null;
if (type.contains("cpu-silicon")) return 0;
if (type.contains("cpu-0")) return 1;
- if (type.contains("cpuss")) return 2; // Qualcomm cpuss composite
- if (type.contains("mtktscpu")) return 2; // MediaTek CPU thermal
- if (type.contains("cpu")) return 2; // cpu, cpu-*-usr, cpu_thermal, cpu_center
- if (type.contains("s5p-tmu")) return 3; // Exynos TMU
+ if (type.contains("cpuss")) return 2;
+ if (type.contains("mtktscpu")) return 2;
+ if (type.contains("cpu")) return 2;
+ if (type.contains("s5p-tmu")) return 3;
if (type.contains("soc")) return 4;
if (type.contains("cputop")) return 5;
- if (type.contains("tsens")) return 6; // Qualcomm tsens aggregate
+ if (type.contains("tsens")) return 6;
if (type.contains("cluster")) return 7;
if (type.contains("big") || type.contains("little")) return 8;
return null;
@@ -365,11 +270,11 @@ public class HudMetrics {
private List discoverPrioritizedGpuTempPaths() {
return prioritizePaths(type -> {
if (type.contains("gpu-silicon")) return 0;
- if (type.contains("gpuss")) return 1; // Qualcomm gpuss
- if (type.contains("mtktsgpu")) return 1; // MediaTek GPU thermal
+ if (type.contains("gpuss")) return 1;
+ if (type.contains("mtktsgpu")) return 1;
if (type.contains("gpu-virt")) return 2;
if (type.contains("gpu")) return 2;
- if (type.contains("g3d")) return 3; // Exynos Mali (g3d)
+ if (type.contains("g3d")) return 3;
if (type.contains("kgsl")) return 4;
if (type.contains("mali")) return 5;
if (type.contains("xclipse") || type.contains("sgpu")) return 6;
@@ -381,12 +286,11 @@ public class HudMetrics {
private List prioritizePaths(Ranker ranker) {
List zones = discoverAllThermalZones();
- ArrayList order = new ArrayList<>(); // {index, rank}
+ ArrayList order = new ArrayList<>();
for (int i = 0; i < zones.size(); i++) {
Integer r = ranker.rank(zones.get(i)[0]);
if (r != null) order.add(new int[]{i, r});
}
- // Sort by rank, then by path for determinism.
order.sort((a, b) -> {
if (a[1] != b[1]) return Integer.compare(a[1], b[1]);
return zones.get(a[0])[1].compareTo(zones.get(b[0])[1]);
@@ -426,14 +330,12 @@ public class HudMetrics {
if (!seen.add(path)) continue;
Integer raw = readIntFromLine(path);
if (raw == null) continue;
- // Round to nearest degree for milli-°C sources; sanity-clamp to reject offline sensors.
int celsius = raw > 1000 ? (raw + 500) / 1000 : raw;
if (celsius >= 1 && celsius <= 150) return celsius;
}
return null;
}
- /** The first path in {@code paths} that yields a plausible reading, or null. */
private String resolveTempPath(List paths) {
LinkedHashSet seen = new LinkedHashSet<>();
for (String path : paths) {
@@ -446,13 +348,8 @@ public class HudMetrics {
return null;
}
- // =======================================================================
- // Temperature danger bands (green / amber / red)
- // =======================================================================
-
public enum TempSensor { CPU, GPU, BATTERY }
- /** Amber and red onset in °C. Always °C internally — conversion happens at format time only. */
public static final class Thresholds {
public final int amberC;
public final int redC;
@@ -463,19 +360,14 @@ public class HudMetrics {
public static final int TEMP_COLOR_AMBER = 0xFFFFB74D;
public static final int TEMP_COLOR_RED = 0xFFEF5350;
- // Tier-2 fallbacks, used when the device declares no usable trip points. Battery is the only one
- // with a well-grounded number (Li-ion); CPU/GPU vary enough between parts that these are a
- // deliberately conservative guess — which is exactly why trip points are preferred.
private static final int DEFAULT_RED_CPU = 90;
private static final int DEFAULT_RED_GPU = 90;
private static final int DEFAULT_RED_BAT = 48;
- /** Amber sits a proportional step below red, which scales sensibly across both CPU/GPU and battery ranges. */
public static int amberForRed(int redC) {
return Math.round(redC * 0.88f);
}
- /** Parsed temperature display options, shared by every overlay so they can't disagree. */
public static final class TempDisplay {
public final boolean fahrenheit;
public final boolean colorBands;
@@ -518,17 +410,11 @@ public class HudMetrics {
}
}
- // Trip points are a device constant — resolve once per sensor and keep it.
private final java.util.EnumMap autoThresholdCache =
new java.util.EnumMap<>(TempSensor.class);
private final java.util.EnumSet autoThresholdResolved =
java.util.EnumSet.noneOf(TempSensor.class);
- /**
- * Bands for a sensor. Manual mode uses the user's red point; Auto prefers the device's OWN
- * declared thermal trip points (per-device truth — a handheld with active cooling and a phone on
- * the same SoC throttle at very different points) and falls back to {@link #DEFAULT_RED_CPU} etc.
- */
public Thresholds resolveThresholds(TempSensor sensor, TempDisplay display) {
if (display != null && !display.auto) {
int red = display.manualRedFor(sensor);
@@ -547,15 +433,6 @@ public class HudMetrics {
return new Thresholds(amberForRed(red), red);
}
- /**
- * Bands from the kernel's declared trip points for the zone we actually read this sensor from:
- * amber ← the lowest sane {@code passive} trip, red ← the lowest sane {@code hot}/{@code critical}.
- *
- * Returns null unless a usable red point is found. Two real traps this guards against: some
- * zones aren't temperature sensors at all (a Snapdragon's {@code pm8550-bcl-lvl0} battery-current
- * limiter reports {@code trip_point_0_temp = 1} with type {@code passive}), and the GPU is often
- * read from a non-thermal_zone node ({@code /sys/class/kgsl/...}) that has no trip points.
- */
private Thresholds readTripPointThresholds(TempSensor sensor) {
String tempPath;
switch (sensor) {
@@ -563,7 +440,7 @@ public class HudMetrics {
tempPath = resolveTempPath(discoverPrioritizedGpuTempPaths());
break;
case BATTERY:
- return null; // battery temp comes from BatteryManager, not a thermal zone
+ return null;
default:
tempPath = resolveTempPath(discoverPrioritizedCpuTempPaths());
}
@@ -580,8 +457,6 @@ public class HudMetrics {
Integer raw = readIntFromLine(tripTemp.getPath());
if (raw == null) continue;
int celsius = raw > 1000 ? (raw + 500) / 1000 : raw;
- // Reject anything that isn't plausibly a thermal trip — this is what filters out the
- // battery-current-limiter zones whose "trip point" is a level index, not a temperature.
if (celsius < 20 || celsius > 120) continue;
String typePath = tripTemp.getPath().replaceAll("_temp$", "_type");
@@ -600,7 +475,6 @@ public class HudMetrics {
return new Thresholds(amber, red);
}
- /** Band colour for a reading, or {@code fallbackColor} when banding is off or the value is unusable. */
public static int tempColor(Float celsius, Thresholds t, TempDisplay display, int fallbackColor) {
if (celsius == null || t == null || display == null || !display.colorBands) return fallbackColor;
if (celsius >= t.redC) return TEMP_COLOR_RED;
@@ -608,7 +482,6 @@ public class HudMetrics {
return TEMP_COLOR_OK;
}
- /** Formats a °C reading in the user's unit. Thresholds stay °C; only display converts. */
public static String formatTemp(float celsius, TempDisplay display, boolean oneDecimal) {
boolean f = display != null && display.fahrenheit;
float value = f ? celsius * 9f / 5f + 32f : celsius;
@@ -618,15 +491,12 @@ public class HudMetrics {
: String.format(Locale.ENGLISH, "%d%s", Math.round(value), unit);
}
- // =======================================================================
- // Battery
- // =======================================================================
public static final class Battery {
public final float watts;
public final boolean charging;
- public final Integer percent; // 0..100 or null
- public final Integer tempC; // rounded °C or null
- public final String runtimeText; // "LEFT 2h 5m" / "LEFT CHG" / null
+ public final Integer percent;
+ public final Integer tempC;
+ public final String runtimeText;
Battery(float watts, boolean charging) {
this(watts, charging, null, null, null);
@@ -640,29 +510,23 @@ public class HudMetrics {
}
}
- /** power_supply current_now channels (µA) for the dual-battery sum. */
private static final String[] CURRENT_CHANNELS = {
"/sys/class/power_supply/battery/current_now",
"/sys/class/power_supply/bms/current_now",
"/sys/class/power_supply/main/current_now",
};
- /** power_supply voltage_now channels (µV) — fallback when {@code EXTRA_VOLTAGE} reads 0 on some
- * OEM firmwares (e.g. HONOR Magic), which otherwise leaves wattage stuck at 0.0W. */
private static final String[] VOLTAGE_CHANNELS = {
"/sys/class/power_supply/battery/voltage_now",
"/sys/class/power_supply/bms/voltage_now",
"/sys/class/power_supply/main/voltage_now",
};
- /** power_supply power_now channels (µW) — last-resort direct power reading when neither the
- * BatteryManager voltage nor {@code voltage_now} is available. */
private static final String[] POWER_CHANNELS = {
"/sys/class/power_supply/battery/power_now",
"/sys/class/power_supply/bms/power_now",
"/sys/class/power_supply/main/power_now",
};
- /** First readable long across a channel list, or null. */
private static Long readLongFromChannels(String[] paths) {
for (String p : paths) {
Long v = readLongFromLine(p);
@@ -671,15 +535,6 @@ public class HudMetrics {
return null;
}
- /**
- * ADDITIVE charging fallback from {@code /sys/class/power_supply/*}, consulted ONLY when the
- * framework gave no usable charge state ({@code EXTRA_STATUS == UNKNOWN} or a null battery intent).
- * A charger/input supply reporting {@code online == 1} — or the battery's own {@code status} reading
- * "Charging"/"Full" — means charging. Returns TRUE when charging is positively detected, FALSE when a
- * status/online node is readable but not charging, or null when nothing usable exists (so the caller
- * keeps its own default). Never reached on devices whose BatteryManager reports a real status
- * (e.g. Adreno phones/handhelds), so it cannot change their reading.
- */
private static Boolean readChargingFromPowerSupply() {
File[] supplies = new File("/sys/class/power_supply").listFiles();
if (supplies == null || supplies.length == 0) return null;
@@ -690,14 +545,12 @@ public class HudMetrics {
type = type == null ? "" : type.trim().toLowerCase(Locale.US);
boolean isBattery = type.equals("battery") || name.equals("battery") || name.equals("bms");
if (isBattery) {
- // The battery's own status string is the most direct charge-state signal.
String st = readFirstLine(new File(supply, "status").getPath());
if (st == null) continue;
st = st.trim().toLowerCase(Locale.US);
- sawSignal = Boolean.FALSE; // "discharging"/"not charging" both land here
+ sawSignal = Boolean.FALSE;
if (st.equals("charging") || st.equals("full")) return Boolean.TRUE;
} else {
- // A charger / power-input supply (ac/usb/wireless/mains/dc): online==1 → external power in.
Long online = readLongFromLine(new File(supply, "online").getPath());
if (online == null) continue;
sawSignal = Boolean.FALSE;
@@ -712,55 +565,6 @@ public class HudMetrics {
private static final double RUNTIME_SMOOTHING_OLD_WEIGHT = 0.65;
private static final double RUNTIME_SMOOTHING_NEW_WEIGHT = 0.35;
- /**
- * Legacy discharge-only power reading used by the classic overlays + {@code PerfHudView}:
- * watts are reported only while discharging (0 when charging). When {@code dualBattery} is set the
- * per-cell current channels are summed to correct devices that report only one cell's current.
- */
- public Battery getBattery(boolean dualBattery) {
- Intent status = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
- boolean charging = false;
- int voltageMv = 0;
- if (status != null) {
- charging = status.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0) != 0;
- voltageMv = status.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
- } else {
- // ADDITIVE: no battery intent → best-effort power_supply charge probe (default stays false).
- // Never reached on devices that deliver ACTION_BATTERY_CHANGED (e.g. Adreno).
- Boolean sysCharging = readChargingFromPowerSupply();
- if (sysCharging != null) charging = sysCharging;
- }
- long microAmps;
- if (dualBattery) {
- long sum = 0; int n = 0;
- for (String path : CURRENT_CHANNELS) {
- Long v = readLongFromLine(path);
- if (v != null) { sum += Math.abs(v); n++; }
- }
- microAmps = n > 0 ? -sum : readCurrentNowFallback();
- } else {
- microAmps = readCurrentNowFallback();
- }
- // current_now's SIGN convention is device-dependent — many OEMs (Xiaomi/Poco especially)
- // report discharge as POSITIVE, the opposite of the AOSP convention. Gating wattage on the
- // sign therefore reads 0W on battery on those devices (and only shows a value while charging).
- // Use the magnitude for the power figure; the reliable charge DIRECTION is EXTRA_PLUGGED (the
- // `charging` flag), which the HUD already uses for the PWR/CHG label.
- // EXTRA_VOLTAGE reads 0 on some OEM firmwares even though current is fine — fall back to the
- // power_supply voltage_now (µV → mV) so wattage isn't stuck at 0.
- if (voltageMv <= 0) {
- Long uv = readLongFromChannels(VOLTAGE_CHANNELS);
- if (uv != null && uv > 0) voltageMv = (int) (Math.abs(uv) / 1000L);
- }
- // current unit auto-detected (mA vs µA) — see currentRawToAmps.
- float watts = (voltageMv / 1000f) * currentRawToAmps(microAmps);
- return new Battery(watts, charging);
- }
-
- /**
- * Full GameNative-parity battery snapshot for the GameNative-style HUD: %, power W (magnitude,
- * regardless of charge/discharge), smoothed runtime-left estimate, and temperature.
- */
public Battery collectBattery() {
BatteryManager bm = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
if (bm == null) return new Battery(0f, false);
@@ -771,15 +575,12 @@ public class HudMetrics {
Intent status = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
if (status == null) {
- // No battery intent at all → additive power_supply charge probe (default stays false).
Boolean sysCharging = readChargingFromPowerSupply();
return new Battery(0f, sysCharging != null && sysCharging, percent, null, null);
}
int st = status.getIntExtra(BatteryManager.EXTRA_STATUS, BatteryManager.BATTERY_STATUS_UNKNOWN);
boolean charging = st == BatteryManager.BATTERY_STATUS_CHARGING || st == BatteryManager.BATTERY_STATUS_FULL;
- // ADDITIVE: only when the framework reports no usable charge state do we consult power_supply.
- // A device that reports CHARGING/DISCHARGING/FULL/NOT_CHARGING (e.g. Adreno) never enters this.
if (st == BatteryManager.BATTERY_STATUS_UNKNOWN) {
Boolean sysCharging = readChargingFromPowerSupply();
if (sysCharging != null) charging = sysCharging;
@@ -792,23 +593,16 @@ public class HudMetrics {
int rawTemp = status.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);
if (rawTemp > 0) tempC = Math.round(rawTemp / 10f);
- // EXTRA_VOLTAGE reads 0 on some OEM firmwares (e.g. HONOR Magic) even though capacity, temp
- // and current all work — which left wattage stuck at 0.0W. Fall back to the power_supply
- // voltage_now (µV → mV); if voltage is still unavailable, use power_now (µW) directly.
if (voltageMv <= 0) {
Long uv = readLongFromChannels(VOLTAGE_CHANNELS);
if (uv != null && uv > 0) voltageMv = (int) (Math.abs(uv) / 1000L);
}
- // Wattage = current × voltage, with current UNIT auto-detected (CURRENT_NOW is nominally µA but
- // many OEMs — e.g. this HONOR — report mA; see batteryCurrentAmps). currentMicroAmps above stays
- // as-is for the runtime estimate (a ratio, so unit-independent). If neither current nor voltage
- // resolves, fall back to power_now (µW) directly.
float amps = batteryCurrentAmps(bm);
float watts = 0f;
if (amps > 0f && voltageMv > 0) {
watts = (voltageMv / 1000f) * amps;
} else {
- Long uw = readLongFromChannels(POWER_CHANNELS); // µW
+ Long uw = readLongFromChannels(POWER_CHANNELS);
if (uw != null && uw != 0L) watts = (float) (Math.abs(uw) / 1_000_000.0);
}
@@ -842,24 +636,12 @@ public class HudMetrics {
return minutes + "m";
}
- private long readCurrentNowFallback() {
- BatteryManager bm = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
- return bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW);
- }
-
- /** Raw battery current reading → AMPS, with unit AUTO-DETECT. {@code BATTERY_PROPERTY_CURRENT_NOW}
- * (and {@code current_now}) are nominally µA, but many OEMs report mA — a small number, whereas a
- * real µA reading is always huge. So a magnitude < 20000 means the device gave mA. Without this,
- * wattage on mA-reporting devices came out ~1000× too small → 0.0W even though current & voltage are
- * fine. Sentinel/zero → 0. (Heuristic mirrors Ludashi-plus WinlatorHUD.getBatteryCurrentAmps().) */
private static float currentRawToAmps(long raw) {
if (raw == 0L || raw == Long.MIN_VALUE) return 0f;
long a = Math.abs(raw);
- return a < 20000L ? a / 1000f : a / 1_000_000f; // mA → A, else µA → A
+ return a < 20000L ? a / 1000f : a / 1_000_000f;
}
- /** Battery current in AMPS for the wattage calc: framework property first, then power_supply
- * {@code current_now} sysfs (battery/bms/main) when it's unsupported ({@code Long.MIN_VALUE}) or 0. */
private float batteryCurrentAmps(BatteryManager bm) {
long raw = (bm != null) ? bm.getLongProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW) : 0L;
if (raw == 0L || raw == Long.MIN_VALUE) {
@@ -869,11 +651,6 @@ public class HudMetrics {
return currentRawToAmps(raw);
}
- // =======================================================================
- // Clock frequencies (best-effort, nullable)
- // =======================================================================
-
- /** Peak CPU core clock in MHz (max scaling_cur_freq across cores), or null when unreadable. */
public Integer getCpuClockMhz() {
int cores = Runtime.getRuntime().availableProcessors();
long maxKhz = 0;
@@ -882,29 +659,26 @@ public class HudMetrics {
if (cur != null && cur > maxKhz) maxKhz = cur;
}
if (maxKhz <= 0) return null;
- return (int) (maxKhz / 1000L); // kHz → MHz
+ return (int) (maxKhz / 1000L);
}
private List gpuClockPathsCache = null;
private static final String[] GPU_CLOCK_PATHS = {
- "/sys/class/kgsl/kgsl-3d0/gpuclk", // Adreno, Hz
- "/sys/class/kgsl/kgsl-3d0/devfreq/cur_freq", // Adreno devfreq, Hz
- "/sys/class/kgsl/kgsl-3d0/clock_mhz", // some kernels, already MHz
- "/sys/kernel/gpu/gpu_clock", // Mali vendor node, MHz
- "/sys/devices/platform/gpusysfs/gpu_clock", // Exynos Mali vendor node, MHz
- "/sys/class/misc/mali0/device/clock", // Mali, kHz/MHz
- "/sys/class/devfreq/gpu/cur_freq", // generic devfreq gpu, Hz
- // ── Additive cross-vendor fallbacks (appended LAST: only reached when every node above
- // is unreadable, so Adreno/Mali devices that already resolve are unaffected). ──
- "/sys/kernel/ged/hal/current_freqency", // MediaTek GED (vendor's spelling), kHz
- "/sys/kernel/ged/hal/gpu_clock", // MediaTek GED alt, MHz
+ "/sys/class/kgsl/kgsl-3d0/gpuclk",
+ "/sys/class/kgsl/kgsl-3d0/devfreq/cur_freq",
+ "/sys/class/kgsl/kgsl-3d0/clock_mhz",
+ "/sys/kernel/gpu/gpu_clock",
+ "/sys/devices/platform/gpusysfs/gpu_clock",
+ "/sys/class/misc/mali0/device/clock",
+ "/sys/class/devfreq/gpu/cur_freq",
+ "/sys/kernel/ged/hal/current_freqency",
+ "/sys/kernel/ged/hal/gpu_clock",
};
private List discoverGpuClockPaths() {
if (gpuClockPathsCache != null) return gpuClockPathsCache;
LinkedHashSet found = new LinkedHashSet<>();
for (String p : GPU_CLOCK_PATHS) if (new File(p).canRead()) found.add(p);
- // Vendor-agnostic devfreq walk: any gpu/mali/panfrost/xclipse/sgpu node's cur_freq (Hz).
File[] devfreqRoots = {
new File("/sys/class/devfreq"),
new File("/sys/devices/virtual/devfreq"),
@@ -928,49 +702,31 @@ public class HudMetrics {
return gpuClockPathsCache;
}
- /** GPU clock in MHz (Adreno KGSL / devfreq / Mali nodes), or null when no source reports it. */
public Integer getGpuClockMhz() {
for (String p : discoverGpuClockPaths()) {
Long raw = readLongFromLine(p);
if (raw == null || raw <= 0) continue;
long mhz;
- if (raw >= 1_000_000L) mhz = raw / 1_000_000L; // Hz
- else if (raw >= 10_000L) mhz = raw / 1_000L; // kHz (defensive)
- else mhz = raw; // already MHz
+ if (raw >= 1_000_000L) mhz = raw / 1_000_000L;
+ else if (raw >= 10_000L) mhz = raw / 1_000L;
+ else mhz = raw;
if (mhz >= 1 && mhz <= 3000) return (int) mhz;
}
return null;
}
- // =======================================================================
- // VRAM (best-effort, Java-only sysfs — no native rebuild)
- // =======================================================================
- // Covered here in pure Java: Adreno KGSL (bytes mapped/allocated) and amdgpu-style drm nodes
- // (Samsung Xclipse / "sgpu", AMD-on-Exynos), which expose mem_info_vram_used/_total directly.
- // TODO(native): VK_EXT_memory_budget as a vendor-agnostic fallback for Mali/PowerVR, which expose
- // no world-readable VRAM node. FEASIBILITY (checked 2026-07): the compositor's Vulkan layer
- // (app/src/main/cpp/winlator/vulkan.c) creates an EPHEMERAL VkInstance/VkPhysicalDevice inside
- // getRenderer() and destroys it every call — it holds no reusable device and loads only the
- // properties/extension entrypoints, not vkGetPhysicalDeviceMemoryProperties2. Wiring the budget
- // query therefore means a new JNI method + enabling VK_KHR_get_physical_device_properties2 /
- // VK_EXT_memory_budget at instance create + an NDK rebuild — out of scope for a source-only pass.
- // CAVEAT to document if/when added: this HUD is an app-side overlay, NOT in the game's Vulkan
- // device, so an app-created instance reports the DEVICE-WIDE heap budget (a GPU-memory-pressure
- // proxy), not the game's per-process VRAM. Devices with no readable node return null → HUD hides VRAM.
private List vramUsedPathsCache = null;
private static final String[] VRAM_USED_PATHS = {
- "/sys/class/kgsl/kgsl-3d0/gpumem_mapped", // bytes currently mapped to the GPU
- "/sys/class/kgsl/kgsl-3d0/page_alloc", // bytes allocated to the KGSL page pool
- "/sys/class/kgsl/kgsl-3d0/mapped", // alt name on some kernels
- "/sys/class/drm/card0/device/mem_info_vram_used",// amdgpu / Xclipse (sgpu), bytes
- "/sys/class/kgsl/kgsl-3d0/page_alloc_max", // high-water fallback
+ "/sys/class/kgsl/kgsl-3d0/gpumem_mapped",
+ "/sys/class/kgsl/kgsl-3d0/page_alloc",
+ "/sys/class/kgsl/kgsl-3d0/mapped",
+ "/sys/class/drm/card0/device/mem_info_vram_used",
+ "/sys/class/kgsl/kgsl-3d0/page_alloc_max",
};
- // Total-VRAM companions (amdgpu exposes one; used only by the diagnostics report).
private static final String[] VRAM_TOTAL_PATHS = {
"/sys/class/drm/card0/device/mem_info_vram_total",
};
- /** Used GPU memory in bytes from Adreno KGSL sysfs, or null when this device exposes nothing readable. */
public Long getVramUsedBytes() {
if (vramUsedPathsCache == null) {
ArrayList found = new ArrayList<>();
@@ -986,50 +742,33 @@ public class HudMetrics {
private static Long sanitizeVramBytes(Long v) {
if (v == null) return null;
- if (v < (1L << 20)) return null; // < 1 MiB → idle-zero / not a byte count
- if (v > 64L * (1L << 30)) return null; // > 64 GiB → not bytes
+ if (v < (1L << 20)) return null;
+ if (v > 64L * (1L << 30)) return null;
return v;
}
- /** Used GPU memory as "x.xGiB" (or "yMiB"), or null when no VRAM source is readable. */
- public String getVramUsedText() {
- Long b = getVramUsedBytes();
- return b == null ? null : formatGiB(b);
- }
-
private static String formatGiB(long bytes) {
return String.format(Locale.US, "%.1fGiB", bytes / (1024.0 * 1024.0 * 1024.0));
}
- // =======================================================================
- // Single cached snapshot — read EVERYTHING once per HUD refresh
- // =======================================================================
-
- /**
- * Immutable point-in-time reading of every metric the Fusion HUD draws. Collected in one pass by
- * {@link #snapshot()} so the view never touches sysfs / BatteryManager during draw (the user's
- * explicit ask: one collection pass, cached, so gameplay isn't strained). All numeric fields are
- * raw (nullable when unreadable); the view formats + colours them.
- */
public static final class Snapshot {
- public final Integer cpuPercent; // 0..100 or null
- public final Integer gpuPercent; // 0..100 or null
- public final Integer cpuClockMhz; // MHz or null
- public final Integer gpuClockMhz; // MHz or null
- public final Integer cpuTempC; // °C or null
- public final Integer gpuTempC; // °C or null
+ public final Integer cpuPercent;
+ public final Integer gpuPercent;
+ public final Integer cpuClockMhz;
+ public final Integer gpuClockMhz;
+ public final Integer cpuTempC;
+ public final Integer gpuTempC;
public final long ramUsedBytes;
public final long ramTotalBytes;
- public final float ramPercent; // 0..100
- public final Long vramUsedBytes; // bytes or null
- public final Battery battery; // never null
- // ---- Mega-only extras ----
- public final int[] perCorePercent; // per-core 0..100, -1 unknown (never null; may be empty)
- public final int[] perCoreClockMhz; // per-core MHz, 0 unknown (never null; may be empty)
- public final Long swapUsedBytes; // bytes or null (no swap)
- public final Long swapTotalBytes; // bytes or null
- public final Long netDownBps; // bytes/sec down, or null (first sample / unreadable)
- public final Long netUpBps; // bytes/sec up, or null
+ public final float ramPercent;
+ public final Long vramUsedBytes;
+ public final Battery battery;
+ public final int[] perCorePercent;
+ public final int[] perCoreClockMhz;
+ public final Long swapUsedBytes;
+ public final Long swapTotalBytes;
+ public final Long netDownBps;
+ public final Long netUpBps;
Snapshot(Integer cpuPercent, Integer gpuPercent, Integer cpuClockMhz, Integer gpuClockMhz,
Integer cpuTempC, Integer gpuTempC, long ramUsedBytes, long ramTotalBytes,
@@ -1066,7 +805,6 @@ public class HudMetrics {
}
}
- /** One collection pass over every metric. Call from the HUD's own ~1 s refresh thread, never draw. */
public Snapshot snapshot() {
if (mango != null) return mangoSnapshot(mango);
Integer cpu = getCpuUsagePercent();
@@ -1102,7 +840,6 @@ public class HudMetrics {
net == null ? null : net[0], net == null ? null : net[1]);
}
- // DroidDeck: the same snapshot with MangoHud's sources and rounding (see MangoReadings).
private Snapshot mangoSnapshot(MangoReadings m) {
MangoReadings.Cpu cpu = m.cpu();
MangoReadings.Memory mem = m.memory();
@@ -1121,11 +858,6 @@ public class HudMetrics {
net == null ? null : net[0], net == null ? null : net[1]);
}
- // =======================================================================
- // Mega-view extras: per-core CPU, swap, network (best-effort, nullable)
- // =======================================================================
-
- /** Per-core clock in MHz (each core's {@code scaling_cur_freq}); 0 for a core that can't be read. */
public int[] getPerCoreClockMhz() {
int cores = Runtime.getRuntime().availableProcessors();
int[] out = new int[Math.max(0, cores)];
@@ -1136,11 +868,12 @@ public class HudMetrics {
return out;
}
- // Per-core /proc/stat deltas — one prev sample per core, seeded on the first read.
private long[] lastCoreTotal = null;
private long[] lastCoreIdle = null;
+ private static final int PER_CORE_STAT = 1, PER_CORE_ESTIMATE = 2;
+ /** Sources of the last per-core reading: PER_CORE_STAT and/or PER_CORE_ESTIMATE (clock speed); 0 when no core was read. */
+ private volatile int perCoreSources = 0;
- /** Per-core CPU usage 0..100 from the {@code cpuN} /proc/stat deltas; -1 for a core not yet sampled. */
public int[] readPerCorePercent() {
int cores = Runtime.getRuntime().availableProcessors();
int[] out = new int[Math.max(0, cores)];
@@ -1153,8 +886,8 @@ public class HudMetrics {
try (BufferedReader r = new BufferedReader(new FileReader("/proc/stat"))) {
String line;
while ((line = r.readLine()) != null) {
- if (!line.startsWith("cpu")) break; // cpu lines are first; stop at the block end
- if (line.length() < 4 || !Character.isDigit(line.charAt(3))) continue; // skip aggregate "cpu "
+ if (!line.startsWith("cpu")) break;
+ if (line.length() < 4 || !Character.isDigit(line.charAt(3))) continue;
String[] parts = line.trim().split("\\s+");
int core;
try { core = Integer.parseInt(parts[0].substring(3)); } catch (Exception e) { continue; }
@@ -1165,8 +898,8 @@ public class HudMetrics {
try {
long v = Long.parseLong(parts[i]);
total += v;
- if (i == 4) idle = v; // idle
- else if (i == 5) idle += v; // + iowait
+ if (i == 4) idle = v;
+ else if (i == 5) idle += v;
} catch (NumberFormatException e) { ok = false; break; }
}
if (!ok) continue;
@@ -1179,21 +912,23 @@ public class HudMetrics {
}
}
} catch (Exception ignored) {}
- // Frequency fallback for any core /proc/stat couldn't give us — restricted on some firmwares
- // (e.g. HONOR / Android 16), which is also why the aggregate getCpuUsagePercent() falls back.
- // scaling_cur_freq / cpuinfo_max_freq is a load proxy (per-core clocks ARE readable there), and
- // it also seeds the very first sample. Cores with a real /proc/stat delta keep it (no regression).
+ int sources = 0;
for (int i = 0; i < out.length; i++) {
- if (out[i] >= 0) continue;
+ if (out[i] >= 0) {
+ sources |= PER_CORE_STAT;
+ continue;
+ }
Long cur = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/scaling_cur_freq");
Long max = readLongFromLine("/sys/devices/system/cpu/cpu" + i + "/cpufreq/cpuinfo_max_freq");
- if (cur != null && max != null && max > 0L)
+ if (cur != null && max != null && max > 0L) {
out[i] = clampPercent((int) ((Math.max(0L, Math.min(cur, max)) * 100L) / max));
+ sources |= PER_CORE_ESTIMATE;
+ }
}
+ perCoreSources = sources;
return out;
}
- /** Swap {used, total} in bytes from /proc/meminfo, or null when there is no swap. */
public long[] getSwapBytes() {
long totalKb = -1, freeKb = -1;
try (BufferedReader r = new BufferedReader(new FileReader("/proc/meminfo"))) {
@@ -1215,10 +950,8 @@ public class HudMetrics {
return v == null ? -1 : v;
}
- // Net rate: cumulative rx/tx bytes + the wall-clock of the previous read → bytes/sec.
private long lastNetRx = -1, lastNetTx = -1, lastNetWallMs = 0;
- /** Network {down, up} in bytes/sec (all interfaces except loopback), or null on the first/failed read. */
public long[] readNetRateBps() {
long rx = 0, tx = 0;
boolean any = false;
@@ -1241,7 +974,7 @@ public class HudMetrics {
long now = SystemClock.elapsedRealtime();
long prevRx = lastNetRx, prevTx = lastNetTx, prevWall = lastNetWallMs;
lastNetRx = rx; lastNetTx = tx; lastNetWallMs = now;
- if (prevRx < 0 || prevWall <= 0) return null; // seed
+ if (prevRx < 0 || prevWall <= 0) return null;
long dt = now - prevWall;
if (dt <= 0) return null;
long down = Math.max(0L, (rx - prevRx) * 1000L / dt);
@@ -1249,26 +982,14 @@ public class HudMetrics {
return new long[]{down, up};
}
- // =======================================================================
- // Diagnostics report (invoked ONLY on user tap — never on the HUD refresh path)
- // =======================================================================
-
- /**
- * One-tap plain-text device report for the "Export HUD diagnostics" action: for every metric it
- * lists the resolved source path/API + current value, or MISS + the exact candidates it tried,
- * followed by an "exists on this device" dump (thermal zone types, devfreq/kgsl/mali nodes) so a
- * device owner can send back the real path for anything that missed. Does a short prime+sample so
- * delta-based readers (CPU%/GPU%/net) report a live value. Run OFF the main thread.
- */
public String buildDiagnosticsReport(Context ctxIn) {
final Context ctx = ctxIn != null ? ctxIn : this.context;
- // Prime the delta-based readers, wait, then take a live sample.
snapshot();
try { Thread.sleep(350L); } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); }
Snapshot s = snapshot();
StringBuilder sb = new StringBuilder();
- sb.append("DroidDeck FusionHUD diagnostics\n");
+ sb.append("DroidDeck HUD diagnostics\n");
sb.append("Generated: ")
.append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(new Date())).append('\n');
sb.append("Device: ").append(Build.MANUFACTURER).append(' ').append(Build.MODEL).append('\n');
@@ -1281,7 +1002,6 @@ public class HudMetrics {
sb.append("\n== Metrics ==\n");
- // ---- CPU ----
boolean procStat = new File("/proc/stat").canRead();
if (s.cpuPercent != null) {
metricHit(sb, "CPU %", s.cpuPercent + "%",
@@ -1292,19 +1012,20 @@ public class HudMetrics {
"/sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq");
}
- // Per-core %
StringBuilder cores = new StringBuilder();
for (int i = 0; i < s.perCorePercent.length; i++) {
if (i > 0) cores.append(' ');
int v = s.perCorePercent[i];
cores.append('c').append(i).append('=').append(v < 0 ? "?" : (v + "%"));
}
- if (s.perCorePercent.length > 0)
- metricHit(sb, "Per-core %", cores.toString(), "/proc/stat (per-cpu lines)");
+ int coreSources = perCoreSources;
+ if (s.perCorePercent.length > 0 && coreSources != 0)
+ metricHit(sb, "Per-core %", cores.toString(), coreSources == PER_CORE_STAT ? "/proc/stat (per-cpu lines)"
+ : coreSources == PER_CORE_ESTIMATE ? "scaling_cur_freq / cpuinfo_max_freq (clock estimate)"
+ : "/proc/stat (per-cpu lines); scaling_cur_freq / cpuinfo_max_freq (clock estimate) for the other cores");
else
- metricMiss(sb, "Per-core %", "/proc/stat");
+ metricMiss(sb, "Per-core %", "/proc/stat", "/sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq");
- // Per-core clock
StringBuilder coreClk = new StringBuilder();
for (int i = 0; i < s.perCoreClockMhz.length; i++) {
if (i > 0) coreClk.append(' ');
@@ -1317,7 +1038,6 @@ public class HudMetrics {
else
metricMiss(sb, "CPU clock", "/sys/devices/system/cpu/cpu*/cpufreq/scaling_cur_freq");
- // CPU temp
String cpuTempPath = resolveTempPath(discoverPrioritizedCpuTempPaths());
if (s.cpuTempC != null && cpuTempPath != null)
metricHit(sb, "CPU temp", s.cpuTempC + "°C", cpuTempPath);
@@ -1325,7 +1045,6 @@ public class HudMetrics {
metricMiss(sb, "CPU temp",
"/sys/class/thermal/thermal_zone*/temp (types: cpu*/cpuss/tsens/mtktscpu/s5p-tmu/soc)");
- // ---- GPU ----
String gpuUsagePath = firstReadableGpuUsagePath();
if (s.gpuPercent != null && gpuUsagePath != null)
metricHit(sb, "GPU %", s.gpuPercent + "%", gpuUsagePath);
@@ -1347,7 +1066,6 @@ public class HudMetrics {
"/sys/class/kgsl/kgsl-3d0/temp", "/sys/class/misc/mali0/device/temp",
"/sys/class/thermal/thermal_zone*/temp (types: gpu*/gpuss/g3d/kgsl/mali/mtktsgpu)");
- // ---- Memory ----
metricHit(sb, "RAM", s.ramUsedText() + " / " + s.ramTotalText()
+ " (" + Math.round(s.ramPercent) + "%)", "ActivityManager.MemoryInfo");
if (s.swapUsedBytes != null)
@@ -1355,7 +1073,6 @@ public class HudMetrics {
else
metricMiss(sb, "SWAP", "/proc/meminfo (SwapTotal=0 or unreadable)");
- // VRAM
String vramPath = firstReadableVramUsedPath();
if (s.vramUsedBytes != null && vramPath != null) {
Long total = readFirstReadableLong(VRAM_TOTAL_PATHS);
@@ -1366,14 +1083,12 @@ public class HudMetrics {
new ArrayList<>(), VRAM_USED_PATHS);
}
- // ---- Net ----
if (s.netDownBps != null)
metricHit(sb, "NET", formatRate(s.netDownBps) + " down / " + formatRate(s.netUpBps) + " up",
"/proc/net/dev");
else
metricMiss(sb, "NET", "/proc/net/dev (first sample or unreadable)");
- // ---- Battery ----
Battery b = s.battery;
StringBuilder bat = new StringBuilder();
bat.append(b.percent != null ? b.percent + "%" : "?%")
@@ -1383,7 +1098,6 @@ public class HudMetrics {
.append(b.runtimeText != null ? ", " + b.runtimeText : "");
metricHit(sb, "Battery", bat.toString(), "BatteryManager + /sys/class/power_supply");
- // ---- Exists-on-device dump ----
appendExistsDump(sb);
return sb.toString();
}
@@ -1415,7 +1129,7 @@ public class HudMetrics {
}
private String firstReadableVramUsedPath() {
- if (vramUsedPathsCache == null) getVramUsedBytes(); // builds the cache
+ if (vramUsedPathsCache == null) getVramUsedBytes();
if (vramUsedPathsCache == null) return null;
for (String p : vramUsedPathsCache) if (sanitizeVramBytes(readLongFromLine(p)) != null) return p;
return null;
@@ -1479,12 +1193,6 @@ public class HudMetrics {
appendGpuNoRootProbes(sb);
}
- /** Probes for a ROOT-FREE GPU-load path on locked-sysfs Adreno devices (SM8750/HONOR etc.):
- * (1) can the app open the KGSL device node? The sysfs mirror (/sys/class/kgsl) is SELinux-blocked
- * (vendor_sysfs_kgsl), but /dev/kgsl-3d0 is labeled gpu_device and is normally app-openable —
- * that's the door for reading GPU busy via ioctl perf-counters instead of sysfs.
- * (2) is there an app-readable devfreq node under /sys/devices/platform that bypasses the blocked
- * /sys/class/kgsl symlink (a free win for at least the clock). */
private void appendGpuNoRootProbes(StringBuilder sb) {
sb.append("-- GPU no-root reachability probes --\n");
sb.append(" /dev/kgsl-3d0 open O_RDWR: ")
@@ -1516,8 +1224,6 @@ public class HudMetrics {
if (!found) sb.append(" devfreq (platform kgsl): (no app-readable node found)\n");
}
- /** open()+close() a path with the given flags, reporting OK or the errno class — used to test
- * whether the app's sandbox can reach a device node without root. */
private static String probeOpen(String path, int flags) {
java.io.FileDescriptor fd = null;
try {
@@ -1530,8 +1236,6 @@ public class HudMetrics {
}
}
- /** Battery-wattage inputs: which power_supply nodes this app can actually READ, and their raw
- * values. Confirms the voltage_now / power_now fallback for devices where EXTRA_VOLTAGE is 0. */
private void appendPowerSupplyDump(StringBuilder sb) {
sb.append("-- /sys/class/power_supply (battery watts inputs) --\n");
File[] nodes = new File("/sys/class/power_supply").listFiles();
@@ -1582,9 +1286,6 @@ public class HudMetrics {
return names.length() == 0 ? "(no readable files)" : names.toString();
}
- // =======================================================================
- // Low-level helpers
- // =======================================================================
private static int clampPercent(int v) { return v < 0 ? 0 : (v > 100 ? 100 : v); }
private static String readFirstLine(String path) {
diff --git a/app/src/main/java/com/droiddeck/launcher/hud/KeyValueSet.java b/app/src/main/java/com/droiddeck/launcher/hud/KeyValueSet.java
index 1c3a1ba9b9..f455d85256 100644
--- a/app/src/main/java/com/droiddeck/launcher/hud/KeyValueSet.java
+++ b/app/src/main/java/com/droiddeck/launcher/hud/KeyValueSet.java
@@ -8,7 +8,7 @@
* link to https://github.com/The412Banner/FusionHUD in the project documentation
* AND in the in-app credits/about screen.
*
- * Ported to DroidDeck from FusionHUD (Bannerlator's HUD); DroidDeck changes are marked in the code.
+ * Ported to DroidDeck from FusionHUD (Bannerlator's HUD) and modified for DroidDeck.
*/
package com.droiddeck.launcher.hud;
@@ -20,17 +20,14 @@ import java.util.Iterator;
public class KeyValueSet implements Iterable {
private String data = "";
- // Default constructor for an empty KeyValueSet
public KeyValueSet() {
this.data = "";
}
- // Constructor to initialize with a string representation of key-value pairs
public KeyValueSet(String data) {
this.data = data != null && !data.isEmpty() ? data : "";
}
- // Helper method to find the start and end indices of a key in the data string
private int[] indexOfKey(String key) {
int start = 0;
int end = data.indexOf(",");
@@ -48,37 +45,31 @@ public class KeyValueSet implements Iterable {
return null;
}
- // Method to get the value associated with a key, or an empty string if the key is not present
public String get(String key) {
for (String[] keyValue : this) if (keyValue[0].equals(key)) return keyValue[1];
return "";
}
- // Method to get the value associated with a key, or a fallback value if the key is not present
public String get(String key, String fallback) {
for (String[] keyValue : this) if (keyValue[0].equals(key)) return keyValue[1];
return fallback;
}
- // Method to get a boolean value associated with a key, or a fallback value if the key is not present
public boolean getBoolean(String key, boolean fallback) {
String value = get(key);
if (value.isEmpty()) return fallback;
return value.equals("1") || value.equals("t") || value.equalsIgnoreCase("true");
}
- // Method to get a float value associated with a key, or a fallback value if the key is not present
public float getFloat(String key, float fallback) {
String value = get(key);
try {
if (!value.isEmpty()) return Float.parseFloat(value);
} catch (NumberFormatException e) {
- // Ignore exception and return fallback
}
return fallback;
}
- // Method to set a value for a key in the key-value data
public void put(String key, Object value) {
int[] range = indexOfKey(key);
if (range != null) {
@@ -88,21 +79,15 @@ public class KeyValueSet implements Iterable {
}
}
- // 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 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() {
diff --git a/app/src/main/java/com/droiddeck/launcher/hud/MangoReadings.kt b/app/src/main/java/com/droiddeck/launcher/hud/MangoReadings.kt
index 828bcc0f5a..d9fbaa4dfc 100644
--- a/app/src/main/java/com/droiddeck/launcher/hud/MangoReadings.kt
+++ b/app/src/main/java/com/droiddeck/launcher/hud/MangoReadings.kt
@@ -1,14 +1,10 @@
package com.droiddeck.launcher.hud
+import android.os.Environment
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
+import kotlin.math.roundToInt
-/**
- * The readings Steam's performance overlay shows in a DroidDeck session (Valve's mangohud 20260902.1,
- * tools/mangoapp), taken from the files the session hands it and computed the same way, so the two
- * overlays agree. Sources and formulas follow that build: cpu.cpp calculateCPUData, deckard_temp.cpp,
- * msm.cpp getQcomGpuInfo, memory.cpp update_meminfo and battery.cpp getPercent / getPower.
- */
internal class MangoReadings(private val sessionDir: File, private val rootDir: File) {
class Cpu(val percent: Int, val perCore: IntArray)
class Memory(val usedBytes: Long, val totalBytes: Long, val swapUsedBytes: Long, val swapTotalBytes: Long)
@@ -17,7 +13,6 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
private val cpuTimes = HashMap()
private val cpuPercents = HashMap()
- /** Total and per-core load from the session's /proc/stat (DroidDeck's stand-in when the app can't read it). */
@JvmOverloads
fun cpu(stat: File = statFile()): Cpu? {
val lines = runCatching { stat.readLines() }.getOrNull() ?: return null
@@ -38,7 +33,6 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
File(sessionDir, "proc-stat").takeIf { !File("/proc/stat").canRead() && it.isFile } ?: File("/proc/stat")
private fun cpuPercent(key: String, v: LongArray): Int {
- // user nice system idle iowait irq softirq steal guest guest_nice; guest time is already in user.
val user = v[0] - v[8]
val nice = v[1] - v[9]
val systemAll = v[2] + v[5] + v[6]
@@ -55,8 +49,8 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
return busy.coerceIn(0f, 100f).toInt().also { cpuPercents[key] = it }
}
- /** Average of the zones the session types cpuN-thermal, truncated. */
fun cpuTempC(): Int? {
+ externalCpuTemp()?.let { return it }
var sum = 0f
var count = 0
for (zone in LinuxRuntime.cpuTempZones()) {
@@ -67,6 +61,13 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
return if (count == 0) null else (sum / count).toInt()
}
+ /** Optional ADB helper feed: /sdcard/DroidDeck/cpu-temp, written from the host while a session runs. */
+ private fun externalCpuTemp(): Int? {
+ val file = File(Environment.getExternalStorageDirectory(), "DroidDeck/cpu-temp")
+ if (!file.isFile || System.currentTimeMillis() - file.lastModified() > CPU_TEMP_FRESH_MS) return null
+ return readFloat(file)?.takeIf { it.isFinite() && it in -20f..150f }?.roundToInt()
+ }
+
fun gpuPercent(): Int? {
val feed = fresh(File(sessionDir, "sys/kgsl-3d0/perf_now"))
val source = feed ?: LinuxRuntime.gpuLoadSource()?.let(::File) ?: return null
@@ -85,7 +86,6 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
return (milli / 1000.0).toInt()
}
- /** MemTotal - MemAvailable and SwapTotal - SwapFree from /proc/meminfo. */
fun memory(): Memory? {
val kb = HashMap()
runCatching {
@@ -103,9 +103,8 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
}
/** The KGSL total DroidDeck shares with the session (GpuMemComponent). */
- fun vramBytes(): Long? = fresh(File(rootDir, VRAM_FILE), VRAM_FRESH_MS)?.let(::readLong)
+ fun vramBytes(): Long? = fresh(File(rootDir, VRAM_FILE), VRAM_FRESH_MS)?.let(::readLong)?.takeIf { it > 0 }
- /** BAT* under the session's power_supply (BatteryComponent): no watts while charging, full or unknown. */
fun battery(): Battery? {
val dirs = File(sessionDir, "sys/power_supply").listFiles { f -> f.name.contains("BAT") }?.sortedBy { it.name }
if (dirs.isNullOrEmpty()) return null
@@ -144,12 +143,12 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
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 const val CPU_TEMP_FRESH_MS = 10_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()
diff --git a/app/src/main/java/com/droiddeck/launcher/hud/WordmarkArt.kt b/app/src/main/java/com/droiddeck/launcher/hud/WordmarkArt.kt
new file mode 100644
index 0000000000..d19c7d6e51
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/hud/WordmarkArt.kt
@@ -0,0 +1,54 @@
+package com.droiddeck.launcher.hud
+
+import android.graphics.Canvas
+import android.graphics.Paint
+import android.graphics.Path
+import androidx.compose.ui.graphics.asAndroidPath
+import androidx.compose.ui.graphics.vector.PathParser
+
+internal object WordmarkArt {
+ const val BOX_X = 239.135f
+ const val BOX_Y = 120.02f
+ const val BOX_W = 1040.7f - 239.135f
+ const val BOX_H = 243.2f - 120.02f
+ const val MARK_SCALE = 0.527445f
+
+ const val LEFT_HALF = "M-31.98 0H56.055V40.489A71.81 71.81 0 0 0 56.055 183.231V223.72H-31.98Z"
+ const val RIGHT_HALF = "M71.885 0.28A111.86 111.86 0 0 1 71.885 223.44V183.234A71.81 71.81 0 0 0 71.885 40.486Z"
+ const val LETTERS =
+ "M361.45 241.36V160.13H387.02V241.36ZM387.02 196.73 376.32 188.38Q379.5 174.17 387.02 166.31Q394.54 158.46 407.91 158.46Q413.76 158.46 418.19 160.21Q422.62 161.97 425.96 165.65L410.75 184.87Q409.08 183.03 406.57 182.03Q404.07 181.02 400.89 181.02Q394.54 181.02 390.78 184.95Q387.02 188.88 387.02 196.73" +
+ "ZM467.91 243.2Q455.38 243.2 445.27 237.6Q435.15 232 429.3 222.31Q423.45 212.61 423.45 200.58Q423.45 188.54 429.3 179.02Q435.15 169.49 445.18 163.89Q455.21 158.29 467.91 158.29Q480.62 158.29 490.64 163.81Q500.67 169.32 506.52 178.93Q512.37 188.54 512.37 200.58Q512.37 212.61 506.52 222.31Q500.67 232 490.64 237.6Q480.62 243.2 467.91 243.2" +
+ "ZM467.91 219.97Q473.43 219.97 477.61 217.54Q481.79 215.12 484.04 210.69Q486.3 206.26 486.3 200.58Q486.3 194.9 483.96 190.63Q481.62 186.37 477.52 183.95Q473.43 181.52 467.91 181.52Q462.56 181.52 458.39 183.95Q454.21 186.37 451.87 190.72Q449.53 195.06 449.53 200.75Q449.53 206.26 451.87 210.69Q454.21 215.12 458.39 217.54Q462.56 219.97 467.91 219.97" +
+ "ZM523.4 241.36V160.13H548.98V241.36ZM536.27 148.93Q530.26 148.93 526.33 144.84Q522.4 140.74 522.4 134.89Q522.4 128.88 526.33 124.86Q530.26 120.85 536.27 120.85Q542.29 120.85 546.13 124.86Q549.98 128.88 549.98 134.89Q549.98 140.74 546.13 144.84Q542.29 148.93 536.27 148.93ZM599.95 243.03Q588.42 243.03 579.48 237.52Q570.54 232 565.44 222.47Q560.34 212.95 560.34 200.75Q560.34 188.54 565.44 179.02Q570.54 169.49 579.48 163.97Q588.42 158.46 599.95 158.46Q608.31 158.46 615.08 161.63Q621.85 164.81 626.28 170.41Q630.71 176.01 631.21 183.2V217.46Q630.71 224.65 626.36 230.41Q622.02 236.18 615.16 239.61Q608.31 243.03 599.95 243.03" +
+ "ZM604.47 219.97Q609.98 219.97 613.99 217.54Q618 215.12 620.34 210.77Q622.68 206.43 622.68 200.75Q622.68 195.06 620.43 190.8Q618.17 186.54 614.08 184.03Q609.98 181.52 604.63 181.52Q599.28 181.52 595.19 184.03Q591.09 186.54 588.67 190.88Q586.25 195.23 586.25 200.75Q586.25 206.26 588.59 210.61Q590.93 214.95 595.11 217.46Q599.28 219.97 604.47 219.97" +
+ "ZM646.75 241.36H621.68V219.46L625.53 199.74L621.18 180.02V120.02H646.75ZM683.19 241.36V218.29H712.44Q723.13 218.29 731.16 214.03Q739.18 209.77 743.53 201.58Q747.87 193.39 747.87 182.19Q747.87 170.99 743.44 162.97Q739.01 154.95 731.07 150.6Q723.13 146.26 712.44 146.26H682.35V123.36H712.77Q726.14 123.36 737.42 127.62Q748.71 131.88 757.15 139.82Q765.59 147.76 770.18 158.54Q774.78 169.32 774.78 182.36Q774.78 195.23 770.18 206.09Q765.59 216.96 757.23 224.81Q748.87 232.67 737.59 237.01Q726.31 241.36 713.11 241.36" +
+ "ZM665.47 241.36V123.36H691.71V241.36ZM827.6 243.2Q814.39 243.2 804.11 237.77Q793.83 232.33 787.98 222.64Q782.13 212.95 782.13 200.75Q782.13 188.54 787.9 178.93Q793.67 169.32 803.53 163.81Q813.39 158.29 825.76 158.29Q837.79 158.29 846.98 163.47Q856.18 168.65 861.44 177.85Q866.71 187.04 866.71 198.91Q866.71 201.08 866.46 203.5Q866.21 205.93 865.54 209.1L795.51 209.27V191.72L854.67 191.55L843.64 198.91Q843.47 191.89 841.47 187.29Q839.46 182.69 835.54 180.27Q831.61 177.85 825.92 177.85Q819.91 177.85 815.48 180.61Q811.05 183.36 808.63 188.38Q806.2 193.39 806.2 200.58Q806.2 207.77 808.79 212.86Q811.38 217.96 816.15 220.72Q820.91 223.48 827.43 223.48Q833.45 223.48 838.29 221.39Q843.14 219.3 846.82 215.12L860.86 229.16Q854.84 236.18 846.32 239.69Q837.79 243.2 827.6 243.2" +
+ "ZM916.68 243.2Q904.15 243.2 893.95 237.68Q883.75 232.17 877.9 222.47Q872.05 212.78 872.05 200.75Q872.05 188.54 877.99 178.93Q883.92 169.32 894.12 163.81Q904.31 158.29 917.02 158.29Q926.54 158.29 934.48 161.55Q942.42 164.81 948.6 171.33L932.22 187.71Q929.38 184.53 925.62 183.03Q921.86 181.52 917.02 181.52Q911.5 181.52 907.24 183.95Q902.98 186.37 900.55 190.63Q898.13 194.9 898.13 200.58Q898.13 206.26 900.55 210.61Q902.98 214.95 907.32 217.46Q911.67 219.97 917.02 219.97Q922.03 219.97 925.96 218.21Q929.88 216.46 932.73 213.28L948.94 229.66Q942.59 236.35 934.56 239.77Q926.54 243.2 916.68 243.2" +
+ "ZM1010.61 241.36 982.2 199.24 1010.45 160.13H1039.03L1004.93 204.09L1005.77 193.56L1040.7 241.36ZM958.63 241.36V120.02H984.21V241.36Z"
+
+ private fun parse(d: String): Path = PathParser().parsePathString(d).toPath().asAndroidPath()
+ private val letters by lazy { parse(LETTERS) }
+ private val leftHalf by lazy { parse(LEFT_HALF) }
+ private val rightHalf by lazy { parse(RIGHT_HALF) }
+ private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
+
+ fun widthFor(height: Float): Float = height * BOX_W / BOX_H
+
+ fun draw(canvas: Canvas, left: Float, top: Float, height: Float, inkColor: Int, ballColor: Int) {
+ val k = height / BOX_H
+ canvas.save()
+ canvas.translate(left, top)
+ canvas.scale(k, k)
+ canvas.translate(-BOX_X, -BOX_Y)
+ paint.color = inkColor
+ canvas.drawPath(letters, paint)
+ canvas.translate(239.135f, 123.36f)
+ canvas.scale(MARK_SCALE, MARK_SCALE)
+ canvas.translate(31.98f, 0f)
+ canvas.drawPath(leftHalf, paint)
+ canvas.drawPath(rightHalf, paint)
+ paint.color = ballColor
+ canvas.drawCircle(63.98f, 111.86f, 55.98f, paint)
+ canvas.restore()
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/BackQamInput.kt b/app/src/main/java/com/droiddeck/launcher/input/BackQamInput.kt
index 65f9e5b83e..54ae373ae2 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/BackQamInput.kt
+++ b/app/src/main/java/com/droiddeck/launcher/input/BackQamInput.kt
@@ -5,7 +5,8 @@ import android.os.Handler
import android.os.Looper
class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap: (Boolean) -> Unit,
- private val doubleTapMs: () -> Long = { 500 }, private val onCancel: () -> Unit = {}) {
+ private val doubleTapMs: () -> Long = { 500 }, private val onCancel: () -> Unit = {},
+ private val holds: () -> Boolean = { true }) {
private class Press(val hold: Runnable, var held: Boolean = false, var used: Boolean = false)
private val handler = Handler(Looper.getMainLooper())
private val presses = mutableMapOf()
@@ -20,6 +21,11 @@ class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap:
fun onChordInput() {
if (presses.isEmpty()) return
+ if (!holds()) {
+ presses.values.forEach { handler.removeCallbacks(it.hold); it.used = true }
+ cancelTap()
+ return
+ }
val alreadyHeld = presses.values.any { it.held }
presses.values.forEach {
handler.removeCallbacks(it.hold)
@@ -43,6 +49,7 @@ class BackQamInput(private val setPressed: (Boolean) -> Unit, private val onTap:
handler.removeCallbacks(singleTap)
val hold = Runnable {
val press = presses[device] ?: return@Runnable
+ if (!holds()) { press.used = true; cancelTap(); return@Runnable }
val alreadyHeld = presses.values.any { it.held }
press.held = true
presses.values.forEach { it.used = true }
diff --git a/app/src/main/java/com/droiddeck/launcher/input/BottomScreenGuests.kt b/app/src/main/java/com/droiddeck/launcher/input/BottomScreenGuests.kt
new file mode 100644
index 0000000000..ae44dc0e6c
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/input/BottomScreenGuests.kt
@@ -0,0 +1,149 @@
+package com.droiddeck.launcher.input
+
+import android.accessibilityservice.AccessibilityService
+import android.accessibilityservice.AccessibilityServiceInfo
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.graphics.Rect
+import android.hardware.display.DisplayManager
+import android.os.Build
+import android.os.Handler
+import android.os.HandlerThread
+import android.util.Log
+import android.view.Display
+import android.view.accessibility.AccessibilityEvent
+import android.view.accessibility.AccessibilityWindowInfo
+import android.view.inputmethod.InputMethodManager
+import java.util.concurrent.ConcurrentHashMap
+
+object BottomScreenGuests {
+ enum class Top { HOME, GUEST, NONE }
+
+ internal const val MIN_COVER = 0.5f
+
+ internal fun classify(pkg: String?, homes: Set): Top = when (pkg) {
+ null -> Top.NONE
+ in homes -> Top.HOME
+ else -> Top.GUEST
+ }
+
+ internal fun holder(topPkg: String?, arrival: String?, homes: Set): String? = when {
+ topPkg != null -> topPkg.takeIf { classify(it, homes) == Top.GUEST }
+ arrival != null -> arrival.takeIf { classify(it, homes) == Top.GUEST }
+ else -> null
+ }
+
+ internal fun ignorable(type: Int): Boolean = type == AccessibilityWindowInfo.TYPE_INPUT_METHOD ||
+ type == AccessibilityWindowInfo.TYPE_ACCESSIBILITY_OVERLAY ||
+ type == AccessibilityWindowInfo.TYPE_SPLIT_SCREEN_DIVIDER ||
+ type == AccessibilityWindowInfo.TYPE_MAGNIFICATION_OVERLAY
+
+ fun supported(model: String = Build.MODEL, sdk: Int = Build.VERSION.SDK_INT): Boolean =
+ sdk >= 33 && DualScreen.yieldsBottom(model)
+}
+
+class BottomScreenWatch(private val service: AccessibilityService) {
+ private class Arrival(val pkg: String)
+
+ private val thread = HandlerThread("bottom-screen").apply { start() }
+ private val handler = Handler(thread.looper)
+ private val own = service.packageName
+ private val arrivals = ConcurrentHashMap()
+ private var homes: Set = emptySet()
+ private var keyboards: Set = emptySet()
+ private var holders: Map = emptyMap()
+ private val check = Runnable { evaluate() }
+
+ fun start() {
+ current = this
+ service.serviceInfo = service.serviceInfo?.apply {
+ eventTypes = eventTypes or AccessibilityEvent.TYPE_WINDOWS_CHANGED or AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
+ flags = flags or AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS
+ }
+ handler.post {
+ homes = homePackages()
+ keyboards = keyboardPackages()
+ evaluate()
+ }
+ }
+
+ fun onEvent(event: AccessibilityEvent) {
+ when (event.eventType) {
+ AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED -> {
+ val pkg = event.packageName?.toString() ?: return
+ if (event.displayId == Display.DEFAULT_DISPLAY || pkg == own || pkg == SYSTEM_UI) return
+ arrivals[event.displayId] = Arrival(pkg)
+ }
+ AccessibilityEvent.TYPE_WINDOWS_CHANGED -> Unit
+ else -> return
+ }
+ handler.removeCallbacks(check)
+ handler.postDelayed(check, 150)
+ }
+
+ fun stop() {
+ handler.removeCallbacksAndMessages(null)
+ handler.post {
+ if (current === this) {
+ current = null
+ DualScreen.setTaken(emptySet())
+ }
+ }
+ thread.quitSafely()
+ }
+
+ private fun evaluate() {
+ val seen = HashMap(arrivals)
+ val all = runCatching { service.windowsOnAllDisplays }.getOrNull() ?: return
+ val displays = service.getSystemService(DisplayManager::class.java) ?: return
+ val taken = mutableMapOf()
+ for (i in 0 until all.size()) {
+ val id = all.keyAt(i)
+ if (id == Display.DEFAULT_DISPLAY) continue
+ val display = displays.getDisplay(id)?.takeIf(DualScreen::builtIn) ?: continue
+ val windows = all.valueAt(i)
+ val topPkg = windows.asSequence()
+ .filter { !BottomScreenGuests.ignorable(it.type) && cover(it, display) >= BottomScreenGuests.MIN_COVER }
+ .sortedByDescending { it.layer }
+ .firstNotNullOfOrNull { packageOf(it)?.takeUnless { pkg -> pkg == own } }
+ val arrival = seen[id]
+ if (topPkg != null && arrival != null) arrivals.remove(id, arrival)
+ BottomScreenGuests.holder(topPkg, arrival?.pkg?.takeUnless { it in keyboards }, homes)?.let { taken[id] = it }
+ }
+ if (current !== this) return
+ if (taken != holders) Log.i(TAG, "bottom screen holders: $taken")
+ holders = taken
+ DualScreen.setTaken(taken.keys)
+ }
+
+ private fun cover(window: AccessibilityWindowInfo, display: Display): Float {
+ val bounds = Rect().also(window::getBoundsInScreen)
+ val area = display.mode.physicalWidth.toFloat() * display.mode.physicalHeight
+ return if (area <= 0f) 0f else bounds.width().toFloat() * bounds.height() / area
+ }
+
+ private fun packageOf(window: AccessibilityWindowInfo): String? =
+ runCatching { window.getRoot(0)?.packageName?.toString() }.getOrNull()
+
+ private fun homePackages(): Set {
+ val pm = service.packageManager
+ return listOf(Intent.CATEGORY_HOME, Intent.CATEGORY_SECONDARY_HOME).flatMap { category ->
+ runCatching {
+ pm.queryIntentActivities(Intent(Intent.ACTION_MAIN).addCategory(category), PackageManager.MATCH_ALL)
+ .filter { it.priority >= 0 }
+ .mapNotNull { it.activityInfo?.packageName }
+ }.getOrDefault(emptyList())
+ }.toSet()
+ }
+
+ private fun keyboardPackages(): Set =
+ runCatching {
+ service.getSystemService(InputMethodManager::class.java)?.inputMethodList.orEmpty().map { it.packageName }.toSet()
+ }.getOrDefault(emptySet())
+
+ private companion object {
+ @Volatile var current: BottomScreenWatch? = null
+ const val TAG = "BottomScreen"
+ const val SYSTEM_UI = "com.android.systemui"
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/DirectTouchHold.kt b/app/src/main/java/com/droiddeck/launcher/input/DirectTouchHold.kt
index d38eb9758c..ee8d68ef05 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/DirectTouchHold.kt
+++ b/app/src/main/java/com/droiddeck/launcher/input/DirectTouchHold.kt
@@ -66,6 +66,10 @@ class DirectTouchHold(
held = false
}
+ fun cancelPendingHold() {
+ handler.removeCallbacks(hold)
+ }
+
fun onTouch(event: MotionEvent): Boolean {
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
if (liftPending) {
diff --git a/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt b/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt
index 7f8e8454cc..cfd37c95c5 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt
+++ b/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt
@@ -4,7 +4,11 @@ import android.content.Context
import android.hardware.display.DisplayManager
import android.os.Build
import android.view.Display
+import android.view.InputDevice
+import android.view.MotionEvent
import com.droiddeck.launcher.session.SessionPrefs
+import kotlin.math.abs
+import kotlin.math.roundToInt
object DualScreen {
const val MODE_AUTO = "auto"
@@ -13,27 +17,86 @@ object DualScreen {
val modes = listOf(MODE_AUTO, MODE_ON, MODE_OFF)
private const val TYPE_INTERNAL = 1
private val knownModels = setOf("retroid pocket duo", "ayn thor")
+ private val touchedDisplays = mutableSetOf()
+ private val takenListeners = java.util.concurrent.CopyOnWriteArraySet<() -> Unit>()
+ @Volatile private var takenDisplays: Set = emptySet()
+ private val main by lazy { android.os.Handler(android.os.Looper.getMainLooper()) }
- fun builtInDisplay(displayManager: DisplayManager, primaryDisplayId: Int): Display? =
+ fun yieldsBottom(model: String): Boolean = model.trim().lowercase().let { m -> knownModels.any(m::startsWith) }
+
+ fun taken(displayId: Int): Boolean = displayId in takenDisplays
+
+ fun setTaken(ids: Set) {
+ if (ids == takenDisplays) return
+ takenDisplays = ids
+ main.post { takenListeners.forEach { it() } }
+ }
+
+ fun watchTaken(listener: () -> Unit) { takenListeners += listener }
+
+ fun unwatchTaken(listener: () -> Unit) { takenListeners -= listener }
+
+ fun builtInDisplay(displayManager: DisplayManager, primaryDisplayId: Int): Display? {
+ val primary = displayManager.getDisplay(primaryDisplayId)
+ val awake = primary?.state != Display.STATE_OFF
+ val panels = if (awake) touchPanels() else emptyList()
+ return internalDisplay(displayManager, primaryDisplayId) {
+ if (awake && it.state == Display.STATE_OFF) return@internalDisplay false
+ synchronized(touchedDisplays) {
+ if (awake && hasOwnTouchPanel(size(it), primary?.let(::size), panels)) touchedDisplays += it.displayId
+ it.displayId in touchedDisplays
+ }
+ }
+ }
+
+ private fun internalDisplay(displayManager: DisplayManager, primaryDisplayId: Int, accept: (Display) -> Boolean = { true }): Display? =
displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION).firstOrNull {
it.isValid && it.displayId != primaryDisplayId && (it.flags and Display.FLAG_PRESENTATION) != 0 &&
- isBuiltIn(displayType(it), Build.MODEL)
+ isBuiltIn(displayType(it), Build.MODEL) && accept(it)
}
- fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int): Display? =
- when (SessionPrefs.dualScreenMode(context)) {
- MODE_OFF -> null
- MODE_ON -> builtInDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId)
- else -> builtInDisplay(displayManager, primaryDisplayId)
+ internal fun hasOwnTouchPanel(display: Pair, primary: Pair?, panels: List