From e58b463f5486ad1769ca69d5f1812e7bcfec2b40 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:21:32 -0500 Subject: [PATCH 01/29] fix(input): declutter the floating gamepad overlay (#2933) --- .../com/droiddeck/launcher/SessionActivity.kt | 23 +++- .../com/droiddeck/launcher/input/KitLayout.kt | 103 +++++++++++++++--- .../launcher/input/OnScreenControls.kt | 28 +++-- .../launcher/input/OnScreenLayout.kt | 16 ++- .../launcher/session/SessionPrefs.kt | 12 ++ .../droiddeck/launcher/ui/SessionOverlay.kt | 10 ++ app/src/main/res/values/strings.xml | 2 + .../droiddeck/launcher/input/KitLayoutTest.kt | 50 +++++++++ .../launcher/input/ShowLayoutTest.kt | 30 +++++ 9 files changed, 244 insertions(+), 30 deletions(-) diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 42cea423e6..9bf498907d 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -260,7 +260,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var steamController: SteamControllerBle? = null private var onScreenControls: OnScreenControls? = null private var bottomInputControls: OnScreenControls? = null - private var primaryInputLayout: com.droiddeck.launcher.input.SavedInputLayout? = null + private var primaryInputLayout by mutableStateOf(null) private var secondaryInputLayout by mutableStateOf(null) private var steamTouchControls: com.droiddeck.launcher.input.SteamTouchControls? = null private var steamTouchAvailable by mutableStateOf(false) @@ -643,6 +643,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var suspendPolicy by mutableStateOf(SessionPrefs.SUSPEND_MANUAL) private var steamDownloadsInBackground by mutableStateOf(false) private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO) + private var oscRearButtons by mutableStateOf(false) + private var oscTrackpads by mutableStateOf(false) private var onScreenButtonsVisible by mutableStateOf(false) private var layoutOptions by mutableStateOf>>(emptyList()) private var layoutChoice by mutableStateOf("") @@ -1745,6 +1747,23 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde layoutOptions = layoutOptions, layoutChoice = layoutChoice, onLayout = ::chooseLayout, + oscRearButtons = oscRearButtons.takeIf { + unfoldedPanel == null && !usesSteamTouchLayout() && com.droiddeck.launcher.input.PadKit.current(this).steam && + primaryInputLayout?.let(com.droiddeck.launcher.input.OnScreenLayout::hasBuiltInKit) == true + }, + oscTrackpads = oscTrackpads, + onOscRearButtons = { shown -> + SessionPrefs.setOscRearButtons(this, shown) + oscRearButtons = shown + onScreenControls?.reload() + bottomInputControls?.reload() + }, + onOscTrackpads = { shown -> + SessionPrefs.setOscTrackpads(this, shown) + oscTrackpads = shown + onScreenControls?.reload() + bottomInputControls?.reload() + }, onEditLayout = when { layoutChoice == com.droiddeck.launcher.input.GameControls.STEAM -> steamTouchControls?.takeIf { steamTouchAvailable && onScreenButtonsVisible && it.visibility == View.VISIBLE }?.let { view -> { drawerOpen = false @@ -2556,6 +2575,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode) steamDownloadsInBackground = SessionPrefs.steamDownloadsInBackground(this) oscMode = sessionOscMode() + oscRearButtons = SessionPrefs.oscRearButtons(this) + oscTrackpads = SessionPrefs.oscTrackpads(this) backHold = SessionPrefs.backHold(this) backActionsInverted = SessionPrefs.backActionsInverted(this) physicalShortcuts.bindings = PhysicalShortcuts.read(this) diff --git a/app/src/main/java/com/droiddeck/launcher/input/KitLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/KitLayout.kt index ef8322e9ce..d74477a278 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/KitLayout.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/KitLayout.kt @@ -2,6 +2,7 @@ package com.droiddeck.launcher.input import android.content.Context import android.graphics.Rect +import android.graphics.RectF import kotlin.math.max import kotlin.math.min @@ -18,6 +19,12 @@ object KitLayout { /** Whether [id] names one of a kit's own controls rather than a key or control the player added. */ fun isKit(id: String) = id.startsWith("legacy:") || id == DPAD_ID || id == KEYBOARD_ID + internal fun visibleOnOverlay(control: InputControl, rearButtons: Boolean, trackpads: Boolean): Boolean = when (control) { + InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5 -> rearButtons + InputControl.LEFT_PAD, InputControl.RIGHT_PAD -> trackpads + else -> true + } + /** The control a kit id stands for in a layout that keeps no kit positions, so bindings saved for it stay valid. */ fun element(id: String): InputSurfaceElement? = when { id == DPAD_ID -> InputSurfaceElement(InputControl.LS, 0f, 0f, .1f, .1f, id, InputElementKind.DPAD) @@ -72,22 +79,24 @@ object KitLayout { dpad(220f, 345f, 150f)) + face(1375f, 345f, 58f, 96f) + listOf( Spec(InputControl.LS, 290f, 640f, 96f), Spec(InputControl.RS, 1310f, 640f, 96f), Spec(InputControl.LEFT_PAD, 470f, 360f, 88f, shape = InputButtonShape.ROUNDED), Spec(InputControl.RIGHT_PAD, 1130f, 360f, 88f, shape = InputButtonShape.ROUNDED), - Spec(InputControl.SELECT, 660f, 150f, 46f, 26f, shape = InputButtonShape.PILL), Spec(InputControl.START, 940f, 150f, 46f, 26f, shape = InputButtonShape.PILL), + Spec(InputControl.SELECT, 660f, 850f, 46f, 26f, shape = InputButtonShape.PILL), Spec(InputControl.START, 940f, 850f, 46f, 26f, shape = InputButtonShape.PILL), Spec(InputControl.GUIDE, 370f, 852f, 66f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.QAM, 1230f, 852f, 66f, 30f, shape = InputButtonShape.PILL), keyboard(136f)) kit.playStation -> shoulders() + listOf(dpad(250f, 395f, 125f)) + face(1350f, 395f, 58f, 96f) + listOf( Spec(InputControl.LS, 565f, 690f, 100f), Spec(InputControl.RS, 1035f, 690f, 100f), Spec(InputControl.L3, 430f, 590f, 42f, ax = 565f, ay = 690f), Spec(InputControl.R3, 1170f, 590f, 42f, ax = 1035f, ay = 690f), - Spec(InputControl.SELECT, 640f, 150f, 50f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.START, 960f, 150f, 50f, 30f, shape = InputButtonShape.PILL), + Spec(InputControl.SELECT, 640f, 850f, 50f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.START, 960f, 850f, 50f, 30f, shape = InputButtonShape.PILL), Spec(InputControl.GUIDE, 800f, 250f, 46f), Spec(InputControl.QAM, 220f, 848f, 46f), keyboard(136f)) else -> shoulders() + listOf(Spec(InputControl.LS, 235f, 400f, 104f), dpad(470f, 675f, 118f)) + face(1375f, 400f, 58f, 94f) + listOf( Spec(InputControl.RS, 1130f, 690f, 104f), Spec(InputControl.L3, 385f, 290f, 42f, ax = 235f, ay = 400f), Spec(InputControl.R3, 1290f, 790f, 42f, ax = 1130f, ay = 690f), - Spec(InputControl.SELECT, 690f, 162f, 38f), Spec(InputControl.GUIDE, 800f, 162f, 54f), Spec(InputControl.START, 910f, 162f, 38f), + Spec(InputControl.SELECT, 690f, 850f, 38f), Spec(InputControl.GUIDE, 800f, 162f, 54f), Spec(InputControl.START, 910f, 850f, 38f), Spec(InputControl.QAM, 220f, 848f, 46f), keyboard(136f)) } /** The default controls for [kit] on a [width] × [height] screen. */ - fun elements(context: Context, kit: PadKit, width: Int, height: Int, inset: Rect = Rect(), scale: Float = 1f): List { + fun elements(context: Context, kit: PadKit, width: Int, height: Int, inset: Rect = Rect(), scale: Float = 1f, + cutouts: List = emptyList(), rearButtons: Boolean = true, trackpads: Boolean = true, + addedControls: List = emptyList()): List { if (width <= 0 || height <= 0) return emptyList() // Insets stay as reported unless what's left is too small to keep every control above the minimum element size. val smallestUnit = InputSurfaceElement.MIN_SIZE * max(width, height) / (2 * SMALLEST_HALF) @@ -100,6 +109,29 @@ object KitLayout { val (top, bottom) = fit(inset.top, inset.bottom, height, REF_H) val safe = Rect(left, top, right, bottom) if (height > width) return portrait(context, kit, width, height, safe, scale) + .filter { visibleOnOverlay(it.control, rearButtons, trackpads) } + val controls = specs(kit).filter { visibleOnOverlay(it.control, rearButtons, trackpads) } + val leftCutouts = cutouts.filter { inset.left > 0 && it.right <= inset.left } + val rightCutouts = cutouts.filter { inset.right > 0 && it.left >= width - inset.right } + if ((leftCutouts.isNotEmpty() || rightCutouts.isNotEmpty()) && + (left == 0 || leftCutouts.isNotEmpty()) && (right == 0 || rightCutouts.isNotEmpty())) { + val corner = cornerInset(safe, cutouts, height, context.resources.displayMetrics.density) + val fullWidth = landscape(context, kit, width, height, Rect(0, top, 0, bottom), scale, corner, controls) + avoidSideCutouts(fullWidth, leftCutouts, rightCutouts, width, height, addedControls)?.let { return it } + } + return landscape(context, kit, width, height, safe, scale, left, controls) + } + + internal fun cornerInset(inset: Rect, cutouts: List, height: Int, density: Float): Int { + val leftCutouts = cutouts.filter { inset.left > 0 && it.right <= inset.left } + val floor = height - inset.bottom + return if (height <= 0 || leftCutouts.isEmpty() || + leftCutouts.any { it.top < floor && it.bottom > floor - CORNER_DP * density && it.left < CORNER_DP * density }) + inset.left else 0 + } + + private fun landscape(context: Context, kit: PadKit, width: Int, height: Int, safe: Rect, scale: Float, + cornerInset: Int, controls: List): List { val w = width.toFloat(); val h = height.toFloat() val unit = (min(w / REF_W, h / REF_H) * cap(context, min(width, height)) * scale).coerceAtMost(min((w - safe.left - safe.right).coerceAtLeast(1f) / MIN_SPAN, (h - safe.top - safe.bottom).coerceAtLeast(1f) / REF_H)) fun x(ref: Float) = when { @@ -113,22 +145,66 @@ object KitLayout { else -> (h / 2f + (ref - REF_H / 2f) * unit).between(safe.top + ref * unit, h - safe.bottom - (REF_H - ref) * unit) } val density = context.resources.displayMetrics.density - var edge = safe.left + CORNER_DP * density - val specs = specs(kit) - val row = specs.filter { it.cy > REF_H * .88f && it.cx < REF_W / 3f }.sortedBy { it.cx }.associateWith { s -> + var edge = cornerInset + CORNER_DP * density + val row = controls.filter { it.cy > REF_H * .88f && it.cx < REF_W / 3f }.sortedBy { it.cx }.associateWith { s -> val hw = s.hw * unit max(x(s.cx), edge + hw).also { edge = it + hw + GAP_DP * density } } - return specs.map { s -> - val cx = row[s] ?: (x(s.ax) + (s.cx - s.ax) * unit); val cy = y(s.ay) + (s.cy - s.ay) * unit; val hw = s.hw * unit; val hh = s.hh * unit + return controls.map { s -> + val cx = when (s.control) { + InputControl.START, InputControl.SELECT -> (w + safe.left - safe.right) / 2f + (s.cx - REF_W / 2f) * unit + else -> row[s] ?: (x(s.ax) + (s.cx - s.ax) * unit) + } + val cy = y(s.ay) + (s.cy - s.ay) * unit; val hw = s.hw * unit; val hh = s.hh * unit InputSurfaceElement(s.control, (cx - hw) / w, (cy - hh) / h, 2 * hw / w, 2 * hh / h, s.id, s.kind, if (s.name == s.control.label) kit.name(s.control) else s.name, floating = s.kind == InputElementKind.STICK, buttonShape = s.shape, icon = s.icon).bounded() } } + private fun avoidSideCutouts(elements: List, leftCutouts: List, rightCutouts: List, + width: Int, height: Int, addedControls: List): List? { + fun bounds(e: InputSurfaceElement) = RectF(e.x * width, e.y * height, (e.x + e.width) * width, (e.y + e.height) * height) + val boxes = elements.map(::bounds) + val addedBoxes = addedControls.map(::bounds) + // Move a face-button cross or a stick and its click button together. + val groups = elements.indices.groupBy { index -> + val element = elements[index] + when (element.control) { + InputControl.A, InputControl.B, InputControl.X, InputControl.Y -> if (element.id == KEYBOARD_ID) element.id else "face" + InputControl.L3 -> "legacy:ls" + InputControl.R3 -> "legacy:rs" + else -> element.id + } + }.values + val shifts = FloatArray(elements.size) + val left = leftCutouts.map(::RectF) + val right = rightCutouts.map(::RectF) + val obstacles = left + right + for (group in groups) { + val leftEdge = left.filter { cutout -> group.any { RectF.intersects(boxes[it], cutout) } }.maxOfOrNull { it.right } + val rightEdge = right.filter { cutout -> group.any { RectF.intersects(boxes[it], cutout) } }.minOfOrNull { it.left } + val shift = when { + leftEdge != null && rightEdge != null -> return null + leftEdge != null -> leftEdge - group.minOf { boxes[it].left } + 1f + rightEdge != null -> rightEdge - group.maxOf { boxes[it].right } - 1f + else -> continue + } + for (index in group) shifts[index] = shift + } + val moved = boxes.mapIndexed { index, box -> RectF(box).apply { offset(shifts[index], 0f) } } + for (i in moved.indices) { + if (moved[i].left < 0f || moved[i].right > width || obstacles.any { RectF.intersects(moved[i], it) }) return null + if (shifts[i] != 0f && addedBoxes.any { RectF.intersects(moved[i], it) }) return null + for (j in 0 until i) { + if (shifts[i] != shifts[j] && RectF.intersects(moved[i], moved[j]) && !RectF.intersects(boxes[i], boxes[j])) return null + } + } + return elements.mapIndexed { index, e -> e.copy(x = e.x + shifts[index] / width).bounded() } + } + /** * A portrait surface gets the same pad as the panel under the game, in the lower part of the screen, with the keyboard, - * Steam, Quick Access and stick-click buttons in a row along the bottom edge that starts after DroidDeck's corner button. + * Steam, Quick Access, Start, Select and stick-click buttons in a row along the bottom edge. */ private fun portrait(context: Context, kit: PadKit, width: Int, height: Int, safe: Rect, scale: Float): List { val w = width.toFloat(); val h = height.toFloat() @@ -137,15 +213,16 @@ object KitLayout { val inner = (w - safe.left - safe.right).coerceAtLeast(1f) val area = (min(h * .6f, inner * 1.15f) * scale).coerceAtMost(h - safe.top - safe.bottom - row).coerceAtLeast(1f) val top = h - safe.bottom - row - area - val pad = dock(context, kit, inner.toInt(), area.toInt(), true, InputControl.LS, InputControl.RS, upright = true).map { e -> + val pad = dock(context, kit, inner.toInt(), area.toInt(), true, InputControl.LS, InputControl.RS, upright = true) + .filterNot { it.control == InputControl.SELECT || it.control == InputControl.START }.map { e -> e.copy(x = (safe.left + e.x * inner) / w, y = (top + e.y * area) / h, width = e.width * inner / w, height = e.height * area / h, floating = e.kind == InputElementKind.STICK) } val specs = specs(kit) fun spec(control: InputControl, id: String = "legacy:${control.id}") = specs.firstOrNull { it.control == control && it.id == id } val gap = GAP_DP * density - val leftRow = listOfNotNull(spec(InputControl.A, KEYBOARD_ID), spec(InputControl.GUIDE).takeIf { kit.steam }, spec(InputControl.L3)) - val rightRow = listOfNotNull(spec(InputControl.QAM), spec(InputControl.GUIDE).takeIf { !kit.steam }, spec(InputControl.R3)) + val leftRow = listOfNotNull(spec(InputControl.A, KEYBOARD_ID), spec(InputControl.GUIDE).takeIf { kit.steam }, spec(InputControl.L3), spec(InputControl.SELECT)) + val rightRow = listOfNotNull(spec(InputControl.QAM), spec(InputControl.GUIDE).takeIf { !kit.steam }, spec(InputControl.R3), spec(InputControl.START)) val start = safe.left + CORNER_DP * density val span = (w - safe.right - gap - start - gap * (leftRow.size + rightRow.size - 1)).coerceAtLeast(1f) val size = min(BUTTON_DP * density, span / (leftRow + rightRow).sumOf { (it.hw / it.hh).toDouble() }.toFloat()) 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 ef65bb1cf7..65712ad07a 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt @@ -15,6 +15,7 @@ import android.view.View import android.view.ViewConfiguration import android.view.WindowInsets import android.widget.FrameLayout +import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.ui.InputSurfaceView import com.droiddeck.launcher.ui.PadArt @@ -25,6 +26,7 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo private val surface = InputSurfaceView(context, pad, inputRole = InputRole.PRIMARY, haptics = dock != null) private var layout: SavedInputLayout? = null private val safe = Rect() + private var cutouts = emptyList() private var viewWidth = 0 private var viewHeight = 0 private val corner = CornerButton(context) @@ -62,11 +64,22 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo } private fun render() { - val placed = OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, dock) + val placed = OnScreenLayout.elements(context, layout, viewWidth, viewHeight, safe, dock, cutouts, + rearButtons = SessionPrefs.oscRearButtons(context), trackpads = SessionPrefs.oscTrackpads(context)) surface.updateCustomLayout(if (hidden != null) placed.filter { it.alwaysShown } else placed) surface.updateStyle(layout?.style ?: InputSurfaceStyle()) corner.visibility = if (layout == null || dock != null) GONE else VISIBLE corner.alpha = (layout?.style?.opacity ?: 100) / 100f + val density = resources.displayMetrics.density + val margin = (CORNER_MARGIN_DP * density).toInt() + val params = corner.layoutParams as LayoutParams + val leftInset = if (dock == null && viewWidth >= viewHeight && layout?.let(OnScreenLayout::generated) == true) + KitLayout.cornerInset(safe, cutouts, viewHeight, density) else safe.left + if (params.leftMargin != leftInset + margin || params.bottomMargin != safe.bottom + margin) { + params.leftMargin = leftInset + margin + params.bottomMargin = safe.bottom + margin + corner.layoutParams = params + } corner.invalidate() } @@ -91,18 +104,11 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo override fun onApplyWindowInsets(insets: WindowInsets): WindowInsets { val cutout = if (Build.VERSION.SDK_INT >= 28) insets.displayCutout else null - val margin = (CORNER_MARGIN_DP * resources.displayMetrics.density).toInt() - val params = corner.layoutParams as LayoutParams - val left = (cutout?.safeInsetLeft ?: 0) + margin - val bottom = (cutout?.safeInsetBottom ?: 0) + margin - if (params.leftMargin != left || params.bottomMargin != bottom) { - params.leftMargin = left - params.bottomMargin = bottom - corner.layoutParams = params - } val fresh = Rect(cutout?.safeInsetLeft ?: 0, if (dock == null) cutout?.safeInsetTop ?: 0 else 0, cutout?.safeInsetRight ?: 0, cutout?.safeInsetBottom ?: 0) - if (fresh != safe) { + val bounds = cutout?.boundingRects.orEmpty() + if (fresh != safe || bounds != cutouts) { safe.set(fresh) + cutouts = bounds render() } return super.onApplyWindowInsets(insets) diff --git a/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt index 39235de581..0682c43d24 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt @@ -23,19 +23,25 @@ object OnScreenLayout { * The built-in gamepad keeps no kit positions until its kit is edited; until then the kit follows the virtual controller and * the layout stores only the keys and controls the player added on top. */ - fun generated(layout: SavedInputLayout) = (layout.id == InputLibraries.OVERLAY || layout.origin == InputLibraries.OVERLAY) && - !layout.kitless && layout.elements.none { KitLayout.isKit(it.id) } + fun generated(layout: SavedInputLayout) = hasBuiltInKit(layout) && layout.elements.none { KitLayout.isKit(it.id) } - fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect, dock: Dock? = null): List { + fun hasBuiltInKit(layout: SavedInputLayout) = + !layout.kitless && (layout.id == InputLibraries.OVERLAY || layout.origin == InputLibraries.OVERLAY) + + fun elements(context: Context, layout: SavedInputLayout?, width: Int, height: Int, safe: Rect, dock: Dock? = null, + cutouts: List = emptyList(), rearButtons: Boolean = true, trackpads: Boolean = true): List { layout ?: return emptyList() if (width <= 0 || height <= 0) return layout.elements if (generated(layout)) { val kit = PadKit.current(context) val extras = if (layout.elements.isEmpty()) emptyList() else fit(layout.elements, aspect(context, layout), 1f, width, height, safe) return (if (dock != null) KitLayout.dock(context, kit, width, height, dock.portrait, dock.left, dock.right) - else KitLayout.elements(context, kit, width, height, safe, layout.scale)) + extras + else KitLayout.elements(context, kit, width, height, safe, layout.scale, cutouts, rearButtons, trackpads, addedControls = extras)) + extras } - return fit(layout.elements, aspect(context, layout), 1f, width, height, safe) + val elements = if (dock == null && hasBuiltInKit(layout)) layout.elements.filter { element -> + !KitLayout.isKit(element.id) || KitLayout.visibleOnOverlay(element.control, rearButtons, trackpads) + } else layout.elements + return fit(elements, aspect(context, layout), 1f, width, height, safe) } fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false): List = diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 5f62fec93a..62cdbf2d2f 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -678,6 +678,18 @@ object SessionPrefs { editor.putString("osc", mode).apply() } + fun oscRearButtons(context: Context): Boolean = prefs(context).getBoolean("oscRearButtons", false) + + fun setOscRearButtons(context: Context, shown: Boolean) { + prefs(context).edit().putBoolean("oscRearButtons", shown).apply() + } + + fun oscTrackpads(context: Context): Boolean = prefs(context).getBoolean("oscTrackpads", false) + + fun setOscTrackpads(context: Context, shown: Boolean) { + prefs(context).edit().putBoolean("oscTrackpads", shown).apply() + } + /** Draw Steam's touch layout for the game instead of DroidDeck's own. */ fun steamTouchLayout(context: Context): Boolean = prefs(context).getBoolean("steamTouchLayout", prefs(context).getString("osc", null) == OSC_STEAM_TOUCH) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index 5a95a0eacf..beb8f9db31 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -295,6 +295,10 @@ class DrawerActions( val layoutChoice: String = "", val onLayout: (String) -> Unit = {}, val onEditLayout: (() -> Unit)? = null, + val oscRearButtons: Boolean? = null, + val oscTrackpads: Boolean = false, + val onOscRearButtons: (Boolean) -> Unit = {}, + val onOscTrackpads: (Boolean) -> Unit = {}, val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null, val onRumble: (Boolean) -> Unit = {}, val onSuspendPolicy: (String) -> Unit, @@ -676,6 +680,12 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont SessionPrefs.OSC_NEVER to stringResource(R.string.common_never)), a.oscMode, tabModifier = { focus.track(page, "osc-$it") }, onPick = a.onOsc) } + a.oscRearButtons?.let { rearButtons -> + ToggleRow(host, "osc-rear-buttons", stringResource(R.string.osc_rear_buttons), null, rearButtons, + chipModifier = focus.track(page, "osc-rear-buttons"), onChange = a.onOscRearButtons) + ToggleRow(host, "osc-trackpads", stringResource(R.string.osc_trackpads), null, a.oscTrackpads, + chipModifier = focus.track(page, "osc-trackpads"), onChange = a.onOscTrackpads) + } ChoiceRow(host, "touch", stringResource(R.string.input_touches), null, listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.drawer_touch_auto, a.touchAuto), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_mouse), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_GESTURES to stringResource(R.string.mode_touch_gestures), diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 0267b4c098..ad991f6615 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -330,6 +330,8 @@ Steam layout Edit layout Show + Rear buttons + Trackpads More controller settings Shortcuts, latency and the PC keyboard Touches elsewhere diff --git a/app/src/test/java/com/droiddeck/launcher/input/KitLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/input/KitLayoutTest.kt index 944c830201..30e0c32eb6 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/KitLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/KitLayoutTest.kt @@ -113,6 +113,56 @@ class KitLayoutTest { } } + @Test fun aSideCutoutOnlyMovesTheOverlappingCluster() { + val w = 2400 + val h = 1080 + val plain = KitLayout.elements(context, PadKit.STEAM_DECK, w, h, rearButtons = false, trackpads = false) + val left = Rect(10, 380, 120, 480) + val right = Rect(w - 120, 380, w, 480) + val adjusted = KitLayout.elements(context, PadKit.STEAM_DECK, w, h, Rect(120, 0, 120, 0), + cutouts = listOf(left, right), rearButtons = false, trackpads = false) + val face = setOf("legacy:a", "legacy:b", "legacy:x", "legacy:y") + val xOffsets = plain.zip(adjusted).associate { (before, after) -> + assertEquals(before.id, after.id) + assertEquals(before.y, after.y, .00001f) + assertEquals(before.width, after.width, .00001f) + assertEquals(before.height, after.height, .00001f) + assertTrue(after.x * w >= left.right || (after.x + after.width) * w <= left.left || + after.y * h >= left.bottom || (after.y + after.height) * h <= left.top) + assertTrue(after.x * w >= right.right || (after.x + after.width) * w <= right.left || + after.y * h >= right.bottom || (after.y + after.height) * h <= right.top) + before.id to (after.x - before.x) * w + } + assertTrue(xOffsets.getValue(KitLayout.DPAD_ID) in 1f..100f) + assertTrue(xOffsets.getValue("legacy:b") in -100f..-1f) + for ((id, offset) in xOffsets) if (id in face) assertEquals(xOffsets.getValue("legacy:b"), offset, .01f) + else if (id != KitLayout.DPAD_ID) assertEquals(id, 0f, offset, .01f) + assertTrue(overlapping(adjusted, w, h).isEmpty()) + } + + @Test fun aCutoutShiftDoesNotCoverAnAddedControl() { + val w = 2400 + val h = 1080 + val safe = Rect(120, 0, 0, 0) + val extra = InputSurfaceElement(InputControl.B, .05f, .4f, .025f, .06f, id = "added") + val layout = SavedInputLayout(InputLibraries.OVERLAY, "Gamepad", listOf(extra), aspect = w.toFloat() / h) + val fallback = OnScreenLayout.elements(context, layout, w, h, safe, rearButtons = false, trackpads = false) + val placed = OnScreenLayout.elements(context, layout, w, h, safe, cutouts = listOf(Rect(0, 380, 120, 480)), + rearButtons = false, trackpads = false) + assertEquals(fallback, placed) + assertTrue(overlapping(placed, w, h).isEmpty()) + } + + @Test fun startAndSelectAreOnTheFloatingOverlayBottomRow() { + for (kit in PadKit.entries) for ((w, h) in sizes) { + val buttons = KitLayout.elements(context, kit, w, h) + val keyboard = buttons.single { it.id == KitLayout.KEYBOARD_ID } + for (button in buttons.filter { it.control == InputControl.SELECT || it.control == InputControl.START }) { + assertTrue("$kit $w x $h ${button.id}", button.y + button.height / 2 in keyboard.y..(keyboard.y + keyboard.height)) + } + } + } + @Test fun widerScreensSpreadTheControlsInsteadOfStretchingThem() { for (kit in PadKit.entries) { val narrow = KitLayout.elements(context, kit, 1920, 1080).associateBy { it.id } diff --git a/app/src/test/java/com/droiddeck/launcher/input/ShowLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/input/ShowLayoutTest.kt index 34aa4bc095..84909de78e 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/ShowLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/ShowLayoutTest.kt @@ -32,6 +32,36 @@ class ShowLayoutTest { view.releaseInputs() } + @Test fun overlayExtrasAreIndependentAndKeepTheirPreferencesWhenRecreated() { + SessionPrefs.setSteamController(context, SessionPrefs.CONTROLLER_DECK) + val kit = SavedInputLayout(InputLibraries.OVERLAY, "Gamepad") + val grips = setOf(InputControl.L4, InputControl.L5, InputControl.R4, InputControl.R5) + val trackpads = setOf(InputControl.LEFT_PAD, InputControl.RIGHT_PAD) + fun controls(dock: OnScreenLayout.Dock? = null, layout: SavedInputLayout = kit): OnScreenControls = + OnScreenControls(context, null, dock).also { it.updateLayout(layout); sized(it, 1920, 1080) } + fun shown(view: OnScreenControls) = view.inputSurface.shownElements.map { it.control }.toSet() + val overlay = controls() + assertTrue(shown(overlay).intersect(grips + trackpads).isEmpty()) + SessionPrefs.setOscRearButtons(context, true) + overlay.reload() + assertTrue(shown(overlay).containsAll(grips)) + assertTrue(shown(overlay).intersect(trackpads).isEmpty()) + SessionPrefs.setOscTrackpads(context, true) + SessionPrefs.setOscRearButtons(context, false) + assertTrue(shown(controls()).containsAll(trackpads)) + assertTrue(shown(controls()).intersect(grips).isEmpty()) + + SessionPrefs.setOscTrackpads(context, false) + val customPad = InputSurfaceElement(InputControl.LEFT_PAD, .4f, .4f, .15f, .15f, id = "custom-pad") + val edited = kit.copy(elements = listOf(customPad, + InputSurfaceElement(InputControl.RIGHT_PAD, .6f, .4f, .15f, .15f, id = "legacy:right-pad"))) + assertEquals(listOf(customPad.id), controls(layout = edited).inputSurface.shownElements.map { it.id }) + + val dock = OnScreenLayout.Dock(portrait = true, grips = true) + val panel = OnScreenControls(context, null, dock).also { it.updateLayout(kit); sized(it, 1080, 1300) } + assertTrue(shown(panel).containsAll(grips + trackpads)) + } + @Test fun aSavedLayoutIsDrawnAsSaved() { val saved = listOf(InputSurfaceElement(InputControl.A, .4f, .4f, .1f, .1f)) val view = InputSurfaceView(context) From acb2cba970e03b3154e80d24bda69c273252ce79 Mon Sep 17 00:00:00 2001 From: MaxsTechReview Date: Fri, 20 Nov 2026 10:27:17 -0500 Subject: [PATCH 02/29] fix(ci): add-on packs compress the same on every runner (#2938) The proot pack pin check failed on GitHub-hosted runners for PRs that do not touch proot. The hosted image puts the latest upstream zstd (1.5.7) in /usr/local/bin, while the self-hosted runners use zstd 1.5.5, and zstd -19 output differs between those versions for identical tar input. tools/packs/build.sh now compresses every pack with the zstd version pinned in tools/packs/zstd/release.env: the system zstd when it is that version, otherwise the checksum-verified upstream release built once into the pack input cache. --- .github/workflows/build.yml | 2 +- tools/packs/build.sh | 20 +++++++++++++++++++- tools/packs/zstd/release.env | 2 ++ 3 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 tools/packs/zstd/release.env diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 3816c1a52c..cfe3e2d57d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -588,7 +588,7 @@ jobs: path: | ~/.cache/droiddeck-pack-inputs ~/.cache/droiddeck-build - key: pack-inputs-v2-${{ hashFiles('tools/packs/build.sh', 'tools/packs/fetch-verified.sh', 'tools/packs/tracking/release.env', 'tools/powervr/release.json') }} + key: pack-inputs-v2-${{ hashFiles('tools/packs/build.sh', 'tools/packs/fetch-verified.sh', 'tools/packs/tracking/release.env', 'tools/packs/zstd/release.env', 'tools/powervr/release.json') }} restore-keys: pack-inputs-v2- - name: Build the add-on packs run: | diff --git a/tools/packs/build.sh b/tools/packs/build.sh index 2b34c7fc6f..b2a99c6110 100755 --- a/tools/packs/build.sh +++ b/tools/packs/build.sh @@ -11,6 +11,8 @@ linuxfs="$repo/app/src/main/assets/linuxfs/usr/local/lib" source "$here/tracking/release.env" # shellcheck source=butler/release.env source "$here/butler/release.env" +# shellcheck source=zstd/release.env +source "$here/zstd/release.env" work=$(mktemp -d) trap 'rm -rf "$work"' EXIT @@ -21,6 +23,22 @@ fetch() { bash "$here/fetch-verified.sh" "$@" } +zstd_version() { "$1" -V 2>/dev/null | sed -n 's/.* v\([0-9][0-9.]*\),.*/\1/p'; } +zstd=$(command -v zstd || true) +if [ -z "$zstd" ] || [ "$(zstd_version "$zstd")" != "$ZSTD_VERSION" ]; then + zstd="${DROIDDECK_PACK_CACHE:-"$HOME/.cache/droiddeck-pack-inputs"}/zstd-$ZSTD_VERSION/zstd" + if [ ! -x "$zstd" ] || [ "$(zstd_version "$zstd")" != "$ZSTD_VERSION" ]; then + fetch "https://github.com/facebook/zstd/releases/download/v$ZSTD_VERSION/zstd-$ZSTD_VERSION.tar.gz" \ + "$ZSTD_SHA256" "$work/zstd.tar.gz" + tar -xzf "$work/zstd.tar.gz" -C "$work" + make -s -C "$work/zstd-$ZSTD_VERSION" -j"$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 2)" zstd-release >/dev/null + mkdir -p "$(dirname "$zstd")" + install -m755 "$work/zstd-$ZSTD_VERSION/programs/zstd" "$zstd.part.$$" + mv -f "$zstd.part.$$" "$zstd" + fi +fi +[ "$(zstd_version "$zstd")" = "$ZSTD_VERSION" ] || { echo "packs need zstd $ZSTD_VERSION, $zstd is not it" >&2; exit 1; } + pack() { local name=$1 src=$2 shift 2 @@ -47,7 +65,7 @@ with tarfile.open(dest, "w", format=tarfile.USTAR_FORMAT) as tar: with open(path, "rb") as f: tar.addfile(info, f) EOF - zstd -q -19 -f "$work/$name.tar" -o "$out/$name.tar.zst" + "$zstd" -q -19 -f "$work/$name.tar" -o "$out/$name.tar.zst" echo "$name $(sha256 "$out/$name.tar.zst") $(wc -c < "$out/$name.tar.zst" | tr -d ' ')" } diff --git a/tools/packs/zstd/release.env b/tools/packs/zstd/release.env new file mode 100644 index 0000000000..4f69b092bf --- /dev/null +++ b/tools/packs/zstd/release.env @@ -0,0 +1,2 @@ +ZSTD_VERSION=1.5.5 +ZSTD_SHA256=9c4396cc829cfae319a6e2615202e82aad41372073482fce286fac78646d3ee4 From d0022a35f9444b023996f6ad2d6f63a665c9bab2 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:40:10 -0500 Subject: [PATCH 03/29] fix(session): remove the keep-top guard from other displays (#2937) * fix(session): remove the keep-top guard from other displays #2763 put a transparent KeepTopActivity on every other display while a session was on top, so lmkd killing that display's home could not move focus off the session. A/B on a 12 GB AYN Thor (Android 13) and a Retroid Pocket Duo (Android 16) found no case where it kept a session alive: with steady pressure the bottom home (stock launcher or Cocoon) was killed up to 400 times per run without taking focus, and a burst big enough to matter makes lmkd kill the session at adj 0 with or without the guard. Its side effects were real: - Android's ActivityRecordInputSink made the bottom screen ignore touch (worked around in #2910 by stepping aside on touch). - Cocoon tracks each display's top activity, so it could not suspend or resume DroidDeck cleanly. - The Thor's Game Assistant gives every app with an activity on top of the bottom display that display's volume, so DroidDeck's audio followed the bottom screen's volume slider. Removes KeepTopActivity, the focus bounce and light pause, the memory pressure trigger and their tests. onPause runs its departure cleanup every time again. tools/memory_guard_ab.py gains a burst mode, reads oom_score_adj without su (lmkd kills the root manager app and su can then open its request screen over the game), handles Android 13 dumps, a hung stop and a session that does not start. docs/development/memory-guard-ab.md has the Thor results. * test(session): the guard A/B fill mode starts its counter again, and a pressure run with no completed run fails * test(session): the burst seed is rebuilt unless it is exactly 256 MiB * test(session): the guard A/B burst takes its last partial chunk, and only a hog run that finished counts --- app/src/main/AndroidManifest.xml | 9 -- .../com/droiddeck/launcher/SessionActivity.kt | 92 +------------- .../launcher/session/KeepTopActivity.kt | 120 ------------------ .../droiddeck/launcher/session/LightPause.kt | 32 ----- .../launcher/session/SessionService.kt | 3 +- .../launcher/session/TopUnderPressure.kt | 13 -- .../launcher/session/LightPauseTest.kt | 56 -------- .../launcher/session/TopUnderPressureTest.kt | 25 ---- docs/development/memory-guard-ab.md | 59 +++++++-- tools/memory_guard_ab.py | 92 +++++++++++--- tools/tests/test_memory_guard_ab.py | 28 ++++ 11 files changed, 149 insertions(+), 380 deletions(-) delete mode 100644 app/src/main/java/com/droiddeck/launcher/session/KeepTopActivity.kt delete mode 100644 app/src/main/java/com/droiddeck/launcher/session/LightPause.kt delete mode 100644 app/src/main/java/com/droiddeck/launcher/session/TopUnderPressure.kt delete mode 100644 app/src/test/java/com/droiddeck/launcher/session/LightPauseTest.kt delete mode 100644 app/src/test/java/com/droiddeck/launcher/session/TopUnderPressureTest.kt diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index aff5658bbe..30650081fc 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -302,15 +302,6 @@ android:resizeableActivity="true" android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" /> - 0) resizeOutputForWindow(surfaceW, surfaceH) applyUnfoldedControls() @@ -5753,8 +5746,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) { - if (::pip.isInitialized && intent.component?.className != com.droiddeck.launcher.session.KeepTopActivity::class.java.name && - (requestCode >= 0 || intent.component?.packageName == packageName || + if (::pip.isInitialized && (requestCode >= 0 || intent.component?.packageName == packageName || intent.action in setOf(Intent.ACTION_CHOOSER, Intent.ACTION_SEND, Intent.ACTION_OPEN_DOCUMENT, Intent.ACTION_GET_CONTENT, "android.settings.PICTURE_IN_PICTURE_SETTINGS"))) pip.background() super.startActivityForResult(intent, requestCode, options) @@ -5786,10 +5778,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } override fun onStop() { - if (lightPause.stopped()) departureCleanup() - uiHandler.removeCallbacks(guardWhenRunning) - uiHandler.removeCallbacks(rearmAfterYield) - com.droiddeck.launcher.session.KeepTopActivity.stepAside() if (runtimeRemovalBlocked) { super.onStop(); return } started = false if (::hud.isInitialized) hud.setBackgrounded(true) @@ -5834,13 +5822,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde override fun onResume() { super.onResume() - com.droiddeck.launcher.session.KeepTopActivity.onYield = onGuardYield - uiHandler.removeCallbacks(lightPauseCheck) - when (lightPause.resumed(com.droiddeck.launcher.session.KeepTopActivity.bounces)) { - com.droiddeck.launcher.session.LightPause.Resume.LIGHT -> return - com.droiddeck.launcher.session.LightPause.Resume.CLEANUP_FIRST -> departureCleanup() - com.droiddeck.launcher.session.LightPause.Resume.NORMAL -> Unit - } drawerGameInventoryRevision++ com.droiddeck.launcher.input.SystemKeyCapture.attach(this, { hasWindowFocus() && !appUiOwnsPointer() && CompositorHost.isStarted }) { event -> com.droiddeck.launcher.input.GuestKeys.send(event) { code, down -> sendGuestKey(code, down, 8) } @@ -5906,73 +5887,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde SessionPrefs.sessionPrefs(this).registerOnSharedPreferenceChangeListener(cardboardPrefListener) } - private var memoryPressureAt = 0L - private var focusBounce = false - private val lightPause = com.droiddeck.launcher.session.LightPause() - private val lightPauseCheck = Runnable { if (lightPause.timedOut()) departureCleanup() } - private var topResumed = false - private val guardWhenRunning = object : Runnable { - override fun run() { - if (!topResumed || isFinishing) return - if (SessionState.running) guardOtherDisplays() else uiHandler.postDelayed(this, 2_000) - } - } - - // A touch that removed a guard while the session kept the top spot did not move focus to that - // display, so the guard comes back unless the user carries on there. - private val rearmAfterYield = Runnable { - if (topResumed && !isFinishing) { - com.droiddeck.launcher.session.KeepTopActivity.rearm() - guardOtherDisplays() - } - } - private val onGuardYield: () -> Unit = { - uiHandler.removeCallbacks(rearmAfterYield) - uiHandler.postDelayed(rearmAfterYield, com.droiddeck.launcher.session.KeepTopActivity.YIELD_GRACE_MS) - } - - // RUNNING_LOW and RUNNING_CRITICAL are not delivered from API 34, so the guard also goes up - // as soon as a running session is on top. - override fun onTrimMemory(level: Int) { - super.onTrimMemory(level) - if (!com.droiddeck.launcher.session.TopUnderPressure.isPressure(level)) return - memoryPressureAt = android.os.SystemClock.elapsedRealtime() - guardOtherDisplays() - } - - override fun onTopResumedActivityChanged(isTopResumedActivity: Boolean) { - super.onTopResumedActivityChanged(isTopResumedActivity) - topResumed = isTopResumedActivity - uiHandler.removeCallbacks(guardWhenRunning) - uiHandler.removeCallbacks(rearmAfterYield) - if (isTopResumedActivity) { - com.droiddeck.launcher.session.KeepTopActivity.rearm() - uiHandler.post(guardWhenRunning) - } - else if (com.droiddeck.launcher.session.TopUnderPressure.shouldReclaim( - android.os.SystemClock.elapsedRealtime(), memoryPressureAt, SessionState.running, isFinishing)) guardOtherDisplays() - } - - private fun guardOtherDisplays() { - if (!SessionState.running || isFinishing || isInPictureInPictureMode) return - val wasResumed = lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED) - val bounced = com.droiddeck.launcher.session.KeepTopActivity.guardOtherDisplays(this, display?.displayId ?: android.view.Display.DEFAULT_DISPLAY) - if (com.droiddeck.launcher.session.KeepTopActivity.hasPendingStarts()) { - uiHandler.removeCallbacks(guardWhenRunning) - uiHandler.postDelayed(guardWhenRunning, com.droiddeck.launcher.session.KeepTopActivity.RETRY_MS) - } - if (!bounced) return - if (!wasResumed) return - focusBounce = true - uiHandler.postDelayed({ focusBounce = false }, 500) - } - override fun onPause() { - if (focusBounce) { - focusBounce = false - lightPause.paused(com.droiddeck.launcher.session.KeepTopActivity.bounces) - uiHandler.postDelayed(lightPauseCheck, 200) - } else departureCleanup() + departureCleanup() super.onPause() } @@ -6635,10 +6551,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } override fun onDestroy() { - uiHandler.removeCallbacks(guardWhenRunning) - uiHandler.removeCallbacks(rearmAfterYield) - if (com.droiddeck.launcher.session.KeepTopActivity.onYield === onGuardYield) com.droiddeck.launcher.session.KeepTopActivity.onYield = null - com.droiddeck.launcher.session.KeepTopActivity.release() synchronized(frameGenGlobalLock) { frameGenActivityActive = false frameGenRequests.incrementAndGet() diff --git a/app/src/main/java/com/droiddeck/launcher/session/KeepTopActivity.kt b/app/src/main/java/com/droiddeck/launcher/session/KeepTopActivity.kt deleted file mode 100644 index 109f6d282a..0000000000 --- a/app/src/main/java/com/droiddeck/launcher/session/KeepTopActivity.kt +++ /dev/null @@ -1,120 +0,0 @@ -package com.droiddeck.launcher.session - -import android.app.Activity -import android.app.ActivityOptions -import android.content.Context -import android.content.Intent -import android.hardware.display.DisplayManager -import android.os.Bundle -import android.os.SystemClock -import android.util.Log -import android.view.Display -import android.view.MotionEvent -import android.view.WindowManager - -// While a session is on screen, sits invisibly on top of every other display, so that display's -// home launcher is not its top activity. lmkd kills the launcher first; restarted as a top activity -// it takes focus from the session, which then drops to adj 50 and is killed next. -// Android gives a translucent activity alone in its task an input sink that eats every touch on the -// display whatever its window flags say, so a touch makes the guard leave that display until the -// session is back on top. -class KeepTopActivity : Activity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - @Suppress("DEPRECATION") overridePendingTransition(0, 0) - if (intent.getBooleanExtra(EXTRA_BOUNCE, false)) { - bounces++ - finish() - return - } - if (intent.getIntExtra(EXTRA_GENERATION, -1) != generation) { - finishAndRemoveTask() - return - } - window.addFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) - val id = display?.displayId ?: Display.INVALID_DISPLAY - starting.remove(id) - if (id in yielded) { - finishAndRemoveTask() - return - } - guards[id]?.takeIf { it !== this && !it.isFinishing }?.finishAndRemoveTask() - guards[id] = this - } - - override fun dispatchTouchEvent(event: MotionEvent): Boolean { - if (event.actionMasked == MotionEvent.ACTION_DOWN && !isFinishing) { - val id = display?.displayId ?: Display.INVALID_DISPLAY - yielded.add(id) - Log.i(TAG, "display $id touched, leaving it to the app below") - finishAndRemoveTask() - onYield?.invoke() - } - return true - } - - override fun onDestroy() { - guards.values.remove(this) - super.onDestroy() - } - - companion object { - private const val TAG = "KeepTop" - private const val EXTRA_BOUNCE = "bounce" - private const val EXTRA_GENERATION = "generation" - private var generation = 0 - var bounces = 0 - private set - private val guards = HashMap() - private const val START_TIMEOUT_MS = 2_000L - private val starting = HashMap() - private val yielded = HashSet() - const val YIELD_GRACE_MS = 5_000L - var onYield: (() -> Unit)? = null - - fun rearm() = yielded.clear() - - fun guardOtherDisplays(context: Context, sessionDisplay: Int): Boolean { - val displays = context.getSystemService(DisplayManager::class.java)?.displays ?: return false - var started = false - for (display in displays) { - val id = display.displayId - if (id == sessionDisplay || id in yielded || display.state != Display.STATE_ON || guards[id]?.isFinishing == false || - starting[id]?.let { SystemClock.elapsedRealtime() - it < START_TIMEOUT_MS } == true) continue - runCatching { - launch(context, id, bounce = false) - starting[id] = SystemClock.elapsedRealtime() - started = true - Log.i(TAG, "guarding display $id from a home launcher restart") - }.onFailure { Log.w(TAG, "could not guard display $id", it) } - } - if (!started) return false - return runCatching { launch(context, sessionDisplay, bounce = true) } - .onFailure { Log.w(TAG, "could not return focus to display $sessionDisplay", it) }.isSuccess - } - - fun hasPendingStarts() = starting.isNotEmpty() - - const val RETRY_MS = START_TIMEOUT_MS + 250 - - fun stepAside() { - generation++ - guards.values.toList().forEach { it.finishAndRemoveTask() } - guards.clear() - starting.clear() - } - - fun release() { - stepAside() - yielded.clear() - } - - private fun launch(context: Context, displayId: Int, bounce: Boolean) { - val intent = Intent(context, KeepTopActivity::class.java) - .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION) - .putExtra(EXTRA_BOUNCE, bounce) - .putExtra(EXTRA_GENERATION, generation) - context.startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(displayId).toBundle()) - } - } -} diff --git a/app/src/main/java/com/droiddeck/launcher/session/LightPause.kt b/app/src/main/java/com/droiddeck/launcher/session/LightPause.kt deleted file mode 100644 index 6ac1eabf9f..0000000000 --- a/app/src/main/java/com/droiddeck/launcher/session/LightPause.kt +++ /dev/null @@ -1,32 +0,0 @@ -package com.droiddeck.launcher.session - -// Tracks a pause that skipped the session's departure cleanup for the keep-top focus bounce. -internal class LightPause { - private var pending = false - private var bouncesAtPause = 0 - - fun paused(bounces: Int) { - pending = true - bouncesAtPause = bounces - } - - // The bounce resumes the session within tens of milliseconds; still paused at the timeout means - // something else holds the pause. - fun timedOut(): Boolean = take() - - fun stopped(): Boolean = take() - - fun resumed(bounces: Int): Resume { - if (!pending) return Resume.NORMAL - pending = false - return if (bounces != bouncesAtPause) Resume.LIGHT else Resume.CLEANUP_FIRST - } - - private fun take(): Boolean { - val was = pending - pending = false - return was - } - - enum class Resume { NORMAL, LIGHT, CLEANUP_FIRST } -} diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index e15fac1c64..94664b4697 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -2394,8 +2394,7 @@ class SessionService : Service() { override fun onTaskRemoved(rootIntent: Intent?) { if (rootIntent?.component?.className in setOf( com.droiddeck.launcher.ui.DualScreenActivity::class.java.name, - com.droiddeck.launcher.ui.SessionTypingActivity::class.java.name, - KeepTopActivity::class.java.name)) return + com.droiddeck.launcher.ui.SessionTypingActivity::class.java.name)) return if (pipTask || xrActivityVisible) { Log.i(TAG, "panel task dismissed - retaining the session under its active surface policy") activityVisible = false diff --git a/app/src/main/java/com/droiddeck/launcher/session/TopUnderPressure.kt b/app/src/main/java/com/droiddeck/launcher/session/TopUnderPressure.kt deleted file mode 100644 index 3c7a55adea..0000000000 --- a/app/src/main/java/com/droiddeck/launcher/session/TopUnderPressure.kt +++ /dev/null @@ -1,13 +0,0 @@ -package com.droiddeck.launcher.session - -import android.content.ComponentCallbacks2 - -internal object TopUnderPressure { - const val WINDOW_MS = 5_000L - - fun isPressure(level: Int) = - level == ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL || level == ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW - - fun shouldReclaim(nowMs: Long, pressureAtMs: Long, sessionRunning: Boolean, finishing: Boolean) = - sessionRunning && !finishing && pressureAtMs > 0 && nowMs - pressureAtMs in 0..WINDOW_MS -} diff --git a/app/src/test/java/com/droiddeck/launcher/session/LightPauseTest.kt b/app/src/test/java/com/droiddeck/launcher/session/LightPauseTest.kt deleted file mode 100644 index 8e14b74147..0000000000 --- a/app/src/test/java/com/droiddeck/launcher/session/LightPauseTest.kt +++ /dev/null @@ -1,56 +0,0 @@ -package com.droiddeck.launcher.session - -import org.junit.Assert.assertEquals -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test - -class LightPauseTest { - @Test - fun theBounceAloneResumesLight() { - val pause = LightPause() - pause.paused(bounces = 3) - assertEquals(LightPause.Resume.LIGHT, pause.resumed(bounces = 4)) - assertFalse(pause.timedOut()) - } - - @Test - fun anUnrelatedPauseWithoutABounceCleansUpAtTheTimeout() { - val pause = LightPause() - pause.paused(bounces = 3) - assertTrue(pause.timedOut()) - assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 3)) - } - - @Test - fun aBounceWhileAnotherActivityHoldsThePauseStillCleansUpAtTheTimeout() { - val pause = LightPause() - pause.paused(bounces = 3) - assertTrue(pause.timedOut()) - assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 4)) - } - - @Test - fun aResumeBeforeTheTimeoutWithoutABounceCleansUpFirst() { - val pause = LightPause() - pause.paused(bounces = 3) - assertEquals(LightPause.Resume.CLEANUP_FIRST, pause.resumed(bounces = 3)) - assertFalse(pause.timedOut()) - } - - @Test - fun aStopAfterALightPauseCleansUpOnce() { - val pause = LightPause() - pause.paused(bounces = 3) - assertTrue(pause.stopped()) - assertFalse(pause.timedOut()) - assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 4)) - } - - @Test - fun aNormalPauseIsUntouched() { - val pause = LightPause() - assertFalse(pause.stopped()) - assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 0)) - } -} diff --git a/app/src/test/java/com/droiddeck/launcher/session/TopUnderPressureTest.kt b/app/src/test/java/com/droiddeck/launcher/session/TopUnderPressureTest.kt deleted file mode 100644 index ac0ec06843..0000000000 --- a/app/src/test/java/com/droiddeck/launcher/session/TopUnderPressureTest.kt +++ /dev/null @@ -1,25 +0,0 @@ -package com.droiddeck.launcher.session - -import android.content.ComponentCallbacks2 -import org.junit.Assert.assertFalse -import org.junit.Assert.assertTrue -import org.junit.Test - -class TopUnderPressureTest { - @Test - fun onlyRunningLevelsCountAsPressure() { - assertTrue(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL)) - assertTrue(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW)) - assertFalse(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE)) - assertFalse(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN)) - } - - @Test - fun reclaimsOnlyDuringASessionShortlyAfterPressure() { - assertTrue(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = true, finishing = false)) - assertFalse(TopUnderPressure.shouldReclaim(20_000, 9_500, sessionRunning = true, finishing = false)) - assertFalse(TopUnderPressure.shouldReclaim(10_000, 0, sessionRunning = true, finishing = false)) - assertFalse(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = false, finishing = false)) - assertFalse(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = true, finishing = true)) - } -} diff --git a/docs/development/memory-guard-ab.md b/docs/development/memory-guard-ab.md index 4ac8d1a214..ded09a59f4 100644 --- a/docs/development/memory-guard-ab.md +++ b/docs/development/memory-guard-ab.md @@ -1,20 +1,24 @@ # Keep-top guard A/B on dual screens -`KeepTopActivity` (#2763) covers every other display while a session is on top, so that -display's home is not its top activity. On the Thor, lmkd kills the bottom home under memory -pressure, Android relaunches it to the front (`wm_task_to_front`), the session loses the top -spot, drops to adj 50 and is killed in lmkd's next pass. +`KeepTopActivity` (#2763, removed in the change that added this section) covered every other +display while a session was on top, so that display's home was not its top activity. The +reasoning: on the Thor, lmkd kills the bottom home under memory pressure, Android relaunches it +to the front, the session loses the top spot, drops to adj 50 and is killed next. -Android gives a translucent activity that is alone in its task an `ActivityRecordInputSink` -that consumes every touch inside the task bounds, whatever the window's flags say -(`ENABLE_TOUCH_OPAQUE_ACTIVITIES`, on for DroidDeck's target SDK; see -`services/core/java/com/android/server/wm/ActivityRecordInputSink.java`). The guard's -`FLAG_NOT_TOUCHABLE` therefore did nothing: with the dual-screen panel closed, the bottom -screen took no touch until the session ended, and the guard also stayed over it after Home. +It had three side effects: -The guard now takes touches itself. A touch removes it from that display. It comes back when -the session is top-resumed again, or after 5 s if the session kept the top spot (one touch on -the bottom screen, then back to the game). Stopping or entering PiP removes the guards. +- Android gives a translucent activity alone in its task an `ActivityRecordInputSink` that + consumes every touch in the task bounds whatever the window's flags say + (`ENABLE_TOUCH_OPAQUE_ACTIVITIES`), so the bottom screen took no touch (#2910 worked around it). +- Cocoon tracks the top activity of each display; with a DroidDeck activity on the bottom it + could not suspend or resume DroidDeck properly. +- The Thor's `com.odin.gameassistant` gives every app with an activity on top of the bottom + display that display's volume (`secondary_screen_volume_level`). With the guard up, all of + DroidDeck's audio played at the bottom screen's volume (AudioFlinger track gain -37, -13 and + -2.6 dB at levels 3, 8 and 13; -7.4 dB, the top level, once the guard was removed). + +The A/B below found no case on either device where the guard kept the session alive, so it was +removed. ## Tool @@ -25,6 +29,7 @@ build that has the debugging tools: python3 tools/memory_guard_ab.py --label main --apk main.apk states python3 tools/memory_guard_ab.py --label fix --apk fix.apk states python3 tools/memory_guard_ab.py --label fix pressure --stop-mb 650 --hold 30 --runs 3 +python3 tools/memory_guard_ab.py --label fix pressure --burst --stop-mb 1500 --hold 20 --runs 3 python3 tools/memory_guard_ab.py --label fix summarize ~/.cache/droiddeck-memory-guard-ab/fix-stop650-1-events.txt ``` @@ -39,6 +44,13 @@ event log of every probe. `--stop-mb`, holds it, and releases it. zram cannot compress that data and no app owns it, so lmkd keeps killing by adj. It records lmkd's `killinfo`, process deaths, focus loss and whether DroidDeck survived. +- `pressure --burst` takes everything above `--stop-mb` at once instead: it copies a 256 MiB + random file into the tmpfs with all copies running in parallel (about 5 GiB in 2 to 3 s on a + Thor), the way a game's GPU allocation burst lands on lmkd. +- `oom_score_adj` is read without `su`. Under pressure lmkd keeps killing the root manager app, + and a `su` call can then open its request screen on top of the game. +- If the bottom display has no home (a killed home is not always restarted), the visible app on + top of it stands in. - `--bottom-tap` must point at an inert spot of the bottom home; `--panel-close` at the panel's close button. Both are fractions of the bottom display. - `am start` of `SessionActivity` needs `--display 0`; without it, it creates a second @@ -88,3 +100,24 @@ moves it to the front, even with no guard. The Thor's focus steal does not happe Duo shows that the guard covers the same states as before, not that it saves the session. That needs a Thor: run `states` and `pressure --stop-mb` near its adj-50 level on `main` and on the fix, and look for `task_to_front` and `session_top_lost` before `droiddeck_died_at_adj` 50. + +## Results: AYN Thor (12 GB), Android 13 + +Builds: `main` (56986b5, guard with the #2910 touch yield) and `no-guard` (`main` with +`guardOtherDisplays` returning at once). The game was focused on the top screen in every run. + +| Pressure | Bottom app | no-guard | main | +| --- | --- | --- | --- | +| Fill to 650 MB free, hold 30 s | stock launcher | survived 1/1 usable run (launcher not reached) | survived 3/3 (launcher killed 80, 25, 0 times) | +| Fill to 550 MB free, hold 30 s | Cocoon as home | survived 3/3, Cocoon killed 387, 400, 84 times | survived 3/3, Cocoon killed 384, 127, 338 times | +| Burst to 400 MB free (about 5 GB in 2.5 to 3.4 s) | stock launcher | killed at adj 0 in 3/3 | killed at adj 0 in 3/3 | +| Burst to 1500 MB free (2.0 to 2.4 s) | stock launcher | survived 1/2, killed at adj 0 in 1/2 | killed at adj 0 in 2/2 | + +No run on either build lost the top spot (`wm_on_top_resumed_lost_called` for +`SessionActivity`), moved a task to the front, or killed DroidDeck at adj 50. A killed bottom +home is either restarted in place or its task disappears and the next app shows on the bottom +screen, without taking focus. A burst big enough to matter makes lmkd kill the foreground +session at adj 0, which no activity on another display can prevent. + +`kill -9` of the bottom app (`states`) is noisy on a Thor with many recent apps: each kill +surfaces the next app on the bottom screen, and every tap the tool sends there moves focus. diff --git a/tools/memory_guard_ab.py b/tools/memory_guard_ab.py index 0bcd81d6d6..9aa2fa21a7 100755 --- a/tools/memory_guard_ab.py +++ b/tools/memory_guard_ab.py @@ -26,30 +26,52 @@ PACKAGE = "com.droiddeck.launcher" SESSION = f"{PACKAGE}/.SessionActivity" HOG_PATH = "/data/local/tmp/dd-memory-hog.sh" HOG_MOUNT = "/dev/dd-memory-hog" +SEED_PATH = "/data/local/tmp/dd-memory-burst.bin" +# oom_score_adj is read without su: under pressure lmkd kills the root manager app, and each su call +# can then open its request screen on top of the game. # Incompressible data in a private tmpfs: zram cannot shrink it and no app owns it, so lmkd keeps # killing by oom_score_adj while it is held. HOG = f"""#!/system/bin/sh -stop_mb=$1; hold=$2 -cleanup() {{ rm -f {HOG_MOUNT}/f*; umount {HOG_MOUNT} 2>/dev/null; }} +stop_mb=$1; hold=$2; mode=$3 +cleanup() {{ kill $(jobs -p) 2>/dev/null; rm -f {HOG_MOUNT}/f*; umount {HOG_MOUNT} 2>/dev/null; }} trap 'cleanup; exit 1' HUP INT TERM mkdir -p {HOG_MOUNT} grep -q ' {HOG_MOUNT} ' /proc/mounts || mount -t tmpfs -o size=16g tmpfs {HOG_MOUNT} -i=0 +i=0; failed=0 +if [ "$mode" = burst ]; then + [ "$(stat -c %s {SEED_PATH} 2>/dev/null)" = 268435456 ] || + {{ head -c 268435456 /dev/urandom > {SEED_PATH}.tmp && mv {SEED_PATH}.tmp {SEED_PATH}; }} || + {{ rm -f {SEED_PATH}.tmp; cleanup; exit 1; }} + cat {SEED_PATH} > /dev/null + avail=$(awk '/MemAvailable/ {{print int($2/1024)}}' /proc/meminfo) + echo "avail=$avail" + take=$((avail - stop_mb)) + [ "$take" -gt 0 ] || {{ echo "nothing to take"; cleanup; exit 2; }} + n=$((take / 256)); rest=$((take % 256)); pids="" + echo "burst_mb=$take start=$(date +%s%N)" + while [ $i -lt $n ]; do cat {SEED_PATH} > {HOG_MOUNT}/f$i & pids="$pids $!"; i=$((i+1)); done + [ "$rest" -gt 0 ] && {{ head -c $((rest * 1048576)) {SEED_PATH} > {HOG_MOUNT}/f$i & pids="$pids $!"; }} + for pid in $pids; do wait "$pid" || failed=1; done + echo "burst_done=$(date +%s%N)" + echo "avail=$(awk '/MemAvailable/ {{print int($2/1024)}}' /proc/meminfo)" + i=512 +fi while [ $i -lt 512 ]; do avail=$(awk '/MemAvailable/ {{print int($2/1024)}}' /proc/meminfo) echo "avail=$avail" [ "$avail" -le "$stop_mb" ] && break - head -c 33554432 /dev/urandom > {HOG_MOUNT}/f$i || break + head -c 33554432 /dev/urandom > {HOG_MOUNT}/f$i || {{ failed=1; break; }} i=$((i+1)) done +[ "$failed" = 0 ] || {{ echo "write failed"; cleanup; exit 1; }} sleep "$hold" cleanup echo released """ # Stops a writer left by an interrupted run before its files go, so the unmount does not fail. The # bracketed patterns keep pkill from matching the shell that runs this line. -HOG_CLEANUP = (f"pkill -f '[d]d-memory-hog.sh'; pkill -f '[h]ead -c 33554432'; sleep 1; rm -f {HOG_MOUNT}/f*; " +HOG_CLEANUP = (f"pkill -f '[d]d-memory-hog.sh'; pkill -f '[h]ead -c 33554432'; pkill -f '[d]d-memory-burst.bin'; sleep 1; rm -f {HOG_MOUNT}/f*; " f"umount {HOG_MOUNT} 2>/dev/null; true") def focused_display(input_dump: str) -> int | None: @@ -58,7 +80,7 @@ def focused_display(input_dump: str) -> int | None: def activity_count(activities_dump: str, activity: str) -> int: - return len(re.findall(r"Hist\s+#\d+: ActivityRecord\{\S+ u\d+ " + re.escape(activity) + r" ", activities_dump)) + return len(re.findall(r"Hist\s+#\d+: ActivityRecord\{\S+ u\d+ " + re.escape(activity) + r"[ }]", activities_dump)) def guard_count(activities_dump: str) -> int: @@ -85,7 +107,8 @@ def panel_windows(windows_dump: str, display: int) -> int: def bottom_home(activities_dump: str, session_display: int) -> tuple[int, str] | None: - display = None + """The visible home on another display, else the visible app on top of it.""" + display, top = None, None for line in activities_dump.splitlines(): section = re.match(r"Display #(\d+) \(activities", line) if section: @@ -96,7 +119,10 @@ def bottom_home(activities_dump: str, session_display: int) -> tuple[int, str] | home = re.search(r"type=home A=\d+:(\S+) .*visible=true", line) if home: return display, home.group(1) - return None + app = re.search(r"type=standard A=\d+:([\w.]+) .*visible=true", line) + if app and top is None and not app.group(1).startswith(PACKAGE): + top = display, app.group(1) + return top def logical_size(displays_dump: str, display: int) -> tuple[int, int] | None: @@ -151,8 +177,11 @@ class Device: return self.sh(f"su -c {shlex.quote(command)}", timeout=timeout) def ctl(self, *args: str, timeout: int = 300) -> subprocess.CompletedProcess[str]: - return subprocess.run([str(TOOLS / "droiddeckctl"), "--adb", self.adb, "--serial", self.serial, *args], - capture_output=True, text=True, timeout=timeout) + command = [str(TOOLS / "droiddeckctl"), "--adb", self.adb, "--serial", self.serial, *args] + try: + return subprocess.run(command, capture_output=True, text=True, timeout=timeout) + except subprocess.TimeoutExpired: + return subprocess.CompletedProcess(command, -1, "", f"timed out after {timeout} s") def phase(self) -> str | None: match = re.search(r'"phase":\s*"(\w+)"', self.ctl("state").stdout) @@ -208,7 +237,8 @@ class Bench: def prepare(self, apk: str | None): self.d.sh("input keyevent KEYCODE_WAKEUP") - self.d.ctl("stop") + if self.d.ctl("stop", timeout=120).returncode != 0: + self.d.sh(f"am force-stop {PACKAGE}") if apk: env = dict(os.environ, ADB_SERIAL=self.d.serial) subprocess.run([str(TOOLS / "deploy_local.sh"), apk], env=env, check=True, capture_output=True) @@ -234,7 +264,7 @@ class Bench: "guards": guard_count(activities), "sessions": session_count(activities), "panel": panel_windows(self.d.sh("dumpsys window windows"), display), - "adj": int(self.d.su(f"cat /proc/{pid}/oom_score_adj").strip() or -9999), + "adj": int(self.d.sh(f"cat /proc/{pid}/oom_score_adj").strip() or -9999), "pid": pid, } @@ -251,7 +281,8 @@ class Bench: before = self.snapshot() _, home = self.bottom() self.d.run("logcat", "-b", "events", "-c") - samples = self.d.su(f"kill -9 $(pidof {home}); for i in $(seq 50); do cat /proc/{before['pid']}/oom_score_adj" + self.d.su(f"kill -9 $(pidof {home})") + samples = self.d.sh(f"for i in $(seq 50); do cat /proc/{before['pid']}/oom_score_adj" " 2>/dev/null || echo DEAD; sleep 0.1; done").split() events = self.d.run("logcat", "-b", "events", "-d") (self.out / f"{self.label}-{state}-events.txt").write_text(events) @@ -297,7 +328,7 @@ class Bench: self.probe("using_bottom_now") self.game_front() - def pressure(self, run: str, stop_mb: int, hold: int): + def pressure(self, run: str, stop_mb: int, hold: int, burst: bool = False) -> bool: with tempfile.NamedTemporaryFile("w", suffix=".sh", delete=False) as script: script.write(HOG) try: @@ -305,16 +336,18 @@ class Bench: finally: os.unlink(script.name) self.d.sh(f"chmod 755 {HOG_PATH}") - self.game_front() self.close_panel() + self.game_front() + self.tap(self.session_display, (0.36, 0.11)) + time.sleep(2) before = self.snapshot() self.d.run("logcat", "-b", "events", "-c") - hog = subprocess.Popen([self.d.adb, "-s", self.d.serial, "shell", f"su -c '{HOG_PATH} {int(stop_mb)} {int(hold)}'"], + hog = subprocess.Popen([self.d.adb, "-s", self.d.serial, "shell", f"su -c '{HOG_PATH} {int(stop_mb)} {int(hold)} {'burst' if burst else 'fill'}'"], stdout=subprocess.PIPE, text=True) samples = [] try: while hog.poll() is None: - samples.append(self.d.su(f"cat /proc/{before['pid']}/oom_score_adj 2>/dev/null || echo DEAD").strip()) + samples.append(self.d.sh(f"cat /proc/{before['pid']}/oom_score_adj 2>/dev/null || echo DEAD").strip()) time.sleep(0.5) output = hog.stdout.read() if hog.stdout else "" finally: @@ -324,12 +357,19 @@ class Bench: time.sleep(3) events = self.d.run("logcat", "-b", "events", "-d") (self.out / f"{self.label}-{run}-events.txt").write_text(events) + workload_ok = hog.returncode == 0 and "released" in output.splitlines() + if not workload_ok: + print(f"memory-guard-ab: {run}: the memory hog failed (exit {hog.returncode}): " + f"{output.strip().splitlines()[-1] if output.strip() else 'no output'}", file=sys.stderr) available = [int(value) for value in re.findall(r"avail=(\d+)", output)] + took = re.search(r"start=(\d+).*?burst_done=(\d+)", output, re.S) self.write("pressure", { - "run": run, "stop_mb": stop_mb, "hold_s": hold, **{k: v for k, v in before.items() if k != "pid"}, + "run": run, "workload_ok": workload_ok, "mode": "burst" if burst else "fill", "stop_mb": stop_mb, "hold_s": hold, + "burst_ms": (int(took.group(2)) - int(took.group(1))) // 1_000_000 if took else None, **{k: v for k, v in before.items() if k != "pid"}, "min_available_mb": min(available) if available else None, "adj_max": max_adj(samples), "droiddeck_alive": self.d.pid() == before["pid"], "phase": self.d.phase(), **summarize_events(events), }) + return workload_ok def fraction_pair(text: str) -> tuple[float, float]: @@ -355,6 +395,8 @@ def main() -> int: pressure.add_argument("--stop-mb", type=int, default=650, help="stop filling at this MemAvailable") pressure.add_argument("--hold", type=int, default=30) pressure.add_argument("--runs", type=int, default=1) + pressure.add_argument("--burst", action="store_true", + help="take everything above --stop-mb at once instead of filling 32 MiB at a time") summarize = commands.add_parser("summarize", help="summarize a saved events log") summarize.add_argument("events", type=Path) args = parser.parse_args() @@ -376,9 +418,19 @@ def main() -> int: bench.prepare(args.apk) bench.states() else: + completed = 0 for run in range(args.runs): - bench.prepare(args.apk if run == 0 else None) - bench.pressure(f"stop{args.stop_mb}-{run + 1}", args.stop_mb, args.hold) + try: + bench.prepare(args.apk if run == 0 else None) + except RuntimeError as exc: + print(f"memory-guard-ab: run {run + 1} skipped: {exc}", file=sys.stderr) + continue + if bench.pressure(f"{'burst' if args.burst else 'stop'}{args.stop_mb}-{run + 1}", args.stop_mb, + args.hold, args.burst): + completed += 1 + if completed == 0: + print("memory-guard-ab: no pressure run completed", file=sys.stderr) + return 1 except RuntimeError as exc: print(f"memory-guard-ab: {exc}", file=sys.stderr) return 1 diff --git a/tools/tests/test_memory_guard_ab.py b/tools/tests/test_memory_guard_ab.py index 6d75f7206f..96565efffa 100644 --- a/tools/tests/test_memory_guard_ab.py +++ b/tools/tests/test_memory_guard_ab.py @@ -66,6 +66,15 @@ class DumpParsingTest(unittest.TestCase): def test_the_bottom_home_is_the_visible_home_on_another_display(self): self.assertEqual((2, "rip.moth.cocoonshell"), ab.bottom_home(ACTIVITIES, 0)) + def test_android_13_activity_records_are_counted(self): + self.assertEqual(1, ab.session_count( + " * Hist #1: ActivityRecord{e1ec207 u0 com.droiddeck.launcher/.SessionActivity} t14519}\n")) + + def test_the_visible_app_stands_in_when_no_home_is_on_the_other_display(self): + dump = ("Display #4 (activities from top to bottom):\n" + " * Task{21f60d6 #14493 type=standard A=10113:com.discord U=0 visible=true visibleRequested=true mode=fullscreen}\n") + self.assertEqual((4, "com.discord"), ab.bottom_home(dump, 0)) + def test_no_bottom_home_without_another_display(self): self.assertIsNone(ab.bottom_home(ACTIVITIES.split("\n\n")[1], 0)) @@ -80,6 +89,25 @@ class DumpParsingTest(unittest.TestCase): self.assertIsNone(ab.logical_size(DISPLAYS, 5)) +class HogScriptTest(unittest.TestCase): + def test_both_modes_start_the_fill_counter(self): + script = ab.HOG.splitlines() + counter = next(n for n, line in enumerate(script) if line.startswith("i=0")) + self.assertLess(counter, script.index('if [ "$mode" = burst ]; then')) + self.assertLess(counter, next(n for n, line in enumerate(script) if line.startswith("while [ $i -lt 512 ]"))) + + + def test_a_failed_write_never_reports_released(self): + script = ab.HOG.splitlines() + check = script.index('[ "$failed" = 0 ] || { echo "write failed"; cleanup; exit 1; }') + self.assertLess(check, script.index("echo released")) + self.assertIn("failed=1", ab.HOG.split("echo released")[0]) + + def test_a_burst_takes_the_remainder_below_one_chunk(self): + self.assertIn("rest=$((take % 256))", ab.HOG) + self.assertIn('echo "nothing to take"', ab.HOG) + + class SummaryTest(unittest.TestCase): def test_max_adj_skips_samples_after_death(self): self.assertEqual(50, ab.max_adj(["0", "50", "DEAD", ""])) From 83dc5f37e9180cf5310b7d0c0f636678dfaa7ce5 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:40:17 -0500 Subject: [PATCH 04/29] fix(session): launching the running game again resumes it instead of asking Steam twice (#2940) * fix(session): launching the running game again resumes it instead of asking Steam twice A front end that resumes a suspended player by launching the same game again (Cocoon 3.07 does) made DroidDeck queue the game for Steam a second time, and Steam answered with "An error occurred while launching this game: Game already running" over the game. queueSteamGame now resumes the session and returns when the requested game is the current one and its process is running. A different game, or one that has exited, still goes to Steam as before. * fix(session): a relaunch during a pending freeze resumes too, and both game ID forms count as the same game --- .../droiddeck/launcher/session/SessionService.kt | 5 +++++ .../droiddeck/launcher/session/SteamGameProcess.kt | 7 +++++++ .../launcher/session/SteamGameProcessTest.kt | 13 +++++++++++++ 3 files changed, 25 insertions(+) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index 94664b4697..285f6b7c08 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -1613,6 +1613,11 @@ class SessionService : Service() { return } val accepted = gameId!! + if (pendingSteamGameId == null && SteamGameProcess.alreadyRunning(accepted, SessionState.gameId)) { + Log.i(TAG, "game $accepted is already running; resuming it instead of launching it again") + if (SessionState.suspended || SessionState.suspending) resumeSession() + return + } if (!pendingSteamPreviousGamePending) { pendingSteamPreviousGameId = SessionState.gameId pendingSteamPreviousGamePending = true diff --git a/app/src/main/java/com/droiddeck/launcher/session/SteamGameProcess.kt b/app/src/main/java/com/droiddeck/launcher/session/SteamGameProcess.kt index 7a00553f3b..6b7ecda60c 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SteamGameProcess.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SteamGameProcess.kt @@ -61,4 +61,11 @@ object SteamGameProcess { runCatching { File(p, "cmdline").readBytes() } .getOrNull()?.let { matches(it, gameId) } == true } == true + + // A front end that resumes a player by launching the same game again would otherwise have Steam + // start it a second time, which Steam answers with "Game already running". + fun alreadyRunning(requested: String, current: String?, proc: File = File("/proc")): Boolean { + val appId = steamAppIdForGameId(requested) ?: return false + return appId == steamAppIdForGameId(current.orEmpty()) && running(requested, proc) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/SteamGameProcessTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SteamGameProcessTest.kt index ae9b31d80c..5e68b5fee9 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SteamGameProcessTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SteamGameProcessTest.kt @@ -88,4 +88,17 @@ class SteamGameProcessTest { process("301", "reaper", "SteamLaunch", "AppId=351710", "--", "proton", "waitforexitandrun", "game.exe") assertTrue(SteamGameProcess.running("351710", proc)) } + + @Test fun onlyTheRunningCurrentGameCountsAsAlreadyRunning() { + val proc = tmp.newFolder("proc-relaunch") + File(proc, "200").apply { mkdirs() }.resolve("cmdline") + .writeBytes(cmdline("reaper", "SteamLaunch", "AppId=584400", "--", "proton", "waitforexitandrun", "SonicMania.exe")) + assertTrue(SteamGameProcess.alreadyRunning("584400", "584400", proc)) + assertFalse(SteamGameProcess.alreadyRunning("584400", "311340", proc)) + assertFalse(SteamGameProcess.alreadyRunning("311340", "311340", proc)) + assertFalse(SteamGameProcess.alreadyRunning("584400", null, proc)) + val shortcutId = ((584400uL shl 32) or 0x02000000uL).toString() + assertTrue(SteamGameProcess.alreadyRunning(shortcutId, "584400", proc)) + assertTrue(SteamGameProcess.alreadyRunning("584400", shortcutId, proc)) + } } From d5c83eae155e74578665c22b3f5085ebb5e80be5 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:54:59 -0500 Subject: [PATCH 05/29] feat(input): describe on-screen layout choices, scope per-game layouts and delete unused ones (#2939) * feat(input): describe on-screen layout choices, scope per-game layouts and delete unused ones - The layout menu says what each choice is: "DroidDeck controls" work in every game and are edited here; "Steam touch controls" are each game's controls from Steam, for Steam games only. - Layouts made with "+ New for " (or "Just this game") are listed only for that game, marked "Just for ". Older ones are recognised by carrying the name of the game that draws them. - Saved layouts nothing uses get a delete button in the menu. Deleting one also removes a profile that still uses it but can no longer be chosen, such as copies made by the old profile screen. - A game set to Steam touch controls that runs without Steam shows a note under Layout instead of silently using the default. * fix(input): a layout the built-in profile still lists can be deleted once another is chosen Applying a layout used to write it into the Game profile; choosing another now goes on top, so the profile's part is no longer drawn. Only parts a mode actually draws count as in use, and deleting points the built-in profile back at the stock layout. --- .../com/droiddeck/launcher/SessionActivity.kt | 16 +++- .../launcher/input/ControlsChoice.kt | 88 +++++++++++++++-- .../droiddeck/launcher/input/GameControls.kt | 10 ++ .../launcher/ui/InputSettingsPage.kt | 4 +- .../droiddeck/launcher/ui/LayoutChoiceRow.kt | 87 +++++++++++++++++ .../droiddeck/launcher/ui/SessionOverlay.kt | 8 +- app/src/main/res/values/strings.xml | 9 +- .../launcher/input/ControlsChoiceTest.kt | 94 +++++++++++++++++-- .../launcher/ui/InputSettingsTest.kt | 14 +++ 9 files changed, 304 insertions(+), 26 deletions(-) create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/LayoutChoiceRow.kt diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index b5020ed92a..19dedc52bf 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -646,8 +646,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var oscRearButtons by mutableStateOf(false) private var oscTrackpads by mutableStateOf(false) private var onScreenButtonsVisible by mutableStateOf(false) - private var layoutOptions by mutableStateOf>>(emptyList()) + private var layoutOptions by mutableStateOf>(emptyList()) private var layoutChoice by mutableStateOf("") + private var layoutHint by mutableStateOf(null) private var layoutEditor by mutableStateOf?>(null) private var layoutEditorScope: String? = null private var layoutEditorSplit: com.droiddeck.launcher.ui.InputEditorSplit? = null @@ -1746,7 +1747,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde layoutGame = controlsGameName(), layoutOptions = layoutOptions, layoutChoice = layoutChoice, + layoutHint = layoutHint, onLayout = ::chooseLayout, + onDeleteLayout = ::deleteLayout, oscRearButtons = oscRearButtons.takeIf { unfoldedPanel == null && !usesSteamTouchLayout() && com.droiddeck.launcher.input.PadKit.current(this).steam && primaryInputLayout?.let(com.droiddeck.launcher.input.OnScreenLayout::hasBuiltInKit) == true @@ -4432,8 +4435,15 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun refreshLayoutOptions() { val steam = SessionState.mode == SessionService.MODE_STEAM val game = controlsGameId() - layoutOptions = com.droiddeck.launcher.input.ControlsChoice.options(this, game, steam, controlsGameName()) - layoutChoice = com.droiddeck.launcher.input.ControlsChoice.current(this, game, steam, loadingMode() == SessionService.MODE_DESKTOP) + val desktop = loadingMode() == SessionService.MODE_DESKTOP + layoutOptions = com.droiddeck.launcher.input.ControlsChoice.options(this, game, steam, controlsGameName(), desktop) + layoutChoice = com.droiddeck.launcher.input.ControlsChoice.current(this, game, steam, desktop) + layoutHint = if (com.droiddeck.launcher.input.ControlsChoice.steamUnavailable(this, game, steam)) getString(R.string.osc_layout_steam_unavailable) else null + } + + private fun deleteLayout(id: String) { + runCatching { com.droiddeck.launcher.input.ControlsChoice.delete(this, id) }.onFailure { Log.w(TAG, "could not delete layout $id", it) } + refreshLayoutOptions() } private fun chooseLayout(id: String) { diff --git a/app/src/main/java/com/droiddeck/launcher/input/ControlsChoice.kt b/app/src/main/java/com/droiddeck/launcher/input/ControlsChoice.kt index 2e4952b971..1fe9bd1f34 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/ControlsChoice.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/ControlsChoice.kt @@ -24,14 +24,84 @@ object ControlsChoice { return if (chosen == null) library else library.selectPart(desktop, InputRole.PRIMARY, chosen) } - fun options(context: Context, game: Long?, steamMode: Boolean, gameName: String? = null): List> { + data class Option(val id: String, val name: String, val detail: String? = null, val deletable: Boolean = false) + + /** Layouts made for one game, so they're listed only for that game. Layouts made before that was recorded are recognised by carrying the name of the game that draws them. */ + private fun owners(context: Context, library: InputLibrary): Map> { + val named = GameControls.games(context).mapNotNull { game -> + val layout = own(library, GameControls.bindings(context, game))?.let { library.preset(it).layoutId } ?: return@mapNotNull null + val name = GameControls.name(context, game) ?: return@mapNotNull null + (layout to game).takeIf { library.layouts.any { it.id == layout && it.name == name } } + } + return (named + GameControls.madeFor(context).toList()).groupBy({ it.first }, { it.second }).mapValues { it.value.toSet() } + } + + private fun defaults(library: InputLibrary) = + listOf(false, true).mapNotNull { library.activeLayout(it, InputRole.PRIMARY)?.id }.toSet() + + private fun deletable(context: Context, library: InputLibrary, layout: SavedInputLayout): Boolean { + if (!layout.editable || layout.id == InputLibraries.OVERLAY || layout.id in defaults(library)) return false + if (GameControls.games(context).any { game -> own(library, GameControls.bindings(context, game))?.let { library.preset(it).layoutId } == layout.id }) return false + return library.profiles.none { p -> p.parts.any { (role, part) -> part.layout == layout.id && drawn(library, p.id, role) } } && + library.bindings.none { it.layoutId == layout.id && library.selectedBindings(it.id) } + } + + /** Whether [profile]'s [role] part is what a mode shows, rather than one a choice made since covers. */ + private fun drawn(library: InputLibrary, profile: String, role: InputRole) = + listOf(false, true).any { desktop -> library.activeId(desktop) == profile && library.selection(desktop).parts[role] == null } + + private fun keeps(library: InputLibrary, profile: String) = + profile == InputProfile.GAME || profile == InputProfile.DESKTOP || listOf(false, true).any { library.activeId(it) == profile } + + fun options(context: Context, game: Long?, steamMode: Boolean, gameName: String? = null, desktop: Boolean = false): List