diff --git a/app/src/main/java/com/steamdeck/launcher/MainActivity.kt b/app/src/main/java/com/steamdeck/launcher/MainActivity.kt index 4684d76d31..908d3e74c0 100644 --- a/app/src/main/java/com/steamdeck/launcher/MainActivity.kt +++ b/app/src/main/java/com/steamdeck/launcher/MainActivity.kt @@ -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>(emptyList()) + private var addedGamesArt by mutableStateOf(true) + @Volatile private var artFetchRunning = false private var addedGames by mutableStateOf>(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 } diff --git a/app/src/main/java/com/steamdeck/launcher/frontend/AddedGameArt.kt b/app/src/main/java/com/steamdeck/launcher/frontend/AddedGameArt.kt new file mode 100644 index 0000000000..c888559d5c --- /dev/null +++ b/app/src/main/java/com/steamdeck/launcher/frontend/AddedGameArt.kt @@ -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): 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): 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() + } + } +} diff --git a/app/src/main/java/com/steamdeck/launcher/frontend/AddedGames.kt b/app/src/main/java/com/steamdeck/launcher/frontend/AddedGames.kt index e2859c3de3..6f3c2ffdd3 100644 --- a/app/src/main/java/com/steamdeck/launcher/frontend/AddedGames.kt +++ b/app/src/main/java/com/steamdeck/launcher/frontend/AddedGames.kt @@ -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("\"", "\\\"") + "\"" } diff --git a/app/src/main/java/com/steamdeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/steamdeck/launcher/session/SessionPrefs.kt index df0a3e0a55..5d410e8e95 100644 --- a/app/src/main/java/com/steamdeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/steamdeck/launcher/session/SessionPrefs.kt @@ -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", "") ?: "" diff --git a/app/src/main/java/com/steamdeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/steamdeck/launcher/ui/ModeSettingsDialog.kt index d7b092f0bf..cd983db663 100644 --- a/app/src/main/java/com/steamdeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/steamdeck/launcher/ui/ModeSettingsDialog.kt @@ -41,6 +41,7 @@ class ModeSettings( /** The chosen Games folders (null = not a Steam page). */ val addedGamesDirs: List? = null, val addedGames: List = 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, diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-shortcuts b/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-shortcuts index ece1030684..d63d306e6c 100755 --- a/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-shortcuts +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-steam-shortcuts @@ -16,6 +16,7 @@ import importlib.util import json import os import re +import shutil import struct import sys @@ -111,7 +112,7 @@ def shortcut(game): "AppName": game["name"], "Exe": '"%s"' % game["exe"], "StartDir": '"%s"' % game["dir"], - "icon": "", + "icon": (game.get("art") or {}).get("icon", "") or "", "ShortcutPath": "", "LaunchOptions": "", "IsHidden": 0, @@ -127,6 +128,62 @@ def shortcut(game): } +ART_MANIFEST = ".steamdeck-art.json" +# listing key -> the client's grid file suffix: p = portrait capsule, = header, +# _hero, _logo. +ART_SLOTS = (("p", "p"), ("header", ""), ("hero", "_hero"), ("logo", "_logo")) + + +def install_art(acct, games): + """Copies each game's art into the client's grid folder under the names it looks for. A file + the client already has that this script did not write (art the user set in the client) is + left alone; ours are replaced when the source changed and removed when the game lost its art.""" + grid = os.path.join(acct, "config", "grid") + os.makedirs(grid, exist_ok=True) + manifest_path = os.path.join(grid, ART_MANIFEST) + try: + with open(manifest_path, encoding="utf-8") as f: + manifest = json.load(f) + except (OSError, ValueError): + manifest = {} + wanted = {} + copied = 0 + for game in games: + art = game.get("art") or {} + appid = str(int(game["appid"]) & 0xFFFFFFFF) + for key, suffix in ART_SLOTS: + src = art.get(key) + if not src or not os.path.isfile(src): + continue + ext = os.path.splitext(src)[1].lower() or ".png" + if ext == ".jpeg": + ext = ".jpg" + name = appid + suffix + ext + dst = os.path.join(grid, name) + size = os.path.getsize(src) + wanted[name] = size + if os.path.exists(dst) and name not in manifest: + continue # the user's own choice inside the client + if os.path.exists(dst) and manifest.get(name) == size: + continue + try: + shutil.copyfile(src, dst + ".tmp") + os.replace(dst + ".tmp", dst) + copied += 1 + except OSError as e: + print("bannerlator-steam-shortcuts: could not copy art %s (%s)" % (name, e)) + for name in list(manifest): + if name not in wanted: + try: + os.remove(os.path.join(grid, name)) + except OSError: + pass + with open(manifest_path, "w", encoding="utf-8") as f: + json.dump(wanted, f) + if copied: + print("bannerlator-steam-shortcuts: %d piece(s) of art placed" % copied) + + def main(): if len(sys.argv) < 3: print(__doc__) @@ -160,6 +217,7 @@ def main(): f.write(write({"shortcuts": entries})) os.replace(tmp, path) print("bannerlator-steam-shortcuts: %d added game(s) written, %d of the client's own kept" % (len(ours), len(kept))) + install_art(acct, [g for g in games if g.get("exe") and g.get("name")]) # Each added game runs under the ARM64 Proton: the compat registrar's own mapping writer. try: # No .py suffix on the registrar, so the loader has to be named.