fix(session): keep the session the top app on dual screens under memory pressure (#2763)

This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-11-17 12:27:54 -05:00
1 parent b88b5f6b1d
commit fa95df37d0
9 files changed
+296 -5

No files matched your search

+9
View File
@@ -298,6 +298,15 @@
android:resizeableActivity="true"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
<activity
android:name=".session.KeepTopActivity"
android:exported="false"
android:excludeFromRecents="true"
android:noHistory="true"
android:taskAffinity="${applicationId}.keeptop"
android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"
android:resizeableActivity="true"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" />
<activity
android:name=".ui.SessionTypingActivity"
android:exported="false"
@@ -3182,6 +3182,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private fun onSessionEnded(status: Int) {
ended = true
uiHandler.removeCallbacks(guardWhenRunning)
com.droiddeck.launcher.session.KeepTopActivity.release()
++steamVrRequestGeneration
if (isInPictureInPictureMode) {
runOnUiThread { finish() }
@@ -5576,7 +5578,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) {
if (::pip.isInitialized && (requestCode >= 0 || intent.component?.packageName == packageName ||
if (::pip.isInitialized && intent.component?.className != com.droiddeck.launcher.session.KeepTopActivity::class.java.name &&
(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)
@@ -5608,6 +5611,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
override fun onStop() {
if (lightPause.stopped()) departureCleanup()
if (runtimeRemovalBlocked) { super.onStop(); return }
started = false
if (::hud.isInitialized) hud.setBackgrounded(true)
@@ -5651,6 +5655,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun onResume() {
super.onResume()
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) }
@@ -5716,10 +5726,63 @@ 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)
}
}
// 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)
if (isTopResumedActivity) 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) 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()
super.onPause()
}
private fun departureCleanup() {
com.droiddeck.launcher.input.SystemKeyCapture.detach(this)
com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this)
if (runtimeRemovalBlocked) { super.onPause(); return }
if (runtimeRemovalBlocked) return
physicalShortcuts.clear()
backQamInput.cancel()
mouseBackInput.cancel()
@@ -5763,7 +5826,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
SessionPrefs.sessionPrefs(this).unregisterOnSharedPreferenceChangeListener(screenEffectsProfilePrefListener)
ControllerPrefs.prefs(this).unregisterOnSharedPreferenceChangeListener(shortcutPrefListener)
updateHeadTracker()
super.onPause()
}
private fun steamVrAction(action: String) {
@@ -6375,6 +6437,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
}
override fun onDestroy() {
uiHandler.removeCallbacks(guardWhenRunning)
com.droiddeck.launcher.session.KeepTopActivity.release()
synchronized(frameGenGlobalLock) {
frameGenActivityActive = false
frameGenRequests.incrementAndGet()
@@ -0,0 +1,91 @@
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.WindowManager
// While a session runs, sits invisibly on top of every other display until it ends, 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.
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_TOUCHABLE or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
val id = display?.displayId ?: Display.INVALID_DISPLAY
starting.remove(id)
guards[id]?.takeIf { it !== this && !it.isFinishing }?.finishAndRemoveTask()
guards[id] = this
}
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<Int, KeepTopActivity>()
private const val START_TIMEOUT_MS = 2_000L
private val starting = HashMap<Int, Long>()
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 || 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 release() {
generation++
guards.values.toList().forEach { it.finishAndRemoveTask() }
guards.clear()
starting.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())
}
}
}
@@ -0,0 +1,32 @@
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 }
}
@@ -2347,7 +2347,8 @@ 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)) return
com.droiddeck.launcher.ui.SessionTypingActivity::class.java.name,
KeepTopActivity::class.java.name)) return
if (pipTask || xrActivityVisible) {
Log.i(TAG, "panel task dismissed - retaining the session under its active surface policy")
activityVisible = false
@@ -0,0 +1,13 @@
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
}
@@ -0,0 +1,56 @@
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))
}
}
@@ -0,0 +1,25 @@
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))
}
}
+1 -1
View File
@@ -29,7 +29,7 @@ else
"$P=$pkg" "$P.androidx-startup=$pkg.androidx-startup" "$P.logs=$pkg.logs" \
"$P.pairingguide=$pkg.pairingguide" "$P.devicecode=$pkg.devicecode" "$P.pin=$pkg.pin" \
"$P.documents=$pkg.documents" "$P.home=$pkg.home" "$P.agent=$pkg.agent" \
"$P.vr_recovery=$pkg.vr_recovery" "$P.dualscreen=$pkg.dualscreen" "$P.typing=$pkg.typing" \
"$P.vr_recovery=$pkg.vr_recovery" "$P.dualscreen=$pkg.dualscreen" "$P.typing=$pkg.typing" "$P.keeptop=$pkg.keeptop" \
"$P.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION=$pkg.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION"
fi
got=$("$BUILD_TOOLS/aapt" dump badging "$work/renamed.apk" | sed -n "s/^package: name='\([^']*\)'.*/\1/p")