added games: artwork - the game folder's own images first, else Steam's store art for the title, into the client's grid

frontend/AddedGameArt: cover/poster/boxart/folder-name images, header, hero, logo and icon from
the game's folder (or its art subfolder); otherwise a one-time store search by folder name and
the capsule, header, hero and logo from Steam's CDN into the app's cache (a miss retried after a
week); an icon pulled from the .exe. The rail shows the portrait. The session's listing carries
the paths; bannerlator-steam-shortcuts copies them into userdata/<acct>/config/grid under the
client's names, never over a file it did not write itself, and sets the shortcut's icon. A toggle
in the cog turns the store lookup off.
This commit is contained in:
The412Banner committed 2026-09-23 09:12:26 -04:00
1 parent b834101cad
commit 44ea7bae78
6 files changed
+279 -3

No files matched your search

@@ -118,6 +118,7 @@ class MainActivity : ComponentActivity() {
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path ->
SessionPrefs.setAddedGamesDirs(this, addedGamesDirs + path)
addedGamesDirs = SessionPrefs.addedGamesDirs(this)
addedGamesArt = SessionPrefs.addedGamesArt(this)
refreshAddedGames()
refresh()
}
@@ -133,6 +134,8 @@ class MainActivity : ComponentActivity() {
}
}
private var addedGamesDirs by mutableStateOf<List<String>>(emptyList())
private var addedGamesArt by mutableStateOf(true)
@Volatile private var artFetchRunning = false
private var addedGames by mutableStateOf<List<com.steamdeck.launcher.ui.AddedGameRow>>(emptyList())
private val pickRomsDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path ->
@@ -394,6 +397,7 @@ class MainActivity : ComponentActivity() {
steamChannel = if (mode == SessionService.MODE_STEAM) steamChannel else null,
addedGamesDirs = if (mode == SessionService.MODE_STEAM) addedGamesDirs else null,
addedGames = if (mode == SessionService.MODE_STEAM) addedGames else emptyList(),
addedGamesArt = addedGamesArt,
),
ModeSettingsActions(
onResolution = { cap -> SessionPrefs.setResolutionCap(this, mode, cap); resolutionCap = cap },
@@ -425,6 +429,7 @@ class MainActivity : ComponentActivity() {
onFexPreset = { id -> SessionPrefs.setFexPreset(this, id); fexPreset = id },
onSteamChannel = { id -> SessionPrefs.setSteamChannel(this, id); steamChannel = id },
onPickAddedGamesDir = { pickAddedGamesDir.launch(InAppFilePicker.buildDirIntent(this, "Choose a folder of your own games", addedGamesDirs.lastOrNull())) },
onAddedGamesArt = { on -> SessionPrefs.setAddedGamesArt(this, on); addedGamesArt = on; if (on) refreshAddedGames() },
onForgetAddedGamesDir = { dir -> SessionPrefs.setAddedGamesDirs(this, addedGamesDirs - dir); addedGamesDirs = SessionPrefs.addedGamesDirs(this); refreshAddedGames(); refresh() },
onAddedGameExe = { folder, path -> SessionPrefs.setAddedGameExe(this, folder, path); refreshAddedGames(); refresh() },
onPickAddedGameExe = { folder ->
@@ -469,6 +474,19 @@ class MainActivity : ComponentActivity() {
addedGames = com.steamdeck.launcher.frontend.AddedGames.scan(this).map { g ->
com.steamdeck.launcher.ui.AddedGameRow(g.folder.path, g.folderName(), g.exe.path, g.exe.name, g.candidates.map { c -> c.path to c.name }.distinctBy { it.first })
}
// Art the games do not have yet, from Steam's store, off the main thread; the rail
// redraws when something arrives.
if (SessionPrefs.addedGamesArt(this) && !artFetchRunning) {
artFetchRunning = true
Thread({
try {
val games = com.steamdeck.launcher.frontend.AddedGames.scan(this)
if (com.steamdeck.launcher.frontend.AddedGameArt.fetchMissing(this, games)) ui.post { refresh() }
} finally {
artFetchRunning = false
}
}, "added-art").start()
}
}
private fun openModeSettings(mode: String) {
@@ -614,7 +632,7 @@ class MainActivity : ComponentActivity() {
// The libraries, off the main thread: manifests and a folder scan.
Thread({
val games = if (ready) Library.steamGames(this) + com.steamdeck.launcher.frontend.AddedGames.scan(this).map { g ->
Library.SteamGame(g.appId.toInt(), g.name, null, "added", g.gameId)
com.steamdeck.launcher.frontend.AddedGameArt.resolve(this, g).let { art -> Library.SteamGame(g.appId.toInt(), g.name, art.portrait ?: art.header, "added", g.gameId) }
} else emptyList()
val emus = Library.emulators(this) { id -> DesktopCatalog.installed(this, id) != null }
ui.post { steamGames = games; emulatorList = emus }
@@ -0,0 +1,173 @@
package com.steamdeck.launcher.frontend
import android.content.Context
import android.graphics.Bitmap
import android.util.Log
import com.steamdeck.launcher.files.PeIconExtractor
import com.steamdeck.launcher.session.SessionPrefs
import org.json.JSONObject
import java.io.File
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
/**
* Artwork for an added game: what the user put in the game's folder first, else what Steam's
* store has for the same title, fetched once into the app's cache. Four pieces, named the way
* the client names them in its grid folder: the portrait capsule, the wide header, the hero
* background and the logo; plus an icon pulled out of the game's own .exe. The session hands
* the paths to the runtime's shortcuts writer, which copies them into the client's grid.
*/
object AddedGameArt {
private const val TAG = "AddedGameArt"
private const val STORE_SEARCH = "https://store.steampowered.com/api/storesearch/?l=english&cc=US&term="
private const val CDN = "https://cdn.cloudflare.steamstatic.com/steam/apps/"
private const val RETRY_AFTER_MS = 7L * 24 * 3600 * 1000
class Art(val portrait: File?, val header: File?, val hero: File?, val logo: File?, val icon: File?) {
val any get() = portrait != null || header != null || hero != null || logo != null
}
private val IMAGE = listOf("png", "jpg", "jpeg")
private val PORTRAIT = listOf("cover", "poster", "grid", "boxart", "capsule", "folder", "library_600x900", "portrait")
private val HEADER = listOf("header", "banner", "library_header", "wide")
private val HERO = listOf("hero", "background", "library_hero")
private val LOGO = listOf("logo")
private fun cacheDir(context: Context, game: AddedGames.Game) = File(context.filesDir, "added-art/${game.appId}")
/** An image in the folder (or its `art` subfolder) under one of the given names, any image extension. */
private fun find(folder: File, names: List<String>): File? {
val dirs = listOf(folder, File(folder, "art"), File(folder, ".art"))
for (dir in dirs) for (name in names) for (ext in IMAGE) {
val f = File(dir, "$name.$ext")
if (f.isFile) return f
}
return null
}
/** What the folder itself offers; the file named after the folder counts as the portrait. */
private fun local(game: AddedGames.Game): Art {
val folder = game.folder
return Art(
portrait = find(folder, PORTRAIT + listOf(folder.name)),
header = find(folder, HEADER),
hero = find(folder, HERO),
logo = find(folder, LOGO),
icon = listOf("icon.png", "icon.ico").map { File(folder, it) }.firstOrNull { it.isFile },
)
}
/** The folder's art, else the cached Steam art, without touching the network. */
fun resolve(context: Context, game: AddedGames.Game): Art {
val own = local(game)
val cache = cacheDir(context, game)
fun cached(name: String) = File(cache, name).takeIf { it.isFile }
return Art(
portrait = own.portrait ?: cached("p.jpg"),
header = own.header ?: cached("header.jpg"),
hero = own.hero ?: cached("hero.jpg"),
logo = own.logo ?: cached("logo.png"),
icon = own.icon ?: exeIcon(context, game),
)
}
/** The first icon inside the game's .exe, kept as a PNG beside the cached art. */
private fun exeIcon(context: Context, game: AddedGames.Game): File? {
val cache = cacheDir(context, game)
val png = File(cache, "icon.png")
if (png.isFile) return png
val none = File(cache, "icon.none")
if (none.isFile) return null
cache.mkdirs()
val bitmap = runCatching { PeIconExtractor.extract(game.exe) }.getOrNull()
if (bitmap == null) { none.writeText(""); return null }
val tmp = File(cache, "icon.png.tmp")
tmp.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
return if (tmp.renameTo(png)) png else null
}
/**
* Looks the games up on Steam's store and fetches the art that is missing, once per game
* (a miss is retried after a week). Blocking: run it off the main thread. Returns true when
* anything new arrived.
*/
fun fetchMissing(context: Context, games: List<AddedGames.Game>): Boolean {
if (!SessionPrefs.addedGamesArt(context)) return false
var changed = false
for (game in games) {
if (local(game).portrait != null) continue
val cache = cacheDir(context, game)
val lookup = File(cache, "steam-appid")
if (File(cache, "p.jpg").isFile) continue
if (lookup.isFile && (lookup.readText().trim() != "none" || System.currentTimeMillis() - lookup.lastModified() < RETRY_AFTER_MS)) {
val id = lookup.readText().trim()
if (id == "none") continue
if (download(id, cache)) changed = true
continue
}
cache.mkdirs()
val id = runCatching { search(game.name) }.onFailure { Log.w(TAG, "${game.name}: store search failed (${it.message})") }.getOrNull()
if (id == null) { lookup.writeText("none"); continue }
lookup.writeText(id)
Log.i(TAG, "${game.name}: Steam app $id")
if (download(id, cache)) changed = true
}
return changed
}
private fun normalize(s: String) = s.lowercase().replace(Regex("[^a-z0-9]"), "")
/** The Steam appid whose store name matches the folder name best, or null for no match. */
private fun search(name: String): String? {
val term = name.replace(Regex("(?i)\\b(complete|definitive|legendary|goty|game of the year|deluxe|ultimate|remastered)( edition)?\\b"), " ").trim().ifEmpty { name }
val json = get(STORE_SEARCH + URLEncoder.encode(term, "UTF-8"))?.toString(Charsets.UTF_8) ?: return null
val items = JSONObject(json).optJSONArray("items") ?: return null
val want = normalize(name)
val wantShort = normalize(term)
var best: String? = null
var bestScore = 0
for (i in 0 until items.length()) {
val item = items.getJSONObject(i)
val got = normalize(item.optString("name"))
val score = when {
got == want -> 4
got == wantShort -> 3
got.startsWith(wantShort) || wantShort.startsWith(got) -> 2
i == 0 -> 1
else -> 0
}
if (score > bestScore) { bestScore = score; best = item.optString("id") }
}
return best?.takeIf { it.isNotEmpty() && bestScore >= 1 }
}
private fun download(id: String, cache: File): Boolean {
var got = false
for ((remote, localName) in listOf(
"library_600x900.jpg" to "p.jpg", "header.jpg" to "header.jpg", "library_hero.jpg" to "hero.jpg", "logo.png" to "logo.png",
)) {
val dst = File(cache, localName)
if (dst.isFile) continue
val bytes = get("$CDN$id/$remote") ?: continue
val tmp = File(cache, "$localName.tmp")
tmp.writeBytes(bytes)
if (tmp.renameTo(dst)) got = true
}
return got
}
private fun get(url: String): ByteArray? {
val c = URL(url).openConnection() as HttpURLConnection
c.connectTimeout = 10_000
c.readTimeout = 15_000
c.setRequestProperty("User-Agent", "SteamDeck-launcher")
return try {
if (c.responseCode != 200) null else c.inputStream.use { it.readBytes() }
} catch (e: Exception) {
Log.w(TAG, "$url: ${e.message}"); null
} finally {
c.disconnect()
}
}
}
@@ -126,11 +126,24 @@ object AddedGames {
games.forEachIndexed { i, g ->
if (i > 0) json.append(',')
json.append("{\"name\":").append(quote(g.name)).append(",\"exe\":").append(quote(g.guestExe))
.append(",\"dir\":").append(quote(g.guestDir)).append(",\"appid\":").append(g.appId).append('}')
.append(",\"dir\":").append(quote(g.guestDir)).append(",\"appid\":").append(g.appId)
// The art, as the session sees it: the app's cache is bound at its own path, a file in
// the game's folder at the folder's guest path.
val art = AddedGameArt.resolve(context, g)
val pieces = listOf("p" to art.portrait, "header" to art.header, "hero" to art.hero, "logo" to art.logo, "icon" to art.icon)
.mapNotNull { (k, f) -> f?.let { file -> artGuestPath(context, file)?.let { k to it } } }
if (pieces.isNotEmpty()) json.append(",\"art\":{").append(pieces.joinToString(",") { (k, v) -> quote(k) + ":" + quote(v) }).append('}')
json.append('}')
}
file.writeText(json.append(']').toString())
return file
}
private fun artGuestPath(context: Context, file: File): String? {
val files = context.filesDir.absolutePath
if (file.absolutePath.startsWith("$files/")) return file.absolutePath
return guestPath(context, file)
}
private fun quote(s: String) = "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"") + "\""
}
@@ -249,6 +249,13 @@ object SessionPrefs {
prefs(context).edit().putString("addedGamesDirs", dirs.distinct().joinToString("\n")).remove("addedGamesDir").apply()
}
/** Whether added games without art of their own get Steam's store art fetched for them. */
fun addedGamesArt(context: Context): Boolean = prefs(context).getBoolean("addedGamesArt", true)
fun setAddedGamesArt(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("addedGamesArt", on).apply()
}
/** The .exe the user chose for one game folder (by its path), "" = the scanner's pick. */
fun addedGameExe(context: Context, folderPath: String): String = prefs(context).getString("addedExe:$folderPath", "") ?: ""
@@ -41,6 +41,7 @@ class ModeSettings(
/** The chosen Games folders (null = not a Steam page). */
val addedGamesDirs: List<String>? = null,
val addedGames: List<AddedGameRow> = emptyList(),
val addedGamesArt: Boolean = true,
)
/** One added game as the settings page shows it: its folder, the chosen .exe, the other .exe files it could be. */
@@ -67,6 +68,7 @@ class ModeSettingsActions(
val onSteamChannel: (String) -> Unit = {},
val onPickAddedGamesDir: () -> Unit = {},
val onForgetAddedGamesDir: (path: String) -> Unit = {},
val onAddedGamesArt: (Boolean) -> Unit = {},
val onAddedGameExe: (folderPath: String, path: String) -> Unit = { _, _ -> },
val onPickAddedGameExe: (folderPath: String) -> Unit = {},
val onDismiss: () -> Unit,
@@ -159,6 +161,11 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
"Your own Windows games, one subfolder each, anywhere: internal storage, the SD card, a USB drive. As many folders as you like. Each game goes into the client's library as a non-Steam game under the ARM64 Proton, at the next session start.",
"Add…", onClick = a.onPickAddedGamesDir,
)
ToggleRow(
host, "addedArt", "Artwork from Steam",
"A game with no art of its own gets the store's capsule, header, hero and logo for the same title, looked up by folder name. Your own art wins: drop cover.jpg (or poster, boxart, folder, the folder's name), header.jpg, hero.jpg, logo.png or icon.png into the game's folder or its art subfolder.",
s.addedGamesArt, onChange = a.onAddedGamesArt,
)
for (g in s.addedGames) ChoiceRow(
host, "added:" + g.folderPath, g.folderName, "Launches ${g.exeName}" + (if (s.addedGamesDirs.size > 1) " · in " + g.folderPath.substringBeforeLast('/').substringAfterLast('/') else ""),
g.candidates + ("__pick__" to "Choose another file…"), g.exePath,