Games: launch options for Steam games in the Edit screen, shared with Steam's Properties (#1888)

This commit is contained in:
K11MCH1 authored and GitHub committed 2026-10-31 13:36:39 -04:00
1 parent ac132a23e2
commit 88719f25d2
37 files changed
+488 -4

No files matched your search

@@ -0,0 +1,162 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.SteamLiveShortcuts
import java.io.File
import java.nio.file.Files
import java.nio.file.StandardCopyOption
object SteamLaunchOptions {
private const val TAG = "SteamLaunchOptions"
private val STEAM = listOf("UserLocalConfigStore", "Software", "Valve", "Steam")
fun current(context: Context, appId: Int): String =
SteamLiveShortcuts.launchOptions(context, appId.toLong()) ?: steam(SessionPrefs.activeSteamRoot(context), appId).orEmpty()
enum class Saved { YES, NO, DESKTOP }
fun set(context: Context, appId: Int, options: String, shown: String): Saved {
val value = options.trim()
if (SessionState.running && SessionState.mode == SessionService.MODE_DESKTOP) return Saved.DESKTOP
if (SessionState.running && SessionState.mode == SessionService.MODE_STEAM) {
val live = SteamLiveShortcuts.launchOptions(context, appId.toLong()) ?: return Saved.NO
if (live.trim() != shown.trim()) return Saved.NO
return if (SteamLiveShortcuts.setLaunchOptions(context, appId.toLong(), value)) Saved.YES else Saved.NO
}
val home = SessionPrefs.activeSteamRoot(context)
if (steam(home, appId).orEmpty().trim() != shown.trim()) return Saved.NO
return if (write(home, appId, value)) Saved.YES else Saved.NO
}
internal fun steam(steamHome: File, appId: Int): String? {
val config = AddedGames.accountConfig(steamHome) ?: return null
val text = runCatching { File(config, "localconfig.vdf").readText() }.getOrNull() ?: return null
return launchOptions(text, appId)
}
internal fun write(steamHome: File, appId: Int, options: String): Boolean {
val config = AddedGames.accountConfig(steamHome)?.let { File(it, "localconfig.vdf") } ?: return false
val text = runCatching { config.readText() }.getOrNull() ?: return false
val updated = withLaunchOptions(text, appId, options) ?: return false
if (updated == text) return true
val staged = File(config.parentFile, config.name + ".staged")
return try {
staged.writeText(updated)
if (config.readText() != text) {
staged.delete()
return false
}
Files.move(staged.toPath(), config.toPath(), StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
true
} catch (e: Exception) {
staged.delete()
Log.w(TAG, "could not write launch options to ${config.path}", e)
false
}
}
internal fun launchOptions(text: String, appId: Int): String? {
val app = section(text, STEAM + "apps" + appId.toString()) ?: return null
return entries(text, app.valueStart, app.end).firstOrNull { !it.section && it.key.equals("LaunchOptions", true) }
?.let { unescape(text.substring(it.valueStart + 1, it.end)) }
}
internal fun withLaunchOptions(text: String, appId: Int, options: String): String? {
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
var updated = text
var path = STEAM
for (key in listOf("apps", appId.toString())) {
updated = withSection(updated, section(updated, path) ?: return null, key, newline) ?: return null
path = path + key
}
val app = section(updated, path) ?: return null
val value = "\"" + escape(options) + "\""
entries(updated, app.valueStart, app.end).firstOrNull { !it.section && it.key.equals("LaunchOptions", true) }?.let {
return updated.replaceRange(it.valueStart, it.end + 1, value)
}
val lineStart = closingLine(updated, app) ?: return null
val indent = updated.substring(lineStart, app.end) + "\t"
return updated.substring(0, lineStart) + indent + "\"LaunchOptions\"\t\t" + value + newline + updated.substring(lineStart)
}
private class Entry(val key: String, val valueStart: Int, val end: Int, val section: Boolean)
private fun section(text: String, path: List<String>): Entry? {
var found: Entry? = null
for (key in path) {
found = entries(text, found?.valueStart ?: -1, found?.end ?: text.length)
.firstOrNull { it.section && it.key.equals(key, true) } ?: return null
}
return found
}
private fun entries(text: String, open: Int, close: Int): List<Entry> {
val found = ArrayList<Entry>()
var key: String? = null
var i = open + 1
while (i < close) {
when {
text[i] == '"' -> {
val end = stringEnd(text, i) ?: return found
if (key == null) key = unescape(text.substring(i + 1, end)) else { found += Entry(key, i, end, false); key = null }
i = end + 1
}
text[i] == '{' -> {
val end = sectionEnd(text, i) ?: return found
key?.let { found += Entry(it, i, end, true) }
key = null
i = end + 1
}
text.startsWith("//", i) -> i = text.indexOf('\n', i).let { if (it < 0) close else it }
else -> i++
}
}
return found
}
private fun stringEnd(text: String, open: Int): Int? {
var i = open + 1
while (i < text.length) {
when (text[i]) {
'\\' -> i += 2
'"' -> return i
else -> i++
}
}
return null
}
private fun sectionEnd(text: String, open: Int): Int? {
var depth = 0
var i = open
while (i < text.length) {
when (text[i]) {
'"' -> i = stringEnd(text, i) ?: return null
'{' -> depth++
'}' -> if (--depth == 0) return i
}
i++
}
return null
}
private fun withSection(text: String, parent: Entry, key: String, newline: String): String? {
if (entries(text, parent.valueStart, parent.end).any { it.section && it.key.equals(key, true) }) return text
val lineStart = closingLine(text, parent) ?: return null
val indent = text.substring(lineStart, parent.end) + "\t"
return text.substring(0, lineStart) + "$indent\"$key\"$newline$indent{$newline$indent}$newline" + text.substring(lineStart)
}
private fun closingLine(text: String, section: Entry): Int? {
val lineStart = text.lastIndexOf('\n', section.end - 1) + 1
return lineStart.takeIf { lineStart > section.valueStart && text.substring(lineStart, section.end).all { it == '\t' || it == ' ' } }
}
private fun escape(value: String) = value.replace("\\", "\\\\").replace("\"", "\\\"")
private fun unescape(value: String) = value.replace(Regex("\\\\(.)"), "$1")
}
@@ -92,6 +92,28 @@ object SteamLiveShortcuts {
if (evaluate(context, js) != null) Log.i(TAG, "live shortcuts: updated $id")
}
fun launchOptions(context: Context, appId: Long): String? {
if (!clientRunning()) return null
val js = """
new Promise(done => {
let handle = null, answer;
const finish = d => { clearTimeout(timer); try { handle?.unregister(); } catch (e) {} done(d); };
const timer = setTimeout(() => finish(null), 4000);
handle = SteamClient.Apps.RegisterForAppDetails(${appId and 0xFFFFFFFFL}, d => { answer = d; if (handle) finish(d); });
if (answer !== undefined) finish(answer);
}).then(d => typeof d?.strLaunchOptions === 'string' ? d.strLaunchOptions : null)
""".trimIndent()
return evaluate(context, js)
}
fun setLaunchOptions(context: Context, appId: Long, options: String): Boolean {
if (!clientRunning()) return false
val id = appId and 0xFFFFFFFFL
val done = evaluate(context, "(async () => { SteamClient.Apps.SetAppLaunchOptions($id, ${JSONObject.quote(options)}); return 1; })()") != null
if (done) Log.i(TAG, "live: launch options for $id")
return done
}
fun setArt(context: Context, appId: Long, assetType: Int?, file: java.io.File?, iconPath: String? = null) {
if (!clientRunning()) return
val id = appId and 0xFFFFFFFFL
@@ -68,6 +68,7 @@ import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.frontend.LogoPosition
import com.droiddeck.launcher.frontend.SteamGameArt
import com.droiddeck.launcher.frontend.SteamGridDb
import com.droiddeck.launcher.frontend.SteamLaunchOptions
import com.droiddeck.launcher.session.SessionPrefs
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@@ -191,7 +192,7 @@ internal fun SteamGameArtEditor(
game: com.droiddeck.launcher.frontend.Library.SteamGame, onClose: () -> Unit, onChanged: () -> Unit,
) {
val target = remember(game.appId) { ArtTarget.of(game) }
ArtOnlyEditor(game.name, target, game, { SteamGameArt.describe(it, game) }, onClose, onChanged)
ArtOnlyEditor(game.name, target, game, { SteamGameArt.describe(it, game) }, onClose, onChanged, launchAppId = game.appId)
}
@Composable
@@ -207,18 +208,25 @@ internal fun StoreGameArtEditor(folder: String, name: String, onClose: () -> Uni
@Composable
private fun ArtOnlyEditor(
name: String, target: ArtTarget?, refresh: Any?, describe: (Context) -> List<AddedGameArt.SlotState>,
onClose: () -> Unit, onChanged: () -> Unit,
onClose: () -> Unit, onChanged: () -> Unit, launchAppId: Int? = null,
) {
val app = LocalContext.current.applicationContext
val colors = MaterialTheme.colorScheme
val scope = rememberCoroutineScope()
val shown = rememberShown(onClose)
val close = { shown.targetState = false }
var version by remember { mutableIntStateOf(0) }
var arts by remember { mutableStateOf<List<AddedGameArt.SlotState>>(emptyList()) }
var artSlot by remember { mutableStateOf<AddedGameArt.Slot?>(null) }
var logoOpen by remember { mutableStateOf(false) }
var launchOptions by remember { mutableStateOf<String?>(null) }
var launchVersion by remember { mutableIntStateOf(0) }
var editingLaunch by remember { mutableStateOf<String?>(null) }
var launchSaving by remember { mutableStateOf(false) }
var launchError by remember { mutableStateOf<Int?>(null) }
val position = rememberLogoPosition(target, version)
LaunchedEffect(version, refresh) { if (target != null) arts = withContext(Dispatchers.IO) { describe(app) } }
LaunchedEffect(launchAppId, launchVersion) { if (launchAppId != null) launchOptions = withContext(Dispatchers.IO) { SteamLaunchOptions.current(app, launchAppId) } }
val first = remember { FocusRequester() }
LaunchedEffect(Unit) { focusWithinFrames({ false }) { first } }
AppDialog(shown, close, "artEditor", wide = false, maxWidth = 460.dp) {
@@ -228,10 +236,19 @@ private fun ArtOnlyEditor(
verticalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.fillMaxWidth().heightIn(max = maxHeight).verticalScroll(rememberScrollState()),
) {
Text(stringResource(R.string.edit_artwork), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 4.dp, top = 2.dp))
if (launchAppId != null) {
FieldRow(stringResource(R.string.edit_launch_options), focus = first, onClick = { if (!launchSaving) launchOptions?.let { editingLaunch = it } }) {
val options = launchOptions
if (options == null || launchSaving) Loading() else ValueText(options.ifEmpty { "—" }, muted = options.isEmpty())
}
val error = launchError
if (error != null) Text(stringResource(error), fontSize = 12.sp, color = colors.error, modifier = Modifier.padding(start = 4.dp))
else Text(stringResource(R.string.edit_launch_options_steam_hint), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 4.dp))
}
Text(stringResource(R.string.edit_artwork), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 4.dp, top = if (launchAppId != null) 8.dp else 2.dp))
for (slot in AddedGameArt.Slot.values()) key(slot) {
val state = arts.firstOrNull { it.slot == slot }
FieldRow(slot.label(), focus = if (slot == AddedGameArt.Slot.COVER) first else null, onClick = { if (target != null) artSlot = slot }) {
FieldRow(slot.label(), focus = if (slot == AddedGameArt.Slot.COVER && launchAppId == null) first else null, onClick = { if (target != null) artSlot = slot }) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
SlotThumb(slot, state?.file)
if (state != null) ValueText(artSourceLabel(state.source), muted = true) else Loading()
@@ -241,6 +258,27 @@ private fun ArtOnlyEditor(
PickerRow(Icons.Outlined.Tune, stringResource(R.string.art_adjust_logo), logoPositionSummary(position?.value), enabled = target != null && position != null) { logoOpen = true }
}
}
val before = editingLaunch
if (before != null && launchAppId != null) TextEntryDialog(stringResource(R.string.edit_launch_options), before, onDismiss = { editingLaunch = null }) { value ->
if (launchSaving || value == before.trim()) return@TextEntryDialog
launchSaving = true
scope.launch {
try {
val saved = withContext(Dispatchers.IO) { SteamLaunchOptions.set(app, launchAppId, value, before) }
launchError = when (saved) {
SteamLaunchOptions.Saved.YES -> null
SteamLaunchOptions.Saved.DESKTOP -> R.string.edit_launch_options_desktop
SteamLaunchOptions.Saved.NO -> R.string.edit_launch_options_not_saved
}
if (saved == SteamLaunchOptions.Saved.YES) launchOptions = value else {
launchOptions = null
launchVersion++
}
} finally {
launchSaving = false
}
}
}
val chosen = target ?: return
artSlot?.let { slot ->
ArtChooserDialog(chosen, slot, arts.firstOrNull { it.slot == slot }, onBack = { artSlot = null }, onCloseAll = { artSlot = null; close() }) { version++; onChanged() }