feat: add persistent per-game compatibility profiles (#449)

* feat(profiles): add persistent per-game compatibility profiles

* fix(profiles): show Windows component overrides

Include per-game Windows component selections in the resolved profile summary so the session overlay marks those games as custom and shows the selected components.

* fix(session): detect Proton games across runtime paths

* fix(profiles): select the active Gamescope game

* fix(profiles): improve per-game reset feedback

* fix(profiles): align session components with game overrides

* fix(session): prefer selected Steam game during refresh

* fix(session): resume profile following when reopening games

* chore: keep local dev testing outside the repository

* test(session): remove local dev package path

* fix(session): preserve profiles when refresh fails

* fix(session): reject empty game profile reset scope

* perf(session): cache drawer inventory by refresh revision

* fix(profiles): align game presets and profile reset behavior

* fix(profiles): preserve originals and normalize shortcut ids

* fix(profiles): keep editor scope stable after rebase

* fix(tests): host Compose tests in both build variants

* fix(profiles): recover interrupted component selection saves

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
This commit is contained in:
Juan MartíandKurt Himebauch authored and GitHub committed 2026-10-11 17:00:28 -04:00
1 parent ef4807fbd0
commit 55c51f843e
46 files changed
+3501 -150

No files matched your search

@@ -1183,6 +1183,9 @@ class MainActivity : ComponentActivity() {
onImport = { pickComponent.launch(InAppFilePicker.buildIntent(this, WCP_EXT, getString(R.string.comp_pick_wcp))) },
// Reached by a hop (a game's Components card, Play's Graphics drivers): back the way it came.
onBack = { if (!com.droiddeck.launcher.ui.Hops.back { showComponents = false }) showComponents = false },
games = steamGames,
generalFexPreset = fexPreset,
onGeneralFexPreset = { id -> SessionPrefs.setFexPreset(this, id); fexPreset = id },
gpu = drivers.state(),
gpuActions = com.droiddeck.launcher.ui.GpuDriversActions(
onAuto = { on -> drivers.setMode(on) },
@@ -40,6 +40,7 @@ import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.core.TextureFiltering
import com.droiddeck.launcher.files.InAppFilePicker
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.agent.AgentGuest
import com.droiddeck.launcher.gpu.FrameGen
import com.droiddeck.launcher.gpu.ScreenEffectLooks
import com.droiddeck.launcher.gpu.ScreenEffects
@@ -64,6 +65,9 @@ import com.droiddeck.launcher.session.PerfHud
import com.droiddeck.launcher.session.PerfMode
import com.droiddeck.launcher.session.SteamRepair
import com.droiddeck.launcher.session.GameEnvironmentStore
import com.droiddeck.launcher.session.GameProfileFollowState
import com.droiddeck.launcher.session.GameProfileInventoryCache
import com.droiddeck.launcher.session.GameProfileRefreshState
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionEvents
import com.droiddeck.launcher.session.SessionArtifacts
@@ -73,6 +77,9 @@ import com.droiddeck.launcher.session.SessionPaths
import com.droiddeck.launcher.wayland.HdrSupport
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.ProtonDefault
import com.droiddeck.launcher.session.SelectedGameProfile
import com.droiddeck.launcher.session.WinComponents
import com.droiddeck.launcher.ui.CursorOverlay
import androidx.compose.ui.graphics.asImageBitmap
import com.droiddeck.launcher.ui.DrawerActions
@@ -86,6 +93,7 @@ import com.droiddeck.launcher.wayland.CompositorHost
import com.droiddeck.launcher.wayland.WaylandCompositor
import java.io.File
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.session.LatestRequestCoordinator
import com.droiddeck.launcher.ui.SessionDrawerPage
import com.droiddeck.launcher.ui.sessionDrawerPages
import com.droiddeck.launcher.ui.step
@@ -247,6 +255,24 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var closeAtOnce = false
/** The drawer's Components tab: the Protons as last read (ComponentsManager). */
private var drawerComponents by mutableStateOf<ComponentsManager.Snapshot?>(null)
private var drawerGameProfileId by mutableStateOf<Long?>(null)
private val drawerGameInventory = GameProfileInventoryCache<Library.SteamGame>()
private var drawerGameInventoryRevision = 0L
private var drawerGameFexPresetSaving by mutableStateOf(false)
private val drawerGameProfileFollowState = GameProfileFollowState()
private data class DrawerGameProfileRefresh(
val followsSteam: Boolean,
val requestedAppId: Long?,
val inventoryRevision: Long,
)
private data class DrawerGameProfileResult(
val profiles: List<Pair<Long, String>>,
val selectedAppId: Long?,
val profile: SelectedGameProfile?,
val error: Exception? = null,
)
private var drawerGameProfileRefresh by mutableStateOf(GameProfileRefreshState<DrawerGameProfileResult>())
private val drawerGameProfileRefreshes = LatestRequestCoordinator<DrawerGameProfileRefresh>()
private var drawerPage by mutableStateOf(SessionDrawerPage.CONTROLLER)
private var drawerControllerActive by mutableStateOf(false)
private var backActionsInverted by mutableStateOf(false)
@@ -260,6 +286,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var effects by mutableStateOf(ScreenEffects.OFF)
private var textureAnisotropy by mutableStateOf(0)
private var textureLodBias by mutableStateOf(TextureFiltering.LOD_BIAS_OFF)
private var drawerTextureAnisotropy by mutableStateOf<Int?>(null)
private var drawerTextureLodBias by mutableStateOf<String?>(null)
private var lossless by mutableStateOf(Lossless.State.NONE)
private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) }
@@ -544,7 +572,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
androidApps = androidApps,
hudOn = hudOn,
upscaler = upscaler, upscaleSharpness = upscaleSharpness,
effects = effects, textureAnisotropy = textureAnisotropy, textureLodBias = textureLodBias,
effects = effects,
textureAnisotropy = if (drawerGameProfileId == null) textureAnisotropy else drawerTextureAnisotropy,
textureLodBias = if (drawerGameProfileId == null) textureLodBias else drawerTextureLodBias,
frameGen = frameGen,
lossless = lossless,
oscMode = oscMode, onScreenButtonsVisible = onScreenButtonsVisible, suspendPolicy = suspendPolicy,
@@ -569,8 +599,24 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionPrefs.setScreenEffects(this@SessionActivity, e); effects = e
e.push(upscaler)
},
onTextureAnisotropy = { v -> SessionPrefs.setTextureAnisotropy(this@SessionActivity, v); textureAnisotropy = v },
onTextureLodBias = { v -> SessionPrefs.setTextureLodBias(this@SessionActivity, v); textureLodBias = v },
onTextureAnisotropy = { value ->
drawerGameProfileId?.let { appId ->
SessionPrefs.setGameTextureAnisotropy(this@SessionActivity, appId.toString(), value)
drawerTextureAnisotropy = value
} ?: value?.let {
SessionPrefs.setTextureAnisotropy(this@SessionActivity, it)
textureAnisotropy = it
}
},
onTextureLodBias = { value ->
drawerGameProfileId?.let { appId ->
SessionPrefs.setGameTextureLodBias(this@SessionActivity, appId.toString(), value)
drawerTextureLodBias = value
} ?: value?.let {
SessionPrefs.setTextureLodBias(this@SessionActivity, it)
textureLodBias = it
}
},
onFrameGenPick = { mode ->
FrameGen.set(this@SessionActivity, mode)
readPrefs()
@@ -666,7 +712,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onClose = { drawerOpen = false },
components = drawerComponents,
onComponentsRefresh = { refreshDrawerComponents() },
gameProfiles = drawerGameProfileRefresh.data?.profiles.orEmpty(),
selectedGameProfileId = drawerGameProfileId,
selectedGameProfile = drawerGameProfileRefresh.data
?.takeIf { it.selectedAppId == drawerGameProfileId }?.profile,
gameProfilesLoaded = drawerGameProfileRefresh.loaded,
gameProfileRefreshFailed = drawerGameProfileRefresh.failed,
onSelectedGameProfile = ::selectDrawerGameProfile,
onGameProfilesPageOpened = {
drawerGameProfileFollowState.resumeFollowingSteam()
drawerGameInventoryRevision++
},
onSelectedGameProfileRefresh = ::refreshDrawerGameProfile,
gameFexPresetSaving = drawerGameFexPresetSaving,
onGameFexPreset = ::setDrawerGameFexPreset,
onComponentSwap = { pid, comp, value -> swapDrawerComponent(pid, comp, value) },
onGameComponent = ::setDrawerGameComponent,
))
if (SessionState.suspended) SessionPausedOverlay(
title = pausedTitle(),
@@ -763,6 +824,107 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}, "drawer-components").start()
}
private fun selectDrawerGameProfile(appId: Long?) {
drawerGameProfileFollowState.selectManually()
drawerGameProfileId = appId
drawerGameProfileRefresh = drawerGameProfileRefresh.retrying()
readDrawerTextureFiltering(appId)
refreshDrawerGameProfile()
}
private fun readDrawerTextureFiltering(appId: Long?) {
val choice = appId?.let { SessionPrefs.gameTextureFiltering(this, it.toString()) }
drawerTextureAnisotropy = choice?.anisotropy
drawerTextureLodBias = choice?.lodBias
}
private fun refreshDrawerGameProfile() {
val refresh = DrawerGameProfileRefresh(
drawerGameProfileFollowState.followsSteam,
drawerGameProfileId,
drawerGameInventoryRevision,
)
if (!drawerGameProfileRefreshes.submit(refresh)) return
Thread({
var request = drawerGameProfileRefreshes.takeLatest()
while (request != null) {
val current = request
val result = resolveDrawerGameProfileRefresh(current.value)
uiHandler.post {
if (!drawerGameProfileRefreshes.isLatest(current)) return@post
applyDrawerGameProfileRefresh(current.value, result)
}
request = drawerGameProfileRefreshes.takeLatest()
}
}, "drawer-game-profile").start()
}
private fun resolveDrawerGameProfileRefresh(
refresh: DrawerGameProfileRefresh,
): DrawerGameProfileResult {
return try {
val games = drawerGameInventory.get(refresh.inventoryRevision) { Library.launchableGames(this) }
val options = games.mapNotNull { game ->
game.profileKey.toLongOrNull()?.let { it to game.name }
}.sortedBy { it.second.lowercase() }
val installedAppIds = options.mapTo(mutableSetOf()) { it.first }
val selectedAppId = if (refresh.followsSteam) {
val activeAppId = AgentGuest.activeSteamAppId(this, installedAppIds)
val selectedSteamAppId = runCatching { AgentGuest.selectedSteamAppId(this) }
AgentGuest.selectedOrActiveInstalledSteamAppId(selectedSteamAppId, activeAppId, installedAppIds)
?: refresh.requestedAppId
} else {
refresh.requestedAppId
}
val profile = selectedAppId?.let { resolveDrawerGameProfile(it, games) }
DrawerGameProfileResult(options, selectedAppId, profile)
} catch (error: Exception) {
DrawerGameProfileResult(emptyList(), refresh.requestedAppId, null, error)
}
}
private fun applyDrawerGameProfileRefresh(
refresh: DrawerGameProfileRefresh,
result: DrawerGameProfileResult,
) {
if (result.error != null) {
if (!drawerGameProfileRefresh.failed) {
Log.w(TAG, "Could not refresh the selected game profile", result.error)
}
drawerGameProfileRefresh = drawerGameProfileRefresh.failed()
return
}
drawerGameProfileRefresh = drawerGameProfileRefresh.succeeded(result)
if (refresh.followsSteam) {
if (drawerGameProfileFollowState.followsSteam) {
drawerGameProfileId = result.selectedAppId
readDrawerTextureFiltering(result.selectedAppId)
}
}
}
private fun resolveDrawerGameProfile(
selectedAppId: Long,
games: List<Library.SteamGame>,
): SelectedGameProfile? {
val game = games.firstOrNull { it.profileKey == selectedAppId.toString() } ?: return null
val snapshot = drawerComponents ?: ComponentsManager.snapshot(this)
val protons = snapshot.protons.map { it.proton }
val gameChoice = ProtonDefault.gameChoice(this, game.profileKey)
return SelectedGameProfile.resolve(
selectedAppId = selectedAppId,
games = games,
generalFexPreset = SessionPrefs.fexPreset(this),
environment = GameEnvironmentStore.read(this),
snapshot = snapshot,
generalProtonId = ProtonDefault.selectedId(this, protons),
gameProtonChoice = gameChoice,
gameProtonId = ProtonDefault.gameSelectedId(this, game.profileKey, protons),
gameComponents = ComponentsManager.gameComponents(this, game.profileKey),
gameWindowsComponents = WinComponents.picks(this, game.profileKey),
)
}
private fun swapDrawerComponent(protonId: String, comp: String, value: String) {
Thread({
val message = runCatching {
@@ -784,6 +946,43 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}, "drawer-components-swap").start()
}
private fun setDrawerGameComponent(appId: Long, comp: String, file: String?) {
val name = drawerGameProfileRefresh.data?.profiles?.firstOrNull { it.first == appId }?.second ?: appId.toString()
Thread({
val message = runCatching {
ComponentsManager.setGameComponent(this, appId.toString(), comp, file)
getString(R.string.comp_game_saved_next, name)
}.getOrElse { e ->
getString(R.string.session_profile_save_failed, e.message ?: e.javaClass.simpleName)
}
uiHandler.post {
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show()
refreshDrawerComponents()
refreshDrawerGameProfile()
}
}, "drawer-game-component").start()
}
private fun setDrawerGameFexPreset(appId: Long, preset: String?) {
if (drawerGameFexPresetSaving) return
drawerGameFexPresetSaving = true
val name = drawerGameProfileRefresh.data?.profiles?.firstOrNull { it.first == appId }?.second ?: appId.toString()
Thread({
val message = try {
GameEnvironmentStore.setGameFexPreset(this, appId.toString(), preset)
getString(R.string.comp_game_saved_next, name)
} catch (error: Exception) {
Log.w(TAG, "Could not save the game FEX preset for $appId", error)
getString(R.string.session_profile_save_failed, error.message ?: error.javaClass.simpleName)
}
uiHandler.post {
drawerGameFexPresetSaving = false
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
refreshDrawerGameProfile()
}
}, "drawer-game-fex-preset").start()
}
/** The session this screen is bringing up: the live one when re-attached, else the intent's. */
private fun loadingMode(): String =
if (SessionState.running) SessionState.mode
@@ -85,6 +85,63 @@ object AgentGuest {
fun focus(context: Context): JSONObject? =
if (SessionState.running) readJson(File(dir(context), "focus.json")) else null
/** The Steam library game whose tile currently has controller or keyboard focus. */
fun selectedSteamAppId(context: Context): Long? {
val result = call(context, JSONObject().put("kind", "steam-selection"), 6_000)
if (!result.optBoolean("ok") || result.isNull("appId")) return null
return result.optLong("appId").takeIf { it in 1..4_294_967_295L }
}
/** The installed game Gamescope is presenting, including while Steam's overlay has focus. */
fun activeSteamAppId(context: Context, installedAppIds: Set<Long>): Long? {
val snapshot = focus(context) ?: return null
val focusedAppId = snapshot.optLong("focusedApp").takeIf { snapshot.has("focusedApp") }
val focusableAppIds = snapshot.optJSONArray("focusableApps")?.let { apps ->
buildList {
for (index in 0 until apps.length()) {
apps.optLong(index).takeIf { it > 0 }?.let(::add)
}
}
}.orEmpty()
val baselayerAppIds = snapshot.optJSONArray("baselayerAppIds")?.let { apps ->
buildList {
for (index in 0 until apps.length()) {
apps.optLong(index).takeIf { it > 0 }?.let(::add)
}
}
}.orEmpty()
return activeInstalledSteamAppId(focusedAppId, focusableAppIds, installedAppIds, baselayerAppIds)
}
internal fun focusedInstalledSteamAppId(focusedAppId: Long?, installedAppIds: Set<Long>): Long? =
focusedAppId?.takeIf { it in installedAppIds }
internal fun activeInstalledSteamAppId(
focusedAppId: Long?,
focusableAppIds: List<Long>,
installedAppIds: Set<Long>,
baselayerAppIds: List<Long> = emptyList(),
): Long? = focusedInstalledSteamAppId(focusedAppId, installedAppIds)
?: focusableAppIds.filter { it in installedAppIds }.distinct().singleOrNull()
?: baselayerAppIds.filter { it in installedAppIds }.distinct().singleOrNull()
internal fun preferredInstalledSteamAppId(
selectedAppId: Long?,
activeAppId: Long?,
installedAppIds: Set<Long>,
): Long? = selectedAppId?.takeIf { it in installedAppIds }
?: activeAppId?.takeIf { it in installedAppIds }
internal fun selectedOrActiveInstalledSteamAppId(
selectedAppId: Result<Long?>,
activeAppId: Long?,
installedAppIds: Set<Long>,
): Long? {
preferredInstalledSteamAppId(selectedAppId.getOrNull(), activeAppId, installedAppIds)?.let { return it }
selectedAppId.exceptionOrNull()?.let { throw it }
return null
}
/** Send one request and wait for its answer. Throws [AgentException] with a stable code. */
fun call(context: Context, request: JSONObject, timeoutMs: Long): JSONObject {
if (request.optString("kind") in setOf("exec", "cdp")) AgentAccess.requireCommands(context)
@@ -30,4 +30,11 @@ object FexPreset {
/** Game-launch variables in KEY=VALUE form. */
fun env(id: String): List<String> = byId(id).env
val environmentKeys: Set<String> by lazy {
all.flatMap { it.env }.mapTo(linkedSetOf()) { it.substringBefore('=') }
}
fun environment(id: String): Map<String, String> =
env(id).associate { it.substringBefore('=') to it.substringAfter('=') }
}
@@ -46,4 +46,37 @@ object GameEnvironment {
fun effective(config: Config, preset: String, scope: String, forceSsbs: Boolean = false): Map<String, String?> =
defaults(preset, forceSsbs) + config.shared + if (scope.isEmpty()) emptyMap() else config.games[scope].orEmpty()
fun hasOverride(config: Config, scope: String, name: String): Boolean =
scope.isNotEmpty() && config.entries(scope).containsKey(name)
fun withScopeValue(config: Config, scope: String, name: String, value: String?): Config {
require(scope.isEmpty() || validScope(scope))
val entries = config.entries(scope).toMutableMap()
if (value == null) entries.remove(name) else entries[name] = value
return config.withEntries(scope, entries)
}
fun gameFexPreset(config: Config, scope: String): String? {
require(scope.isNotEmpty() && validScope(scope))
val entries = config.games[scope].orEmpty()
if (FexPreset.environmentKeys.none(entries::containsKey)) return null
return FexPreset.all.firstOrNull { preset ->
val expected = FexPreset.environment(preset.id)
FexPreset.environmentKeys.all { key -> entries.containsKey(key) && entries[key] == expected[key] }
}?.id ?: CUSTOM_FEX_PRESET
}
fun withGameFexPreset(config: Config, scope: String, preset: String?): Config {
require(scope.isNotEmpty() && validScope(scope))
require(preset == null || FexPreset.all.any { it.id == preset })
val entries = config.entries(scope).filterKeys { it !in FexPreset.environmentKeys }.toMutableMap()
if (preset != null) {
val values = FexPreset.environment(preset)
FexPreset.environmentKeys.forEach { key -> entries[key] = values[key] }
}
return config.withEntries(scope, entries)
}
const val CUSTOM_FEX_PRESET = "__custom__"
}
@@ -31,6 +31,8 @@ object Library {
) {
/** Decimal form used by Steam links and Android shortcuts, including unsigned shortcut ids. */
val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId)
/** Key used by per-game environment and Windows-component profiles. */
val profileKey: String get() = if (library == ADDED) java.lang.Integer.toUnsignedString(appId) else appId.toString()
}
/** The [SteamGame.library] of a game added to the library rather than installed by Steam, and the [SteamGame.source] of a plain added folder. */
const val ADDED = "added"
@@ -6,6 +6,7 @@ import android.content.Context
import android.util.Log
import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.github.luben.zstd.ZstdInputStream
@@ -79,7 +80,14 @@ object ComponentsManager {
private const val PLUGIN_DATA = "root/homebrew/data/decky-components-manager"
data class Proton(val id: String, val name: String, val dir: File, val guestPath: String, val version: String, val valve: Boolean)
data class Component(val detected: String, val detail: String, val inUse: String, val activeFile: String?, val queued: String?)
data class Component(
val detected: String,
val detail: String,
val inUse: String,
val selected: String,
val activeFile: String?,
val queued: String?,
)
data class Original(val comp: String, val protonVersion: String, val label: String, val size: Long)
data class Package(val file: String, val comp: String, val version: String, val description: String, val size: Long)
data class CatalogItem(val file: String, val comp: String, val release: String, val url: String, val size: Long, val digest: String)
@@ -129,23 +137,121 @@ object ComponentsManager {
// ------------------------------------------------------------------ state
private fun loadState(context: Context): JSONObject =
runCatching { JSONObject(stateFile(context).readText()) }.getOrElse { JSONObject() }.apply {
private fun pendingStateFile(context: Context) = File(dataDir(context), "state.pending.json")
private fun loadState(context: Context): JSONObject {
recoverState(context)
return runCatching { JSONObject(stateFile(context).readText()) }.getOrElse { JSONObject() }.apply {
if (!has("active")) put("active", JSONObject())
if (!has("queued")) put("queued", JSONObject())
if (!has("profiles")) put("profiles", JSONObject())
}
}
private fun writeStateFile(file: File, text: String) {
val tmp = File(file.parentFile, file.name + ".tmp")
try {
writeSynced(tmp, text)
check(tmp.renameTo(file)) { "Could not save component selections: ${file.name}" }
} finally {
tmp.delete()
}
}
private fun writeSynced(file: File, text: String) {
FileOutputStream(file).use {
it.write(text.toByteArray(Charsets.UTF_8))
it.fd.sync()
}
}
private fun recoverState(context: Context) {
val pending = pendingStateFile(context)
if (!pending.exists()) return
val transaction = JSONObject(pending.readText())
val state = transaction.getJSONObject("state")
val expected = transaction.getString("launchSha256")
val published = File(launchDir(context), "desired.tsv")
val staged = File(launchDir(context), "desired.tsv.tmp")
// The launch-table rename is the commit point. Never read stale app selections after it.
if (!staged.exists() && published.isFile && Hashes.sha256(published) == expected) {
writeStateFile(stateFile(context), state.toString(2))
Log.i(TAG, "recovered published component selections")
} else {
Log.i(TAG, "discarded unpublished component selections")
}
check(pending.delete()) { "Could not finish component selection recovery" }
if (staged.exists()) check(staged.delete()) { "Could not remove unpublished component selections" }
}
private fun saveState(context: Context, state: JSONObject) {
val f = stateFile(context)
val tmp = File(f.parentFile, f.name + ".tmp")
tmp.writeText(state.toString(2))
tmp.renameTo(f)
// Every change of choice reaches the launch wrappers at once.
runCatching { syncLaunchState(context, state) }.onFailure { Log.w(TAG, "launch state", it) }
val prepared = prepareLaunchState(context, state)
val dir = launchDir(context)
val tmp = File(dir, "desired.tsv.tmp")
try {
writeSynced(tmp, prepared.text)
writeStateFile(pendingStateFile(context), JSONObject()
.put("state", state)
.put("launchSha256", Hashes.sha256(tmp))
.toString())
check(tmp.renameTo(File(dir, "desired.tsv"))) { "Could not publish component selections" }
writeStateFile(stateFile(context), state.toString(2))
check(pendingStateFile(context).delete()) { "Could not finish saving component selections" }
} finally {
if (!pendingStateFile(context).exists()) tmp.delete()
}
File(dir, "store").listFiles()?.filter { it.isDirectory && it.name !in prepared.keep }
?.forEach { it.deleteRecursively() }
}
private fun JSONObject.sub(key: String): JSONObject = optJSONObject(key) ?: JSONObject().also { put(key, it) }
// Keep launch-time restore rows after the last per-game selection is removed.
private fun rememberProfiledComponent(state: JSONObject, comp: String) {
val profiled = state.optJSONArray("profiledComponents")?.let { values ->
(0 until values.length()).mapNotNull { values.optString(it).takeIf(COMPONENTS::contains) }
}.orEmpty().toMutableSet()
if (profiled.add(comp)) state.put("profiledComponents", JSONArray(profiled.sorted()))
}
fun gameComponents(context: Context, scope: String): Map<String, String> = synchronized(lock) {
val profile = loadState(context).sub("profiles").optJSONObject(scope) ?: return emptyMap()
COMPONENTS.mapNotNull { comp -> profile.optString(comp).takeIf(String::isNotEmpty)?.let { comp to it } }.toMap()
}
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) = synchronized(lock) {
require(scope.matches(Regex("[1-9][0-9]{0,9}")) && scope.toLong() <= 4294967295L)
require(comp in COMPONENTS)
val state = loadState(context)
val profiles = state.sub("profiles")
val profile = profiles.optJSONObject(scope) ?: JSONObject().also { profiles.put(scope, it) }
if (file == null) {
if (profile.optString(comp).isNotEmpty()) rememberProfiledComponent(state, comp)
profile.remove(comp)
if (profile.length() == 0) profiles.remove(scope)
} else {
val name = safeName(file)
val wcp = File(packagesDir(context), name)
require(packageInfo(context, wcp).comp == comp)
for (proton in protons(context)) ensureOriginal(context, proton, comp, state)
rememberProfiledComponent(state, comp)
profile.put(comp, name)
}
saveState(context, state)
}
fun clearGameComponents(context: Context, scope: String) = synchronized(lock) {
require(GameEnvironment.validScope(scope))
val state = loadState(context)
val profiles = state.sub("profiles")
profiles.optJSONObject(scope)?.let { profile ->
COMPONENTS.filter { profile.optString(it).isNotEmpty() }
.forEach { rememberProfiledComponent(state, it) }
}
profiles.remove(scope)
saveState(context, state)
}
/** Takes over the Decky plugin's packages, originals and swap records, once. */
private fun migratePlugin(context: Context) {
val marker = File(dataDir(context), ".plugin-imported")
@@ -220,24 +326,33 @@ object ComponentsManager {
* Is anything running on this Proton right now - a game, or the client's own start-up runs,
* whose Wine processes can outlive them? Swaps wait while it is. Read from the command lines.
*/
fun inUse(context: Context, proton: Proton): Boolean = anyProcess(context, proton) { needle, text -> text.contains(needle + "proton ") || text.contains(needle + "files/bin") }
fun inUse(context: Context, proton: Proton): Boolean =
anyProcess(context, proton) { paths, text -> processUsesProton(paths, text, gameOnly = false) }
/**
* Is a game running on this Proton? Only a launch runs proton with the verb waitforexitandrun
* (Proton's own script stays up until the game exits); the client's start-up runs do not.
*/
fun gameRunning(context: Context, proton: Proton): Boolean = anyProcess(context, proton) { needle, text -> text.contains(needle + "proton waitforexitandrun") }
fun gameRunning(context: Context, proton: Proton): Boolean =
anyProcess(context, proton) { paths, text -> processUsesProton(paths, text, gameOnly = true) }
private fun anyProcess(context: Context, proton: Proton, match: (String, String) -> Boolean): Boolean {
val needles = (listOf(proton.guestPath) + EsyncPacks.distPathsFor(root(context), proton.guestPath))
.map { it.trimEnd('/') + "/" }
internal fun processUsesProton(paths: List<String>, text: String, gameOnly: Boolean): Boolean =
paths.any { path ->
val needle = path.trimEnd('/') + "/"
if (gameOnly) text.contains(needle + "proton waitforexitandrun")
else text.contains(needle + "proton ") || text.contains(needle + "files/bin")
}
private fun anyProcess(context: Context, proton: Proton, match: (List<String>, String) -> Boolean): Boolean {
val guestPaths = listOf(proton.guestPath) + EsyncPacks.distPathsFor(root(context), proton.guestPath)
val paths = (guestPaths + guestPaths.map { host(context, it).absolutePath } + proton.dir.absolutePath).distinct()
val procs = File("/proc").listFiles() ?: return false
for (p in procs) {
if (!p.name.all(Char::isDigit)) continue
val cmd = runCatching { File(p, "cmdline").readBytes() }.getOrNull() ?: continue
if (cmd.isEmpty()) continue
val text = String(cmd).replace('\u0000', ' ')
if (needles.any { match(it, text) }) return true
if (match(paths, text)) return true
}
return false
}
@@ -261,7 +376,7 @@ object ComponentsManager {
private fun compFiles(dir: File, comp: String): List<String> {
if (comp == "fex") return FEX_FILES.filter { File(dir, it).isFile }
val base = File(dir, COMP_DIR.getValue(comp))
return base.walkTopDown().filter { it.isFile }.map { it.relativeTo(dir).path }.sorted().toList()
return base.walkTopDown().filter { it.isFile }.map { it.relativeTo(dir).invariantSeparatorsPath }.sorted().toList()
}
private fun owned(comp: String, rel: String) = comp == "fex" || PE_ARCHES.any { "/$it/" in rel }
@@ -352,7 +467,7 @@ object ComponentsManager {
tar.closeArchiveEntry()
}
}
tmp.renameTo(dest)
check(tmp.renameTo(dest)) { "Could not save original bundle ${dest.name}" }
}
// ------------------------------------------------------------------ originals
@@ -380,8 +495,18 @@ object ComponentsManager {
if (dest.isFile) return
val active = state.sub("active").optJSONObject(p.id)?.optJSONObject(comp)
if (active != null && active.optString("protonVersion") == p.version) return
val published = File(launchDir(context), "desired.tsv")
if (published.isFile) {
val mayHaveOverride = published.useLines { rows ->
rows.any { row ->
val fields = row.split('\t')
fields.size == 7 && fields[0] != "*" && fields[1] == p.dir.name &&
fields[2] == p.version && fields[3] == comp
}
}
check(!mayHaveOverride) { context.getString(R.string.cmgr_original_missing) }
}
val rels = compFiles(p.dir, comp)
if (rels.isEmpty()) return
val current = if (comp == "fex") fexVersion(p.dir) else readVersionFile(File(p.dir, "${COMP_DIR.getValue(comp)}/version"))
val profile = JSONObject()
.put("type", TYPE_OF.getValue(comp))
@@ -400,7 +525,7 @@ object ComponentsManager {
for (p in protons(context)) for (comp in COMPONENTS) {
runCatching { ensureOriginal(context, p, comp, state) }.onFailure { Log.w(TAG, "original $comp of ${p.name}", it) }
}
runCatching { syncLaunchState(context, state) }.onFailure { Log.w(TAG, "launch state", it) }
runCatching { saveState(context, state) }.onFailure { Log.w(TAG, "launch state", it) }
}
// ------------------------------------------------------------------ view
@@ -431,9 +556,14 @@ object ComponentsManager {
else context.getString(R.string.cmgr_changed_outside)
}
}
val selectedLabel = when {
active == null || active.optString("protonVersion") != p.version ->
context.getString(R.string.comp_tag_original)
else -> originalLabel(context, active) ?: active.optString("label", active.optString("file"))
}
val q = state.sub("queued").optJSONObject(p.id)?.optJSONObject(comp)
Component(
detected.ifEmpty { context.getString(R.string.cmgr_not_present) }, detail, inUseLabel,
detected.ifEmpty { context.getString(R.string.cmgr_not_present) }, detail, inUseLabel, selectedLabel,
active?.optString("file")?.takeIf { active.optString("protonVersion") == p.version },
q?.let { originalLabel(context, it) ?: it.optString("label") },
)
@@ -455,64 +585,111 @@ object ComponentsManager {
// ------------------------------------------------------------------ launch-time enforcement
private data class PreparedLaunchState(val text: String, val keep: Set<String>)
/**
* Writes what each Proton should be using for the launch wrappers: desired.tsv, one line per
* file (tool dir, Proton build, component, file, sha256, source copy), and an unpacked copy of
* every package or older-build original in use to copy from. Rebuilt whole after every change, so
* a restored or deleted choice simply stops being enforced. The Proton's own current-build
* originals are not listed: the wrappers also give Steam's probe runs their own prefix, which is
* what overwrote files in the first place.
* Stages what each Proton should use for the launch wrappers. General rows use scope `*`;
* per-game rows use the game's compatdata id and replace General for that component. Deletion
* rows remove managed DLLs absent from the chosen package, so switching games cannot leave files
* from the previous game's component set behind.
*/
private fun syncLaunchState(context: Context, state: JSONObject) {
private fun prepareLaunchState(context: Context, state: JSONObject): PreparedLaunchState {
val dir = launchDir(context)
val store = File(dir, "store").apply { mkdirs() }
val all = protons(context)
val lines = StringBuilder()
val keep = HashSet<String>()
val active = state.sub("active")
for (pid in active.keys()) {
val p = all.firstOrNull { it.id == pid } ?: continue
val comps = active.optJSONObject(pid) ?: continue
for (comp in comps.keys()) {
val a = comps.optJSONObject(comp) ?: continue
if (a.optString("protonVersion") != p.version) continue
val file = a.optString("file")
val (key, wcp) = if (file.startsWith("original ")) {
val v = file.removePrefix("original ")
"original-$pid-${safeName(v)}-$comp" to File(originalsDir(context), "$pid/${safeName(v)}/$comp.wcp")
} else safeName(file.removeSuffix(".wcp")) to File(packagesDir(context), file)
if (!wcp.isFile) continue
val unpacked = File(store, key)
if (!File(unpacked, ".complete").isFile) {
unpacked.deleteRecursively()
readWcp(wcp) { tar ->
while (true) {
val e = tar.nextTarEntry ?: break
val rel = normalize(e.name)
if (e.isDirectory || !rel.startsWith("files/") || rel.split('/').any { it == ".." }) continue
val out = File(unpacked, rel)
out.parentFile?.mkdirs()
FileOutputStream(out).use { tar.copyTo(it) }
}
fun unpack(key: String, wcp: File, comp: String): File {
check(wcp.isFile) { context.getString(R.string.cmgr_not_stored) }
val unpacked = File(store, key)
if (!File(unpacked, ".complete").isFile) {
check(packageInfo(context, wcp).comp == comp) { "Wrong component in ${wcp.name}" }
unpacked.deleteRecursively()
check(unpacked.mkdirs()) { "Could not stage component bundle ${wcp.name}" }
readWcp(wcp) { tar ->
while (true) {
val e = tar.nextTarEntry ?: break
val rel = normalize(e.name)
if (e.isDirectory || !rel.startsWith("files/") || rel.split('/').any { it == ".." }) continue
val out = File(unpacked, rel)
out.parentFile?.mkdirs()
FileOutputStream(out).use { tar.copyTo(it) }
}
File(unpacked, ".complete").writeText("1\n")
}
keep += key
val files = a.optJSONObject("files") ?: continue
for (rel in files.keys()) {
val src = File(unpacked, rel)
if (!src.isFile) continue
val guestSrc = "/" + src.absolutePath.removePrefix(root(context).absolutePath.trimEnd('/')).trimStart('/')
lines.append(p.dir.name).append('\t').append(p.version).append('\t').append(comp).append('\t')
.append(rel).append('\t').append(files.optString(rel)).append('\t').append(guestSrc).append('\n')
}
File(unpacked, ".complete").writeText("1\n")
}
keep += key
return unpacked
}
fun managed(comp: String): Set<String> = if (comp == "fex") FEX_FILES.toSet() else buildSet {
for (arch in PE_ARCHES) for (dll in COMP_DLLS.getValue(comp)) add("${COMP_DIR.getValue(comp)}/$arch/$dll")
}
fun append(scope: String, p: Proton, comp: String, key: String, wcp: File) {
val unpacked = unpack(key, wcp, comp)
val files = unpacked.let { base ->
File(base, "files").walkTopDown().filter { it.isFile }.map { it.relativeTo(base).invariantSeparatorsPath }
.filter { owned(comp, it) }.associateWith { File(base, it) }
}
for (rel in managed(comp) - files.keys) {
lines.append(scope).append('\t').append(p.dir.name).append('\t').append(p.version).append('\t').append(comp)
.append('\t').append(rel).append("\t-\t-\n")
}
for ((rel, src) in files) {
val guestSrc = "/" + src.relativeTo(root(context)).invariantSeparatorsPath
lines.append(scope).append('\t').append(p.dir.name).append('\t').append(p.version).append('\t').append(comp)
.append('\t').append(rel).append('\t').append(Hashes.sha256(src)).append('\t').append(guestSrc).append('\n')
}
}
store.listFiles()?.filter { it.isDirectory && it.name !in keep }?.forEach { it.deleteRecursively() }
val list = File(dir, "desired.tsv")
val tmp = File(dir, "desired.tsv.tmp")
tmp.writeText(lines.toString())
tmp.renameTo(list)
fun choice(p: Proton, comp: String, entry: JSONObject): Pair<String, File>? {
val file = entry.optString("file")
return if (file.startsWith("original ")) {
val version = safeName(file.removePrefix("original "))
"original-${p.id}-$version-$comp" to File(originalsDir(context), "${p.id}/$version/$comp.wcp")
} else {
safeName(file.removeSuffix(".wcp")) to File(packagesDir(context), file)
}.takeIf { it.second.isFile }
}
val profiles = state.sub("profiles")
val profiledComponents = buildSet {
state.optJSONArray("profiledComponents")?.let { stored ->
for (index in 0 until stored.length()) {
stored.optString(index).takeIf(COMPONENTS::contains)?.let(::add)
}
}
for (scope in profiles.keys()) {
val profile = profiles.optJSONObject(scope) ?: continue
COMPONENTS.filterTo(this) { profile.optString(it).isNotEmpty() }
}
}
val active = state.sub("active")
for (p in all) for (comp in COMPONENTS) {
val entry = active.optJSONObject(p.id)?.optJSONObject(comp)
val selected = entry?.takeIf { it.optString("protonVersion") == p.version }?.let { choice(p, comp, it) }
if (selected != null) append("*", p, comp, selected.first, selected.second)
else if (comp in profiledComponents) {
ensureOriginal(context, p, comp, state)
val original = originalFile(context, p, comp)
check(original.isFile) { context.getString(R.string.cmgr_original_missing) }
append("*", p, comp, "original-${p.id}-${safeName(p.version)}-$comp", original)
}
}
for (scope in profiles.keys()) {
val profile = profiles.optJSONObject(scope) ?: continue
for (comp in COMPONENTS) {
val file = profile.optString(comp)
if (file.isEmpty()) continue
val wcp = File(packagesDir(context), file)
if (!wcp.isFile) continue
val key = safeName(file.removeSuffix(".wcp"))
for (p in all) append(scope, p, comp, key, wcp)
}
}
return PreparedLaunchState(lines.toString(), keep)
}
// ------------------------------------------------------------------ actions
@@ -615,6 +792,11 @@ object ComponentsManager {
val comps = active.optJSONObject(pid) ?: continue
for (comp in comps.keys()) check(comps.optJSONObject(comp)?.optString("file") != name) { context.getString(R.string.cmgr_package_in_use, name, pid) }
}
val profiles = state.sub("profiles")
for (scope in profiles.keys()) {
val profile = profiles.optJSONObject(scope) ?: continue
check(COMPONENTS.none { profile.optString(it) == name }) { context.getString(R.string.cmgr_package_in_use, name, scope) }
}
val f = File(packagesDir(context), name)
check(f.isFile) { context.getString(R.string.cmgr_package_not_stored, name) }
f.delete()
@@ -13,6 +13,7 @@ object GameEnvironmentStore {
private const val GUEST_FILE = "root/.config/droiddeck/game-environment.json"
/** The published file's extra DXVK options (droiddeck-game-env reads it; the app's own file has none). */
const val DXVK_CONFIG = "dxvkConfig"
const val DXVK_CONFIG_GAMES = "dxvkConfigGames"
@Synchronized
fun read(context: Context): GameEnvironment.Config {
@@ -57,6 +58,13 @@ object GameEnvironmentStore {
publish(context, config)
}
@Synchronized
fun setGameFexPreset(context: Context, scope: String, preset: String?): GameEnvironment.Config {
val config = GameEnvironment.withGameFexPreset(read(context), scope, preset)
save(context, config)
return config
}
@Synchronized
fun publish(context: Context, config: GameEnvironment.Config = read(context)) {
val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + config.shared)
@@ -68,6 +76,21 @@ object GameEnvironmentStore {
TextureFiltering.autoLodBias(SessionState.upscaleRatio),
)
if (dxvk.isNotEmpty()) json.put(DXVK_CONFIG, dxvk)
val autoBias = TextureFiltering.autoLodBias(SessionState.upscaleRatio)
val generalAnisotropy = SessionPrefs.textureAnisotropy(context)
val generalLodBias = SessionPrefs.textureLodBias(context)
val gameDxvk = JSONObject()
SessionPrefs.gameTextureFiltering(context).forEach { (scope, choice) ->
gameDxvk.put(
scope,
TextureFiltering.dxvkOptions(
choice.anisotropy ?: generalAnisotropy,
choice.lodBias ?: generalLodBias,
autoBias,
),
)
}
if (gameDxvk.length() > 0) json.put(DXVK_CONFIG_GAMES, gameDxvk)
write(File(LinuxRuntime.rootDir(context), GUEST_FILE), json.toString())
}
@@ -0,0 +1,14 @@
package com.droiddeck.launcher.session
internal class GameProfileFollowState {
var followsSteam = true
private set
fun selectManually() {
followsSteam = false
}
fun resumeFollowingSteam() {
followsSteam = true
}
}
@@ -0,0 +1,16 @@
package com.droiddeck.launcher.session
internal class GameProfileInventoryCache<T : Any> {
private val lock = Any()
private var revision: Long? = null
private var value: List<T>? = null
// Called only by the refresh worker; the UI invalidates through request revisions.
fun get(requestedRevision: Long, load: () -> List<T>): List<T> = synchronized(lock) {
value?.takeIf { revision == requestedRevision } ?: load().toList().also {
value = it
revision = requestedRevision
}
}
}
@@ -0,0 +1,31 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.core.GameEnvironment
object GameProfileManager {
@Synchronized
fun reset(context: Context, scope: String) {
require(scope.isNotEmpty() && GameEnvironment.validScope(scope))
val failures = mutableListOf<Pair<String, Throwable>>()
fun clear(name: String, action: () -> Unit) {
runCatching(action).onFailure { failures += name to it }
}
clear("environment") {
GameEnvironmentStore.save(
context,
GameEnvironmentStore.read(context).withEntries(scope, emptyMap()),
)
}
clear("Proton") { ProtonDefault.requestGame(context, scope, null) }
clear("component packages") { ComponentsManager.clearGameComponents(context, scope) }
clear("texture filtering") { SessionPrefs.clearGameTextureFiltering(context, scope) }
clear("Windows components") { WinComponents.setPicks(context, scope, emptyList()) }
if (failures.isNotEmpty()) {
val names = failures.joinToString { it.first }
throw IllegalStateException("Could not clear: $names", failures.first().second)
}
}
}
@@ -0,0 +1,13 @@
package com.droiddeck.launcher.session
internal data class GameProfileRefreshState<T>(
val data: T? = null,
val loaded: Boolean = false,
val failed: Boolean = false,
) {
fun succeeded(data: T) = GameProfileRefreshState(data, loaded = true)
fun failed() = copy(failed = true)
fun retrying() = copy(failed = false)
}
@@ -0,0 +1,33 @@
package com.droiddeck.launcher.session
internal class LatestRequestCoordinator<T> {
data class Request<T>(val generation: Long, val value: T)
private val lock = Any()
private var generation = 0L
private var running = false
private var latest: Request<T>? = null
private var pending: Request<T>? = null
fun submit(value: T): Boolean = synchronized(lock) {
if (latest?.value != value) generation++
pending = Request(generation, value).also { latest = it }
if (running) {
false
} else {
running = true
true
}
}
fun takeLatest(): Request<T>? = synchronized(lock) {
pending.also {
pending = null
if (it == null) running = false
}
}
fun isLatest(request: Request<T>): Boolean = synchronized(lock) {
request.generation == latest?.generation
}
}
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.session
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONObject
import java.io.File
@@ -9,10 +10,12 @@ import java.io.File
object ProtonDefault {
private const val TAG = "ProtonDefault"
private const val DIR = "root/.local/share/droiddeck-compat"
private const val GAMES = "games.json"
data class Tool(val name: String, val display: String, val dir: String, val valve: Boolean)
data class Request(val seq: Long, val valve: Boolean, val dir: String)
data class State(val default: String?, val applied: Long, val live: Boolean, val pending: String?, val tools: List<Tool>)
data class GameChoice(val valve: Boolean, val dir: String)
enum class Outcome { LIVE, NEXT_START, NOT_RUNNABLE }
@@ -60,6 +63,33 @@ object ProtonDefault {
return protons.firstOrNull { it.valve == pick.first && it.dir.name == pick.second }?.id
}
internal fun parseGames(text: String?): Map<String, GameChoice?> {
val root = runCatching { JSONObject(text ?: "") }.getOrNull() ?: return emptyMap()
if (root.optInt("version", 0) != 1) return emptyMap()
val games = root.optJSONObject("games") ?: return emptyMap()
return buildMap {
games.keys().forEach { id ->
if (!GameEnvironment.validScope(id)) return@forEach
if (games.isNull(id)) {
put(id, null)
} else {
val value = games.optJSONObject(id) ?: return@forEach
val gameDir = value.optString("dir")
val valve = value.opt("valve")
if (gameDir.isNotEmpty() && valve is Boolean) put(id, GameChoice(valve, gameDir))
}
}
}
}
fun gameChoice(context: Context, scope: String): GameChoice? =
parseGames(read(File(dir(context), GAMES)))[scope]
fun gameSelectedId(context: Context, scope: String, protons: List<ComponentsManager.Proton>): String? {
val pick = gameChoice(context, scope) ?: return null
return protons.firstOrNull { it.valve == pick.valve && it.dir.name == pick.dir }?.id
}
internal fun nextSeq(now: Long, state: State, previous: Request?): Long =
maxOf(now, state.applied + 1, (previous?.seq ?: 0) + 1)
@@ -83,4 +113,33 @@ object ProtonDefault {
val tool = state.tools.firstOrNull { it.valve == proton.valve && it.dir == proton.dir.name }
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
}
@Synchronized
fun requestGame(context: Context, scope: String, proton: ComponentsManager.Proton?): Outcome {
require(GameEnvironment.validScope(scope))
val d = dir(context)
val choices = parseGames(read(File(d, GAMES))).toMutableMap()
choices[scope] = proton?.let { GameChoice(it.valve, it.dir.name) }
val games = JSONObject()
choices.forEach { (id, choice) ->
games.put(id, choice?.let { JSONObject().put("valve", it.valve).put("dir", it.dir) } ?: JSONObject.NULL)
}
val staged = File(d, "$GAMES.staged")
try {
d.mkdirs()
staged.writeText(JSONObject().put("version", 1).put("games", games).toString(1) + "\n")
if (!staged.renameTo(File(d, GAMES))) throw java.io.IOException("rename failed")
} catch (e: Exception) {
staged.delete()
Log.w(TAG, "could not write the per-game Proton request", e)
throw e
}
val state = state(context)
val tool = proton?.let { selected -> state.tools.firstOrNull { it.valve == selected.valve && it.dir == selected.dir.name } }
return if (SessionState.running && state.live && (proton == null || tool != null && state.pending != tool.name)) {
Outcome.LIVE
} else {
Outcome.NEXT_START
}
}
}
@@ -0,0 +1,70 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.core.FexPreset
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.frontend.Library
data class ProfileValue(val value: String, val inherited: Boolean)
data class SelectedGameProfile(
val appId: Long,
val name: String,
val fexPreset: ProfileValue,
val proton: ProfileValue,
val protonId: String?,
val components: Map<String, ProfileValue>,
val componentFiles: Map<String, String>,
val environmentOverrides: Int,
val windowsComponentNames: List<String>,
) {
val hasOverrides: Boolean
get() = !fexPreset.inherited ||
!proton.inherited ||
components.values.any { !it.inherited } ||
environmentOverrides > 0 ||
windowsComponentNames.isNotEmpty()
companion object {
fun resolve(
selectedAppId: Long,
games: List<Library.SteamGame>,
generalFexPreset: String,
environment: GameEnvironment.Config,
snapshot: ComponentsManager.Snapshot,
generalProtonId: String?,
gameProtonChoice: ProtonDefault.GameChoice?,
gameProtonId: String?,
gameComponents: Map<String, String>,
gameWindowsComponents: List<String>,
): SelectedGameProfile? {
val game = games.firstOrNull { it.profileKey == selectedAppId.toString() } ?: return null
val fexOverride = GameEnvironment.gameFexPreset(environment, game.profileKey)
val selectedProtonId = if (gameProtonChoice == null) generalProtonId else gameProtonId
val selectedProton = snapshot.protons.firstOrNull { it.proton.id == selectedProtonId }
val packages = snapshot.packages.associateBy { it.file }
val components = ComponentsManager.COMPONENTS.associateWith { component ->
val override = gameComponents[component]
ProfileValue(
value = override?.let { packages[it]?.version ?: it }
?: selectedProton?.components?.get(component)?.selected.orEmpty(),
inherited = override == null,
)
}
val otherEnvironment = environment.games[game.profileKey].orEmpty().keys - FexPreset.environmentKeys
return SelectedGameProfile(
appId = selectedAppId,
name = game.name,
fexPreset = ProfileValue(fexOverride ?: generalFexPreset, fexOverride == null),
proton = ProfileValue(
selectedProton?.proton?.name ?: gameProtonChoice?.dir.orEmpty(),
gameProtonChoice == null,
),
protonId = selectedProtonId,
components = components,
componentFiles = gameComponents,
environmentOverrides = otherEnvironment.size,
windowsComponentNames = gameWindowsComponents.map(WinComponentNames::of),
)
}
}
}
@@ -4,12 +4,15 @@ import android.content.Context
import android.content.pm.ActivityInfo
import androidx.annotation.StringRes
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.core.TextureFiltering
import com.droiddeck.launcher.gpu.ScreenEffects
import org.json.JSONObject
/** The in-session switches: the HUD and how the on-screen controls decide to appear. */
object SessionPrefs {
data class GameTextureFiltering(val anisotropy: Int? = null, val lodBias: String? = null)
const val SUSPEND_AUTO = "auto"
const val SUSPEND_NATIVE = "native"
const val SUSPEND_MANUAL = "manual"
@@ -868,6 +871,74 @@ object SessionPrefs {
publishGameEnvironment(context)
}
fun gameTextureFiltering(context: Context, scope: String): GameTextureFiltering {
require(GameEnvironment.validScope(scope))
return gameTextureFiltering(context)[scope] ?: GameTextureFiltering()
}
fun gameTextureFiltering(context: Context): Map<String, GameTextureFiltering> {
val json = runCatching {
JSONObject(prefs(context).getString("gameTextureFiltering", null) ?: "{}")
}.getOrElse { JSONObject() }
return buildMap {
json.keys().forEach { scope ->
if (!GameEnvironment.validScope(scope)) return@forEach
val entry = json.optJSONObject(scope) ?: return@forEach
val anisotropy = entry.optInt("anisotropy").takeIf {
entry.has("anisotropy") && it in TextureFiltering.ANISOTROPY
}
val lodBias = entry.optString("lodBias").takeIf {
entry.has("lodBias") && it in TextureFiltering.LOD_BIAS
}
if (anisotropy != null || lodBias != null) {
put(scope, GameTextureFiltering(anisotropy, lodBias))
}
}
}
}
fun setGameTextureAnisotropy(context: Context, scope: String, value: Int?) {
require(value == null || value in TextureFiltering.ANISOTROPY)
updateGameTextureFiltering(context, scope) { it.copy(anisotropy = value) }
}
fun setGameTextureLodBias(context: Context, scope: String, choice: String?) {
require(choice == null || choice in TextureFiltering.LOD_BIAS)
updateGameTextureFiltering(context, scope) { it.copy(lodBias = choice) }
}
fun clearGameTextureFiltering(context: Context, scope: String) {
require(GameEnvironment.validScope(scope))
val choices = gameTextureFiltering(context).toMutableMap()
if (choices.remove(scope) == null) return
saveGameTextureFiltering(context, choices)
publishGameEnvironment(context)
}
private fun updateGameTextureFiltering(
context: Context,
scope: String,
change: (GameTextureFiltering) -> GameTextureFiltering,
) {
require(GameEnvironment.validScope(scope))
val choices = gameTextureFiltering(context).toMutableMap()
val next = change(choices[scope] ?: GameTextureFiltering())
if (next.anisotropy == null && next.lodBias == null) choices.remove(scope) else choices[scope] = next
saveGameTextureFiltering(context, choices)
publishGameEnvironment(context)
}
private fun saveGameTextureFiltering(context: Context, choices: Map<String, GameTextureFiltering>) {
val json = JSONObject()
choices.forEach { (id, choice) ->
json.put(id, JSONObject().apply {
choice.anisotropy?.let { put("anisotropy", it) }
choice.lodBias?.let { put("lodBias", it) }
})
}
prefs(context).edit().putString("gameTextureFiltering", json.toString()).apply()
}
/** Hands the change to the next game launch (GameEnvironmentStore); the running game keeps its own. */
private fun publishGameEnvironment(context: Context) {
runCatching { GameEnvironmentStore.publish(context) }
@@ -37,6 +37,7 @@ import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Delete
import androidx.compose.material.icons.outlined.Refresh
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
@@ -80,6 +81,19 @@ import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.session.ComponentsManager.CatalogItem
import com.droiddeck.launcher.session.ComponentsManager.Snapshot
import kotlinx.coroutines.delay
import androidx.compose.foundation.layout.widthIn
import androidx.compose.runtime.rememberCoroutineScope
import com.droiddeck.launcher.core.FexPreset
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.frontend.Library
import com.droiddeck.launcher.session.GameEnvironmentStore
import com.droiddeck.launcher.session.GameProfileManager
import com.droiddeck.launcher.session.ProtonDefault
import com.droiddeck.launcher.session.WinComponents
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.text.DateFormat
import java.util.Date
@@ -108,6 +122,13 @@ private class InstalledItem(
val protonVersion: String?,
)
private data class ProfileEditorState(
val environment: GameEnvironment.Config,
val protonChoice: ProtonDefault.GameChoice?,
val protonId: String?,
val components: Map<String, String>,
)
private val GOLD = Color(0xFFF2C66D)
private val QUEUED = Color(0xFFFFB86B)
private val ROW_SHAPE = RoundedCornerShape(10.dp)
@@ -142,6 +163,9 @@ fun ComponentsPage(
onRefresh: () -> Unit,
onImport: () -> Unit,
onBack: () -> Unit,
games: List<Library.SteamGame> = emptyList(),
generalFexPreset: String = "",
onGeneralFexPreset: (String) -> Unit = {},
requestInitialFocus: Boolean = true,
/** The GPU drivers layer ([GPU_TAB]): what it shows and does. */
gpu: GpuDriversState = GpuDriversState(),
@@ -160,6 +184,209 @@ fun ComponentsPage(
val inputMode = LocalInputModeManager.current
val layer = if (comp in LAYERS) comp else GPU_TAB
BackHandler(onBack = onBack)
var scopeMenu by remember { mutableStateOf(false) }
var selectedGameKey by remember { mutableStateOf<String?>(null) }
var fexMenu by remember { mutableStateOf(false) }
var gameProtonMenu by remember { mutableStateOf(false) }
var gameProtonId by remember { mutableStateOf<String?>(null) }
var gameProtonChoice by remember { mutableStateOf<ProtonDefault.GameChoice?>(null) }
var gameComponents by remember { mutableStateOf<Map<String, String>>(emptyMap()) }
var gameComponentMenu by remember { mutableStateOf<String?>(null) }
var environmentEditor by remember { mutableStateOf(false) }
var winComponentsOpen by remember { mutableStateOf<Boolean?>(null) }
var winComponentsRevision by remember { mutableStateOf(0) }
var environment by remember { mutableStateOf<GameEnvironment.Config?>(null) }
var profileLoading by remember { mutableStateOf(false) }
var profileLoadGeneration by remember { mutableStateOf(0L) }
var environmentBusy by remember { mutableStateOf(false) }
var environmentError by remember { mutableStateOf(false) }
var profileNotice by remember { mutableStateOf<String?>(null) }
var confirm by remember { mutableStateOf<Pair<String, () -> Unit>?>(null) }
var confirmTitle by remember { mutableStateOf("") }
var confirmVerb by remember { mutableStateOf(R.string.comp_swap) }
fun ask(title: String, body: String, verb: Int, action: () -> Unit) {
confirmTitle = title
confirmVerb = verb
confirm = body to action
}
val coroutine = rememberCoroutineScope()
val selectedGame = games.firstOrNull { it.profileKey == selectedGameKey }
LaunchedEffect(Unit) {
runCatching { withContext(Dispatchers.IO) { GameEnvironmentStore.read(ctx) } }
.onSuccess { environment = it }
.onFailure { environmentError = true }
}
LaunchedEffect(games, selectedGameKey) {
if (selectedGameKey != null && games.none { it.profileKey == selectedGameKey }) selectedGameKey = null
}
LaunchedEffect(selectedGame?.profileKey, snapshot) {
profileLoadGeneration++
val generation = profileLoadGeneration
val game = selectedGame
profileNotice = null
environmentError = false
gameProtonChoice = null
gameProtonId = null
gameComponents = emptyMap()
gameProtonMenu = false
gameComponentMenu = null
fexMenu = false
if (game == null) {
profileLoading = false
return@LaunchedEffect
}
profileLoading = true
try {
val (choice, id, components) = withContext(Dispatchers.IO) {
val choice = ProtonDefault.gameChoice(ctx, game.profileKey)
Triple(
choice,
ProtonDefault.gameSelectedId(ctx, game.profileKey, snapshot?.protons.orEmpty().map { it.proton }),
ComponentsManager.gameComponents(ctx, game.profileKey),
)
}
if (profileLoadGeneration == generation && selectedGameKey == game.profileKey) {
gameProtonChoice = choice
gameProtonId = id
gameComponents = components
}
} catch (error: CancellationException) {
throw error
} catch (error: Exception) {
if (profileLoadGeneration == generation && selectedGameKey == game.profileKey) {
environmentError = true
profileNotice = ctx.getString(
R.string.comp_game_load_failed,
game.name,
error.message ?: error.javaClass.simpleName,
)
}
} finally {
if (profileLoadGeneration == generation) profileLoading = false
}
}
fun setGameFexPreset(preset: String?) {
val game = selectedGame ?: return
environmentBusy = true
profileNotice = null
coroutine.launch {
runCatching {
withContext(Dispatchers.IO) {
GameEnvironmentStore.setGameFexPreset(ctx, game.profileKey, preset)
}
}.onSuccess { saved ->
environment = saved
if (selectedGameKey == game.profileKey) {
environmentError = false
profileNotice = ctx.getString(R.string.comp_game_saved_next, game.name)
}
}.onFailure {
if (selectedGameKey == game.profileKey) {
environmentError = true
profileNotice = ctx.getString(R.string.comp_game_save_failed, it.message ?: it.javaClass.simpleName)
}
}
environmentBusy = false
}
}
fun setGameProton(id: String?) {
val game = selectedGame ?: return
val proton = id?.let { wanted -> snapshot?.protons?.firstOrNull { it.proton.id == wanted }?.proton }
environmentBusy = true
profileNotice = null
coroutine.launch {
runCatching { withContext(Dispatchers.IO) { ProtonDefault.requestGame(ctx, game.profileKey, proton) } }
.onSuccess { outcome ->
if (selectedGameKey == game.profileKey) {
gameProtonChoice = proton?.let { ProtonDefault.GameChoice(it.valve, it.dir.name) }
gameProtonId = id
environmentError = false
profileNotice = ctx.getString(
when (outcome) {
ProtonDefault.Outcome.LIVE -> R.string.comp_game_proton_live
ProtonDefault.Outcome.NEXT_START -> R.string.comp_game_proton_next
ProtonDefault.Outcome.NOT_RUNNABLE -> R.string.comp_game_proton_not_runnable
},
game.name,
)
}
}
.onFailure {
if (selectedGameKey == game.profileKey) {
environmentError = true
profileNotice = ctx.getString(R.string.comp_game_save_failed, it.message ?: it.javaClass.simpleName)
}
}
environmentBusy = false
}
}
fun setGameComponent(comp: String, file: String?) {
val game = selectedGame ?: return
environmentBusy = true
profileNotice = null
coroutine.launch {
runCatching { withContext(Dispatchers.IO) { ComponentsManager.setGameComponent(ctx, game.profileKey, comp, file) } }
.onSuccess {
val components = ComponentsManager.gameComponents(ctx, game.profileKey)
if (selectedGameKey == game.profileKey) {
gameComponents = components
environmentError = false
profileNotice = ctx.getString(R.string.comp_game_saved_next, game.name)
}
}
.onFailure {
if (selectedGameKey == game.profileKey) {
environmentError = true
profileNotice = ctx.getString(R.string.comp_game_save_failed, it.message ?: it.javaClass.simpleName)
}
}
environmentBusy = false
}
}
fun resetGameProfile() {
val game = selectedGame ?: return
environmentBusy = true
profileNotice = null
coroutine.launch {
runCatching {
withContext(Dispatchers.IO) {
val resetFailure = runCatching { GameProfileManager.reset(ctx, game.profileKey) }.exceptionOrNull()
val config = GameEnvironmentStore.read(ctx)
val choice = ProtonDefault.gameChoice(ctx, game.profileKey)
val id = ProtonDefault.gameSelectedId(
ctx,
game.profileKey,
snapshot?.protons.orEmpty().map { it.proton },
)
val components = ComponentsManager.gameComponents(ctx, game.profileKey)
ProfileEditorState(config, choice, id, components) to resetFailure
}
}.onSuccess { (state, resetFailure) ->
environment = state.environment
if (selectedGameKey == game.profileKey) {
gameProtonChoice = state.protonChoice
gameProtonId = state.protonId
gameComponents = state.components
winComponentsRevision++
environmentError = resetFailure != null
profileNotice = if (resetFailure == null) {
ctx.getString(R.string.comp_game_reset_done, game.name)
} else {
ctx.getString(
R.string.comp_game_reset_failed,
resetFailure.message ?: resetFailure.javaClass.simpleName,
)
}
}
}.onFailure {
if (selectedGameKey == game.profileKey) {
environmentError = true
profileNotice = ctx.getString(R.string.comp_game_reset_failed, it.message ?: it.javaClass.simpleName)
}
}
environmentBusy = false
}
}
val views = snapshot?.protons ?: emptyList()
val view = views.firstOrNull { it.proton.id == protonId } ?: views.firstOrNull()
@@ -247,7 +474,7 @@ fun ComponentsPage(
val layerFocus = remember { LAYERS.associateWith { FocusRequester() } }
// Arrived (from the rail, a hop, a game's card): a pad starts on the chosen layer.
LaunchedEffect(requestInitialFocus) {
if (!requestInitialFocus || inputMode.inputMode != InputMode.Keyboard) return@LaunchedEffect
if (!requestInitialFocus || selectedGame != null || inputMode.inputMode != InputMode.Keyboard) return@LaunchedEffect
delay(Motion.ms(200).toLong())
focusSoon { layerFocus.getValue(layer) }
}
@@ -259,7 +486,7 @@ fun ComponentsPage(
LaunchedEffect(layer) {
if (seenLayer[0] == layer) return@LaunchedEffect
seenLayer[0] = layer
if (!pageFocused || inputMode.inputMode != InputMode.Keyboard) return@LaunchedEffect
if (selectedGame != null || !pageFocused || inputMode.inputMode != InputMode.Keyboard) return@LaunchedEffect
if (narrowOpen != null) runCatching { firstRow.requestFocus() }
else focusSoon { layerFocus.getValue(layer) }
}
@@ -534,6 +761,21 @@ fun ComponentsPage(
Column(Modifier.weight(1f)) { slide { k -> RowGroup(availableTitle(k)) { availableRows(k) } } }
}
Box(Modifier.padding(top = 14.dp)) { slide { k -> actions(k) } }
if (l == "fex") {
SettingsGroup(stringResource(R.string.fex_preset_title)) {
SettingsRow(stringResource(R.string.fex_preset_title), null) {
FexPresetChip(
preset = generalFexPreset,
inherited = false,
open = fexMenu,
enabled = true,
onToggle = { fexMenu = !fexMenu },
onDismiss = { fexMenu = false },
onPick = { it?.let(onGeneralFexPreset) },
)
}
}
}
if (l == PROTON_TAB) {
Spacer(Modifier.height(10.dp))
if (!protons.runtimeReady) EmptyLine(stringResource(R.string.content_needs_runtime))
@@ -550,7 +792,10 @@ fun ComponentsPage(
Box(Modifier.fillMaxSize().onGloballyPositioned { pageAt = it.positionInRoot() }.onFocusChanged { pageFocused = it.hasFocus }) {
Column(
Modifier.fillMaxSize().padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)
.bumpers(onPrevious = { pick(layerStep(layer, -1)) }, onNext = { pick(layerStep(layer, 1)) }),
.then(if (selectedGame == null) Modifier.bumpers(
onPrevious = { pick(layerStep(layer, -1)) },
onNext = { pick(layerStep(layer, 1)) },
) else Modifier),
) {
// ---- header: the title, the device, when the lists were checked and the one refresh ----
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth()) {
@@ -569,29 +814,109 @@ fun ComponentsPage(
}
if (narrow) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 6.dp)) { DeviceChip(gpu) }
Spacer(Modifier.height(14.dp))
Row(Modifier.weight(1f).fillMaxWidth()) {
// ---- the stack ----
Box(
(if (narrow) Modifier.fillMaxWidth() else Modifier.width(250.dp)).fillMaxHeight()
.onGloballyPositioned { stackAt = it.positionInRoot() },
) {
val tint = rememberUpdatedState(pal.signal)
val local = cardsAt[layer]?.translate(-stackAt)
ChipGlide(LAYERS.indexOf(layer), local, tint, GlideAxis.Vertical, corner = 12.dp)
Stack(
layer, view, gpu, focus = layerFocus, landed = landed, rings = rings,
onPlaced = { l, r -> cardsAt[l] = r },
onFocus = { l -> pick(l) },
onOpen = { l ->
pick(l)
if (narrow) narrowOpen = l
else runCatching { firstRow.requestFocus() }
if (games.isNotEmpty()) {
SettingsGroup(stringResource(R.string.comp_profile_configure)) {
SettingsRow(
stringResource(R.string.comp_profile),
if (selectedGame == null) {
stringResource(R.string.comp_scope_general_detail)
} else {
stringResource(R.string.comp_profile_game_detail, selectedGame.name)
},
)
) {
Box {
ValueChip(
selectedGame?.name ?: stringResource(R.string.comp_scope_general),
scopeMenu,
modifier = Modifier.widthIn(max = 320.dp).heightIn(min = 44.dp),
) { scopeMenu = !scopeMenu }
AnchoredMenu(
scopeMenu,
onDismiss = { scopeMenu = false },
title = stringResource(R.string.comp_profile_configure),
) { first ->
MenuItem(
stringResource(R.string.comp_scope_general),
checked = selectedGame == null,
detail = stringResource(R.string.comp_scope_general_detail),
focusRequester = first,
) {
selectedGameKey = null
scopeMenu = false
}
games.sortedBy { it.name.lowercase() }.forEach { game ->
MenuItem(game.name, checked = selectedGameKey == game.profileKey) {
selectedGameKey = game.profileKey
scopeMenu = false
}
}
}
}
}
}
if (!narrow) {
Spacer(Modifier.width(16.dp))
Box(Modifier.weight(1f).fillMaxHeight()) { detail(layer, false) }
}
if (selectedGame != null) {
GameComponentOverrides(
game = selectedGame,
config = environment,
generalFexPreset = generalFexPreset,
generalProton = view?.proton,
protons = views.map { it.proton },
protonId = gameProtonId,
protonChoice = gameProtonChoice,
packages = snapshot?.packages.orEmpty(),
componentChoices = gameComponents,
componentMenu = gameComponentMenu,
protonMenu = gameProtonMenu,
fexMenu = fexMenu,
busy = environmentBusy || profileLoading,
error = environmentError,
notice = profileNotice,
winComponentsRevision = winComponentsRevision,
onFexMenu = { fexMenu = it },
onFexPreset = ::setGameFexPreset,
onProtonMenu = { gameProtonMenu = it },
onProton = ::setGameProton,
onComponentMenu = { gameComponentMenu = it },
onComponent = ::setGameComponent,
onEnvironment = { environmentEditor = true },
onWinComponents = { winComponentsOpen = false },
onReset = {
ask(
ctx.getString(R.string.comp_game_reset_title, selectedGame.name),
ctx.getString(R.string.comp_game_reset_body),
R.string.comp_game_reset,
::resetGameProfile,
)
},
modifier = Modifier.weight(1f).fillMaxWidth(),
)
} else {
Row(Modifier.weight(1f).fillMaxWidth()) {
// ---- the stack ----
Box(
(if (narrow) Modifier.fillMaxWidth() else Modifier.width(250.dp)).fillMaxHeight()
.onGloballyPositioned { stackAt = it.positionInRoot() },
) {
val tint = rememberUpdatedState(pal.signal)
val local = cardsAt[layer]?.translate(-stackAt)
ChipGlide(LAYERS.indexOf(layer), local, tint, GlideAxis.Vertical, corner = 12.dp)
Stack(
layer, view, gpu, focus = layerFocus, landed = landed, rings = rings,
onPlaced = { l, r -> cardsAt[l] = r },
onFocus = { l -> pick(l) },
onOpen = { l ->
pick(l)
if (narrow) narrowOpen = l
else runCatching { firstRow.requestFocus() }
},
)
}
if (!narrow) {
Spacer(Modifier.width(16.dp))
Box(Modifier.weight(1f).fillMaxHeight()) { detail(layer, false) }
}
}
}
}
@@ -636,6 +961,50 @@ fun ComponentsPage(
if (from == null) body() else PageFlood(from, driverLeaving) { body() }
}
}
confirm?.let { (body, action) ->
AlertDialog(
onDismissRequest = { confirm = null },
title = { Text(confirmTitle) },
text = { Text(body, fontSize = 14.sp) },
// Opens on Cancel, so a stray A press on a controller never swaps or deletes anything.
confirmButton = {
val del = confirmVerb == R.string.common_delete || confirmVerb == R.string.comp_game_reset
FocusText(stringResource(confirmVerb), if (del) colors.error else pal.signal) { confirm = null; action() }
},
dismissButton = {
val cancelFocus = remember { FocusRequester() }
LaunchedEffect(Unit) { runCatching { cancelFocus.requestFocus() } }
FocusText(stringResource(R.string.common_cancel), colors.onBackground, modifier = Modifier.focusRequester(cancelFocus)) { confirm = null }
},
)
}
if (environmentEditor && selectedGame != null) {
GameEnvironmentEditor(
byPad = androidx.compose.ui.platform.LocalInputModeManager.current.inputMode == androidx.compose.ui.input.InputMode.Keyboard,
initialScope = selectedGame.profileKey,
) {
environmentEditor = false
coroutine.launch {
runCatching { withContext(Dispatchers.IO) { GameEnvironmentStore.read(ctx) } }
.onSuccess { environment = it; environmentError = false }
.onFailure { environmentError = true }
}
}
}
val winOpen = winComponentsOpen
if (winOpen != null && selectedGame != null) {
WinComponentsDialog(
selectedGame.profileKey,
selectedGame.name,
selectedGame.gameFiles,
winOpen,
compat = selectedGame.protonPrefix,
steamAppId = selectedGame.appId.takeIf { selectedGame.library != Library.ADDED },
) {
winComponentsOpen = null
winComponentsRevision++
}
}
}
/** The Installed rows of one component layer for the Proton the page shows. */
@@ -798,6 +1167,253 @@ private fun EmptyLine(text: String) {
Text(text, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp))
}
@Composable
private fun GameComponentOverrides(
game: Library.SteamGame,
config: GameEnvironment.Config?,
generalFexPreset: String,
generalProton: ComponentsManager.Proton?,
protons: List<ComponentsManager.Proton>,
protonId: String?,
protonChoice: ProtonDefault.GameChoice?,
packages: List<ComponentsManager.Package>,
componentChoices: Map<String, String>,
componentMenu: String?,
protonMenu: Boolean,
fexMenu: Boolean,
busy: Boolean,
error: Boolean,
notice: String?,
winComponentsRevision: Int,
onFexMenu: (Boolean) -> Unit,
onFexPreset: (String?) -> Unit,
onProtonMenu: (Boolean) -> Unit,
onProton: (String?) -> Unit,
onComponentMenu: (String?) -> Unit,
onComponent: (String, String?) -> Unit,
onEnvironment: () -> Unit,
onWinComponents: () -> Unit,
onReset: () -> Unit,
modifier: Modifier = Modifier,
) {
val context = LocalContext.current
val override = config?.let { GameEnvironment.gameFexPreset(it, game.profileKey) }
val proton = protons.firstOrNull { it.id == protonId }
val effectiveProton = if (protonChoice == null) generalProton else proton
val picks = remember(game.profileKey, winComponentsRevision) { WinComponents.picks(context, game.profileKey) }
Column(
verticalArrangement = Arrangement.spacedBy(14.dp),
modifier = modifier.verticalScroll(rememberScrollState()).padding(top = 14.dp, bottom = 16.dp),
) {
Text(
stringResource(R.string.comp_game_hint),
fontSize = 13.sp,
color = MaterialTheme.colorScheme.onSurfaceVariant,
)
SettingsGroup(stringResource(R.string.fex_preset_title)) {
SettingsRow(
stringResource(R.string.comp_game_fex),
stringResource(if (override == null) R.string.comp_game_fex_inherited else R.string.comp_game_fex_override),
) {
FexPresetChip(
preset = override ?: generalFexPreset,
inherited = override == null,
open = fexMenu,
enabled = config != null && !busy,
allowInheritance = true,
onToggle = { onFexMenu(!fexMenu) },
onDismiss = { onFexMenu(false) },
onPick = onFexPreset,
)
}
GamePackageRow(
comp = "fex",
packages = packages,
selectedFile = componentChoices["fex"],
open = componentMenu == "fex",
busy = busy,
onMenu = onComponentMenu,
onPick = onComponent,
)
}
SettingsGroup(stringResource(R.string.comp_game_compatibility)) {
SettingsRow(
stringResource(R.string.comp_proton),
stringResource(if (protonChoice == null) R.string.comp_game_proton_inherited else R.string.comp_game_proton_override),
) {
Box {
ValueChip(
proton?.name ?: protonChoice?.dir ?: stringResource(R.string.comp_game_use_general),
protonMenu,
enabled = protons.isNotEmpty() && !busy,
modifier = Modifier.widthIn(max = 280.dp),
) { onProtonMenu(!protonMenu) }
AnchoredMenu(
protonMenu,
onDismiss = { onProtonMenu(false) },
title = stringResource(R.string.comp_proton),
) { first ->
MenuItem(
stringResource(R.string.comp_game_use_general),
checked = protonChoice == null,
focusRequester = first,
) { onProton(null); onProtonMenu(false) }
protons.forEach { option ->
MenuItem(option.name, checked = proton?.id == option.id) {
onProton(option.id)
onProtonMenu(false)
}
}
}
}
}
GamePackageRow(
comp = "dxvk",
packages = packages,
selectedFile = componentChoices["dxvk"],
open = componentMenu == "dxvk",
busy = busy,
proton = effectiveProton,
onMenu = onComponentMenu,
onPick = onComponent,
onRuntimeOptions = onEnvironment,
)
GamePackageRow(
comp = "vkd3d",
packages = packages,
selectedFile = componentChoices["vkd3d"],
open = componentMenu == "vkd3d",
busy = busy,
proton = effectiveProton,
onMenu = onComponentMenu,
onPick = onComponent,
onRuntimeOptions = onEnvironment,
)
SettingsRow(
stringResource(R.string.game_env_title),
stringResource(R.string.comp_game_environment_other_hint),
) {
SecondaryButton(stringResource(R.string.game_env_edit), enabled = !busy, onClick = onEnvironment)
}
SettingsRow(
stringResource(R.string.wincomp_title),
if (picks.isEmpty()) stringResource(R.string.wincomp_card_none)
else picks.joinToString(", ") { com.droiddeck.launcher.session.WinComponentNames.of(it) },
) {
SecondaryButton(stringResource(R.string.game_env_edit), onClick = onWinComponents)
}
}
notice?.let {
Text(
it,
fontSize = 13.sp,
color = if (error) MaterialTheme.colorScheme.error else LocalPalette.current.good,
)
}
if (error && notice == null) Text(stringResource(R.string.game_env_error), fontSize = 13.sp, color = MaterialTheme.colorScheme.error)
if (!busy) {
FocusText(
stringResource(R.string.comp_game_reset),
MaterialTheme.colorScheme.error,
onClick = onReset,
)
}
if (busy) LinearProgressIndicator(Modifier.fillMaxWidth())
}
}
@Composable
private fun GamePackageRow(
comp: String,
packages: List<ComponentsManager.Package>,
selectedFile: String?,
open: Boolean,
busy: Boolean,
proton: ComponentsManager.Proton? = null,
onMenu: (String?) -> Unit,
onPick: (String, String?) -> Unit,
onRuntimeOptions: (() -> Unit)? = null,
) {
val choices = packages.filter { it.comp == comp }
val selected = choices.firstOrNull { it.file == selectedFile }
val title = ComponentsManager.LABEL[comp] ?: comp
SettingsRow(
title,
if (selected == null) {
if (proton == null) stringResource(R.string.comp_game_component_general)
else stringResource(R.string.comp_game_component_runtime, proton.name)
} else stringResource(R.string.comp_game_component_override, selected.version),
) {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
Box {
ValueChip(
selected?.version ?: stringResource(R.string.comp_game_use_general),
open,
enabled = !busy,
modifier = Modifier.widthIn(max = 240.dp),
) { onMenu(if (open) null else comp) }
AnchoredMenu(open, onDismiss = { onMenu(null) }, title = title) { first ->
MenuItem(
stringResource(R.string.comp_game_use_general),
checked = selected == null,
focusRequester = first,
) { onPick(comp, null); onMenu(null) }
choices.forEach { option ->
MenuItem(option.version, checked = option.file == selectedFile, detail = option.description) {
onPick(comp, option.file)
onMenu(null)
}
}
}
}
if (onRuntimeOptions != null) {
SecondaryButton(stringResource(R.string.comp_game_runtime_options), enabled = !busy, onClick = onRuntimeOptions)
}
}
}
}
@Composable
internal fun FexPresetChip(
preset: String,
inherited: Boolean,
open: Boolean,
enabled: Boolean,
onToggle: () -> Unit,
onDismiss: () -> Unit,
onPick: (String?) -> Unit,
allowInheritance: Boolean = false,
modifier: Modifier = Modifier,
) {
val chosen = FexPreset.all.firstOrNull { it.id == preset }
val label = when {
preset == GameEnvironment.CUSTOM_FEX_PRESET -> stringResource(R.string.comp_game_fex_custom)
chosen == null -> stringResource(FexPreset.byId("").label)
inherited -> stringResource(R.string.comp_game_use_general)
else -> stringResource(chosen.label)
}
Box {
ValueChip(label, open, enabled = enabled, modifier = modifier.widthIn(max = 260.dp), onClick = onToggle)
AnchoredMenu(open && enabled, onDismiss = onDismiss, title = stringResource(R.string.fex_preset_title)) { first ->
if (allowInheritance) {
MenuItem(
stringResource(R.string.comp_game_use_general),
checked = inherited,
focusRequester = first,
) { onPick(null); onDismiss() }
}
FexPreset.all.forEachIndexed { index, option ->
MenuItem(
stringResource(option.label),
checked = !inherited && option.id == preset,
detail = stringResource(option.detail),
focusRequester = if (index == 0 && !allowInheritance) first else null,
) { onPick(option.id); onDismiss() }
}
}
}
}
@Composable
internal fun ToolIcon(icon: ImageVector, description: String, busy: Boolean = false, enabled: Boolean = true, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -478,10 +478,7 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current
// The game's prefix is compatdata/<id>, as droiddeck-game-env reads it: a Steam title's appid, an
// added game's shortcut appid (unsigned). Recommended scans the game's own folder either way.
val wincompKey = game?.let {
if (it.library == com.droiddeck.launcher.frontend.Library.ADDED) Integer.toUnsignedString(it.appId)
else it.appId.takeIf { id -> id > 0 }?.toString()
}
val wincompKey = game?.takeIf { it.library == com.droiddeck.launcher.frontend.Library.ADDED || it.appId > 0 }?.profileKey
var wincompOpen by remember(wincompKey) { mutableStateOf<Boolean?>(null) }
val wincompPicks = remember(wincompKey, wincompOpen) { wincompKey?.let { com.droiddeck.launcher.session.WinComponents.picks(context, it) }.orEmpty() }
val cards = buildList<@Composable (Modifier) -> Unit> {
@@ -52,7 +52,11 @@ import kotlinx.coroutines.withContext
// dialog, with each variable's actions in a menu off its value as everywhere else.
@Composable
fun GameEnvironmentRow(modifier: Modifier = Modifier, showHint: Boolean = true) {
fun GameEnvironmentRow(
modifier: Modifier = Modifier,
showHint: Boolean = true,
initialScope: String = "",
) {
var open by remember { mutableStateOf(false) }
// Opened with a pad, the editor starts with focus in it; the dialog is a window of its own and
// would otherwise give the pad nothing to move from.
@@ -64,7 +68,7 @@ fun GameEnvironmentRow(modifier: Modifier = Modifier, showHint: Boolean = true)
open = true
}
}
if (open) GameEnvironmentEditor(byPad) { open = false }
if (open) GameEnvironmentEditor(byPad, initialScope) { open = false }
}
/** With a pad driving, focus [target] once the dialog is laid out, and keep the dialog in pad mode. */
@@ -81,19 +85,19 @@ internal fun PadFocus(byPad: Boolean, target: FocusRequester) {
}
@Composable
private fun GameEnvironmentEditor(byPad: Boolean, onClose: () -> Unit) {
internal fun GameEnvironmentEditor(byPad: Boolean, initialScope: String = "", onClose: () -> Unit) {
val context = LocalContext.current
val coroutine = rememberCoroutineScope()
val shown = rememberShown(onClose)
val close = { shown.targetState = false }
var config by remember { mutableStateOf<GameEnvironment.Config?>(null) }
var games by remember { mutableStateOf(emptyList<Pair<String, String>>()) }
var scope by remember { mutableStateOf("") }
var scope by remember { mutableStateOf(initialScope) }
var otherId by remember { mutableStateOf<String?>(null) }
var menu by remember { mutableStateOf<String?>(null) }
var busy by remember { mutableStateOf(false) }
var error by remember { mutableStateOf(false) }
var editing by remember { mutableStateOf<Pair<String, String>?>(null) }
var editing by remember { mutableStateOf<EnvironmentVariableEdit?>(null) }
val preset = SessionPrefs.fexPreset(context)
val forceSsbs = SessionPrefs.forceSsbs(context)
val firstFocus = remember { FocusRequester() }
@@ -168,7 +172,7 @@ private fun GameEnvironmentEditor(byPad: Boolean, onClose: () -> Unit) {
VariableRow(
name, value, inherited = !own.containsKey(name), open = menu == "var:$name", enabled = !busy,
onToggle = { menu = if (menu == "var:$name") null else "var:$name" }, onDismiss = { if (menu == "var:$name") menu = null },
onEdit = { menu = null; editByPad = dialogInput.inputMode == InputMode.Keyboard; editing = name to (value ?: "") },
onEdit = { menu = null; editByPad = dialogInput.inputMode == InputMode.Keyboard; editing = EnvironmentVariableEdit(scope, profileName, name, value ?: "") },
// A value set here or inherited can be switched off for this profile; one set here can go back to inheriting.
onUnset = if (value != null) ({ menu = null; save(current.withEntries(scope, own + (name to null))) }) else null,
onRestore = if (own.containsKey(name)) ({ menu = null; save(current.withEntries(scope, own - name)) }) else null,
@@ -185,9 +189,9 @@ private fun GameEnvironmentEditor(byPad: Boolean, onClose: () -> Unit) {
SecondaryButton(stringResource(R.string.game_env_add), enabled = !busy) { menu = if (menu == "add") null else "add" }
AnchoredMenu(menu == "add", onDismiss = { if (menu == "add") menu = null }, title = stringResource(R.string.game_env_add)) { first ->
for ((i, option) in GameEnvironmentOptions.all.withIndex()) MenuItem(option.name, checked = false, focusRequester = if (i == 0) first else null) {
menu = null; editByPad = dialogInput.inputMode == InputMode.Keyboard; editing = option.name to option.value
menu = null; editByPad = dialogInput.inputMode == InputMode.Keyboard; editing = EnvironmentVariableEdit(scope, profileName, option.name, option.value)
}
MenuItem(stringResource(R.string.game_env_custom), checked = false) { menu = null; editByPad = dialogInput.inputMode == InputMode.Keyboard; editing = "" to "" }
MenuItem(stringResource(R.string.game_env_custom), checked = false) { menu = null; editByPad = dialogInput.inputMode == InputMode.Keyboard; editing = EnvironmentVariableEdit(scope, profileName, "", "") }
}
}
if (current != null && current.entries(scope).isNotEmpty()) FocusText(stringResource(R.string.game_env_reset), LocalPalette.current.signal) {
@@ -197,19 +201,21 @@ private fun GameEnvironmentEditor(byPad: Boolean, onClose: () -> Unit) {
PrimaryButton(stringResource(R.string.game_env_done), enabled = !busy, onClick = close)
}
}
editing?.let { (name, value) ->
VariableDialog(name, value, profileName, editByPad, onDismiss = { editing = null }) { key, content ->
editing?.let { edit ->
VariableDialog(edit.name, edit.value, edit.profileName, editByPad, onDismiss = { editing = null }) { key, content ->
config?.let {
val entries = it.entries(scope).toMutableMap()
if (name.isNotEmpty() && name != key) entries[name] = null
val entries = it.entries(edit.scope).toMutableMap()
if (edit.name.isNotEmpty() && edit.name != key) entries[edit.name] = null
entries[key] = content
save(it.withEntries(scope, entries))
save(it.withEntries(edit.scope, entries))
}
editing = null
}
}
}
private data class EnvironmentVariableEdit(val scope: String, val profileName: String, val name: String, val value: String)
/** The panel the profile and the variables sit in, as a settings group does. */
@Composable
private fun Panel(content: @Composable androidx.compose.foundation.layout.ColumnScope.() -> Unit) =
@@ -18,6 +18,7 @@ import androidx.compose.ui.input.key.type
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import kotlin.math.roundToInt
@@ -88,6 +89,9 @@ import com.droiddeck.launcher.HomeApp
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Spring
import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.session.ProfileValue
import com.droiddeck.launcher.session.SelectedGameProfile
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.semantics.stateDescription
@@ -205,8 +209,8 @@ class DrawerActions(
/** The compositor's post chain (gpu/ScreenEffects), changed live. */
val effects: ScreenEffects = ScreenEffects.OFF,
/** Texture filtering for DirectX 9-11 games (core/TextureFiltering); lands on their next launch. */
val textureAnisotropy: Int = 0,
val textureLodBias: String = TextureFiltering.LOD_BIAS_OFF,
val textureAnisotropy: Int? = 0,
val textureLodBias: String? = TextureFiltering.LOD_BIAS_OFF,
val secondScreenMode: SecondScreenMode,
val secondScreenDisplays: List<SecondScreenDisplay>,
val selectedSecondScreenDisplay: Int,
@@ -235,8 +239,8 @@ class DrawerActions(
val onUpscaler: (Int) -> Unit = {},
val onUpscaleSharpness: (Int) -> Unit = {},
val onEffects: (ScreenEffects) -> Unit = {},
val onTextureAnisotropy: (Int) -> Unit = {},
val onTextureLodBias: (String) -> Unit = {},
val onTextureAnisotropy: (Int?) -> Unit = {},
val onTextureLodBias: (String?) -> Unit = {},
val onSecondScreenMode: (SecondScreenMode) -> Unit,
val onSecondScreenDisplay: (Int) -> Unit,
val onLaunchAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit,
@@ -257,8 +261,22 @@ class DrawerActions(
val components: ComponentsManager.Snapshot? = null,
/** Re-reads the Protons (and runs swaps that waited for a game to close). */
val onComponentsRefresh: () -> Unit = {},
/** Installed games available for profile inspection in the session drawer. */
val gameProfiles: List<Pair<Long, String>> = emptyList(),
/** The selected game profile, or null for the Default profile. */
val selectedGameProfileId: Long? = null,
val selectedGameProfile: SelectedGameProfile? = null,
val gameProfilesLoaded: Boolean = false,
val gameProfileRefreshFailed: Boolean = false,
val onSelectedGameProfile: (Long?) -> Unit = {},
val onGameProfilesPageOpened: () -> Unit = {},
val onSelectedGameProfileRefresh: () -> Unit = {},
val gameFexPresetSaving: Boolean = false,
val onGameFexPreset: (Long, String?) -> Unit = { _, _ -> },
/** Swaps [value] ("orig:<build>" or a stored package file) into a Proton's component. */
val onComponentSwap: (protonId: String, comp: String, value: String) -> Unit = { _, _, _ -> },
/** Saves a stored package for a game, or null to inherit that component from the Default profile. */
val onGameComponent: (appId: Long, comp: String, file: String?) -> Unit = { _, _, _ -> },
)
@OptIn(ExperimentalComposeUiApi::class)
@@ -286,7 +304,19 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
}
BackHandler(enabled = open && confirmStop) { confirmStop = false }
LaunchedEffect(page) { host.open = null; appToChooseDisplay = null }
LaunchedEffect(open, page) { if (open && page == SessionDrawerPage.GAMES) a.onComponentsRefresh() }
LaunchedEffect(a.selectedGameProfileId) {
if (host.open == "fex") host.open = null
}
LaunchedEffect(open, page) {
if (open && page == SessionDrawerPage.GAMES) {
a.onGameProfilesPageOpened()
a.onComponentsRefresh()
while (true) {
a.onSelectedGameProfileRefresh()
delay(1_000)
}
}
}
LaunchedEffect(open, controllerActive) {
if (open && !controllerActive) focusManager.clearFocus(force = true)
}
@@ -479,14 +509,17 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont
SecondScreenGroup(host, a) { key -> focus.track(page, key) }
}
SessionDrawerPage.GAMES -> {
if (a.steam) SelectedGameProfileGroup(host, a) { key -> focus.track(page, key) }
Text(stringResource(R.string.fex_next_launch), fontSize = 12.sp,
color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp))
TextureFilteringGroup(host, a) { key -> focus.track(page, key) }
if (a.steam) SettingsGroup(stringResource(R.string.game_settings_title)) {
ChoiceRow(host, "fex", stringResource(R.string.fex_preset_title), null,
FexPreset.all.map { it.id to stringResource(it.label) }, a.fexPreset,
chipModifier = focus.track(page, "fex"), onPick = a.onFexPreset)
GameEnvironmentRow(modifier = focus.track(page, "game-env"), showHint = false)
DrawerFexPresetRow(host, a, focus.track(page, "fex"))
GameEnvironmentRow(
modifier = focus.track(page, "game-env"),
showHint = false,
initialScope = a.selectedGameProfileId?.toString().orEmpty(),
)
}
ComponentsDrawerPage(host, a) { key -> focus.track(page, key) }
}
@@ -874,20 +907,187 @@ private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String)
}
}
@Composable
private fun DrawerFexPresetRow(host: MenuHost, a: DrawerActions, modifier: Modifier) {
val appId = a.selectedGameProfileId
val profile = a.selectedGameProfile?.takeIf { it.appId == appId }
val inherited = profile?.fexPreset?.inherited == true
val hint = if (profile == null) null else stringResource(
if (inherited) R.string.comp_game_fex_inherited else R.string.comp_game_fex_override,
)
SettingsRow(stringResource(R.string.fex_preset_title), hint, highlighted = host.open == "fex") {
if (appId != null && profile == null) {
ValueChip("-", false, enabled = false, modifier = modifier) {}
} else {
FexPresetChip(
preset = profile?.fexPreset?.value ?: a.fexPreset,
inherited = inherited,
open = host.open == "fex",
enabled = !a.gameFexPresetSaving,
onToggle = { host.open = if (host.open == "fex") null else "fex" },
onDismiss = { if (host.open == "fex") host.open = null },
onPick = { preset ->
if (appId == null) {
preset?.let(a.onFexPreset)
} else {
a.onGameFexPreset(appId, preset)
}
},
allowInheritance = appId != null,
modifier = modifier,
)
}
}
}
/** Texture filtering on the Games page: DXVK options for the next DirectX 9-11 launch. */
@Composable
private fun TextureFilteringGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
val inherited = a.selectedGameProfileId != null
val anisotropyChoices: List<Pair<Int?, String>> =
(if (inherited) listOf(null to stringResource(R.string.comp_game_use_general)) else emptyList()) +
SessionPrefs.textureAnisotropyChoices(LocalContext.current).map { (value, label) -> value as Int? to label }
val lodBiasChoices: List<Pair<String?, String>> =
(if (inherited) listOf(null to stringResource(R.string.comp_game_use_general)) else emptyList()) +
SessionPrefs.textureLodBiasChoices(LocalContext.current).map { (value, label) -> value as String? to label }
SettingsGroup(stringResource(R.string.drawer_texture)) {
ChoiceRow(host, "anisotropy", stringResource(R.string.drawer_anisotropy), null,
SessionPrefs.textureAnisotropyChoices(LocalContext.current), a.textureAnisotropy, chipModifier = track("anisotropy"), onPick = a.onTextureAnisotropy)
anisotropyChoices, a.textureAnisotropy, chipModifier = track("anisotropy"), onPick = a.onTextureAnisotropy)
ChoiceRow(host, "texture-sharpness", stringResource(R.string.drawer_texture_sharpness), null,
SessionPrefs.textureLodBiasChoices(LocalContext.current), a.textureLodBias, note = stringResource(R.string.drawer_texture_sharpness_note),
lodBiasChoices, a.textureLodBias, note = stringResource(R.string.drawer_texture_sharpness_note),
chipModifier = track("texture-sharpness"), onPick = a.onTextureLodBias)
}
}
private fun signed(v: Int) = if (v > 0) "+$v" else "$v"
@Composable
private fun SelectedGameProfileGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
val colors = MaterialTheme.colorScheme
val options: List<Pair<Long?, String>> = listOf(null to stringResource(R.string.comp_scope_general)) +
a.gameProfiles.map { (id, name) -> Pair(id, name) }
val profile = a.selectedGameProfile
SettingsGroup(stringResource(R.string.drawer_selected_profile)) {
DrawerStackedChoice(
host = host,
key = "game-profile",
label = stringResource(R.string.comp_profile),
hint = if (a.selectedGameProfileId == null) stringResource(R.string.comp_scope_general_detail)
else stringResource(R.string.drawer_profile_inspect_hint),
options = options,
selected = a.selectedGameProfileId,
chipModifier = track("game-profile"),
onPick = a.onSelectedGameProfile,
)
if (a.gameProfileRefreshFailed) {
Text(
stringResource(
if (a.gameProfilesLoaded) {
R.string.drawer_profile_refresh_failed_stale
} else {
R.string.drawer_profile_refresh_failed_initial
},
),
fontSize = 13.sp,
color = colors.error,
modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp),
)
}
if (a.selectedGameProfileId == null) return@SettingsGroup
if (profile == null) {
if (!a.gameProfileRefreshFailed) Text(
stringResource(R.string.drawer_selected_profile_none),
fontSize = 13.sp,
color = colors.onSurfaceVariant,
modifier = Modifier.padding(14.dp),
)
return@SettingsGroup
}
val hasOverrides = profile.hasOverrides ||
a.textureAnisotropy != null ||
a.textureLodBias != null
Column(modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 11.dp)) {
Text(
stringResource(
if (hasOverrides) R.string.drawer_profile_custom
else R.string.drawer_profile_default,
),
fontSize = 12.sp,
color = colors.onSurfaceVariant,
modifier = Modifier.padding(bottom = if (hasOverrides) 5.dp else 0.dp),
)
if (!profile.fexPreset.inherited) {
ProfileSummaryRow(stringResource(R.string.comp_game_fex), fexProfileLabel(profile.fexPreset))
}
if (!profile.proton.inherited) {
ProfileSummaryRow(stringResource(R.string.comp_proton), profileValueLabel(profile.proton))
}
for (component in ComponentsManager.COMPONENTS) {
val value = profile.components.getValue(component)
if (!value.inherited) {
ProfileSummaryRow(ComponentsManager.LABEL.getValue(component), profileValueLabel(value))
}
}
if (profile.environmentOverrides > 0) {
ProfileSummaryRow(
stringResource(R.string.game_env_title),
pluralStringResource(
R.plurals.drawer_profile_environment_overrides,
profile.environmentOverrides,
profile.environmentOverrides,
),
)
}
if (profile.windowsComponentNames.isNotEmpty()) {
ProfileSummaryRow(
stringResource(R.string.wincomp_title),
profile.windowsComponentNames.joinToString(", "),
)
}
a.textureAnisotropy?.let { value ->
ProfileSummaryRow(
stringResource(R.string.drawer_anisotropy),
SessionPrefs.textureAnisotropyChoices(LocalContext.current)
.firstOrNull { it.first == value }?.second.orEmpty(),
)
}
a.textureLodBias?.let { value ->
ProfileSummaryRow(
stringResource(R.string.drawer_texture_sharpness),
SessionPrefs.textureLodBiasChoices(LocalContext.current)
.firstOrNull { it.first == value }?.second.orEmpty(),
)
}
}
}
}
@Composable
private fun fexProfileLabel(value: ProfileValue): String {
return when (value.value) {
GameEnvironment.CUSTOM_FEX_PRESET -> stringResource(R.string.comp_game_fex_custom)
else -> stringResource(FexPreset.byId(value.value).label)
}
}
@Composable
private fun profileValueLabel(value: ProfileValue) =
value.value.ifEmpty { stringResource(R.string.comp_no_proton_short) }
@Composable
private fun ProfileSummaryRow(label: String, value: String) {
Row(modifier = Modifier.fillMaxWidth().padding(top = 3.dp)) {
Text(label, fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.width(96.dp))
Text(
value,
fontSize = 12.sp,
color = MaterialTheme.colorScheme.onBackground,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
}
/**
* The Games tab's components: quick swaps between what is already installed, per Proton. A swap
* into the Proton a running game uses waits until that game closes; downloading, importing and
@@ -903,6 +1103,54 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
}
return
}
val gameProfile = a.selectedGameProfileId?.let { appId ->
a.selectedGameProfile?.takeIf { it.appId == appId }
}
if (a.selectedGameProfileId != null) {
if (gameProfile == null) {
SettingsGroup(stringResource(R.string.drawer_page_components)) {
Text(
stringResource(R.string.comp_reading),
fontSize = 13.sp,
color = colors.onSurfaceVariant,
modifier = Modifier.padding(14.dp),
)
}
return
}
SettingsGroup(stringResource(R.string.drawer_page_components)) {
Column(modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 11.dp)) {
ProfileSummaryRow(stringResource(R.string.comp_proton), gameProfile.proton.value)
}
for (comp in ComponentsManager.COMPONENTS) {
val value = gameProfile.components.getValue(comp)
val options: List<Pair<String?, String>> =
listOf(null to stringResource(R.string.comp_game_use_general)) +
snap.packages.filter { it.comp == comp }.map { it.file to it.version }
DrawerStackedChoice(
host = host,
key = "game-cmp-$comp",
label = ComponentsManager.LABEL.getValue(comp),
hint = if (value.inherited) {
stringResource(R.string.drawer_component_inherited, value.value)
} else {
null
},
options = options,
selected = gameProfile.componentFiles[comp],
chipModifier = track("cmp-$comp"),
onPick = { file -> a.onGameComponent(gameProfile.appId, comp, file) },
)
}
}
Text(
stringResource(R.string.drawer_game_components_note, gameProfile.name),
fontSize = 12.sp,
color = colors.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 4.dp, vertical = 12.dp),
)
return
}
val running = snap.protons.filter { it.inUseByGame }
var pick by rememberSaveable { mutableStateOf<String?>(null) }
val view = snap.protons.firstOrNull { it.proton.id == pick } ?: running.firstOrNull() ?: snap.protons.firstOrNull()