>()
if (showResolution) band.add(listOf(Span("RES ", colDim, bandPx), Span(resolutionString(), colValue, bandPx)))
if (displayServer.isNotBlank()) band.add(listOf(Span("DISP ", colDim, bandPx), Span(displayServer, colDisp, bandPx)))
@@ -1407,7 +1236,6 @@ class DroidDeckHudView(context: Context) : View(context) {
y = bBottom; maxRight = max(maxRight, bRight)
}
- // ---- Full-width frametime graph ----
if (showGraph) {
y += sp(3f)
val gh = sp(22f)
@@ -1417,9 +1245,6 @@ class DroidDeckHudView(context: Context) : View(context) {
y += gh
}
- // ---- Stack-layer lines BELOW the frametime graph, subtle (same size/style as the bottom
- // band): the DX-wrapper version first (e.g. "DXVK 2.4.1-…", gated by "DX ver"), then the
- // graphics wrapper beneath it (e.g. "Original", gated by "Wrapper"). ----
val dxLine = dxVersionLabeled()
val hasDx = showDxVer && dxLine.isNotBlank()
if (hasDx) {
@@ -1435,12 +1260,10 @@ class DroidDeckHudView(context: Context) : View(context) {
contentW = maxRight + pad
contentH = y + pad
- addSubtleClock(pad) // subtle time-of-day, consistent with the other sizes
+ addSubtleClock(pad)
}
- // ---- Measure / draw ---------------------------------------------------
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
- // The Strip spans the parent, past the side margin the floating sizes keep.
if (stripRect != null) { setMeasuredDimension(contentW.roundToInt(), resolveSize(contentH.roundToInt(), heightMeasureSpec)); return }
setMeasuredDimension(
resolveSize(contentW.roundToInt(), widthMeasureSpec),
@@ -1460,7 +1283,6 @@ class DroidDeckHudView(context: Context) : View(context) {
drawTabPreview(canvas, blend)
}
- /** The docked tab drawn at its own size in the middle of the view, undoing the view's scale. */
private fun drawTabPreview(canvas: Canvas, blend: Float) {
val (w, h) = dockTabSize()
if (scaleX <= 0f || scaleY <= 0f) return
@@ -1470,8 +1292,8 @@ class DroidDeckHudView(context: Context) : View(context) {
canvas.translate(-w / 2f, -h / 2f)
canvas.saveLayerAlpha(0f, 0f, w, h, (blend * 255f).roundToInt())
drawTab(canvas, RectF(0f, 0f, w, h), previewEdge)
- var x = sp(9f)
- val baseline = sp(7f) + capHeight(sp(20f))
+ var x = sp(TAB_PAD_X_SP)
+ val baseline = sp(TAB_PAD_Y_SP) + capHeight(sp(TAB_NUM_SP))
for (span in tabSpans()) {
drawPaint.textSize = span.sizePx
drawPaint.color = blend(span.color)
@@ -1486,7 +1308,6 @@ class DroidDeckHudView(context: Context) : View(context) {
dPanel?.let { panel -> panelFrame(panel)?.let { canvas.drawBitmap(it, 0f, 0f, null) } }
- // Tile backings
if (tileRects.isNotEmpty()) {
tilePaint.color = Color.argb((14 * bgOpacity).roundToInt().coerceIn(8, 40), 255, 255, 255)
val tr = sp(6f)
@@ -1497,7 +1318,6 @@ class DroidDeckHudView(context: Context) : View(context) {
tabRect?.let { drawTab(canvas, it) }
stripRect?.let { drawStrip(canvas, it) }
- // Text
for (g in glyphs) {
val paint = if (g.sans) wordmarkPaint else drawPaint
paint.textSize = g.sizePx
@@ -1508,14 +1328,11 @@ class DroidDeckHudView(context: Context) : View(context) {
}
headerMark?.let { DroidDeckMark.draw(canvas, it.left, it.top, it.height(), blend(colValue), accent) }
- // Frametime graph
graphRect?.let { drawGraph(canvas, it) }
lockController.drawBadge(canvas)
}
- // MangoHud's frametime graph: the last 200 frames on a fixed 0-50 ms scale, longer frames clipped
- // to 49.9 ms (hud_elements.cpp TransformForward_Custom).
private fun drawGraph(canvas: Canvas, rect: RectF) {
val stats = frames ?: return
stats.graph(graphBuf)
@@ -1527,7 +1344,6 @@ class DroidDeckHudView(context: Context) : View(context) {
if (i == 0) graphPath.moveTo(px, py) else graphPath.lineTo(px, py)
}
if (dPanel != null) {
- // Neon without a blur: a blur would be redrawn with every frame.
graphPaint.strokeWidth = sp(4.5f)
graphPaint.color = withAlpha(blend(colGraph), 56)
canvas.drawPath(graphPath, graphPaint)
@@ -1537,7 +1353,6 @@ class DroidDeckHudView(context: Context) : View(context) {
canvas.drawPath(graphPath, graphPaint)
}
- /** The bar, with the accent line on the side that faces the game (under it at the top, over it at the bottom). */
private fun drawStrip(canvas: Canvas, rect: RectF) {
headerPaint.shader = null
headerPaint.color = panelColor()
@@ -1559,8 +1374,6 @@ class DroidDeckHudView(context: Context) : View(context) {
private fun withAlpha(color: Int, alpha: Int): Int =
Color.argb(alpha, Color.red(color), Color.green(color), Color.blue(color))
- /** The D: straight left side with small corners, round on the right with radius [rad] (a half circle
- * when it is half the height). */
private fun dShape(l: Float, t: Float, r: Float, b: Float, rad: Float, corner: Float): Path {
return Path().apply {
moveTo(l, t + corner)
@@ -1574,7 +1387,6 @@ class DroidDeckHudView(context: Context) : View(context) {
}
}
- /** Where the inside of the outline's round side is at height [y]. */
private fun roundEdgeX(p: RectF, y: Float, stroke: Float): Float {
val r = dRadius - stroke
val cx = p.right - dRadius
@@ -1604,7 +1416,6 @@ class DroidDeckHudView(context: Context) : View(context) {
headerPaint.color = withAlpha(accent, 90)
c.drawRect(panel.left, dDividerTop, roundEdgeX(panel, dDividerTop, stroke), dividerBottom, headerPaint)
}
- // The watermark fills the half circle on the short sizes and sits on the right of the tall ones.
val halfRound = dRadius >= panel.height() / 2f - 0.5f
val wmH = if (halfRound) panel.height() * 0.92f else min(panel.height(), panel.width()) * 0.55f
DroidDeckMark.draw(c, panel.right - DroidDeckMark.widthFor(wmH) - (if (halfRound) panel.height() * 0.02f else sp(10f)),
@@ -1615,7 +1426,6 @@ class DroidDeckHudView(context: Context) : View(context) {
val outline = dShape(panel.left + h, panel.top + h, panel.right - h, panel.bottom - h, dRadius - h, corner)
val blur = BlurMaskFilter((sp(3.2f) - 0.5f).coerceAtLeast(0.5f) / 0.57735f, BlurMaskFilter.Blur.NORMAL)
glowPaint.strokeWidth = stroke
- // Two blurred passes under the sharp one, as the 4-in-1 preview's neon.
for (pass in 0..2) {
glowPaint.maskFilter = if (pass < 2) blur else null
glowPaint.style = Paint.Style.STROKE; glowPaint.color = outlineColor()
@@ -1656,10 +1466,8 @@ class DroidDeckHudView(context: Context) : View(context) {
DroidDeckMark.draw(canvas, rect.centerX() - markW / 2f, rect.centerY() - markH / 2f, markH, blend(colValue), accent)
}
- /** Screen point → whether an on-screen control under the HUD takes a touch there. */
internal var passesTouchAt: ((rawX: Float, rawY: Float) -> Boolean)? = null
- // Declining the down event hands the whole gesture to the views under the HUD.
override fun onTouchEvent(event: MotionEvent): Boolean {
if (dock != DroidDeckHudDock.NONE) return onTabTouch(event)
if (event.actionMasked == MotionEvent.ACTION_DOWN && lockController.isLocked() &&
@@ -1675,6 +1483,10 @@ class DroidDeckHudView(context: Context) : View(context) {
internal val isDragging: Boolean get() = lockController.isDragging() || tabDragging
private companion object {
+ const val TAB_NUM_SP = 15f
+ const val TAB_LABEL_SP = 7.25f
+ const val TAB_PAD_X_SP = 7f
+ const val TAB_PAD_Y_SP = 5.5f
const val REFRESH_MS = 500L
private const val HUE_IDLE_MS = 500L
const val MIN_SCALE = 0.5f
diff --git a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckMark.kt b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckMark.kt
index dd21683f0e..621f6dc1fb 100644
--- a/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckMark.kt
+++ b/app/src/main/java/com/droiddeck/launcher/hud/DroidDeckMark.kt
@@ -5,7 +5,6 @@ import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.Path
-/** artwork/droiddeck-mark.svg: the split D with its circular cut-out and the blue orb. */
internal object DroidDeckMark {
private const val VIEW_X = -55.98f
const val VIEW_W = 239.92f
@@ -36,7 +35,6 @@ internal object DroidDeckMark {
fun widthFor(height: Float): Float = height * VIEW_W / VIEW_H
- /** Where the drawn mark starts and ends inside [widthFor]: the artwork has empty space on both sides. */
fun inkLeftFor(height: Float): Float = (-31.98f - VIEW_X) * height / VIEW_H
fun inkRightFor(height: Float): Float = (175.93f - VIEW_X) * height / VIEW_H
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 adf3e067e5..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 DroidDeck HUD's own readouts.
- */
internal class FrameStats {
private val graph = FloatArray(GRAPH_FRAMES)
private var graphHead = 0
@@ -26,14 +19,16 @@ internal class FrameStats {
private var sessionStartNs = 0L
private var sessionFrames = 0L
+ private val slowTimes = LongArray(SLOW_FRAMES)
+ private var slowHead = 0
+ private var slowSize = 0
+
@Volatile var fps = 0f
private set
- /** Completed sampling periods; MangoHud redraws its readouts when one completes. */
@Volatile var fpsUpdates = 0L
private set
- /** Frames added so far; the HUD redraws its graph when this moves. */
@Volatile var count = 0L
private set
@@ -60,6 +55,11 @@ internal class FrameStats {
if (lowsSize < LOWS_FRAMES) lowsSize++
if (sessionStartNs == 0L) sessionStartNs = timeNs - frametimeNs
sessionFrames++
+ if (frametimeNs > SLOW_NS) {
+ slowTimes[slowHead] = timeNs
+ slowHead = (slowHead + 1) % SLOW_FRAMES
+ if (slowSize < SLOW_FRAMES) slowSize++
+ }
}
count++
}
@@ -77,14 +77,14 @@ internal class FrameStats {
cachedLowsNs = 0L
sessionStartNs = 0L
sessionFrames = 0L
+ slowHead = 0
+ slowSize = 0
fps = 0f
count++
}
- /** MangoHud's frame time readout: 1000 / FPS. */
fun frametimeMs(): Float = 1000f / maxOf(fps, 1f)
- /** The graph, oldest first, into [out] (GRAPH_FRAMES long). */
@Synchronized
fun graph(out: FloatArray) {
for (i in 0 until GRAPH_FRAMES) out[i] = graph[(graphHead + i) % GRAPH_FRAMES]
@@ -96,7 +96,6 @@ internal class FrameStats {
@Synchronized
fun graphMaxMs(): Float = graph.max()
- /** Average over the frames this session, from the first frame to [nowNs]'s last frame. */
@Synchronized
fun averageFps(): Float {
if (sessionFrames < 2 || lastPresentNs <= sessionStartNs) return 0f
@@ -106,13 +105,22 @@ internal class FrameStats {
@Synchronized
fun sessionSeconds(nowNs: Long): Float = if (sessionStartNs == 0L) 0f else (nowNs - sessionStartNs) / 1e9f
+ @Synchronized
+ fun slowFrames(nowNs: Long, windowNs: Long): Int {
+ var n = 0
+ for (i in 0 until slowSize) {
+ if (nowNs - slowTimes[(slowHead - 1 - i + SLOW_FRAMES) % SLOW_FRAMES] > windowNs) break
+ n++
+ }
+ return n
+ }
+
class Lows(val low1Fps: Float, val low01Fps: Float, val low001Fps: Float) {
companion object {
val EMPTY = Lows(0f, 0f, 0f)
}
}
- /** FPS at the 99th, 99.9th and 99.99th percentile frame time of the last LOWS_FRAMES frames. */
fun lows(nowNs: Long): Lows {
val copy: LongArray
synchronized(this) {
@@ -141,15 +149,12 @@ internal class FrameStats {
const val FPS_PERIOD_NS = 500_000_000L
const val LOWS_FRAMES = 8192
private const val PAUSE_NS = 1_000_000_000L
+ const val SLOW_NS = 33_333_334L
+ private const val SLOW_FRAMES = 2048
private const val LOWS_RECOMPUTE_NS = 250_000_000L
}
}
-/**
- * Feeds [stats] with the frame times gamescope shares (the ones MangoHud shows). Sessions without the
- * shared file, or where gamescope stopped sending, fall back to the frames DroidDeck's compositor shows,
- * which stop at the screen's refresh rate.
- */
internal class GameFrameFeed(private val file: File, val stats: FrameStats = FrameStats()) {
private var handle = 0L
private var nextOpenNs = 0L
@@ -160,7 +165,7 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
private val info = IntArray(5)
@Volatile private var fromGamescope = false
private var lastCompositorNs = 0L
- @Volatile private var compositorFrames = 0L // written by the compositor thread only
+ @Volatile private var compositorFrames = 0L
private var seenCompositorFrames = 0L
@Volatile var engine = ""
@@ -176,7 +181,8 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
@Volatile var refreshMilliHz = 0
private set
- /** Main thread, once per display frame. True when new frames arrived. */
+ val live: Boolean get() = fromGamescope
+
fun poll(nowNs: Long): Boolean {
val compositorAdded = compositorFrames != seenCompositorFrames
seenCompositorFrames = compositorFrames
@@ -185,7 +191,6 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
nextOpenNs = nowNs + REOPEN_NS
handle = runCatching { HudFrames.nativeOpen(file.path) }.getOrDefault(0L)
if (handle == 0L) return compositorAdded
- // Frames already in the file were written before this reader started.
HudFrames.nativePoll(handle, frametimes, times)
}
val n = HudFrames.nativePoll(handle, frametimes, times)
@@ -199,7 +204,6 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
} else if (lastRingFrameNs != 0L && nowNs - lastRingFrameNs > LIVE_NS) {
fromGamescope = false
}
- // A new session writes the file again from the start; reopen when gamescope has gone quiet.
if (n <= 0 && nowNs - maxOf(lastRingFrameNs, nextOpenNs - REOPEN_NS) > STALE_NS) close()
if (nowNs - lastInfoNs >= INFO_NS) {
lastInfoNs = nowNs
@@ -208,7 +212,6 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
return n > 0 || compositorAdded
}
- /** Compositor thread: one frame shown on the panel. */
fun onCompositorFrame(nowNs: Long) {
if (fromGamescope) {
lastCompositorNs = 0L
@@ -247,8 +250,6 @@ internal class GameFrameFeed(private val file: File, val stats: FrameStats = Fra
private const val STALE_NS = 5_000_000_000L
private const val INFO_NS = 500_000_000L
- /** DroidDeck's mangoapp's names for gamescope's engine field (Valve's 20260902.1 build, app/main.cpp
- * engine_type_from_str and overlay.h engines); gamescope sends "gamescope" when it knows none. */
fun engineLabel(name: String): String = when (name) {
"DXVK" -> "DXVK"
"vkd3d" -> "VKD3D"
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 f739ec8b60..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;
@@ -28,48 +28,18 @@ import android.view.View;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
-/**
- * Shared touch + lock behaviour for every in-game performance HUD (classic FrameRating(+Horizontal),
- * GameHub PerfHudView, GameNative PerformanceHudView, and the DroidDeck HUD). One place so the four
- * overlays can't drift:
- *
- *
- * - tap → {@link Callbacks#onTap()} (orientation-toggle for the first three; size-cycle for
- * the DroidDeck HUD) — a no-op that only re-flashes the lock badge while locked.
- * - 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 DroidDeckHudView} 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 (DroidDeck HUD). */
void onTap();
- /** Drag released (unlocked): persist the new (x, y). */
void onMoved(float x, float y);
- /** The view moved under a drag (unlocked), with the finger at screen point (rawX, rawY). */
default void onDragged(float rawX, float rawY) {}
- /** The drag ended in a fling (unlocked), in pixels per second; comes just before {@link #onMoved}. */
default void onFlung(float velocityX, float velocityY) {}
- /** Lock toggled by long-press: persist {@code hudLocked} + sync the menu chip. */
void onLockChanged(boolean locked);
- /** Two-finger pinch (unlocked): the change since the previous event, above 1 when the fingers spread. */
default void onPinch(float factor) {}
- /** The fingers came off a pinch: persist the new size. */
default void onPinchEnd() {}
}
- // Fade timing (ms): in → hold → out. Lock/unlock hold ~1.5 s; a blocked-gesture re-flash is shorter.
private static final long FADE_IN_MS = 160;
private static final long HOLD_TOGGLE_MS = 1500;
private static final long HOLD_REFLASH_MS = 750;
@@ -83,13 +53,10 @@ public class HudLockController {
private boolean locked = false;
- // Drag state
private float downRawX, downRawY, startX, startY;
private boolean dragging = false;
- // A pinch ends the gesture's drag and tap: the finger left down after it must not move the HUD.
private boolean pinched = false;
- // Fade state
private long fadeStart = 0;
private long holdMs = HOLD_TOGGLE_MS;
private boolean fadeShowLocked = false;
@@ -110,14 +77,12 @@ public class HudLockController {
iconStroke.setStrokeJoin(Paint.Join.ROUND);
}
- /** Set lock state from config (applyConfig) WITHOUT firing the persist callback. */
public void setLocked(boolean locked) { this.locked = locked; }
public boolean isLocked() { return locked; }
public boolean isDragging() { return dragging; }
- /** Feed from the host view's onTouchEvent. Always consumes (mirrors the legacy manual handlers). */
public boolean onTouchEvent(MotionEvent event) {
scaleDetector.onTouchEvent(event);
detector.onTouchEvent(event);
@@ -143,7 +108,6 @@ public class HudLockController {
@Override
public void onLongPress(MotionEvent e) {
- // Long-press always toggles — this is the only gesture that still works while locked.
locked = !locked;
cb.onLockChanged(locked);
flash(locked, HOLD_TOGGLE_MS);
@@ -153,7 +117,7 @@ public class HudLockController {
public boolean onSingleTapUp(MotionEvent e) {
if (pinched) return true;
if (locked) {
- flash(true, HOLD_REFLASH_MS); // intentionally locked — remind the user
+ flash(true, HOLD_REFLASH_MS);
} else {
cb.onTap();
}
@@ -171,7 +135,7 @@ public class HudLockController {
if (pinched) return true;
if (locked) {
if (!dragging) flash(true, HOLD_REFLASH_MS);
- dragging = true; // mark so the blocked drag doesn't fall through to a tap
+ dragging = true;
return true;
}
view.setX(startX + (e2.getRawX() - downRawX));
@@ -203,7 +167,6 @@ public class HudLockController {
}
}
- // ---- Fade badge -------------------------------------------------------
private void flash(boolean showLocked, long hold) {
fadeShowLocked = showLocked;
holdMs = hold;
@@ -236,14 +199,6 @@ public class HudLockController {
return Color.argb(Math.round(255 * a), Color.red(color), Color.green(color), Color.blue(color));
}
- /**
- * Draw the padlock badge in the top-right of the panel if a fade is in progress. Call from the
- * host's onDraw (plain View) or dispatchDraw (ViewGroup), after the content.
- *
- *
No background box: the glyph is drawn twice — a slightly expanded, thicker semi-transparent
- * black "halo" pass for legibility on any game frame, then the white glyph on top — so it reads as
- * a floating icon, not an opaque tile.
- */
public void drawBadge(Canvas canvas) {
float a = currentAlpha();
if (a <= 0f) return;
@@ -262,14 +217,12 @@ public class HudLockController {
float r = size * 0.2f;
float shackleTop = top + size * 0.08f;
- // Pass 1: dark halo (expanded body, thicker shackle) for contrast; Pass 2: white glyph.
drawLock(canvas, cx, bodyTop, bodyLeft, bodyRight, bottom, r, shackleTop, d,
Color.argb(Math.round(150 * a), 0, 0, 0), 3.0f * d, 0.9f * d, false);
drawLock(canvas, cx, bodyTop, bodyLeft, bodyRight, bottom, r, shackleTop, d,
withAlpha(0xFFFFFFFF, a), 1.7f * d, 0f, true);
}
- /** One padlock pass. {@code halo} inflates the body/shackle in dark; the white pass punches the keyhole. */
private void drawLock(Canvas canvas, float cx, float bodyTop, float bodyLeft, float bodyRight,
float bottom, float r, float shackleTop, float d,
int color, float strokeW, float expand, boolean punchKeyhole) {
@@ -277,7 +230,6 @@ public class HudLockController {
iconStroke.setColor(color);
iconStroke.setStrokeWidth(strokeW);
- // Body
canvas.drawRoundRect(bodyLeft - expand, bodyTop - expand, bodyRight + expand, bottom + expand,
2.4f * d, 2.4f * d, iconFill);
if (punchKeyhole) {
@@ -289,19 +241,16 @@ public class HudLockController {
RectF arc = new RectF(cx - r, shackleTop, cx + r, shackleTop + 2f * r);
if (fadeShowLocked) {
- // Closed: both legs run straight down into the body.
Path p = new Path();
p.addArc(arc, 180f, 180f);
p.moveTo(cx - r, shackleTop + r); p.lineTo(cx - r, bodyTop);
p.moveTo(cx + r, shackleTop + r); p.lineTo(cx + r, bodyTop);
canvas.drawPath(p, iconStroke);
} else {
- // Open, clearly to the LEFT: the RIGHT leg stays seated in the body; the arc + LEFT leg
- // hinge up-and-left off the right attachment so the left leg lifts well clear of the body.
- canvas.drawLine(cx + r, shackleTop + r, cx + r, bodyTop, iconStroke); // fixed right leg
+ canvas.drawLine(cx + r, shackleTop + r, cx + r, bodyTop, iconStroke);
Path p = new Path();
p.addArc(arc, 180f, 180f);
- p.moveTo(cx - r, shackleTop + r); p.lineTo(cx - r, bodyTop); // full-length left leg
+ p.moveTo(cx - r, shackleTop + r); p.lineTo(cx - r, bodyTop);
canvas.save();
canvas.rotate(-42f, cx + r, shackleTop + r);
canvas.drawPath(p, iconStroke);
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 a98aa85355..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 DroidDeck HUD draws. Collected in one pass by
- * {@link #snapshot()} so the view never touches sysfs / BatteryManager during draw (the user's
- * explicit ask: one collection pass, cached, so gameplay isn't strained). All numeric fields are
- * raw (nullable when unreadable); the view formats + colours them.
- */
public static final class Snapshot {
- public final Integer cpuPercent; // 0..100 or null
- public final Integer gpuPercent; // 0..100 or null
- public final Integer cpuClockMhz; // MHz or null
- public final Integer gpuClockMhz; // MHz or null
- public final Integer cpuTempC; // °C or null
- public final Integer gpuTempC; // °C or null
+ public final Integer cpuPercent;
+ public final Integer gpuPercent;
+ public final Integer cpuClockMhz;
+ public final Integer gpuClockMhz;
+ public final Integer cpuTempC;
+ public final Integer gpuTempC;
public final long ramUsedBytes;
public final long ramTotalBytes;
- public final float ramPercent; // 0..100
- public final Long vramUsedBytes; // bytes or null
- public final Battery battery; // never null
- // ---- Mega-only extras ----
- public final int[] perCorePercent; // per-core 0..100, -1 unknown (never null; may be empty)
- public final int[] perCoreClockMhz; // per-core MHz, 0 unknown (never null; may be empty)
- public final Long swapUsedBytes; // bytes or null (no swap)
- public final Long swapTotalBytes; // bytes or null
- public final Long netDownBps; // bytes/sec down, or null (first sample / unreadable)
- public final Long netUpBps; // bytes/sec up, or null
+ public final float ramPercent;
+ public final Long vramUsedBytes;
+ public final Battery battery;
+ public final int[] perCorePercent;
+ public final int[] perCoreClockMhz;
+ public final Long swapUsedBytes;
+ public final Long swapTotalBytes;
+ public final Long netDownBps;
+ public final Long netUpBps;
Snapshot(Integer cpuPercent, Integer gpuPercent, Integer cpuClockMhz, Integer gpuClockMhz,
Integer cpuTempC, Integer gpuTempC, long ramUsedBytes, long ramTotalBytes,
@@ -1066,7 +805,6 @@ public class HudMetrics {
}
}
- /** One collection pass over every metric. Call from the HUD's own ~1 s refresh thread, never draw. */
public Snapshot snapshot() {
if (mango != null) return mangoSnapshot(mango);
Integer cpu = getCpuUsagePercent();
@@ -1102,7 +840,6 @@ public class HudMetrics {
net == null ? null : net[0], net == null ? null : net[1]);
}
- // DroidDeck: the same snapshot with MangoHud's sources and rounding (see MangoReadings).
private Snapshot mangoSnapshot(MangoReadings m) {
MangoReadings.Cpu cpu = m.cpu();
MangoReadings.Memory mem = m.memory();
@@ -1121,11 +858,6 @@ public class HudMetrics {
net == null ? null : net[0], net == null ? null : net[1]);
}
- // =======================================================================
- // Mega-view extras: per-core CPU, swap, network (best-effort, nullable)
- // =======================================================================
-
- /** Per-core clock in MHz (each core's {@code scaling_cur_freq}); 0 for a core that can't be read. */
public int[] getPerCoreClockMhz() {
int cores = Runtime.getRuntime().availableProcessors();
int[] out = new int[Math.max(0, cores)];
@@ -1136,11 +868,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,20 +982,8 @@ public class HudMetrics {
return new long[]{down, up};
}
- // =======================================================================
- // Diagnostics report (invoked ONLY on user tap — never on the HUD refresh path)
- // =======================================================================
-
- /**
- * One-tap plain-text device report for the "Export HUD diagnostics" action: for every metric it
- * lists the resolved source path/API + current value, or MISS + the exact candidates it tried,
- * followed by an "exists on this device" dump (thermal zone types, devfreq/kgsl/mali nodes) so a
- * device owner can send back the real path for anything that missed. Does a short prime+sample so
- * delta-based readers (CPU%/GPU%/net) report a live value. Run OFF the main thread.
- */
public String buildDiagnosticsReport(Context ctxIn) {
final Context ctx = ctxIn != null ? ctxIn : this.context;
- // Prime the delta-based readers, wait, then take a live sample.
snapshot();
try { Thread.sleep(350L); } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); }
Snapshot s = snapshot();
@@ -1281,7 +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..ade7aa6563 100644
--- a/app/src/main/java/com/droiddeck/launcher/hud/MangoReadings.kt
+++ b/app/src/main/java/com/droiddeck/launcher/hud/MangoReadings.kt
@@ -3,12 +3,6 @@ package com.droiddeck.launcher.hud
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
-/**
- * The readings Steam's performance overlay shows in a DroidDeck session (Valve's mangohud 20260902.1,
- * tools/mangoapp), taken from the files the session hands it and computed the same way, so the two
- * overlays agree. Sources and formulas follow that build: cpu.cpp calculateCPUData, deckard_temp.cpp,
- * msm.cpp getQcomGpuInfo, memory.cpp update_meminfo and battery.cpp getPercent / getPower.
- */
internal class MangoReadings(private val sessionDir: File, private val rootDir: File) {
class Cpu(val percent: Int, val perCore: IntArray)
class Memory(val usedBytes: Long, val totalBytes: Long, val swapUsedBytes: Long, val swapTotalBytes: Long)
@@ -17,7 +11,6 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
private val cpuTimes = HashMap()
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 +31,6 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
File(sessionDir, "proc-stat").takeIf { !File("/proc/stat").canRead() && it.isFile } ?: File("/proc/stat")
private fun cpuPercent(key: String, v: LongArray): Int {
- // user nice system idle iowait irq softirq steal guest guest_nice; guest time is already in user.
val user = v[0] - v[8]
val nice = v[1] - v[9]
val systemAll = v[2] + v[5] + v[6]
@@ -55,7 +47,6 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
return busy.coerceIn(0f, 100f).toInt().also { cpuPercents[key] = it }
}
- /** Average of the zones the session types cpuN-thermal, truncated. */
fun cpuTempC(): Int? {
var sum = 0f
var count = 0
@@ -85,7 +76,6 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
return (milli / 1000.0).toInt()
}
- /** MemTotal - MemAvailable and SwapTotal - SwapFree from /proc/meminfo. */
fun memory(): Memory? {
val kb = HashMap()
runCatching {
@@ -102,10 +92,8 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
return Memory((total - available) * 1024, total * 1024, (swapTotal - swapFree) * 1024, swapTotal * 1024)
}
- /** The KGSL total DroidDeck shares with the session (GpuMemComponent). */
fun vramBytes(): Long? = fresh(File(rootDir, VRAM_FILE), VRAM_FRESH_MS)?.let(::readLong)
- /** BAT* under the session's power_supply (BatteryComponent): no watts while charging, full or unknown. */
fun battery(): Battery? {
val dirs = File(sessionDir, "sys/power_supply").listFiles { f -> f.name.contains("BAT") }?.sortedBy { it.name }
if (dirs.isNullOrEmpty()) return null
@@ -149,7 +137,6 @@ internal class MangoReadings(private val sessionDir: File, private val rootDir:
private fun readLong(file: File): Long? = runCatching { file.readText().trim().toLong() }.getOrNull()
private fun readFloat(file: File): Float? = runCatching { file.readLines().first().trim().toFloat() }.getOrNull()
- /** std::stod on the first line: the leading number, "6 %" -> 6. */
fun leadingNumber(file: File): Double? = runCatching {
Regex("^\\s*-?\\d+(\\.\\d+)?").find(file.readLines().first())?.value?.trim()?.toDouble()
}.getOrNull()
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/DualScreen.kt b/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt
index e8d7fd71e2..cfd37c95c5 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt
+++ b/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt
@@ -18,6 +18,23 @@ object DualScreen {
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 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)
@@ -61,20 +78,25 @@ object DualScreen {
(x.max - x.min + 1f).roundToInt() to (y.max - y.min + 1f).roundToInt()
}
- fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int): Display? =
- when (SessionPrefs.dualScreenMode(context)) {
+ fun sessionDisplay(context: Context, displayManager: DisplayManager, primaryDisplayId: Int): Display? =
+ display(context, displayManager, primaryDisplayId, SessionPrefs.dualScreenSessionMode(context))
+
+ fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int, mode: String = SessionPrefs.dualScreenMode(context)): Display? =
+ when (mode) {
MODE_OFF -> null
MODE_ON -> internalDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId)
else -> builtInDisplay(displayManager, primaryDisplayId)
- }
+ }?.takeUnless { taken(it.displayId) }
fun anyDisplay(displayManager: DisplayManager, primaryDisplayId: Int): Display? =
displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION).firstOrNull {
it.isValid && it.displayId != primaryDisplayId && (it.flags and Display.FLAG_PRESENTATION) != 0
}
+ fun builtIn(display: Display): Boolean = isBuiltIn(displayType(display), Build.MODEL)
+
internal fun isBuiltIn(type: Int?, model: String): Boolean =
- if (type != null) type == TYPE_INTERNAL else model.trim().lowercase() in knownModels
+ if (type != null) type == TYPE_INTERNAL else yieldsBottom(model)
private fun displayType(display: Display): Int? =
runCatching { Display::class.java.getMethod("getType").invoke(display) as Int }.getOrNull()
diff --git a/app/src/main/java/com/droiddeck/launcher/input/FakeInputWriter.java b/app/src/main/java/com/droiddeck/launcher/input/FakeInputWriter.java
index 46ce997984..8cbe135e7a 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/FakeInputWriter.java
+++ b/app/src/main/java/com/droiddeck/launcher/input/FakeInputWriter.java
@@ -612,7 +612,6 @@ public class FakeInputWriter {
for (int i = 0; i < length; i++) output[9 + i] = ring.get(TRITON_OUTPUT_OFFSET + i);
nativeStoreFence();
if (seq != ring.getLong(TRITON_OUTPUT_SEQ_OFFSET)) return null;
- // Acknowledge the exact report sequence taken so a concurrent timeout overwrite cannot lose its length.
ring.putInt(TRITON_OUTPUT_ACK_OFFSET, (int) seq);
nativeStoreFence();
return output;
diff --git a/app/src/main/java/com/droiddeck/launcher/input/GesturePrefs.kt b/app/src/main/java/com/droiddeck/launcher/input/GesturePrefs.kt
index b8be5bf542..55588d6fd4 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/GesturePrefs.kt
+++ b/app/src/main/java/com/droiddeck/launcher/input/GesturePrefs.kt
@@ -2,7 +2,6 @@ package com.droiddeck.launcher.input
import android.content.Context
-/** Global defaults with optional overrides for the currently focused game. */
object GesturePrefs {
private fun prefs(context: Context) = context.getSharedPreferences("touch_gestures", Context.MODE_PRIVATE)
diff --git a/app/src/main/java/com/droiddeck/launcher/input/GestureTouchStreamGate.kt b/app/src/main/java/com/droiddeck/launcher/input/GestureTouchStreamGate.kt
index 68d5722d0a..4d69f68c5b 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/GestureTouchStreamGate.kt
+++ b/app/src/main/java/com/droiddeck/launcher/input/GestureTouchStreamGate.kt
@@ -2,7 +2,6 @@ package com.droiddeck.launcher.input
import android.view.MotionEvent
-/** Keeps split Android touch targets from restarting one shared gesture recognizer. */
internal class GestureTouchStreamGate {
enum class Source { SURFACE, SCREEN_KEYS, ON_SCREEN_CONTROLS }
diff --git a/app/src/main/java/com/droiddeck/launcher/input/GuestKeys.kt b/app/src/main/java/com/droiddeck/launcher/input/GuestKeys.kt
new file mode 100644
index 0000000000..fbc3739cd9
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/input/GuestKeys.kt
@@ -0,0 +1,31 @@
+package com.droiddeck.launcher.input
+
+import android.view.KeyEvent
+
+object GuestKeys {
+ /** Sends [event] as evdev presses, with Shift around characters typed by a keyboard that has no Shift key; false when it has no evdev code. */
+ fun send(event: KeyEvent, sendKey: (code: Int, down: Boolean) -> Unit): Boolean {
+ val down = event.action == KeyEvent.ACTION_DOWN
+ if (!down && event.action != KeyEvent.ACTION_UP) return false
+ var evdev = EvdevKeys.fromKeyCode(event.keyCode)
+ val ch = event.unicodeChar
+ val plain = if (ch > 0) EvdevKeys.unshiftedChar(ch) else 0
+ if (evdev <= 0 && ch > 0) {
+ val code = EvdevKeys.fromKeyCode(EvdevKeys.keycodeForChar(if (plain != 0) plain else ch))
+ if (code > 0) evdev = code
+ }
+ val shiftEvdev = if (evdev > 0 && plain != 0 && event.deviceId <= 0) KEY_LEFTSHIFT else 0
+ if (evdev <= 0 && event.scanCode > 0) evdev = event.scanCode
+ if (evdev <= 0) return false
+ if (down) {
+ if (shiftEvdev != 0) sendKey(shiftEvdev, true)
+ sendKey(evdev, true)
+ } else {
+ sendKey(evdev, false)
+ if (shiftEvdev != 0) sendKey(shiftEvdev, false)
+ }
+ return true
+ }
+
+ private const val KEY_LEFTSHIFT = 42
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/HomeButtonService.kt b/app/src/main/java/com/droiddeck/launcher/input/HomeButtonService.kt
index 21ca4717d2..f9d9d34f4d 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/HomeButtonService.kt
+++ b/app/src/main/java/com/droiddeck/launcher/input/HomeButtonService.kt
@@ -37,7 +37,6 @@ object HomeButtonShortcuts {
}
fun onKeyEvent(context: Context, event: KeyEvent): Boolean {
- // AYN maps its system-assistant key (gpio-keys KEY_F24) to HOME too; only the pad's Home is Guide.
if (!HomeGuideInput.isHome(event.keyCode) || !PadBridge.isControllerKeyEvent(event)) return false
return input.onKeyEvent(event, enabled() && HomeApp.isDefault(context))
}
@@ -47,12 +46,20 @@ object HomeButtonShortcuts {
}
class HomeButtonService : AccessibilityService(), InputManager.InputDeviceListener {
+ private var bottomScreen: BottomScreenWatch? = null
+
override fun onServiceConnected() {
getSystemService(InputManager::class.java).registerInputDeviceListener(this, Handler(Looper.getMainLooper()))
+ if (bottomScreen == null && BottomScreenGuests.supported()) bottomScreen = BottomScreenWatch(this).also { it.start() }
+ }
+
+ private fun stopBottomScreen() {
+ bottomScreen?.stop()
+ bottomScreen = null
}
override fun onKeyEvent(event: KeyEvent) = HomeButtonShortcuts.onKeyEvent(this, event)
- override fun onAccessibilityEvent(event: AccessibilityEvent?) {}
+ override fun onAccessibilityEvent(event: AccessibilityEvent?) { event?.let { bottomScreen?.onEvent(it) } }
override fun onInterrupt() { HomeButtonShortcuts.release() }
override fun onInputDeviceAdded(deviceId: Int) {}
override fun onInputDeviceChanged(deviceId: Int) {}
@@ -60,12 +67,14 @@ class HomeButtonService : AccessibilityService(), InputManager.InputDeviceListen
override fun onUnbind(intent: Intent?): Boolean {
HomeButtonShortcuts.release()
+ stopBottomScreen()
com.droiddeck.launcher.core.SteamIntegration.syncShortcutsListing(this)
return super.onUnbind(intent)
}
override fun onDestroy() {
HomeButtonShortcuts.release()
+ stopBottomScreen()
getSystemService(InputManager::class.java).unregisterInputDeviceListener(this)
super.onDestroy()
}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/HomeGuideInput.kt b/app/src/main/java/com/droiddeck/launcher/input/HomeGuideInput.kt
index fd289f7347..e4d7120447 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/HomeGuideInput.kt
+++ b/app/src/main/java/com/droiddeck/launcher/input/HomeGuideInput.kt
@@ -46,7 +46,6 @@ class HomeGuideInput(private val setPressed: (Boolean) -> Unit, private val onCa
}
companion object {
- // The Retroid Nova pad falls back to Generic.kl, which maps its Home scan code to MOVE_HOME.
fun isHome(keyCode: Int) = keyCode == KeyEvent.KEYCODE_HOME || keyCode == KeyEvent.KEYCODE_MOVE_HOME
private const val DUO_QUICK_MENU_SCAN_CODE = 194
diff --git a/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt b/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt
index b7fced7106..8f546e8b07 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt
+++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt
@@ -672,7 +672,6 @@ class OnScreenControls(
private fun closestSnap(position: Float, targets: List): Float? =
targets.minByOrNull { abs(position - it) }?.takeIf { abs(position - it) <= dp(SNAP_DP) }
- /** Whether a finger going down at ([x], [y]) lands on something here, as [onTouchEvent] decides it. */
fun takesTouchAt(x: Float, y: Float): Boolean =
editing || keyboardContains(x, y) || (!buttonsOnly && quickContains(x, y)) ||
(!quickHidden && (controlAt(x, y) ?: adaptiveStickAt(x, y)) != null)
diff --git a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java
index 7dd234daf1..edb95fbe6e 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java
+++ b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java
@@ -250,11 +250,6 @@ public final class PadBridge {
|| device.supportsSource(InputDevice.SOURCE_JOYSTICK));
}
- public static boolean isControllerKey(KeyEvent event) {
- return isFromController(event.getDevice())
- && isPadKey(event.getKeyCode(), event.getDevice().getKeyboardType());
- }
-
public static boolean isPadKey(int keyCode, int keyboardType) {
if ((keyCode >= KeyEvent.KEYCODE_BUTTON_A && keyCode <= KeyEvent.KEYCODE_BUTTON_MODE)
|| (keyCode >= KeyEvent.KEYCODE_BUTTON_1 && keyCode <= KeyEvent.KEYCODE_BUTTON_16)) return true;
@@ -616,7 +611,6 @@ public final class PadBridge {
private void writePad(PadState report) {
if (backQamAxesBlocked && !hasAxes(state)) backQamAxesBlocked = false;
long at = android.os.SystemClock.uptimeMillis();
- // Steam must see the modifier before a partner; preserve quick press/release pairs in order.
if (backQamPressed || homeGuidePressed || !backQamWrites.isEmpty()) at += backQamDelayMs;
writeBackQamReport(report, at);
}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/ScreenKey.kt b/app/src/main/java/com/droiddeck/launcher/input/ScreenKey.kt
index 2967a06f6a..4223754320 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/ScreenKey.kt
+++ b/app/src/main/java/com/droiddeck/launcher/input/ScreenKey.kt
@@ -36,12 +36,6 @@ fun screenKeyDirections(shape: Int): List = when (shape) {
else -> emptyList()
}
-val SCREEN_KEY_SHAPES =
- listOf(
- SCREEN_KEY_PILL, SCREEN_KEY_ROUND, SCREEN_KEY_CIRCLE, SCREEN_KEY_RECT,
- SCREEN_KEY_TRIGGER, SCREEN_KEY_DPAD, SCREEN_KEY_STICK,
- )
-
data class ScreenKey(
val codes: List,
val x: Float,
@@ -55,9 +49,4 @@ data class ScreenKey(
val toggle: Boolean = false,
val labels: Boolean = true,
) {
- fun shownLabel(context: Context): String = when {
- text.isNotEmpty() -> text
- glyph.isNotEmpty() -> glyph
- else -> screenKeyLabel(context, codes)
- }
}
diff --git a/app/src/main/java/com/droiddeck/launcher/input/ScreenKeys.kt b/app/src/main/java/com/droiddeck/launcher/input/ScreenKeys.kt
index df129888c8..be1f658f34 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/ScreenKeys.kt
+++ b/app/src/main/java/com/droiddeck/launcher/input/ScreenKeys.kt
@@ -609,7 +609,6 @@ class ScreenKeys(context: Context, private val sendKey: (Int, Boolean) -> Unit)
else -> entry.halfH
}
- /** Whether a finger going down at ([x], [y]) lands on something here, as [onTouchEvent] decides it. */
fun takesTouchAt(x: Float, y: Float): Boolean = editing || entryAt(x, y) != null
private fun entryAt(x: Float, y: Float): Entry? = entries.lastOrNull { entry ->
diff --git a/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt b/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt
index f030565ff5..0f18132efc 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt
+++ b/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt
@@ -10,14 +10,15 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int) {
KEYBOARD_TRACKPAD("keyboard-trackpad", R.string.second_mode_keyboard_trackpad),
TERMINAL("terminal", R.string.second_mode_terminal),
DECK_CONTROLS("deck-controls", R.string.second_mode_deck_controls),
- DASHBOARD("dashboard", R.string.second_mode_dashboard);
+ DASHBOARD("dashboard", R.string.second_mode_dashboard),
+ DESKTOP("desktop", R.string.second_mode_desktop);
companion object {
- fun opening(remembered: String?, deckPad: Boolean, dashboard: Boolean = false): SecondScreenMode {
+ fun opening(remembered: String?, deckPad: Boolean, dashboard: Boolean = false, desktop: Boolean = false): SecondScreenMode {
entries.firstOrNull {
- it != NONE && it.id == remembered && (it != DECK_CONTROLS || deckPad) && (it != DASHBOARD || dashboard)
+ it != NONE && it.id == remembered && (it != DECK_CONTROLS || deckPad) && (it != DASHBOARD || dashboard) &&
+ (it != DESKTOP || desktop)
}?.let { return it }
- // No pick yet: the dashboard. A pick that can't open right now keeps the old fallback.
val picked = entries.any { it != NONE && it.id == remembered }
return when {
dashboard && !picked -> DASHBOARD
diff --git a/app/src/main/java/com/droiddeck/launcher/input/SteamTouchControls.kt b/app/src/main/java/com/droiddeck/launcher/input/SteamTouchControls.kt
index 68eed5edea..672cf9b470 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/SteamTouchControls.kt
+++ b/app/src/main/java/com/droiddeck/launcher/input/SteamTouchControls.kt
@@ -112,7 +112,6 @@ class SteamTouchControls(
private var selected = -1
private var dragOffset = 0f to 0f
private var pinchStart = 0f
- private var pinchScale = 1f
private var saving = false
private val pendingBindings = HashMap()
private var pendingColor: FloatArray? = null
@@ -244,7 +243,6 @@ class SteamTouchControls(
private fun hit(list: List, x: Float, y: Float): Element? =
list.filter { reach(it, x, y) <= 1.15f }.minByOrNull { reach(it, x, y) }
- /** Whether a finger going down at ([x], [y]) lands on something here, as [onTouchEvent] decides it. */
fun takesTouchAt(x: Float, y: Float): Boolean = editing || menuOpen || hit(live(), x, y) != null
private fun live(): List =
@@ -350,17 +348,6 @@ class SteamTouchControls(
canvas.restore()
}
- private fun drawSteamMark(canvas: Canvas, x: Float, y: Float, r: Float, color: Int) {
- val p = Paint(Paint.ANTI_ALIAS_FLAG).apply { this.color = color; style = Paint.Style.STROKE; strokeCap = Paint.Cap.ROUND }
- p.strokeWidth = r * 0.16f
- canvas.drawCircle(x + r * 0.28f, y - r * 0.18f, r * 0.27f, p)
- canvas.drawCircle(x + r * 0.28f, y - r * 0.18f, r * 0.1f, Paint(p).apply { style = Paint.Style.FILL })
- canvas.drawCircle(x - r * 0.3f, y + r * 0.3f, r * 0.17f, p)
- p.strokeWidth = r * 0.2f
- canvas.drawLine(x + r * 0.1f, y - r * 0.02f, x - r * 0.2f, y + r * 0.22f, p)
- canvas.drawLine(x - r * 0.45f, y + r * 0.28f, x - r * 0.95f, y + r * 0.1f, p)
- }
-
private fun drawFace(canvas: Canvas, type: Int, binding: SteamTouchBindings.Binding?, x: Float, y: Float, r: Float,
alpha: Int, pressed: Boolean) {
val square = isSquare(type)
@@ -855,19 +842,6 @@ class SteamTouchControls(
invalidate()
}
- private fun controlName(type: Int) = when (type) {
- SteamTouchConfig.DPAD -> context.getString(R.string.touch_dpad)
- SteamTouchConfig.JOYSTICK_LEFT -> context.getString(R.string.touch_left_stick)
- SteamTouchConfig.JOYSTICK_RIGHT -> context.getString(R.string.touch_right_stick)
- SteamTouchConfig.TRACKPAD_LEFT -> context.getString(R.string.deck_left_trackpad)
- SteamTouchConfig.TRACKPAD_RIGHT -> context.getString(R.string.deck_right_trackpad)
- SteamTouchConfig.TRACKPAD_CENTER -> context.getString(R.string.deck_surface_trackpad)
- SteamTouchConfig.STEAM -> "Steam"
- SteamTouchConfig.THUMB -> context.getString(R.string.touch_menu)
- SteamTouchConfig.KEYBOARD -> context.getString(R.string.touch_keyboard)
- else -> label(type)
- }
-
private fun moreMenu() {
val host = parent as? android.view.ViewGroup ?: return
val density = resources.displayMetrics.density
diff --git a/app/src/main/java/com/droiddeck/launcher/input/SteamTouchDevice.kt b/app/src/main/java/com/droiddeck/launcher/input/SteamTouchDevice.kt
index 2d63358d3d..560bff4f06 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/SteamTouchDevice.kt
+++ b/app/src/main/java/com/droiddeck/launcher/input/SteamTouchDevice.kt
@@ -74,8 +74,6 @@ class SteamTouchDevice private constructor(private val buffer: ByteBuffer) {
Log.i(TAG, "steam touch: " + if (value) "plugged in" else "unplugged")
}
- fun setBattery(percent: Int) = buffer.putInt(OFF_BATTERY, percent.coerceIn(0, 100))
-
fun state(): State {
repeat(8) {
val seq = buffer.getLong(OFF_STATE_SEQ)
diff --git a/app/src/main/java/com/droiddeck/launcher/input/SteamVolumeKeys.kt b/app/src/main/java/com/droiddeck/launcher/input/SteamVolumeKeys.kt
index 3e0ca925aa..062bfbfdc4 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/SteamVolumeKeys.kt
+++ b/app/src/main/java/com/droiddeck/launcher/input/SteamVolumeKeys.kt
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.input
import android.media.AudioManager
import android.view.KeyEvent
-/** Use Steam's PulseAudio bridge for feedback instead of requesting Android's volume UI. */
internal object SteamVolumeKeys {
fun dispatch(event: KeyEvent, enabled: Boolean, adjust: (Int) -> Unit): Boolean {
val direction = when (event.keyCode) {
diff --git a/app/src/main/java/com/droiddeck/launcher/input/TouchscreenGestures.java b/app/src/main/java/com/droiddeck/launcher/input/TouchscreenGestures.java
index 140b4ace41..819226764b 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/TouchscreenGestures.java
+++ b/app/src/main/java/com/droiddeck/launcher/input/TouchscreenGestures.java
@@ -28,7 +28,6 @@ public final class TouchscreenGestures {
void key(int code, boolean down);
void wheel(int steps);
void showKeyboard();
- /** Establish the pointer origin before a relative middle-mouse pan begins. */
default void prepareRelativePan() {}
default void gesture(Gesture gesture) {}
}
@@ -97,12 +96,10 @@ public final class TouchscreenGestures {
final int code;
MouseButton(int code) { this.code = code; }
}
- // Long-press detection
private Runnable longPressRunnable;
private boolean longPressTriggered;
private boolean longPressActionHeld, twoFingerHoldActionHeld, threeFingerHoldActionHeld;
- // Double-tap detection
private long lastTapTime;
private float lastTapX;
private float lastTapY;
@@ -110,76 +107,54 @@ public final class TouchscreenGestures {
private float doubleTapAnchorX, doubleTapAnchorY;
private long singleFingerDownTime;
- // Drag tracking (box selection)
private boolean isDragging;
private boolean dragButtonPressed;
- // Two-finger tracking
private boolean twoFingerDragging;
private float twoFingerLastX0, twoFingerLastY0;
private float twoFingerLastX1, twoFingerLastY1;
private boolean twoFingerMiddleButtonDown;
- // Pinch tracking
private float pinchLastDistance;
private float pinchZoomRemainder;
private float keyPanRemainderX, keyPanRemainderY;
private static final float PINCH_STEP_PX = 10f;
- // Two-finger tap detection
private boolean twoFingerTapPossible;
private boolean twoFingerTapFired;
- // Track which WASD/arrow keys are currently held
private boolean panKeyUp, panKeyDown, panKeyLeft, panKeyRight;
- // True when finger has moved beyond tap tolerance (prevents spurious tap on lift)
private boolean movedBeyondTapThreshold;
- // True after a multi-finger gesture has been active — prevents the remaining
- // finger from starting a spurious single-finger drag on lift sequence.
private boolean multiFingerGestureUsed;
- // Remember which keycodes were actually pressed so releasePanKeys releases only those
private Integer panLeftKey, panRightKey, panUpKey, panDownKey;
- // Long-press movement tolerance (pixels of raw finger movement before cancelling long-press)
private static final float LONG_PRESS_MOVE_TOLERANCE = 50f;
- // Raw touch-down coordinates for measuring finger travel
private float touchDownRawX, touchDownRawY;
- // Last raw coordinates for single-finger drag delta
private float singleFingerLastRawX, singleFingerLastRawY;
- // Two-finger gesture mutual exclusion (only pan OR pinch, not both)
private static final int TWO_FINGER_GESTURE_NONE = 0;
private static final int TWO_FINGER_GESTURE_PAN = 1;
private static final int TWO_FINGER_GESTURE_ZOOM = 2;
private int twoFingerGestureMode = TWO_FINGER_GESTURE_NONE;
- // Accumulated deltas for deciding which two-finger gesture to lock into
private float accumulatedPinchDelta, accumulatedPanDelta;
- // Settle window: ignore movement for first N ms after second finger lands (#1)
- // Also serves as a grace period for a third finger to arrive before 2F locks in
private static final long TWO_FINGER_SETTLE_MS = 120;
private static final long THREE_FINGER_SETTLE_MS = 50;
private long twoFingerDownTime;
private long threeFingerDownTime;
- // Velocity gating for two-finger hold vs drag (#2)
private long twoFingerLastMoveTime;
- private static final float MIN_DRAG_VELOCITY = 0.3f; // px/ms to commit to drag
+ private static final float MIN_DRAG_VELOCITY = 0.3f;
- // Pinch vs drag ratio: pinch delta must exceed pan by this factor to classify as pinch (#4)
private static final float PINCH_RATIO_THRESHOLD = 1.5f;
- // Cancel-and-reclassify: allow reclassification within this window after lock-in (#5)
private static final long RECLASSIFY_WINDOW_MS = 100;
private long twoFingerLockTime;
private float reclassifyPinchDelta, reclassifyPanDelta;
- // Gesture pointer ownership tracking (prevents d-pad/button pointer conflicts)
private int gestureFingerCount = 0;
private final ArrayList gestureOwnedPointerIds = new ArrayList<>();
private final int[] multiFingerStartIds = new int[3];
private final float[] multiFingerStartX = new float[3], multiFingerStartY = new float[3];
private int multiFingerStartCount;
- // Two-finger hold detection
private Runnable twoFingerHoldRunnable;
private boolean twoFingerHoldTriggered;
- // Three-finger tracking
private boolean threeFingerTapPossible;
private boolean threeFingerTapFired;
private boolean threeFingerDragging;
@@ -199,9 +174,7 @@ public final class TouchscreenGestures {
switch (action) {
case MotionEvent.ACTION_DOWN:
- // A new touch must not shorten or discard an already recognized click.
handleTsCancel(true);
- // First pointer overall — gesture system claims it
gestureOwnedPointerIds.clear();
gestureOwnedPointerIds.add(pointerId);
gestureFingerCount = 1;
@@ -209,13 +182,11 @@ public final class TouchscreenGestures {
break;
case MotionEvent.ACTION_POINTER_DOWN:
- // New pointer arrived — gesture system claims it
if (!gestureOwnedPointerIds.contains(pointerId)) {
gestureOwnedPointerIds.add(pointerId);
gestureFingerCount++;
}
if (gestureFingerCount == 1) {
- // First gesture finger (controls own earlier pointers)
handleTsDown(event, actionIndex);
} else if (gestureFingerCount == 2) {
handleTsPointerDown(event);
@@ -242,15 +213,12 @@ public final class TouchscreenGestures {
gestureOwnedPointerIds.remove(Integer.valueOf(pointerId));
gestureFingerCount = Math.max(0, gestureFingerCount - 1);
if (prevCount == 3 && gestureFingerCount == 2) {
- // Three-finger gesture ending
handleTsThreeFingerUp(event);
} else if (prevCount == 2 && gestureFingerCount == 1) {
- // Two-finger gesture ending (2→1)
handleTsPointerUp(event);
} else if (prevCount >= 4) {
if (removedIndex < 3) rebaseThreeFingerMovement(event);
} else if (prevCount >= 1 && gestureFingerCount == 0) {
- // Last gesture finger lifted while controls still hold pointers
handleTsUp(event, actionIndex);
}
}
@@ -261,9 +229,6 @@ public final class TouchscreenGestures {
int prevCount = gestureFingerCount;
gestureOwnedPointerIds.remove(Integer.valueOf(pointerId));
gestureFingerCount = Math.max(0, gestureFingerCount - 1);
- // Clean up multi-finger state if needed, routing by previous
- // gesture mode so a 3-finger gesture isn't ended via the
- // two-finger cleanup path.
if (prevCount >= 3) {
handleTsThreeFingerUp(event);
} else if (prevCount == 2) {
@@ -271,7 +236,6 @@ public final class TouchscreenGestures {
}
handleTsUp(event, actionIndex);
}
- // ACTION_UP = last pointer overall — full cleanup
gestureOwnedPointerIds.clear();
gestureFingerCount = 0;
break;
@@ -309,15 +273,12 @@ public final class TouchscreenGestures {
threeFingerHoldTriggered = false;
accumulatedThreeFingerDelta = 0;
- // Store raw touch coordinates for long-press movement tolerance
touchDownRawX = event.getX(actionIndex);
touchDownRawY = event.getY(actionIndex);
singleFingerDownTime = SystemClock.uptimeMillis();
singleFingerLastRawX = touchDownRawX;
singleFingerLastRawY = touchDownRawY;
- // Keep a nearby re-tap undecided until UP: it can still become a drag,
- // long press, or multi-finger gesture instead of a double click.
if (isDoubleTap(event, actionIndex)) {
secondTapCandidate = true;
doubleTapAnchorX = lastTapX;
@@ -327,7 +288,6 @@ public final class TouchscreenGestures {
if (!secondTapCandidate && delayedPress == null && pendingTapPress == null) moveCursorTo(x, y);
- // Schedule long-press
if (gestureConfig.getLongPressEnabled()) {
longPressRunnable = () -> {
secondTapCandidate = false;
@@ -342,7 +302,6 @@ public final class TouchscreenGestures {
postDelayed(longPressRunnable, gestureConfig.getLongPressDelay());
}
- // Tap: immediate cursor move (press is deferred to UP for click, or MOVE for drag)
}
private void handleTsPointerDown(MotionEvent event) {
@@ -351,11 +310,6 @@ public final class TouchscreenGestures {
flushPendingTapRelease();
lastTapTime = 0;
flushPendingHoldClickRelease();
- // Cancel any single-finger long-press. cancelLongPressTimer only
- // clears the pending runnable; if the long-press has already fired
- // we must also release the held action before we transition into a
- // multi-finger gesture, otherwise the long-press button/key stays
- // down for the rest of the touch sequence.
if (longPressTriggered) {
longPressActionHeld = releaseHoldAction(longPressActionHeld, gestureConfig.getLongPressAction());
longPressTriggered = false;
@@ -388,7 +342,6 @@ public final class TouchscreenGestures {
event.getY(idx0) - event.getY(idx1));
recordMultiFingerOrigins(event, 2);
}
- // Schedule two-finger hold
if (gestureConfig.getTwoFingerHoldEnabled()) {
twoFingerHoldRunnable = () -> {
twoFingerHoldTriggered = true;
@@ -404,33 +357,26 @@ public final class TouchscreenGestures {
}
private void handleTsMove(MotionEvent event, int pointerIndex) {
- // After a multi-finger gesture, ignore single-finger movement until all fingers lift
if (multiFingerGestureUsed) return;
int x = (int) event.getX(pointerIndex);
int y = (int) event.getY(pointerIndex);
- // If long press already triggered, ignore movement (right-click already sent)
if (longPressTriggered) return;
- // Measure raw finger travel from initial touch point
float rawTravel = maxFingerTravel(event, pointerIndex, touchDownRawX, touchDownRawY);
if (secondTapCandidate && (rawTravel > doubleTapSlop
|| maxFingerTravel(event, pointerIndex, doubleTapAnchorX, doubleTapAnchorY) >= doubleTapSlop)) {
secondTapCandidate = false;
}
- // The threshold decides when a drag starts. An active drag must keep
- // following the finger even when it returns through the touch origin.
if (!isDragging && rawTravel <= LONG_PRESS_MOVE_TOLERANCE) {
return;
}
- // Beyond tolerance — cancel long press
cancelLongPressTimer();
movedBeyondTapThreshold = true;
- // Detect drag start
if (!isDragging && gestureConfig.getDragEnabled()) {
flushPendingTapRelease();
String dragAction = gestureConfig.getDragAction();
@@ -438,14 +384,7 @@ public final class TouchscreenGestures {
dragButtonPressed = true;
singleFingerLastRawX = event.getX(pointerIndex);
singleFingerLastRawY = event.getY(pointerIndex);
- // Send the configured drag press immediately so that a short
- // move followed straight by UP still produces a press+release
- // pair. A zero-delta performPanAction just presses the button
- // (or is a no-op for the key-pan variants, which press per
- // direction on their next move frame).
if (isClickDragAction(dragAction)) {
- // The candidate's cursor stayed at the previous click. Start
- // a drag at this touch's own origin before pressing its button.
moveCursorTo((int) touchDownRawX, (int) touchDownRawY);
if (useRelativeMouseDragMovement()) {
pressClickDragAction(dragAction);
@@ -456,7 +395,6 @@ public final class TouchscreenGestures {
performPanAction(0f, 0f, dragAction);
}
notifyGesture(Gesture.DRAG);
- // Non-click pan actions continue with real deltas on the next frame.
return;
}
@@ -481,14 +419,11 @@ public final class TouchscreenGestures {
return;
}
- // Move cursor
moveCursorTo(x, y);
}
private void handleTsTwoFingerMove(MotionEvent event) {
if (multiFingerGestureUsed) return;
- // If a two-finger hold has already fired, ignore subsequent jitter so
- // it can't lock into a pan/zoom gesture mid-hold.
if (twoFingerHoldTriggered) return;
if (gestureFingerCount < 2 || gestureOwnedPointerIds.size() < 2) return;
@@ -496,20 +431,15 @@ public final class TouchscreenGestures {
int idx1 = event.findPointerIndex(gestureOwnedPointerIds.get(1));
if (idx0 < 0 || idx1 < 0) return;
- // Settling delays recognition, not movement tracking. A swipe or pinch
- // must stop being a tap/hold even when it finishes inside that delay.
if (multiFingerMovementExceeded(event)) {
twoFingerTapPossible = false;
cancelTwoFingerHoldTimer();
}
- // Slow deliberate travel can cross touch slop before reaching the
- // pan/zoom threshold. It must not turn into a stationary hold first.
if (multiFingerMovementExceeded(event, true)) cancelTwoFingerHoldTimer();
float x0 = event.getX(idx0), y0 = event.getY(idx0);
float x1 = event.getX(idx1), y1 = event.getY(idx1);
- // Compute per-frame pan and pinch deltas
float currDist = (float) Math.hypot(x0 - x1, y0 - y1);
float framePinchDelta = Math.abs(currDist - pinchLastDistance);
@@ -523,7 +453,6 @@ public final class TouchscreenGestures {
long now = SystemClock.uptimeMillis();
if (now - twoFingerDownTime < TWO_FINGER_SETTLE_MS) {
- // Still settling — update stored positions but don't accumulate deltas
twoFingerLastX0 = x0; twoFingerLastY0 = y0;
twoFingerLastX1 = x1; twoFingerLastY1 = y1;
pinchLastDistance = currDist;
@@ -531,14 +460,12 @@ public final class TouchscreenGestures {
}
long frameTime = now - twoFingerLastMoveTime;
twoFingerLastMoveTime = now;
- float velocity = (frameTime > 0) ? framePanDelta / frameTime : 0; // px/ms
+ float velocity = (frameTime > 0) ? framePanDelta / frameTime : 0;
- // Accumulate deltas until we have enough movement to decide gesture type
if (twoFingerGestureMode == TWO_FINGER_GESTURE_NONE) {
accumulatedPinchDelta += framePinchDelta;
accumulatedPanDelta += framePanDelta;
if (accumulatedPinchDelta + accumulatedPanDelta > (float) gestureConfig.getGestureThreshold()) {
- // Enough movement to lock into a gesture — no longer a tap or hold
twoFingerTapPossible = false;
cancelTwoFingerHoldTimer();
if (accumulatedPinchDelta > accumulatedPanDelta * PINCH_RATIO_THRESHOLD
@@ -551,7 +478,6 @@ public final class TouchscreenGestures {
twoFingerLockTime = now;
notifyGesture(Gesture.TWO_FINGER_DRAG);
} else if (accumulatedPanDelta >= accumulatedPinchDelta && gestureConfig.getTwoFingerDragEnabled()) {
- // Fallback: pan is dominant but velocity was too low — still drag
twoFingerGestureMode = TWO_FINGER_GESTURE_PAN;
twoFingerLockTime = now;
notifyGesture(Gesture.TWO_FINGER_DRAG);
@@ -571,7 +497,7 @@ public final class TouchscreenGestures {
reclassifyPinchDelta += framePinchDelta;
reclassifyPanDelta += framePanDelta;
float reclassifyTotal = reclassifyPinchDelta + reclassifyPanDelta;
- if (reclassifyTotal > 20f) { // enough post-lock data to reclassify
+ if (reclassifyTotal > 20f) {
boolean shouldBeZoom = reclassifyPinchDelta > reclassifyPanDelta * PINCH_RATIO_THRESHOLD;
if (shouldBeZoom && twoFingerGestureMode == TWO_FINGER_GESTURE_PAN
&& gestureConfig.getPinchEnabled()) {
@@ -585,7 +511,7 @@ public final class TouchscreenGestures {
resetSmallMovement();
notifyGesture(Gesture.TWO_FINGER_DRAG);
}
- twoFingerLockTime = 0; // done reclassifying
+ twoFingerLockTime = 0;
reclassifyPinchDelta = 0;
reclassifyPanDelta = 0;
}
@@ -595,12 +521,10 @@ public final class TouchscreenGestures {
pinchZoomRemainder = accumulateSignedMovement(pinchZoomRemainder, delta);
if (Math.abs(pinchZoomRemainder) >= PINCH_STEP_PX) {
performZoomAction(pinchZoomRemainder > 0);
- // Keep the fractional travel, without queuing a burst of old
- // zoom actions after a large move or a direction reversal.
pinchZoomRemainder %= PINCH_STEP_PX;
}
}
- pinchLastDistance = currDist; // Always update baseline to avoid stale deltas
+ pinchLastDistance = currDist;
if (twoFingerGestureMode == TWO_FINGER_GESTURE_PAN) {
String twoFingerDragAction = gestureConfig.getTwoFingerDragAction();
if (isClickDragAction(twoFingerDragAction)) {
@@ -627,14 +551,11 @@ public final class TouchscreenGestures {
private void handleTsPointerUp(MotionEvent event) {
cancelTwoFingerHoldTimer();
if (multiFingerMovementExceeded(event)) twoFingerTapPossible = false;
- // Two-finger hold release
if (twoFingerHoldTriggered) {
twoFingerHoldActionHeld = releaseHoldAction(twoFingerHoldActionHeld, gestureConfig.getTwoFingerHoldAction());
twoFingerHoldTriggered = false;
}
- // Two-finger tap detection
else if (twoFingerTapPossible && !twoFingerDragging && gestureConfig.getTwoFingerTapEnabled()) {
- // Move cursor to midpoint between the two fingers
float midX = (twoFingerLastX0 + twoFingerLastX1) / 2f;
float midY = (twoFingerLastY0 + twoFingerLastY1) / 2f;
queueTapClick(gestureConfig.getTwoFingerTapAction(), midX, midY);
@@ -652,7 +573,6 @@ public final class TouchscreenGestures {
reclassifyPinchDelta = 0;
reclassifyPanDelta = 0;
twoFingerLockTime = 0;
- // Suppress single-finger tap/drag when last finger lifts after any 2F gesture
movedBeyondTapThreshold = true;
multiFingerGestureUsed = true;
}
@@ -661,7 +581,6 @@ public final class TouchscreenGestures {
cancelLongPressTimer();
if (longPressTriggered) {
- // Release the long-press action
longPressActionHeld = releaseHoldAction(longPressActionHeld, gestureConfig.getLongPressAction());
longPressTriggered = false;
return;
@@ -671,7 +590,6 @@ public final class TouchscreenGestures {
float y = event.getY(actionIndex);
if (isDragging && dragButtonPressed) {
- // End drag (release any held drag buttons/keys)
releaseDragInput();
dragButtonPressed = false;
isDragging = false;
@@ -685,8 +603,6 @@ public final class TouchscreenGestures {
? gestureConfig.getLongPressDelay() : ViewConfiguration.getLongPressTimeout();
if (SystemClock.uptimeMillis() - singleFingerDownTime < tapLimit
&& Math.hypot(x - doubleTapAnchorX, y - doubleTapAnchorY) < doubleTapSlop) {
- // A normal left tap already supplied the first click. Other
- // single-tap mappings need a complete synthesized double click.
boolean firstTapClicked = gestureConfig.getTapEnabled()
&& TouchGestureConfig.ACTION_LEFT_CLICK.equals(gestureConfig.getTapAction());
int clicks = firstTapClicked ? 1 : 2;
@@ -697,26 +613,21 @@ public final class TouchscreenGestures {
}
}
- // Two-finger tap already sent its click on POINTER_UP — skip the tap on UP
if (twoFingerTapFired) {
twoFingerTapFired = false;
return;
}
- // Three-finger tap already sent its click — skip the tap on UP
if (threeFingerTapFired) {
threeFingerTapFired = false;
return;
}
- // Simple tap — only if finger stayed within tap tolerance
if (gestureConfig.getTapEnabled() && !movedBeyondTapThreshold) {
queueTapClick(gestureConfig.getTapAction(), x, y);
notifyGesture(Gesture.TAP);
}
- // Record for double-tap detection (even if tap itself is disabled,
- // so double-tap can still prime from single touch-ups)
if (!movedBeyondTapThreshold && (gestureConfig.getTapEnabled() || gestureConfig.getDoubleTapEnabled())) {
lastTapTime = SystemClock.uptimeMillis();
lastTapX = x;
@@ -776,13 +687,10 @@ public final class TouchscreenGestures {
cancelLongPressTimer();
cancelDrag();
cancelTwoFingerHoldTimer();
- // If a two-finger hold already injected its action, release it before
- // transitioning so the held button/key doesn't stay down.
if (twoFingerHoldTriggered) {
twoFingerHoldActionHeld = releaseHoldAction(twoFingerHoldActionHeld, gestureConfig.getTwoFingerHoldAction());
twoFingerHoldTriggered = false;
}
- // Clean up two-finger state
releaseDragInput();
resetSmallMovement();
twoFingerDragging = false;
@@ -797,7 +705,6 @@ public final class TouchscreenGestures {
threeFingerDragOffsetX = threeFingerDragOffsetY = 0f;
threeFingerDownTime = SystemClock.uptimeMillis();
- // Compute midpoint of three gesture fingers
if (gestureOwnedPointerIds.size() >= 3) {
float sumX = 0, sumY = 0;
int validCount = 0;
@@ -809,13 +716,12 @@ public final class TouchscreenGestures {
validCount++;
}
}
- if (validCount < 3) return; // Can't proceed without all 3 pointers
+ if (validCount < 3) return;
threeFingerLastMidX = sumX / 3f;
threeFingerLastMidY = sumY / 3f;
recordMultiFingerOrigins(event, 3);
}
- // Schedule three-finger hold
if (gestureConfig.getThreeFingerHoldEnabled()) {
threeFingerHoldRunnable = () -> {
threeFingerHoldTriggered = true;
@@ -831,8 +737,6 @@ public final class TouchscreenGestures {
private void handleTsThreeFingerMove(MotionEvent event) {
if (gestureFingerCount < 3 || gestureOwnedPointerIds.size() < 3) return;
- // If a three-finger hold has already fired, ignore subsequent jitter so
- // it can't lock into a pan gesture mid-hold.
if (threeFingerHoldTriggered) return;
if (multiFingerMovementExceeded(event)) {
threeFingerTapPossible = false;
@@ -877,8 +781,6 @@ public final class TouchscreenGestures {
}
if (threeFingerGestureMode == THREE_FINGER_GESTURE_PAN) {
- // Once recognized, retain small mouse movements. Keyboard panning
- // accumulates its own direction threshold in performKeyPan.
String threeFingerDragAction = gestureConfig.getThreeFingerDragAction();
if (isClickDragAction(threeFingerDragAction)) {
if (useRelativeMouseDragMovement()) {
@@ -919,7 +821,6 @@ public final class TouchscreenGestures {
multiFingerStartCount = 0;
resetSmallMovement();
threeFingerGestureMode = THREE_FINGER_GESTURE_NONE;
- // Suppress single-finger tap/drag when last finger lifts after any 3F gesture
movedBeyondTapThreshold = true;
multiFingerGestureUsed = true;
}
@@ -966,7 +867,6 @@ public final class TouchscreenGestures {
}
x /= 3f;
y /= 3f;
- // Replacing a tracked finger changes the centroid without moving the cursor.
if (threeFingerDragging) {
threeFingerDragOffsetX += threeFingerLastMidX - x;
threeFingerDragOffsetY += threeFingerLastMidY - y;
@@ -1030,9 +930,6 @@ public final class TouchscreenGestures {
private void startPendingTapClick() {
if (delayedPress != null || pendingTapPress != null || pendingTapClicks.isEmpty()) return;
TapClick click = pendingTapClicks.peekFirst();
- // Games that poll button state need an observable UP interval too.
- // Reuse the first tap's location: normal finger drift must not turn
- // this into two clicks on different targets or a tiny drag.
long delay = Math.max(0, CLICK_DELAYED_TIME - (SystemClock.uptimeMillis() - lastInputReleaseTime));
pendingTapPress = () -> {
pendingTapPress = null;
@@ -1224,9 +1121,6 @@ public final class TouchscreenGestures {
pressButton(MouseButton.BUTTON_MIDDLE);
twoFingerMiddleButtonDown = true;
}
- // Pan from the client's current pointer. Games can recenter the mouse
- // when the middle button goes down; replaying our old absolute touch
- // anchor after that warp causes a large, unintended camera movement.
moveCursorByRelativeDelta(dx, dy);
}
@@ -1287,10 +1181,6 @@ public final class TouchscreenGestures {
}
private void performKeyPan(float dx, float dy, Integer leftKey, Integer rightKey, Integer upKey, Integer downKey) {
- // When fingers are actively moving, update key states to match the
- // swipe direction. When fingers stop moving but stay on screen,
- // keep the current keys held — movement continues until finger-up
- // calls releasePanKeys().
keyPanRemainderX = accumulateSignedMovement(keyPanRemainderX, dx);
keyPanRemainderY = accumulateSignedMovement(keyPanRemainderY, dy);
@@ -1300,9 +1190,6 @@ public final class TouchscreenGestures {
dy = keyPanRemainderY;
keyPanRemainderX = keyPanRemainderY = 0f;
- // --- Significant movement detected: update each axis ---
-
- // Horizontal: determine desired state from this frame's delta
boolean wantLeft = dx < -3f;
boolean wantRight = dx > 3f;
@@ -1311,7 +1198,6 @@ public final class TouchscreenGestures {
if (wantLeft && !panKeyLeft) { pressKey(leftKey); panKeyLeft = true; panLeftKey = leftKey; }
if (wantRight && !panKeyRight) { pressKey(rightKey); panKeyRight = true; panRightKey = rightKey; }
- // Vertical: determine desired state from this frame's delta
boolean wantUp = dy < -3f;
boolean wantDown = dy > 3f;
diff --git a/app/src/main/java/com/droiddeck/launcher/input/VrControllers.kt b/app/src/main/java/com/droiddeck/launcher/input/VrControllers.kt
index 343d18bdd4..0734710a39 100644
--- a/app/src/main/java/com/droiddeck/launcher/input/VrControllers.kt
+++ b/app/src/main/java/com/droiddeck/launcher/input/VrControllers.kt
@@ -6,7 +6,6 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.io.File
-/** What SteamVR sees for the game pad. The driver reads the file once, when SteamVR starts. */
object VrControllers {
enum class Emulate(val key: String) { OFF("off"), INDEX("index"), TOUCH("touch"), VIVE("vive") }
@@ -46,7 +45,6 @@ object VrControllers {
fun encode(settings: Settings): String =
"emulate=${settings.emulate.key}\nsticks=${if (settings.sticksMoveHands) "hands" else "game"}\n"
- /** Writes into the session's runtime dir, which the guest sees as /run/droiddeck. */
fun publish(context: Context) {
runCatching {
val dir = File(context.filesDir, ".wayland-rt").apply { mkdirs() }
diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/DeckyManager.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DeckyManager.kt
index 5c5687c967..c45c748210 100644
--- a/app/src/main/java/com/droiddeck/launcher/runtime/DeckyManager.kt
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/DeckyManager.kt
@@ -23,7 +23,6 @@ object DeckyManager {
private const val PATH = "root/homebrew/services/PluginLoader"
private const val VERSION = "root/homebrew/services/.droiddeck-decky-version"
private const val SETTINGS = "root/homebrew/settings/loader.json"
- // droiddeck-session reads the marker from the root of the client it runs.
private val CEF_REMOTE_DEBUG_MARKERS = listOf(
"root/.local/share/Steam/.cef-enable-remote-debugging",
"root/.droiddeck-x64/.local/share/Steam/.cef-enable-remote-debugging",
@@ -58,7 +57,6 @@ object DeckyManager {
check(staged.renameTo(file)) { "cannot write ${file.path}" }
}
- // Mirrors Decky's updater: Stable takes the newest non-prerelease tag, Prerelease the newest tag of either kind.
fun latest(channels: ReleaseChannels, branch: Int): Release? =
if (branch == BRANCH_STABLE) channels.stable.firstOrNull() else channels.all.firstOrNull()
diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/DesktopCatalog.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DesktopCatalog.kt
index 4a4857634b..2b976796fc 100644
--- a/app/src/main/java/com/droiddeck/launcher/runtime/DesktopCatalog.kt
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/DesktopCatalog.kt
@@ -51,7 +51,6 @@ object DesktopCatalog {
private fun journal(root: File, id: String) = File(root, ".droiddeck-pkg-$id$JOURNAL_SUFFIX")
- /** Packages whose extraction over the runtime started and never finished. */
fun interrupted(context: Context): List = interrupted(LinuxRuntime.rootDir(context))
fun interrupted(root: File): List =
@@ -63,7 +62,6 @@ object DesktopCatalog {
private fun downloadFile(context: Context, entry: Entry) = File(context.cacheDir, "pkg-${entry.id}-${entry.sha256.take(12)}.download")
- /** Drops downloads kept for installs that no longer need finishing, such as after the runtime was reinstalled. */
fun pruneDownloads(context: Context) = synchronized(installLock) {
val keep = interrupted(context).map { downloadFile(context, it).name }.toSet()
context.cacheDir.listFiles { f -> f.name.startsWith("pkg-") && f.name.removeSuffix(".resume.properties").endsWith(".download") }
@@ -102,7 +100,6 @@ object DesktopCatalog {
o.optString("icon", "applications-games"), o.optString("category", "Game"),
)
- /** A finished download is kept until its extraction completes, so resuming does not fetch it again. */
private fun downloaded(file: File, entry: Entry): Boolean =
file.isFile && file.length() > 0 && !File(file.path + ".resume.properties").exists() &&
(entry.size <= 0 || file.length() == entry.size) && entry.sha256.equals(Hashes.sha256(file), ignoreCase = true)
diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/DesktopLanguage.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DesktopLanguage.kt
new file mode 100644
index 0000000000..c1bb3a192d
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/DesktopLanguage.kt
@@ -0,0 +1,69 @@
+package com.droiddeck.launcher.runtime
+
+import android.content.Context
+import android.util.Log
+import com.droiddeck.launcher.core.Downloader
+import com.droiddeck.launcher.core.FileUtils
+import com.droiddeck.launcher.core.Hashes
+import com.droiddeck.launcher.session.DesktopLocale
+import java.io.File
+import java.util.Locale
+
+object DesktopLanguage {
+ private const val TAG = "DesktopLanguage"
+ private const val INDEX = "desktop-kde.i18n.txt"
+ private const val ABSENT = "absent"
+
+ class Pack(val locale: String, val sha256: String, val size: Long)
+
+ internal fun parseIndex(text: String): Map = text.lineSequence().mapNotNull { line ->
+ val parts = line.trim().split(' ')
+ if (parts.size != 3 || !parts[0].matches(Regex("[A-Za-z_]+")) || !parts[1].matches(Regex("[0-9a-fA-F]{64}"))) return@mapNotNull null
+ Pack(parts[0], parts[1], parts[2].toLongOrNull() ?: return@mapNotNull null)
+ }.associateBy { it.locale }
+
+ /** KDE ships region packs (pt_BR, zh_TW) beside bare-language ones (pt, es). */
+ internal fun candidates(locale: Locale): List {
+ val region = DesktopLocale.lang(locale).removeSuffix(".UTF-8")
+ if (region == DesktopLocale.DEFAULT.removeSuffix(".UTF-8") || region.startsWith("en")) return emptyList()
+ return listOfNotNull(region, "zh_TW".takeIf { region == "zh_HK" }, region.substringBefore('_')).distinct()
+ }
+
+ internal fun baseUrl(desktopUrl: String) = desktopUrl.substringBeforeLast('/') + "/"
+
+ private fun marker(root: File, tag: String, name: String) = File(root, ".droiddeck-i18n-$tag-$name")
+
+ /** Installs the desktop's translations for [locale]; false when a download failed and is worth retrying. */
+ @Synchronized
+ fun ensure(context: Context, locale: Locale): Boolean {
+ val root = LinuxRuntime.rootDir(context)
+ if (!DesktopCatalog.desktopInstalled(root)) return true
+ val entry = DesktopCatalog.desktopEntry(context)
+ val pending = candidates(locale).filterNot { marker(root, entry.version, it).isFile }
+ if (pending.isEmpty()) return true
+ val base = baseUrl(entry.url)
+ val index = parseIndex(Downloader.downloadString(base + INDEX) ?: return false)
+ var complete = true
+ for (name in pending) {
+ val pack = index[name]
+ if (pack == null) {
+ FileUtils.writeString(marker(root, entry.version, name), ABSENT)
+ continue
+ }
+ val download = File(context.cacheDir, "i18n-$name-${pack.sha256.take(12)}.download")
+ try {
+ val ok = Downloader.downloadFile(
+ base + "desktop-kde-i18n-$name.tar.zst", download, true, pack.sha256, java.util.function.Consumer { },
+ ) && pack.sha256.equals(Hashes.sha256(download), ignoreCase = true) &&
+ LinuxRuntimeInstaller.extract(context, download, root, null)
+ if (ok) FileUtils.writeString(marker(root, entry.version, name), pack.sha256) else complete = false
+ } catch (e: Exception) {
+ Log.w(TAG, "language pack $name: $e")
+ complete = false
+ } finally {
+ download.delete()
+ }
+ }
+ return complete
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt b/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt
index cf0d3d7f63..334bce3dfc 100644
--- a/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/DeviceControlsComponent.kt
@@ -189,7 +189,6 @@ class DeviceControlsComponent(context: Context, root: File, private val activity
companion object {
private const val TAG = "DeviceControls"
- // AudioService sends these on every stream step; the Settings observer and 250 ms poll lag a held volume key.
private const val VOLUME_CHANGED_ACTION = "android.media.VOLUME_CHANGED_ACTION"
private const val STREAM_MUTE_CHANGED_ACTION = "android.media.STREAM_MUTE_CHANGED_ACTION"
private const val PERMISSION_CHANNEL = "brightness_permission"
diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt b/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt
index 7db52a9e24..8e5769c312 100644
--- a/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/GuestCommand.kt
@@ -39,7 +39,6 @@ object GuestCommand {
if (linkDir != null) cmd.add(1, "--link2symlink")
val binds = LinuxRuntime.binds(context, null, runtimeDir, Environment.getExternalStorageDirectory(), extraBinds)
binds.forEach { cmd.add("-b"); cmd.add(it) }
- // Fake root and link2symlink are emulated by proot, so their syscalls must stay on the traced path.
val fastPathKey = if (fastPath && !fakeRoot && linkDir == null && ProotFastPath.enabled(context)) ProotFastPath.key(root, binds) else null
cmd += listOf(
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "LANG=C.UTF-8",
@@ -48,8 +47,6 @@ object GuestCommand {
"DROIDDECK_BWRAP_SOCKET=${BwrapSpawner.socket(context)}",
"XDG_DATA_DIRS=/root/.local/share/flatpak/exports/share:/usr/local/share:/usr/share",
)
- // The Steam client installer and the package tools inside the guest fetch over plain curl,
- // so the app proxy has to reach them through the environment proot starts them with.
DownloadSource.proxyHostPort(context).takeIf { it.isNotEmpty() }?.let { hostPort ->
cmd += listOf(
"http_proxy=http://$hostPort", "https_proxy=http://$hostPort",
@@ -77,7 +74,6 @@ object GuestCommand {
try {
while (process.isAlive && !flag.get()) Thread.sleep(200)
if (flag.get()) {
- // PRoot ignores SIGTERM; SIGQUIT makes it kill its tracees and exit cleanly.
if (pid > 0) {
runCatching { android.system.Os.kill(pid, android.system.OsConstants.SIGQUIT) }
} else {
diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java
index 04926193ac..ab5a587370 100644
--- a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java
@@ -50,7 +50,6 @@ public final class LinuxRuntime {
}
public static File liveDir(Context context) {
- // Android may evict cache files even while guest processes are using them.
File dir = new File(context.getNoBackupFilesDir(), "guest-runtime");
dir.mkdirs();
return dir;
@@ -63,9 +62,7 @@ public final class LinuxRuntime {
}
private static final String HOST_DIR = "opt/android-host";
- /** The downloaded add-on pack. The APK does not ship this binary. */
public static final String PROOT_PACK = "add-on pack";
- /** Termux's unpatched proot inside the rootfs. Developer switch only. */
public static final String PROOT_ROOTFS = "rootfs fallback";
public static final String PROOT_MISSING = "missing";
@@ -81,7 +78,6 @@ public final class LinuxRuntime {
return rootfsProot(context).isFile() && rootfsLoader(context).isFile();
}
- /** Patched proot is the add-on pack. The rootfs copy is not that binary. */
public static boolean patchedProot(Context context) {
return AddonPack.PROOT.installed(context);
}
@@ -98,7 +94,6 @@ public final class LinuxRuntime {
return AddonPack.PROOT.file(context, "libproot-loader.so");
}
- /** Where {@link #prootBinary} came from: {@link #PROOT_PACK}, {@link #PROOT_ROOTFS} or {@link #PROOT_MISSING}. */
public static String prootSource(Context context) {
File bin = prootBinary(context);
if (!bin.isFile()) return PROOT_MISSING;
@@ -116,7 +111,6 @@ public final class LinuxRuntime {
return hasRootfs(context) && (patchedProot(context) || rootfsProotReady(context));
}
- /** The rootfs alone: enough to read the game library, while the proot pack can still be downloading. */
public static boolean hasRootfs(Context context) {
if (LinuxRuntimeInstaller.isRemoving() || LinuxRuntimeInstaller.hasRemovalPending(context)) return false;
File root = rootDir(context);
@@ -392,9 +386,6 @@ public final class LinuxRuntime {
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 replacedZoneTypes() {
java.util.Map replaced = new java.util.HashMap<>();
if (gpuTempSource() != null) {
@@ -405,7 +396,6 @@ public final class LinuxRuntime {
return replaced;
}
- /** The zones the session's MangoHud averages for the CPU temperature (all typed cpuN-thermal there). */
public static List cpuTempZones() {
java.util.Map replaced = replacedZoneTypes();
List zones = new ArrayList<>();
diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntimeInstaller.java b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntimeInstaller.java
index ee3349405f..50fb07355e 100644
--- a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntimeInstaller.java
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntimeInstaller.java
@@ -244,10 +244,6 @@ public final class LinuxRuntimeInstaller {
}
}
- /**
- * The download is named after the release, so a partial file is only ever resumed for the same
- * version and checksum, never for a different runtime that happens to share a fixed name.
- */
static String archiveName(Release release) {
String version = release.version.replaceAll("[^A-Za-z0-9._-]", "_");
String sum = release.sha256.replaceAll("[^A-Za-z0-9]", "");
@@ -255,7 +251,6 @@ public final class LinuxRuntimeInstaller {
return "linuxfs-" + version + "-" + sum + ".tar.zst";
}
- /** Removes archives left by other releases and by builds that used the fixed name. */
private static void deleteOtherArchives(File dir, String keep) {
File[] files = dir.listFiles((d, name) -> name.startsWith("linuxfs") && name.endsWith(".tar.zst") && !name.equals(keep));
if (files == null) return;
@@ -264,8 +259,6 @@ public final class LinuxRuntimeInstaller {
private static boolean installOnce(Context context, Release release, ProgressListener listener) {
File archive = new File(context.getCacheDir(), archiveName(release));
- // A failed download keeps what it fetched so the next attempt resumes it; anything that
- // reached verification and failed is not trusted and is removed.
boolean keepPartial = false;
try {
deleteOtherArchives(context.getCacheDir(), archive.getName());
@@ -526,8 +519,6 @@ public final class LinuxRuntimeInstaller {
}
}
- // Packages extract over the live runtime and their archives list a link before the file it
- // names, so a kill mid-way must leave neither a truncated file nor a link to a missing one.
public static boolean extract(Context context, File archive, File destination, ProgressListener listener) {
return extract(context, archive, destination, destination, listener);
}
diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/ProotFastPath.kt b/app/src/main/java/com/droiddeck/launcher/runtime/ProotFastPath.kt
index 974b6fe16e..e9a9f4a72e 100644
--- a/app/src/main/java/com/droiddeck/launcher/runtime/ProotFastPath.kt
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/ProotFastPath.kt
@@ -12,10 +12,6 @@ object ProotFastPath {
const val LIBRARY = "/usr/local/lib/libblfastpath.so"
const val MAX_BINDS = 256
- /**
- * The fast path's trampoline is let through only by the proot built with patches/0014.
- * The rootfs copy (Termux's stock proot) is not that binary, so the library stays out.
- */
fun allows(preference: Boolean, noSeccomp: Boolean, source: String): Boolean =
preference && !noSeccomp && source == LinuxRuntime.PROOT_PACK
diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/RuntimeFileTree.java b/app/src/main/java/com/droiddeck/launcher/runtime/RuntimeFileTree.java
index 3b2a39ee85..fbbc5ddaed 100644
--- a/app/src/main/java/com/droiddeck/launcher/runtime/RuntimeFileTree.java
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/RuntimeFileTree.java
@@ -74,11 +74,6 @@ public final class RuntimeFileTree {
throw new IOException("Cannot make directory removable: " + dir);
}
- /**
- * Paths in a runtime tree that belong to the user: the home folder, imported AppImages and script apps, and catalog
- * AppImages with their menu entries and markers. Tar-kind catalog packages (the desktop) unpack over /usr and cannot
- * be carried.
- */
static java.util.List userPaths(File tree) throws IOException {
java.util.List paths = new java.util.ArrayList<>(java.util.Arrays.asList("root", "opt/appimages/user", "opt/droiddeck-apps", "opt/droiddeck/wincomponents"));
for (String n : children(new File(tree, "usr/local/share/applications"))) {
@@ -168,13 +163,6 @@ public final class RuntimeFileTree {
return false;
}
- /**
- * Moves each user path that exists in {@code from} into {@code to}, replacing what {@code to} ships there. With
- * {@code onlyMissing}, a path already present in {@code to} is left alone. On failure the paths already moved go back
- * before the exception is thrown. Rollback failures are suppressed on that exception; callers must retain the source
- * of any incomplete rollback.
- * Returns the moved paths.
- */
static java.util.List carryUserData(File from, File to, boolean onlyMissing) throws IOException {
return carryUserData(from, to, onlyMissing, new java.util.ArrayList<>(userPaths(from, to)));
}
@@ -200,7 +188,6 @@ public final class RuntimeFileTree {
return moved;
}
- /** Puts the given paths back from {@code from} into {@code to}; failures are collected, not stopped on. */
static void carryBack(File from, File to, java.util.List paths) throws IOException {
IOException failed = null;
for (int i = paths.size() - 1; i >= 0; i--) {
diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/RuntimeHealth.kt b/app/src/main/java/com/droiddeck/launcher/runtime/RuntimeHealth.kt
index f334e6cc54..94d7f443f6 100644
--- a/app/src/main/java/com/droiddeck/launcher/runtime/RuntimeHealth.kt
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/RuntimeHealth.kt
@@ -10,7 +10,6 @@ object RuntimeHealth {
fun brokenLibraryLinks(context: Context): List = brokenLibraryLinks(LinuxRuntime.rootDir(context))
- /** A complete runtime has no library link in usr/lib whose target is missing. */
fun brokenLibraryLinks(root: File): List =
listOf("usr/lib", "usr/lib/aarch64-linux-gnu").flatMap { dir ->
val lib = File(root, dir)
diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/RuntimeInstallService.kt b/app/src/main/java/com/droiddeck/launcher/runtime/RuntimeInstallService.kt
index aa53092fe2..a641cf1f28 100644
--- a/app/src/main/java/com/droiddeck/launcher/runtime/RuntimeInstallService.kt
+++ b/app/src/main/java/com/droiddeck/launcher/runtime/RuntimeInstallService.kt
@@ -117,7 +117,6 @@ class RuntimeInstallService : Service() {
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent)
}
- /** Keeps the process in the foreground until the returned release runs, so closing the app does not stop the install. */
fun holdForPackage(context: Context, title: String): () -> Unit {
packageTitle = title
packageStage = title
diff --git a/app/src/main/java/com/droiddeck/launcher/session/BatteryComponent.kt b/app/src/main/java/com/droiddeck/launcher/session/BatteryComponent.kt
index 517fa6c74f..ef64bfde02 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/BatteryComponent.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/BatteryComponent.kt
@@ -56,7 +56,6 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
val timeToEmptyS = if (discharging && chargeNowUah > 0 && abs(currentAvgUa) > 0) chargeNowUah * 3600L / abs(currentAvgUa) else 0L
val charging = status == BatteryManager.BATTERY_STATUS_CHARGING
val timeToFullS = if (charging && chargeFullUah > chargeNowUah && abs(currentAvgUa) > 0) (chargeFullUah - chargeNowUah) * 3600L / abs(currentAvgUa) else 0L
- // Android can keep reporting charging at 100%; Linux reports Full there, and Steam shows 99% until it does.
val statusText = when (status) {
BatteryManager.BATTERY_STATUS_CHARGING -> if (pct >= 100) "Full" else "Charging"
BatteryManager.BATTERY_STATUS_DISCHARGING -> "Discharging"
@@ -127,9 +126,6 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
companion object {
private const val TAG = "SessionService"
- // CURRENT_NOW/CURRENT_AVERAGE are documented as µA, but Samsung and other vendors report mA,
- // which made every lifetime estimate 1000x too long. No real µA reading under load is below 10 mA,
- // and no mA reading is above 10 A, so anything smaller than 10_000 is taken as mA.
private const val MILLIAMP_CEILING = 10_000L
internal fun toMicroamps(raw: Long): Long = if (abs(raw) < MILLIAMP_CEILING) raw * 1000L else raw
diff --git a/app/src/main/java/com/droiddeck/launcher/session/BootMovie.kt b/app/src/main/java/com/droiddeck/launcher/session/BootMovie.kt
index 953196900c..a525bed375 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/BootMovie.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/BootMovie.kt
@@ -24,7 +24,6 @@ object BootMovie {
DROIDDECK_60 to "droiddeck-startup-60.webm",
)
- // Steam's CEF player only takes WebM codecs; MediaMuxer's WebM writer cannot take AV1.
internal val VIDEO_CODECS = setOf(MediaFormat.MIMETYPE_VIDEO_VP8, MediaFormat.MIMETYPE_VIDEO_VP9, MediaFormat.MIMETYPE_VIDEO_AV1)
private val REMUX_CODECS = setOf(MediaFormat.MIMETYPE_VIDEO_VP8, MediaFormat.MIMETYPE_VIDEO_VP9)
internal val AUDIO_CODECS = setOf(MediaFormat.MIMETYPE_AUDIO_OPUS, MediaFormat.MIMETYPE_AUDIO_VORBIS)
@@ -39,18 +38,14 @@ object BootMovie {
private fun dir(context: Context) = File(context.filesDir, "boot-movie")
private fun customFile(context: Context) = File(dir(context), "custom.webm")
- /** A movie imported before movies were kept in Steam's own folder. */
internal fun legacyCustomFile(context: Context) = customFile(context)
- /** Unpacks one of DroidDeck's own movies on demand; null for anything else. */
internal fun assetFile(context: Context, id: String): File? = ASSETS[id]?.let { extractAsset(context, it) }
- /** Picking a movie here makes it Steam's startup movie at the next session, over whatever Steam had picked. */
fun select(context: Context, id: String) {
SessionPrefs.setBootMovie(context, id)
SessionPrefs.setBootMovieApplyNext(context, true)
BootMovieReport.note(context, "picked $id here; Steam names ${SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context))}")
- // Whatever Steam names right now is about to be replaced, so it is not a pick to adopt later.
SessionFiles.startupMovieLocalPath(BootMovieLibrary.steamConfig(context))?.let { SessionPrefs.setBootMovieSteamSeen(context, it) }
}
@@ -67,7 +62,6 @@ object BootMovie {
}
}
- /** The file the current choice plays from, before any volume or length change. */
fun currentFile(context: Context): File? = sourceOf(context, choice(context))
private fun sourceOf(context: Context, choice: String): File? = when {
@@ -84,7 +78,6 @@ object BootMovie {
return variant(context, source)
}
- /** The movie as Steam should get it: with the chosen volume and cut off after the chosen number of seconds. */
private fun variant(context: Context, source: File): File? {
val volume = if (SessionPrefs.bootMovieSound(context)) SessionPrefs.bootMovieVolume(context) else 0
val seconds = SessionPrefs.bootMovieSeconds(context)
@@ -124,21 +117,15 @@ object BootMovie {
internal enum class Step { REMUX_SILENT, REMUX_AUDIO, TRANSCODE_SILENT, TRANSCODE_AUDIO, REGAIN }
- /**
- * How a movie is processed: the steps tried in order until one works, whether the source goes out untouched, and
- * whether it still plays as it is when every step fails.
- */
internal class Plan(val passthrough: Boolean, val steps: List, val sourceOnFailure: Boolean)
internal fun plan(volume: Int, seconds: Int): Plan = when {
volume == 100 && seconds == 0 -> Plan(true, emptyList(), true)
volume == 0 -> Plan(false, listOf(Step.REMUX_SILENT, Step.TRANSCODE_SILENT), false)
- // Only a length that could not be applied plays as it is; a volume that could not be applied plays no louder.
volume == 100 -> Plan(false, listOf(Step.REMUX_AUDIO, Step.TRANSCODE_AUDIO), true)
else -> Plan(false, listOf(Step.REGAIN, Step.REMUX_SILENT, Step.TRANSCODE_AUDIO), false)
}
- /** Frames beyond 1920x1080 (4K and the like) have made Steam crash while it starts, so such a movie is always scaled down. */
internal const val MAX_LONG_SIDE = 1920
internal const val MAX_SHORT_SIDE = 1080
@@ -150,22 +137,16 @@ object BootMovie {
private fun isOversized(source: File): Boolean = probe(source)?.first?.let { oversized(it) } == true
- /** A movie that is too large never goes out as it is: it is converted at the chosen volume, and plays nothing if that fails. */
internal fun oversizedPlan(volume: Int): Plan =
Plan(false, listOf(if (volume == 0) Step.TRANSCODE_SILENT else Step.TRANSCODE_AUDIO), false)
private fun transcodeSilent(source: File, target: File, limitUs: Long) =
BootMovieTranscoder.transcode(source, target, keepAudio = false, limitUs = limitUs) {} != null
- /** Keeps at most the one processed copy in use, so trying settings never leaves movies piling up. */
private fun prune(folder: File, keep: String?) {
folder.listFiles()?.forEach { if (it.name != keep) it.delete() }
}
- /**
- * Takes over a startup movie chosen in Steam's own settings: when Steam's config names a movie it did not name before,
- * that movie becomes the choice here. Steam already plays it, so nothing is staged over it. True when the choice changed.
- */
fun syncFromSteam(context: Context): Boolean {
val named = SessionFiles.startupMovieLocalPath(BootMovieLibrary.steamConfig(context)) ?: return false
val seen = SessionPrefs.bootMovieSteamSeen(context)
@@ -174,7 +155,6 @@ object BootMovie {
if (named == SessionFiles.BOOT_MOVIE_PATH || (named.isEmpty() && seen == null)) return false
val path = named.ifEmpty { "/movies/steam_os_startup.webm" }
val prefix = "/uioverrides/movies/"
- // The list names a bought movie from the Steam folder (/config/communityitemscache/...), Steam's config from its config folder.
val id = if (path.startsWith(prefix)) BootMovieLibrary.idOf(path.removePrefix(prefix)) else {
val listed = BootMovieLibrary.list(context).firstOrNull { it.id.startsWith(BootMovieLibrary.STEAM_PREFIX) && it.id.endsWith(path) }
listed?.id ?: BootMovieLibrary.STEAM_PREFIX + path
diff --git a/app/src/main/java/com/droiddeck/launcher/session/BootMovieLibrary.kt b/app/src/main/java/com/droiddeck/launcher/session/BootMovieLibrary.kt
index 0dd7a0fadf..6fb1f56a9e 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/BootMovieLibrary.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/BootMovieLibrary.kt
@@ -9,22 +9,14 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONObject
import java.io.File
-/**
- * The boot movies a person can pick from: DroidDeck's own two, a movie imported before this list existed, every `.webm` in
- * Steam's custom movies folder (imports, SteamDeckRepo and movies put there by hand; all of them can be removed), Steam's own
- * three startup movies and the movies bought in Steam's points shop (neither can be removed).
- */
object BootMovieLibrary {
private const val TAG = "BootMovieLibrary"
const val PREFIX = "file:"
- /** A movie Steam itself keeps outside its custom movies folder, such as one bought in its points shop: `steam:`. */
const val STEAM_PREFIX = "steam:"
- /** Held while the movie list is read and changed, so two imports at once cannot overwrite each other's entries. */
private val lock = Any()
- /** Names DroidDeck stages the chosen movie under; they are copies, not movies of their own. */
internal val STAGED = setOf("bigpicture_startup.webm", "steam_os_startup.webm", "droiddeck-startup.webm")
const val SOURCE_DROIDDECK = "droiddeck"
@@ -37,28 +29,21 @@ object BootMovieLibrary {
internal fun moviesDir(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/config/uioverrides/movies")
- /**
- * The folders whose custom movies are listed, found and removed: [moviesDir], where imports are put and managed, then the
- * x86-64 client's. The order never depends on which client is running, so a saved choice keeps meaning the same file.
- */
internal fun customMovieDirs(context: Context): List =
listOf(moviesDir(context), File(SessionPrefs.steamRoot(context, "x86_64"), "config/uioverrides/movies")).distinctBy { it.path }
- /** Where imported and installed movies are kept for good; Steam's folder holds a copy, which is put back if it goes missing. */
internal fun libraryDir(context: Context) = File(context.filesDir, "boot-movie/library")
private fun metaFile(context: Context) = File(context.filesDir, "boot-movie/movies.json")
internal fun steamRoot(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
- /** The running (else selected) Steam client's config, the one whose startup movie choice is read and recorded. */
internal fun steamConfig(context: Context) = File(SessionPrefs.activeSteamRoot(context), "config/config.vdf")
private fun thumbsDir(context: Context) = File(context.filesDir, "boot-movie/thumbs")
fun idOf(name: String) = PREFIX + name
- /** Every Steam client folder: the usual one and the x86-64 client's. */
internal fun steamRoots(context: Context): List = listOf(
steamRoot(context), File(LinuxRuntime.rootDir(context), "root/.droiddeck-x64/.local/share/Steam"),
).filter { it.isDirectory }
@@ -86,7 +71,6 @@ object BootMovieLibrary {
private fun readMeta(context: Context): JSONObject =
runCatching { JSONObject(metaFile(context).readText()) }.getOrDefault(JSONObject())
- /** Changes the movie list one writer at a time; [change] gets the list and returns whether to save it. */
private fun editMeta(context: Context, change: (JSONObject) -> Boolean) = synchronized(lock) {
val meta = readMeta(context)
if (change(meta)) {
@@ -100,7 +84,6 @@ object BootMovieLibrary {
}
}
- /** The post a movie was installed from, if it came from SteamDeckRepo. */
fun repoId(context: Context, name: String): String? =
readMeta(context).optJSONObject(name)?.optString("repo")?.takeIf { it.isNotEmpty() }
@@ -128,7 +111,6 @@ object BootMovieLibrary {
val info = meta.optJSONObject(f.name)
val source = info?.optString("source")?.takeIf { it.isNotEmpty() } ?: SOURCE_STEAM
val title = info?.optString("title")?.takeIf { it.isNotEmpty() } ?: f.nameWithoutExtension
- // Everything in Steam's custom movies folder is the person's own (imported, from SteamDeckRepo or put there by hand).
out.add(Entry(idOf(f.name), title, if (source == SOURCE_STEAM) SOURCE_IMPORT else source, f, removable = true))
}
val steam = LinkedHashMap()
@@ -147,14 +129,12 @@ object BootMovieLibrary {
for ((id, file) in steam) {
val native = file.nameWithoutExtension.lowercase() in NATIVE
if ((file.name in STAGED && !native) || !seen.add(file.canonicalPath)) continue
- // Steam names a bought movie by an item number and a hash; the points shop's own title is shown when Steam has it.
val title = if (native) NATIVE[file.nameWithoutExtension.lowercase()] ?: file.nameWithoutExtension else bought[file.path] ?: boughtId(file)?.let { "#$it" } ?: file.nameWithoutExtension
out.add(Entry(id, title, if (native) SOURCE_STEAM else SOURCE_POINTSHOP, file, removable = false))
}
return out
}
- /** The four startup movies Steam ships with; Steam's movies folder holds many more videos that are not startup movies. */
private val NATIVE = mapOf(
"deck_startup" to "Deck startup", "oled_startup" to "Oled startup", "startup_machine" to "Machine startup",
"steam_os_startup" to "SteamOS startup",
@@ -167,13 +147,8 @@ object BootMovieLibrary {
private val scans = HashMap()
- /** Forgets the last search for Steam's own movies. */
internal fun forgetScan() = synchronized(scanLock) { scans.clear() }
- /**
- * Movies Steam keeps outside its custom movies folder, such as ones bought in its points shop: every `.webm` below the
- * client's config, cache and user folders. The search is repeated at most every 15 seconds for each client folder.
- */
private fun pointShopMovies(root: File): Scan = synchronized(scanLock) {
val now = System.currentTimeMillis()
scans[root.path]?.let { if (now - it.at < 15_000L) return it }
@@ -191,10 +166,8 @@ object BootMovieLibrary {
scan
}
- /** The item number in the name Steam gives a bought movie, `- _.webm`; null for any other name. */
private fun boughtId(file: File) = Regex("^(\\d+)_").find(file.nameWithoutExtension)?.groupValues?.get(1)
- /** What the points shop calls a bought movie, from the list of startup movies Steam keeps in each user's local config. */
private fun boughtTitle(root: File, id: String): String? {
val key = "communityitemid\\\":\\\"$id\\\""
val title = Regex("item_title\\\\\":\\\\\"([^\\\\\"]*)")
@@ -209,7 +182,6 @@ object BootMovieLibrary {
private const val OVERRIDES = "/uioverrides/movies/"
- /** Puts back, in Steam's folder, any movie of DroidDeck's that went missing there, such as after the runtime was reset. */
internal fun restore(context: Context) = synchronized(lock) {
migrateLegacyMeta(context)
val meta = readMeta(context)
@@ -222,7 +194,6 @@ object BootMovieLibrary {
}
}
- /** Takes in the movie notes an earlier version kept inside Steam's movies folder, so those movies keep their title and source. */
private fun migrateLegacyMeta(context: Context) {
val legacy = File(moviesDir(context), ".droiddeck-movies.json")
if (!legacy.isFile) return
@@ -238,7 +209,6 @@ object BootMovieLibrary {
legacy.delete()
}
- /** Copies [kept] to [copy] through a staging name, so Steam never sees half a movie. */
private fun mirror(kept: File, copy: File): Boolean {
val staged = File(copy.parentFile, copy.name + ".${System.nanoTime()}.staged")
return try {
@@ -255,10 +225,8 @@ object BootMovieLibrary {
fun title(context: Context, id: String): String = list(context).firstOrNull { it.id == id }?.title ?: id
- /** The file a movie id plays from; DroidDeck's own movies live in the app and are unpacked on demand. */
fun fileOf(context: Context, entry: Entry): File? = entry.file ?: BootMovie.assetFile(context, entry.id)
- /** A free `.webm` name for a movie called [title]; the same title twice gets " (2)", " (3)"… */
fun freeName(context: Context, title: String): String {
val base = title.replace(Regex("[^\\p{L}\\p{N} ._()\\-]"), "").replace(Regex("\\s+"), " ").trim().trim('.').take(60).ifEmpty { "movie" }
val dirs = customMovieDirs(context)
@@ -269,10 +237,6 @@ object BootMovieLibrary {
return name
}
- /**
- * Keeps the finished movie [staged] (a file in [libraryDir]) under a free name, copies it into Steam's folder and notes its
- * title, source and cover. Returns the name, or null when it could not be kept. Runs one movie at a time.
- */
internal fun commit(context: Context, staged: File, title: String, source: String, repoId: String? = null, cover: ByteArray? = null): String? =
synchronized(lock) {
val name = freeName(context, title)
@@ -283,7 +247,6 @@ object BootMovieLibrary {
name
}
- /** Notes a movie that was just put into Steam's folder: what to call it, where it came from and its cover. */
fun register(context: Context, name: String, title: String, source: String, repoId: String? = null, cover: ByteArray? = null) {
editMeta(context) { meta ->
val info = JSONObject().put("title", title).put("source", source)
@@ -301,12 +264,10 @@ object BootMovieLibrary {
val removed = when {
id == BootMovie.CUSTOM -> { BootMovie.removeCustom(context); true }
else -> {
- // Only movies in Steam's custom movies folder are ever deleted; Steam's own and points shop movies are left alone.
if (!id.startsWith(PREFIX)) return false
val name = id.removePrefix(PREFIX)
if (name.isEmpty() || name.contains('/') || name.contains('\\') || name in STAGED) return false
val copies = customMovieDirs(context).map { File(it, name) }
- // A name can exist in more than one client's folder; the entry is the first one found (see customMovieDirs), and only that file is deleted.
val target = copies.firstOrNull { it.exists() }
val managed = File(libraryDir(context), name)
if (readMeta(context).optJSONObject(name) == null && target == null && !managed.isFile) return false
@@ -335,14 +296,12 @@ object BootMovieLibrary {
return removed
}
- /** What every processed copy of [source] starts with; the hash of its full path keeps same-named files in different places apart. */
internal fun variantPrefix(source: File) = safe(source.name) + "." + Integer.toHexString(source.absolutePath.hashCode()) + "-"
private fun safe(name: String) = name.replace(Regex("[^A-Za-z0-9._-]"), "_")
private fun coverName(name: String) = "cover-" + safe(name)
- /** How long a movie runs, in whole seconds; 0 when it cannot be read. */
fun durationSeconds(file: File?): Int {
if (file == null || !file.isFile) return 0
val retriever = MediaMetadataRetriever()
@@ -357,7 +316,6 @@ object BootMovieLibrary {
}
}
- /** The first frame that is not nearly black out of several taken through the movie, else the brightest; a movie may open dark. */
private fun brightestFrame(retriever: MediaMetadataRetriever, durationMs: Long): Bitmap? {
var best: Bitmap? = null
var bestLuma = -1
@@ -382,11 +340,9 @@ object BootMovieLibrary {
private const val MIN_COVER_LUMA = 24
- /** A cover for a movie: the picture SteamDeckRepo gave it, or one frame taken from the video and remembered. */
fun cover(context: Context, entry: Entry): File? {
val file = fileOf(context, entry) ?: return null
val name = if (entry.id.startsWith(PREFIX)) file.name else entry.id
- // Points Shop covers once kept a picture that was not always the movie's own; those files are not used.
val given = File(thumbsDir(context), if (entry.source == SOURCE_POINTSHOP) "v2-" + coverName(name) else coverName(name))
if (given.isFile && given.length() > 0L) return given
val key = "frame-" + safe(name) + "-v2-" + file.length() + "-" + file.lastModified() + ".jpg"
diff --git a/app/src/main/java/com/droiddeck/launcher/session/BootMovieReport.kt b/app/src/main/java/com/droiddeck/launcher/session/BootMovieReport.kt
index 3a672dcfd9..18ff31169d 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/BootMovieReport.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/BootMovieReport.kt
@@ -8,10 +8,6 @@ import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
-/**
- * What DroidDeck and Steam know about boot movies, in one text file: Steam's startup movie setting, every movie file and
- * where it lives, DroidDeck's own state, and a short trace of what each session start did to Steam's config.
- */
object BootMovieReport {
private const val TAG = "BootMovieReport"
private const val MAX_TRACE_LINES = 200
@@ -23,7 +19,6 @@ object BootMovieReport {
private fun traceFile(context: Context) = File(context.filesDir, "boot-movie/apply.log")
- /** Adds a line to the short trace kept for the report; only the latest lines are kept. */
fun note(context: Context, line: String) {
synchronized(lock) {
runCatching {
@@ -36,7 +31,6 @@ object BootMovieReport {
}
}
- /** Writes the report to Downloads/DroidDeck, or to the app's own folder when that is not possible; null when the report cannot be built or neither folder works. */
fun write(context: Context): File? {
val text = runCatching { build(context) }.getOrElse {
Log.w(TAG, "could not build the report", it)
diff --git a/app/src/main/java/com/droiddeck/launcher/session/BootMovieTranscoder.kt b/app/src/main/java/com/droiddeck/launcher/session/BootMovieTranscoder.kt
index 92bbbae4e2..55f84c006d 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/BootMovieTranscoder.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/BootMovieTranscoder.kt
@@ -46,7 +46,6 @@ internal object BootMovieTranscoder {
return Result(audioDropped = hadAudio && !muxedAudio)
}
- /** Copies the video of [source] untouched and gives it its sound again at [gain] of its level, cut to [limitUs]. */
fun regain(source: File, target: File, gain: Float, limitUs: Long): Boolean {
val audio = runCatching { encodeAudio(source, gain, limitUs) }
.onFailure { Log.w(TAG, "could not change the volume of ${source.name}", it) }.getOrNull() ?: return false
@@ -121,7 +120,6 @@ internal object BootMovieTranscoder {
internal class Layout(val width: Int, val height: Int, val x: Int, val y: Int, val contentWidth: Int, val contentHeight: Int)
- // Steam fills the screen with its startup movie, so portrait clips are pillarboxed into 16:9 instead of cropped.
internal fun layout(width: Int, height: Int, rotation: Int): Layout {
val (w, h) = if (rotation % 180 != 0) height to width else width to height
fun even(v: Double) = maxOf(2, (v.toInt() / 2) * 2)
@@ -137,7 +135,6 @@ internal object BootMovieTranscoder {
return Layout(canvas, ch, (canvas - cw) / 2, 0, cw, ch)
}
- /** [pcm] made quieter by [gain] and cut to its first [limitUs] microseconds. */
internal fun scale(pcm: ShortArray, channels: Int, gain: Float, limitUs: Long): ShortArray {
val frames = pcm.size / channels
val kept = if (limitUs == Long.MAX_VALUE) frames else minOf(frames.toLong(), limitUs * OPUS_RATE / 1_000_000L).toInt()
@@ -164,7 +161,6 @@ internal object BootMovieTranscoder {
return out
}
- /** Most decoded audio held in memory at once: about six minutes of 48 kHz stereo. */
private const val MAX_PCM_BYTES = 64 shl 20
private fun encodeAudio(source: File, gain: Float = 1f, limitUs: Long = Long.MAX_VALUE): Audio? {
@@ -212,7 +208,6 @@ internal object BootMovieTranscoder {
}
dec.releaseOutputBuffer(index, false)
if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) break
- // Past the length that will be kept there is nothing more to decode; without a length, a track too big to hold is dropped.
if (limitUs != Long.MAX_VALUE && info.presentationTimeUs > limitUs) break
if (pcm.size() > MAX_PCM_BYTES) { if (limitUs == Long.MAX_VALUE) return null else break }
}
diff --git a/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt b/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt
new file mode 100644
index 0000000000..923ee29996
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt
@@ -0,0 +1,353 @@
+package com.droiddeck.launcher.session
+
+import android.content.ComponentName
+import android.content.Context
+import android.content.Intent
+import android.content.ServiceConnection
+import android.os.Bundle
+import android.os.Environment
+import android.os.Handler
+import android.os.IBinder
+import android.os.Looper
+import android.os.Message
+import android.os.Messenger
+import android.util.Log
+import android.view.Surface
+import com.droiddeck.launcher.core.HostProcess
+import com.droiddeck.launcher.runtime.DesktopCatalog
+import com.droiddeck.launcher.runtime.LinuxRuntime
+import com.droiddeck.launcher.wayland.BottomDesktopCompositorService as Comp
+import java.io.File
+
+/**
+ * KDE Plasma on the bottom screen while the session keeps the top one: its own compositor process
+ * ([Comp]) and a second guest started with the session's environment, like the bottom-screen terminal.
+ */
+object BottomDesktop {
+ private const val TAG = "BottomDesktop"
+ const val SCRIPT = "/usr/local/bin/droiddeck-bottom-desktop"
+ private const val TARGET_SHORT_SIDE = 720f
+
+ enum class State { OFF, STARTING, RUNNING, ENDED, FAILED }
+
+ private class Launch(
+ val guest: List,
+ val binds: List,
+ val sessionRoot: File,
+ val hostEnvironment: Array,
+ val root: File,
+ val sessionDir: File,
+ val generation: Int,
+ val installed: Boolean,
+ )
+
+ @Volatile private var launch: Launch? = null
+ private val launchLock = Any()
+ private val main = Handler(Looper.getMainLooper())
+ private val listeners = LinkedHashSet<() -> Unit>()
+
+ @Volatile var state = State.OFF
+ private set
+ private var onTextInput: ((Boolean) -> Unit)? = null
+ private var imeWatcher: android.os.FileObserver? = null
+
+ private var appContext: Context? = null
+ private var service: Messenger? = null
+ private var binding: ServiceConnection? = null
+ private var pendingAttach: Message? = null
+ /** The desktop guest's proot: -1 when there is none, 0 while it is being started. */
+ @Volatile private var guestPid = -1
+
+ /** The proot to freeze with the session when it pauses. */
+ val suspendPid: Int get() = guestPid
+ private var guestGeneration = 0
+ private var outputSize = 0 to 0
+ private var cursorShown = false
+ /** The session generation whose launch the running compositor and guest belong to; -1 when none. */
+ private var owner = -1
+
+ private val replies = Messenger(object : Handler(Looper.getMainLooper()) {
+ override fun handleMessage(msg: Message) {
+ if (msg.arg1 != owner) return
+ when (msg.what) {
+ Comp.MSG_ATTACHED -> {
+ service?.let { send(it, Message.obtain(null, Comp.MSG_CURSOR, if (cursorShown) 1 else 0, 0)) }
+ if (guestPid < 0 && state == State.STARTING) startGuest()
+ }
+ Comp.MSG_FIRST_FRAME -> if (state == State.STARTING) setState(State.RUNNING)
+ }
+ }
+ })
+
+ fun prepare(
+ guest: List,
+ binds: List,
+ sessionRoot: File,
+ hostEnvironment: Array,
+ root: File,
+ sessionDir: File,
+ generation: Int,
+ stillCurrent: () -> Boolean,
+ ) {
+ val prepared = Launch(ArrayList(guest), ArrayList(binds), sessionRoot, hostEnvironment.copyOf(), root, sessionDir, generation,
+ DesktopCatalog.desktopInstalled(root))
+ synchronized(launchLock) { if (stillCurrent()) launch = prepared }
+ }
+
+ fun available(): Boolean =
+ launch?.installed == true && SessionState.running && SessionState.mode != SessionService.MODE_DESKTOP
+
+ /**
+ * The desktop renders below the panel's resolution: about 720 pixels on the short side keeps
+ * Plasma's text big enough to touch and its software rendering cheap. A running desktop keeps its size.
+ */
+ fun outputSizeFor(width: Int, height: Int): Pair {
+ if ((state == State.STARTING || state == State.RUNNING) && outputSize.first > 0) return outputSize
+ if (width <= 0 || height <= 0) return 0 to 0
+ val scale = maxOf(1f, Math.round(minOf(width, height) / TARGET_SHORT_SIDE * 2f) / 2f)
+ return ((width / scale).toInt() and 1.inv()) to ((height / scale).toInt() and 1.inv())
+ }
+
+ fun addListener(listener: () -> Unit) { listeners.add(listener) }
+
+ fun removeListener(listener: () -> Unit) { listeners.remove(listener) }
+
+ /** Called on the main thread when a text field in the desktop gains or loses focus (droiddeck-ime's report). */
+ fun setTextInputListener(listener: ((Boolean) -> Unit)?) { onTextInput = listener }
+
+ private fun watchIme(dir: File) {
+ imeWatcher?.stopWatching()
+ dir.deleteRecursively()
+ dir.mkdirs()
+ @Suppress("DEPRECATION")
+ imeWatcher = object : android.os.FileObserver(dir.path, MOVED_TO or CLOSE_WRITE) {
+ override fun onEvent(event: Int, path: String?) {
+ if (path != "ime.json") return
+ val focused = runCatching { org.json.JSONObject(File(dir, path).readText()).optBoolean("textField") }
+ .getOrNull() ?: return
+ main.post { if (imeWatcher === this) onTextInput?.invoke(focused) }
+ }
+ }.also { it.startWatching() }
+ }
+
+ private fun setState(next: State) {
+ if (Looper.myLooper() != Looper.getMainLooper()) { main.post { setState(next) }; return }
+ if (state == next) return
+ Log.i(TAG, "state $state -> $next")
+ state = next
+ listeners.toList().forEach { it() }
+ }
+
+ fun attach(context: Context, surface: Surface, width: Int, height: Int, refreshHz: Float) {
+ val current = launch
+ if (current == null || !SessionState.running) {
+ setState(State.FAILED)
+ return
+ }
+ if (owner != -1 && owner != current.generation) stop(context, owner)
+ appContext = context.applicationContext
+ owner = current.generation
+ outputSize = width to height
+ val dir = File(current.sessionDir, "bottom-desktop").apply { mkdirs() }
+ val msg = Message.obtain(null, Comp.MSG_ATTACH).apply {
+ arg1 = owner
+ obj = surface
+ replyTo = replies
+ data = Bundle().apply {
+ putString(Comp.KEY_RUNTIME_DIR, runtimeDir(context).path)
+ putInt(Comp.KEY_WIDTH, width)
+ putInt(Comp.KEY_HEIGHT, height)
+ putFloat(Comp.KEY_REFRESH, refreshHz)
+ putString(Comp.KEY_LOG, File(dir, "wayland.log").path)
+ }
+ }
+ if (state == State.OFF || state == State.ENDED || state == State.FAILED) setState(State.STARTING)
+ val target = service
+ if (target != null) send(target, msg) else {
+ pendingAttach = msg
+ bind(context.applicationContext)
+ }
+ }
+
+ fun detach() {
+ pendingAttach = null
+ service?.let { send(it, Message.obtain(null, Comp.MSG_DETACH)) }
+ }
+
+ fun sendTouch(action: Int, pointerId: Int, x: Int, y: Int) {
+ val target = service ?: return
+ send(target, Message.obtain(null, Comp.MSG_TOUCH, (pointerId shl 8) or (action and 0xff),
+ (x.coerceIn(0, 0xffff) shl 16) or y.coerceIn(0, 0xffff)))
+ }
+
+ fun sendPointer(x: Int, y: Int) {
+ val target = service ?: return
+ send(target, Message.obtain(null, Comp.MSG_POINTER, x, y))
+ }
+
+ /** Button (3), wheel (4) and smooth-scroll (12) input, as `WaylandCompositor.nativeSendSceneInput` takes it. */
+ fun sendScene(type: Int, a: Int, b: Int = 0) {
+ val target = service ?: return
+ send(target, Message.obtain(null, Comp.MSG_SCENE, type, a).apply {
+ if (b != 0) data = Bundle().apply { putInt(Comp.KEY_B, b) }
+ })
+ }
+
+ fun showCursor(on: Boolean) {
+ cursorShown = on
+ service?.let { send(it, Message.obtain(null, Comp.MSG_CURSOR, if (on) 1 else 0, 0)) }
+ }
+
+ /** False when the next attach starts a new compositor process, which needs a surface no earlier one used. */
+ val connected: Boolean get() = service != null
+
+ fun sendKey(evdev: Int, down: Boolean) {
+ val target = service ?: return
+ send(target, Message.obtain(null, Comp.MSG_KEY, evdev, if (down) 1 else 0))
+ }
+
+ fun sendText(text: String) {
+ val target = service ?: return
+ send(target, Message.obtain(null, Comp.MSG_TEXT).apply { data = Bundle().apply { putString(Comp.KEY_TEXT, text) } })
+ }
+
+ fun stop(context: Context, generation: Int? = null) {
+ if (Looper.myLooper() != Looper.getMainLooper()) { main.post { stop(context, generation) }; return }
+ synchronized(launchLock) {
+ if (generation != null && launch?.generation == generation) launch = null
+ }
+ // A newer session may already have prepared its launch; only the desktop the stopped session started goes.
+ if (generation != null && owner != generation) return
+ owner = -1
+ val pid = guestPid
+ guestPid = -1
+ guestGeneration++
+ if (pid > 1) SessionService.stopTerminalProcess(context, pid)
+ service?.let { send(it, Message.obtain(null, Comp.MSG_STOP)) }
+ binding?.let { runCatching { context.applicationContext.unbindService(it) } }
+ binding = null
+ service = null
+ pendingAttach = null
+ imeWatcher?.stopWatching()
+ imeWatcher = null
+ setState(State.OFF)
+ }
+
+ private fun bind(context: Context) {
+ if (binding != null) return
+ val connection = object : ServiceConnection {
+ override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {
+ if (binding !== this || binder == null) return
+ val messenger = Messenger(binder)
+ service = messenger
+ pendingAttach?.let { send(messenger, it) }
+ pendingAttach = null
+ }
+
+ override fun onServiceDisconnected(name: ComponentName?) {
+ if (binding !== this) return
+ Log.w(TAG, "the desktop's compositor process died")
+ service = null
+ binding = null
+ runCatching { context.unbindService(this) }
+ val pid = guestPid
+ guestPid = -1
+ guestGeneration++
+ if (pid > 1) SessionService.stopTerminalProcess(context, pid)
+ imeWatcher?.stopWatching()
+ imeWatcher = null
+ owner = -1
+ setState(State.FAILED)
+ }
+ }
+ binding = connection
+ val bound = runCatching {
+ context.bindService(Intent(context, Comp::class.java), connection,
+ Context.BIND_AUTO_CREATE or Context.BIND_IMPORTANT)
+ }.getOrDefault(false)
+ if (!bound) {
+ Log.e(TAG, "could not bind the desktop's compositor")
+ binding = null
+ setState(State.FAILED)
+ }
+ }
+
+ private fun send(target: Messenger, msg: Message) {
+ runCatching { target.send(msg) }.onFailure { Log.w(TAG, "compositor message ${msg.what} not delivered", it) }
+ }
+
+ private fun runtimeDir(context: Context) = File(context.filesDir, ".wayland-rt-bottom")
+
+ private fun startGuest() {
+ val context = appContext ?: return
+ val current = launch
+ if (current == null || !SessionState.running || current.generation != owner) {
+ setState(State.FAILED)
+ return
+ }
+ // A freeze collects its helpers once, when it begins; a guest started after that would run on unfrozen.
+ if (SessionState.suspended || SessionState.suspending) {
+ setState(State.OFF)
+ return
+ }
+ val generation = ++guestGeneration
+ guestPid = 0
+ val (width, height) = outputSize
+ service?.let { send(it, Message.obtain(null, Comp.MSG_NEW_GUEST)) }
+ Thread({
+ if (!DesktopCatalog.desktopInstalled(current.root)) {
+ Log.e(TAG, "the desktop package is not installed")
+ main.post { if (generation == guestGeneration) { guestPid = -1; setState(State.FAILED) } }
+ return@Thread
+ }
+ val dir = File(current.sessionDir, "bottom-desktop").apply { mkdirs() }
+ val runtime = runtimeDir(context).apply { mkdirs() }
+ val imeDir = File(current.sessionRoot, "bottom-desktop-ime")
+ main.post { if (generation == guestGeneration) watchIme(imeDir) }
+ val binds = LinuxRuntime.binds(context, current.sessionRoot, runtime, Environment.getExternalStorageDirectory(), current.binds)
+ val guest = ArrayList(current.guest).apply {
+ add("BL_WIDTH=$width")
+ add("BL_HEIGHT=$height")
+ add("BL_DEBUG_DIR=" + dir.path)
+ add("BL_TOP_SESSION=" + SessionState.mode)
+ add("BL_IME_DIR=" + imeDir.path)
+ add(SCRIPT)
+ }
+ val command = LinuxRuntime.commandWithBinds(context, current.root, binds, guest)
+ val line = command.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") }
+ val pid = HostProcess.start(line, current.hostEnvironment, current.root, { status ->
+ main.post {
+ if (generation != guestGeneration) return@post
+ Log.i(TAG, "the desktop ended ($status)")
+ SessionService.terminalProcessExited(context, guestPid)
+ guestPid = -1
+ guestGeneration++
+ setState(if (state == State.RUNNING || status == 0) State.ENDED else State.FAILED)
+ }
+ }, null, File(dir, "proot.log"))
+ main.post {
+ if (generation != guestGeneration || launch !== current) {
+ if (pid > 1) SessionService.stopTerminalProcess(context, pid)
+ if (generation == guestGeneration) guestPid = -1
+ return@post
+ }
+ if (pid <= 1) {
+ guestPid = -1
+ Log.e(TAG, "the desktop's guest did not start")
+ setState(State.FAILED)
+ return@post
+ }
+ if (SessionState.suspended || SessionState.suspending) {
+ SessionService.stopTerminalProcess(context, pid)
+ guestPid = -1
+ guestGeneration++
+ setState(State.OFF)
+ return@post
+ }
+ guestPid = pid
+ SessionService.registerTerminalProcess(context, pid)
+ Log.i(TAG, "desktop guest pid $pid at ${width}x$height")
+ }
+ }, "bottom-desktop-start").start()
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/session/BottomNotifications.kt b/app/src/main/java/com/droiddeck/launcher/session/BottomNotifications.kt
index d43b1f6175..45e0890c52 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/BottomNotifications.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/BottomNotifications.kt
@@ -7,13 +7,8 @@ import android.service.notification.StatusBarNotification
import androidx.compose.runtime.mutableStateListOf
import androidx.core.app.NotificationManagerCompat
-/** One notification for the bottom-screen list. Kept in memory only; never written to disk or logs. */
data class BottomNotification(val key: String, val app: String, val title: String, val text: String, val postedAt: Long)
-/**
- * Notifications from other apps for the bottom screen, so a message can be read without leaving the game.
- * Works only after the user allows DroidDeck notification access in Android settings.
- */
object BottomNotifications {
val items = mutableStateListOf()
diff --git a/app/src/main/java/com/droiddeck/launcher/session/BottomScreenshots.kt b/app/src/main/java/com/droiddeck/launcher/session/BottomScreenshots.kt
index 90010a82cb..905f227158 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/BottomScreenshots.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/BottomScreenshots.kt
@@ -12,12 +12,10 @@ import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
-/** A screenshot for the bottom-screen gallery: one DroidDeck took (a MediaStore [uri]) or one Steam saved (a [file]). */
data class BottomShot(val uri: Uri?, val file: File?, val takenAt: Long, val steam: Boolean) {
val model: Any get() = uri ?: file!!
}
-/** Game frames DroidDeck saves to Pictures/DroidDeck, plus the screenshots Steam keeps under userdata. */
object BottomScreenshots {
private const val FOLDER = "DroidDeck"
private const val QUALITY = 95
@@ -58,7 +56,6 @@ object BottomScreenshots {
}
}.getOrDefault(false)
- /** Newest first, at most [LIMIT]. */
fun list(context: Context, runtimeRoot: File): List =
(own(context) + steam(runtimeRoot)).sortedByDescending { it.takenAt }.take(LIMIT)
@@ -85,7 +82,6 @@ object BottomScreenshots {
shots
}.getOrDefault(emptyList())
- /** The .jpg files in userdata//760/remote//screenshots of each Steam home; the thumbnails folder is skipped. */
internal fun steam(runtimeRoot: File): List =
SteamDownloadMonitor.STEAM_HOMES.flatMap { home ->
File(runtimeRoot, "$home/userdata").listFiles { f -> f.isDirectory }.orEmpty().flatMap { account ->
diff --git a/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt b/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt
index 8b7ad50f0c..b1d70902a8 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/ComponentsManager.kt
@@ -34,7 +34,6 @@ object ComponentsManager {
"Dxvk-gplasync-Linux" to "dxvk",
"Vkd3d-proton-Linux" to "vkd3d",
)
- // DD_NIGHTLY holds every component in one release; the file name says which.
private val NIGHTLY_PREFIXES = linkedMapOf("DD-dxvk-" to "dxvk", "DD-vkd3d-proton-" to "vkd3d", "DD-FEXCore-" to "fex")
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY)
private val DOWNLOAD_REPOS = listOf(NIGHTLIES, DD_COMPONENTS)
@@ -976,12 +975,9 @@ object ComponentsManager {
internal fun assetComp(release: String, name: String): String? =
RELEASES[release] ?: if (release == DD_NIGHTLY) NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value else null
- // Per component: the stable packages newest first, then the nightlies.
internal val CATALOG_ORDER: Comparator =
compareBy { it.comp }.thenBy { it.release == DD_NIGHTLY }.then(newestFirst { it.file })
- // A nightly DD--[+N]-nightly.wcp pairs with the newest stable -[-]-linux.wcp
- // in the same list, so the stable row can offer it behind a Stable/Nightly switch. Unpaired nightlies keep their own row.
internal fun nightlyPairs(items: List): Map {
val stable = items.filter { it.release != DD_NIGHTLY }
return items.filter { it.release == DD_NIGHTLY }.mapNotNull { n ->
diff --git a/app/src/main/java/com/droiddeck/launcher/session/DesktopLocale.kt b/app/src/main/java/com/droiddeck/launcher/session/DesktopLocale.kt
new file mode 100644
index 0000000000..68ada01296
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/session/DesktopLocale.kt
@@ -0,0 +1,64 @@
+package com.droiddeck.launcher.session
+
+import java.util.Locale
+
+object DesktopLocale {
+ const val DEFAULT = "C.UTF-8"
+
+ private val regions = mapOf(
+ "en" to "US", "id" to "ID", "ms" to "MY", "cs" to "CZ", "da" to "DK", "de" to "DE",
+ "es" to "ES", "fr" to "FR", "it" to "IT", "hu" to "HU", "nl" to "NL", "nb" to "NO",
+ "pl" to "PL", "pt" to "PT", "ro" to "RO", "fi" to "FI", "sv" to "SE", "vi" to "VN",
+ "tr" to "TR", "el" to "GR", "bg" to "BG", "ru" to "RU", "uk" to "UA", "ar" to "EG",
+ "hi" to "IN", "th" to "TH", "ja" to "JP", "ko" to "KR", "zh" to "CN",
+ )
+
+ private val systemRegions = mapOf(
+ "en" to setOf("US", "GB", "AU", "CA", "IN", "NZ", "IE", "ZA", "SG"),
+ "fr" to setOf("FR", "CA", "BE", "CH", "LU"),
+ "de" to setOf("DE", "AT", "CH", "LU"),
+ "it" to setOf("IT", "CH"),
+ "nl" to setOf("NL", "BE"),
+ "pt" to setOf("PT", "BR"),
+ "sv" to setOf("SE", "FI"),
+ "ar" to setOf("EG", "SA", "AE", "MA", "DZ", "TN", "JO", "KW", "IQ"),
+ )
+
+ private val traditionalRegions = setOf("TW", "HK", "MO")
+
+ fun lang(locale: Locale): String {
+ val language = when (locale.language) {
+ "in" -> "id"
+ "no", "nn" -> "nb"
+ else -> locale.language
+ }
+ val region = when {
+ language == "es" && SteamLanguage.forLocale(locale) == "latam" ->
+ locale.country.takeIf { it.length == 2 && it != "US" } ?: "MX"
+ language == "zh" -> chineseRegion(locale)
+ locale.country in systemRegions[language].orEmpty() -> locale.country
+ else -> regions[language] ?: return DEFAULT
+ }
+ return "${language}_$region.UTF-8"
+ }
+
+ private fun chineseRegion(locale: Locale): String = when {
+ locale.script == "Hans" -> "CN"
+ locale.script == "Hant" -> if (locale.country == "HK") "HK" else "TW"
+ locale.country == "HK" -> "HK"
+ locale.country in traditionalRegions -> "TW"
+ else -> "CN"
+ }
+
+ fun language(locale: Locale): String? {
+ val lang = lang(locale)
+ if (lang == DEFAULT) return null
+ val full = lang.removeSuffix(".UTF-8")
+ val short = full.substringBefore('_')
+ return when {
+ short == "en" -> full
+ full == "zh_HK" -> "zh_HK:zh_TW:zh"
+ else -> "$full:$short"
+ }
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/session/FexCatalog.kt b/app/src/main/java/com/droiddeck/launcher/session/FexCatalog.kt
index 92cd7652da..d3471283e8 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/FexCatalog.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/FexCatalog.kt
@@ -7,11 +7,6 @@ import com.droiddeck.launcher.core.Downloader
import org.json.JSONObject
import java.io.File
-/**
- * The FEX build DroidDeck-Components' fex.json names for x86 programs. A session uses the last copy read.
- * Components' build-fex.yml replaces the archive on its single `fex` release and records the build's version;
- * a release per build (fex-2610-r5) is still read.
- */
object FexCatalog {
private const val TAG = "FexCatalog"
const val CATALOG_URL = "https://raw.githubusercontent.com/Droid-Deck/DroidDeck-Components/main/fex.json"
@@ -43,7 +38,6 @@ object FexCatalog {
fun cached(context: Context): Build? = runCatching { parse(file(context).readText()) }.getOrNull()
- /** Reads fex.json straight from GitHub (a digest never comes from a mirror), at most every ten minutes. */
@Synchronized
fun refresh(context: Context, now: Long = System.currentTimeMillis()): Build? {
if (now - refreshedAt < REFRESH_MS) return cached(context)
@@ -62,7 +56,6 @@ object FexCatalog {
return build
}
- /** For droiddeck-fex-update: the build and every source its archive may come from (it checks the sha256). */
fun environment(build: Build, sources: List = DownloadSource.candidates(build.url)): List = listOf(
"BL_FEX_TAG=${build.tag}",
"BL_FEX_SHA256=${build.sha256}",
diff --git a/app/src/main/java/com/droiddeck/launcher/session/GameStorage.kt b/app/src/main/java/com/droiddeck/launcher/session/GameStorage.kt
index 447fb254c9..eb5bb4e0d9 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/GameStorage.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/GameStorage.kt
@@ -17,7 +17,6 @@ object GameStorage {
val primary = context.getExternalFilesDir(null)?.absolutePath
val primaryStorage = Environment.getExternalStorageDirectory()?.absolutePath
return context.getExternalFilesDirs(null).orEmpty().filterNotNull().mapNotNull { dir ->
- // Non-primary app dirs are usable even when Android reports the volume as non-removable (USB SSDs often do).
if (primary != null && dir.absolutePath == primary) return@mapNotNull null
if (!primaryStorage.isNullOrBlank() && dir.absolutePath.startsWith("$primaryStorage/")) return@mapNotNull null
val volume = try { sm?.getStorageVolume(dir) } catch (e: Exception) { null }
@@ -63,12 +62,14 @@ object GameStorage {
fun gamesFolderLibraries(context: Context): List {
if (SessionPrefs.gameStorage(context).isNotEmpty()) return emptyList()
val card = effective(context)?.let { canonical(File(it.path)) }
+ val added = SteamLibraries.list(context).map { canonical(it.host) }
val sm = context.getSystemService(StorageManager::class.java)
return AddedGames.roots(context).mapNotNull { root ->
val host = canonical(root.host)
if (!hasInstalledGames(root.host)) return@mapNotNull null
if ('"' in root.guest || '\\' in root.guest || !root.host.isDirectory || !root.host.canWrite()) return@mapNotNull null
if (card != null && (host == card || host.startsWith("$card/") || card.startsWith("$host/"))) return@mapNotNull null
+ if (added.any { SteamLibraries.overlaps(it, host) }) return@mapNotNull null
val volume = try { sm?.getStorageVolume(root.host)?.getDescription(context) } catch (e: Exception) { null }
val name = root.host.name.ifEmpty { context.getString(R.string.gstore_folder) }
val label = if (volume.isNullOrBlank()) name else context.getString(R.string.gstore_folder_on_volume, name, volume)
diff --git a/app/src/main/java/com/droiddeck/launcher/session/GameTelemetry.kt b/app/src/main/java/com/droiddeck/launcher/session/GameTelemetry.kt
index 28777f6b06..2a32d817ec 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/GameTelemetry.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/GameTelemetry.kt
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.session
import java.nio.ByteBuffer
import java.nio.ByteOrder
-/** One reading from a racing game's telemetry. Fractions are 0..1; null means the game does not send it. */
data class Telemetry(
val source: String,
val speedKmh: Float? = null,
@@ -19,33 +18,22 @@ data class Telemetry(
val currentLapS: Float? = null,
val lastLapS: Float? = null,
val bestLapS: Float? = null,
- /** G-force as the game sends it (lateral, longitudinal) and steering from -1 (left) to 1 (right). */
val gLat: Float? = null,
val gLon: Float? = null,
val steer: Float? = null,
- /** Front left, front right, rear left, rear right. */
val tireTempsC: List? = null,
val turboBar: Float? = null,
val engineTempC: Float? = null,
val oilTempC: Float? = null,
- /** OutGauge dashboard lights that are on, as GameTelemetry.DL_* bits. */
val lights: Int? = null,
)
-/**
- * Racing telemetry games send over UDP to 127.0.0.1. Each format has its own port, the one the game or
- * its common tools use by default:
- * - [CODEMASTERS_PORT]: DiRT Rally 1/2, DiRT 4, GRID ("extradata 3" float array), DiRT Showdown (152-byte packet).
- * - [FORZA_PORT]: Forza Motorsport 7/2023 and Forza Horizon 4/5 "Data Out" (Sled and Dash).
- * - [OUTGAUGE_PORT]: BeamNG.drive and Live for Speed OutGauge.
- */
object GameTelemetry {
const val CODEMASTERS_PORT = 20777
const val FORZA_PORT = 5300
const val OUTGAUGE_PORT = 4444
val PORTS = listOf(CODEMASTERS_PORT, FORZA_PORT, OUTGAUGE_PORT)
- // Games send to 127.0.0.1; on Android InetAddress.getLoopbackAddress() is ::1, which IPv4 packets never reach.
val LISTEN_ADDRESS: java.net.InetAddress = java.net.InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1))
fun parse(port: Int, data: ByteArray, length: Int): Telemetry? = runCatching {
@@ -61,15 +49,12 @@ object GameTelemetry {
private const val MPS_TO_KMH = 3.6f
private const val GRAVITY = 9.81f
- // OutGauge DashLights / ShowLights bits (Live for Speed InSim; BeamNG uses the same values).
const val DL_SHIFT = 1
const val DL_HANDBRAKE = 4
const val DL_PITSPEED = 8
const val DL_TC = 16
const val DL_ABS = 1024
- // Float indexes of the Codemasters packet; engine rpm values are sent divided by 10. Older games
- // (DiRT Showdown) send only the first 38 floats, so lap count, position, fuel and max rpm are missing there.
private const val CM_LAP_TIME = 1
private const val CM_SPEED = 7
private const val CM_THROTTLE = 29
@@ -99,7 +84,6 @@ object GameTelemetry {
speedKmh = f(CM_SPEED) * MPS_TO_KMH,
rpm = f(CM_RPM) * 10f,
maxRpm = (f(CM_MAX_RPM) * 10f).takeIf { it > 0f },
- // Neutral is 0; DiRT Rally 2.0 reports reverse as 10, older games as -1.
gear = when {
gear == 0 -> "N"
gear < 0 || gear == 10 -> "R"
@@ -119,8 +103,6 @@ object GameTelemetry {
)
}
- // Forza "Data Out": Sled is 232 bytes; the Dash block follows it (FM7 311, FM 2023 331). Horizon 4/5 send
- // 324 bytes with 12 extra bytes before the Dash block.
private const val FORZA_SLED = 232
private const val FORZA_FM7 = 311
private const val FORZA_HORIZON = 324
@@ -140,7 +122,6 @@ object GameTelemetry {
if (dash < 0) return Telemetry(source = "Forza", rpm = rpm, maxRpm = maxRpm.takeIf { it > 0f })
if (!racing) return Telemetry(source = "Forza")
val gear = buf.get(dash + 75).toInt() and 0xFF
- // Tire temperatures are read as Fahrenheit, as community Data Out parsers do; not checked on a device.
val tiresF = (0 until 4).map { buf.getFloat(dash + 24 + it * 4) }
return Telemetry(
source = "Forza",
@@ -163,7 +144,6 @@ object GameTelemetry {
)
}
- // OutGauge: 92 bytes, or 96 with the optional id at the end.
private const val OUTGAUGE_SIZE = 92
internal fun outGauge(buf: ByteBuffer, length: Int): Telemetry? {
@@ -189,14 +169,12 @@ object GameTelemetry {
}
}
-/** Games that publish their state locally without any setup: War Thunder's web page and Elite Dangerous' Status.json. */
object GameStatusFiles {
const val WAR_THUNDER_STATE = "http://127.0.0.1:8111/state"
private const val ELITE_APP = "359320"
private const val ELITE_STATUS = "pfx/drive_c/users/steamuser/Saved Games/Frontier Developments/Elite Dangerous/Status.json"
const val WAR_THUNDER_ROWS = 12
- /** War Thunder's own labels (for example "TAS, km/h") with their values, while a match runs. */
internal fun warThunder(json: String): List> {
val state = org.json.JSONObject(json)
if (!state.optBoolean("valid", false)) return emptyList()
@@ -214,7 +192,6 @@ object GameStatusFiles {
data class Elite(val fuelMain: Double?, val fuelReserve: Double?, val cargo: Double?, val pips: List?, val legal: String?, val balance: Long?)
- /** Null while Elite is at its menus (Status.json then carries only the timestamp and flags). */
internal fun elite(json: String): Elite? {
val s = org.json.JSONObject(json)
val fuel = s.optJSONObject("Fuel")
diff --git a/app/src/main/java/com/droiddeck/launcher/session/GameThreadHints.kt b/app/src/main/java/com/droiddeck/launcher/session/GameThreadHints.kt
index 1b5b90db62..3c2c5098b7 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/GameThreadHints.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/GameThreadHints.kt
@@ -12,54 +12,26 @@ import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import kotlin.math.abs
-/**
- * The game's busiest threads named to Android's performance hint service (ADPF) for a session.
- *
- * Qualcomm's WALT moves a thread to the prime cores only once it fills a mid core (the Odin 3's
- * sched_upmigrate is 95), and a game thread that waits on its workers or the GPU for part of each
- * frame never does: Factorio's update thread sat at ~68% on cores 0-5 with 6-7 idle, and ran 60%
- * faster pinned to 6-7. An app may not raise a thread's uclamp (EPERM without CAP_SYS_NICE), but a
- * hint session may name any thread of its UID - the guest's are - and one reported behind its
- * target is boosted by the power HAL onto the prime cores: on the Odin 3 a 70%-busy thread of a
- * child process went from cores 0-5 to 6-7 and ran 1.7x faster within a second.
- *
- * Once a second the busiest threads of this UID are read from /proc; one busy more than [ENTER] of
- * the time (averaged with the second before, so a loading spike does not count) joins the session,
- * and leaves it under [LEAVE] - well below, since it runs faster where it was moved. While the
- * session has threads it reports them behind target, which is what asks for the boost: the reports
- * carry no frame timing, the busy share is the signal (a capped game's frame interval looks the same
- * as a slow one's). Nothing is boosted while the device is critically hot or saves power.
- *
- * Nor while the game holds the panel's rate or a fraction of it ([holdsPace]): there is nothing to
- * gain, and it cost frame pacing - Serious Sam capped at 120 fps ran its boosted main thread on prime
- * cores the governor kept at 2.2 GHz, slower than a 3.5 GHz mid core, and 23-25% of its frames fell
- * under 90 fps against 2-7% unboosted. A game with no frames (Factorio's benchmark, a loading screen)
- * or one falling behind the panel is boosted; one holding pace keeps what it has for [PACE_LEAVE_S]
- * seconds and is then let go.
- */
object GameThreadHints {
private const val TAG = "GameThreadHints"
private const val TARGET_NS = 10_000_000L
private const val REPORT_MS = 50L
- private const val SCAN_EVERY = 20 // reports, so once a second
+ private const val SCAN_EVERY = 20
private const val ENTER = 0.6
- private const val LEAVE = 0.15 // a capped game's main thread idles to ~30% on a prime core; under 0.3 it hopped back and forth
- private const val MAX_THREADS = 2 // one per prime core; a third would be sped up in place instead
+ private const val LEAVE = 0.15
+ private const val MAX_THREADS = 2
private const val TOP_PROCESSES = 3
private const val PACE_WINDOW_S = 3
private const val PACE_LEAVE_S = 10
private const val PACE_TOLERANCE = 0.08
- /** Busy, but not the game: the app itself and the Steam client, whose UI would otherwise hold the prime cores. */
private val NOT_GAMES = setOf("steam", "steamwebhelper")
private var worker: Thread? = null
- /** At a session's start. The line is for the log. */
@Synchronized
fun start(context: Context): String {
if (!SessionPrefs.gameThreadHints(context)) return "game thread hints: off"
- // Measured on the Odin 3 (CQ8725S) only; another HAL may boost differently, or not at all.
if (Build.VERSION.SDK_INT < 31 || Build.SOC_MODEL != "CQ8725S") return "game thread hints: Odin 3 only"
val hm = context.getSystemService(PerformanceHintManager::class.java)
?: return "game thread hints: no PerformanceHintManager"
@@ -69,7 +41,6 @@ object GameThreadHints {
return "game thread hints: watching"
}
- /** At a session's end. */
@Synchronized
fun stop() {
worker?.interrupt()
@@ -92,7 +63,6 @@ object GameThreadHints {
val fps = (frames.last() - frames.first()).toDouble() / (frames.size - 1).coerceAtLeast(1)
val paced = frames.size > PACE_WINDOW_S && holdsPace(fps, SessionState.refreshHz.toDouble())
pacedFor = if (paced) pacedFor + 1 else 0
- // Not SEVERE: the Odin 3 reports it once its skin reaches 50 C, a couple of minutes into any game.
val spare = pm.isPowerSaveMode || pm.currentThermalStatus >= PowerManager.THERMAL_STATUS_CRITICAL
val next = when {
spare || pacedFor >= PACE_LEAVE_S -> emptySet()
@@ -101,7 +71,6 @@ object GameThreadHints {
}
if (next != boosted) {
session = update(hm, session, next)
- // No session means a thread exited in between: tried again next second.
boosted = if (session == null) emptySet() else next
Log.i(TAG, (if (session == null && next.isNotEmpty()) "no session for " else "boosting ") +
next.joinToString { "${readName("/proc/$it/comm")}/$it ${((busy[it] ?: 0.0) * 100).toInt()}%" }.ifEmpty { "nothing" } +
@@ -119,7 +88,6 @@ object GameThreadHints {
}
}
- /** A new session over [tids] in place of [session]; null for none. The set changes seldom, so no setThreads. */
private fun update(hm: PerformanceHintManager, session: PerformanceHintManager.Session?, tids: Set): PerformanceHintManager.Session? {
session?.close()
if (tids.isEmpty()) return null
@@ -131,19 +99,9 @@ object GameThreadHints {
}
}
- /**
- * Whether a game presenting [fps] frames a second keeps up with a [refreshHz] panel: within
- * [PACE_TOLERANCE] of the rate or of a half, a third or a quarter of it (a 60 fps limiter on 120 Hz).
- * A game with next to no frames (a headless benchmark, a loading screen) does not.
- */
- // ponytail: a CPU-bound game that happens to run at ~60 fps on a 120 Hz panel reads as limited; narrow the band if that shows up
internal fun holdsPace(fps: Double, refreshHz: Double): Boolean =
fps >= 10 && refreshHz > 0 && (1..4).any { k -> abs(fps - refreshHz / k) < PACE_TOLERANCE * refreshHz / k }
- /**
- * The threads to boost next: those already boosted that are still above [LEAVE], then new ones
- * above [ENTER], busiest first, at most [MAX_THREADS].
- */
internal fun pick(boosted: Set, busy: Map): Set =
busy.entries
.filter { (tid, share) -> share >= if (tid in boosted) LEAVE else ENTER }
@@ -154,7 +112,6 @@ object GameThreadHints {
private fun readName(path: String) = try { File(path).readText().trim() } catch (_: Exception) { "?" }
- /** Busy shares of this UID's threads since the last sample: /proc shows an app only its own processes. */
private class Scanner {
private val self = Process.myPid()
private val hz = Os.sysconf(OsConstants._SC_CLK_TCK).toDouble()
@@ -163,7 +120,6 @@ object GameThreadHints {
private var lastThread = HashMap()
private var lastBusy = HashMap()
- /** Only the busiest few processes have their threads read, so a second costs a few dozen small reads. */
fun sample(): Map {
val now = System.nanoTime()
val seconds = (now - lastNs) / 1e9
@@ -197,7 +153,6 @@ object GameThreadHints {
return busy
}
- /** utime + stime of a /proc stat line; fields counted after the command's closing parenthesis. */
private fun cpuTicks(path: String): Long? = try {
val line = File(path).readText()
val fields = line.substring(line.lastIndexOf(')') + 2).split(' ')
diff --git a/app/src/main/java/com/droiddeck/launcher/session/GpuMemComponent.kt b/app/src/main/java/com/droiddeck/launcher/session/GpuMemComponent.kt
index 93214c3d19..a9d55199d2 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/GpuMemComponent.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/GpuMemComponent.kt
@@ -21,7 +21,8 @@ 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) || com.droiddeck.launcher.hud.DroidDeckHudHost.showing)) sample()?.let { write(it) }
+ if (running && (OverlayShown.check(root) || com.droiddeck.launcher.hud.DroidDeckHudHost.showing ||
+ com.droiddeck.launcher.hud.BottomHudPresence.showing)) sample()?.let { write(it) }
}
}, "gpu-mem").apply { isDaemon = true; start() }
}
diff --git a/app/src/main/java/com/droiddeck/launcher/session/GpuStatsComponent.kt b/app/src/main/java/com/droiddeck/launcher/session/GpuStatsComponent.kt
index 0063509167..a5ddcb95d7 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/GpuStatsComponent.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/GpuStatsComponent.kt
@@ -7,10 +7,16 @@ import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import java.io.RandomAccessFile
-class GpuStatsComponent(val dir: File) : SessionPart() {
+class GpuStatsComponent(val dir: File, private val root: File) : SessionPart() {
@Volatile private var running = false
private var thread: Thread? = null
private val feeds = ArrayList()
+ private var layerLoad: LayerLoad? = null
+ private var memstore: KgslBusy.Reader? = null
+ private var memstoreLoad: MemstoreLoad? = null
+ private var memstoreState: String? = null
+ private var cycleClock: KgslClock.Sampler? = null
+ @Volatile private var shown = false
private class Feed(
val file: File, val source: String, val read: () -> Long?, val format: String, val percent: Boolean = false,
@@ -24,9 +30,13 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
}
fun prepare(): Boolean {
+ sources = ""
+ KgslBusy.status = "not tried"
+ KgslClock.status = "not tried"
if (!File(KGSL).exists()) return false
val unreadable = MANGOHUD_FILES.any { File(KGSL, it).let { f -> f.exists() && !f.canRead() } }
- if (!unreadable && !File(GPUBUSY).canRead()) return false
+ // Where SELinux hides the kgsl nodes completely (exists() is false too), the layer and cycle-counter feeds stand in.
+ if (!unreadable && !File(GPUBUSY).canRead() && !loadBlocked()) return false
return try {
dir.mkdirs()
dir.listFiles()?.forEach { java.nio.file.Files.deleteIfExists(it.toPath()) }
@@ -34,19 +44,18 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
PASSTHROUGH_FILES.forEach { name ->
runCatching { File(dir, name).writeText(File(KGSL, name).readText()) }
}
- loadFeed()?.let { load ->
+ (loadFeed() ?: blockedLoadFeed())?.let { load ->
feeds.add(load)
feeds.add(Feed(File(dir, "perf_now"), load.source, load.read, "%-6s\n", percent = true))
}
- pick("clock_mhz", clockSources(), "%5d\n") { mhz(it) }?.let { clock ->
+ (pick("clock_mhz", clockSources(), "%5d\n") { mhz(it) } ?: cycleClockFeed())?.let { clock ->
feeds.add(clock)
feeds.add(Feed(File(dir, "cur_freq"), clock.source, { clock.read()?.times(1_000_000) }, "%-10d\n"))
}
pick("temp", tempSources(), "%6d\n") { milliCelsius(it) }?.let { feeds.add(it) }
refresh()
- Log.i(TAG, "hud: kgsl stats from the session's own: " + MANGOHUD_FILES.joinToString { name ->
- "$name " + (feeds.firstOrNull { it.file.name == name }?.source ?: "none")
- })
+ describeSources()
+ Log.i(TAG, "hud: kgsl stats from the session's own: $sources")
true
} catch (e: Exception) {
Log.w(TAG, "hud: could not stand in for kgsl stats: $e")
@@ -66,19 +75,217 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
}, "gpu-stats").apply { isDaemon = true; start() }
}
- // kgsl's gpubusy can read 0 0 straight after a read, so feeds that share a reader share one read.
private fun refresh() {
+ if (layerLoad != null || cycleClock != null || memstore != null) {
+ shown = hudShown()
+ memstore?.run(shown)
+ if (!shown) memstoreLoad?.pause()
+ layerLoad?.wanted(shown && memstoreLoad?.working != true)
+ }
val values = HashMap<() -> Long?, Long?>()
for (feed in feeds) {
if (feed.read !in values) values[feed.read] = feed.read()
values[feed.read]?.let { write(feed, it) }
}
+ memstoreLoad?.let { load ->
+ val state = when {
+ load.working -> "working"
+ load.failed -> "failed"
+ else -> null
+ }
+ if (state != memstoreState) {
+ memstoreState = state
+ if (load.failed) {
+ memstore?.close()
+ memstore = null
+ KgslBusy.status += ", but the stamps never moved"
+ Log.i(TAG, "hud: kgsl memstore timestamps never moved; GPU load from Vulkan timing")
+ } else if (load.working) {
+ Log.i(TAG, "hud: GPU load from the kgsl memstore (all GPU work)")
+ }
+ describeSources()
+ }
+ }
+ }
+
+ private fun describeSources() {
+ sources = MANGOHUD_FILES.joinToString { name ->
+ val source = if (name == "gpu_busy_percentage" && memstoreLoad != null) memstoreSource()
+ else feeds.firstOrNull { it.file.name == name }?.source
+ "$name " + (source ?: "none")
+ }
+ }
+
+ private fun memstoreSource(): String = when {
+ memstoreLoad?.working == true ->
+ if (memstore?.mode == KgslBusy.MODE_CONTEXTS) "kgsl memstore per-context timestamps (all GPU work)"
+ else "kgsl memstore ringbuffer timestamps (all GPU work)"
+ memstoreLoad?.failed == true -> LAYER_SOURCE
+ else -> "kgsl memstore once its timestamps move; until then $LAYER_SOURCE"
}
override fun stop() {
running = false
thread?.interrupt()
thread = null
+ memstore?.close()
+ memstore = null
+ memstoreLoad = null
+ memstoreState = null
+ layerLoad?.clear()
+ cycleClock?.close()
+ cycleClock = null
+ sources = ""
+ }
+
+ private fun hudShown(): Boolean = OverlayShown.check(root) || com.droiddeck.launcher.hud.DroidDeckHudHost.showing ||
+ com.droiddeck.launcher.hud.BottomHudPresence.showing
+
+ // Android hides the load (kgsl sysfs blocked): the kgsl memstore gives the whole GPU's busy share. The in-game
+ // Vulkan layer and the compositor time their own GPU work until the memstore timestamps are seen moving, and
+ // for the whole session where they never move.
+ private fun blockedLoadFeed(): Feed? {
+ if (!loadBlocked()) return null
+ val load = LayerLoad(guestLoadDir(root), extra = ::compositorBusyNs, onWanted = ::compositorTiming)
+ .also { it.clear(); layerLoad = it }
+ val sampled = KgslBusy.open()?.let { reader ->
+ memstore = reader
+ MemstoreLoad(reader::counts).also { memstoreLoad = it }
+ }
+ val read = read@{
+ if (!shown) return@read null
+ val whole = sampled?.percent()
+ if (sampled?.working == true) whole else load.percent()
+ }
+ return Feed(File(dir, "gpu_busy_percentage"), LAYER_SOURCE, read, "%3d %%\n")
+ }
+
+ // The clock nodes are blocked too: read the GPU's cycle counter from a small GPU job of our own.
+ private fun cycleClockFeed(): Feed? {
+ val sampler = KgslClock.open() ?: return null
+ cycleClock = sampler
+ // clock_mhz and cur_freq both read this; one GPU job per refresh serves both.
+ var at = 0L
+ var last: Long? = null
+ val read = {
+ val now = SystemClock.elapsedRealtime()
+ if (now - at > PERIOD_MS / 2) { at = now; last = if (shown) sampler.mhz()?.toLong() else null }
+ last
+ }
+ return Feed(File(dir, "clock_mhz"), "GPU cycle counter (own GPU job)", read, "%5d\n")
+ }
+
+ private fun compositorBusyNs(): Long? =
+ runCatching { com.droiddeck.launcher.wayland.WaylandCompositor.nativeGpuBusyNs() }.getOrNull()?.takeIf { it >= 0 }
+
+ private fun compositorTiming(on: Boolean) {
+ runCatching { com.droiddeck.launcher.wayland.WaylandCompositor.nativeSetGpuTiming(on) }
+ }
+
+ /**
+ * Busy time the layer (tools/gpuload) writes per process, plus [extra] (the compositor's own GPU time), as a share
+ * of wall time between two reads.
+ */
+ internal class LayerLoad(
+ private val dir: File,
+ private val clock: () -> Long = System::nanoTime,
+ private val extra: () -> Long? = { null },
+ private val onWanted: (Boolean) -> Unit = {},
+ ) {
+ private val last = HashMap()
+ private var lastAt = 0L
+ private var on = false
+
+ fun wanted(on: Boolean) {
+ val flag = File(dir, "on")
+ if (on && !flag.exists()) runCatching { dir.mkdirs(); flag.createNewFile() }
+ if (!on && flag.exists()) { flag.delete(); last.clear(); lastAt = 0L }
+ if (on != this.on) onWanted(on)
+ this.on = on
+ }
+
+ fun percent(): Long? {
+ val now = clock()
+ val files = dir.listFiles { f -> f.name.isNotEmpty() && f.name.all(Char::isDigit) }.orEmpty()
+ var busy = 0L
+ val seen = HashSet()
+ for (file in files) {
+ val total = runCatching { file.readText().trim().substringBefore(' ').toLong() }.getOrNull() ?: continue
+ seen += file.name
+ last[file.name]?.let { if (total >= it) busy += total - it }
+ last[file.name] = total
+ if (System.currentTimeMillis() - file.lastModified() > STALE_MS) file.delete()
+ }
+ extra()?.let { total ->
+ seen += EXTRA
+ last[EXTRA]?.let { if (total >= it) busy += total - it }
+ last[EXTRA] = total
+ }
+ last.keys.retainAll(seen)
+ val wall = now - lastAt
+ val first = lastAt == 0L
+ lastAt = now
+ if (first || wall <= 0) return null
+ return (busy * 100 / wall).coerceIn(0, 100)
+ }
+
+ fun clear() {
+ dir.listFiles()?.forEach { it.delete() }
+ last.clear()
+ lastAt = 0L
+ if (on) onWanted(false)
+ on = false
+ }
+
+ private companion object {
+ const val EXTRA = "compositor"
+ }
+ }
+
+ /**
+ * Busy share over the last [WINDOW] reads from [KgslBusy] running totals (busy samples, samples, samples with
+ * new ringbuffer work). Not [working] until new work has been seen; [failed] once [GIVE_UP_SAMPLES] samples
+ * passed without any.
+ */
+ internal class MemstoreLoad(private val counts: () -> LongArray?) {
+ var working = false
+ private set
+ var failed = false
+ private set
+ private val window = ArrayDeque()
+ private var waited = 0L
+
+ fun percent(): Long? {
+ if (failed) return null
+ val now = counts() ?: return null
+ val previous = window.lastOrNull()
+ window.addLast(now)
+ while (window.size > WINDOW + 1) window.removeFirst()
+ if (previous == null) return null
+ val fresh = now[1] - previous[1]
+ if (fresh <= 0) return null
+ if (!working) {
+ if (now[2] > previous[2]) {
+ working = true
+ } else {
+ waited += fresh
+ if (waited >= GIVE_UP_SAMPLES) failed = true
+ return null
+ }
+ }
+ val base = window.first()
+ return ((now[0] - base[0]) * 100 / (now[1] - base[1])).coerceIn(0, 100)
+ }
+
+ /** The totals stop while sampling is off; the next reading starts a new window. */
+ fun pause() {
+ window.clear()
+ }
+
+ companion object {
+ const val GIVE_UP_SAMPLES = 5_000L
+ const val WINDOW = 2
+ }
}
private fun loadFeed(): Feed? {
@@ -86,8 +293,6 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
return pick("gpu_busy_percentage", LOAD_SOURCES, "%3d %%\n") { it.coerceIn(0, 100) }
}
- // kgsl publishes busy/total once per ~1 s of GPU-on time and zeroes it on any read while the GPU is
- // power-collapsed, so direct pollers mostly see 0; latch each published window instead.
private fun latchedBusyFeed(): Feed? {
var load = 0L
var windowAt = 0L
@@ -134,6 +339,30 @@ class GpuStatsComponent(val dir: File) : SessionPart() {
private const val LOAD_HOLD_MS = 5_000L
private val MANGOHUD_FILES = listOf("gpu_busy_percentage", "clock_mhz", "temp")
private val PASSTHROUGH_FILES = listOf("gpu_model", "gpu_chipid")
+ const val GUEST_LOAD_DIR = "/run/droiddeck-hud/gpu-load"
+ private const val LAYER_SOURCE = "Vulkan timing: games ($GUEST_LOAD_DIR) + DroidDeck compositor"
+
+ /** Where the running session's GPU feeds come from, for the HUD diagnostics export. */
+ @Volatile var sources = ""
+
+ /** Why the no-root GPU readers work or not, for the HUD diagnostics export; empty where they were not needed. */
+ fun readerStatus(): String =
+ if (KgslBusy.status == "not tried" && KgslClock.status == "not tried") ""
+ else "kgsl memstore ${KgslBusy.status}; GPU cycle counter ${KgslClock.status}"
+
+ private const val STALE_MS = 30_000L
+
+ fun guestLoadDir(root: File) = File(root, GUEST_LOAD_DIR.removePrefix("/"))
+
+ /** True when this app can see kgsl but none of its GPU load nodes (SELinux-blocked, e.g. the Retroid Pocket Duo). */
+ fun loadBlocked(): Boolean = File(KGSL).exists() && !File(GPUBUSY).canRead() && LOAD_SOURCES.none { File(it).canRead() }
+
+ /** Turns on the in-game layer (tools/gpuload) where the load is blocked; empty elsewhere. */
+ fun guestEnv(root: File): List {
+ if (!loadBlocked()) return emptyList()
+ guestLoadDir(root).mkdirs()
+ return listOf("DROIDDECK_GPU_LOAD=1", "DROIDDECK_GPU_LOAD_DIR=$GUEST_LOAD_DIR")
+ }
private const val QCOM_GPU = "/sys/kernel/gpu"
private val LOAD_SOURCES = listOf(
"$KGSL/gpu_busy_percentage", "$KGSL/devfreq/gpu_load", "$KGSL/gpuload", "$QCOM_GPU/gpu_busy",
diff --git a/app/src/main/java/com/droiddeck/launcher/session/HwmonComponent.kt b/app/src/main/java/com/droiddeck/launcher/session/HwmonComponent.kt
index 2cd84747d4..66401c7fa0 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/HwmonComponent.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/HwmonComponent.kt
@@ -108,5 +108,9 @@ class HwmonComponent(val dir: File, private val root: File) : SessionPart() {
private fun readNumber(path: String): Long? =
runCatching { File(path).readText().trim().toLong() }.getOrNull()?.takeIf { it >= 0 }
+
+ fun fanSource(): String? = FAN_SOURCES().firstOrNull { readNumber(it) != null }
+
+ fun readRpm(path: String): Long? = readNumber(path)
}
}
diff --git a/app/src/main/java/com/droiddeck/launcher/session/KgslBusy.kt b/app/src/main/java/com/droiddeck/launcher/session/KgslBusy.kt
new file mode 100644
index 0000000000..d3962dd765
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/session/KgslBusy.kt
@@ -0,0 +1,67 @@
+package com.droiddeck.launcher.session
+
+import android.util.Log
+
+/**
+ * Whole-GPU busy share for Adreno devices whose kgsl load nodes are SELinux-blocked for apps
+ * (app/src/main/cpp/gpuclock/kgsl_busy.c). It covers every process's GPU work, Android's own composition included.
+ */
+object KgslBusy {
+ private const val TAG = "SessionService"
+
+ @JvmStatic private external fun nativeOpen(error: IntArray): Long
+ @JvmStatic private external fun nativeMode(handle: Long): Int
+ @JvmStatic private external fun nativeRun(handle: Long, on: Boolean)
+ @JvmStatic private external fun nativeRead(handle: Long, out: LongArray): Boolean
+ @JvmStatic private external fun nativeClose(handle: Long)
+
+ private val loaded: Boolean by lazy {
+ runCatching { System.loadLibrary("gpuclock") }.onFailure { Log.w(TAG, "hud: gpuclock library: $it") }.isSuccess
+ }
+
+ class Reader internal constructor(private var handle: Long) : AutoCloseable {
+ /** Samples once a millisecond while on. */
+ @Synchronized fun run(on: Boolean) {
+ if (handle != 0L) nativeRun(handle, on)
+ }
+
+ /** Which memstore entries are watched: [MODE_RINGBUFFER] or [MODE_CONTEXTS] (hardware-scheduled kernels). */
+ val mode: Int = if (handle != 0L) runCatching { nativeMode(handle) }.getOrDefault(0) else 0
+
+ /** Running totals: busy samples, samples, samples in which a ringbuffer or context started new work. */
+ @Synchronized fun counts(): LongArray? {
+ if (handle == 0L) return null
+ val out = LongArray(3)
+ return if (nativeRead(handle, out)) out else null
+ }
+
+ @Synchronized override fun close() {
+ if (handle != 0L) nativeClose(handle)
+ handle = 0L
+ }
+ }
+
+ const val MODE_RINGBUFFER = 1
+ const val MODE_CONTEXTS = 2
+
+ /** What the last [open] found, for the HUD diagnostics export. */
+ @Volatile var status = "not tried"
+
+ fun open(): Reader? {
+ if (!loaded) {
+ status = "gpuclock library did not load"
+ return null
+ }
+ val error = IntArray(1)
+ val handle = runCatching { nativeOpen(error) }.getOrDefault(0L)
+ if (handle == 0L) {
+ status = "open failed: ${KgslErrors.describe(error[0])}"
+ Log.i(TAG, "hud: no GPU load from the kgsl memstore (open error ${error[0]})")
+ return null
+ }
+ val reader = Reader(handle)
+ status = if (reader.mode == MODE_CONTEXTS) "per-context stamps (hardware-scheduled kernel)" else "ringbuffer stamps"
+ Log.i(TAG, "hud: kgsl memstore reader uses $status")
+ return reader
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/session/KgslClock.kt b/app/src/main/java/com/droiddeck/launcher/session/KgslClock.kt
new file mode 100644
index 0000000000..a8089cb328
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/session/KgslClock.kt
@@ -0,0 +1,72 @@
+package com.droiddeck.launcher.session
+
+import android.util.Log
+
+/**
+ * GPU clock from the GPU's own cycle counter, for Adreno devices whose kgsl clock nodes are SELinux-blocked for
+ * apps (app/src/main/cpp/gpuclock/kgsl_clock.c). Each [mhz] call runs one tiny GPU job, so callers sample only
+ * while a HUD is shown.
+ */
+object KgslClock {
+ private const val TAG = "SessionService"
+
+ @JvmStatic private external fun nativeOpen(error: IntArray): Long
+ @JvmStatic private external fun nativeSample(handle: Long): Int
+ @JvmStatic private external fun nativeClose(handle: Long)
+
+ private val loaded: Boolean by lazy {
+ runCatching { System.loadLibrary("gpuclock") }.onFailure { Log.w(TAG, "hud: gpuclock library: $it") }.isSuccess
+ }
+
+ class Sampler internal constructor(private var handle: Long) : AutoCloseable {
+ /** MHz, or null when this sample was refused or failed its checks. */
+ @Synchronized fun mhz(): Int? = sample().takeIf { it > 0 }
+
+ /** MHz, or a negative native code: -errno from kgsl or [RANGE_CHECK_FAILED]. */
+ @Synchronized fun sample(): Int = if (handle == 0L) CLOSED else nativeSample(handle)
+
+ @Synchronized override fun close() {
+ if (handle != 0L) nativeClose(handle)
+ handle = 0L
+ }
+ }
+
+ /** -EBADF, what the native side also returns for a closed handle. */
+ private const val CLOSED = -9
+
+ /** The native sample code for a reading that failed its range checks (kgsl_clock.c sampler_mhz). */
+ const val RANGE_CHECK_FAILED = -1000
+
+ /** What the last [open] found, for the HUD diagnostics export. */
+ @Volatile var status = "not tried"
+
+ /** A sampler that already produced one good reading, or null (the reason goes to the log and [status]). */
+ fun open(): Sampler? {
+ if (!loaded) {
+ status = "gpuclock library did not load"
+ return null
+ }
+ val error = IntArray(1)
+ val handle = runCatching { nativeOpen(error) }.getOrDefault(0L)
+ if (handle == 0L) {
+ status = "open failed: ${KgslErrors.describe(error[0])}"
+ Log.i(TAG, "hud: no GPU clock from the cycle counter (open error ${error[0]})")
+ return null
+ }
+ val sampler = Sampler(handle)
+ var code = 0
+ val first = (0 until 3).firstNotNullOfOrNull {
+ code = sampler.sample()
+ code.takeIf { it > 0 }
+ }
+ if (first == null) {
+ status = "no usable reading: ${KgslErrors.describe(code)}"
+ Log.i(TAG, "hud: GPU cycle counter gave no usable reading ($code)")
+ sampler.close()
+ return null
+ }
+ status = "working ($first MHz at start)"
+ Log.i(TAG, "hud: GPU clock from the cycle counter ($first MHz now)")
+ return sampler
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/session/KgslErrors.kt b/app/src/main/java/com/droiddeck/launcher/session/KgslErrors.kt
new file mode 100644
index 0000000000..819b627664
--- /dev/null
+++ b/app/src/main/java/com/droiddeck/launcher/session/KgslErrors.kt
@@ -0,0 +1,11 @@
+package com.droiddeck.launcher.session
+
+/** Readable text for the negative errno codes the gpuclock library returns. */
+internal object KgslErrors {
+ fun describe(code: Int): String {
+ if (code == 0) return "no error code"
+ if (code == KgslClock.RANGE_CHECK_FAILED) return "sample out of range"
+ val name = runCatching { android.system.OsConstants.errnoName(-code) }.getOrNull()
+ return if (name != null) "$name ($code)" else "error $code"
+ }
+}
diff --git a/app/src/main/java/com/droiddeck/launcher/session/OfflineMode.kt b/app/src/main/java/com/droiddeck/launcher/session/OfflineMode.kt
index 5632bd27ea..f673f282be 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/OfflineMode.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/OfflineMode.kt
@@ -21,7 +21,6 @@ object OfflineMode {
fun account(context: Context): String? {
val root = LinuxRuntime.rootDir(context)
- // Until its first start the x86-64 client has no sign-in; droiddeck-steam-x64 --sync-login copies the arm64 one.
val file = x64LoginUsers(root).takeIf { SessionPrefs.activeSteamClientArch(context) == "x86_64" && it.isFile }
?: loginUsers(root)
val text = try {
diff --git a/app/src/main/java/com/droiddeck/launcher/session/OrphanReaper.kt b/app/src/main/java/com/droiddeck/launcher/session/OrphanReaper.kt
index 35ac169a77..300306f8c7 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/OrphanReaper.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/OrphanReaper.kt
@@ -11,7 +11,7 @@ object OrphanReaper {
fun release(pid: Int) { kept.remove(pid) }
- fun reap(reason: String): Int {
+ fun reap(reason: String, matching: (String) -> Boolean = { true }): Int {
val me = android.os.Process.myPid()
val uid = android.os.Process.myUid()
val spared = descendants(kept)
@@ -21,6 +21,7 @@ object OrphanReaper {
if (pid == me || pid <= 1 || pid in spared) return@forEach
if (uidOf(pid) != uid) return@forEach
val name = try { File(entry, "cmdline").readText().substringBefore('\u0000') } catch (e: Exception) { "?" }
+ if (!matching(name)) return@forEach
try {
android.os.Process.killProcess(pid)
killed++
diff --git a/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt b/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt
index 5826db97ab..39d99bfa6c 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/RumbleComponent.kt
@@ -214,8 +214,6 @@ class RumbleComponent : SessionPart() {
if (any) manager.vibrate(combined.combine()) else cancel()
}
- // Some vendors' input-device vibrator HALs (Samsung's) don't halt a Bluetooth pad's running
- // effect on cancel(), but a new effect always replaces it.
override fun cancel() {
val supersede = CombinedVibration.startParallel()
ids.forEach { supersede.addVibrator(it, VibrationEffect.createOneShot(1L, 1)) }
@@ -255,7 +253,6 @@ class RumbleComponent : SessionPart() {
private const val TAG = "SessionService"
const val NAME = "droiddeck-rumble"
const val MIN_GAP_MS = 50L
- // Must match RUMBLE_HOLD_MS in fakeinput_steam.cpp.
const val HOLD_MS = 0xFFFF
const val HOLD_EFFECT_MS = 2000L
const val KEEPALIVE_MS = 1500L
diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt
index b4408c48b9..4fc0043043 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt
@@ -31,7 +31,6 @@ object SessionArtifacts {
private val collectingDone = collectingLock.newCondition()
private val collecting = HashSet()
- /** Recovery leaves [dir] alone from the stop until [collect] has finished it. */
fun collectionStarted(dir: File) {
collectingLock.lock()
try { collecting.add(dir) } finally { collectingLock.unlock() }
@@ -317,7 +316,6 @@ object SessionArtifacts {
runCatching { File(dir, CLIENT_FILE).writeText("$arch\n") }
}
- /** The Steam client a session ran, when it recorded one. */
internal fun recordedClient(dir: File): String? =
runCatching { File(dir, CLIENT_FILE).readText().trim() }.getOrNull()?.takeIf { it == "arm64" || it == "x86_64" }
diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt
index 31b9b10988..1cb526c90d 100644
--- a/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt
+++ b/app/src/main/java/com/droiddeck/launcher/session/SessionDisplay.kt
@@ -7,6 +7,10 @@ object SessionDisplay {
const val MATCH_SCREEN = "screen"
const val FOLLOW_SCREEN = "follow"
const val FOLLOW_MIN_SIDE = 480
+ val FOLLOW_SCALES = listOf(1.5f, 2f, 2.5f, 3f, 4f)
+ const val FOLLOW_CUSTOM = "follow/custom"
+ const val FOLLOW_SCALE_MAX = 8f
+ private const val FOLLOW_SCALED_PREFIX = "follow/"
const val DEFAULT_RESOLUTION = "720p"
private val PRESET_HEIGHTS = listOf(720, 900, 1080)
@@ -14,12 +18,30 @@ object SessionDisplay {
fun presetHeight(choice: String): Int? =
if (choice.endsWith("p")) choice.dropLast(1).toIntOrNull()?.takeIf { it > 0 } else null
+ fun followScaled(scale: Float): String = FOLLOW_SCALED_PREFIX + formatScale(scale)
+
+ fun formatScale(scale: Float): String =
+ (Math.round(scale * 10) / 10f).let { if (it % 1f == 0f) it.toInt().toString() else it.toString() }
+
+ fun parseFollowScale(text: String): Float? =
+ text.trim().replace(',', '.').toFloatOrNull()
+ ?.let { Math.round(it * 10) / 10f }?.takeIf { it > 1f && it <= FOLLOW_SCALE_MAX }
+
+ fun isFollow(choice: String): Boolean = followScale(choice) != null
+
+ fun followScale(choice: String): Float? = when {
+ choice == FOLLOW_SCREEN -> 1f
+ choice.startsWith(FOLLOW_SCALED_PREFIX) -> parseFollowScale(choice.removePrefix(FOLLOW_SCALED_PREFIX))
+ else -> null
+ }
+
fun screenSize(panel: Pair): Pair =
(maxOf(panel.first, panel.second) and 1.inv()) to (minOf(panel.first, panel.second) and 1.inv())
fun resolveChoice(panel: Pair, choice: String, portrait: Boolean = false): Pair {
fun orient(size: Pair) = if (portrait) size.second to size.first else size
- if (choice == MATCH_SCREEN || choice == FOLLOW_SCREEN) return orient(screenSize(panel))
+ if (choice == MATCH_SCREEN) return orient(screenSize(panel))
+ followScale(choice)?.let { return orient(scaledDown(screenSize(panel), it)) }
presetHeight(choice)?.let { return orient(resolve(panel, it, SessionPrefs.SHAPE_AUTO)) }
val parts = choice.split('x').map { it.toIntOrNull() }
return if (parts.size == 2 && parts.all { it != null && it > 0 }) parts[0]!! to parts[1]!!
@@ -29,13 +51,16 @@ object SessionDisplay {
fun resolutionOptions(panel: Pair