Games: revamped add games feature (#492)

Adding and managing your own (non-Steam) games moves out of the Steam
settings into the Games tab, and works like Steam's own non-Steam
Properties.

- A + beside "Games N" opens a compact in-app picker: the storage first,
  then that storage's root, every folder, .exe files only. Picking an exe
  adds the game with its name, art, Custom badge and Steam shortcut.
- "Add all games in this folder" adds every game folder inside at once.
  A summary opens immediately and fills in as each game is found, with a
  "?" where the exe was a close call and a red X to remove a game.
- An edit button on each Custom game opens its editor: Name, Target
  (ranked exes, Other exe…), Start in, Launch options, the four pieces of
  art with thumbnails, and Remove. Edits go through the same Steam
  shortcut, so the appid never changes and nothing duplicates.
- Art chooser per piece: images in the game folder, Steam's official art,
  SteamGridDB alternatives, your own image, or back to automatic.
- Finding the exe: up to five folders deep, every exe scored (name match,
  Unreal -Shipping builds, bin folders and size up; launchers, crash
  reporters, installers, redistributables and depth down).
- Real titles from the game's files (Steam manifest, GOG info, the exe's
  version info), keeping the folder's spacing when both spell the same
  title, underscores read as spaces.
- Art: the exact Steam appid when the game names one, strict name
  matches otherwise, Steam's hashed asset paths for newer games,
  SteamGridDB as a fallback (built-in key from the SGDB_API_KEY secret,
  optional own key in Setup, sealed with the Keystore), and a cover made
  from the exe's icon when nothing else has one.
- Removing a game is instant and keeps its files; adding it again brings
  it back. Steam's shortcut list is rewritten once, in the background.
- The Games section is gone from Steam settings; folders added before
  keep listing their games. Artwork switch and SteamGridDB key are in
  Setup.
This commit is contained in:
The412Banner authored and GitHub committed 2026-10-09 19:50:03 -04:00
1 parent d99ed8e00b
commit d250b43eb9
45 files changed
+4175 -295

No files matched your search

