Feat: Add per game screens effects (#2472)

* Add per-game screen effects profiles

* Fix stale screen effects callbacks

* Fix per-game screen effects profile handling

* Fix screen effects restoration on cancelled launch

* Allow nullable screen effects profile in drawer

* Fix per-game screen effects initialization

* Fix per-game screen effects tracking

* Tighten Steam process detection tests

* Fix per-game screen effects profile resolution

* Fix per-game screen effects profile selection

* Fix screen effects cleanup on game exit

* Fix Steam closing between game launches

* Update SessionService.kt comments removed

* Fix screen effects profile synchronization

* Fix saving screen effects without profile

* Prevent stale screen effects overwriting active profile

* Refresh screen effects on session resume

* Update SessionActivity.kt ( used rabbit suggested fixed )

* Fix Steam game exit detection and return

* Clear screen effects profile while awaiting Steam exit

* Preserve screen effects profile when game restarts

* Refactor screen effects sync and fix game exit handling

* Fix Steam URL game ID fallback

* Add screen effects translations for all locales

* Add per-game screen effects profiles

* Fix per-game screen effects preset persistence

* Fix screen effects profile upscaler handling

* Fix screen effects profile synchronization

* Fix screen effects focus profile synchronization

* Fix screen effects profile restoration on resume

* Fix screen effects profile switching

* Fix Steam game launch rollback target

* Fix screen effects upscaler profile inheritance

* Update SessionActivity.kt ( removed coments )

* Remove unused setup stores translations

* Guard screen effects profile rollback

* Fix per-game screen effects and queued launches

* Fix queued game state and suspend-aware startup timeout

* Fix integer scaling picture bounds

* Fix nullable automatic screen effects profile validation

* Fix integer scaling fallback for small outputs

* Revert "Fix integer scaling fallback for small outputs"

This reverts commit c667a50d58.

* Fix Steam game exit watcher for direct launches

* Fix per-game screen effects resume handling

* Fix game picture bounds scaling
This commit is contained in:
LunaDL authored and GitHub committed 2026-11-15 09:20:37 -05:00
1 parent ae9bac225d
commit 9ce6d45be8
41 files changed
+845 -89

No files matched your search

@@ -13,6 +13,8 @@ import com.droiddeck.launcher.gpu.TurnipDriver
import org.json.JSONObject
import java.io.File
private const val SCREEN_EFFECTS_PROFILE_UPSCALER_KEY = "upscaler"
object SessionPrefs {
data class GameTextureFiltering(val anisotropy: Int? = null, val lodBias: String? = null)
@@ -1443,15 +1445,136 @@ object SessionPrefs {
}
private const val SCREEN_EFFECTS_PROFILES_KEY = "screenEffects.profiles"
const val SCREEN_EFFECTS_ACTIVE_PROFILE_KEY = "screenEffects.activeProfile"
fun screenEffectsProfileId(mode: String, gameId: String?, program: String?): String? {
if (mode == SessionService.MODE_DESKTOP) return "desktop"
val id = gameId?.trim()?.takeIf { it.isNotEmpty() }
if (id != null) return "game:$id"
return if (mode == SessionService.MODE_RUN) {
program?.trim()?.takeIf { it.isNotEmpty() }?.let { "program:$it" }
} else null
}
fun activeScreenEffectsProfileId(context: Context): String? =
prefs(context).getString(SCREEN_EFFECTS_ACTIVE_PROFILE_KEY, null)?.takeIf { it.isNotBlank() }
fun setActiveScreenEffectsProfile(context: Context, profileId: String?) {
prefs(context).edit().putString(SCREEN_EFFECTS_ACTIVE_PROFILE_KEY, profileId.orEmpty()).apply()
}
fun screenEffects(context: Context): ScreenEffects {
val text = prefs(context).getString("screenEffects", null) ?: return ScreenEffects.OFF
return runCatching { ScreenEffects.decode(JSONObject(text)) }.getOrDefault(ScreenEffects.OFF)
}
fun screenEffects(context: Context, profileId: String?): ScreenEffects {
if (profileId.isNullOrBlank()) return screenEffects(context)
val storedProfiles = prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null)
val profile = storedProfiles?.let { raw ->
runCatching { JSONObject(raw).optJSONObject(profileId) }.getOrNull()
}
return profile?.let {
runCatching { ScreenEffects.decode(it) }.getOrDefault(ScreenEffects.OFF)
} ?: screenEffects(context)
}
fun setScreenEffects(context: Context, effects: ScreenEffects) {
prefs(context).edit().putString("screenEffects", effects.encode().toString()).apply()
}
fun setScreenEffects(context: Context, profileId: String?, effects: ScreenEffects) {
if (profileId.isNullOrBlank()) {
setScreenEffects(context, effects)
return
}
val sessionPrefs = prefs(context)
val profiles = runCatching {
JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
}.getOrDefault(JSONObject())
val encoded = effects.encode()
profiles.optJSONObject(profileId)?.let { savedProfile ->
if (savedProfile.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY)) {
encoded.put(
SCREEN_EFFECTS_PROFILE_UPSCALER_KEY,
savedProfile.optInt(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY),
)
}
}
profiles.put(profileId, encoded)
sessionPrefs.edit().putString(SCREEN_EFFECTS_PROFILES_KEY, profiles.toString()).apply()
}
fun hasScreenEffectsUpscalerOverride(context: Context, profileId: String?): Boolean {
if (profileId.isNullOrBlank()) return false
return runCatching {
val profiles = JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
profiles.optJSONObject(profileId)?.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) == true
}.getOrDefault(false)
}
fun screenEffectsUpscaler(context: Context, profileId: String?): Int {
if (profileId.isNullOrBlank()) return upscaler(context)
val stored = runCatching {
val profiles = JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
val profile = profiles.optJSONObject(profileId)
if (profile?.has(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY) == true) {
profile.optInt(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY, -1)
} else -1
}.getOrDefault(-1)
return if (stored >= 0) canonicalUpscaler(stored) else upscaler(context)
}
fun setScreenEffectsUpscaler(context: Context, profileId: String?, mode: Int) {
if (profileId.isNullOrBlank()) {
setUpscaler(context, mode)
return
}
val sessionPrefs = prefs(context)
val profiles = runCatching {
JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
}.getOrDefault(JSONObject())
val profile = profiles.optJSONObject(profileId)
?: screenEffects(context, profileId).encode()
profile.put(SCREEN_EFFECTS_PROFILE_UPSCALER_KEY, canonicalUpscaler(mode))
profiles.put(profileId, profile)
sessionPrefs.edit().putString(SCREEN_EFFECTS_PROFILES_KEY, profiles.toString()).apply()
}
fun screenEffectsProfileIds(context: Context): Set<String> {
val profiles = runCatching {
JSONObject(prefs(context).getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
}.getOrElse { JSONObject() }
return buildSet {
val keys = profiles.keys()
while (keys.hasNext()) add(keys.next())
}
}
fun hasScreenEffectsOverride(context: Context, profileId: String?): Boolean {
if (profileId.isNullOrBlank()) return prefs(context).contains("screenEffects")
return profileId in screenEffectsProfileIds(context)
}
fun resetScreenEffectsProfile(context: Context, profileId: String?) {
setScreenEffects(context, profileId, ScreenEffects.OFF)
}
fun deleteScreenEffectsProfile(context: Context, profileId: String?) {
if (profileId.isNullOrBlank()) return
val sessionPrefs = prefs(context)
val profiles = runCatching {
JSONObject(sessionPrefs.getString(SCREEN_EFFECTS_PROFILES_KEY, null) ?: "{}")
}.getOrElse { JSONObject() }
if (!profiles.has(profileId)) return
profiles.remove(profileId)
sessionPrefs.edit().apply {
if (profiles.length() == 0) remove(SCREEN_EFFECTS_PROFILES_KEY)
else putString(SCREEN_EFFECTS_PROFILES_KEY, profiles.toString())
}.apply()
}
const val CARDBOARD_KEY = "cardboard"
fun cardboard(context: Context): Cardboard {
@@ -114,7 +114,10 @@ class SessionService : Service() {
private var freezePending = false
private var freezeCancelled = false
private var pendingSteamGameId: String? = null
private var pendingSteamPreviousGameId: String? = null
private var pendingSteamPreviousGamePending = false
private var pendingSteamGameGeneration = -1
private var pendingSteamGameExitWatchToken = -1
@Volatile private var gameExitWatchToken = 0
private val flushSteamGame = object : Runnable {
override fun run() = flushQueuedSteamGame()
@@ -390,9 +393,28 @@ class SessionService : Service() {
pipTask = false
SessionState.program = intent?.getStringExtra(EXTRA_PROGRAM)
SessionState.programArgs = intent?.getStringArrayExtra(EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
SessionState.gameId = intent?.getStringExtra(EXTRA_GAME_ID)
SessionState.steamUi = intent?.getStringExtra(EXTRA_STEAM_UI)
SessionState.steamUrl = intent?.getStringExtra(EXTRA_STEAM_URL)
val steamUrlGameId = SessionState.steamUrl
?.let { url ->
when {
url.startsWith(GAME_URL_PREFIX) ->
url.removePrefix(GAME_URL_PREFIX)
url.startsWith("steam://run/") ->
url.removePrefix("steam://run/")
else -> null
}
}
?.takeIf(GameLaunchLink::validId)
val resolvedGameId = intent?.getStringExtra(EXTRA_GAME_ID)
?.trim()
?.takeIf(GameLaunchLink::validId)
?: steamUrlGameId
SessionState.gameId = resolvedGameId
SessionPrefs.setActiveScreenEffectsProfile(
this,
SessionPrefs.screenEffectsProfileId(SessionState.mode, resolvedGameId, SessionState.program),
)
com.droiddeck.launcher.stores.battlenet.BattleNetClient.clearRequests(LinuxRuntime.sessionRoot(this))
val gen = synchronized(stopLock) {
SessionState.steamClientArch = null
@@ -413,8 +435,9 @@ class SessionService : Service() {
if (SessionPrefs.clearCachedApps(this)) clearCachedApps()
cancelQueuedSteamGame(clearMailbox = false)
clearSteamGameMailbox()
if (SessionState.mode == MODE_STEAM) SessionState.steamUrl
?.takeIf { it.startsWith(GAME_URL_PREFIX) }?.let { watchGameExit(it.removePrefix(GAME_URL_PREFIX), gen) }
if (SessionState.mode == MODE_STEAM) {
resolvedGameId?.let { watchGameExit(it, gen, ++gameExitWatchToken) }
}
acquireLocks()
Thread({
OrphanReaper.reap("session starting")
@@ -1520,7 +1543,19 @@ class SessionService : Service() {
return
}
val accepted = gameId!!
if (pendingSteamGameId != null) Log.i(TAG, "replacing a queued game launch with $accepted")
if (!pendingSteamPreviousGamePending) {
pendingSteamPreviousGameId = SessionState.gameId
pendingSteamPreviousGamePending = true
}
if (pendingSteamGameId != null) {
Log.i(TAG, "replacing queued game ${pendingSteamGameId} with $accepted")
}
pendingSteamGameExitWatchToken = ++gameExitWatchToken
SessionState.gameId = accepted
val effectsProfileId = SessionPrefs.screenEffectsProfileId(MODE_STEAM, accepted, null)
SessionPrefs.setActiveScreenEffectsProfile(this, effectsProfileId)
SessionPrefs.screenEffects(this, effectsProfileId)
.push(SessionPrefs.screenEffectsUpscaler(this, effectsProfileId))
pendingSteamGameId = accepted
pendingSteamGameGeneration = sessionGen
if (SessionState.suspended) resumeSession()
@@ -1531,9 +1566,29 @@ class SessionService : Service() {
private fun flushQueuedSteamGame() {
val gameId = pendingSteamGameId ?: return
val gen = pendingSteamGameGeneration
val exitWatchToken = pendingSteamGameExitWatchToken
if (exitWatchToken != gameExitWatchToken) return
if (gen != sessionGen || !SessionState.running || SessionState.stopRequested ||
SessionState.mode != MODE_STEAM || !GameLaunchLink.validId(gameId)) {
SessionState.mode != MODE_STEAM || SessionState.gameId != gameId ||
!GameLaunchLink.validId(gameId)) {
val previousGameId = pendingSteamPreviousGameId
val queuedProfileId = SessionPrefs.screenEffectsProfileId(MODE_STEAM, gameId, null)
val canRestore = gen == sessionGen &&
SessionState.running && !SessionState.stopRequested &&
SessionState.mode == MODE_STEAM &&
SessionState.gameId == gameId &&
SessionPrefs.activeScreenEffectsProfileId(this) == queuedProfileId
cancelQueuedSteamGame()
if (canRestore) {
SessionState.gameId = previousGameId
val previousProfileId =
SessionPrefs.screenEffectsProfileId(MODE_STEAM, previousGameId, null)
SessionPrefs.setActiveScreenEffectsProfile(this, previousProfileId)
SessionPrefs.screenEffects(this, previousProfileId)
.push(SessionPrefs.screenEffectsUpscaler(this, previousProfileId))
}
return
}
if (SessionState.suspended) {
@@ -1560,33 +1615,95 @@ class SessionService : Service() {
}
pendingSteamGameId = null
pendingSteamGameGeneration = -1
pendingSteamGameExitWatchToken = -1
SessionEvents.record("steam.game_launch_requested", mapOf("gameId" to gameId, "generation" to gen))
watchGameExit(gameId, gen)
watchGameExit(gameId, gen, exitWatchToken, pendingSteamPreviousGameId)
Log.i(TAG, "queued Steam game $gameId for the running client")
}
private fun watchGameExit(gameId: String, gen: Int) {
if (!SessionPrefs.returnAfterGame(this)) return
val token = ++gameExitWatchToken
private fun watchGameExit(
gameId: String,
gen: Int,
token: Int,
previousGameId: String? = null
) {
Thread({
val startBy = android.os.SystemClock.elapsedRealtime() + GAME_START_TIMEOUT_MS
var startupRemaining = GAME_START_TIMEOUT_MS
var lastStartupCheck = android.os.SystemClock.elapsedRealtime()
var startupWasSuspended = false
var seen = false
var goneSince = 0L
while (token == gameExitWatchToken && gen == sessionGen && SessionState.running && !SessionState.stopRequested) {
val now = android.os.SystemClock.elapsedRealtime()
if (steamGameRunning()) {
if (!seen) Log.i(TAG, "game $gameId started; returning to the launcher when it closes")
val startupSuspended = SessionState.suspended || SessionState.suspending || SessionState.phase != SessionPhase.READY
if (!seen) {
if (startupSuspended) {
startupWasSuspended = true
lastStartupCheck = now
} else if (startupWasSuspended) {
startupWasSuspended = false
lastStartupCheck = now
} else {
startupRemaining -= (now - lastStartupCheck).coerceAtLeast(0L)
lastStartupCheck = now
}
}
if (steamGameRunning(gameId)) {
if (!seen) {
Log.i(TAG, "game $gameId started; tracking its exit")
mainHandler.post {
if (token == gameExitWatchToken && gen == sessionGen &&
pendingSteamPreviousGamePending &&
pendingSteamPreviousGameId == previousGameId) {
pendingSteamPreviousGameId = null
pendingSteamPreviousGamePending = false
}
}
}
seen = true
goneSince = 0L
} else if (!seen) {
if (now > startBy) {
Log.i(TAG, "game $gameId did not start; not watching for its exit")
if (!startupSuspended && startupRemaining <= 0L) {
mainHandler.post {
if (token != gameExitWatchToken || gen != sessionGen ||
!SessionState.running || SessionState.stopRequested) {
return@post
}
if (previousGameId != null && steamGameRunning(previousGameId)) {
Log.w(TAG, "game $gameId did not start; restoring previous game $previousGameId")
SessionState.gameId = previousGameId
val previousProfileId =
SessionPrefs.screenEffectsProfileId(MODE_STEAM, previousGameId, null)
val failedGameProfileId =
SessionPrefs.screenEffectsProfileId(MODE_STEAM, gameId, null)
if (SessionPrefs.activeScreenEffectsProfileId(this@SessionService) == failedGameProfileId) {
SessionPrefs.setActiveScreenEffectsProfile(this@SessionService, previousProfileId)
SessionPrefs.screenEffects(this@SessionService, previousProfileId)
.push(SessionPrefs.screenEffectsUpscaler(this@SessionService, previousProfileId))
}
pendingSteamPreviousGameId = null
pendingSteamPreviousGamePending = false
watchGameExit(previousGameId, gen, token)
} else {
Log.i(TAG, "game $gameId did not start; clearing its screen effects profile")
pendingSteamPreviousGameId = null
pendingSteamPreviousGamePending = false
clearActiveScreenEffectsProfile(gameId, gen, token)
}
}
return@Thread
}
} else if (goneSince == 0L) {
goneSince = now
} else if (now - goneSince >= GAME_EXIT_GRACE_MS) {
mainHandler.post { returnAfterGame(gameId, gen, token) }
mainHandler.post {
if (SessionPrefs.returnAfterGame(this@SessionService)) {
returnAfterGame(gameId, gen, token)
} else {
clearActiveScreenEffectsProfile(gameId, gen, token)
}
}
return@Thread
}
try { Thread.sleep(GAME_EXIT_POLL_MS) } catch (e: InterruptedException) { return@Thread }
@@ -1594,17 +1711,52 @@ class SessionService : Service() {
}, "game-exit-watch").start()
}
private fun returnAfterGame(gameId: String, gen: Int, token: Int) {
if (token != gameExitWatchToken || gen != sessionGen || !SessionState.running ||
SessionState.stopRequested || SessionState.mode != MODE_STEAM || !SessionPrefs.returnAfterGame(this)) return
val written = runCatching { File(LinuxRuntime.sessionRoot(this), "steam-stop").writeText("") }
.onFailure { Log.w(TAG, "could not ask the client to exit after game $gameId", it) }.isSuccess
if (!written) return
SessionEvents.record("steam.return_after_game", mapOf("gameId" to gameId))
Log.i(TAG, "game $gameId closed: asking the client to exit and returning to the launcher")
private fun clearActiveScreenEffectsProfile(gameId: String, gen: Int, token: Int) {
if (token != gameExitWatchToken || gen != sessionGen || !SessionState.running || SessionState.stopRequested) return
val gameProfileId = SessionPrefs.screenEffectsProfileId(MODE_STEAM, gameId, null)
if (SessionPrefs.activeScreenEffectsProfileId(this) != gameProfileId) return
SessionPrefs.setActiveScreenEffectsProfile(this, null)
SessionPrefs.screenEffects(this, null).push(SessionPrefs.screenEffectsUpscaler(this, null))
}
private fun steamGameRunning(): Boolean = SteamGameProcess.running()
private fun returnAfterGame(gameId: String, gen: Int, token: Int) {
mainHandler.postDelayed({
if (token != gameExitWatchToken || gen != sessionGen || !SessionState.running ||
SessionState.stopRequested || SessionState.mode != MODE_STEAM ||
SessionState.gameId != gameId || pendingSteamGameId != null) {
return@postDelayed
}
if (steamGameRunning(gameId)) {
Log.i(TAG, "game $gameId is running again; restarting its exit watcher")
watchGameExit(gameId, gen, token)
return@postDelayed
}
if (SteamGameProcess.running()) {
Log.i(TAG, "another Steam game is still running after $gameId; checking again")
returnAfterGame(gameId, gen, token)
return@postDelayed
}
clearActiveScreenEffectsProfile(gameId, gen, token)
if (!SessionPrefs.returnAfterGame(this)) {
Log.i(TAG, "return after game disabled; keeping the Steam session open")
return@postDelayed
}
val written = runCatching { File(LinuxRuntime.sessionRoot(this), "steam-stop").writeText("") }
.onFailure { Log.w(TAG, "could not ask the client to exit after game $gameId", it) }.isSuccess
if (!written) return@postDelayed
SessionEvents.record("steam.return_after_game", mapOf("gameId" to gameId))
Log.i(TAG, "game $gameId closed: asking the client to exit and returning to the launcher")
}, GAME_EXIT_CONFIRM_MS)
}
private fun steamGameRunning(gameId: String): Boolean =
SteamGameProcess.running(gameId)
private fun resumeSession(panelVisible: Boolean = true) {
if (SessionState.suspended) SessionState.resumeRequested = true
@@ -1624,7 +1776,11 @@ class SessionService : Service() {
private fun cancelQueuedSteamGame(clearMailbox: Boolean = true) {
mainHandler.removeCallbacks(flushSteamGame)
pendingSteamGameId = null
pendingSteamPreviousGameId = null
pendingSteamPreviousGamePending = false
pendingSteamGameGeneration = -1
pendingSteamGameExitWatchToken = -1
gameExitWatchToken++
if (clearMailbox) clearSteamGameMailbox()
}
@@ -2447,6 +2603,7 @@ class SessionService : Service() {
private const val GAME_URL_PREFIX = "steam://rungameid/"
private const val GAME_START_TIMEOUT_MS = 20 * 60_000L
private const val GAME_EXIT_GRACE_MS = 10_000L
private const val GAME_EXIT_CONFIRM_MS = 2_000L
private const val GAME_EXIT_POLL_MS = 2_000L
private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad"
private const val NO_UINPUT_SWITCH = "Download/droiddeck-no-uinput"
@@ -5,14 +5,59 @@ import java.io.File
object SteamGameProcess {
fun matches(cmdline: ByteArray): Boolean {
val args = String(cmdline).split('\u0000')
for (i in args.indices) {
if (args[i] == "waitforexitandrun") return true
if (args[i] == "SteamLaunch" && args.getOrNull(i + 1)?.startsWith("AppId=") == true) return true
return args.indices.any { i ->
args[i] == "waitforexitandrun" ||
(args[i] == "SteamLaunch" &&
args.getOrNull(i + 1)?.startsWith("AppId=") == true)
}
}
fun running(): Boolean =
File("/proc").listFiles()?.any { p ->
p.name.all(Char::isDigit) &&
runCatching { File(p, "cmdline").readBytes() }
.getOrNull()?.let(::matches) == true
} == true
private fun steamAppIdForGameId(gameId: String): String? {
if (gameId.isEmpty() || !gameId.all(Char::isDigit)) return null
val numericId = gameId.toULongOrNull() ?: return null
val appId = if (numericId > UInt.MAX_VALUE.toULong()) {
numericId shr 32
} else {
numericId
}
return appId.takeIf { it != 0uL }?.toString()
}
fun matches(cmdline: ByteArray, gameId: String): Boolean {
val expectedAppId = steamAppIdForGameId(gameId) ?: return false
val args = String(cmdline).split('\u0000')
for (i in args.indices) {
if (args[i] == "SteamLaunch") {
val appId = args.getOrNull(i + 1)
?.takeIf { it.startsWith("AppId=") }
?.removePrefix("AppId=")
if (appId == expectedAppId) return true
}
if (args[i] == "-applaunch" &&
args.getOrNull(i + 1) == expectedAppId
) {
return true
}
}
return false
}
fun running(proc: File = File("/proc")): Boolean = proc.listFiles()?.any { p ->
p.name.all(Char::isDigit) && runCatching { File(p, "cmdline").readBytes() }.getOrNull()?.let(::matches) == true
} == true
fun running(gameId: String, proc: File = File("/proc")): Boolean =
proc.listFiles()?.any { p ->
p.name.all(Char::isDigit) &&
runCatching { File(p, "cmdline").readBytes() }
.getOrNull()?.let { matches(it, gameId) } == true
} == true
}