From 77c3fd323ee5afca14c0da6b58a2639a4d55bc52 Mon Sep 17 00:00:00 2001 From: FX1922 <120828496+FX192@users.noreply.github.com> Date: Sat, 17 Oct 2026 17:02:22 +0300 Subject: [PATCH] =?UTF-8?q?feat:=20Adjust=20a=20game=E2=80=99s=20logo=20po?= =?UTF-8?q?sition=20and=20size=20in=20the=20artwork=20editors=20(#1004)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add an Adjust logo screen to move and resize a game's logo in Steam * Report a failed write of the local logo position instead of throwing * Record a Steam-side logo position change only once it has been taken over here --- .../launcher/frontend/AddedGameEdits.kt | 10 + .../launcher/frontend/LogoPosition.kt | 48 +++++ .../launcher/frontend/SteamGameArt.kt | 8 + .../droiddeck/launcher/frontend/SteamGrid.kt | 86 ++++++++ .../launcher/stores/SteamLiveShortcuts.kt | 10 + .../droiddeck/launcher/ui/AddedGameEditor.kt | 46 +++++ .../launcher/ui/LogoPositionDialog.kt | 188 ++++++++++++++++++ app/src/main/res/values/strings.xml | 14 ++ .../launcher/frontend/LogoPositionTest.kt | 51 +++++ .../launcher/frontend/SteamGridTest.kt | 57 ++++++ docs/development/added-games.md | 11 + 11 files changed, 529 insertions(+) create mode 100644 app/src/main/java/com/droiddeck/launcher/frontend/LogoPosition.kt create mode 100644 app/src/main/java/com/droiddeck/launcher/ui/LogoPositionDialog.kt create mode 100644 app/src/test/java/com/droiddeck/launcher/frontend/LogoPositionTest.kt diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameEdits.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameEdits.kt index ae7add6e80..42b0877880 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameEdits.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGameEdits.kt @@ -51,6 +51,16 @@ object AddedGameEdits { } } + fun logoPosition(context: Context, folder: String): LogoPosition.Value? = + game(context, folder)?.let { SteamGrid.position(SteamGrid.target(it, context)) } + + fun setLogoPosition(context: Context, folder: String, value: LogoPosition.Value?): Boolean { + val game = game(context, folder) ?: return false + if (!SteamGrid.writePosition(context, SteamGrid.target(game, context), value)) return false + publish(context) { SteamLiveShortcuts.setLogoPosition(context, game.appId, value) } + return true + } + private fun applyArt(context: Context, game: AddedGames.Game, slot: AddedGameArt.Slot) { val file = AddedGameArt.describe(context, game).first { it.slot == slot }.file if (slot != AddedGameArt.Slot.ICON) SteamGrid.write(context, SteamGrid.target(game, context), slot, AddedGameArt.chosen(AddedGameArt.cacheDir(context, game), slot)) diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/LogoPosition.kt b/app/src/main/java/com/droiddeck/launcher/frontend/LogoPosition.kt new file mode 100644 index 0000000000..a047da09e4 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/frontend/LogoPosition.kt @@ -0,0 +1,48 @@ +package com.droiddeck.launcher.frontend + +import org.json.JSONObject + +/** Where Steam pins a game's logo on its hero image and how big it draws it; the same JSON Steam keeps in `.json`. */ +object LogoPosition { + enum class Pin(val steam: String) { + UPPER_LEFT("UpperLeft"), UPPER_CENTER("UpperCenter"), CENTER("CenterCenter"), BOTTOM_LEFT("BottomLeft"), BOTTOM_CENTER("BottomCenter"); + + companion object { + fun of(steam: String): Pin? = values().firstOrNull { it.steam == steam } + } + } + + data class Value(val pin: Pin, val widthPct: Int, val heightPct: Int) + + const val MIN_PCT = 10 + const val MAX_PCT = 100 + + /** What Steam draws when a game has no custom position. */ + val DEFAULT = Value(Pin.BOTTOM_LEFT, 50, 50) + + private const val VERSION = 1 + private const val KEY = "logoPosition" + + fun sized(pin: Pin, size: Int): Value = size.coerceIn(MIN_PCT, MAX_PCT).let { Value(pin, it, it) } + + /** `{"nVersion":1,"logoPosition":{...}}`, with whatever else [into] already held kept as it was. */ + fun toJson(value: Value, into: JSONObject = JSONObject()): JSONObject = into + .put("nVersion", VERSION) + .put(KEY, JSONObject().put("pinnedPosition", value.pin.steam).put("nWidthPct", value.widthPct).put("nHeightPct", value.heightPct)) + + fun parse(text: String): Value? = runCatching { parse(JSONObject(text)) }.getOrNull() + + fun parse(json: JSONObject): Value? { + val inner = json.optJSONObject(KEY) ?: return null + val pin = Pin.of(inner.optString("pinnedPosition")) ?: return null + if (!inner.has("nWidthPct") || !inner.has("nHeightPct")) return null + return Value(pin, inner.optInt("nWidthPct").coerceIn(MIN_PCT, MAX_PCT), inner.optInt("nHeightPct").coerceIn(MIN_PCT, MAX_PCT)) + } + + /** [existing] without the logo position; null when nothing but the version number would be left. */ + fun without(existing: JSONObject): JSONObject? { + existing.remove(KEY) + val rest = existing.keys().asSequence().filter { it != "nVersion" }.toList() + return if (rest.isEmpty()) null else existing + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/SteamGameArt.kt b/app/src/main/java/com/droiddeck/launcher/frontend/SteamGameArt.kt index 026435799f..4b0d951f72 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/SteamGameArt.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/SteamGameArt.kt @@ -82,6 +82,14 @@ object SteamGameArt { } } + fun position(context: Context, game: Library.SteamGame): LogoPosition.Value? = SteamGrid.position(SteamGrid.target(game, context)) + + fun setPosition(context: Context, game: Library.SteamGame, value: LogoPosition.Value?): Boolean { + if (!SteamGrid.writePosition(context, SteamGrid.target(game, context), value)) return false + AddedGamesPublisher.later(context) { SteamLiveShortcuts.setLogoPosition(context, game.appId.toLong(), value) } + return true + } + private fun push(context: Context, game: Library.SteamGame, slot: AddedGameArt.Slot, file: File?): Boolean { val type = slot.assetType ?: return true if (!SteamGrid.write(context, SteamGrid.target(game, context), slot, file)) return false diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/SteamGrid.kt b/app/src/main/java/com/droiddeck/launcher/frontend/SteamGrid.kt index f3d44659aa..615595debf 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/SteamGrid.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/SteamGrid.kt @@ -77,6 +77,85 @@ object SteamGrid { return true } + private const val POSITION = "logo-position" + private const val POSITION_SIG = "grid-json" + + private fun positionFile(grid: File, id: Long) = File(grid, "$id.json") + + private fun positionIn(file: File): LogoPosition.Value? = file.takeIf { it.isFile }?.let { runCatching { it.readText() }.getOrNull() }?.let(LogoPosition::parse) + + /** The logo position chosen here (or taken over from Steam) for a game; null when Steam's own default applies. */ + fun position(target: Target): LogoPosition.Value? = positionIn(File(target.artDir, POSITION)) + + private fun positionRecorded(target: Target): String? = File(target.artDir, POSITION_SIG).takeIf { it.isFile }?.readText() + + private fun recordPosition(target: Target, value: String) { + target.artDir.mkdirs() + File(target.artDir, POSITION_SIG).writeText(value) + } + + private fun storePosition(target: Target, value: LogoPosition.Value?): Boolean { + val file = File(target.artDir, POSITION) + if (value == null) return !file.exists() || file.delete() + target.artDir.mkdirs() + return runCatching { file.writeText(LogoPosition.toJson(value).toString()) }.isSuccess + } + + /** Sets (or with null, clears) a game's logo position here and in the client's grid folder, whether or not Steam is running. */ + fun writePosition(context: Context, target: Target, value: LogoPosition.Value?): Boolean = synchronized(lock) { + placePosition(context, target, value) && storePosition(target, value) + } + + /** Steam keeps the position in `.json`; anything else that file holds is left as it was. */ + private fun placePosition(context: Context, target: Target, value: LogoPosition.Value?): Boolean { + val grid = dir(context) ?: return true + val file = positionFile(grid, target.id) + val existing = if (file.isFile) runCatching { JSONObject(file.readText()) }.getOrNull() else null + if (file.isFile && existing == null) return value == null + val next = if (value == null) existing?.let(LogoPosition::without) else LogoPosition.toJson(value, existing ?: JSONObject()) + if (next == null) { + if (file.isFile && !file.delete()) return false + recordPosition(target, "") + return true + } + grid.mkdirs() + val tmp = File(grid, file.name + ".tmp") + val placed = runCatching { tmp.writeText(next.toString()); tmp.renameTo(file) }.getOrDefault(false) + if (!placed) { + tmp.delete() + return false + } + recordPosition(target, signature(file)) + return true + } + + /** A `logoPosition` this version cannot read (a pin it does not know, say) is left alone rather than read as "removed". */ + private fun hasUnknownPosition(file: File): Boolean { + val json = runCatching { JSONObject(file.readText()) }.getOrNull() ?: return false + return json.has("logoPosition") && LogoPosition.parse(json) == null + } + + private fun reconcilePosition(context: Context, grid: File, target: Target) { + val file = positionFile(grid, target.id) + if (hasUnknownPosition(file)) return + val theirs = positionIn(file) + val now = if (theirs != null) signature(file) else "" + val before = positionRecorded(target) + val own = position(target) + when { + before == null && own != null && theirs == null -> placePosition(context, target, own) + before == null || now != before -> { + // Recorded only once the local side agrees, so a failed take-over is tried again on the next scan. + if (theirs != null) { + if (own == theirs || storePosition(target, theirs)) recordPosition(target, now) + } else { + if (own == null || storePosition(target, null)) recordPosition(target, "") + } + } + own != null && own != theirs -> placePosition(context, target, own) + } + } + /** Takes over what changed in Steam since the last look; returns true when a choice was added, replaced or dropped. */ fun sync(context: Context, targets: List): Boolean = synchronized(lock) { reconcile(context, targets) } @@ -113,6 +192,13 @@ object SteamGrid { Log.w(TAG, "${target.id} ${slot.key}: ${e.javaClass.simpleName}") } } + for (target in targets) { + try { + reconcilePosition(context, grid, target) + } catch (e: Exception) { + Log.w(TAG, "${target.id} logo position: ${e.javaClass.simpleName}") + } + } if (changed) Log.i(TAG, "took over art changed in Steam") return changed } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/SteamLiveShortcuts.kt b/app/src/main/java/com/droiddeck/launcher/stores/SteamLiveShortcuts.kt index 4f0bcfce3c..03504baace 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/SteamLiveShortcuts.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/SteamLiveShortcuts.kt @@ -5,6 +5,7 @@ import android.util.Base64 import android.util.Log import com.droiddeck.launcher.frontend.AddedGames import com.droiddeck.launcher.frontend.Library +import com.droiddeck.launcher.frontend.LogoPosition import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.session.SessionService import com.droiddeck.launcher.session.SessionState @@ -90,6 +91,15 @@ object SteamLiveShortcuts { if (evaluate(context, js) != null) Log.i(TAG, "live shortcuts: art $assetType for $id") } + /** Moves and resizes a game's logo in the running client; with null the client's default position comes back. */ + fun setLogoPosition(context: Context, appId: Long, position: LogoPosition.Value?) { + if (!clientRunning()) return + val id = appId and 0xFFFFFFFFL + val js = if (position == null) "(async () => { try { await SteamClient.Apps.ClearCustomLogoPositionForApp($id); } catch (e) {} return 1; })()" + else "(async () => { try { await SteamClient.Apps.SetCustomLogoPositionForApp($id, ${JSONObject.quote(LogoPosition.toJson(position).toString())}); } catch (e) {} return 1; })()" + if (evaluate(context, js) != null) Log.i(TAG, "live shortcuts: logo position for $id") + } + private fun clientRunning(): Boolean = SessionState.running && SessionState.mode == SessionService.MODE_STEAM && !SessionState.stopRequested private fun evaluate(context: Context, expression: String): String? { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddedGameEditor.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddedGameEditor.kt index 1e44f24a51..cec6c7a426 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddedGameEditor.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddedGameEditor.kt @@ -23,6 +23,7 @@ import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.outlined.Image import androidx.compose.material.icons.outlined.Search +import androidx.compose.material.icons.outlined.Tune import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable @@ -58,6 +59,7 @@ import com.droiddeck.launcher.R import com.droiddeck.launcher.frontend.AddedGameArt import com.droiddeck.launcher.frontend.AddedGameEdits 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.session.SessionPrefs @@ -152,6 +154,8 @@ internal class ArtTarget( val choices: (Context, AddedGameArt.Slot) -> AddedGameArt.Choices, val set: (Context, AddedGameArt.Slot, AddedGameArt.Option) -> Boolean, val reset: (Context, AddedGameArt.Slot) -> Unit, + val position: (Context) -> LogoPosition.Value?, + val setPosition: (Context, LogoPosition.Value?) -> Boolean, ) { companion object { fun of(game: AddedGames.Game) = ArtTarget( @@ -160,6 +164,8 @@ internal class ArtTarget( { c, slot -> AddedGameArt.choices(c, game, slot) }, { c, slot, option -> AddedGameEdits.setArt(c, game.folder.path, slot, option) }, { c, slot -> AddedGameEdits.resetArt(c, game.folder.path, slot) }, + { c -> AddedGameEdits.logoPosition(c, game.folder.path) }, + { c, value -> AddedGameEdits.setLogoPosition(c, game.folder.path, value) }, ) fun of(game: com.droiddeck.launcher.frontend.Library.SteamGame) = ArtTarget( @@ -168,6 +174,8 @@ internal class ArtTarget( { c, slot -> SteamGameArt.choices(c, game, slot) }, { c, slot, option -> SteamGameArt.choose(c, game, slot, option) }, { c, slot -> SteamGameArt.reset(c, game, slot) }, + { c -> SteamGameArt.position(c, game) }, + { c, value -> SteamGameArt.setPosition(c, game, value) }, ) } } @@ -202,6 +210,8 @@ private fun ArtOnlyEditor( var version by remember { mutableIntStateOf(0) } var arts by remember { mutableStateOf>(emptyList()) } var artSlot by remember { mutableStateOf(null) } + var logoOpen by remember { mutableStateOf(false) } + val position = rememberLogoPosition(target, version) LaunchedEffect(version, refresh) { if (target != null) arts = withContext(Dispatchers.IO) { describe(app) } } val first = remember { FocusRequester() } LaunchedEffect(Unit) { focusWithinFrames({ false }) { first } } @@ -222,12 +232,41 @@ private fun ArtOnlyEditor( } } } + PickerRow(Icons.Outlined.Tune, stringResource(R.string.art_adjust_logo), logoPositionSummary(position?.value), enabled = target != null && position != null) { logoOpen = true } } } val chosen = target ?: return artSlot?.let { slot -> ArtChooserDialog(chosen, slot, arts.firstOrNull { it.slot == slot }, onBack = { artSlot = null }, onCloseAll = { artSlot = null; close() }) { version++; onChanged() } } + val loaded = position + if (logoOpen && loaded != null) LogoPositionHost(chosen, arts, loaded, onBack = { logoOpen = false }, onCloseAll = { logoOpen = false; close() }) { version++; onChanged() } +} + +/** The position as last read; null until it has been read, so the screen never opens on a guess and saves it over the real one. */ +private class LoadedPosition(val value: LogoPosition.Value?) + +@Composable +private fun rememberLogoPosition(target: ArtTarget?, version: Int): LoadedPosition? { + val app = LocalContext.current.applicationContext + var position by remember(target) { mutableStateOf(null) } + LaunchedEffect(target, version) { + position = if (target == null) null else withContext(Dispatchers.IO) { LoadedPosition(runCatching { target.position(app) }.getOrNull()) } + } + return position +} + +/** The "Adjust logo" screen for [target], over the game's background and logo as they are now. */ +@Composable +private fun LogoPositionHost( + target: ArtTarget, arts: List, start: LoadedPosition, + onBack: () -> Unit, onCloseAll: () -> Unit, onChanged: () -> Unit, +) { + fun file(slot: AddedGameArt.Slot) = arts.firstOrNull { it.slot == slot }?.file + LogoPositionDialog( + target, hero = file(AddedGameArt.Slot.BACKGROUND) ?: file(AddedGameArt.Slot.WIDE), logo = file(AddedGameArt.Slot.LOGO), start = start.value, + onBack = onBack, onCloseAll = onCloseAll, onChanged = onChanged, + ) } @Composable @@ -256,6 +295,9 @@ internal fun AddedGameEditor( var editing by remember { mutableStateOf(null) } var otherExe by remember { mutableStateOf(false) } var artSlot by remember { mutableStateOf(null) } + var logoOpen by remember { mutableStateOf(false) } + val artTarget = remember(game?.appId) { game?.let { ArtTarget.of(it) } } + val position = rememberLogoPosition(artTarget, version) var unreachable by remember { mutableStateOf(false) } LaunchedEffect(version) { withContext(Dispatchers.IO) { @@ -329,6 +371,7 @@ internal fun AddedGameEditor( } } } + PickerRow(Icons.Outlined.Tune, stringResource(R.string.art_adjust_logo), logoPositionSummary(position?.value), enabled = g != null && position != null) { logoOpen = true } RemoveRow(armed) { if (!armed) armed = true else { armed = false @@ -373,6 +416,9 @@ internal fun AddedGameEditor( val current = arts.firstOrNull { it.slot == slot } ArtChooserDialog(ArtTarget.of(g), slot, current, onBack = { artSlot = null }, onCloseAll = { artSlot = null; close() }) { version++; onChanged() } } + val logoTarget = artTarget + val loaded = position + if (logoOpen && logoTarget != null && loaded != null) LogoPositionHost(logoTarget, arts, loaded, onBack = { logoOpen = false }, onCloseAll = { logoOpen = false; close() }) { version++; onChanged() } } private fun hostPath(context: android.content.Context, game: AddedGames.Game): String { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LogoPositionDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/LogoPositionDialog.kt new file mode 100644 index 0000000000..7e42aab512 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/LogoPositionDialog.kt @@ -0,0 +1,188 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import coil.compose.AsyncImage +import com.droiddeck.launcher.R +import com.droiddeck.launcher.frontend.LogoPosition +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File + +/** Steam's library hero is 3840 x 1240, so the preview keeps that shape. */ +private const val HERO_RATIO = 3840f / 1240f + +/** The gap Steam leaves between the pinned logo and the edge of the hero, as a share of the hero's width. */ +private const val EDGE = 0.03f + +@Composable +private fun LogoPosition.Pin.label(): String = stringResource( + when (this) { + LogoPosition.Pin.UPPER_LEFT -> R.string.logo_pos_upper_left + LogoPosition.Pin.UPPER_CENTER -> R.string.logo_pos_upper_center + LogoPosition.Pin.CENTER -> R.string.logo_pos_center + LogoPosition.Pin.BOTTOM_LEFT -> R.string.logo_pos_bottom_left + LogoPosition.Pin.BOTTOM_CENTER -> R.string.logo_pos_bottom_center + }, +) + +private fun LogoPosition.Pin.alignment(): Alignment = when (this) { + LogoPosition.Pin.UPPER_LEFT -> Alignment.TopStart + LogoPosition.Pin.UPPER_CENTER -> Alignment.TopCenter + LogoPosition.Pin.CENTER -> Alignment.Center + LogoPosition.Pin.BOTTOM_LEFT -> Alignment.BottomStart + LogoPosition.Pin.BOTTOM_CENTER -> Alignment.BottomCenter +} + +@Composable +internal fun logoPositionSummary(value: LogoPosition.Value?): String = + if (value == null) stringResource(R.string.logo_pos_default) else "${value.pin.label()} · ${value.widthPct}%" + +/** + * Where a game's logo sits on its background in Steam's library: the logo box is [Value.widthPct] x [Value.heightPct] of the + * background, pinned to one of five places, and the logo is drawn as large as fits in it. + */ +@Composable +private fun LogoPreview(hero: File?, logo: File?, value: LogoPosition.Value) { + val shape = RoundedCornerShape(10.dp) + BoxWithConstraints(Modifier.fillMaxWidth().aspectRatio(HERO_RATIO).clip(shape).background(Color(0xFF0E1218)).border(1.dp, LocalPalette.current.line, shape)) { + if (hero != null) AsyncImage(model = hero, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize()) + if (logo != null) { + val edge = maxWidth * EDGE + Box( + Modifier.align(value.pin.alignment()).padding(edge) + .size((maxWidth - edge * 2) * (value.widthPct / 100f), (maxHeight - edge * 2) * (value.heightPct / 100f)), + ) { + AsyncImage(model = logo, contentDescription = null, contentScale = ContentScale.Fit, alignment = value.pin.alignment(), modifier = Modifier.fillMaxSize()) + } + } + } +} + +@Composable +private fun PinChip(label: String, selected: Boolean, onClick: () -> Unit) { + val pal = LocalPalette.current + val colors = MaterialTheme.colorScheme + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + val shape = RoundedCornerShape(8.dp) + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.clip(shape) + .background(if (selected) pal.signal.copy(alpha = 0.14f) else Color.White.copy(alpha = 0.03f)) + .border(if (selected) 2.dp else 1.dp, if (selected) pal.signal else pal.line, shape) + .glideBorder(hot, shape, pal.signal) + .hoverable(src) + .clickable(interactionSource = src, indication = androidx.compose.foundation.LocalIndication.current, role = Role.RadioButton, onClick = onClick) + .controllerConfirm(onClick = onClick) + .semantics { contentDescription = label; this.selected = selected } + .padding(horizontal = 12.dp, vertical = 9.dp), + ) { + Text(label, fontSize = 13.sp, fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal, color = colors.onBackground, maxLines = 1) + } +} + +/** The "Adjust logo" screen: the game's background with its logo on it, where to pin the logo and how large to draw it. */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +internal fun LogoPositionDialog( + target: ArtTarget, hero: File?, logo: File?, start: LogoPosition.Value?, + onBack: () -> Unit, onCloseAll: () -> Unit, onChanged: () -> Unit, +) { + val app = LocalContext.current.applicationContext + val colors = MaterialTheme.colorScheme + val scope = rememberCoroutineScope() + val shown = rememberShown(onBack) + val back = { shown.targetState = false } + var value by remember { mutableStateOf(start ?: LogoPosition.DEFAULT) } + var failed by remember { mutableStateOf(false) } + var busy by remember { mutableStateOf(false) } + val save: (LogoPosition.Value?) -> Unit = { next -> + if (!busy) { + busy = true + scope.launch { + val saved = withContext(Dispatchers.IO) { runCatching { target.setPosition(app, next) }.getOrDefault(false) } + busy = false + failed = !saved + if (saved) { + onChanged() + back() + } + } + } + } + AppDialog(shown, back, "logoPosition", wide = false, maxWidth = 460.dp) { + DialogTitleRow(stringResource(R.string.art_adjust_logo), onClose = onCloseAll, leading = { + SmallIconButton(Icons.AutoMirrored.Filled.ArrowBack, stringResource(R.string.common_back), colors.onBackground, onClick = back) + }) + val maxHeight = (LocalConfiguration.current.screenHeightDp * 0.72f).dp + Column( + verticalArrangement = Arrangement.spacedBy(10.dp), + modifier = Modifier.fillMaxWidth().heightIn(max = maxHeight).verticalScroll(rememberScrollState()), + ) { + LogoPreview(hero, logo, value) + Text( + stringResource(if (logo == null) R.string.logo_pos_no_logo else R.string.logo_pos_hint), + fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 2.dp), + ) + Text(stringResource(R.string.logo_pos_position), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 2.dp, top = 2.dp)) + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + for (pin in LogoPosition.Pin.values()) PinChip(pin.label(), pin == value.pin) { value = value.copy(pin = pin) } + } + ValueSlider( + value.widthPct, LogoPosition.MIN_PCT..LogoPosition.MAX_PCT, step = 1, enabled = true, label = stringResource(R.string.logo_pos_size), + format = { "$it%" }, + ) { value = LogoPosition.sized(value.pin, it) } + if (failed) Text(stringResource(R.string.logo_pos_failed), fontSize = 12.sp, color = colors.error, modifier = Modifier.padding(horizontal = 2.dp)) + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) { + SecondaryButton(stringResource(R.string.logo_pos_reset), enabled = !busy, compact = true) { save(null) } + PrimaryButton(stringResource(R.string.logo_pos_save), enabled = !busy, compact = true) { save(value) } + } + } + } +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 443ee14ef0..bdddb1802e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2144,6 +2144,20 @@ Remove Cover Wide cover + Adjust logo + Default + Top left + Top center + Center + Bottom left + Bottom center + Position + Size + Save + Reset to default + Shown on the game\'s background, the way Steam draws it. The exact spot can differ by a few pixels. + This game has no logo yet. Choose one under Logo to see it here. + Couldn\'t save the logo position. Try again. Background Logo Icon diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/LogoPositionTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/LogoPositionTest.kt new file mode 100644 index 0000000000..2fecb6503a --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/frontend/LogoPositionTest.kt @@ -0,0 +1,51 @@ +package com.droiddeck.launcher.frontend + +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class LogoPositionTest { + @Test fun steamsOwnJsonIsReadAndWrittenBack() { + val steam = """{"nVersion":1,"logoPosition":{"pinnedPosition":"BottomLeft","nWidthPct":50,"nHeightPct":50}}""" + assertEquals(LogoPosition.DEFAULT, LogoPosition.parse(steam)) + assertEquals(LogoPosition.DEFAULT, LogoPosition.parse(LogoPosition.toJson(LogoPosition.DEFAULT).toString())) + } + + @Test fun everyPinKeepsItsSteamName() { + for (pin in LogoPosition.Pin.values()) { + val json = LogoPosition.toJson(LogoPosition.sized(pin, 40)) + assertEquals(pin.steam, json.getJSONObject("logoPosition").getString("pinnedPosition")) + assertEquals(pin, LogoPosition.parse(json)?.pin) + } + assertEquals(setOf("BottomLeft", "UpperLeft", "CenterCenter", "UpperCenter", "BottomCenter"), LogoPosition.Pin.values().map { it.steam }.toSet()) + } + + @Test fun sizesAreKeptInsideTheRange() { + assertEquals(LogoPosition.MAX_PCT, LogoPosition.sized(LogoPosition.Pin.CENTER, 400).widthPct) + assertEquals(LogoPosition.MIN_PCT, LogoPosition.sized(LogoPosition.Pin.CENTER, 0).heightPct) + val wild = """{"logoPosition":{"pinnedPosition":"CenterCenter","nWidthPct":900,"nHeightPct":-4}}""" + assertEquals(LogoPosition.Value(LogoPosition.Pin.CENTER, LogoPosition.MAX_PCT, LogoPosition.MIN_PCT), LogoPosition.parse(wild)) + } + + @Test fun somethingThatIsNotAPositionIsNotOne() { + assertNull(LogoPosition.parse("not json")) + assertNull(LogoPosition.parse("{}")) + assertNull(LogoPosition.parse("""{"logoPosition":{"pinnedPosition":"Nowhere","nWidthPct":5,"nHeightPct":5}}""")) + assertNull(LogoPosition.parse("""{"logoPosition":{"pinnedPosition":"CenterCenter"}}""")) + } + + @Test fun clearingKeepsForeignKeysAndEmptiesAJsonThatHeldNothingElse() { + val mixed = LogoPosition.toJson(LogoPosition.DEFAULT, JSONObject().put("other", 1)) + val kept = LogoPosition.without(mixed) + assertNotNull(kept) + assertEquals(1, kept!!.getInt("other")) + assertNull(LogoPosition.without(LogoPosition.toJson(LogoPosition.DEFAULT))) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/SteamGridTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/SteamGridTest.kt index ce71607ce4..d3539155f0 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/SteamGridTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/SteamGridTest.kt @@ -58,6 +58,63 @@ class SteamGridTest { assertNull(SteamGameArt.chosenFile(app, 620, AddedGameArt.Slot.WIDE)) } + private val corner = LogoPosition.Value(LogoPosition.Pin.UPPER_CENTER, 35, 35) + + @Test fun aLogoPositionIsWrittenToSteamsJsonKeepingWhatElseIsInIt() { + File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs() + grid.mkdirs() + File(grid, "620.json").writeText("""{"nVersion":1,"other":"kept"}""") + assertTrue(SteamGameArt.setPosition(app, game(), corner)) + val written = org.json.JSONObject(File(grid, "620.json").readText()) + assertEquals("kept", written.getString("other")) + assertEquals(corner, LogoPosition.parse(written)) + assertEquals(corner, SteamGameArt.position(app, game())) + + assertTrue(SteamGameArt.setPosition(app, game(), null)) + val left = org.json.JSONObject(File(grid, "620.json").readText()) + assertFalse(left.has("logoPosition")) + assertEquals("kept", left.getString("other")) + assertNull(SteamGameArt.position(app, game())) + } + + @Test fun aLogoPositionAloneLeavesNoFileBehindWhenCleared() { + File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs() + assertTrue(SteamGameArt.setPosition(app, game(), corner)) + assertEquals(corner, LogoPosition.parse(File(grid, "620.json").readText())) + assertTrue(SteamGameArt.setPosition(app, game(), null)) + assertFalse(File(grid, "620.json").exists()) + } + + @Test fun aLogoPositionSetInSteamIsTakenOverAndRemovingItDropsIt() { + File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs() + grid.mkdirs() + val theirs = File(grid, "620.json").apply { writeText(LogoPosition.toJson(corner).toString()) } + SteamGrid.sync(app, listOf(target())) + assertEquals(corner, SteamGameArt.position(app, game())) + + theirs.writeText(LogoPosition.toJson(LogoPosition.Value(LogoPosition.Pin.CENTER, 80, 80)).toString()) + theirs.setLastModified(theirs.lastModified() + 5000) + SteamGrid.sync(app, listOf(target())) + assertEquals(LogoPosition.Pin.CENTER, SteamGameArt.position(app, game())?.pin) + + theirs.delete() + SteamGrid.sync(app, listOf(target())) + assertNull(SteamGameArt.position(app, game())) + } + + @Test fun aLogoPositionChosenHereIsNotTakenBackAsASteamChange() { + File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs() + assertTrue(SteamGameArt.setPosition(app, game(), corner)) + SteamGrid.sync(app, listOf(target())) + assertEquals(corner, SteamGameArt.position(app, game())) + assertEquals(corner, LogoPosition.parse(File(grid, "620.json").readText())) + } + + @Test fun aLogoPositionWithoutSteamAccountIsStillKeptHere() { + assertTrue(SteamGameArt.setPosition(app, game(), corner)) + assertEquals(corner, SteamGameArt.position(app, game())) + } + @Test fun artSetInSteamIsTakenOverAndRemovingItInSteamDropsIt() { File(LinuxRuntime.rootDir(app), "root/.local/share/Steam/userdata/123/config").mkdirs() grid.mkdirs() diff --git a/docs/development/added-games.md b/docs/development/added-games.md index f577179578..9e1566dd43 100644 --- a/docs/development/added-games.md +++ b/docs/development/added-games.md @@ -97,6 +97,17 @@ a file removed in Steam drops it, and files the shortcuts writer placed itself (`.droiddeck-art.json`) are not mistaken for choices. A chosen image is stored as `chosen--