@@ -301,29 +301,34 @@ class MainActivity : ComponentActivity() {
GameSaves.savesDir().mkdirs()
pickSaveDir.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.main_saves_pick_folder, name, layout.label(this)), GameSaves.savesDir().path))
}
private val pickAddedGamesDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
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()
}
/** The Games tab's +: the picked .exe becomes a game (or selects / switches the one it belongs to). */
private fun addGameExe(path: String) {
val exe = java.io.File(path)
Thread({
val result = try { com.droiddeck.launcher.frontend.AddedGames.addExe(this, exe) } catch (e: Exception) {
Log.w(TAG, "add game: ${e.message}"); com.droiddeck.launcher.frontend.AddedGames.AddResult.NotFound
}
val game = when (result) {
is com.droiddeck.launcher.frontend.AddedGames.AddResult.Added -> result.game
is com.droiddeck.launcher.frontend.AddedGames.AddResult.Existing -> result.game
is com.droiddeck.launcher.frontend.AddedGames.AddResult.Switched -> result.game
else -> null
}
ui.post {
if (game == null) {
if (result is com.droiddeck.launcher.frontend.AddedGames.AddResult.Unreachable)
android.widget.Toast.makeText(this, R.string.games_add_unreachable, android.widget.Toast.LENGTH_LONG).show()
return@post
}
updateAddedGames(listOf(game.folder.path), then = { fetchAddedGameArt() })
navRequest = "app:${game.steamAppId ?: game.appId.toInt()}"
}
}, "add-game-exe").start()
}
private var pendingAddedGame: String? = null
private val pickAddedGameExe = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
val folder = pendingAddedGame ?: return@registerForActivityResult
pendingAddedGame = null
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path ->
SessionPrefs.setAddedGameExe(this, folder, path)
refreshAddedGames()
refresh()
}
}
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.droiddeck.launcher.ui.AddedGameRow>>(emptyList())
/** The user entered a SteamGridDB API key of their own. */
private var sgdbUserKey by mutableStateOf(false)
private val pickRomsDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path ->
SessionPrefs.setRomsDir(this, path)
@@ -590,6 +595,8 @@ class MainActivity : ComponentActivity() {
gameStoresSpeedTier = gameStoresSpeedTier,
storesOpenTab = storesOpenTab,
navigate = navRequest,
addedGamesArt = addedGamesArt,
sgdbUserKey = sgdbUserKey,
storesShowMature = storesShowMature,
storeDownloadsActive = com.droiddeck.launcher.stores.StoresState.activeDownloads,
),
@@ -606,6 +613,20 @@ class MainActivity : ComponentActivity() {
onGameShortcut = { g -> com.droiddeck.launcher.frontend.GameShortcuts.pin(this, g) },
onExportGameFile = { g -> pickGameExport(g) },
onSyncGameFiles = { pickGameExport(null) },
onAddGameExe = { path -> addGameExe(path) },
onAddedGamesChanged = { folders ->
// New games want art; an edit does not.
val known = steamGames.mapNotNull { it.gameFiles?.path }.toSet()
updateAddedGames(folders, then = { if (folders.any { it !in known }) fetchAddedGameArt() })
},
onAddedGameRemoved = { folder, appId, name -> removeAddedGame(folder, appId, name) },
onAddedGamesArt = { on -> SessionPrefs.setAddedGamesArt(this, on); addedGamesArt = on; if (on) refreshAddedGames() },
onSgdbKey = { key ->
Thread({
com.droiddeck.launcher.frontend.SteamGridDb.setUserKey(this, key)
ui.post { sgdbUserKey = key.isNotBlank(); refreshAddedGames() }
}, "sgdb-key").start()
},
onStopGameFileSync = {
Thread({
GameFileSync.disable(this)
@@ -1252,9 +1273,6 @@ class MainActivity : ComponentActivity() {
wifiDiscoveryLocation = wifiDiscoveryLocation,
wifiDiscoveryAsked = wifiDiscoveryAsked,
wifiDiscoveryBlocked = wifiDiscoveryBlocked,
addedGamesDirs = if (mode == SessionService.MODE_STEAM) addedGamesDirs else null,
addedGames = if (mode == SessionService.MODE_STEAM) addedGames else emptyList(),
addedGamesArt = addedGamesArt,
deckyInstalled = if (mode == SessionService.MODE_STEAM) decky.deckyInstalled else null,
deckyLatestRelease = if (mode == SessionService.MODE_STEAM) decky.deckyReleases.firstOrNull() else null,
deckyChecking = decky.deckyChecking, deckyStage = decky.deckyStage, deckyPercent = decky.deckyPercent,
@@ -1335,14 +1353,6 @@ class MainActivity : ComponentActivity() {
SessionPrefs.setRunSteamAtStartup(this, on)
runSteamAtStartup = on
},
onPickAddedGamesDir = { pickAddedGamesDir.launch(InAppFilePicker.buildDirIntent(this, getString(R.string.main_pick_added_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 ->
pendingAddedGame = folder
pickAddedGameExe.launch(InAppFilePicker.buildIntent(this, listOf("exe"), getString(R.string.main_pick_game_exe), folder))
},
onDeckyInstall = { release -> decky.installDecky(release) },
onDeckyCheck = { decky.refreshDecky() },
onDeckyEnabled = { enabled -> DeckyManager.setSupervisorEnabled(this, enabled); decky.deckySupervisor = enabled },
@@ -1397,18 +1407,42 @@ class MainActivity : ComponentActivity() {
)
}
/** The added games as the settings page lists them; a scan of the folder, on this thread (one level, small). */
/** The added games for the session settings: a folder walk, so off the main thread. */
private fun refreshAddedGames() {
/**
* The Games tab after these added games were added or edited: each read alone and put in
* place of its old entry (or added), no library-wide scan. [then] runs after, on the main thread.
*/
private fun updateAddedGames(folders: List<String>, then: () -> Unit = {}) {
if (folders.isEmpty()) return
Thread({
val games = scanAddedGames()
ui.post { addedGames = games; fetchAddedGameArt() }
}, "added-games").start()
val fresh = folders.mapNotNull { f ->
com.droiddeck.launcher.frontend.AddedGames.single(this, f)?.let { com.droiddeck.launcher.frontend.Library.addedGame(this, it) }
}
ui.post {
val paths = folders.toSet()
steamGames = (steamGames.filterNot { it.library == Library.ADDED && it.gameFiles?.path in paths } + fresh).distinctBy { it.gameId }
then()
}
}, "added-games-update").start()
}
/** Walks the added-games folders, which can sit on slow shared storage or an SD card. */
private fun scanAddedGames() = com.droiddeck.launcher.frontend.AddedGames.scan(this).map { g ->
com.droiddeck.launcher.ui.AddedGameRow(g.folder.path, g.folderName(), g.exe.path, g.exe.name, (g.candidates + g.exe).map { c -> c.path to c.name }.distinctBy { it.first })
/** An added game removed: off the Games tab now; the rest (cache, Steam, listing) off the main thread. */
private fun removeAddedGame(folder: String, appId: Long?, name: String) {
steamGames = steamGames.filterNot { it.library == Library.ADDED && it.gameFiles?.path == folder }
Thread({ com.droiddeck.launcher.frontend.AddedGames.remove(this, java.io.File(folder), appId, name) }, "added-game-remove").start()
}
/** After the added games changed: art that is missing is fetched (off the main thread). */
private fun refreshAddedGames() {
sgdbKeyKnown()
fetchAddedGameArt()
}
/** Whether the user has a SteamGridDB key of their own, for Setup; read off the main thread. */
private fun sgdbKeyKnown() {
Thread({
val set = com.droiddeck.launcher.frontend.SteamGridDb.userKey(this).isNotEmpty()
ui.post { sgdbUserKey = set }
}, "sgdb-key-state").start()
}
private fun fetchAddedGameArt() {
@@ -1447,7 +1481,6 @@ class MainActivity : ComponentActivity() {
mangoapp = SessionPrefs.mangoapp(this)
steamController = SessionPrefs.steamController(this)
runSteamAtStartup = SessionPrefs.runSteamAtStartup(this)
addedGamesDirs = SessionPrefs.addedGamesDirs(this)
hdrOn = SessionPrefs.hdr(this, mode)
fpsLimit = SessionPrefs.fpsLimit(this, mode)
upscaler = SessionPrefs.upscaler(this)
@@ -1469,12 +1502,10 @@ class MainActivity : ComponentActivity() {
// added-games folders, the storage volumes) lands while it animates in.
Thread({
drivers.refreshDrivers()
val games = scanAddedGames()
val storage = GameStorage.options(this)
val deckyInstalled = if (mode == SessionService.MODE_STEAM) DeckyManager.installed(this) else null
val deckySupervisor = mode == SessionService.MODE_STEAM && DeckyManager.supervisorEnabled(this)
ui.post {
addedGames = games
storageOptions = storage
if (mode == SessionService.MODE_STEAM) {
decky.deckyInstalled = deckyInstalled
@@ -1523,6 +1554,7 @@ class MainActivity : ComponentActivity() {
private fun refresh() {
if (!busy && LinuxRuntimeInstaller.isBusy()) followRuntimeOperation { LinuxRuntimeInstaller.attach(it) }
addedGamesArt = SessionPrefs.addedGamesArt(this)
desktopInstalled = DesktopCatalog.desktopInstalled(this)
offlineAccount = OfflineMode.account(this)
offline = OfflineMode.enabled(this)
@@ -0,0 +1,48 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
/**
* Games added from the Games tab's + rather than a Games folder: one picked .exe, or each game
* "Add all games in this folder" found. Kept by the game's folder in `files/added-exes.json`,
* which [AddedGames.scan] merges in. The exe chosen later, the shortcut appid, the edits and the
* removal live where every added game keeps them ([com.droiddeck.launcher.session.SessionPrefs]);
* this holds which folders are games and the exe they came with.
*/
object AddedExes {
/** [picked]: the user chose [exe]; false = [GameExePicker]'s best guess, which a scan ranks again. */
class Entry(val folder: String, val exe: String, val picked: Boolean = true)
private fun file(context: Context) = File(context.filesDir, "added-exes.json")
@Synchronized
fun list(context: Context): List<Entry> = try {
val array = JSONArray(file(context).takeIf { it.isFile }?.readText() ?: "[]")
(0 until array.length()).mapNotNull { i ->
val o = array.optJSONObject(i) ?: return@mapNotNull null
val folder = o.optString("folder"); val exe = o.optString("exe")
if (folder.isEmpty() || exe.isEmpty()) null else Entry(folder, exe, o.optBoolean("picked", true))
}
} catch (e: Exception) {
emptyList()
}
/** Adds [entry], replacing one for the same folder. */
@Synchronized
fun put(context: Context, entry: Entry) = write(context, list(context).filter { it.folder != entry.folder } + entry)
@Synchronized
fun drop(context: Context, folder: String) = write(context, list(context).filter { it.folder != folder })
private fun write(context: Context, entries: List<Entry>) {
val array = JSONArray()
entries.forEach { array.put(JSONObject().put("folder", it.folder).put("exe", it.exe).put("picked", it.picked)) }
val f = file(context)
val tmp = File(f.path + ".tmp")
tmp.writeText(array.toString())
if (!tmp.renameTo(f)) { f.delete(); tmp.renameTo(f) }
}
}
@@ -12,8 +12,9 @@ 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
* Artwork for an added game: what the user put in the game's folder first, else what Steam has
* for it - by the Steam appid its files name, else by a store search on its title - else what
* SteamGridDB has ([SteamGridDb]), 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.
@@ -28,13 +29,40 @@ object AddedGameArt {
val any get() = portrait != null || header != null || hero != null || logo != null
}
/**
* The pieces a user can choose, as the client takes them: [assetType] is its custom-artwork
* number (null: the icon, set by path); [cacheName] the automatic file in the game's cache.
*/
enum class Slot(val key: String, val cacheName: String, val assetType: Int?) {
COVER("p", "p.jpg", 0), BACKGROUND("hero", "hero.jpg", 1), LOGO("logo", "logo.png", 2), ICON("icon", "icon.png", null),
}
/** Where a piece came from; [AUTO] = nothing found yet. */
const val FOLDER = "folder"
const val STEAM = "steam"
const val SGDB = "sgdb"
const val FILE = "file"
const val EXE = "exe"
const val AUTO = ""
/** A slot as it stands: the file shown and where it came from (one of [FOLDER].. [AUTO]); [chosen] = the user picked it. */
class SlotState(val slot: Slot, val file: File?, val source: String, val chosen: Boolean)
/** One image the chooser offers: its group ([FOLDER], [STEAM], [SGDB]), a thumbnail and the full image (URL or path). */
class Option(val group: String, val thumb: String, val full: String)
private val CHOSEN = Regex("""chosen-(\w+)\.(\w+)""")
private fun chosen(cache: File, slot: Slot): File? =
cache.listFiles { f -> CHOSEN.matchEntire(f.name)?.groupValues?.get(1) == slot.key }?.firstOrNull()
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}")
internal 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? {
@@ -58,20 +86,112 @@ object AddedGameArt {
)
}
/** The folder's art, else the cached Steam art, without touching the network. */
/** The user's choice for each piece, else the folder's art, else the cached art; no 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),
portrait = chosen(cache, Slot.COVER) ?: own.portrait ?: cached("p.jpg") ?: exeArt(context, game, cover = true),
header = own.header ?: cached("header.jpg") ?: exeArt(context, game, cover = false),
hero = chosen(cache, Slot.BACKGROUND) ?: own.hero ?: cached("hero.jpg"),
logo = chosen(cache, Slot.LOGO) ?: own.logo ?: cached("logo.png"),
icon = chosen(cache, Slot.ICON) ?: own.icon ?: cached("icon-sgdb.png") ?: exeIcon(context, game),
)
}
/** Each choosable piece with its file and where it came from, for the game's editor; no network. */
fun describe(context: Context, game: AddedGames.Game): List<SlotState> {
val own = local(game)
val cache = cacheDir(context, game)
fun cached(name: String): Pair<File, String>? = File(cache, name).takeIf { it.isFile }?.let { f ->
f to (File(cache, "$name.src").takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: STEAM)
}
return Slot.values().map { slot ->
chosen(cache, slot)?.let { return@map SlotState(slot, it, chosenSource(context, game, slot).first.ifEmpty { FILE }, true) }
val auto: Pair<File, String>? = when (slot) {
Slot.COVER -> own.portrait?.let { it to FOLDER } ?: cached("p.jpg") ?: exeArt(context, game, cover = true)?.let { it to EXE }
Slot.BACKGROUND -> own.hero?.let { it to FOLDER } ?: cached("hero.jpg")
Slot.LOGO -> own.logo?.let { it to FOLDER } ?: cached("logo.png")
Slot.ICON -> own.icon?.let { it to FOLDER } ?: File(cache, "icon-sgdb.png").takeIf { it.isFile }?.let { it to SGDB }
?: exeIcon(context, game)?.let { it to EXE }
}
SlotState(slot, auto?.first, auto?.second ?: AUTO, false)
}
}
private val CHOOSABLE = setOf("png", "jpg", "jpeg", "webp")
/** Images in the game's folder (and its art folders) that could stand for a piece. */
internal fun folderImages(folder: File): List<File> =
listOf(folder, File(folder, "art"), File(folder, ".art")).flatMap { dir ->
dir.listFiles { f -> f.isFile && f.extension.lowercase() in CHOOSABLE }?.sortedBy { it.name.lowercase() }.orEmpty()
}.take(12)
/**
* What the chooser offers for [slot]: the game folder's images, Steam's official piece (when the
* game has a Steam appid and Steam has the piece), and SteamGridDB's best few (with a key).
* Blocking: it asks the network.
*/
fun options(context: Context, game: AddedGames.Game, slot: Slot): List<Option> {
val out = ArrayList<Option>()
folderImages(game.folder).forEach { out.add(Option(FOLDER, it.path, it.path)) }
val cache = cacheDir(context, game)
val steamId = runCatching { GameIdentifier.identify(game.exe).appId?.toString() }.getOrNull()
?: File(cache, "steam-appid").takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() && it != "none" }
val remote = when (slot) { Slot.COVER -> "library_600x900.jpg"; Slot.BACKGROUND -> "library_hero.jpg"; Slot.LOGO -> "logo.png"; Slot.ICON -> null }
if (steamId != null && remote != null) {
val url = "$CDN$steamId/$remote".takeIf { exists(it) } ?: steamAssetUrl(steamId, remote)
if (url != null) out.add(Option(STEAM, url, url))
}
val key = SteamGridDb.key(context)
if (key.isNotEmpty()) {
cache.mkdirs()
val gridId = remembered(File(cache, "sgdb-id")) {
runCatching { SteamGridDb.gameId(key, steamId?.toIntOrNull(), game.name) }.getOrNull()?.toString()
}?.toIntOrNull()
if (gridId != null) runCatching { SteamGridDb.images(key, gridId, slot, if (slot == Slot.ICON) 3 else 5) }.getOrNull()
?.forEach { (thumb, full) -> out.add(Option(SGDB, thumb, full)) }
}
return out
}
/** Sets [slot] to [option] (a file is copied, a URL fetched) and records where it came from. False when it could not be had. Blocking. */
fun choose(context: Context, game: AddedGames.Game, slot: Slot, option: Option): Boolean {
val bytes = if (option.full.startsWith("https://")) get(option.full) else runCatching { File(option.full).readBytes() }.getOrNull()
bytes ?: return false
val ext = option.full.substringAfterLast('.', "png").substringBefore('?').lowercase().takeIf { it in CHOOSABLE + "ico" } ?: "png"
val cache = cacheDir(context, game).apply { mkdirs() }
chosen(cache, slot)?.delete()
val dst = File(cache, "chosen-${slot.key}.${if (ext == "jpeg") "jpg" else ext}")
val tmp = File(cache, dst.name + ".tmp")
tmp.writeBytes(bytes)
if (!tmp.renameTo(dst)) return false
SessionPrefs.setAddedGameArtSource(context, game.folder.path, slot.key, option.group + "|" + option.full)
return true
}
/** Where the user's choice for [slot] came from and which image it was ("" both when automatic). */
fun chosenSource(context: Context, game: AddedGames.Game, slot: Slot): Pair<String, String> {
val value = SessionPrefs.addedGameArtSource(context, game.folder.path, slot.key)
return value.substringBefore('|') to value.substringAfter('|', "")
}
/** [slot] back to what is found by itself. */
fun reset(context: Context, game: AddedGames.Game, slot: Slot) {
chosen(cacheDir(context, game), slot)?.delete()
SessionPrefs.setAddedGameArtSource(context, game.folder.path, slot.key, "")
}
private fun exists(url: String): Boolean = runCatching {
val c = URL(url).openConnection() as HttpURLConnection
c.requestMethod = "HEAD"
c.connectTimeout = 8_000
c.readTimeout = 8_000
c.setRequestProperty("User-Agent", "DroidDeck-launcher")
try { c.responseCode == 200 } finally { c.disconnect() }
}.getOrDefault(false)
/** 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)
@@ -88,58 +208,93 @@ object AddedGameArt {
}
/**
* 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.
* Fetches the art that is missing: Steam first (the appid the game's files name, else a store
* search on its title whose result carries the same name), then SteamGridDB when a key is
* set. Each lookup runs 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
val sgdbKey = SteamGridDb.key(context)
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
val appId = runCatching { GameIdentifier.identify(game.exe).appId }.getOrNull()
val id = steamAppId(game.name, appId, File(cache, "steam-appid")) { name ->
runCatching { search(name) }.onFailure { Log.w(TAG, "${game.name}: store search failed (${it.message})") }.getOrNull()
}
if (id != null && download(id, cache)) changed = true
if (File(cache, "p.jpg").isFile || sgdbKey.isEmpty()) continue
val gridId = remembered(File(cache, "sgdb-id")) {
runCatching { SteamGridDb.gameId(sgdbKey, appId ?: id?.toIntOrNull(), game.name) }.getOrNull()?.toString()
}?.toIntOrNull() ?: continue
if (runCatching { SteamGridDb.download(sgdbKey, gridId, cache) }.getOrDefault(false)) changed = true
}
return changed
}
/**
* The game's Steam appid for its art: the one its files name ([appId]) as it is, else the
* remembered or freshly searched one ([search] on [name]); null for none.
*/
internal fun steamAppId(name: String, appId: Int?, lookup: File, search: (String) -> String?): String? {
if (appId != null) {
lookup.writeText(appId.toString())
Log.i(TAG, "$name: Steam app $appId (from its files)")
return appId.toString()
}
return remembered(lookup) { search(name)?.also { Log.i(TAG, "$name: Steam app $it") } }
}
/** What [marker] remembers (an id, or "none" for a week), else [find]'s answer written to it. */
private fun remembered(marker: File, find: () -> String?): String? {
if (marker.isFile) {
val value = marker.readText().trim()
if (value != "none") return value
if (System.currentTimeMillis() - marker.lastModified() < RETRY_AFTER_MS) return null
}
val found = find()
marker.writeText(found ?: "none")
return found
}
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 val EDITION = Regex("(?i)\\b(complete|definitive|legendary|goty|game of the year|deluxe|ultimate|remastered)( edition)?\\b")
/**
* How well a result's name [got] matches the game's [name]: 3 the same, 2 the same once
* edition words are dropped, 1 one starts with the other; 0 no match. Nothing is taken for
* being the first result.
*/
internal fun nameMatch(name: String, got: String): Int {
val want = normalize(name)
val wantShort = normalize(name.replace(EDITION, " ").trim().ifEmpty { name })
val have = normalize(got)
if (have.isEmpty() || wantShort.isEmpty()) return 0
return when {
have == want -> 3
have == wantShort -> 2
have.startsWith(wantShort) || wantShort.startsWith(have) -> 1
else -> 0
}
}
/** The id of the store result whose name matches [name] best, or null when none does. */
internal fun pickStoreResult(name: String, items: List<Pair<String, String>>): String? =
items.map { (id, got) -> id to nameMatch(name, got) }
.filter { it.second > 0 && it.first.isNotEmpty() }
.maxByOrNull { it.second }?.first
/** The Steam appid whose store name matches [name], 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 term = name.replace(EDITION, " ").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 }
return pickStoreResult(name, (0 until items.length()).map { items.getJSONObject(it) }.map { it.optString("id") to it.optString("name") })
}
private fun download(id: String, cache: File): Boolean {
@@ -149,15 +304,73 @@ object AddedGameArt {
)) {
val dst = File(cache, localName)
if (dst.isFile) continue
val bytes = get("$CDN$id/$remote") ?: continue
val bytes = get("$CDN$id/$remote") ?: steamAssetUrl(id, remote)?.let { get(it) } ?: continue
val tmp = File(cache, "$localName.tmp")
tmp.writeBytes(bytes)
if (tmp.renameTo(dst)) got = true
if (tmp.renameTo(dst)) { got = true; File(cache, "$localName.src").writeText(STEAM) }
}
return got
}
private fun get(url: String): ByteArray? {
/**
* Newer Steam games keep their art under hashed paths (store_item_assets/steam/apps/<id>/<hash>/…),
* where the fixed CDN names above 404. The store's item API names those paths; once per appid.
*/
private fun steamAssetUrl(id: String, remote: String): String? {
val assets = steamAssets.getOrPut(id) {
runCatching {
val input = """{"ids":[{"appid":$id}],"context":{"language":"english","country_code":"US"},"data_request":{"include_assets":true}}"""
val json = get("https://api.steampowered.com/IStoreBrowseService/GetItems/v1/?input_json=" + URLEncoder.encode(input, "UTF-8"))
?.toString(Charsets.UTF_8) ?: return@runCatching emptyMap()
val a = JSONObject(json).optJSONObject("response")?.optJSONArray("store_items")?.optJSONObject(0)?.optJSONObject("assets")
?: return@runCatching emptyMap()
val format = a.optString("asset_url_format").takeIf { it.contains("\${FILENAME}") } ?: return@runCatching emptyMap()
fun url(vararg keys: String) = keys.firstNotNullOfOrNull { k -> a.optString(k).takeIf { it.isNotEmpty() } }
?.let { "https://shared.akamai.steamstatic.com/store_item_assets/" + format.replace("\${FILENAME}", it) }
mapOf(
"library_600x900.jpg" to url("library_capsule_2x", "library_capsule"),
"header.jpg" to url("header"),
"library_hero.jpg" to url("library_hero_2x", "library_hero"),
).filterValues { it != null }.mapValues { it.value!! }
}.getOrDefault(emptyMap())
}
return assets[remote]
}
private val steamAssets = java.util.concurrent.ConcurrentHashMap<String, Map<String, String>>()
/**
* When nothing else gave a cover (or header), one made from the exe's icon: the icon centred on
* its own colour, darkened toward the bottom, so the game still has a face in the list and in
* Steam. Made once per game; real art found later takes over because it is looked at first.
*/
private fun exeArt(context: Context, game: AddedGames.Game, cover: Boolean): File? {
val cache = cacheDir(context, game)
val out = File(cache, if (cover) "p-exe.png" else "header-exe.png")
if (out.isFile) return out
val icon = exeIcon(context, game) ?: return null
val src = android.graphics.BitmapFactory.decodeFile(icon.path) ?: return null
val (w, h) = if (cover) 600 to 900 else 920 to 430
val tint = android.graphics.Bitmap.createScaledBitmap(src, 1, 1, true).getPixel(0, 0)
val bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
val canvas = android.graphics.Canvas(bmp)
fun shade(c: Int, f: Float) = android.graphics.Color.rgb(
(android.graphics.Color.red(c) * f).toInt(), (android.graphics.Color.green(c) * f).toInt(), (android.graphics.Color.blue(c) * f).toInt(),
)
canvas.drawPaint(android.graphics.Paint().apply {
shader = android.graphics.LinearGradient(0f, 0f, 0f, h.toFloat(), shade(tint, 0.7f), shade(tint, 0.15f), android.graphics.Shader.TileMode.CLAMP)
})
val side = (minOf(w, h) * 0.5f).toInt()
val left = (w - side) / 2f
val top = (h - side) / 2f
canvas.drawBitmap(src, null, android.graphics.RectF(left, top, left + side, top + side), android.graphics.Paint(android.graphics.Paint.FILTER_BITMAP_FLAG))
cache.mkdirs()
val tmp = File(cache, "${out.name}.tmp")
tmp.outputStream().use { bmp.compress(Bitmap.CompressFormat.PNG, 100, it) }
return if (tmp.renameTo(out)) out else null
}
internal fun get(url: String): ByteArray? {
val c = URL(url).openConnection() as HttpURLConnection
c.connectTimeout = 10_000
c.readTimeout = 15_000
@@ -0,0 +1,77 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.SteamLiveShortcuts
import java.io.File
/**
* The game editor's writes for an added game, Steam's non-Steam Properties in the app: name,
* target, Start in, launch options and art. Each goes through the same shortcut - the listing the
* shortcuts writer reads, and the running client - on the appid the game already has, so an edit
* never makes a second shortcut. Each call is quick (the game alone, [AddedGames.single]); the
* client and the listing follow on [AddedGamesPublisher], in order. Call off the main thread.
*/
object AddedGameEdits {
/** The added game in [folder] as it stands now, or null when it is not listed. */
fun game(context: Context, folder: String): AddedGames.Game? = AddedGames.single(context, folder)
/** The client told ([live]), then the listing rewritten, on [AddedGamesPublisher]. */
private fun publish(context: Context, live: () -> Unit) = AddedGamesPublisher.later(context, live)
/** [name] as the game's name; "" goes back to the name found by itself. */
fun setName(context: Context, folder: String, name: String): AddedGames.Game? {
SessionPrefs.setAddedGameName(context, folder, name)
return apply(context, folder)
}
/** [exe] as the game's target; false when the session cannot see it. */
fun setExe(context: Context, folder: String, exe: File): Boolean {
if (!exe.isFile || AddedGames.guestPath(context, exe) == null) return false
SessionPrefs.setAddedGameExe(context, folder, exe.path)
apply(context, folder)
return true
}
/** [dir] (a host folder) as the game's Start in; "" = the exe's own folder. False when the session cannot see it. */
fun setStartIn(context: Context, folder: String, dir: String): Boolean {
val guest = if (dir.isBlank()) "" else AddedGames.guestPath(context, File(dir.trim())) ?: return false
SessionPrefs.setAddedGameStartIn(context, folder, guest)
apply(context, folder)
return true
}
fun setLaunchOptions(context: Context, folder: String, options: String): AddedGames.Game? {
SessionPrefs.setAddedGameLaunch(context, folder, options)
return apply(context, folder)
}
/** [slot] set to [option], then handed to the shortcut. False when the image could not be had. */
fun setArt(context: Context, folder: String, slot: AddedGameArt.Slot, option: AddedGameArt.Option): Boolean {
val game = game(context, folder) ?: return false
if (!AddedGameArt.choose(context, game, slot, option)) return false
applyArt(context, game, slot)
return true
}
/** [slot] back to automatic, then handed to the shortcut. */
fun resetArt(context: Context, folder: String, slot: AddedGameArt.Slot) {
val game = game(context, folder) ?: return
AddedGameArt.reset(context, game, slot)
applyArt(context, game, slot)
}
private fun applyArt(context: Context, game: AddedGames.Game, slot: AddedGameArt.Slot) {
val file = AddedGameArt.describe(context, game).first { it.slot == slot }.file
publish(context) {
if (slot == AddedGameArt.Slot.ICON) SteamLiveShortcuts.setArt(context, game.appId, null, null, iconPath = file?.absolutePath.orEmpty())
else SteamLiveShortcuts.setArt(context, game.appId, slot.assetType, file)
}
}
private fun apply(context: Context, folder: String): AddedGames.Game? {
val game = game(context, folder)
if (game != null) publish(context) { SteamLiveShortcuts.update(context, game) }
return game
}
}
@@ -33,6 +33,12 @@ object AddedGames {
val source: String = Library.ADDED,
/** The store's own id for the game, from its sidecar; null for a plain added folder. */
val storeId: String? = null,
/** The exe is the picker's guess and nothing clearly won ([GameExePicker.Ranking.uncertain]). */
val exeUncertain: Boolean = false,
/** Steam's launch options for the shortcut; "" for none. */
val launchOptions: String = "",
/** Added from the Games tab (an entry of its own), not found in a Games folder. */
val single: Boolean = false,
) {
fun folderName(): String = folder.name
}
@@ -86,23 +92,73 @@ object AddedGames {
// root/Games/Stores): the tree is the session's / and needs no bind.
val runtime = LinuxRuntime.rootDir(context).absolutePath
if (path.startsWith("$runtime/")) return "/" + path.removePrefix("$runtime/")
// Internal storage, bound at /root/Storage in every session: an exe picked anywhere on it.
val storage = android.os.Environment.getExternalStorageDirectory().absolutePath
if (path.startsWith("$storage/")) return "/root/Storage/" + path.removePrefix("$storage/")
return null
}
/** The .exe files a game folder offers, best first. */
fun candidates(folder: File): List<File> {
val exes = ArrayList<File>()
val roots = listOf(folder) + (folder.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList())
for (dir in roots) {
dir.listFiles { f -> f.isFile && f.name.endsWith(".exe", ignoreCase = true) && !SKIP.matches(f.name) }
?.let { exes.addAll(it) }
/** The .exe files a game folder offers, best first ([GameExePicker]); also what its exe box lists, in that order. */
fun candidates(folder: File): List<File> = rank(folder).exes
/** [GameExePicker]'s ranking of [folder], without the names this list never offers. */
fun rank(folder: File): GameExePicker.Ranking {
val key = "${folder.path}|${folder.lastModified()}"
val now = System.currentTimeMillis()
ranked[key]?.takeIf { now - it.first < RANK_FRESH_MS }?.let { return it.second }
return GameExePicker.rank(folder) { !SKIP.matches(it.name) }.also {
if (ranked.size > 256) ranked.clear()
ranked[key] = now to it
}
}
/** A folder's ranking for a minute, so one add (rank, then the game built from it) walks it once. */
private val ranked = java.util.concurrent.ConcurrentHashMap<String, Pair<Long, GameExePicker.Ranking>>()
private const val RANK_FRESH_MS = 60_000L
/**
* Names identified from an exe (Steam manifest, GOG info, version resource), by the exe's path,
* size and time and its game folder's time (a GOG info file dropped in changes the latter).
*/
private val identified = java.util.concurrent.ConcurrentHashMap<String, String>()
/**
* The game's own title for [exe] when the disk names one ([GameIdentifier]: a Steam manifest,
* a GOG info file, the exe's version resource), else null (the folder name stands).
*/
internal fun identifiedName(folder: File, exe: File): String? {
val key = "${exe.path}|${exe.length()}|${exe.lastModified()}|${folder.lastModified()}"
identified[key]?.let { return it.ifEmpty { null } }
val id = runCatching { GameIdentifier.identify(exe) }.getOrNull()
val found = id?.name?.takeIf {
id.nameSource in setOf(GameIdentifier.Source.STEAM_MANIFEST_ACF, GameIdentifier.Source.GOG_INFO, GameIdentifier.Source.PE_VERSION)
}
val name = found?.let { if (id?.nameSource == GameIdentifier.Source.PE_VERSION) betterSpelling(underscoresToSpaces(it), folder.name) else it }
identified[key] = name.orEmpty()
return name
}
/**
* The exe's version resource often spells the title the way a programmer typed it ("Insane2")
* while the folder has the real spacing ("Insane 2"). When both spell the same letters and
* digits, the one with more word breaks wins; a tie keeps mixed case over all one case
* ("DiRT 3" over "dirt 3"), else the exe's spelling. Different titles keep the exe's.
*/
/** "Watch_Dogs" → "Watch Dogs": an underscore in a version-resource title is a programmer's space. */
internal fun underscoresToSpaces(name: String): String =
name.replace('_', ' ').replace(Regex("\\s+"), " ").trim().ifEmpty { name }
internal fun betterSpelling(peName: String, folderName: String): String {
fun key(s: String) = s.lowercase().filter { it.isLetterOrDigit() }
if (key(peName) != key(folderName) || folderName.isBlank()) return peName
fun breaks(s: String) = s.count { !it.isLetterOrDigit() }
fun mixed(s: String) = s.any { it.isUpperCase() } && s.any { it.isLowerCase() }
return when {
breaks(folderName) > breaks(peName) -> folderName.trim()
breaks(folderName) < breaks(peName) -> peName
mixed(folderName) && !mixed(peName) -> folderName.trim()
else -> peName
}
val key = folder.name.lowercase().replace(Regex("[^a-z0-9]"), "")
return exes.sortedWith(
compareByDescending<File> { it.parentFile == folder }
.thenByDescending { it.nameWithoutExtension.lowercase().replace(Regex("[^a-z0-9]"), "").let { n -> n == key || key.startsWith(n) || n.startsWith(key) } }
.thenByDescending { it.length() },
)
}
fun scan(context: Context): List<Game> {
@@ -111,22 +167,181 @@ object AddedGames {
GameStorage.effective(context)?.let { File(it.path) },
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
)
val removed = SessionPrefs.removedAddedGames(context).toSet()
for (dir in folders.distinctBy { it.absolutePath }) {
if (!dir.isDirectory) { Log.w(TAG, "$dir is not a folder; skipped"); continue }
val steamInstalls = steamInstallDirs(dir)
for (folder in dir.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList()) {
if (folder.name.lowercase() in steamInstalls || folder.name.equals("steamapps", ignoreCase = true)) continue
// Removed from the list by the user (the folder stays on disk); restored from the settings page.
if (folder.path in removed) continue
// The store install root sits inside the Games storage; its games are scanned below, per store.
if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue
scanGame(context, folder, out)
}
}
// Games added as one picked exe (the Games tab's +), by that exe's folder.
for (entry in AddedExes.list(context)) {
val folder = File(entry.folder)
if (folder.path in removed || !folder.isDirectory) continue
scanGame(context, folder, out, single = entry)
}
// Games the Stores section installed: one folder each under <root>/<Store>/, with a sidecar.
// An unfinished one (sidecar still `installing`, or none at all) is neither a game nor Custom.
for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out)
return out.distinctBy { it.folder.canonicalPath }
}
/**
* The game in [folderPath] alone, built by the same rules as [scan] (store sidecar, an entry
* from the Games tab, the chosen exe, the edits) without walking every other game: what the
* editor needs for one game. Null when that folder is not a game, or was removed.
*/
fun single(context: Context, folderPath: String): Game? {
val folder = File(folderPath)
if (!folder.isDirectory || folderPath in SessionPrefs.removedAddedGames(context)) return null
val out = ArrayList<Game>(1)
scanGame(context, folder, out, single = AddedExes.list(context).firstOrNull { it.folder == folderPath })
return out.firstOrNull()
}
/**
* Stops listing the added game in [folder] at once: marked removed and dropped from the
* library cache; the running client loses its shortcut ([appId], else the one stored for the
* folder) and the listing is rewritten afterwards ([AddedGamesPublisher]). Nothing on disk is
* deleted. Quick; call off the main thread (preferences and a small file).
*/
fun remove(context: Context, folder: File, appId: Long? = null, name: String = folder.name) {
val app = context.applicationContext
val started = android.os.SystemClock.elapsedRealtime()
val id = appId ?: SessionPrefs.addedGameStoredAppId(app, folder.path)
SessionPrefs.setAddedGameRemoved(app, folder.path, true)
LibraryCache.save(app, LibraryCache.load(app).filterNot { it.library == Library.ADDED && it.gameFiles?.path == folder.path })
Log.i(TAG, "games: remove $name took ${android.os.SystemClock.elapsedRealtime() - started}ms")
AddedGamesPublisher.later(app) { if (id != null) com.droiddeck.launcher.stores.SteamLiveShortcuts.remove(app, id) }
}
/** What [addExe] did with a picked exe. */
sealed class AddResult {
/** A new game, or the existing one the exe already is, or the listed game whose exe it now is. */
class Added(val game: Game) : AddResult()
class Existing(val game: Game) : AddResult()
class Switched(val game: Game) : AddResult()
/** The session cannot see the exe's path. */
object Unreachable : AddResult()
object NotFound : AddResult()
}
private fun canonical(f: File): String = runCatching { f.canonicalPath }.getOrDefault(f.absolutePath)
private fun inside(path: String, folder: String) = path.startsWith(folder.trimEnd('/') + "/")
/**
* The game folder [exe] belongs to, without a scan: an entry from the Games tab, a removed
* game, a store install, or the first-level folder under a Games folder (or the Steam library)
* that holds it. Null when it is in none.
*/
private fun ownerFolder(context: Context, exe: File): File? {
val path = canonical(exe)
fun holds(f: File) = inside(path, canonical(f))
AddedExes.list(context).map { File(it.folder) }.firstOrNull(::holds)?.let { return it }
SessionPrefs.removedAddedGames(context).map { File(it) }.firstOrNull(::holds)?.let { return it }
StoreInstallRoot.gameFolders(context).firstOrNull(::holds)?.let { return it }
val dirs = roots(context).map { it.host } + listOfNotNull(
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
GameStorage.effective(context)?.let { File(it.path) },
)
for (dir in dirs) {
val base = canonical(dir)
if (!inside(path, base)) continue
val first = path.removePrefix("$base/").substringBefore('/')
File(dir, first).takeIf { it.isDirectory && first != "steamapps" }?.let { return it }
}
return null
}
/**
* Adds the game [exe] is: the game itself when it is listed already, that game's exe switched
* when [exe] sits in a listed (or removed) game's folder, else a new game for [exe]'s folder.
* Only that one game is read; Steam (the running client, then the listing) follows on
* [AddedGamesPublisher]. Nothing is added when the session cannot see the path.
*/
fun addExe(context: Context, exe: File): AddResult {
val app = context.applicationContext
if (!exe.isFile) return AddResult.NotFound
val path = canonical(exe)
val owner = ownerFolder(app, exe)
if (owner != null && owner.path !in SessionPrefs.removedAddedGames(app)) {
single(app, owner.path)?.takeIf { canonical(it.exe) == path }?.let { return AddResult.Existing(it) }
}
if (owner == null && guestPath(app, exe) == null) return AddResult.Unreachable
val folder = owner ?: exe.parentFile ?: return AddResult.NotFound
SessionPrefs.setAddedGameRemoved(app, folder.path, false)
SessionPrefs.setAddedGameExe(app, folder.path, exe.path)
if (owner == null) AddedExes.put(app, AddedExes.Entry(folder.path, exe.path))
val game = single(app, folder.path) ?: return AddResult.NotFound
AddedGamesPublisher.later(app) { com.droiddeck.launcher.stores.SteamLiveShortcuts.sync(app, listOf(game)) { true } }
Log.i(TAG, "added ${game.name} from its exe")
return if (owner == null) AddResult.Added(game) else AddResult.Switched(game)
}
/** What [addFolder] did: the games it added, and how many of the folder's games were listed already. */
class FolderResult(val added: List<Game>, val already: Int)
/**
* "Add all games in this folder": every subfolder of [dir] with an .exe becomes a game with
* [GameExePicker]'s best one (marked uncertain where nothing clearly won), as an entry of its
* own, not a Games folder. A subfolder that is, holds or sits in a listed game counts as
* already there; a removed one comes back. Steam follows once, on [AddedGamesPublisher]. Blocking.
*/
fun addFolder(context: Context, dir: File, onGame: (Game) -> Unit = {}, onChecking: (String?) -> Unit = {}): FolderResult {
val app = context.applicationContext
val removed = SessionPrefs.removedAddedGames(app).toSet()
val listed = listedFolders(app, removed)
var already = 0
val fresh = ArrayList<String>()
val added = ArrayList<Game>()
for (sub in dir.listFiles { f -> f.isDirectory && !f.name.startsWith(".") }?.sortedBy { it.name.lowercase() }.orEmpty()) {
val path = canonical(sub)
if (listed.any { it == path || inside(path, it) || inside(it, path) }) { already++; continue }
onChecking(sub.name)
val best = rank(sub).exes.firstOrNull() ?: continue
if (guestPath(app, best) == null) continue
if (sub.path in removed) SessionPrefs.setAddedGameRemoved(app, sub.path, false)
AddedExes.put(app, AddedExes.Entry(sub.path, best.path, picked = false))
fresh.add(sub.path)
single(app, sub.path)?.let { added.add(it); onGame(it) }
}
onChecking(null)
if (fresh.isEmpty()) return FolderResult(emptyList(), already)
AddedGamesPublisher.later(app) { com.droiddeck.launcher.stores.SteamLiveShortcuts.sync(app, added) { true } }
Log.i(TAG, "added ${added.size} game(s) from ${dir.name}, $already already listed")
return FolderResult(added, already)
}
/**
* The game folders already listed, without building any game: the first-level folders of the
* Games folders and the Steam library (as [scan] walks them), the Games tab's entries and the
* store installs. Canonical paths; removed games are left out.
*/
private fun listedFolders(context: Context, removed: Set<String>): List<String> {
val out = ArrayList<String>()
val dirs = roots(context).map { it.host } + listOfNotNull(
GameStorage.effective(context)?.let { File(it.path) },
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
)
for (dir in dirs.distinctBy { it.absolutePath }) {
for (folder in dir.listFiles { f -> f.isDirectory }.orEmpty()) {
if (folder.path in removed || folder.name.equals("steamapps", ignoreCase = true)) continue
if (folder.name == "Games" && StoreInstallRoot.roots(context).any { it.absolutePath == folder.absolutePath }) continue
out.add(canonical(folder))
}
}
AddedExes.list(context).filter { it.folder !in removed }.forEach { out.add(canonical(File(it.folder))) }
StoreInstallRoot.gameFolders(context).forEach { out.add(canonical(it)) }
return out
}
/**
* The folders under a library's steamapps/common that a manifest beside it already claims.
* Steam lists those itself, so a shortcut would only add a non-Steam copy of the game. Steam
@@ -145,13 +360,16 @@ object AddedGames {
private val INSTALL_DIR = Regex("\"installdir\"\\s*\"([^\"]*)\"", RegexOption.IGNORE_CASE)
private fun scanGame(context: Context, folder: File, out: MutableList<Game>) {
/** [single]: the entry a game added from the Games tab has; its exe stands in when no other is chosen and the user picked it. */
private fun scanGame(context: Context, folder: File, out: MutableList<Game>, single: AddedExes.Entry? = null) {
run {
// A store install carries a sidecar; every one of them is a shortcut.
val sidecar = StoreGameSidecar.read(folder)
val candidates = candidates(folder)
val ranking = rank(folder)
val candidates = ranking.exes
val picked = SessionPrefs.addedGameExe(context, folder.path)
val chosen = picked.takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
?: single?.takeIf { it.picked }?.let { File(it.exe) }?.takeIf { it.isFile }
// A store install says which exe it is; the folder's guess only when that file is gone.
val found = chosen ?: sidecar?.exeFile(folder)?.takeIf { it.isFile } ?: candidates.firstOrNull() ?: return
// The store's launcher .bat stands in front of the exe when the game needs arguments or
@@ -159,23 +377,32 @@ object AddedGames {
val launch = if (chosen == null) sidecar?.launcherFile(folder)?.takeIf { it.isFile } ?: found else found
val foundGuest = guestPath(context, launch)
if (foundGuest == null) { Log.w(TAG, "${folder.name}: the session cannot see ${launch.path}"); return }
val name = sidecar?.title ?: folder.name
// A store install's title; else the title the disk gives (the shortcut's appid is kept
// per folder from its first scan, so a name found later does not move it); else the folder.
val autoName = sidecar?.title ?: identifiedName(folder, found) ?: folder.name
// Keyed by the pre-rename path so shortcut ids, and the prefixes and saves under them, stay put.
val crc = CRC32().apply { update(("\"${foundGuest.replaceFirst(Regex("^$LIBRARY/"), "$LEGACY_LIBRARY/")}\"" + name).toByteArray()) }.value
val crc = CRC32().apply { update(("\"${foundGuest.replaceFirst(Regex("^$LIBRARY/"), "$LEGACY_LIBRARY/")}\"" + autoName).toByteArray()) }.value
val appId = SessionPrefs.addedGameAppId(context, folder.path, crc or 0x80000000L)
val config = accountConfig(File(LinuxRuntime.rootDir(context), "root/.local/share/Steam"))
val record = config?.let { shortcutRecord(it, appId) }
val rev = record?.optInt("rev", 0) ?: 0
// Name, Start in and launch options edited in Steam's own Properties become the app's.
if (sidecar == null && record != null) adoptSteamEdits(context, folder, record)
val name = SessionPrefs.addedGameName(context, folder.path).takeIf { sidecar == null && it.isNotEmpty() } ?: autoName
val adopted = guestPath(context, folder)
?.let { steamTarget(folder, it, record, foundGuest, SessionPrefs.addedGameExeSeen(context, folder.path)) }
?.takeIf { SessionPrefs.adoptAddedGameExe(context, folder.path, picked, it.path, rev) }
val exe = adopted ?: found
val guestExe = if (adopted != null) guestPath(context, adopted) ?: return else foundGuest
val guestDir = guestPath(context, (if (adopted != null) adopted else launch).parentFile ?: folder) ?: return
val guestDir = SessionPrefs.addedGameStartIn(context, folder.path).takeIf { sidecar == null && it.isNotEmpty() }
?: guestPath(context, (if (adopted != null) adopted else launch).parentFile ?: folder) ?: return
val steamId = config?.let { steamRoute(it, appId) }
out.add(Game(folder, name, exe, guestExe, guestDir, appId,
steamId?.toLong() ?: ((appId shl 32) or 0x02000000L), candidates, steamId,
source = sidecar?.store?.id ?: Library.ADDED, storeId = sidecar?.id))
source = sidecar?.store?.id ?: Library.ADDED, storeId = sidecar?.id,
exeUncertain = sidecar == null && chosen == null && adopted == null && ranking.uncertain,
launchOptions = if (sidecar == null) SessionPrefs.addedGameLaunch(context, folder.path) else "",
single = single != null))
}
}
@@ -208,6 +435,35 @@ object AddedGames {
private fun unquote(value: String?): String = value.orEmpty().trim().trim('"')
/**
* What the user changed in Steam's Properties since the app last wrote the shortcut ([record]:
* what the app asked for, and what Steam had): a new name, launch options, or a Start in other
* than the exe's folder, taken over as the app's own. Each Steam value is taken once, so an app
* edit made after it is not undone before the shortcut is written again.
*/
internal fun adoptSteamEdits(context: Context, folder: File, record: JSONObject) {
val app = record.optJSONObject("app") ?: return
val steam = record.optJSONObject("steam") ?: return
fun adopt(field: String, value: String, apply: (String) -> Unit) {
if (SessionPrefs.addedGameAdopted(context, folder.path, field) == value) return
SessionPrefs.setAddedGameAdopted(context, folder.path, field, value)
apply(value)
}
if (steam.has("AppName") && app.has("AppName")) {
val s = steam.optString("AppName"); val a = app.optString("AppName")
if (s.isNotEmpty() && s != a) adopt("AppName", s) { SessionPrefs.setAddedGameName(context, folder.path, it) }
}
if (steam.has("LaunchOptions") && app.has("LaunchOptions")) {
val s = steam.optString("LaunchOptions"); val a = app.optString("LaunchOptions")
if (s != a) adopt("LaunchOptions", s) { SessionPrefs.setAddedGameLaunch(context, folder.path, it) }
}
if (steam.has("StartDir") && app.has("StartDir")) {
val s = unquote(steam.optString("StartDir")); val a = unquote(app.optString("StartDir"))
val exeDir = unquote(steam.optString("Exe")).substringBeforeLast('/', "")
if (s.isNotEmpty() && s != a) adopt("StartDir", s) { SessionPrefs.setAddedGameStartIn(context, folder.path, if (it == exeDir) "" else it) }
}
}
/** The list the session hands the runtime's shortcuts writer; one file per session start. */
fun writeListing(context: Context, games: List<Game>): File {
val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() }
@@ -218,6 +474,7 @@ object AddedGames {
.append(",\"folder\":").append(quote(guestPath(context, g.folder) ?: g.guestDir))
.append(",\"dir\":").append(quote(g.guestDir)).append(",\"appid\":").append(g.appId)
.append(",\"seen\":").append(SessionPrefs.addedGameExeSeen(context, g.folder.path))
if (g.launchOptions.isNotEmpty()) json.append(",\"launch\":").append(quote(g.launchOptions))
// 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)
@@ -0,0 +1,40 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import android.util.Log
import androidx.annotation.VisibleForTesting
import java.util.concurrent.Executors
/**
* The slow part of an added-game change, off the caller's path and in order: the running client
* told ([later]'s work), then the listing the shortcuts writer reads at the next session start and
* the library cache, both from one scan ([republish]). An add, an edit or a removal shows at once;
* this follows.
*/
object AddedGamesPublisher {
private const val TAG = "AddedGamesPublisher"
/** Tests publish at once, to read the listing right after a change. */
@VisibleForTesting
@Volatile
internal var now = false
private val worker = Executors.newSingleThreadExecutor { r -> Thread(r, "added-games-publish") }
/** [live] (a DevTools call or nothing), then [republish], on the worker. */
fun later(context: Context, live: () -> Unit = {}) {
val app = context.applicationContext
val work = Runnable {
try { live() } catch (e: Exception) { Log.w(TAG, "live: ${e.message}") }
try { republish(app) } catch (e: Exception) { Log.w(TAG, "listing: ${e.message}") }
}
if (now) work.run() else worker.execute(work)
}
/** The listing and the library cache from one scan of the added games. Blocking. */
fun republish(context: Context) {
val games = AddedGames.scan(context)
AddedGames.writeListing(context, games)
LibraryCache.save(context, Library.launchableGames(context, added = games))
}
}
@@ -0,0 +1,130 @@
package com.droiddeck.launcher.frontend
import java.io.File
/**
* Which `.exe` in a game folder is the game. A real install holds installers, crash handlers,
* anti-cheat stubs and launchers beside the game, and the game itself may sit several levels down
* (`Game/Binaries/Win64/Game-Win64-Shipping.exe`), so candidates are collected with a bounded walk
* and ranked rather than guessed by position.
*/
object GameExePicker {
/** How far below a game folder to look: Unreal puts the game three down, repacks deeper. */
const val MAX_DEPTH = 5
/** Folders and .exe files looked at per game before the walk stops, so a huge game stays quick. */
const val WALK_BUDGET = 400
/** Below this the pick is marked uncertain rather than trusted silently. */
const val CONFIDENT_SCORE = 60
/** The best and the runner-up this close together: nothing clearly won. */
const val AMBIGUOUS_MARGIN = 15
/** Folders that never hold the game itself. */
private val SKIP_DIRS = setOf(
"_commonredist", "commonredist", "redist", "redistributable", "redistributables",
"directx", "dotnet", "dotnetfx", "vcredist", "vc_redist", "prerequisites", "prereq",
"installer", "installers", "__installer", "support", "extras", "docs", "documentation", "manual",
"soundtrack", "ost", "artbook", "bonus", "dlc", "mods", "saves", "savegames",
"crashreportclient", "easyanticheat", "battleye", "punkbuster", "steamworks shared", ".git",
)
private val SKIP_DIR_PREFIX = listOf("dotnet", "vcredist", "$")
private val SKIP_PATHS = listOf("engine/extras", "engine/binaries/thirdparty")
/** Exe names that are never the game. */
private val JUNK_EXE_RE = Regex(
"""(?i)^(unins\w*|setup|install\w*|vc_?redist.*|vcredist.*|dxsetup|dxwebsetup|directx.*|""" +
"""oalinst|openal.*|dotnetfx.*|ndp\d.*|unitycrashhandler\d*|crashreport\w*|crashpad\w*|""" +
"""crashsender\w*|easyanticheat\w*|eac\w*|battleye\w*|beservice\w*|punkbuster\w*|""" +
"""steamerrorreporter\d*|gameoverlayui|touchup|cleanup|config|settings|benchmark|""" +
"""activation\w*|register\w*|readme|report\w*|.*_debug|.*-debug)$""",
)
/** A folder's exes best first, with their scores, and whether the first clearly won. */
class Ranking(val exes: List<File>, val scores: List<Int>, val uncertain: Boolean)
/** Ranks the .exe files under [folder]; [keep] drops names the caller never offers. */
fun rank(folder: File, keep: (File) -> Boolean = { true }): Ranking {
val scored = collect(folder).filter { keep(it.first) }.map { (exe, depth) -> exe to score(exe, folder, depth) }
.sortedWith(compareByDescending<Pair<File, Int>> { it.second }.thenBy { it.first.path.lowercase() })
val best = scored.firstOrNull()?.second
val runnerUp = scored.getOrNull(1)?.second
val uncertain = best != null && (best < CONFIDENT_SCORE || (runnerUp != null && best - runnerUp < AMBIGUOUS_MARGIN))
return Ranking(scored.map { it.first }, scored.map { it.second }, uncertain)
}
/**
* Every plausible exe under [folder] with its depth (0 = in the folder itself): up to
* [MAX_DEPTH] folders down, nearest levels first, at most [WALK_BUDGET] entries, never through a
* symlink, past folders that never hold the game.
*/
private fun collect(folder: File): List<Pair<File, Int>> {
val found = ArrayList<Pair<File, Int>>()
var visited = 0
var level = listOf(folder)
var depth = 0
walk@ while (level.isNotEmpty()) {
val next = ArrayList<File>()
for (dir in level) {
val entries = dir.listFiles()?.sortedBy { it.name.lowercase() } ?: continue
for (f in entries) {
if (visited >= WALK_BUDGET) break@walk
if (isLink(f)) continue
if (f.isDirectory) {
visited++
if (depth < MAX_DEPTH && !skipDir(f, f.relativeTo(folder).invariantSeparatorsPath)) next.add(f)
} else if (f.isFile && f.name.endsWith(".exe", ignoreCase = true)) {
visited++
if (!JUNK_EXE_RE.matches(f.nameWithoutExtension)) found.add(f to depth)
}
}
}
level = next
depth++
}
return found
}
/**
* How likely [exe] is to be the game in [folder]. Relative only: the numbers rank candidates
* against each other and decide whether anything won clearly enough to trust.
*/
internal fun score(exe: File, folder: File, depth: Int): Int {
var score = 0
val base = exe.nameWithoutExtension
val exeKey = key(base)
val folderKey = key(folder.name)
// The exe named after its folder is the single strongest signal.
if (exeKey.isNotEmpty() && folderKey.isNotEmpty()) {
when {
exeKey == folderKey -> score += 100
folderKey.contains(exeKey) || exeKey.contains(folderKey) -> score += 60
}
}
// Unreal ships as <Game>-Win64-Shipping.exe under Binaries/Win64.
if (base.endsWith("-Win64-Shipping", true) || base.endsWith("-Win32-Shipping", true)) score += 70
val path = exe.absolutePath.lowercase()
if (path.contains("/binaries/win64") || path.contains("/binaries/win32")) score += 30
if (path.contains("/bin/") || path.contains("/bin64/")) score += 10
// A launcher is a real entry point, so it stays a candidate, just not the preferred one.
if (GameIdentifier.isLauncherExeName(base)) score -= 40
if (GameIdentifier.isJunkPeName(base)) score -= 30
// Shallower is more likely the entry point; big binaries beat small helpers.
score -= depth * 8
score += (exe.length() / (8L * 1024 * 1024)).toInt().coerceAtMost(30)
return score
}
private fun skipDir(dir: File, relative: String): Boolean {
val name = dir.name.lowercase().trim()
if (name in SKIP_DIRS || SKIP_DIR_PREFIX.any { name.startsWith(it) }) return true
val rel = relative.lowercase()
return SKIP_PATHS.any { rel == it || rel.endsWith("/$it") }
}
private fun isLink(f: File): Boolean = runCatching { java.nio.file.Files.isSymbolicLink(f.toPath()) }.getOrDefault(false)
/** Comparison key: letters and digits only, so "GTA IV" and "gta-iv" match. */
private fun key(s: String) = s.lowercase().filter { it.isLetterOrDigit() }
}
@@ -0,0 +1,328 @@
package com.droiddeck.launcher.frontend
import java.io.File
/**
* Best-effort identification of a game from its on-disk footprint, given its .exe: a Steam appId
* and/or a display name, so an added game is not just named after its folder or exe. Pure
* filesystem and PE parsing, no network, never throws; it reports only what the disk tells.
*
* Signal chain (appId preferred; best name chosen across all hits):
* 1. steam_appid.txt → appId (Goldberg-style installs)
* 2. ColdClientLoader / emu ini → appId (AppId= key)
* 3. appmanifest_<id>.acf → appId + name (real Steam install under steamapps/)
* 4. goggame-<id>.info → name (+ gogId) (GOG installs)
* 5. PE VS_VERSIONINFO → name (ProductName / FileDescription)
* 6. cleaned folder / exe name → name (weak fallback)
*/
object GameIdentifier {
/** How far up the directory tree to look for marker files (games nest deep, e.g. Game/Binaries/Win64/x.exe). */
private const val MAX_PARENT_DEPTH = 6
enum class Source { STEAM_APPID_TXT, STEAM_MANIFEST_ACF, STEAM_EMU_INI, GOG_INFO, PE_VERSION, FILENAME, NONE }
enum class Confidence { HIGH, MEDIUM, LOW }
/**
* @param appId Steam appId if one was found on disk, else null.
* @param gogId GOG product id if a goggame info file was found, else null.
* @param name Best display name found locally; may be null when only an appId was
* found (caller resolves the name from the appId over the network).
* @param source Which signal produced the primary identity.
*/
data class GameIdentity(
val appId: Int? = null,
val gogId: String? = null,
val name: String? = null,
val source: Source = Source.NONE,
val confidence: Confidence = Confidence.LOW,
/** Which signal gave [name]: [Source.FILENAME] means only a cleaned folder or exe name. */
val nameSource: Source = Source.NONE,
) {
val hasStrongId: Boolean get() = appId != null
}
/** Identify the game owning [exeFile]. Never throws; returns an empty identity if nothing matched. */
fun identify(exeFile: File): GameIdentity {
val dirs = ancestorDirs(exeFile)
// Steam appId from a bare steam_appid.txt (in the exe dir, a steam_settings/ subdir, or an ancestor).
val steamAppId = dirs.firstNotNullOfOrNull { readSteamAppIdTxt(it) }
// AppId= out of a ColdClientLoader.ini / steam_emu.ini next to the game.
val emuAppId = dirs.firstNotNullOfOrNull { readEmuIniAppId(it) }
// Real Steam install: appmanifest_<id>.acf up under steamapps/ — carries both appId and name.
val acf = resolveSteamManifest(exeFile, dirs)
// GOG: goggame-<id>.info JSON with the real title.
val gog = dirs.firstNotNullOfOrNull { readGogInfo(it) }
// PE ProductName / FileDescription — but not when it merely names a launcher/loader
// ("Rockstar Games Launcher Redirector", "GSE", …), which must not become the game name.
val peName = PeVersionInfo.bestName(PeVersionInfo.read(exeFile))?.takeUnless { isJunkPeName(it) }
val appId = acf?.appId ?: steamAppId ?: emuAppId
// Best name, most-trustworthy first.
val nameHit: Pair<String, Source>? = when {
acf?.name != null -> acf.name to Source.STEAM_MANIFEST_ACF
gog?.name != null -> gog.name to Source.GOG_INFO
peName != null -> peName to Source.PE_VERSION
else -> cleanedFallbackName(exeFile)?.let { it to Source.FILENAME }
}
// Primary source = whatever gave us the appId (strongest), else the name source.
val primary: Source = when {
acf?.appId != null -> Source.STEAM_MANIFEST_ACF
steamAppId != null -> Source.STEAM_APPID_TXT
emuAppId != null -> Source.STEAM_EMU_INI
else -> nameHit?.second ?: Source.NONE
}
val confidence = when {
appId != null -> Confidence.HIGH
nameHit?.second == Source.GOG_INFO -> Confidence.HIGH
nameHit?.second == Source.PE_VERSION -> Confidence.MEDIUM
else -> Confidence.LOW
}
return GameIdentity(
appId = appId,
gogId = gog?.id,
name = nameHit?.first?.let(::normalizeName)?.takeIf { it.isNotBlank() },
source = primary,
confidence = confidence,
nameSource = nameHit?.second ?: Source.NONE,
)
}
/**
* Make an identified title readable and filesystem-safe (a Steam shortcut's name also names
* files): "DARK SOULS: REMASTERED" becomes "DARK SOULS - REMASTERED". Strips trademark marks,
* turns title punctuation into safe equivalents, and collapses whitespace.
*/
fun normalizeName(raw: String): String {
var s = raw
s = s.replace("™", "").replace("®", "").replace("©", "")
s = s.replace(Regex("""(?i)\(\s*(tm|r|c)\s*\)"""), "") // "(TM)" / "(R)" / "(C)"
s = s.replace(":", " - ") // colon → dash separator (safe + readable)
s = s.replace(Regex("""[\\/]"""), " ") // path separators → space
s = s.replace(Regex("""["*?<>|]"""), "") // other illegal chars → drop
// Drop trailing generic descriptors a PE FileDescription tacks on ("DiRT 3 Executable" → "DiRT 3").
s = s.replace(Regex("""(?i)[ \-]+(executable|application|launcher|redistributable|installer|setup)$"""), "")
s = s.replace(Regex("""\s+"""), " ").trim() // collapse whitespace
return s.trim(' ', '-').trim() // tidy stray leading/trailing dashes
}
// ── directory walk ──
/** The exe's directory plus its ancestors, nearest-first, bounded by [MAX_PARENT_DEPTH]. */
private fun ancestorDirs(exeFile: File): List<File> {
val out = ArrayList<File>(MAX_PARENT_DEPTH + 1)
var d: File? = exeFile.absoluteFile.parentFile
var depth = 0
while (d != null && depth <= MAX_PARENT_DEPTH) {
out.add(d)
d = d.parentFile
depth++
}
return out
}
// ── signal readers (all best-effort; return null on anything unexpected) ──
/** steam_appid.txt directly in [dir] or in a steam_settings/ subdir. */
private fun readSteamAppIdTxt(dir: File): Int? {
for (candidate in arrayOf(File(dir, "steam_appid.txt"), File(dir, "steam_settings/steam_appid.txt"))) {
// Strip a leading UTF-8 BOM (trim() doesn't) before reading the digits.
val id = readSmallTextFile(candidate)?.removePrefix("\uFEFF")?.trim()
?.takeWhile { it.isDigit() }?.toIntOrNull()
if (id != null && id > 0) return id
}
return null
}
/**
* First `AppId=<n>` in a crack/emu config .ini next to the game (ColdClientLoader, steam_emu,
* flt, hlm, …). Known names are tried first, then any other `.ini` in the dir — only crack
* configs carry an `AppId=` key, game settings .ini files (settings.ini, graphics.ini) don't,
* so the broad scan is safe.
*/
private fun readEmuIniAppId(dir: File): Int? {
val re = Regex("""(?im)^\s*appid\s*=\s*(\d+)""")
val named = arrayOf(
"ColdClientLoader.ini", "steam_emu.ini", "flt.ini", "hlm.ini",
"valve.ini", "cream_api.ini", "SmartSteamEmu.ini", "GreenLuma.ini",
)
val seen = HashSet<String>()
val candidates = ArrayList<File>()
for (n in named) File(dir, n).let { if (it.isFile) { candidates.add(it); seen.add(n.lowercase()) } }
(dir.listFiles { f -> f.isFile && f.name.endsWith(".ini", ignoreCase = true) && f.name.lowercase() !in seen }
?: emptyArray()).sortedBy { it.name }.forEach { candidates.add(it) }
for (f in candidates) {
val text = readSmallTextFile(f) ?: continue
val id = re.find(text)?.groupValues?.getOrNull(1)?.toIntOrNull()
if (id != null && id > 0) return id
}
return null
}
private data class Acf(val appId: Int?, val name: String?)
/**
* Resolve the Steam appmanifest for this game: find the `common` ancestor on the exe's
* path, read the sibling `steamapps/appmanifest_*.acf`, and match by installdir == the
* game folder under common. No match, no manifest: a folder in steamapps/common that no
* manifest claims is exactly the kind added games list, and the library's one other game is
* not its name.
*/
private fun resolveSteamManifest(exeFile: File, dirs: List<File>): Acf? {
val commonIdx = dirs.indexOfFirst { it.name.equals("common", ignoreCase = true) }
if (commonIdx < 0) return null
val commonDir = dirs[commonIdx]
val steamapps = commonDir.parentFile ?: return null
val manifests = steamapps.listFiles { f ->
f.isFile && f.name.startsWith("appmanifest_") && f.name.endsWith(".acf")
} ?: return null
if (manifests.isEmpty()) return null
// The game's install folder is the child of `common` on our descent path.
val gameFolder = if (commonIdx > 0) dirs[commonIdx - 1].name else null
val match = manifests.firstOrNull { m ->
val text = readSmallTextFile(m) ?: return@firstOrNull false
val installdir = vdfValue(text, "installdir")
gameFolder != null && installdir != null && installdir.equals(gameFolder, ignoreCase = true)
} ?: return null
val text = readSmallTextFile(match) ?: return null
val appId = vdfValue(text, "appid")?.toIntOrNull()?.takeIf { it > 0 }
val name = vdfValue(text, "name")?.takeIf { it.isNotBlank() }
return if (appId == null && name == null) null else Acf(appId, name)
}
private data class Gog(val id: String?, val name: String?)
/** goggame-<id>.info JSON: pull `name` (and the id from the filename). */
private fun readGogInfo(dir: File): Gog? {
val files = dir.listFiles { f ->
f.isFile && f.name.startsWith("goggame-") && f.name.endsWith(".info")
} ?: return null
for (f in files) {
val text = readSmallTextFile(f) ?: continue
val name = jsonStringValue(text, "name")?.takeIf { it.isNotBlank() } ?: continue
val id = f.name.removePrefix("goggame-").removeSuffix(".info").takeIf { it.isNotBlank() }
return Gog(id, name)
}
return null
}
// ── filename fallback ──
private val REPACK_TOKENS = setOf(
"fitgirl", "dodi", "codex", "plaza", "skidrow", "rune", "empress", "flt", "tenoke",
"reloaded", "elamigos", "razor1911", "hoodlum", "gog", "repack", "multi", "goldberg",
// repack/site tags that show up in folder names
"ankergames", "steamrip", "onlinefix", "online-fix", "gload", "fitgirlrepacks",
)
private const val EXE_NOISE_WORDS =
"""win64|win32|shipping|wingdk|client|launcher|game|x64|x86|64bit|32bit"""
/**
* Does this exe basename look like engine/arch boilerplate rather than a title? Deliberately
* UNANCHORED — "GameConTest" is boilerplate-ish wherever the giveaway sits, and the answer
* decides whether we trust the folder name instead of the exe name.
*/
private val EXE_NOISE_RE = Regex("""(?i)[-_. ]*(?:$EXE_NOISE_WORDS)""")
/**
* Trailing noise to strip off a title. ANCHORED to the end and allowed to repeat, because these
* words are only junk as a suffix: "Witcher3-Win64-Shipping" -> "Witcher3", while
* "Game of Thrones" and "Client Simulator" must survive intact.
*
* Kept separate from [EXE_NOISE_RE] on purpose. One regex used to serve both jobs, so
* anchoring it to fix stripping ALSO narrowed the boilerplate test — and a game in
* "Game Controller Test/GameConTest.exe" stopped preferring its folder and became "GameConTest".
*/
private val EXE_SUFFIX_RE = Regex("""(?i)(?:[-_. ]*(?:$EXE_NOISE_WORDS))+$""")
private val VERSION_TOKEN_RE = Regex("""(?i)\b(v?\d+([._]\d+)+|build[-_ ]?\d+|update[-_ ]?\d+)\b""")
/**
* True when an exe basename is a launcher/loader rather than the game — its parent folder is the
* better title. Catches "PlayGTAV"/"Play - GTA IV"/"LaunchGame"/"MyLauncher"/"GSE" but NOT a real
* title that merely starts with those letters ("PlayerUnknown"). A "play|launch|start|run" prefix
* counts only when it's a whole token — followed by a separator or a camelCase uppercase boundary,
* not another lowercase letter (checked case-sensitively, so it survives the case-insensitive JUNK
* matching used elsewhere).
*/
/** True when an exe basename looks like a launcher/loader rather than the game itself. */
fun isLauncherExeName(base: String): Boolean {
val lower = base.lowercase()
if (lower == "gse" || lower.endsWith("launcher") || lower.endsWith("redirector")) return true
for (p in arrayOf("play", "launch", "start", "run")) {
if (!lower.startsWith(p)) continue
val rest = base.substring(p.length)
if (rest.isEmpty()) return true // exactly "Play"
val c = rest[0]
if (!c.isLetterOrDigit() || c.isUpperCase()) return true // "Play - GTA IV" / camelCase "PlayGTAV"
// lowercase continuation ("Player…") → part of a longer word, not a launcher
}
return false
}
/** A PE ProductName/FileDescription that describes a launcher/loader, not the game — reject it so it
* doesn't become the shortcut name (e.g. "Rockstar Games Launcher Redirector", "GSE", "Steam"). */
private val JUNK_NAME_RE = Regex(
"""(?i)^(gse|steam|steam client|goldberg.*|launcher|game|play|start|setup|.* launcher.*|.*launcher redirector|.* redirector|rockstar games launcher.*|epic games launcher|smartsteamemu|coldclient.*|steamemu.*)$"""
)
/** True when a PE name is a launcher/loader label rather than a real game title. */
fun isJunkPeName(name: String): Boolean {
val n = name.trim()
return n.isEmpty() || JUNK_NAME_RE.matches(n)
}
/**
* Prefer the game's install-folder name (usually the real title) over the exe basename when the
* exe is a UE-style shipping binary OR a launcher/loader; then strip repack/suffix noise.
*/
private fun cleanedFallbackName(exeFile: File): String? {
val exeBase = exeFile.nameWithoutExtension
val preferFolder = EXE_NOISE_RE.containsMatchIn(exeBase) ||
isLauncherExeName(exeBase) ||
exeBase.equals("game", true) || exeBase.equals("start", true)
val folder = exeFile.absoluteFile.parentFile?.name
val raw = if (preferFolder && !folder.isNullOrBlank()) folder else exeBase
return cleanName(raw)
}
/** Strip bracketed tags, repack-group names, engine/arch suffixes and version tokens; tidy separators. */
private fun cleanName(raw: String): String? {
var s = raw
s = s.replace(Regex("""[\[(][^\])]*[\])]"""), " ") // (…) […]
s = VERSION_TOKEN_RE.replace(s, " ")
s = EXE_SUFFIX_RE.replace(s, " ")
s = s.replace(Regex("""[._]+"""), " ")
// Drop standalone repack-group words.
s = s.split(Regex("""[\s-]+"""))
.filter { it.isNotBlank() && it.lowercase() !in REPACK_TOKENS }
.joinToString(" ")
s = s.trim()
return s.ifBlank { null }
}
// ── tiny text/format helpers (regex-based → no Android/org.json dependency, unit-testable) ──
/** Read a small text file (guards against accidentally slurping a huge file). */
private fun readSmallTextFile(f: File, maxBytes: Long = 1L * 1024 * 1024): String? = try {
if (f.isFile && f.length() in 1..maxBytes) f.readText(Charsets.UTF_8) else null
} catch (_: Throwable) {
null
}
/** Value of a Valve KeyValues (.acf/.vdf) `"key" "value"` pair, first match, case-insensitive key. */
private fun vdfValue(text: String, key: String): String? =
Regex(""""${Regex.escape(key)}"\s*"([^"]*)"""", RegexOption.IGNORE_CASE).find(text)?.groupValues?.getOrNull(1)?.trim()
/** Value of a JSON `"key": "value"` pair, first match. Sufficient for the flat goggame .info files. */
private fun jsonStringValue(text: String, key: String): String? =
Regex(""""${Regex.escape(key)}"\s*:\s*"([^"\\]*(?:\\.[^"\\]*)*)"""").find(text)
?.groupValues?.getOrNull(1)?.replace("\\\"", "\"")?.replace("\\\\", "\\")?.trim()
}
@@ -152,21 +152,24 @@ object Library {
}
/** The same installed-game inventory used for links, shortcuts and file exports. */
fun launchableGames(context: Context, strictRead: Boolean = false): List<SteamGame> {
/** [added]: the added games when the caller has just scanned them, so they are not scanned again. */
fun launchableGames(context: Context, strictRead: Boolean = false, added: List<AddedGames.Game>? = null): List<SteamGame> {
val roots = steamLibraries(context).map { it.first }
return (steamGames(context, strictRead) + AddedGames.scan(context).map { g ->
AddedGameArt.resolve(context, g).let { art ->
SteamGame(
g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, ADDED, g.gameId,
hero = art.hero ?: art.header, gameFiles = g.folder,
protonPrefix = protonPrefix(context, g.steamAppId?.toLong() ?: g.appId, libraries = roots),
icon = art.icon?.takeIf { it.extension.lowercase() != "ico" },
source = g.source, storeId = g.storeId,
)
}
}).distinctBy { it.gameId }
return (steamGames(context, strictRead) + (added ?: AddedGames.scan(context)).map { g -> addedGame(context, g, roots) }).distinctBy { it.gameId }
}
/** One added game as the Games tab lists it; [roots] the Steam libraries, for its Proton prefix. */
fun addedGame(context: Context, g: AddedGames.Game, roots: List<File> = steamLibraries(context).map { it.first }): SteamGame =
AddedGameArt.resolve(context, g).let { art ->
SteamGame(
g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, ADDED, g.gameId,
hero = art.hero ?: art.header, gameFiles = g.folder,
protonPrefix = protonPrefix(context, g.steamAppId?.toLong() ?: g.appId, libraries = roots),
icon = art.icon?.takeIf { it.extension.lowercase() != "ico" },
source = g.source, storeId = g.storeId,
)
}
/** Steam stores current library art inside hash-named folders under the app's cache dir. */
private fun steamCacheImage(cache: File, appId: Int, names: List<String>): File? {
val appDir = File(cache, appId.toString())
@@ -0,0 +1,250 @@
package com.droiddeck.launcher.frontend
import java.io.File
import java.io.RandomAccessFile
/**
* Reads the StringFileInfo strings (ProductName, FileDescription, …) out of the
* VS_VERSION_INFO resource embedded in a Windows PE executable (.exe).
*
* Walks the PE resource directory to the first RT_VERSION resource — the same
* navigation [com.droiddeck.launcher.files.PeIconExtractor] uses for icons — then parses the alignment-heavy
* VS_VERSIONINFO → StringFileInfo → StringTable → String tree by hand.
*
* Everything is best-effort: any malformed / oversized / unsupported input returns
* null (or an empty map). No allocation beyond the single resource blob.
*/
object PeVersionInfo {
private const val RT_VERSION = 16
private const val MAX_RES_SECTION = 64 * 1024 * 1024 // don't slurp absurd resource sections
/**
* Returns the StringFileInfo key→value map (e.g. `"ProductName" -> "Palworld"`),
* or null if the file has no readable version resource. Keys are the raw
* VS_VERSIONINFO names; look up [productName]/[fileDescription] for the common ones.
*/
fun read(file: File): Map<String, String>? = try {
RandomAccessFile(file, "r").use { raf ->
val blob = versionResourceBytes(raf) ?: return@use null
parseStringFileInfo(blob).takeIf { it.isNotEmpty() }
}
} catch (_: Throwable) {
null
}
/**
* Best display name from a version map. ProductName is usually the cleanest title, but is
* sometimes an internal abbreviation (e.g. God of War ships ProductName "GoW" while
* FileDescription is "God of War"). When ProductName is a single spaceless token and
* FileDescription is a normal multi-word title, prefer FileDescription. Trimmed; null if
* neither is meaningful.
*/
fun bestName(map: Map<String, String>?): String? {
if (map == null) return null
val product = map["ProductName"]?.trim()?.takeIf { it.isNotEmpty() }
val desc = map["FileDescription"]?.trim()?.takeIf { it.isNotEmpty() }
if (product != null && desc != null &&
!product.contains(' ') && desc.contains(' ') && desc.length <= 60
) {
return desc
}
return product ?: desc
}
// ── locate the RT_VERSION resource blob (mirrors PeIconExtractor's navigation) ──
private fun versionResourceBytes(raf: RandomAccessFile): ByteArray? {
val dos = read(raf, 0, 0x40) ?: return null
if (u8(dos, 0) != 0x4D || u8(dos, 1) != 0x5A) return null // "MZ"
val peOff = u32(dos, 0x3C).toInt()
val coff = read(raf, peOff.toLong(), 24) ?: return null
if (u8(coff, 0) != 0x50 || u8(coff, 1) != 0x45 || u8(coff, 2) != 0 || u8(coff, 3) != 0) return null // "PE\0\0"
val numSections = u16(coff, 6)
val sizeOpt = u16(coff, 20)
if (numSections <= 0 || numSections > 96 || sizeOpt <= 0) return null
val optOff = peOff + 24L
val opt = read(raf, optOff, sizeOpt) ?: return null
val magic = u16(opt, 0)
val ddOff = if (magic == 0x20B) 112 else 96 // PE32+ vs PE32 data-directory offset
val resDirEntry = ddOff + 2 * 8 // data directory index 2 = resource table
if (resDirEntry + 8 > opt.size) return null
val resRVA = u32(opt, resDirEntry).toInt()
val resSize = u32(opt, resDirEntry + 4).toInt()
if (resRVA == 0 || resSize == 0) return null
val secTabOff = optOff + sizeOpt
val secTab = read(raf, secTabOff, numSections * 40) ?: return null
var secVA = 0
var secPtr = 0L
var secRaw = 0
var found = false
for (i in 0 until numSections) {
val o = i * 40
if (o + 40 > secTab.size) break
val va = u32(secTab, o + 12).toInt()
val vSize = u32(secTab, o + 8).toInt()
val raw = u32(secTab, o + 16).toInt()
val pRaw = u32(secTab, o + 20)
val span = maxOf(vSize, raw)
if (resRVA >= va && resRVA < va + span) {
secVA = va; secPtr = pRaw; secRaw = raw; found = true; break
}
}
if (!found || secRaw <= 0 || secRaw > MAX_RES_SECTION) return null
val res = read(raf, secPtr, secRaw) ?: return null
val resDirStart = resRVA - secVA
if (resDirStart < 0 || resDirStart + 16 > res.size) return null
val verTypeDir = findIdSubdir(res, resDirStart, RT_VERSION, resDirStart) ?: return null
val verData = firstDataEntry(res, verTypeDir, resDirStart) ?: return null
return dataEntryBytes(res, verData, secVA)
}
/** Resolve the sub-directory under [dirIdx] whose id matches [wantId]; null if absent or not a directory. */
private fun findIdSubdir(res: ByteArray, dirIdx: Int, wantId: Int, resDirStart: Int): Int? {
if (dirIdx + 16 > res.size) return null
val total = u16(res, dirIdx + 12) + u16(res, dirIdx + 14)
val start = dirIdx + 16
for (i in 0 until total) {
val e = start + i * 8
if (e + 8 > res.size) break
val id = u32(res, e)
val off = u32(res, e + 4)
if (id and 0x80000000L == 0L && id.toInt() == wantId) {
if (off and 0x80000000L != 0L) return resDirStart + (off and 0x7FFFFFFFL).toInt()
return null
}
}
return null
}
/** Descend the first entry of each level until an IMAGE_RESOURCE_DATA_ENTRY; returns its index. */
private fun firstDataEntry(res: ByteArray, dirIdx: Int, resDirStart: Int): Int? {
if (dirIdx + 16 > res.size) return null
if (u16(res, dirIdx + 12) + u16(res, dirIdx + 14) == 0) return null
val e = dirIdx + 16
if (e + 8 > res.size) return null
val off = u32(res, e + 4)
return if (off and 0x80000000L != 0L) {
firstDataEntry(res, resDirStart + (off and 0x7FFFFFFFL).toInt(), resDirStart)
} else {
resDirStart + off.toInt()
}
}
/** Read the bytes an IMAGE_RESOURCE_DATA_ENTRY points at (its OffsetToData is an RVA). */
private fun dataEntryBytes(res: ByteArray, entryIdx: Int, secVA: Int): ByteArray? {
if (entryIdx < 0 || entryIdx + 8 > res.size) return null
val rva = u32(res, entryIdx).toInt()
val size = u32(res, entryIdx + 4).toInt()
val start = rva - secVA
if (size <= 0 || start < 0 || start + size > res.size) return null
return res.copyOfRange(start, start + size)
}
// ── VS_VERSIONINFO tree parse ──
//
// Every node is: WORD wLength, WORD wValueLength, WORD wType, WCHAR szKey[],
// then (32-bit aligned) an optional Value, then (32-bit aligned) child nodes.
// We only care about: VS_VERSIONINFO → StringFileInfo → StringTable → String.
private fun parseStringFileInfo(b: ByteArray): Map<String, String> {
val out = LinkedHashMap<String, String>()
if (b.size < 6) return out
val rootLen = minOf(u16(b, 0), b.size)
// VS_VERSION_INFO header: skip szKey "VS_VERSION_INFO" then the FIXEDFILEINFO value.
val rootValLen = u16(b, 2)
var pos = align4(6 + (utf16zLen(b, 6) + 1) * 2)
pos = align4(pos + rootValLen)
while (pos + 6 <= rootLen) {
val childLen = u16(b, pos)
if (childLen < 6 || pos + childLen > b.size) break
val key = utf16z(b, pos + 6)
if (key == "StringFileInfo") parseTables(b, pos, pos + childLen, out)
pos = align4(pos + childLen)
if (childLen == 0) break
}
return out
}
/** Iterate the StringTable children inside a StringFileInfo block [start, end). */
private fun parseTables(b: ByteArray, start: Int, end: Int, out: MutableMap<String, String>) {
var p = align4(start + 6 + (utf16zLen(b, start + 6) + 1) * 2)
while (p + 6 <= end) {
val tableLen = u16(b, p)
if (tableLen < 6 || p + tableLen > end) break
parseStrings(b, p, minOf(p + tableLen, end), out)
p = align4(p + tableLen)
if (tableLen == 0) break
}
}
/** Iterate the String children inside a StringTable block [start, end). */
private fun parseStrings(b: ByteArray, start: Int, end: Int, out: MutableMap<String, String>) {
var q = align4(start + 6 + (utf16zLen(b, start + 6) + 1) * 2)
while (q + 6 <= end) {
val strLen = u16(b, q)
if (strLen < 6 || q + strLen > end) break
val key = utf16z(b, q + 6)
val valOff = align4(q + 6 + (key.length + 1) * 2)
if (key.isNotEmpty() && valOff < q + strLen) {
val value = utf16z(b, valOff, q + strLen).trim()
if (value.isNotEmpty()) out[key] = value
}
q = align4(q + strLen)
if (strLen == 0) break
}
}
// ── little-endian / UTF-16 readers ──
private fun align4(x: Int): Int = (x + 3) and 3.inv()
/** Number of UTF-16 code units before the null terminator starting at [off]. */
private fun utf16zLen(b: ByteArray, off: Int): Int {
var i = off
while (i + 1 < b.size) {
if (b[i].toInt() == 0 && b[i + 1].toInt() == 0) break
i += 2
}
return (i - off) / 2
}
/** Read a null-terminated UTF-16LE string starting at [off], not reading past [limit]. */
private fun utf16z(b: ByteArray, off: Int, limit: Int = b.size): String {
val sb = StringBuilder()
var i = off
val end = minOf(limit, b.size)
while (i + 1 < end) {
val c = u8(b, i) or (u8(b, i + 1) shl 8)
if (c == 0) break
sb.append(c.toChar())
i += 2
}
return sb.toString()
}
private fun u8(b: ByteArray, off: Int): Int = if (off < 0 || off >= b.size) 0 else b[off].toInt() and 0xFF
private fun u16(b: ByteArray, off: Int): Int = u8(b, off) or (u8(b, off + 1) shl 8)
private fun u32(b: ByteArray, off: Int): Long =
u8(b, off).toLong() or (u8(b, off + 1).toLong() shl 8) or
(u8(b, off + 2).toLong() shl 16) or (u8(b, off + 3).toLong() shl 24)
private fun read(raf: RandomAccessFile, pos: Long, len: Int): ByteArray? {
if (len <= 0 || pos < 0) return null
val fileLen = raf.length()
if (pos >= fileLen) return null
val n = minOf(len.toLong(), fileLen - pos).toInt()
if (n <= 0) return null
val buf = ByteArray(n)
raf.seek(pos)
raf.readFully(buf)
return buf
}
}
@@ -0,0 +1,160 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import android.util.Log
import androidx.annotation.VisibleForTesting
import com.droiddeck.launcher.stores.CredentialCipher
import org.json.JSONArray
import org.json.JSONObject
import java.io.File
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
/**
* SteamGridDB, the art source after Steam's store: a game by its Steam appid, else by a search
* whose result must carry the same name, then its best-rated grids, heroes, logos and icons.
*
* The API key: the user's own (Steam settings › Games), sealed with [CredentialCipher] in the
* app's files, else the one the build carries (`BuildConfig.SGDB_API_KEY`, from a CI secret), else
* none, and then this step is skipped. The key travels only in the Authorization header and is
* never logged.
*/
object SteamGridDb {
private const val TAG = "SteamGridDb"
private const val API = "https://www.steamgriddb.com/api/v2"
private const val QUERY = "nsfw=false&humor=false"
@VisibleForTesting
@Volatile
internal var keys: CredentialCipher.KeyProvider = CredentialCipher.Keystore
private fun keyFile(context: Context) = File(context.filesDir, "sgdb/key.json")
/** The key the build carries, or "" (a build without the secret, a fork's PR build). */
fun builtInKey(): String = runCatching {
Class.forName("com.droiddeck.launcher.BuildConfig").getField("SGDB_API_KEY").get(null) as? String
}.getOrNull().orEmpty()
/** The user's key wins, then the build's; "" when there is neither. */
fun pick(user: String, builtIn: String): String = user.trim().ifEmpty { builtIn.trim() }
fun key(context: Context): String = pick(userKey(context), builtInKey())
/** The key the user entered, or "". */
@Synchronized
fun userKey(context: Context): String {
val f = keyFile(context)
if (!f.isFile) return ""
return try {
val json = JSONObject(f.readText())
if (CredentialCipher.isEnvelope(json)) CredentialCipher.open(json, keys) else json.optString("key")
} catch (e: Exception) {
if (CredentialCipher.isPermanent(e)) f.delete()
Log.w(TAG, "the saved key cannot be read (${e.javaClass.simpleName})")
""
}
}
/** Saves the user's key sealed (plain only where the Keystore does not work); "" clears it. */
@Synchronized
fun setUserKey(context: Context, key: String) {
val f = keyFile(context)
val value = key.trim()
if (value.isEmpty()) { f.delete(); return }
f.parentFile?.mkdirs()
val text = try {
CredentialCipher.seal(value, keys).toString()
} catch (e: Exception) {
Log.w(TAG, "keystore unavailable, the key stays plain (${e.javaClass.simpleName})")
JSONObject().put("key", value).toString()
}
val tmp = File(f.path + ".tmp")
tmp.writeText(text)
tmp.setReadable(false, false); tmp.setReadable(true, true)
if (!tmp.renameTo(f)) { f.delete(); tmp.renameTo(f) }
}
/** The SteamGridDB game id for [steamAppId], else for a search on [name] that returns the same name; null when neither. */
fun gameId(key: String, steamAppId: Int?, name: String): Int? {
if (steamAppId != null) {
json(key, "$API/games/steam/$steamAppId")?.optJSONObject("data")?.optInt("id")?.takeIf { it > 0 }?.let { return it }
}
val term = URLEncoder.encode(name, "UTF-8").replace("+", "%20")
val results = json(key, "$API/search/autocomplete/$term")?.optJSONArray("data") ?: return null
return match(name, (0 until results.length()).map { results.getJSONObject(it) }.map { it.optInt("id") to it.optString("name") })
}
/** The id of the first result whose name matches [name] ([AddedGameArt.nameMatch]); no blind first pick. */
internal fun match(name: String, results: List<Pair<Int, String>>): Int? =
results.map { (id, got) -> id to AddedGameArt.nameMatch(name, got) }
.filter { it.second > 0 && it.first > 0 }
.maxByOrNull { it.second }?.first
/**
* Fetches what is missing into [cache] under the names Steam's art uses there (p.jpg,
* header.jpg, hero.jpg, logo.png) and the icon as icon-sgdb.png. True when anything arrived.
*/
fun download(key: String, id: Int, cache: File): Boolean {
var got = false
for ((path, local) in listOf(
"grids/game/$id?dimensions=600x900&$QUERY" to "p.jpg",
"grids/game/$id?dimensions=460x215,920x430&$QUERY" to "header.jpg",
"heroes/game/$id?$QUERY" to "hero.jpg",
"logos/game/$id?$QUERY" to "logo.png",
"icons/game/$id?$QUERY" to "icon-sgdb.png",
)) {
val dst = File(cache, local)
if (dst.isFile) continue
val items = json(key, "$API/$path")?.optJSONArray("data") ?: continue
val url = best(items, local.endsWith(".png")) ?: continue
val bytes = AddedGameArt.get(url) ?: continue
val tmp = File(cache, "$local.tmp")
tmp.writeBytes(bytes)
if (tmp.renameTo(dst)) { got = true; File(cache, "$local.src").writeText(AddedGameArt.SGDB) }
}
return got
}
/** The best-scored [limit] images for [slot] of game [id], as (thumbnail, full image) URLs. */
fun images(key: String, id: Int, slot: AddedGameArt.Slot, limit: Int): List<Pair<String, String>> {
val path = when (slot) {
AddedGameArt.Slot.COVER -> "grids/game/$id?dimensions=600x900&$QUERY"
AddedGameArt.Slot.BACKGROUND -> "heroes/game/$id?$QUERY"
AddedGameArt.Slot.LOGO -> "logos/game/$id?$QUERY"
AddedGameArt.Slot.ICON -> "icons/game/$id?$QUERY"
}
val items = json(key, "$API/$path")?.optJSONArray("data") ?: return emptyList()
return ranked(items, pngOnly = slot == AddedGameArt.Slot.LOGO || slot == AddedGameArt.Slot.ICON).take(limit)
}
/** [items] best-scored first, as (thumbnail, full image) URLs; for a .png slot only PNGs. */
internal fun ranked(items: JSONArray, pngOnly: Boolean): List<Pair<String, String>> =
(0 until items.length()).map { items.getJSONObject(it) }
.filter { it.optString("url").startsWith("https://") && (!pngOnly || it.optString("mime") == "image/png" || it.optString("url").endsWith(".png", true)) }
.sortedByDescending { it.optInt("score", 0) }
.map { (it.optString("thumb").takeIf { t -> t.startsWith("https://") } ?: it.optString("url")) to it.optString("url") }
/** The highest-scored image's URL; for a .png slot only a PNG. */
internal fun best(items: JSONArray, pngOnly: Boolean): String? =
(0 until items.length()).map { items.getJSONObject(it) }
.filter { it.optString("url").startsWith("https://") && (!pngOnly || it.optString("mime") == "image/png" || it.optString("url").endsWith(".png", true)) }
.maxByOrNull { it.optInt("score", 0) }?.optString("url")
/** A GET with the key in its Authorization header; the body as JSON, or null. Logs the path only. */
private fun json(key: String, url: String): JSONObject? {
val c = URL(url).openConnection() as HttpURLConnection
c.connectTimeout = 10_000
c.readTimeout = 15_000
c.setRequestProperty("User-Agent", "DroidDeck-launcher")
c.setRequestProperty("Authorization", "Bearer $key")
return try {
if (c.responseCode != 200) { Log.w(TAG, "${URL(url).path}: HTTP ${c.responseCode}"); null }
else JSONObject(c.inputStream.use { it.readBytes() }.toString(Charsets.UTF_8)).takeIf { it.optBoolean("success", true) }
} catch (e: Exception) {
Log.w(TAG, "${URL(url).path}: ${e.javaClass.simpleName}"); null
} finally {
c.disconnect()
}
}
}
@@ -625,6 +625,60 @@ object SessionPrefs {
prefs(context).edit().putString("addedGamesDirs", dirs.distinct().joinToString("\n")).remove("addedGamesDir").apply()
}
/**
* Game folders (by path) the user removed from the added games: a scan skips them, so they
* stay off the Games tab and out of Steam until restored. Nothing on disk is touched.
*/
fun removedAddedGames(context: Context): List<String> =
(prefs(context).getString("removedAddedGames", "") ?: "").split('\n').filter { it.isNotEmpty() }
fun setAddedGameRemoved(context: Context, folderPath: String, removed: Boolean) {
synchronized(addedGameLock) {
val now = removedAddedGames(context).filter { it != folderPath } + listOfNotNull(folderPath.takeIf { removed })
prefs(context).edit().putString("removedAddedGames", now.joinToString("\n")).apply()
}
}
/** An added game's name as the user set it (in the app, or in Steam's Properties); "" = automatic. */
fun addedGameName(context: Context, folderPath: String): String = prefs(context).getString("addedName:$folderPath", "") ?: ""
fun setAddedGameName(context: Context, folderPath: String, name: String) {
prefs(context).edit().putString("addedName:$folderPath", name.trim()).apply()
}
/** An added game's Start in, as the session sees it; "" = the exe's own folder. */
fun addedGameStartIn(context: Context, folderPath: String): String = prefs(context).getString("addedStartIn:$folderPath", "") ?: ""
fun setAddedGameStartIn(context: Context, folderPath: String, guestDir: String) {
prefs(context).edit().putString("addedStartIn:$folderPath", guestDir.trim()).apply()
}
/** An added game's launch options, as Steam takes them ("-dx11", "VAR=1 %command%"). */
fun addedGameLaunch(context: Context, folderPath: String): String = prefs(context).getString("addedLaunch:$folderPath", "") ?: ""
fun setAddedGameLaunch(context: Context, folderPath: String, options: String) {
prefs(context).edit().putString("addedLaunch:$folderPath", options.trim()).apply()
}
/**
* The last value of [field] (AppName, StartDir, LaunchOptions) taken over from Steam's own
* Properties for this game, so the same Steam edit is not taken again over a later app edit.
*/
fun addedGameAdopted(context: Context, folderPath: String, field: String): String? =
prefs(context).getString("addedAdopted:$field:$folderPath", null)
fun setAddedGameAdopted(context: Context, folderPath: String, field: String, value: String) {
prefs(context).edit().putString("addedAdopted:$field:$folderPath", value).apply()
}
/** Where an added game's art for [slot] comes from when the user chose it ("folder", "steam", "sgdb", "file"); "" = automatic. */
fun addedGameArtSource(context: Context, folderPath: String, slot: String): String =
prefs(context).getString("addedArt:$slot:$folderPath", "") ?: ""
fun setAddedGameArtSource(context: Context, folderPath: String, slot: String, source: String) {
prefs(context).edit().putString("addedArt:$slot:$folderPath", source).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)
@@ -650,6 +704,10 @@ object SessionPrefs {
unchanged
}
/** The shortcut appid stored for the folder, or null before its first scan. */
fun addedGameStoredAppId(context: Context, folderPath: String): Long? =
prefs(context).getLong("addedAppId:$folderPath", 0L).takeIf { it != 0L }
fun addedGameAppId(context: Context, folderPath: String, first: Long): Long = synchronized(addedGameLock) {
val p = prefs(context)
p.getLong("addedAppId:$folderPath", 0L).takeIf { it != 0L }
@@ -36,9 +36,9 @@ object SteamLiveShortcuts {
private const val TAG_NAME = "droiddeck-app"
private const val COMPAT_TOOL = "droiddeck-proton-arm64"
/** Adds every store game in [games] the client does not list yet. Blocking; worker thread. */
fun sync(context: Context, games: List<AddedGames.Game>) {
val wanted = games.filter { it.source != Library.ADDED }
/** Adds every game in [games] that [include] takes (store games by default) and the client does not list yet. Blocking; worker thread. */
fun sync(context: Context, games: List<AddedGames.Game>, include: (AddedGames.Game) -> Boolean = { it.source != Library.ADDED }) {
val wanted = games.filter(include)
if (wanted.isEmpty() || !clientRunning()) return
val list = JSONArray()
for (g in wanted) list.put(JSONObject().put("name", g.name).put("exe", g.guestExe).put("dir", g.guestDir))
@@ -71,6 +71,47 @@ object SteamLiveShortcuts {
if (result != null) Log.i(TAG, "live shortcuts: removed $appId")
}
/**
* The running client's shortcut for [game] made to match it: name, target, Start in and
* launch options, on the same appid (an edit never adds a second shortcut). Blocking.
*/
fun update(context: Context, game: AddedGames.Game) {
if (!clientRunning()) return
val id = game.appId and 0xFFFFFFFFL
val js = """
(async () => {
const id = $id;
try { SteamClient.Apps.SetShortcutName(id, ${JSONObject.quote(game.name)}); } catch (e) {}
try { SteamClient.Apps.SetShortcutExe(id, ${JSONObject.quote("\"" + game.guestExe + "\"")}); } catch (e) {}
try { SteamClient.Apps.SetShortcutStartDir(id, ${JSONObject.quote("\"" + game.guestDir + "\"")}); } catch (e) {}
try { SteamClient.Apps.SetShortcutLaunchOptions(id, ${JSONObject.quote(game.launchOptions)}); } catch (e) {}
return 1;
})()
""".trimIndent()
if (evaluate(context, js) != null) Log.i(TAG, "live shortcuts: updated $id")
}
/**
* One piece of art for the running client's shortcut [appId]: [assetType] as the client numbers
* them (0 portrait capsule, 1 hero, 2 logo, 3 wide capsule), from [file]; null clears it. The
* icon goes by path ([iconPath]). Blocking.
*/
fun setArt(context: Context, appId: Long, assetType: Int?, file: java.io.File?, iconPath: String? = null) {
if (!clientRunning()) return
val id = appId and 0xFFFFFFFFL
val js = when {
iconPath != null -> "(async () => { try { SteamClient.Apps.SetShortcutIcon($id, ${JSONObject.quote(iconPath)}); } catch (e) {} return 1; })()"
assetType == null -> return
file == null -> "(async () => { try { await SteamClient.Apps.ClearCustomArtworkForApp($id, $assetType); } catch (e) {} return 1; })()"
else -> {
val data = runCatching { Base64.encodeToString(file.readBytes(), Base64.NO_WRAP) }.getOrNull() ?: return
val type = if (file.extension.equals("png", true)) "png" else "jpg"
"(async () => { try { await SteamClient.Apps.SetCustomArtworkForApp($id, ${JSONObject.quote(data)}, ${JSONObject.quote(type)}, $assetType); } catch (e) {} return 1; })()"
}
}
if (evaluate(context, js) != null) Log.i(TAG, "live shortcuts: art $assetType for $id")
}
private fun clientRunning(): Boolean = SessionState.running && SessionState.mode == SessionService.MODE_STEAM && !SessionState.stopRequested
/** `Runtime.evaluate` of [expression] in the client's SharedJSContext; the value as text, or null. */
@@ -64,7 +64,7 @@ object StoreInstalls {
try {
val games = AddedGames.scan(app)
AddedGames.writeListing(app, games)
LibraryCache.save(app, Library.launchableGames(app))
LibraryCache.save(app, Library.launchableGames(app, added = games))
SteamLiveShortcuts.sync(app, games)
} catch (e: Exception) {
Log.w(TAG, "registration: ${e.message}")
@@ -41,6 +41,7 @@ import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
@@ -313,12 +314,17 @@ internal fun rememberShown(onDismiss: () -> Unit): MutableTransitionState<Boolea
@Composable
internal fun AppDialog(
shown: MutableTransitionState<Boolean>, close: () -> Unit, label: String, wide: Boolean,
modifier: Modifier = Modifier, maxWidth: Dp? = null, content: @Composable ColumnScope.() -> Unit,
modifier: Modifier = Modifier, maxWidth: Dp? = null,
/** [width] fixed, else as wide as its content when [fitContent], else as wide as it may be. */
width: Dp? = null, fitContent: Boolean = false,
/** What B / Back does, when not [close] (a picker goes up a folder first). */
back: (() -> Unit)? = null,
content: @Composable ColumnScope.() -> Unit,
) {
val pal = LocalPalette.current
// The page's ring stays out of sight behind it.
VeilRing()
Dialog(onDismissRequest = close, properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) {
Dialog(onDismissRequest = back ?: close, properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false)) {
// The page's focus memory stays the page's: nothing in here is a place to come back to.
CompositionLocalProvider(LocalFrontFocus provides null) {
Box(
@@ -337,14 +343,20 @@ internal fun AppDialog(
modifier = Modifier
.padding(12.dp)
.widthIn(max = maxWidth ?: if (wide) 860.dp else 560.dp)
.fillMaxWidth()
.then(
when {
width != null -> Modifier.width(width)
fitContent -> Modifier.width(androidx.compose.foundation.layout.IntrinsicSize.Max)
else -> Modifier.fillMaxWidth()
},
)
.heightIn(max = (LocalConfiguration.current.screenHeightDp - 24).dp)
.shadow(24.dp, Shape16, ambientColor = Color.Black, spotColor = Color.Black)
.clip(Shape16)
.background(pal.surfaceVariant.copy(alpha = 0.97f))
.border(1.dp, pal.signal.copy(alpha = 0.22f), Shape16)
.clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {}
.controllerBack(close)
.controllerBack(back ?: close)
.then(modifier)
.verticalScroll(rememberScrollState())
.padding(horizontal = 18.dp, vertical = 16.dp),
@@ -0,0 +1,555 @@
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.layout.Arrangement
import androidx.compose.foundation.layout.Box
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.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
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.filled.Close
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.outlined.Image
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableIntStateOf
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.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.pluralStringResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
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.AddedGameArt
import com.droiddeck.launcher.frontend.AddedGameEdits
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.session.SessionPrefs
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
/** Each art slot's thumbnail, in its true shape: width, height, corner. */
private fun AddedGameArt.Slot.shape(): Triple<Dp, Dp, Dp> = when (this) {
AddedGameArt.Slot.COVER -> Triple(28.dp, 41.dp, 5.dp)
AddedGameArt.Slot.BACKGROUND -> Triple(60.dp, 34.dp, 5.dp)
AddedGameArt.Slot.LOGO -> Triple(60.dp, 26.dp, 5.dp)
AddedGameArt.Slot.ICON -> Triple(30.dp, 30.dp, 7.dp)
}
@Composable
private fun AddedGameArt.Slot.label(): String = stringResource(
when (this) {
AddedGameArt.Slot.COVER -> R.string.art_cover
AddedGameArt.Slot.BACKGROUND -> R.string.art_background
AddedGameArt.Slot.LOGO -> R.string.art_logo
AddedGameArt.Slot.ICON -> R.string.art_icon
},
)
@Composable
private fun artSourceLabel(source: String): String = stringResource(
when (source) {
AddedGameArt.FOLDER -> R.string.art_src_folder
AddedGameArt.STEAM -> R.string.art_src_steam
AddedGameArt.SGDB -> R.string.art_src_sgdb
AddedGameArt.FILE -> R.string.art_src_file
AddedGameArt.EXE -> R.string.art_src_exe
else -> R.string.art_src_auto
},
)
/** A thumbnail of [model] (a file or URL) in [slot]'s shape, scaled by [scale]. */
@Composable
private fun SlotThumb(slot: AddedGameArt.Slot, model: Any?, scale: Float = 1f, selected: Boolean = false) {
val pal = LocalPalette.current
val (w, h, r) = slot.shape()
val shape = RoundedCornerShape(r)
Box(
Modifier.size(w * scale, h * scale).clip(shape).background(MaterialTheme.colorScheme.surfaceVariant)
.border(if (selected) 2.dp else 1.dp, if (selected) pal.signal else pal.line, shape),
) {
if (model != null) AsyncImage(
model = model, contentDescription = null,
contentScale = if (slot == AddedGameArt.Slot.LOGO || slot == AddedGameArt.Slot.ICON) ContentScale.Fit else ContentScale.Crop,
modifier = Modifier.matchParentSize(),
)
}
}
/** A row of the editor: a label column, then the value. */
@Composable
private fun FieldRow(label: String, focus: FocusRequester? = null, onClick: () -> Unit, value: @Composable () -> Unit) {
ListRow(focus = focus, onClick = onClick) {
Text(label, fontSize = 14.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.width(110.dp))
Box(Modifier.weight(1f)) { value() }
}
}
/** Where the editor opens: its game's folder, straight on Target, and whether it came from the added-games summary. */
internal class EditRequest(val folder: String, val openTarget: Boolean, val fromSummary: Boolean, val preview: EditPreview)
/**
* What the editor shows on its first frame, from what the page already has (the game's row, or
* the summary's); the rest (the ranked exes, where each piece of art came from) follows.
* [exeName] / [startIn] null = not known yet.
*/
internal class EditPreview(
val name: String, val exeName: String?, val startIn: String?, val launchOptions: String,
val art: Map<AddedGameArt.Slot, File?>,
) {
companion object {
/** From the Games tab's row for [game] and the few preferences the edits keep. */
fun of(context: android.content.Context, game: com.droiddeck.launcher.frontend.Library.SteamGame, folder: String): EditPreview {
val exe = SessionPrefs.addedGameExe(context, folder).ifEmpty {
com.droiddeck.launcher.frontend.AddedExes.list(context).firstOrNull { it.folder == folder && it.picked }?.exe.orEmpty()
}.takeIf { it.isNotEmpty() }?.let { File(it) }
val startIn = SessionPrefs.addedGameStartIn(context, folder).takeIf { it.isNotEmpty() }?.substringAfterLast('/') ?: exe?.parentFile?.name
return EditPreview(
game.name, exe?.name, startIn, SessionPrefs.addedGameLaunch(context, folder),
mapOf(AddedGameArt.Slot.COVER to game.art, AddedGameArt.Slot.BACKGROUND to game.hero, AddedGameArt.Slot.ICON to game.icon),
)
}
/** From a summary row's game and its cover. */
fun of(game: AddedGames.Game, cover: File?) = EditPreview(
game.name, game.exe.name, game.guestDir.substringAfterLast('/'), game.launchOptions, mapOf(AddedGameArt.Slot.COVER to cover),
)
}
}
/** A small spinner where a value is still being read. */
@Composable
private fun Loading() {
androidx.compose.material3.CircularProgressIndicator(Modifier.size(14.dp), strokeWidth = 2.dp)
}
/**
* An added game's editor, Steam's non-Steam Properties in the app: Name, Target (the ranked exes,
* "?" where nothing clearly won, Other exe…), Start in, Launch options, the four pieces of art, and
* Remove (two presses; the files stay). Every change goes through the game's own Steam shortcut.
*/
@Composable
internal fun AddedGameEditor(
request: EditRequest, onBack: () -> Unit, onClose: () -> Unit, onChanged: () -> Unit,
/** Remove pressed twice: the game's folder, its shortcut appid when known, its name. */
onRemove: (folder: String, appId: Long?, name: String) -> Unit,
) {
val ctx = LocalContext.current
val app = ctx.applicationContext
val colors = MaterialTheme.colorScheme
val scope = rememberCoroutineScope()
val shown = rememberShown(onClose)
val close = { shown.targetState = false }
val folder = request.folder
var version by remember { mutableIntStateOf(0) }
var game by remember { mutableStateOf<AddedGames.Game?>(null) }
var arts by remember { mutableStateOf<List<AddedGameArt.SlotState>>(emptyList()) }
var ranked by remember { mutableStateOf<List<File>?>(null) }
var targetOpen by remember { mutableStateOf(request.openTarget) }
var armed by remember { mutableStateOf(false) }
var editing by remember { mutableStateOf<String?>(null) }
var otherExe by remember { mutableStateOf(false) }
var artSlot by remember { mutableStateOf<AddedGameArt.Slot?>(null) }
var unreachable by remember { mutableStateOf(false) }
LaunchedEffect(version) {
withContext(Dispatchers.IO) {
val g = AddedGameEdits.game(app, folder)
game = g
if (g != null) {
ranked = g.candidates.let { list -> if (list.any { it.path == g.exe.path }) list else listOf(g.exe) + list }
arts = AddedGameArt.describe(app, g)
}
}
}
LaunchedEffect(armed) { if (armed) { kotlinx.coroutines.delay(4_000); armed = false } }
val change: (() -> Unit) -> Unit = { work ->
scope.launch {
withContext(Dispatchers.IO) { work() }
version++
onChanged()
}
}
val first = remember { FocusRequester() }
LaunchedEffect(Unit) { focusWithinFrames({ false }) { first } }
val preview = request.preview
AppDialog(shown, close, "gameEditor", wide = false, maxWidth = 460.dp) {
val g = game
val name = g?.name ?: preview.name
DialogTitleRow(
name, onClose = close,
leading = if (request.fromSummary) ({ SmallIconButton(Icons.AutoMirrored.Filled.ArrowBack, stringResource(R.string.common_back), colors.onBackground) { onBack(); close() } }) else null,
)
val maxHeight = (LocalConfiguration.current.screenHeightDp * 0.72f).dp
Column(
verticalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.fillMaxWidth().heightIn(max = maxHeight).verticalScroll(rememberScrollState()),
) {
FieldRow(stringResource(R.string.edit_name), focus = first, onClick = { editing = "name" }) { ValueText(name) }
FieldRow(stringResource(R.string.edit_target), onClick = { targetOpen = !targetOpen }) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
val exeName = g?.exe?.name ?: preview.exeName
Box(Modifier.weight(1f)) { if (exeName != null) ValueText(exeName) else Loading() }
if (g == null && exeName != null) Loading()
if (g?.exeUncertain == true) UncertainMark(stringResource(R.string.mode_added_exe_check))
}
}
if (targetOpen) {
Column(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.padding(start = 16.dp)) {
val list = ranked
if (g == null || list == null) Box(Modifier.padding(8.dp)) { Loading() }
else for (exe in list) key(exe.path) {
val rel = exe.relativeToOrSelf(g.folder).invariantSeparatorsPath
PickerRow(null, exe.name, rel.substringBeforeLast('/', "").ifEmpty { null }, accent = exe.path == g.exe.path) {
targetOpen = false
change { AddedGameEdits.setExe(app, folder, exe) }
}
}
PickerRow(null, stringResource(R.string.edit_other_exe), null, enabled = g != null) { otherExe = true }
}
}
FieldRow(stringResource(R.string.edit_start_in), onClick = { if (g != null) editing = "start" }) {
val startIn = g?.guestDir?.substringAfterLast('/') ?: preview.startIn
if (startIn != null) ValueText(startIn) else Loading()
}
val launch = g?.launchOptions ?: preview.launchOptions
FieldRow(stringResource(R.string.edit_launch_options), onClick = { editing = "launch" }) { ValueText(launch.ifEmpty { "—" }, muted = launch.isEmpty()) }
Text(stringResource(R.string.edit_artwork), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 4.dp, top = 8.dp))
for (slot in AddedGameArt.Slot.values()) key(slot) {
val state = arts.firstOrNull { it.slot == slot }
FieldRow(slot.label(), onClick = { if (g != null) artSlot = slot }) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
SlotThumb(slot, if (state != null) state.file else preview.art[slot])
if (state != null) ValueText(artSourceLabel(state.source), muted = true) else Loading()
}
}
}
RemoveRow(armed) {
if (!armed) armed = true else {
armed = false
// At once: the page drops the game and the rest runs off this dialog's life.
onRemove(folder, game?.appId, game?.name ?: preview.name)
if (request.fromSummary) onBack()
close()
}
}
}
if (unreachable) Text(stringResource(R.string.games_add_unreachable), fontSize = 12.sp, color = colors.error)
}
val shownName = game?.name ?: preview.name
when (editing) {
"name" -> TextEntryDialog(stringResource(R.string.edit_name), SessionPrefs.addedGameName(ctx, folder).ifEmpty { shownName }, onDismiss = { editing = null }) { value ->
change { AddedGameEdits.setName(app, folder, if (value == shownName && SessionPrefs.addedGameName(app, folder).isEmpty()) "" else value) }
}
"launch" -> TextEntryDialog(stringResource(R.string.edit_launch_options), game?.launchOptions ?: preview.launchOptions, onDismiss = { editing = null }) { value ->
change { AddedGameEdits.setLaunchOptions(app, folder, value) }
}
}
val g = game ?: return
when (editing) {
"start" -> TextEntryDialog(stringResource(R.string.edit_start_in), hostPath(ctx, g), onDismiss = { editing = null }) { value ->
scope.launch {
val ok = withContext(Dispatchers.IO) { AddedGameEdits.setStartIn(app, folder, if (value == g.exe.parentFile?.path) "" else value) }
unreachable = !ok
version++
onChanged()
}
}
}
if (otherExe) ExePickerDialog(stringResource(R.string.games_pick_exe_title), start = g.folder, onDismiss = { otherExe = false }, onPick = { exe ->
targetOpen = false
scope.launch {
val ok = withContext(Dispatchers.IO) { AddedGameEdits.setExe(app, folder, exe) }
unreachable = !ok
version++
onChanged()
}
})
artSlot?.let { slot ->
val current = arts.firstOrNull { it.slot == slot }
ArtChooserDialog(g, slot, current, onBack = { artSlot = null }, onCloseAll = { artSlot = null; close() }) { version++; onChanged() }
}
}
/** Start in as a path on the device: the override mapped back under the game's folder, else the exe's folder. */
private fun hostPath(context: android.content.Context, game: AddedGames.Game): String {
val folderGuest = AddedGames.guestPath(context, game.folder) ?: return game.exe.parentFile?.path.orEmpty()
return when {
game.guestDir == folderGuest -> game.folder.path
game.guestDir.startsWith("$folderGuest/") -> game.folder.path + game.guestDir.removePrefix(folderGuest)
else -> game.exe.parentFile?.path.orEmpty()
}
}
@Composable
private fun ValueText(text: String, muted: Boolean = false) {
Text(
text, fontSize = 14.sp, color = if (muted) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.onBackground,
maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
/** "Remove" in red; pressed once it asks, a second press within four seconds removes. */
@Composable
private fun RemoveRow(armed: Boolean, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val src = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }
val hot = rememberHot(src)
Box(
Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape12)
.background(if (armed) colors.error.copy(alpha = 0.18f) else if (hot) colors.error.copy(alpha = 0.10f) else androidx.compose.ui.graphics.Color.Transparent)
.glideBorder(hot, Shape12, colors.error, colors.error.copy(alpha = 0.4f))
.hoverable(src)
.clickable(interactionSource = src, indication = androidx.compose.foundation.LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
.padding(horizontal = 12.dp, vertical = 10.dp),
) {
Text(
stringResource(if (armed) R.string.mode_added_remove_confirm else R.string.edit_remove),
fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.error,
)
}
}
/** One line of text in a compact dialog: [title] and a red X, the field, OK. */
@Composable
internal fun TextEntryDialog(title: String, initial: String, onDismiss: () -> Unit, onSave: (String) -> Unit) {
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
var value by remember { mutableStateOf(initial) }
val focus = remember { FocusRequester() }
LaunchedEffect(Unit) { focusWithinFrames({ false }) { focus } }
AppDialog(shown, close, "textEntry", wide = false, maxWidth = 460.dp) {
DialogTitleRow(title, onClose = close)
androidx.compose.material3.OutlinedTextField(
value, { value = it }, singleLine = true, modifier = Modifier.fillMaxWidth().focusRequester(focus),
keyboardActions = androidx.compose.foundation.text.KeyboardActions(onDone = { onSave(value.trim()); close() }),
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(imeAction = androidx.compose.ui.text.input.ImeAction.Done),
)
Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
SecondaryButton(stringResource(R.string.common_ok), compact = true) { onSave(value.trim()); close() }
}
}
}
/**
* The art chooser for one [slot]: back, the slot's name and a red X; the images grouped by where
* they come from (the game's folder, Steam, SteamGridDB, fetched as it opens), the current one
* outlined, a tap applies it; "Pick image…" and "Reset to automatic".
*/
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun ArtChooserDialog(
game: AddedGames.Game, slot: AddedGameArt.Slot, current: AddedGameArt.SlotState?,
onBack: () -> Unit, onCloseAll: () -> Unit, onChanged: () -> Unit,
) {
val ctx = LocalContext.current
val app = ctx.applicationContext
val colors = MaterialTheme.colorScheme
val scope = rememberCoroutineScope()
val shown = rememberShown(onBack)
val back = { shown.targetState = false }
var options by remember { mutableStateOf<List<AddedGameArt.Option>?>(null) }
var picking by remember { mutableStateOf(false) }
val chosenRef = remember(current) { AddedGameArt.chosenSource(app, game, slot).second }
LaunchedEffect(slot) { options = withContext(Dispatchers.IO) { runCatching { AddedGameArt.options(app, game, slot) }.getOrDefault(emptyList()) } }
val first = remember { FocusRequester() }
LaunchedEffect(Unit) { focusWithinFrames({ false }) { first } }
val apply: (AddedGameArt.Option) -> Unit = { option ->
scope.launch {
withContext(Dispatchers.IO) { AddedGameEdits.setArt(app, game.folder.path, slot, option) }
onChanged()
back()
}
}
val slotName = slot.label()
AppDialog(shown, back, "artChooser", wide = false, maxWidth = 460.dp) {
DialogTitleRow(slotName, 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(8.dp),
modifier = Modifier.fillMaxWidth().heightIn(max = maxHeight).verticalScroll(rememberScrollState()),
) {
val opts = options
if (opts == null) {
androidx.compose.material3.LinearProgressIndicator(Modifier.fillMaxWidth().padding(vertical = 8.dp))
} else {
var firstGiven = false
for (group in listOf(AddedGameArt.FOLDER, AddedGameArt.STEAM, AddedGameArt.SGDB)) {
val inGroup = opts.filter { it.group == group }
if (inGroup.isEmpty()) continue
Text(artSourceLabel(group), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(start = 2.dp, top = 4.dp))
FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
for (option in inGroup) key(option.full) {
val focus = if (!firstGiven) first.also { firstGiven = true } else null
ArtOption(slot, option, selected = current?.chosen == true && option.full == chosenRef, focus = focus, description = "${artSourceLabel(group)} $slotName") { apply(option) }
}
}
}
}
PickerRow(Icons.Outlined.Image, stringResource(R.string.art_pick_image), null, focus = if (opts?.isEmpty() != false) first else null) { picking = true }
PickerRow(null, stringResource(R.string.art_reset), null) {
scope.launch {
withContext(Dispatchers.IO) { AddedGameEdits.resetArt(app, game.folder.path, slot) }
onChanged()
back()
}
}
}
}
if (picking) ExePickerDialog(stringResource(R.string.art_pick_title, slotName), kind = PickKind.IMAGE, onDismiss = { picking = false }, onPick = { file ->
apply(AddedGameArt.Option(AddedGameArt.FILE, file.path, file.path))
})
}
@Composable
private fun ArtOption(slot: AddedGameArt.Slot, option: AddedGameArt.Option, selected: Boolean, focus: FocusRequester?, description: String, onClick: () -> Unit) {
val pal = LocalPalette.current
val src = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }
val hot = rememberHot(src)
val scale = when (slot) { AddedGameArt.Slot.COVER -> 1.9f; AddedGameArt.Slot.ICON -> 1.6f; else -> 1.5f }
Box(
Modifier.then(if (focus != null) Modifier.focusRequester(focus) else Modifier).clip(RoundedCornerShape(8.dp))
.glideBorder(hot, RoundedCornerShape(8.dp), pal.signal)
.hoverable(src)
.clickable(interactionSource = src, indication = androidx.compose.foundation.LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
.semantics { contentDescription = description }
.padding(2.dp),
) {
SlotThumb(slot, if (option.thumb.startsWith("https://")) option.thumb else File(option.thumb), scale, selected)
}
}
/**
* After "Add all games in this folder": how many were added and how many were there already, then
* one row per added game (cover, name, exe, "?" where unsure); a row opens that game's editor.
* [games] are the added games as the add left them, shown at once; the rows then follow edits and
* removals, and the covers arrive.
*/
@Composable
internal fun AddedGamesSummaryDialog(
games: List<AddedGames.Game>, already: Int, checking: String? = null,
onOpen: (folder: String, uncertain: Boolean, preview: EditPreview) -> Unit,
onRemove: (folder: String, appId: Long?, name: String) -> Unit,
onDismiss: () -> Unit,
) {
val ctx = LocalContext.current
val app = ctx.applicationContext
val colors = MaterialTheme.colorScheme
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
var rows by remember { mutableStateOf(games.map { it to (null as File?) }) }
var gone by remember { mutableStateOf(emptySet<String>()) }
var armed by remember { mutableStateOf<String?>(null) }
LaunchedEffect(armed) { if (armed != null) { kotlinx.coroutines.delay(4_000); armed = null } }
// Rows show as the games arrive; each is refreshed once (current name and exe, a removed one
// dropped) and gets its cover, without redoing the ones already done when more arrive.
var resolved by remember { mutableStateOf(emptyMap<String, Pair<AddedGames.Game, File?>?>()) }
LaunchedEffect(games) {
for (old in games) {
val path = old.folder.path
if (path in resolved) continue
val fresh = withContext(Dispatchers.IO) { AddedGames.single(app, path)?.let { g -> g to AddedGameArt.resolve(app, g).portrait } }
resolved = resolved + (path to fresh)
}
}
LaunchedEffect(games, resolved) {
rows = games.mapNotNull { g -> if (g.folder.path in resolved) resolved[g.folder.path] else g to null }
}
val first = remember { FocusRequester() }
val list = rows.filter { it.first.folder.path !in gone }
LaunchedEffect(list.isNotEmpty()) { if (list.isNotEmpty()) focusWithinFrames({ false }) { first } }
AppDialog(shown, close, "addedSummary", wide = false, maxWidth = 440.dp) {
DialogTitleRow(
if (list.isEmpty() && checking == null) stringResource(R.string.games_added_none) else pluralStringResource(R.plurals.games_added_n, list.size, list.size),
onClose = close,
)
if (already > 0) Text(pluralStringResource(R.plurals.games_already_n, already, already), fontSize = 12.sp, color = colors.onSurfaceVariant)
if (checking != null) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
androidx.compose.material3.CircularProgressIndicator(Modifier.size(14.dp), strokeWidth = 2.dp, color = colors.primary)
Text(checking, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
val maxHeight = (LocalConfiguration.current.screenHeightDp * 0.7f).dp
Column(
verticalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.fillMaxWidth().heightIn(max = maxHeight).verticalScroll(rememberScrollState()),
) {
list.forEachIndexed { i, (g, cover) ->
key(g.folder.path) {
ListRow(focus = if (i == 0) first else null, onClick = { onOpen(g.folder.path, g.exeUncertain, EditPreview.of(g, cover)); close() }) {
SlotThumb(AddedGameArt.Slot.COVER, cover, 0.9f)
Column(Modifier.weight(1f)) {
Text(g.name, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(g.exe.name, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
if (g.exeUncertain) UncertainMark(stringResource(R.string.mode_added_exe_check))
val path = g.folder.path
RemoveX(armed == path, stringResource(R.string.summary_remove_game, g.name)) {
if (armed != path) armed = path else {
armed = null
gone = gone + path
onRemove(path, g.appId, g.name)
}
}
}
}
}
}
}
}
/** A summary row's red X: the first press arms it (filled), a second within 4 s removes the game. */
@Composable
private fun RemoveX(armed: Boolean, description: String, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val src = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }
val hot = rememberHot(src)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.size(32.dp).clip(Shape12)
.background(if (armed) colors.error else if (hot) colors.error.copy(alpha = 0.15f) else androidx.compose.ui.graphics.Color.Transparent)
.glideBorder(hot, Shape12, colors.error)
.hoverable(src)
.clickable(interactionSource = src, indication = androidx.compose.foundation.LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
.semantics { contentDescription = description },
) {
androidx.compose.material3.Icon(Icons.Filled.Close, null, tint = if (armed) colors.onError else colors.error, modifier = Modifier.size(18.dp))
}
}
@@ -0,0 +1,234 @@
package com.droiddeck.launcher.ui
import android.content.Context
import android.os.Environment
import android.os.StatFs
import androidx.compose.foundation.LocalIndication
import androidx.compose.foundation.background
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.Column
import androidx.compose.foundation.layout.Row
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.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.outlined.Folder
import androidx.compose.material.icons.outlined.Image
import androidx.compose.material.icons.outlined.InsertDriveFile
import androidx.compose.material.icons.outlined.SdCard
import androidx.compose.material.icons.outlined.Smartphone
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.stores.formatBytes
import java.io.File
/** What a picker lists besides folders. */
internal enum class PickKind(val extensions: Set<String>) {
EXE(setOf("exe")),
IMAGE(setOf("png", "jpg", "jpeg", "webp", "ico")),
}
/** A place a file can be picked from: internal storage or a card, at its root. */
internal class PickVolume(val root: File, val label: String, val removable: Boolean) {
val free: Long get() = runCatching { StatFs(root.path).availableBytes }.getOrDefault(0L)
}
internal fun pickVolumes(context: Context): List<PickVolume> =
listOf(PickVolume(Environment.getExternalStorageDirectory(), context.getString(R.string.games_internal), removable = false)) +
GameStorage.options(context).mapNotNull { o ->
File(o.path.substringBefore("/Android/")).takeIf { it.isDirectory }?.let { PickVolume(it, o.name, removable = true) }
}.distinctBy { it.root.absolutePath }
/** A folder in a listing; [readable] false = shown greyed, not opened. */
internal class PickFolder(val dir: File, val readable: Boolean)
internal class PickListing(val folders: List<PickFolder>, val files: List<File>)
/**
* Every folder of [dir] (dot-folders left out, the unreadable ones marked), then the files [kind]
* takes; each A-Z.
*/
internal fun pickListing(dir: File, kind: PickKind): PickListing {
val all = dir.listFiles()?.filter { !it.name.startsWith(".") }.orEmpty().sortedBy { it.name.lowercase() }
return PickListing(
all.filter { it.isDirectory }.map { PickFolder(it, it.canRead() && it.list() != null) },
all.filter { it.isFile && it.extension.lowercase() in kind.extensions },
)
}
/**
* The compact in-app file picker: [title] and a red X on one line; the storage rows (internal
* storage, each card, free space); inside one, its root first, a breadcrumb, "..", every folder
* and the [kind] files, scrolling in the dialog. Its width is what the first step needed and stays;
* long names are cut short. B / Back goes up a folder, and closes from the storage rows. [start]
* opens in a folder. [onAddAll] adds a row on top of a folder with subfolders.
*/
@Composable
internal fun ExePickerDialog(
title: String, kind: PickKind = PickKind.EXE, start: File? = null,
onAddAll: ((File) -> Unit)? = null, onPick: (File) -> Unit, onDismiss: () -> Unit,
) {
val ctx = LocalContext.current
val colors = MaterialTheme.colorScheme
val density = LocalDensity.current
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
val volumes = remember { pickVolumes(ctx) }
fun volumeOf(d: File) = volumes.filter { d.path == it.root.path || d.path.startsWith(it.root.path + "/") }.maxByOrNull { it.root.path.length }
var dir by remember { mutableStateOf(start?.takeIf { it.isDirectory && volumeOf(it) != null }) }
val volume = dir?.let { volumeOf(it) }
val up = { dir = dir?.let { d -> if (volume == null || d.path == volume.root.path) null else d.parentFile } }
val back = { if (dir == null) close() else up() }
val first = remember(dir) { FocusRequester() }
LaunchedEffect(dir) { focusWithinFrames({ false }) { first } }
val listing = remember(dir) { dir?.let { pickListing(it, kind) } }
var locked by remember { mutableStateOf<Dp?>(null) }
AppDialog(
shown, close, "filePicker", wide = false, maxWidth = 520.dp, width = locked, fitContent = locked == null, back = back,
modifier = Modifier.onSizeChanged { if (locked == null && it.width > 0) locked = with(density) { it.width.toDp() } },
) {
Column(verticalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) {
DialogTitleRow(title, onClose = close)
if (dir != null && volume != null) {
val crumbs = listOf(volume.label) + dir!!.path.removePrefix(volume.root.path).split('/').filter { it.isNotEmpty() }
Text(crumbs.joinToString(" › "), fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
val maxHeight = (LocalConfiguration.current.screenHeightDp * 0.7f).dp
Column(
verticalArrangement = Arrangement.spacedBy(6.dp),
modifier = Modifier.fillMaxWidth().heightIn(max = maxHeight).verticalScroll(rememberScrollState()).padding(top = 4.dp),
) {
if (dir == null) {
volumes.forEachIndexed { i, v ->
key(v.root.path) {
PickerRow(if (v.removable) Icons.Outlined.SdCard else Icons.Outlined.Smartphone, v.label,
stringResource(R.string.stores_target_free, formatBytes(v.free)), tall = true, focus = if (i == 0) first else null) { dir = v.root }
}
}
} else {
val shownListing = listing ?: PickListing(emptyList(), emptyList())
PickerRow(Icons.AutoMirrored.Outlined.ArrowBack, "..", null, focus = first, onClick = up)
if (onAddAll != null && shownListing.folders.any { it.readable }) {
PickerRow(Icons.Filled.Add, stringResource(R.string.games_add_all), null, accent = true) { onAddAll(dir!!); close() }
}
for (f in shownListing.folders) key(f.dir.path) {
PickerRow(Icons.Outlined.Folder, f.dir.name, null, enabled = f.readable) { dir = f.dir }
}
for (f in shownListing.files) key(f.path) {
PickerRow(if (kind == PickKind.IMAGE) Icons.Outlined.Image else Icons.Outlined.InsertDriveFile, f.name, formatBytes(f.length()), file = true) {
onPick(f); close()
}
}
}
}
}
}
}
/** A compact dialog's title line: [leading] (a back arrow), the title, a small red X. */
@Composable
internal fun DialogTitleRow(title: String, onClose: () -> Unit, leading: (@Composable () -> Unit)? = null) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) {
leading?.invoke()
Text(title, fontSize = 15.sp, color = MaterialTheme.colorScheme.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = MaterialTheme.colorScheme.error, onClick = onClose)
}
}
/** A 32 dp icon button for a dialog's title line. */
@Composable
internal fun SmallIconButton(icon: ImageVector, description: String, tint: androidx.compose.ui.graphics.Color, onClick: () -> Unit) {
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.size(32.dp).clip(Shape12)
.background(if (hot) tint.copy(alpha = 0.15f) else androidx.compose.ui.graphics.Color.Transparent)
.glideBorder(hot, Shape12, tint)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
.semantics { contentDescription = description },
) {
Icon(icon, null, tint = tint, modifier = Modifier.size(18.dp))
}
}
/** One row of a compact dialog's list, the Install dialog's style: [content] laid out in a row. */
@Composable
internal fun ListRow(
enabled: Boolean = true, accent: Boolean = false, tall: Boolean = false, focus: FocusRequester? = null,
onClick: () -> Unit, content: @Composable androidx.compose.foundation.layout.RowScope.(hot: Boolean) -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src) && enabled
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
modifier = Modifier.fillMaxWidth().then(if (focus != null) Modifier.focusRequester(focus) else Modifier).clip(Shape12)
.alpha(if (enabled) 1f else 0.4f)
.background(if (hot) pal.signal.copy(alpha = 0.14f) else colors.surface.copy(alpha = 0.6f))
.glideBorder(hot, Shape12, pal.signal, if (accent) pal.signal else pal.line)
.then(
if (enabled) Modifier.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick) else Modifier,
)
.padding(horizontal = 12.dp, vertical = if (tall) 11.dp else 9.dp),
) { content(hot) }
}
/** A list row with an icon, a name (cut short when long) and a detail on the right. */
@Composable
internal fun PickerRow(
icon: ImageVector?, name: String, detail: String?, tall: Boolean = false, file: Boolean = false, accent: Boolean = false,
enabled: Boolean = true, focus: FocusRequester? = null, onClick: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
ListRow(enabled, accent, tall, focus, onClick) { hot ->
if (icon != null) Icon(icon, null, tint = if (hot || file || accent) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(20.dp))
Text(name, fontSize = 14.sp, fontWeight = if (tall) FontWeight.SemiBold else FontWeight.Normal, color = colors.onBackground,
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
if (detail != null) Text(detail, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, modifier = Modifier.padding(start = 8.dp))
}
}
@@ -30,6 +30,10 @@ 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.outlined.Edit
import androidx.compose.ui.semantics.semantics
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
@@ -55,6 +59,7 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.droiddeck.launcher.frontend.Library
import kotlinx.coroutines.launch
// The Games page: the list, the hero for the selected game and its labels.
@@ -67,9 +72,15 @@ internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, o
val games = remember(s.steamGames) { s.steamGames.sortedByDescending { it.lastPlayed } }
val narrow = LocalNarrowPane.current
val current = games.firstOrNull { "app:${it.appId}" == selected } ?: games.firstOrNull()
GamesDialogs(a)
val onAdd: (() -> Unit)? = if (s.shortcutPicker) null else ({ GamesDialogState.adding = true })
val pageContext = androidx.compose.ui.platform.LocalContext.current
val onEdit: (Library.SteamGame) -> Unit = { g ->
g.gameFiles?.let { GamesDialogState.editing = EditRequest(it.path, openTarget = false, fromSummary = false, preview = EditPreview.of(pageContext, g, it.path)) }
}
if (current == null) {
Column(modifier = modifier.padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)) {
Rise(0) { PageHeader(stringResource(R.string.content_games)) }
Rise(0) { PageHeader(stringResource(R.string.content_games)) { onAdd?.let { AddGameButton(it) } } }
Rise(1) { Note(stringResource(if (s.shortcutPicker && s.shortcutLibraryScanning) R.string.game_shortcut_scanning else R.string.games_empty)) }
if (!s.shortcutPicker) Rise(2) {
Actions { PrimaryButton(stringResource(R.string.games_play_steam), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = Modifier.padding(top = 12.dp).testTag("play-steam"), onClick = a.onPlay) }
@@ -81,11 +92,12 @@ internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, o
val host = rememberMenuHost()
if (games.size == 1) {
Column(modifier = modifier.verticalScroll(rememberScrollState()).padding(horizontal = if (narrow) 16.dp else 22.dp, vertical = if (narrow) 12.dp else 18.dp)) {
if (onAdd != null) Rise(0) { GamesHeader(1, onAdd, Modifier.padding(bottom = 10.dp)) }
Rise(0) {
Row(verticalAlignment = Alignment.Bottom) {
GameHero(current, Modifier.weight(1f).heightIn(min = if (narrow) 190.dp else 250.dp)) {
GameHeroCopy(current, if (narrow) 28.sp else 38.sp)
GameActions(current, s, a)
GameActions(current, s, a, onEdit)
}
if (!narrow) Poster(current.art, current.name, Modifier.width(168.dp))
}
@@ -98,7 +110,7 @@ internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, o
}
val pal = LocalPalette.current
Row(modifier = modifier) {
GameList(games, current, onSelect = { onSelect("app:${it.appId}") }, onLaunch = { a.onSteamGame(it) },
GameList(games, current, onSelect = { onSelect("app:${it.appId}") }, onLaunch = { a.onSteamGame(it) }, onAdd = onAdd,
modifier = Modifier.width(if (narrow) 168.dp else 250.dp).fillMaxHeight())
Box(Modifier.width(1.dp).fillMaxHeight().background(pal.line))
Column(
@@ -107,7 +119,7 @@ internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, o
) {
GameHero(current, Modifier.fillMaxWidth().heightIn(min = if (narrow) 170.dp else 200.dp)) {
GameHeroCopy(current, if (narrow) 24.sp else 32.sp)
GameActions(current, s, a)
GameActions(current, s, a, onEdit)
}
SectionTitle(stringResource(R.string.games_launch_settings), null)
LaunchSettings(s, a, host, current)
@@ -135,7 +147,7 @@ private fun GameFileFolderActions(s: FrontEndState, a: FrontEndActions) {
@Composable
private fun GameActions(g: Library.SteamGame, s: FrontEndState, a: FrontEndActions) {
private fun GameActions(g: Library.SteamGame, s: FrontEndState, a: FrontEndActions, onEdit: (Library.SteamGame) -> Unit) {
Actions {
PrimaryButton(stringResource(if (s.shortcutPicker) R.string.game_shortcut_choose else R.string.games_launch), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow) { a.onSteamGame(g) }
g.gameFiles?.takeIf { it.isDirectory }?.let { dir ->
@@ -147,6 +159,8 @@ private fun GameActions(g: Library.SteamGame, s: FrontEndState, a: FrontEndActio
if (g.library == Library.ADDED) ManageSaves(g, dir, a)
}
if (!s.shortcutPicker) GameShortcutMenu(g, a)
// A game added in DroidDeck (Custom): its editor, Steam's Properties for a non-Steam game.
if (!s.shortcutPicker && g.library == Library.ADDED && g.source == Library.ADDED && g.gameFiles != null) EditGameButton { onEdit(g) }
BusyChip(s)
}
}
@@ -299,7 +313,7 @@ private fun ColumnScope.GameHeroCopy(g: Library.SteamGame, titleSize: androidx.c
@Composable
private fun GameList(
games: List<Library.SteamGame>, current: Library.SteamGame,
onSelect: (Library.SteamGame) -> Unit, onLaunch: (Library.SteamGame) -> Unit, modifier: Modifier,
onSelect: (Library.SteamGame) -> Unit, onLaunch: (Library.SteamGame) -> Unit, onAdd: (() -> Unit)?, modifier: Modifier,
) {
val colors = MaterialTheme.colorScheme
// Laid out whole, as the art grid is: the pad's focus search only finds rows that exist.
@@ -307,16 +321,127 @@ private fun GameList(
verticalArrangement = Arrangement.spacedBy(2.dp),
modifier = modifier.verticalScroll(rememberScrollState()).padding(start = 12.dp, end = 10.dp, top = 16.dp, bottom = 16.dp),
) {
Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(start = 6.dp, bottom = 10.dp)) {
Text(stringResource(R.string.content_games), fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1)
Text(games.size.toString(), fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(bottom = 3.dp))
}
GamesHeader(games.size, onAdd, Modifier.padding(start = 6.dp, bottom = 10.dp))
for (g in games) key(g.appId) {
GameRow(g, g.appId == current.appId, onSelect = { onSelect(g) }, onLaunch = { onLaunch(g) })
}
}
}
/** "Games N", and the + that adds a game from its .exe beside it ([onAdd] null: no +). */
@Composable
private fun GamesHeader(count: Int, onAdd: (() -> Unit)?, modifier: Modifier) {
val colors = MaterialTheme.colorScheme
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = modifier) {
Text(stringResource(R.string.content_games), fontSize = 22.sp, fontWeight = FontWeight.Bold, color = colors.onBackground, maxLines = 1)
Text(count.toString(), fontSize = 13.sp, color = colors.onSurfaceVariant)
if (onAdd != null) AddGameButton(onAdd)
}
}
/**
* The Games tab's dialogs, one at a time: the + picker, the summary after "Add all games in this
* folder", and a game's editor (from the page's ✎ or a summary row, with back to the summary).
*/
internal object GamesDialogState {
var adding by androidx.compose.runtime.mutableStateOf(false)
var summary by androidx.compose.runtime.mutableStateOf<Pair<List<com.droiddeck.launcher.frontend.AddedGames.Game>, Int>?>(null)
var editing by androidx.compose.runtime.mutableStateOf<EditRequest?>(null)
/** The subfolder "Add all games in this folder" is looking at; null when it is done. */
var checking by androidx.compose.runtime.mutableStateOf<String?>(null)
/** The summary an editor opened from it goes back to. */
var behindEditor: Pair<List<com.droiddeck.launcher.frontend.AddedGames.Game>, Int>? = null
}
@Composable
private fun GamesDialogs(a: FrontEndActions) {
val ctx = androidx.compose.ui.platform.LocalContext.current
val scope = androidx.compose.runtime.rememberCoroutineScope()
val st = GamesDialogState
if (st.adding) ExePickerDialog(
stringResource(R.string.games_add_title),
onAddAll = { dir ->
st.summary = emptyList<com.droiddeck.launcher.frontend.AddedGames.Game>() to 0
st.checking = dir.name
scope.launch {
val result = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
com.droiddeck.launcher.frontend.AddedGames.addFolder(
ctx.applicationContext, dir,
onGame = { g -> scope.launch { st.summary?.let { (list, n) -> st.summary = (list + g) to n } } },
onChecking = { name -> scope.launch { st.checking = name } },
)
}
st.checking = null
a.onAddedGamesChanged(result.added.map { it.folder.path })
st.summary?.let { (list, _) -> st.summary = list to result.already }
}
},
onPick = { a.onAddGameExe(it.path) },
onDismiss = { st.adding = false },
)
st.summary?.let { (added, already) ->
AddedGamesSummaryDialog(added, already, checking = st.checking, onOpen = { folder, uncertain, preview ->
st.behindEditor = added to already
st.editing = EditRequest(folder, openTarget = uncertain, fromSummary = true, preview = preview)
}, onRemove = { folder, appId, name ->
st.summary = st.summary?.let { (list, n) -> list.filterNot { it.folder.path == folder } to n }
a.onAddedGameRemoved(folder, appId, name)
}, onDismiss = { st.summary = null; st.checking = null })
}
st.editing?.let { request ->
AddedGameEditor(
request,
onBack = { st.behindEditor?.let { st.summary = it }; st.behindEditor = null },
onClose = { st.editing = null },
onChanged = { a.onAddedGamesChanged(listOf(request.folder)) },
onRemove = { folder, appId, name -> a.onAddedGameRemoved(folder, appId, name) },
)
}
}
/** The ✎ on a Custom game's page: icon only. */
@Composable
private fun EditGameButton(onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = rememberHot(src)
val label = stringResource(R.string.common_edit)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.paneItem("game:edit").size(40.dp).clip(Shape12)
.background(if (hot) pal.signal.copy(alpha = 0.18f) else colors.surface.copy(alpha = 0.55f))
.glideBorder(hot, Shape12, pal.signal, pal.line2)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = androidx.compose.ui.semantics.Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
.semantics { contentDescription = label },
) {
androidx.compose.material3.Icon(Icons.Outlined.Edit, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(18.dp))
}
}
/** A round + that opens the .exe picker. */
@Composable
private fun AddGameButton(onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val focused by src.collectIsFocusedAsState()
val hovered by src.collectIsHoveredAsState()
val label = stringResource(R.string.games_add)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.paneItem("games:add").size(32.dp).clip(CircleShape)
.background(if (focused || hovered) pal.signal.copy(alpha = 0.18f) else colors.surfaceVariant)
.glideBorder(focused, CircleShape, pal.signal)
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = androidx.compose.ui.semantics.Role.Button, onClick = onClick)
.controllerConfirm(onClick = onClick)
.semantics { contentDescription = label },
) {
androidx.compose.material3.Icon(Icons.Filled.Add, contentDescription = null, tint = colors.onBackground, modifier = Modifier.size(20.dp))
}
}
/** One game in the list. Moving onto it with the pad shows it; A launches it, a tap only shows it. */
@Composable
private fun GameRow(g: Library.SteamGame, selected: Boolean, onSelect: () -> Unit, onLaunch: () -> Unit) {
@@ -137,6 +137,9 @@ class FrontEndState(
val storesOpenTab: String = SessionPrefs.STORES_OPEN_LIBRARY,
/** A page to open once: "stores:downloads", or a selection such as "app:<id>" (a notification's tap). */
val navigate: String? = null,
/** Setup: art for added games is fetched; the user has a SteamGridDB key of their own. */
val addedGamesArt: Boolean = true,
val sgdbUserKey: Boolean = false,
val storesShowMature: Boolean = false,
/** Downloads queued, running or paused across the three stores; the rail item's badge. */
val storeDownloadsActive: Int = 0,
@@ -151,6 +154,15 @@ class FrontEndActions(
val onGameShortcut: (Library.SteamGame) -> Unit = {},
val onExportGameFile: (Library.SteamGame) -> Unit = {},
val onSyncGameFiles: () -> Unit = {},
/** The Games tab's +: the .exe picked in its dialog, to add as a game. */
val onAddGameExe: (path: String) -> Unit = {},
/** These added games (by folder) were added or edited: the Games tab updates just them. */
val onAddedGamesChanged: (folders: List<String>) -> Unit = {},
/** An added game removed in its editor: off the Games tab at once, out of Steam after. */
val onAddedGameRemoved: (folder: String, appId: Long?, name: String) -> Unit = { _, _, _ -> },
/** Setup's Artwork switch and the user's SteamGridDB API key ("" removes it). */
val onAddedGamesArt: (Boolean) -> Unit = {},
val onSgdbKey: (String) -> Unit = {},
val onStopGameFileSync: () -> Unit = {},
val onCopyGameLink: (Library.SteamGame) -> Unit = {},
val onDesktop: () -> Unit,
@@ -164,6 +164,8 @@ internal fun SetupPanel(
val limitBlocks = PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
val signedIn = s.offlineAccount != null
var showLimitDetails by rememberSaveable { mutableStateOf(false) }
var editSgdbKey by remember { mutableStateOf(false) }
if (editSgdbKey) SgdbKeyDialog(s.sgdbUserKey, onSave = { a.onSgdbKey(it); editSgdbKey = false }, onDismiss = { editSgdbKey = false })
// Four tabs instead of one long scroll; LB and RB turn them from anywhere on the page. Build
// and credits are on the Updates page.
val tabs = listOf(stringResource(R.string.setup_tab_overview), stringResource(R.string.setup_tab_controller), stringResource(R.string.setup_tab_session), stringResource(R.string.setup_tab_launcher))
@@ -368,6 +370,13 @@ internal fun SetupPanel(
s.storeEnabled,
) { a.onStoreEnabled(it) }
}
SettingsGroup(stringResource(R.string.content_games)) {
ToggleRow(host, "added-art", stringResource(R.string.mode_added_art), stringResource(R.string.mode_added_art_hint), s.addedGamesArt) { a.onAddedGamesArt(it) }
ActionRow(
stringResource(R.string.mode_sgdb_key), if (s.sgdbUserKey) stringResource(R.string.mode_sgdb_key_yours) else null,
stringResource(R.string.mode_sgdb_edit), onClick = { editSgdbKey = true },
)
}
SettingsGroup(stringResource(R.string.setup_stores)) {
ToggleRow(
host, "stores-enabled", stringResource(R.string.setup_stores_show),
@@ -103,10 +103,6 @@ class ModeSettings(
val wifiDiscoveryLocation: Boolean = false,
val wifiDiscoveryAsked: Boolean = false,
val wifiDiscoveryBlocked: Boolean = false,
/** Steam only: the user's chosen Games folders; null outside Steam. */
val addedGamesDirs: List<String>? = null,
val addedGames: List<AddedGameRow> = emptyList(),
val addedGamesArt: Boolean = true,
/** Latest Banners-Turnip release: what each driver menu offers to download, and the refresh line. */
/** Steam only: Decky Loader is managed from the Steam session settings. */
val deckyInstalled: String? = null,
@@ -120,9 +116,6 @@ class ModeSettings(
val deckySessionRunning: Boolean = false,
)
/** One added game as the settings page shows it: its folder, the chosen .exe, the other .exe files it could be. */
class AddedGameRow(val folderPath: String, val folderName: String, val exePath: String, val exeName: String, val candidates: List<Pair<String, String>>)
class ModeSettingsActions(
val onResolution: (String) -> Unit,
val onHdr: (Boolean) -> Unit,
@@ -154,11 +147,6 @@ class ModeSettingsActions(
val onRunSteamAtStartup: (Boolean) -> Unit = {},
val onWifiDiscovery: (Boolean) -> Unit = {},
val onWifiDiscoverySettings: () -> 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 onDeckyInstall: (DeckyManager.Release) -> Unit = {},
val onDeckyCheck: () -> Unit = {},
val onDeckyEnabled: (Boolean) -> Unit = {},
@@ -429,33 +417,6 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
}
}
}
if (steam && tab == ModeSettingsTab.GAMES && s.addedGamesDirs != null) SettingsGroup(stringResource(R.string.mode_added_games)) {
for (dir in s.addedGamesDirs) {
val n = s.addedGames.count { it.folderPath.startsWith("$dir/") }
ActionRow(
dir.substringAfterLast('/').ifEmpty { dir }, dir + " · " + (if (n == 0) stringResource(R.string.mode_added_none) else pluralStringResource(R.plurals.mode_added_count, n, n)) + ". " + stringResource(R.string.added_games_forget_hint),
stringResource(R.string.common_forget), onClick = { a.onForgetAddedGamesDir(dir) },
)
}
ActionRow(
if (s.addedGamesDirs.isEmpty()) stringResource(R.string.mode_games_folder) else stringResource(R.string.mode_games_folder_another),
stringResource(R.string.added_games_import_hint),
stringResource(R.string.common_add_ellipsis), onClick = a.onPickAddedGamesDir,
)
ToggleRow(
host, "addedArt", stringResource(R.string.mode_added_art),
stringResource(R.string.mode_added_art_hint),
s.addedGamesArt, onChange = a.onAddedGamesArt,
)
for (g in s.addedGames) {
ChoiceRow(
host, "added:" + g.folderPath, g.folderName, if (s.addedGamesDirs.size > 1) stringResource(R.string.mode_added_launches_in, g.exeName, g.folderPath.substringBeforeLast('/').substringAfterLast('/')) else stringResource(R.string.mode_added_launches, g.exeName),
g.candidates + ("__pick__" to stringResource(R.string.mode_added_choose)), g.exePath,
note = stringResource(R.string.mode_added_exe_note),
onPick = { path -> if (path == "__pick__") a.onPickAddedGameExe(g.folderPath) else a.onAddedGameExe(g.folderPath, path) },
)
}
}
if (steam && tab == ModeSettingsTab.GAMES && s.fexPreset != null) SettingsGroup(stringResource(R.string.game_settings_title)) {
if (s.syncBackend != null) SettingsRow(
stringResource(R.string.sync_backend_title),
@@ -552,6 +513,31 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) {
}
/** Width × height for the session, with the common handheld shapes one tap away. */
/** Entry for the user's SteamGridDB API key; the saved key is never shown back. */
@Composable
internal fun SgdbKeyDialog(hasKey: Boolean, onSave: (String) -> Unit, onDismiss: () -> Unit) {
var key by remember { mutableStateOf("") }
androidx.compose.material3.AlertDialog(
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.mode_sgdb_key)) },
text = {
androidx.compose.material3.OutlinedTextField(
key, { v -> key = v.trim() }, label = { Text(stringResource(R.string.mode_sgdb_key)) },
singleLine = true, visualTransformation = androidx.compose.ui.text.input.PasswordVisualTransformation(),
keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = androidx.compose.ui.text.input.KeyboardType.Password),
modifier = Modifier.fillMaxWidth(),
)
},
confirmButton = { androidx.compose.material3.TextButton(onClick = { onSave(key) }, enabled = key.isNotEmpty()) { Text(stringResource(R.string.common_ok)) } },
dismissButton = {
androidx.compose.foundation.layout.Row {
if (hasKey) androidx.compose.material3.TextButton(onClick = { onSave("") }) { Text(stringResource(R.string.common_delete)) }
androidx.compose.material3.TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) }
}
},
)
}
@OptIn(androidx.compose.foundation.layout.ExperimentalLayoutApi::class)
@Composable
internal fun CustomResolutionDialog(initial: Pair<Int, Int>?, onSave: (Pair<Int, Int>) -> Unit, onDismiss: () -> Unit) {
@@ -494,6 +494,19 @@ fun <T> ChoiceRow(
}
}
/** A small "?" beside a value the app guessed and is not sure of; [description] says what to check. */
@Composable
fun UncertainMark(description: String) {
val colors = MaterialTheme.colorScheme
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.size(22.dp).clip(CircleShape).background(colors.surfaceVariant)
.semantics { contentDescription = description },
) {
Text("?", fontSize = 13.sp, fontWeight = FontWeight.Bold, color = colors.onSurfaceVariant)
}
}
@Composable
fun ToggleRow(host: MenuHost, key: String, label: String, hint: String?, checked: Boolean, enabled: Boolean = true, chipModifier: Modifier = Modifier, onChange: (Boolean) -> Unit) =
SettingsRow(label, hint) {