mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-20 21:35:59 +00:00
cleanup (#764)
This commit is contained in:
1 parent
4163b31b02
commit
83ec5708ed
852 files changed
+4844
-46144
No files matched your search
@@ -5,15 +5,7 @@ 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")
|
||||
@@ -30,7 +22,6 @@ object AddedExes {
|
||||
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)
|
||||
|
||||
|
||||
@@ -11,14 +11,6 @@ import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.net.URLEncoder
|
||||
|
||||
/**
|
||||
* Artwork for an added game: what the user put in the game's folder first, else what Steam 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.
|
||||
*/
|
||||
object AddedGameArt {
|
||||
private const val TAG = "AddedGameArt"
|
||||
private const val STORE_SEARCH = "https://store.steampowered.com/api/storesearch/?l=english&cc=US&term="
|
||||
@@ -29,15 +21,10 @@ 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"
|
||||
@@ -45,10 +32,8 @@ object AddedGameArt {
|
||||
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+)""")
|
||||
@@ -64,7 +49,6 @@ object AddedGameArt {
|
||||
|
||||
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? {
|
||||
val dirs = listOf(folder, File(folder, "art"), File(folder, ".art"))
|
||||
for (dir in dirs) for (name in names) for (ext in IMAGE) {
|
||||
@@ -74,7 +58,6 @@ object AddedGameArt {
|
||||
return null
|
||||
}
|
||||
|
||||
/** What the folder itself offers; the file named after the folder counts as the portrait. */
|
||||
private fun local(game: AddedGames.Game): Art {
|
||||
val folder = game.folder
|
||||
return Art(
|
||||
@@ -86,7 +69,6 @@ object AddedGameArt {
|
||||
)
|
||||
}
|
||||
|
||||
/** 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)
|
||||
@@ -100,7 +82,6 @@ object AddedGameArt {
|
||||
)
|
||||
}
|
||||
|
||||
/** 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)
|
||||
@@ -122,17 +103,11 @@ object AddedGameArt {
|
||||
|
||||
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)) }
|
||||
@@ -155,7 +130,6 @@ object AddedGameArt {
|
||||
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
|
||||
@@ -170,13 +144,11 @@ object AddedGameArt {
|
||||
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, "")
|
||||
@@ -191,7 +163,6 @@ object AddedGameArt {
|
||||
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)
|
||||
val png = File(cache, "icon.png")
|
||||
@@ -206,12 +177,6 @@ object AddedGameArt {
|
||||
return if (tmp.renameTo(png)) png else null
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)
|
||||
@@ -236,17 +201,12 @@ object AddedGameArt {
|
||||
return changed
|
||||
}
|
||||
|
||||
/**
|
||||
* The game's Steam app, the one record its Windows components use too ([SteamMatch]): what its
|
||||
* files name, else a store search on its title ([search]) whose result has the same name.
|
||||
*/
|
||||
internal fun steamMatch(context: Context, game: AddedGames.Game, search: (String) -> Int?): SteamMatch.Match {
|
||||
val match = SteamMatch.resolve(context, game.folder.path, game.exe, game.name, legacy = File(cacheDir(context, game), "steam-appid"), search = search)
|
||||
match.appId?.let { Log.i(TAG, "${game.name}: Steam app $it (${match.certainty.name.lowercase()})") }
|
||||
return match
|
||||
}
|
||||
|
||||
/** 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()
|
||||
@@ -262,11 +222,6 @@ object AddedGameArt {
|
||||
|
||||
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 })
|
||||
@@ -280,13 +235,11 @@ object AddedGameArt {
|
||||
}
|
||||
}
|
||||
|
||||
/** 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(EDITION, " ").trim().ifEmpty { name }
|
||||
val json = get(STORE_SEARCH + URLEncoder.encode(term, "UTF-8"))?.toString(Charsets.UTF_8) ?: return null
|
||||
@@ -309,10 +262,6 @@ object AddedGameArt {
|
||||
return got
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
@@ -336,11 +285,6 @@ object AddedGameArt {
|
||||
|
||||
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")
|
||||
|
||||
@@ -5,27 +5,16 @@ 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)
|
||||
@@ -33,7 +22,6 @@ object AddedGameEdits {
|
||||
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)
|
||||
@@ -46,7 +34,6 @@ object AddedGameEdits {
|
||||
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
|
||||
@@ -54,7 +41,6 @@ object AddedGameEdits {
|
||||
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)
|
||||
|
||||
@@ -11,7 +11,6 @@ import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import java.io.File
|
||||
import java.util.zip.CRC32
|
||||
|
||||
/** Windows game folders shared with the Steam session. */
|
||||
object AddedGames {
|
||||
private const val TAG = "AddedGames"
|
||||
private const val LIBRARY = "/mnt/droiddeck-sd"
|
||||
@@ -19,38 +18,23 @@ object AddedGames {
|
||||
|
||||
class Game(
|
||||
val folder: File, val name: String,
|
||||
/** The game's own .exe: what the icon is read from and what the settings page lists. */
|
||||
val exe: File,
|
||||
/** The guest path the shortcut runs: [exe], or a store install's launcher .bat in front of it. */
|
||||
val guestExe: String, val guestDir: String,
|
||||
/** The client's 32-bit appid for this shortcut, as an unsigned value. */
|
||||
val appId: Long,
|
||||
/** What steam://rungameid/ takes for a shortcut. */
|
||||
val gameId: Long,
|
||||
val candidates: List<File>,
|
||||
val steamAppId: Int? = null,
|
||||
/** Where the game came from: a store's id, or [Library.ADDED] for a folder the user added. */
|
||||
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
|
||||
}
|
||||
|
||||
/** A Games folder an earlier build had, and where the session sees it. */
|
||||
class Root(val host: File, val guest: String)
|
||||
|
||||
/**
|
||||
* The Games folders earlier builds had, bound into the session at the guest paths they had
|
||||
* then (/root/Games/<name>), so the games in them (entries now, [GamesFolderMigration]) keep
|
||||
* their paths and shortcuts. Nothing adds one any more.
|
||||
*/
|
||||
fun roots(context: Context): List<Root> {
|
||||
GamesFolderMigration.run(context)
|
||||
return SessionPrefs.gameFolderBinds(context).map { (host, guest) -> Root(File(host), guest) }
|
||||
@@ -61,14 +45,10 @@ object AddedGames {
|
||||
"|.*installer.*|.*uninstall.*|.*updater?.*|.*config(ur.*)?|.*settings.*|.*editor.*|.*server.*|.*benchmark.*|.*helper.*|.*eac.*|.*easyanticheat.*|.*battleye.*)\\.exe$",
|
||||
)
|
||||
|
||||
/** Under here the chosen Games folders are bound inside the session, one each. */
|
||||
const val GUEST_DIR = "/root/Games"
|
||||
|
||||
/** Where a host path appears inside the session, or null when the session cannot see it. */
|
||||
fun guestPath(context: Context, host: File): String? {
|
||||
val path = host.absolutePath
|
||||
// The Games folders are bound on their own, so a folder anywhere - an SD card, a USB
|
||||
// drive - works without being inside one of the other binds.
|
||||
for (root in roots(context)) {
|
||||
val dir = root.host.absolutePath
|
||||
if (path == dir) return root.guest
|
||||
@@ -77,26 +57,19 @@ object AddedGames {
|
||||
SessionPrefs.romsDir(context).takeIf { it.isNotEmpty() }?.let { roms ->
|
||||
if (path.startsWith("$roms/")) return "/root/ROMs/" + path.removePrefix("$roms/")
|
||||
}
|
||||
// A store root on a card has a bind of its own, before the library rule: the same folder
|
||||
// keeps the same guest path (and appid) whether or not that card is also the Steam library.
|
||||
StoreInstallRoot.externalGuestPath(context, host)?.let { return it }
|
||||
GameStorage.effective(context)?.let { lib ->
|
||||
if (path.startsWith("${lib.path}/")) return "$LIBRARY/" + path.removePrefix("${lib.path}/")
|
||||
}
|
||||
// Inside the runtime's own tree (store installs on internal storage live at
|
||||
// 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 ([GameExePicker]); declared Store exes lead. */
|
||||
fun candidates(folder: File): List<File> = rank(folder).exes
|
||||
|
||||
/** [GameExePicker]'s ranking, with a Store-declared executable taking precedence when present. */
|
||||
fun rank(folder: File): GameExePicker.Ranking {
|
||||
val key = "${folder.path}|${folder.lastModified()}"
|
||||
val now = System.currentTimeMillis()
|
||||
@@ -115,20 +88,11 @@ object AddedGames {
|
||||
return result
|
||||
}
|
||||
|
||||
/** 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 } }
|
||||
@@ -141,13 +105,6 @@ object AddedGames {
|
||||
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 }
|
||||
|
||||
@@ -163,7 +120,6 @@ object AddedGames {
|
||||
else -> peName
|
||||
}
|
||||
}
|
||||
/** The executables MicrosoftGame.config or appxmanifest.xml declares that exist inside [folder]. */
|
||||
internal fun declaredExes(folder: File): List<File> {
|
||||
val names = DECLARED.flatMap { (file, pattern) ->
|
||||
runCatching { pattern.findAll(File(folder, file).readText()).map { it.groupValues[1] }.toList() }.getOrDefault(emptyList())
|
||||
@@ -195,30 +151,20 @@ object AddedGames {
|
||||
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
|
||||
@@ -227,12 +173,6 @@ object AddedGames {
|
||||
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()
|
||||
@@ -243,13 +183,10 @@ object AddedGames {
|
||||
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()
|
||||
}
|
||||
@@ -258,11 +195,6 @@ object AddedGames {
|
||||
|
||||
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 (Games folders
|
||||
* of earlier builds included), a removed game, a store install, or the first-level folder under
|
||||
* the Steam library that holds it. Null when it is in none.
|
||||
*/
|
||||
private fun ownerFolder(context: Context, exe: File): File? {
|
||||
GamesFolderMigration.run(context)
|
||||
val path = canonical(exe)
|
||||
@@ -270,7 +202,6 @@ object AddedGames {
|
||||
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 }
|
||||
// Games folders of earlier builds are entries now, found above.
|
||||
val dirs = listOfNotNull(
|
||||
GameStorage.effective(context)?.let { File(it.path, "steamapps/common") },
|
||||
GameStorage.effective(context)?.let { File(it.path) },
|
||||
@@ -284,12 +215,6 @@ object AddedGames {
|
||||
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
|
||||
@@ -309,15 +234,8 @@ object AddedGames {
|
||||
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()
|
||||
@@ -343,11 +261,6 @@ object AddedGames {
|
||||
return FolderResult(added, already)
|
||||
}
|
||||
|
||||
/**
|
||||
* The game folders already listed, without building any game: the first-level folders of the
|
||||
* Steam library (as [scan] walks them), the Games tab's entries (Games folders of earlier builds
|
||||
* included) 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>()
|
||||
GamesFolderMigration.run(context)
|
||||
@@ -367,11 +280,6 @@ object AddedGames {
|
||||
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
|
||||
* may lowercase installdir on Android's case-insensitive storage, so names compare lowercased.
|
||||
*/
|
||||
internal fun steamInstallDirs(dir: File): Set<String> {
|
||||
val steamapps = dir.parentFile?.takeIf { dir.name == "common" && it.name == "steamapps" } ?: return emptySet()
|
||||
return steamapps.listFiles { f -> f.isFile && f.name.startsWith("appmanifest_") && f.name.endsWith(".acf") }
|
||||
@@ -385,33 +293,24 @@ object AddedGames {
|
||||
|
||||
private val INSTALL_DIR = Regex("\"installdir\"\\s*\"([^\"]*)\"", RegexOption.IGNORE_CASE)
|
||||
|
||||
/** [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 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
|
||||
// environment; it is what the shortcut runs. Dropped when the user picked another exe.
|
||||
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 }
|
||||
// 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/")}\"" + 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)
|
||||
@@ -460,12 +359,6 @@ 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
|
||||
@@ -489,7 +382,6 @@ object AddedGames {
|
||||
}
|
||||
}
|
||||
|
||||
/** 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() }
|
||||
val json = StringBuilder("[")
|
||||
@@ -500,8 +392,6 @@ object AddedGames {
|
||||
.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)
|
||||
val pieces = listOf("p" to art.portrait, "header" to art.header, "hero" to art.hero, "logo" to art.logo, "icon" to art.icon)
|
||||
.mapNotNull { (k, f) -> f?.let { file -> artGuestPath(context, file)?.let { k to it } } }
|
||||
|
||||
@@ -5,23 +5,15 @@ 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 {
|
||||
@@ -31,7 +23,6 @@ object AddedGamesPublisher {
|
||||
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)
|
||||
|
||||
@@ -16,29 +16,12 @@ import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.concurrent.PriorityBlockingQueue
|
||||
|
||||
/**
|
||||
* Turns on, per game, the Windows components its source's list names ([WinCompSources]). Only the
|
||||
* findings marked auto are turned on, only the ones that install here, and never one the user
|
||||
* switched off: the user's switches are kept apart ([WinComponents.Selection.user]) and win.
|
||||
*
|
||||
* All the work is done by one background thread (low priority, so are the runtime helpers it
|
||||
* starts), one job at a time from one queue: working out a game's list (kept, so a page opens on
|
||||
* it) and downloading a component (each once, whichever games want it). The queue waits while a
|
||||
* session runs; jobs nobody asked for (the start-up sweep, a game being launched) also wait on
|
||||
* battery saver, a warm device or a metered network. Nothing here runs on the caller's thread.
|
||||
*/
|
||||
object AutoComponents {
|
||||
private const val TAG = "AutoComponents"
|
||||
|
||||
/** The key a game's picks are kept under: the appid its prefix is named after. */
|
||||
fun appKey(game: Library.SteamGame): String? =
|
||||
if (game.library == Library.ADDED) Integer.toUnsignedString(game.appId) else game.appId.takeIf { it > 0 }?.toString()
|
||||
|
||||
/**
|
||||
* What turns on by itself for [findings], given [catalog] and what is [installed]: the catalog
|
||||
* name each auto finding installs as, with its reason. A component that needs a Windows
|
||||
* installer, or is not in the catalog, stays out (the editor lists it as a suggestion).
|
||||
*/
|
||||
fun autoPicks(findings: List<WinCompSources.Finding>, catalog: Map<String, WinComponents.Component>): Map<String, WinComponents.AutoReason> {
|
||||
val out = LinkedHashMap<String, WinComponents.AutoReason>()
|
||||
for (f in findings) {
|
||||
@@ -51,30 +34,22 @@ object AutoComponents {
|
||||
return out
|
||||
}
|
||||
|
||||
// ---- seams for tests ----
|
||||
@VisibleForTesting internal var catalogOf: (Context, Boolean) -> List<WinComponents.Component>? =
|
||||
{ c, network -> if (network) WinComponents.fetch(c) else WinComponents.cached(c) }
|
||||
@VisibleForTesting internal var installedOf: (Context) -> Set<String> = { WinComponents.installedIds(it).toSet() }
|
||||
@VisibleForTesting internal var installer: (Context, WinComponents.Component, Map<String, WinComponents.Component>, (WinComponents.Progress) -> Unit) -> String? =
|
||||
{ c, comp, all, progress -> WinComponents.install(c, comp, all, progress) }
|
||||
@VisibleForTesting internal var sessionRunning: () -> Boolean = { SessionState.running }
|
||||
/** Battery saver, a warm device or a metered network: no work nobody asked for. */
|
||||
@VisibleForTesting internal var unfavourable: (Context) -> Boolean = { c -> constrained(c) }
|
||||
/** A usable network: a download waits for one. */
|
||||
@VisibleForTesting internal var online: (Context) -> Boolean = { c -> isOnline(c) }
|
||||
/** Tests run the queue on the caller's thread ([drain]) instead of the worker. */
|
||||
@VisibleForTesting @Volatile internal var runNow = false
|
||||
|
||||
/** Bumped whenever a game's list or automatic components change, so an open page reads them again. */
|
||||
val changes = MutableStateFlow(0)
|
||||
|
||||
/** The components downloading for an automatic pick right now, with their progress. */
|
||||
val downloading = MutableStateFlow<Map<String, WinComponents.Progress>>(emptyMap())
|
||||
|
||||
/** Games (by [appKey]) whose list is queued or being worked out: a page waits on it. */
|
||||
val pendingGames = MutableStateFlow<Set<String>>(emptySet())
|
||||
|
||||
/** Components queued for an automatic pick, not yet downloaded. */
|
||||
val pendingComponents = MutableStateFlow<Set<String>>(emptySet())
|
||||
|
||||
private fun mark(job: Job, on: Boolean) {
|
||||
@@ -84,10 +59,8 @@ object AutoComponents {
|
||||
flow.value = if (on) flow.value + id else flow.value - id
|
||||
}
|
||||
|
||||
/** One piece of work: a game's list ([game]) or one component's download ([component]). [asked]: the user is waiting on it. */
|
||||
internal class Job(
|
||||
val game: Library.SteamGame?, val component: String?, val asked: Boolean, val seq: Long, val pics: List<Int>? = null,
|
||||
/** For a game Steam installed during the running session: may run in it, unless a game is running. */
|
||||
val inSession: Boolean = false,
|
||||
) {
|
||||
val key get() = when {
|
||||
@@ -95,24 +68,17 @@ object AutoComponents {
|
||||
component != null -> "c:$component"
|
||||
else -> "g:" + (game?.let { appKey(it) } ?: "")
|
||||
}
|
||||
/** Needs the network: a download, or Steam asked anonymously. */
|
||||
val online get() = component != null || pics != null
|
||||
}
|
||||
|
||||
private val seq = java.util.concurrent.atomic.AtomicLong()
|
||||
/** What the user asked for first, then in the order queued. */
|
||||
private val jobs = PriorityBlockingQueue<Job>(16, compareByDescending<Job> { it.asked }.thenBy { it.seq })
|
||||
@Volatile private var draining = false
|
||||
private val queuedKeys = java.util.Collections.synchronizedSet(HashSet<String>())
|
||||
/** The games waiting on a component's download, to turn it on for when it lands. */
|
||||
private val waiting = HashMap<String, MutableList<Library.SteamGame>>()
|
||||
@Volatile private var worker: Thread? = null
|
||||
private const val PAUSE_MS = 15_000L
|
||||
|
||||
/**
|
||||
* [game]'s list worked out again on the worker, and its components queued: [asked] when the
|
||||
* user is waiting (its page is open, or they installed or added it).
|
||||
*/
|
||||
fun queueGame(context: Context, game: Library.SteamGame, asked: Boolean) {
|
||||
if (appKey(game) == null) return
|
||||
enqueue(context, Job(game, null, asked, seq.incrementAndGet()))
|
||||
@@ -121,10 +87,8 @@ object AutoComponents {
|
||||
private fun queueDownload(context: Context, id: String, asked: Boolean, inSession: Boolean = false) =
|
||||
enqueue(context, Job(null, id, asked, seq.incrementAndGet(), inSession = inSession))
|
||||
|
||||
/** Adds [job] unless the same one is queued (a game or a component, once each). */
|
||||
private fun enqueue(context: Context, job: Job) {
|
||||
if (!queuedKeys.add(job.key)) {
|
||||
// Asked for now: ahead of what nobody asked for, so the open page does not wait behind the sweep.
|
||||
if (job.asked && jobs.removeIf { it.key == job.key && !it.asked }) jobs.add(job)
|
||||
if (runNow && !draining) drain(context)
|
||||
return
|
||||
@@ -135,12 +99,10 @@ object AutoComponents {
|
||||
if (runNow) { if (!draining) drain(context) } else ensureWorker(context.applicationContext)
|
||||
}
|
||||
|
||||
/** Whether [job] has to wait: always while a session runs; one nobody asked for also when it is unfavourable. */
|
||||
internal fun mustWait(context: Context, job: Job): Boolean =
|
||||
if (job.inSession && sessionRunning()) gameRunning() || (job.online && !online(context))
|
||||
else sessionRunning() || (job.online && !online(context)) || (!job.asked && unfavourable(context))
|
||||
|
||||
/** A game is running in the session (Steam's reaper, or Proton waiting on its game). */
|
||||
@VisibleForTesting internal var gameRunning: () -> Boolean = { gameProcessRunning() }
|
||||
|
||||
private fun gameProcessRunning(): Boolean = File("/proc").listFiles()?.any { p ->
|
||||
@@ -148,17 +110,11 @@ object AutoComponents {
|
||||
?.let { it.contains("SteamLaunch AppId=") || it.contains("proton waitforexitandrun") } == true
|
||||
} == true
|
||||
|
||||
/**
|
||||
* A game Steam installed during the running session: its list worked out and its components
|
||||
* readied in the session (one job, low priority), so a launch right after finds them; it
|
||||
* waits while a game runs. All other work stays paused until the session ends.
|
||||
*/
|
||||
fun queueInSession(context: Context, game: Library.SteamGame) {
|
||||
if (appKey(game) == null) return
|
||||
enqueue(context, Job(game, null, true, seq.incrementAndGet(), inSession = true))
|
||||
}
|
||||
|
||||
/** Runs the queued jobs on this thread until the queue is empty or the next one has to wait. Tests. */
|
||||
@VisibleForTesting
|
||||
internal fun drain(context: Context) {
|
||||
draining = true
|
||||
@@ -173,7 +129,6 @@ object AutoComponents {
|
||||
}
|
||||
}
|
||||
|
||||
/** The first job in order that may run now, taken off the queue; null when none may. */
|
||||
private fun next(context: Context): Job? = synchronized(jobs) {
|
||||
val job = jobs.sortedWith(order).firstOrNull { !mustWait(context, it) } ?: return null
|
||||
jobs.remove(job)
|
||||
@@ -190,8 +145,6 @@ object AutoComponents {
|
||||
worker = Thread({
|
||||
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND)
|
||||
while (true) {
|
||||
// Something queued, then the first that may run (one for a game installed in the
|
||||
// session goes ahead of paused work); else a look again in a while.
|
||||
try { jobs.put(jobs.take()) } catch (e: InterruptedException) { return@Thread }
|
||||
val job = next(app)
|
||||
if (job == null) {
|
||||
@@ -219,21 +172,14 @@ object AutoComponents {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* [game]'s list (worked out again only when what it is read from changed), its automatic
|
||||
* components that are downloaded turned on, and the rest queued for download.
|
||||
*/
|
||||
private fun apply(context: Context, game: Library.SteamGame, asked: Boolean, inSession: Boolean = false) {
|
||||
val key = appKey(game) ?: return
|
||||
val folder = game.gameFiles
|
||||
if (game.library == Library.ADDED && game.source == Library.ADDED && folder != null && SteamMatch.get(context, folder.path) == null) {
|
||||
AddedGames.single(context, folder.path)?.let { SteamMatch.resolve(context, folder.path, it.exe, it.name) }
|
||||
}
|
||||
// A GOG or Epic game installed before its sidecar kept the store's list: read it once from the store.
|
||||
val store = com.droiddeck.launcher.stores.Store.byId(game.source)
|
||||
if (folder != null && (store == com.droiddeck.launcher.stores.Store.GOG || store == com.droiddeck.launcher.stores.Store.EPIC)) StoreListBackfill.fill(context, folder)
|
||||
// Its Steam app, when the client never saw it: Steam asked anonymously now if the user is
|
||||
// waiting on this game (a pass over every game asks for all of them in one go, [sweep]).
|
||||
if (asked && online(context)) steamAppOf(context, game)?.let { SteamAppInfo.lookup(context, listOf(it)) }
|
||||
val findings = findings(context, game)
|
||||
val catalog = (catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name } ?: return
|
||||
@@ -249,7 +195,6 @@ object AutoComponents {
|
||||
queueDownload(context, id, asked, inSession)
|
||||
missing.add(id)
|
||||
}
|
||||
// In a session the launch waits a little for these (droiddeck-wincomponents reads the list).
|
||||
if (inSession) Pending.set(context, key, missing)
|
||||
val before = WinComponents.selection(context, key).auto
|
||||
if (before.keys != kept.keys) {
|
||||
@@ -259,7 +204,6 @@ object AutoComponents {
|
||||
changes.value = changes.value + 1
|
||||
}
|
||||
|
||||
/** One component downloaded and installed, then turned on for every game waiting on it. */
|
||||
private fun download(context: Context, id: String, asked: Boolean, inSession: Boolean = false) {
|
||||
val catalog = catalogOf(context, true)?.associateBy { it.name } ?: run { Pending.drop(context, id); return }
|
||||
if (id !in installedOf(context)) {
|
||||
@@ -279,10 +223,6 @@ object AutoComponents {
|
||||
Pending.drop(context, id)
|
||||
}
|
||||
|
||||
/**
|
||||
* The components still being readied for games installed in the session, where the launch
|
||||
* reads them (~/.config/droiddeck/wincomponents-pending.json in the runtime).
|
||||
*/
|
||||
internal object Pending {
|
||||
private fun file(context: Context) = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.config/droiddeck/wincomponents-pending.json")
|
||||
|
||||
@@ -315,11 +255,9 @@ object AutoComponents {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- the list, kept per game ----
|
||||
|
||||
private const val FINDINGS = "wincomp-findings.json"
|
||||
|
||||
/** What the list is read from, by modification time: a change means it is worked out again. */
|
||||
internal fun signature(context: Context, game: Library.SteamGame): String {
|
||||
val folder = game.gameFiles
|
||||
val parts = listOfNotNull(
|
||||
@@ -334,7 +272,6 @@ object AutoComponents {
|
||||
return parts.joinToString("|")
|
||||
}
|
||||
|
||||
/** [game]'s list: the one kept when nothing it is read from changed, else worked out again and kept. Worker only. */
|
||||
internal fun findings(context: Context, game: Library.SteamGame): List<WinCompSources.Finding> {
|
||||
val key = appKey(game) ?: return emptyList()
|
||||
val sig = signature(context, game)
|
||||
@@ -345,7 +282,6 @@ object AutoComponents {
|
||||
return fresh
|
||||
}
|
||||
|
||||
/** The list kept for [appKey], without working anything out; null before the first time. */
|
||||
fun cachedFindings(context: Context, appKey: String): List<WinCompSources.Finding>? =
|
||||
readFindings(context).optJSONObject(appKey)?.let { decode(it.optJSONArray("findings")) }
|
||||
|
||||
@@ -374,34 +310,21 @@ object AutoComponents {
|
||||
WinCompSources.Finding(o.optString("component").takeIf { it.isNotEmpty() }, o.optString("original"), origin, o.optBoolean("auto"), args)
|
||||
}
|
||||
|
||||
// ---- when ----
|
||||
|
||||
/** Before a launch from DroidDeck: nothing but a queued look (it waits for the session to end). */
|
||||
fun beforeLaunch(context: Context, game: Library.SteamGame) = queueGame(context, game, asked = false)
|
||||
|
||||
/** After an install or an add: the user did it, so it does not wait on a metered network. */
|
||||
fun refreshLater(context: Context, game: Library.SteamGame) = queueGame(context, game, asked = true)
|
||||
|
||||
/**
|
||||
* Every game, whatever its source, at app start and after each session (Steam installs its
|
||||
* games without a word to DroidDeck; older GOG and Epic installs get their list read once):
|
||||
* only queued, one game at a time, behind anything asked for, under the same conditions. A
|
||||
* game whose files did not change costs a look at their times.
|
||||
*/
|
||||
fun sweep(context: Context, games: List<Library.SteamGame>) {
|
||||
// First every Steam app these games are that the client never saw, asked of Steam in one
|
||||
// connection; then each game's list.
|
||||
val apps = games.mapNotNull { steamAppOf(context, it) }.distinct()
|
||||
if (apps.isNotEmpty() && SteamAppInfo.needLookup(context, apps).isNotEmpty()) enqueue(context, Job(null, null, false, seq.incrementAndGet(), pics = apps))
|
||||
games.forEach { queueGame(context, it, asked = false) }
|
||||
}
|
||||
|
||||
/** The Steam app whose list a game takes: a Steam game's own, or an added game's match. */
|
||||
private fun steamAppOf(context: Context, game: Library.SteamGame): Int? =
|
||||
if (game.library != Library.ADDED) game.appId.takeIf { it > 0 }
|
||||
else game.gameFiles?.let { SteamMatch.get(context, it.path) }?.appId
|
||||
|
||||
/** The default network is there and validated (reaches the internet). */
|
||||
fun isOnline(context: Context): Boolean {
|
||||
val cm = context.getSystemService(ConnectivityManager::class.java) ?: return false
|
||||
val caps = cm.getNetworkCapabilities(cm.activeNetwork ?: return false) ?: return false
|
||||
@@ -409,7 +332,6 @@ object AutoComponents {
|
||||
caps.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED)
|
||||
}
|
||||
|
||||
/** Battery saver, thermal status moderate or worse, or a metered network. */
|
||||
private fun constrained(context: Context): Boolean {
|
||||
val power = context.getSystemService(PowerManager::class.java)
|
||||
if (power?.isPowerSaveMode == true) return true
|
||||
|
||||
@@ -11,27 +11,12 @@ import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.net.URLEncoder
|
||||
|
||||
/**
|
||||
* Box art for the emulators' games, found and kept on the device: the front end shows a disc image
|
||||
* with nothing but its emulator's logo otherwise.
|
||||
*
|
||||
* In order: the name of the file against RetroArch's thumbnail collection for the system
|
||||
* (libretro-thumbnails, named after the standard disc-dump names - "Need for Speed - Underground 2
|
||||
* (USA)"), first exactly and then loosely (tags dropped, the same region preferred) against the
|
||||
* collection's list of names; then the disc's own ID, read from the image - PS2 serials against
|
||||
* xlenore/ps2-covers (what PCSX2 and ARMSX2 download from), GameCube/Wii IDs against GameTDB (what
|
||||
* Dolphin uses). A PS3 disc image gives its own PS3_GAME/ICON0.PNG first: the libretro PS3
|
||||
* collection is small. A cover is downloaded once into files/covers; a game none of them has is not
|
||||
* asked about again for a few days.
|
||||
*/
|
||||
object CoverArt {
|
||||
private const val TAG = "CoverArt"
|
||||
private const val MISS_RETRY_MS = 3L * 24 * 3600 * 1000
|
||||
private const val INDEX_TTL_MS = 14L * 24 * 3600 * 1000
|
||||
/** Downloads in one pass, so a first visit to a big library does not hold the network for long. */
|
||||
private const val MAX_PER_PASS = 40
|
||||
|
||||
/** The emulator's systems in libretro-thumbnails, in the order they are tried. */
|
||||
private val collections = mapOf(
|
||||
"rpcs3" to listOf("Sony_-_PlayStation_3"),
|
||||
"armsx2" to listOf("Sony_-_PlayStation_2"),
|
||||
@@ -44,14 +29,12 @@ object CoverArt {
|
||||
|
||||
private fun root(context: Context) = File(context.filesDir, "covers")
|
||||
|
||||
/** The file name, as the cover is kept under: a game keeps its art when its folder moves. */
|
||||
private fun keyOf(rom: Library.Rom): String =
|
||||
rom.hostPath.name.replace(Regex("[^A-Za-z0-9._() -]"), "_").take(150)
|
||||
|
||||
private fun coverFile(context: Context, rom: Library.Rom) = File(root(context), "${rom.emulatorId}/${keyOf(rom)}.img")
|
||||
private fun missFile(context: Context, rom: Library.Rom) = File(root(context), "${rom.emulatorId}/${keyOf(rom)}.miss")
|
||||
|
||||
/** A cover already on the device for this game, or null. */
|
||||
fun cached(context: Context, rom: Library.Rom): File? = coverFile(context, rom).takeIf { it.isFile && it.length() > 0 }
|
||||
|
||||
private fun wanted(context: Context, rom: Library.Rom): Boolean {
|
||||
@@ -60,10 +43,6 @@ object CoverArt {
|
||||
return !(miss.isFile && System.currentTimeMillis() - miss.lastModified() < MISS_RETRY_MS)
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks for covers for the games that have none, on the calling (background) thread. True when
|
||||
* at least one was found, so the caller rebuilds the list to show it.
|
||||
*/
|
||||
fun fetchMissing(context: Context, roms: List<Library.Rom>): Boolean {
|
||||
var found = false
|
||||
var tries = 0
|
||||
@@ -71,7 +50,6 @@ object CoverArt {
|
||||
if (!wanted(context, rom)) continue
|
||||
if (++tries > MAX_PER_PASS) break
|
||||
val target = coverFile(context, rom)
|
||||
// A PS3 disc carries its own cover (PS3_GAME/ICON0.PNG, not encrypted): no download.
|
||||
if (rom.emulatorId == "rpcs3" && try { copyPs3Icon(rom.hostPath, target) } catch (e: Exception) { false }) {
|
||||
Log.i(TAG, "${rom.name}: ICON0.PNG from the disc")
|
||||
missFile(context, rom).delete()
|
||||
@@ -93,13 +71,10 @@ object CoverArt {
|
||||
private fun findUrl(context: Context, rom: Library.Rom): String? {
|
||||
val name = rom.hostPath.nameWithoutExtension.removeSuffix(".dec")
|
||||
for (collection in collections.getValue(rom.emulatorId)) {
|
||||
// Exactly the dump name first: no listing needed.
|
||||
val exact = thumbnailUrl(collection, name)
|
||||
if (exists(exact)) return exact
|
||||
// Then loosely, against the collection's names.
|
||||
nearest(name, names(context, collection))?.let { return thumbnailUrl(collection, it) }
|
||||
}
|
||||
// The disc's own ID.
|
||||
return when (rom.emulatorId) {
|
||||
"armsx2" -> ps2Serial(rom.hostPath)?.let { "https://raw.githubusercontent.com/xlenore/ps2-covers/main/covers/default/$it.jpg" }
|
||||
"dolphin" -> nintendoDiscId(rom.hostPath)?.let { id ->
|
||||
@@ -110,18 +85,15 @@ object CoverArt {
|
||||
}?.takeIf { exists(it) }
|
||||
}
|
||||
|
||||
/** libretro-thumbnails replaces these in a title's file name. */
|
||||
private fun thumbName(title: String) = title.replace(Regex("[&*/:`<>?\\\\|\"]"), "_")
|
||||
|
||||
private fun thumbnailUrl(collection: String, title: String) =
|
||||
"https://raw.githubusercontent.com/libretro-thumbnails/$collection/master/Named_Boxarts/" +
|
||||
URLEncoder.encode("${thumbName(title)}.png", "UTF-8").replace("+", "%20")
|
||||
|
||||
// ---- loose matching ------------------------------------------------------------------------
|
||||
|
||||
private fun tags(name: String): List<String> = Regex("[(\\[]([^)\\]]*)[)\\]]").findAll(name).map { it.groupValues[1].lowercase() }.toList()
|
||||
|
||||
/** A title without its tags, articles and punctuation: "Legend of Zelda, The (USA)" = "legend of zelda". */
|
||||
private fun base(name: String): String = name
|
||||
.replace(Regex("\\s*[(\\[][^)\\]]*[)\\]]"), " ")
|
||||
.lowercase()
|
||||
@@ -139,7 +111,6 @@ object CoverArt {
|
||||
return same.firstOrNull { region in tags(it) } ?: same.firstOrNull { "usa" in tags(it) } ?: same.first()
|
||||
}
|
||||
|
||||
/** The titles in a collection's Named_Boxarts (no extension), kept for a fortnight. */
|
||||
private fun names(context: Context, collection: String): List<String> {
|
||||
val cache = File(root(context), "index-$collection.txt")
|
||||
if (cache.isFile && System.currentTimeMillis() - cache.lastModified() < INDEX_TTL_MS) return cache.readLines()
|
||||
@@ -161,12 +132,7 @@ object CoverArt {
|
||||
|
||||
private fun cachedOr(cache: File): List<String> = if (cache.isFile) cache.readLines() else emptyList()
|
||||
|
||||
// ---- disc IDs ------------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* A file's bytes from an ISO 9660 image by path ("PS3_GAME/ICON0.PNG"), or null. Primary volume
|
||||
* names only (upper case, ";1" suffix), which is what PS2 and PS3 discs use.
|
||||
*/
|
||||
private fun isoFile(file: File, path: String, maxSize: Int): ByteArray? {
|
||||
if (!file.name.endsWith(".iso", ignoreCase = true)) return null
|
||||
RandomAccessFile(file, "r").use { f ->
|
||||
@@ -208,14 +174,12 @@ object CoverArt {
|
||||
return if (bounds.outWidth > 0 && tmp.renameTo(target)) true else { tmp.delete(); false }
|
||||
}
|
||||
|
||||
/** "SLUS-21065" from a PS2 .iso's SYSTEM.CNF (BOOT2 = cdrom0:\SLUS_210.65;1), or null. */
|
||||
private fun ps2Serial(file: File): String? {
|
||||
val cnf = String(isoFile(file, "SYSTEM.CNF", 4096) ?: return null, Charsets.US_ASCII)
|
||||
val m = Regex("BOOT2\\s*=\\s*cdrom0:\\\\?([A-Z]{4})_(\\d{3})\\.(\\d{2})").find(cnf) ?: return null
|
||||
return "${m.groupValues[1]}-${m.groupValues[2]}${m.groupValues[3]}"
|
||||
}
|
||||
|
||||
/** The six-character ID of a GameCube/Wii disc image (.iso/.gcm, or .wbfs), or null. */
|
||||
private fun nintendoDiscId(file: File): String? {
|
||||
val offset = when (file.extension.lowercase()) { "iso", "gcm" -> 0L; "wbfs" -> 0x200L; else -> return null }
|
||||
RandomAccessFile(file, "r").use { f ->
|
||||
@@ -225,7 +189,6 @@ object CoverArt {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- network -------------------------------------------------------------------------------
|
||||
|
||||
private fun open(url: String, method: String = "GET"): HttpURLConnection =
|
||||
(URL(url).openConnection() as HttpURLConnection).apply {
|
||||
@@ -245,7 +208,6 @@ object CoverArt {
|
||||
if (c.responseCode != 200) { c.disconnect(); null } else c.inputStream.bufferedReader().use { it.readText() }
|
||||
} catch (e: Exception) { Log.w(TAG, "$url: $e"); null }
|
||||
|
||||
/** Saves the image at [url] to [target] if it really is an image. */
|
||||
private fun download(url: String, target: File): Boolean = try {
|
||||
val c = open(url)
|
||||
if (c.responseCode != 200) { c.disconnect(); false } else {
|
||||
|
||||
@@ -3,49 +3,25 @@ package com.droiddeck.launcher.frontend
|
||||
import java.io.File
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* Best-effort detection of the Windows redistributables a game bundles, by scanning its install
|
||||
* folder for the redist installers Steam/Epic/GOG ship (`_CommonRedist/`, `_Redist/`,
|
||||
* `Redistributables/`, loose `vcredist_x64.exe`, …) and mapping them to entries in our component
|
||||
* catalog (WinComponents, Bannerlator's components.json `name` keys). The result drives the
|
||||
* Recommended part of a game's Windows components; the user still switches each one on.
|
||||
* Bannerlator's detector, unchanged but for this note and its package.
|
||||
*
|
||||
* Wine-aware: keeps the redists that actually matter under Wine/DXVK (VC++ runtimes, .NET, PhysX,
|
||||
* OpenAL, XACT, XNA, GFWL) and SKIPS the ones DXVK/VKD3D already provide (DX12 Agility SDK) or that
|
||||
* aren't our components (anti-cheat, Rockstar/Social-Club/launcher setups). Never throws; returns an
|
||||
* empty list on anything unexpected. Pure filesystem — no network, no Android deps (unit-testable).
|
||||
*/
|
||||
object DependencyDetector {
|
||||
|
||||
/** How a recommendation was found — drives the UI's "recommended vs optional" split. */
|
||||
enum class Kind {
|
||||
/** The game bundles the redist installer (in _CommonRedist etc.) — meant to be installed. */
|
||||
BUNDLED,
|
||||
/** A runtime DLL the game ships loose — usually already works from the game folder; install
|
||||
* only if the game misbehaves. */
|
||||
SHIPPED,
|
||||
/** Steam installs it with the game from Steamworks Shared ([SteamRedists]). */
|
||||
STEAM,
|
||||
}
|
||||
|
||||
/** A recommended component: the catalog [componentName] to install, a display [label], the on-disk
|
||||
* redist that triggered it ([reason]), and [kind] (bundled installer vs shipped DLL). */
|
||||
data class Recommendation(val componentName: String, val label: String, val reason: String, val kind: Kind = Kind.BUNDLED)
|
||||
|
||||
private const val MAX_DEPTH = 5
|
||||
private const val MAX_ENTRIES = 8000 // cost guard against giant game trees
|
||||
private const val MAX_ENTRIES = 8000
|
||||
|
||||
/** A loose VC++ installer with no year in its path — resolved to "latest" only if no specific
|
||||
* vcredistYYYY was found anywhere (else it's just a duplicate of the versioned one). */
|
||||
private const val VCREDIST_LOOSE = "__vcredist_loose"
|
||||
|
||||
/** Directory names that are redist containers worth descending into. */
|
||||
private val REDIST_DIR_RE = Regex(
|
||||
"""(?i)^(_?commonredist|_?redist(ributables)?|__?installer|vcredist|vc_redist|directx|direct_x|physx|openal|dotnet(fx)?|\.net|xna|xact|redist|support)$"""
|
||||
)
|
||||
|
||||
/** Skip whole subtrees that are never our components. */
|
||||
private val SKIP_DIR_RE = Regex("""(?i)^(d3d12.*|.*agility.*|dxvk|vkd3d|battleye|easyanticheat|eac|anticheat)$""")
|
||||
|
||||
private val YEAR_TO_VCREDIST = mapOf(
|
||||
@@ -70,7 +46,6 @@ object DependencyDetector {
|
||||
"dotnetcoredesktop8" to ".NET Desktop 8",
|
||||
)
|
||||
|
||||
/** Preferred install order (runtimes others may depend on first). */
|
||||
private val INSTALL_ORDER = listOf(
|
||||
"vcredist2005", "vcredist2008", "vcredist2010", "vcredist2012", "vcredist2013",
|
||||
"vcredist2015", "vcredist2019", "vcredist2022",
|
||||
@@ -79,13 +54,6 @@ object DependencyDetector {
|
||||
"d3dx9", "d3dx11", "xact", "xact_x64", "xna31", "xna40", "physx", "oalinst", "XLiveRedist",
|
||||
)
|
||||
|
||||
/**
|
||||
* Detect from the .exe the user picked, resolving the game root first: walk up from the exe's
|
||||
* folder (bounded) to the nearest ancestor that holds a redist container (`_CommonRedist`, …) at
|
||||
* its top level, and scan from there — so a nested exe (`…/Game/bin/x.exe`) still finds a root-level
|
||||
* `_CommonRedist`, without over-reaching into a shared `steamapps/common` (which has no redist
|
||||
* container of its own). Falls back to scanning the exe's own folder.
|
||||
*/
|
||||
fun detectForExe(exeFile: File): List<Recommendation> {
|
||||
val start = exeFile.absoluteFile.parentFile ?: return emptyList()
|
||||
var d: File? = start
|
||||
@@ -101,19 +69,14 @@ object DependencyDetector {
|
||||
return detect(start)
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan [gameDir] and return the recommended components, de-duplicated (first reason wins), in a
|
||||
* stable install-friendly order. Empty when nothing is detected or [gameDir] isn't a directory.
|
||||
*/
|
||||
fun detect(gameDir: File): List<Recommendation> {
|
||||
if (!gameDir.isDirectory) return emptyList()
|
||||
val hits = LinkedHashMap<String, Recommendation>() // componentName -> first recommendation
|
||||
val hits = LinkedHashMap<String, Recommendation>()
|
||||
var visited = 0
|
||||
|
||||
fun consider(f: File, isDir: Boolean, insideRedist: Boolean) {
|
||||
val name = f.name.lowercase(Locale.US)
|
||||
val path = f.path.replace('\\', '/').lowercase(Locale.US)
|
||||
// Bundled = in a redist container or an installer (exe/msi/cab); shipped = a loose runtime DLL.
|
||||
val kind = if (insideRedist || isDir || name.endsWith(".exe") || name.endsWith(".msi") || name.endsWith(".cab"))
|
||||
Kind.BUNDLED else Kind.SHIPPED
|
||||
for (comp in classify(path, name, isDir)) {
|
||||
@@ -121,7 +84,7 @@ object DependencyDetector {
|
||||
if (existing == null) {
|
||||
hits[comp] = Recommendation(comp, LABELS[comp] ?: comp, relativeReason(gameDir, f), kind)
|
||||
} else if (existing.kind == Kind.SHIPPED && kind == Kind.BUNDLED) {
|
||||
hits[comp] = existing.copy(kind = Kind.BUNDLED) // a bundled installer outranks a shipped DLL
|
||||
hits[comp] = existing.copy(kind = Kind.BUNDLED)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -134,17 +97,11 @@ object DependencyDetector {
|
||||
val lower = f.name.lowercase(Locale.US)
|
||||
if (f.isDirectory) {
|
||||
if (SKIP_DIR_RE.matches(lower)) continue
|
||||
// Unity's <Game>_Data/Managed holds the game's own Mono assemblies, not a .NET
|
||||
// Framework to install.
|
||||
if (lower == "managed" && dir.name.endsWith("_Data", ignoreCase = true)) continue
|
||||
val isRedistDir = insideRedist || REDIST_DIR_RE.matches(lower)
|
||||
if (isRedistDir) consider(f, isDir = true, insideRedist = true)
|
||||
// Aggressive coverage: descend redist containers fully, and otherwise sweep the game
|
||||
// tree a few levels deep so runtime libraries the game ships (in bin/, etc.) are seen.
|
||||
if (isRedistDir || depth < 3) walk(f, depth + 1, isRedistDir)
|
||||
} else {
|
||||
// Classify installers + runtime libraries (.dll/.exe/.msi) anywhere in the scanned
|
||||
// tree; other files are ignored. Recommendations are advisory, so cast a wide net.
|
||||
val ext = lower.substringAfterLast('.', "")
|
||||
if (insideRedist || ext == "dll" || ext == "exe" || ext == "msi") consider(f, isDir = false, insideRedist = insideRedist)
|
||||
}
|
||||
@@ -160,20 +117,13 @@ object DependencyDetector {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The catalog components one installer stands for, by its path ("_CommonRedist/vcredist/2015/
|
||||
* vc_redist.x64.exe", "DXSETUP.exe"): what a store's install list names. A VC++ installer
|
||||
* with no year is the latest; empty for one that is none of ours.
|
||||
*/
|
||||
fun componentsFor(path: String): List<String> {
|
||||
val p = path.replace('\\', '/').lowercase(Locale.US)
|
||||
return classify(p, p.substringAfterLast('/'), isDir = false).map { if (it == VCREDIST_LOOSE) "vcredist2022" else it }
|
||||
}
|
||||
|
||||
/** The name the catalog component [name] goes by, for a reason line. */
|
||||
fun label(name: String): String = LABELS[name] ?: name
|
||||
|
||||
/** A loose VC++ installer resolves to the latest 14.x only if no specific vcredistYYYY was found. */
|
||||
private fun resolveLooseVcredist(hits: LinkedHashMap<String, Recommendation>) {
|
||||
val loose = hits.remove(VCREDIST_LOOSE) ?: return
|
||||
val hasSpecific = hits.keys.any { it in YEAR_TO_VCREDIST.values }
|
||||
@@ -186,52 +136,38 @@ object DependencyDetector {
|
||||
return if (p.startsWith("$g/")) p.substring(g.length + 1) else f.name
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a redist file/dir (its full lowercased [path], leaf [name], and whether it [isDir]) to
|
||||
* catalog component name(s). Empty for things we deliberately skip.
|
||||
*/
|
||||
private fun classify(path: String, name: String, isDir: Boolean): List<String> {
|
||||
// Hard skips first — DX12 is provided by DXVK/VKD3D; these aren't our components.
|
||||
if (path.contains("d3d12") || path.contains("agility") ||
|
||||
path.contains("battleye") || path.contains("anticheat") || path.contains("easyanticheat") ||
|
||||
name.contains("socialclub") || name.contains("social-club") ||
|
||||
name.contains("rockstar") || name == "setup.exe"
|
||||
) return emptyList()
|
||||
|
||||
// Visual C++ runtimes — most important. Year comes from the path context.
|
||||
if (path.contains("vcredist") || path.contains("vc_redist") || name.startsWith("vcredist") || name.startsWith("vc_redist")) {
|
||||
val year = YEAR_TO_VCREDIST.keys.firstOrNull { path.contains(it) }
|
||||
return when {
|
||||
year != null -> listOf(YEAR_TO_VCREDIST.getValue(year))
|
||||
isDir -> emptyList() // bare "vcredist" container — wait for the year subfolder / installer
|
||||
else -> listOf(VCREDIST_LOOSE) // loose installer, no year → resolved post-walk
|
||||
isDir -> emptyList()
|
||||
else -> listOf(VCREDIST_LOOSE)
|
||||
}
|
||||
}
|
||||
// VC++ runtime DLL the game ships (msvcp140.dll → 2015-2022, msvcp120.dll → 2013, …).
|
||||
VCRUNTIME_DLL.entries.firstOrNull { name.startsWith(it.key) }?.let { return listOf(it.value) }
|
||||
if (path.contains("openal") || name.startsWith("oalinst") || name == "openal32.dll" || name == "wrap_oal.dll") return listOf("oalinst")
|
||||
if (path.contains("physx") || name.startsWith("physx")) return listOf("physx")
|
||||
if (path.contains("xact") || name.startsWith("xactengine") || name.startsWith("x3daudio")) return listOf("xact", "xact_x64")
|
||||
// Games for Windows Live — the redist folder, OR a GFWL library the game ships (xlive.dll,
|
||||
// Codemasters' dbxLive32/64, gfwl*): GFWL titles need XLiveRedist to run even when they don't
|
||||
// bundle the redist itself.
|
||||
if (path.contains("xliveredist") || name.contains("xlive") || name.startsWith("gfwl") || name.startsWith("dbxlive")) {
|
||||
return listOf("XLiveRedist")
|
||||
}
|
||||
if (path.contains("xna")) return listOf(if (path.contains("3.1") || path.contains("3_1") || path.contains("v31")) "xna31" else "xna40")
|
||||
// .NET — Framework and Core/Desktop runtimes.
|
||||
if (path.contains("dotnet") || path.contains(".net") || name.startsWith("ndp") || name.startsWith("dotnetfx") || name.contains("windowsdesktop-runtime")) {
|
||||
val comp = dotnetComponent("$path $name")
|
||||
return when {
|
||||
comp != null -> listOf(comp)
|
||||
isDir -> emptyList() // bare ".NET" container — wait for the versioned installer
|
||||
else -> listOf("dotnet48") // unlabeled .NET Framework installer file → sensible default
|
||||
isDir -> emptyList()
|
||||
else -> listOf("dotnet48")
|
||||
}
|
||||
}
|
||||
// DirectX 11 helper DLLs the game ships (d3dx11_43.dll).
|
||||
if (D3DX11_RE.matches(name)) return listOf("d3dx11")
|
||||
// DirectX 9 helper DLLs / d3dcompiler / June-2010 DX redist (DXVK provides core d3d9 but NOT
|
||||
// these helper DLLs).
|
||||
if (name.startsWith("dxsetup") || name.startsWith("dxwebsetup") ||
|
||||
D3DX9_RE.matches(name) || D3DCOMPILER_RE.matches(name) ||
|
||||
(path.contains("directx") && name.endsWith(".exe"))
|
||||
@@ -239,7 +175,6 @@ object DependencyDetector {
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
/** Runtime DLL prefix → the VC++ redistributable that provides it (checked with startsWith). */
|
||||
private val VCRUNTIME_DLL = linkedMapOf(
|
||||
"vcruntime140" to "vcredist2022", "msvcp140" to "vcredist2022", "msvcr140" to "vcredist2022", "concrt140" to "vcredist2022",
|
||||
"msvcp120" to "vcredist2013", "msvcr120" to "vcredist2013",
|
||||
@@ -252,7 +187,6 @@ object DependencyDetector {
|
||||
private val D3DX11_RE = Regex("""d3dx11_\d+\.dll""")
|
||||
private val D3DCOMPILER_RE = Regex("""d3dcompiler_\d+\.dll""")
|
||||
|
||||
/** Resolve a .NET component from installer/path text, or null when no version is discernible. */
|
||||
private fun dotnetComponent(s: String): String? = when {
|
||||
s.contains("desktop-runtime-8") || Regex("""\b8\.\d""").containsMatchIn(s) -> "dotnetcoredesktop8"
|
||||
s.contains("desktop-runtime-7") || Regex("""\b7\.\d""").containsMatchIn(s) -> "dotnetcoredesktop7"
|
||||
@@ -264,6 +198,6 @@ object DependencyDetector {
|
||||
s.contains("dotnetfx45") || s.contains("ndp45") || s.contains("4.5") -> "dotnet45"
|
||||
s.contains("dotnetfx40") || s.contains("ndp40") || s.contains("4.0") -> "dotnet40"
|
||||
s.contains("dotnetfx35") || s.contains("3.5") -> "dotnet35"
|
||||
else -> null // no version signal (e.g. a bare "DotNet" container dir)
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
@@ -2,26 +2,15 @@ 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",
|
||||
@@ -32,7 +21,6 @@ object GameExePicker {
|
||||
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*|""" +
|
||||
@@ -41,10 +29,8 @@ object GameExePicker {
|
||||
"""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() })
|
||||
@@ -54,11 +40,6 @@ object GameExePicker {
|
||||
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
|
||||
@@ -86,31 +67,23 @@ object GameExePicker {
|
||||
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
|
||||
@@ -125,6 +98,5 @@ object GameExePicker {
|
||||
|
||||
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() }
|
||||
}
|
||||
@@ -10,7 +10,6 @@ import java.io.File
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
/** Runs while DroidDeck's process is alive, including downloads in a background Steam session. */
|
||||
object GameFileSync {
|
||||
private val worker = Executors.newSingleThreadScheduledExecutor { task -> Thread(task, "game-file-sync").apply { isDaemon = true } }
|
||||
private fun prefs(context: Context) = context.getSharedPreferences("game_files", Context.MODE_PRIVATE)
|
||||
@@ -39,7 +38,6 @@ object GameFileSync {
|
||||
|
||||
@Synchronized private fun sync(context: Context, folder: File) {
|
||||
check(LinuxRuntime.isInstalled(context)) { context.getString(R.string.game_sync_err_runtime) }
|
||||
// A disconnected library must not be interpreted as a mass uninstall.
|
||||
check(File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps").isDirectory) { context.getString(R.string.game_sync_err_steam_library) }
|
||||
val storage = GameStorage.effective(context)
|
||||
val storageSetting = SessionPrefs.gameStorage(context)
|
||||
|
||||
@@ -11,14 +11,12 @@ import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.io.InputStream
|
||||
|
||||
/** Small, portable launch files for frontends that scan ROM folders. No guest paths or commands. */
|
||||
object GameFiles {
|
||||
const val EXTENSION = "steam"
|
||||
private const val MAX_BYTES = 128
|
||||
private const val INVENTORY = ".droiddeck-sync.json"
|
||||
private const val FORMAT = "droiddeck-game-files-v1"
|
||||
|
||||
/** Called on a worker: content providers and shared storage may block. */
|
||||
fun readIntent(context: Context, request: Intent): String? = runCatching {
|
||||
if (request.action != Intent.ACTION_VIEW) return null
|
||||
val uri = request.data ?: return null
|
||||
@@ -36,7 +34,6 @@ object GameFiles {
|
||||
}.getOrNull()
|
||||
|
||||
fun read(stream: InputStream): String? {
|
||||
// An untrusted URI must not make us buffer an arbitrary ROM or parse a command.
|
||||
val bytes = ByteArray(MAX_BYTES + 1)
|
||||
var count = 0
|
||||
while (count < bytes.size) {
|
||||
@@ -84,7 +81,6 @@ object GameFiles {
|
||||
} else target
|
||||
}
|
||||
|
||||
/** Cocoon matches icons in its data folder's images directory. Never replace custom art. */
|
||||
private fun exportArt(context: Context, folder: File, game: Library.SteamGame) {
|
||||
val art = listOfNotNull(game.icon, game.art).firstOrNull {
|
||||
it.isFile && it.extension.lowercase() in listOf("jpg", "jpeg", "png", "webp")
|
||||
@@ -100,7 +96,6 @@ object GameFiles {
|
||||
if (!target.exists()) AtomicFile(target).writeBytes(art.readBytes())
|
||||
}
|
||||
|
||||
/** Only remove files in our inventory whose content is still exactly what we wrote. */
|
||||
@Synchronized fun sync(context: Context, folder: File, games: List<Library.SteamGame>) {
|
||||
require(folder.isDirectory) { context.getString(R.string.gfiles_folder_unavailable) }
|
||||
val inventory = child(context, folder, INVENTORY)
|
||||
@@ -119,21 +114,17 @@ object GameFiles {
|
||||
else exportTarget(context, folder, game, name)
|
||||
val text = contents(game.gameIdString)
|
||||
val existed = target.exists()
|
||||
// Keep an edited export without letting it block the rest of the library sync.
|
||||
val owned = inventoryOwns(context, folder, previous, target, game.gameIdString)
|
||||
val file = if (owned && target.exists() &&
|
||||
!matches(target, text)) target else exportNamed(context, folder, game, target.name)
|
||||
if (!existed || owned) next.put(file.name, game.gameIdString)
|
||||
file
|
||||
}
|
||||
// Write new exports before pruning; a failed write must not remove old launch files.
|
||||
for (name in previous.keys()) {
|
||||
val id = previous.getString(name)
|
||||
if (!next.has(name) && name.endsWith(".$EXTENSION") && GameLaunchLink.validId(id)) {
|
||||
val file = child(context, folder, name)
|
||||
if (matches(file, contents(id))) {
|
||||
// Android shared storage is often case insensitive. A case-only rename may
|
||||
// still resolve to the live export, which must not be pruned as an old file.
|
||||
val retained = exports.any { java.nio.file.Files.isSameFile(it.toPath(), file.toPath()) }
|
||||
if (!retained) check(file.delete()) { context.getString(R.string.gfiles_remove_failed, name) }
|
||||
}
|
||||
|
||||
@@ -2,65 +2,35 @@ 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
|
||||
@@ -68,7 +38,6 @@ object GameIdentifier {
|
||||
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
|
||||
@@ -93,27 +62,19 @@ object GameIdentifier {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 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)\(\s*(tm|r|c)\s*\)"""), "")
|
||||
s = s.replace(":", " - ")
|
||||
s = s.replace(Regex("""[\\/]"""), " ")
|
||||
s = s.replace(Regex("""["*?<>|]"""), "")
|
||||
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
|
||||
s = s.replace(Regex("""\s+"""), " ").trim()
|
||||
return s.trim(' ', '-').trim()
|
||||
}
|
||||
|
||||
// ── 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
|
||||
@@ -126,12 +87,9 @@ object GameIdentifier {
|
||||
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
|
||||
@@ -139,12 +97,6 @@ object GameIdentifier {
|
||||
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(
|
||||
@@ -166,13 +118,6 @@ object GameIdentifier {
|
||||
|
||||
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
|
||||
@@ -183,7 +128,6 @@ object GameIdentifier {
|
||||
} ?: 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 ->
|
||||
@@ -200,7 +144,6 @@ object GameIdentifier {
|
||||
|
||||
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")
|
||||
@@ -214,75 +157,42 @@ object GameIdentifier {
|
||||
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"
|
||||
if (rest.isEmpty()) return true
|
||||
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
|
||||
if (!c.isLetterOrDigit() || c.isUpperCase()) return true
|
||||
}
|
||||
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) ||
|
||||
@@ -293,14 +203,12 @@ object GameIdentifier {
|
||||
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 = 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(" ")
|
||||
@@ -308,20 +216,16 @@ object GameIdentifier {
|
||||
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()
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.droiddeck.launcher.frontend
|
||||
|
||||
/** External callers can select a game, never a guest path or arbitrary Steam command. */
|
||||
object GameLaunchLink {
|
||||
private val idPattern = Regex("[1-9][0-9]{0,19}")
|
||||
private val linkPattern = Regex("droiddeck://game/([1-9][0-9]{0,19})")
|
||||
|
||||
@@ -42,7 +42,6 @@ object GameShortcuts {
|
||||
if (!requested) Toast.makeText(activity, R.string.game_shortcut_unsupported, Toast.LENGTH_LONG).show()
|
||||
}
|
||||
|
||||
/** Standard shortcut picker result, understood by launchers that import Android shortcuts. */
|
||||
fun result(activity: Activity, game: Library.SteamGame): Intent =
|
||||
activity.getSystemService(ShortcutManager::class.java).createShortcutResultIntent(info(activity, game))
|
||||
}
|
||||
@@ -8,15 +8,6 @@ import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
import java.io.File
|
||||
import java.util.zip.CRC32
|
||||
|
||||
/**
|
||||
* Games folders (the roots earlier builds let the user add in Steam settings) become what the
|
||||
* Games tab's "Add all games in this folder" makes: one entry per game ([AddedExes]). Everything
|
||||
* a game had is keyed by its own folder and stays as it was - the chosen exe, the shortcut appid,
|
||||
* the name, Start in, launch options, art choices, a removal. The roots stay bound into the
|
||||
* session at the same guest paths ([SessionPrefs.gameFolderBinds]), so every exe keeps its path
|
||||
* inside the session and every Steam shortcut its target; they are no longer Steam libraries.
|
||||
* Runs whenever saved roots remain (so twice is the same as once) and clears them after.
|
||||
*/
|
||||
object GamesFolderMigration {
|
||||
private const val TAG = "GamesFolderMigration"
|
||||
|
||||
@@ -26,7 +17,6 @@ object GamesFolderMigration {
|
||||
if (dirs.isEmpty()) return
|
||||
val roots = legacyRoots(SessionPrefs.gameFolderBinds(context).map { it.first } + dirs)
|
||||
.filter { root -> root.host.path in dirs }
|
||||
// The binds first: a game's guest path (and with it the shortcut's appid) depends on them.
|
||||
SessionPrefs.setGameFolderBinds(context, SessionPrefs.gameFolderBinds(context) + roots.map { it.host.path to it.guest })
|
||||
val removed = SessionPrefs.removedAddedGames(context).toSet()
|
||||
val entries = AddedExes.list(context).map { it.folder }.toMutableSet()
|
||||
@@ -50,10 +40,6 @@ object GamesFolderMigration {
|
||||
SessionPrefs.setGamesFoldersMigrated(context)
|
||||
}
|
||||
|
||||
/**
|
||||
* The guest paths earlier builds gave Games folders: /root/Games/<folder name>, with a short
|
||||
* hash of the host path when two share a name. Kept exactly, so nothing moves in the session.
|
||||
*/
|
||||
internal fun legacyRoots(paths: List<String>): List<AddedGames.Root> {
|
||||
val hosts = paths.distinct().map { File(it) }
|
||||
val names = hosts.groupingBy { it.name.lowercase() }.eachCount()
|
||||
|
||||
@@ -8,42 +8,24 @@ import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.session.SecondaryLibrary
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* What the front end lists: the Steam client's installed games (from its own appmanifests, both
|
||||
* libraries) and each emulator's games (files in the ROMs folder, by extension, with a system
|
||||
* folder as a hint). Read on a worker thread; nothing here is cached beyond one screen refresh.
|
||||
*/
|
||||
object Library {
|
||||
/** [gameId] is what steam://rungameid/ takes: the appid for a Steam title, the shortcut id for an added game. */
|
||||
/**
|
||||
* [art] is the portrait capsule; [hero] the wide banner Steam shows above a game's page, when
|
||||
* the client has cached one. [lastPlayed] is Steam's own "LastPlayed" (unix seconds), 0 = never.
|
||||
*/
|
||||
class SteamGame(
|
||||
val appId: Int, val name: String, val art: File?, val library: String, val gameId: Long = appId.toLong(),
|
||||
val hero: File? = null, val lastPlayed: Long = 0L,
|
||||
val gameFiles: File? = null, val protonPrefix: File? = null,
|
||||
val icon: File? = null,
|
||||
/** Where the game came from: [SOURCE_STEAM], a store's id (gog, epic, amazon) or [ADDED] for a folder the user added. */
|
||||
val source: String = SOURCE_STEAM,
|
||||
/** The store's own id for a store install; null otherwise. */
|
||||
val storeId: String? = null,
|
||||
) {
|
||||
/** Decimal form used by Steam links and Android shortcuts, including unsigned shortcut ids. */
|
||||
val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId)
|
||||
/** Key used by per-game environment and Windows-component profiles. */
|
||||
val profileKey: String get() = if (library == ADDED) java.lang.Integer.toUnsignedString(appId) else appId.toString()
|
||||
}
|
||||
/** The [SteamGame.library] of a game added to the library rather than installed by Steam, and the [SteamGame.source] of a plain added folder. */
|
||||
const val ADDED = "added"
|
||||
/** The [SteamGame.source] of a title Steam itself installed. */
|
||||
const val SOURCE_STEAM = "steam"
|
||||
|
||||
class Rom(val name: String, val hostPath: File, val guestPath: String, val emulatorId: String, val art: File? = null)
|
||||
class Emulator(val id: String, val name: String, val system: String, val program: String, val installed: Boolean, val games: List<Rom>) {
|
||||
/** The shown name of [system] when it is words rather than a platform name, else 0. */
|
||||
val systemRes: Int get() = if (id == "retroarch") R.string.content_system_many else 0
|
||||
/** The emulator's own icon, bundled (the runtime keeps them as theme SVGs the app cannot draw). */
|
||||
val iconRes: Int get() = when (id) {
|
||||
"rpcs3" -> R.drawable.emu_rpcs3; "armsx2" -> R.drawable.emu_pcsx2; "dolphin" -> R.drawable.emu_dolphin
|
||||
"duckstation" -> R.drawable.emu_duckstation; "melonds" -> R.drawable.emu_melonds; "cemu" -> R.drawable.emu_cemu
|
||||
@@ -51,34 +33,33 @@ object Library {
|
||||
}
|
||||
}
|
||||
|
||||
/** The client's own tools and runtimes live in steamapps beside the games; they are not titles. */
|
||||
private val NOT_GAMES = setOf(
|
||||
858280, // Proton 3.7
|
||||
961940, // Proton 3.16
|
||||
993090, // Lossless Scaling
|
||||
1054830, // Proton 4.2
|
||||
1070560, // Steam Linux Runtime 1.0
|
||||
1113280, // Proton 4.11
|
||||
1245040, // Proton 5.0
|
||||
1391110, // Steam Linux Runtime 2.0
|
||||
1420170, // Proton 5.13
|
||||
1493710, // Proton Experimental
|
||||
1580130, // Proton 6.3
|
||||
1628350, // Steam Linux Runtime 3.0
|
||||
1887720, // Proton 7
|
||||
2180100, // Proton Hotfix
|
||||
228980, // Steamworks Common Redistributables
|
||||
2348590, // Proton 8
|
||||
2805730, // Proton 9
|
||||
3029110, // Lepton
|
||||
3127680, // FEX
|
||||
3658110, // Proton 10
|
||||
4183110, // Steam Linux Runtime 4.0
|
||||
4185400, // Steam Linux Runtime 4.0 for ARM64
|
||||
4427310, // Proton Experimental for ARM64
|
||||
4628710, // Proton 11 / Proton Next
|
||||
4628740, // Proton 11 for ARM64
|
||||
4690330, // Legacy Steam Runtime
|
||||
858280,
|
||||
961940,
|
||||
993090,
|
||||
1054830,
|
||||
1070560,
|
||||
1113280,
|
||||
1245040,
|
||||
1391110,
|
||||
1420170,
|
||||
1493710,
|
||||
1580130,
|
||||
1628350,
|
||||
1887720,
|
||||
2180100,
|
||||
228980,
|
||||
2348590,
|
||||
2805730,
|
||||
3029110,
|
||||
3127680,
|
||||
3658110,
|
||||
4183110,
|
||||
4185400,
|
||||
4427310,
|
||||
4628710,
|
||||
4628740,
|
||||
4690330,
|
||||
)
|
||||
private val STEAM_CAPSULES = listOf("library_capsule.jpg", "library_600x900.jpg")
|
||||
private val STEAM_HEROES = listOf("library_hero.jpg")
|
||||
@@ -88,7 +69,6 @@ object Library {
|
||||
private val LAST_PLAYED = Regex("^\\s*\"LastPlayed\"\\s*\"(\\d+)\"", RegexOption.MULTILINE)
|
||||
private val INSTALL_DIR = Regex("^\\s*\"installdir\"\\s*\"([^\"]*)\"", RegexOption.MULTILINE)
|
||||
|
||||
/** Steam's library roots visible to this launcher: its private default plus the selected library. */
|
||||
private fun steamLibraries(context: Context): List<Pair<File, String>> {
|
||||
val root = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
|
||||
return listOfNotNull(
|
||||
@@ -97,7 +77,6 @@ object Library {
|
||||
) + GameStorage.gamesFolderLibraries(context).map { it.host to it.label }
|
||||
}
|
||||
|
||||
/** Proton keeps each game's prefix below compatdata/<appid>/pfx in a Steam library. */
|
||||
fun protonPrefix(
|
||||
context: Context, appId: Long, preferredLibrary: File? = null,
|
||||
libraries: List<File> = steamLibraries(context).map { it.first },
|
||||
@@ -130,14 +109,10 @@ object Library {
|
||||
val text = try { manifest.readText() } catch (e: Exception) { if (strictRead) throw e; return@forEach }
|
||||
val name = NAME.find(text)?.groupValues?.get(1)?.trim().orEmpty()
|
||||
val flags = STATE.find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
|
||||
// StateFlags 4 = fully installed; anything else is downloading, updating or broken.
|
||||
if (name.isEmpty() || flags and 4 == 0) return@forEach
|
||||
val art = steamCacheImage(cache, appId, STEAM_CAPSULES)
|
||||
val hero = steamCacheImage(cache, appId, STEAM_HEROES)
|
||||
val lastPlayed = LAST_PLAYED.find(text)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
|
||||
// App manifests are Valve KeyValues (VDF) files. installdir is one folder
|
||||
// below steamapps/common; only expose it when the directory exists and the
|
||||
// manifest value cannot escape that directory.
|
||||
val installDir = INSTALL_DIR.find(text)?.groupValues?.get(1)?.trim()
|
||||
?.takeIf { it.isNotEmpty() && it != "." && it != ".." && '/' !in it && '\\' !in it }
|
||||
val gameFiles = installDir?.let { File(steamapps, "common/$it").takeIf(File::isDirectory) }
|
||||
@@ -153,14 +128,11 @@ object Library {
|
||||
return out.values.toList()
|
||||
}
|
||||
|
||||
/** The same installed-game inventory used for links, shortcuts and file exports. */
|
||||
/** [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) + (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(
|
||||
@@ -172,7 +144,6 @@ object Library {
|
||||
)
|
||||
}
|
||||
|
||||
/** 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())
|
||||
val dirs = listOf(appDir) + appDir.listFiles()
|
||||
@@ -182,12 +153,9 @@ object Library {
|
||||
.firstOrNull { it.isFile && it.length() > 0L }
|
||||
}
|
||||
|
||||
/** [atPanel]: frames cheap enough to draw at the panel's own size (see [drawsAtPanel]). */
|
||||
private class Spec(val id: String, val name: String, val system: String, val program: String, val folders: List<String>, val exts: Set<String>, val atPanel: Boolean = false)
|
||||
private val specs = listOf(
|
||||
Spec("rpcs3", "RPCS3", "PS3", "/opt/appimages/rpcs3.AppImage", listOf("ps3"), setOf("iso")),
|
||||
// PS2: ARMSX2, the PCSX2 fork with ARM64 recompilers. Upstream PCSX2 interprets the PS2's
|
||||
// CPUs on ARM64 (NFS Underground 2: 17 fps against ARMSX2's full 60), so it is not offered.
|
||||
Spec("armsx2", "ARMSX2", "PS2", "/opt/appimages/armsx2.AppImage", listOf("ps2"), setOf("iso", "chd", "cso", "gz")),
|
||||
Spec("dolphin", "Dolphin", "GameCube / Wii", "/opt/appimages/dolphin.AppImage", listOf("gc", "gamecube", "wii"), setOf("iso", "rvz", "gcz", "wbfs", "ciso")),
|
||||
Spec("duckstation", "DuckStation", "PS1", "/opt/appimages/duckstation.AppImage", listOf("ps1", "psx"), setOf("cue", "chd", "pbp", "iso", "bin", "img", "ecm", "m3u")),
|
||||
@@ -196,73 +164,46 @@ object Library {
|
||||
Spec("ppsspp", "PPSSPP", "PSP", "/usr/bin/PPSSPPSDL", listOf("psp"), setOf("iso", "cso", "pbp", "chd")),
|
||||
Spec("retroarch", "RetroArch", "many systems", "/usr/bin/retroarch", emptyList(), emptySet()),
|
||||
)
|
||||
/**
|
||||
* A dump's file name as a title: its tags - (USA), (En,Fr,Es,Pt), [!], (v1.01) - identify the
|
||||
* file and are dropped for reading ("Tomb Raider (USA) (En,Fr,Es,Pt)" -> "Tomb Raider"). The
|
||||
* file keeps them, and the cover lookup still uses them.
|
||||
*/
|
||||
private fun displayTitle(name: String): String =
|
||||
name.replace(Regex("\\s*[(\\[][^)\\]]*[)\\]]"), "").trim().ifEmpty { name }
|
||||
|
||||
/** Every system folder name the specs claim, so a loose-file scan of the root skips them. */
|
||||
private val systemFolders: Set<String> by lazy { specs.flatMap { it.folders }.toSet() }
|
||||
private val installedIds = mapOf(
|
||||
"rpcs3" to "rpcs3", "armsx2" to "armsx2", "dolphin" to "dolphin", "duckstation" to "duckstation",
|
||||
"melonds" to "melonds", "cemu" to "cemu", "ppsspp" to "emulators", "retroarch" to "emulators",
|
||||
)
|
||||
|
||||
/** The emulator's name for a program path from the rail ("ARMSX2"), or null. */
|
||||
fun nameForProgram(program: String?): String? =
|
||||
if (program == com.droiddeck.launcher.runtime.FlatpakManager.LAUNCHER || program == com.droiddeck.launcher.runtime.AppImageManager.LAUNCHER ||
|
||||
program == com.droiddeck.launcher.runtime.UserApps.SCRIPT_LAUNCHER) {
|
||||
com.droiddeck.launcher.session.SessionState.programArgs.firstOrNull()?.let { flatpakNames[it] ?: it.substringAfterLast('.') }
|
||||
} else specs.firstOrNull { it.program == program }?.name
|
||||
|
||||
/** Added apps' names by Flatpak id or directory, as launched: the session only knows that. */
|
||||
val flatpakNames = java.util.concurrent.ConcurrentHashMap<String, String>()
|
||||
|
||||
/**
|
||||
* Whether a program from the rail runs at the panel's own resolution rather than the session's
|
||||
* 720p default. melonDS draws two 256x192 screens on the CPU: the panel's size costs it
|
||||
* nothing, and 720p scaled up to the panel blurs the sharp pixels its screen layout is set
|
||||
* up for (droiddeck-pad-defaults).
|
||||
*/
|
||||
fun drawsAtPanel(program: String?): Boolean = specs.any { it.program == program && it.atPanel }
|
||||
|
||||
/** Desktop catalog package that supplies this emulator. */
|
||||
fun packageId(emulatorId: String): String? = installedIds[emulatorId]
|
||||
|
||||
/** Every emulator the app knows, installed or not, with the games its system folder holds. */
|
||||
fun emulators(context: Context, installedPackage: (String) -> Boolean): List<Emulator> {
|
||||
val romsRoot = SessionPrefs.romsDir(context).takeIf { it.isNotEmpty() }?.let(::File)?.takeIf { it.isDirectory }
|
||||
return specs.map { spec ->
|
||||
val games = ArrayList<Rom>()
|
||||
if (romsRoot != null && spec.exts.isNotEmpty()) {
|
||||
// The system's folder(s), matched without regard to case, and up to three folders
|
||||
// inside them - a dump usually comes as a folder named for the game with the image
|
||||
// inside it, and people sort those into folders of their own (ps2/games/<game>/).
|
||||
// The root itself only one deep, for a file left loose there.
|
||||
val systemDirs = romsRoot.listFiles { f -> f.isDirectory && f.name.lowercase() in spec.folders }.orEmpty().toList()
|
||||
val dirs = LinkedHashSet<File>()
|
||||
// A BIOS folder holds the console's firmware, not games (psx/bios/SCPH1001.BIN).
|
||||
for (top in systemDirs) top.walkTopDown().maxDepth(3).onEnter { it.name.lowercase() !in firmwareFolders }
|
||||
.filter { it.isDirectory }.forEach { dirs.add(it) }
|
||||
dirs.add(romsRoot)
|
||||
// ...and not into another system's folder: a PS3 .iso in ps3/ is not a PS2 game.
|
||||
romsRoot.listFiles { f -> f.isDirectory && f.name.lowercase() !in systemFolders }?.forEach { dirs.add(it) }
|
||||
for (dir in dirs) {
|
||||
// A PS3 disc dump is a folder with PS3_GAME in it; RPCS3 boots the folder.
|
||||
if (spec.id == "rpcs3" && File(dir, "PS3_GAME").isDirectory) {
|
||||
val rel = dir.relativeTo(romsRoot).path
|
||||
games.add(Rom(displayTitle(dir.name), dir, "/root/ROMs/$rel", spec.id,
|
||||
// The dump carries its own art, as an installed package does.
|
||||
art = File(dir, "PS3_GAME/ICON0.PNG").takeIf { it.isFile }))
|
||||
continue
|
||||
}
|
||||
val files = dir.listFiles()?.sortedBy { it.name.lowercase() }.orEmpty()
|
||||
// A disc sheet (.cue, .gdi) names its track files and a playlist (.m3u) its
|
||||
// discs: the sheet is the game, what it names is part of it. A .bin beside a
|
||||
// .cue of the same name is a track even when the sheet can't be read.
|
||||
val parts = files.filter { it.isFile && it.extension.lowercase() in sheetExts }.flatMap(::sheetParts).toSet()
|
||||
files.forEach { f ->
|
||||
val ext = f.extension.lowercase()
|
||||
@@ -275,7 +216,6 @@ object Library {
|
||||
}
|
||||
}
|
||||
if (spec.id == "rpcs3") games.addAll(rpcs3Installed(context))
|
||||
// A cover found for the game before (CoverArt) where it has no art of its own.
|
||||
val withArt = games.map { g -> if (g.art != null) g else CoverArt.cached(context, g)?.let { Rom(g.name, g.hostPath, g.guestPath, g.emulatorId, it) } ?: g }
|
||||
Emulator(spec.id, spec.name, spec.system, spec.program, installedPackage(installedIds.getValue(spec.id)), withArt)
|
||||
}
|
||||
@@ -284,27 +224,19 @@ object Library {
|
||||
private val firmwareFolders = setOf("bios", "firmware")
|
||||
private val sheetExts = setOf("cue", "gdi", "m3u")
|
||||
|
||||
/** The file names (lower case) a .cue, .gdi or .m3u refers to, from its own folder. */
|
||||
private fun sheetParts(sheet: File): List<String> = runCatching {
|
||||
if (sheet.length() > 64 * 1024) return emptyList()
|
||||
sheet.readLines().mapNotNull { line ->
|
||||
val t = line.trim()
|
||||
when (sheet.extension.lowercase()) {
|
||||
// FILE "Tekken 3 (USA) (Track 1).bin" BINARY
|
||||
"cue" -> Regex("^FILE\\s+\"([^\"]+)\"", RegexOption.IGNORE_CASE).find(t)?.groupValues?.get(1)
|
||||
?: Regex("^FILE\\s+(\\S+)", RegexOption.IGNORE_CASE).find(t)?.groupValues?.get(1)
|
||||
// 1 0 4 2352 "track01.bin" 0 / 1 0 4 2352 track01.bin 0
|
||||
"gdi" -> Regex("\"([^\"]+)\"").find(t)?.groupValues?.get(1) ?: t.split(Regex("\\s+")).getOrNull(4)
|
||||
else -> t.takeIf { it.isNotEmpty() && !it.startsWith("#") }
|
||||
}
|
||||
}.map { File(it.replace('\\', '/')).name.lowercase() }
|
||||
}.getOrDefault(emptyList())
|
||||
|
||||
/**
|
||||
* What RPCS3 has installed on its own HDD - packages (PSN games) land in dev_hdd0/game/<ID>
|
||||
* with a PARAM.SFO for the title and an EBOOT to boot - as RPCS3's own file list would show
|
||||
* them. Not in the ROMs folder, so listed from RPCS3's home in the runtime.
|
||||
*/
|
||||
private fun rpcs3Installed(context: Context): List<Rom> {
|
||||
val hdd = File(LinuxRuntime.rootDir(context), "root/.config/rpcs3/dev_hdd0/game")
|
||||
return hdd.listFiles { f -> f.isDirectory }?.sortedBy { it.name }?.mapNotNull { dir ->
|
||||
@@ -312,7 +244,6 @@ object Library {
|
||||
val sfo = File(dir, "PARAM.SFO")
|
||||
if (!eboot.isFile || !sfo.isFile) return@mapNotNull null
|
||||
val fields = readSfo(sfo)
|
||||
// Only games: patches, DLC and save data live here too, with their own categories.
|
||||
if (fields["CATEGORY"]?.let { it == "HG" || it == "DG" || it == "GD" } == false) return@mapNotNull null
|
||||
val title = fields["TITLE"]?.trim()?.takeIf { it.isNotEmpty() } ?: dir.name
|
||||
Rom(title, eboot, "/root/.config/rpcs3/dev_hdd0/game/${dir.name}/USRDIR/EBOOT.BIN", "rpcs3",
|
||||
@@ -320,7 +251,6 @@ object Library {
|
||||
} ?: emptyList()
|
||||
}
|
||||
|
||||
/** The string fields of a PARAM.SFO (the PSP/PS3 metadata file): a small binary table. */
|
||||
private fun readSfo(file: File): Map<String, String> {
|
||||
val out = HashMap<String, String>()
|
||||
try {
|
||||
@@ -337,7 +267,7 @@ object Library {
|
||||
var keyEnd = keyStart
|
||||
while (keyEnd < b.size && b[keyEnd] != 0.toByte()) keyEnd++
|
||||
val key = String(b, keyStart, keyEnd - keyStart, Charsets.US_ASCII)
|
||||
if (fmt == 0x0204 || fmt == 0x0004) { // utf8 string (null-terminated or not)
|
||||
if (fmt == 0x0204 || fmt == 0x0004) {
|
||||
val start = data + dataOff
|
||||
val end = minOf(b.size, start + len)
|
||||
var stop = start
|
||||
@@ -346,38 +276,21 @@ object Library {
|
||||
}
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
// unreadable metadata: the folder name stands in
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** How the emulator is told which game to boot, on its command line. */
|
||||
fun launchArgs(emulatorId: String, guestPath: String): List<String> = when (emulatorId) {
|
||||
"rpcs3" -> listOf("--no-gui", guestPath)
|
||||
// Straight into the game in its controller-driven full-screen UI (first-time setup there
|
||||
// too), and gone when the game is quit from its pause menu (guide button): -batch.
|
||||
"armsx2" -> listOf("-batch", "-bigpicture", "-fullscreen", "--", guestPath)
|
||||
// DuckStation shares PCSX2's flags (src/duckstation-qt/qthost.cpp): the same launch and exit.
|
||||
"duckstation" -> listOf("-batch", "-bigpicture", "-fullscreen", "--", guestPath)
|
||||
// Dolphin: full screen, drawn inside its own main window, without its "stop the emulation?"
|
||||
// question; no warning boxes either, which wait for a click a controller cannot give
|
||||
// (they still go to Dolphin's log). The guide button is Dolphin's Toggle Fullscreen hotkey
|
||||
// (droiddeck-pad-defaults), which shows Dolphin's window and its settings - so no -b, which
|
||||
// hides that window; closing Dolphin ends the session. Under gamescope Dolphin does not
|
||||
// always see its window as focused, and by default both its hotkeys and the game's
|
||||
// controller then stop: HotkeysRequireFocus off, BackgroundInput on. -C sets a Dolphin.ini
|
||||
// value for this run only, so Dolphin started from the desktop keeps its own settings.
|
||||
"dolphin" -> listOf(
|
||||
"-C", "Dolphin.Display.Fullscreen=True", "-C", "Dolphin.Display.RenderToMain=True",
|
||||
"-C", "Dolphin.Interface.ConfirmStop=False", "-C", "Dolphin.Interface.UsePanicHandlers=False",
|
||||
"-C", "Dolphin.General.HotkeysRequireFocus=False", "-C", "Dolphin.Input.BackgroundInput=True",
|
||||
"-e", guestPath,
|
||||
)
|
||||
// Full screen (LaunchSettings.cpp -f); the settings seed keeps the Getting Started
|
||||
// dialog away (droiddeck-pad-defaults).
|
||||
"cemu" -> listOf("-f", "-g", guestPath)
|
||||
// Full screen (CLI.cpp --fullscreen); the guide button leaves it for melonDS's menus and
|
||||
// comes back (HK_FullscreenToggle, droiddeck-pad-defaults).
|
||||
"melonds" -> listOf("-f", guestPath)
|
||||
else -> listOf(guestPath)
|
||||
}
|
||||
|
||||
@@ -6,11 +6,6 @@ import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* The last game list the front end showed, kept in the app's files so the next start draws the
|
||||
* Steam wall on its first frame. Building the list reads every manifest and walks the added-games
|
||||
* folders, which can take a second or more; the fresh list replaces this one when it is ready.
|
||||
*/
|
||||
object LibraryCache {
|
||||
private const val TAG = "LibraryCache"
|
||||
private fun file(context: Context) = File(context.filesDir, "library-cache.json")
|
||||
|
||||
@@ -3,27 +3,11 @@ 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
|
||||
private const val MAX_RES_SECTION = 64 * 1024 * 1024
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -33,13 +17,6 @@ object PeVersionInfo {
|
||||
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() }
|
||||
@@ -52,15 +29,14 @@ object PeVersionInfo {
|
||||
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"
|
||||
if (u8(dos, 0) != 0x4D || u8(dos, 1) != 0x5A) return null
|
||||
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"
|
||||
if (u8(coff, 0) != 0x50 || u8(coff, 1) != 0x45 || u8(coff, 2) != 0 || u8(coff, 3) != 0) return null
|
||||
val numSections = u16(coff, 6)
|
||||
val sizeOpt = u16(coff, 20)
|
||||
if (numSections <= 0 || numSections > 96 || sizeOpt <= 0) return null
|
||||
@@ -68,8 +44,8 @@ object PeVersionInfo {
|
||||
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
|
||||
val ddOff = if (magic == 0x20B) 112 else 96
|
||||
val resDirEntry = ddOff + 2 * 8
|
||||
if (resDirEntry + 8 > opt.size) return null
|
||||
val resRVA = u32(opt, resDirEntry).toInt()
|
||||
val resSize = u32(opt, resDirEntry + 4).toInt()
|
||||
@@ -105,7 +81,6 @@ object PeVersionInfo {
|
||||
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)
|
||||
@@ -123,7 +98,6 @@ object PeVersionInfo {
|
||||
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
|
||||
@@ -137,7 +111,6 @@ object PeVersionInfo {
|
||||
}
|
||||
}
|
||||
|
||||
/** 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()
|
||||
@@ -147,17 +120,11 @@ object PeVersionInfo {
|
||||
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)
|
||||
@@ -173,7 +140,6 @@ object PeVersionInfo {
|
||||
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) {
|
||||
@@ -185,7 +151,6 @@ object PeVersionInfo {
|
||||
}
|
||||
}
|
||||
|
||||
/** 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) {
|
||||
@@ -202,11 +167,9 @@ object PeVersionInfo {
|
||||
}
|
||||
}
|
||||
|
||||
// ── 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) {
|
||||
@@ -216,7 +179,6 @@ object PeVersionInfo {
|
||||
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
|
||||
|
||||
@@ -3,18 +3,9 @@ package com.droiddeck.launcher.frontend
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Which catalog components a game's prefix already has from elsewhere - a real installer, the game,
|
||||
* the user - so the list can say so instead of recommending them again. Bannerlator's detector,
|
||||
* on DroidDeck's compatdata/<id>: only markers absent from a fresh Proton prefix count (OpenAL32,
|
||||
* Mono, PhysX, Games for Windows Live); msvcp140, d3dx9 and the like ship with Proton and cannot
|
||||
* tell. Files DroidDeck put there itself (droiddeck-wincomponents' state) are not counted.
|
||||
* Pure filesystem reads; never throws.
|
||||
*/
|
||||
object PrefixInstalledDetector {
|
||||
private const val STATE = ".droiddeck-wincomponents.json"
|
||||
|
||||
/** Detector names (oalinst, mono, physx, XLiveRedist) present in [compat]/pfx. */
|
||||
fun detect(compat: File?): Set<String> = try {
|
||||
val pfx = compat?.let { File(it, "pfx") }
|
||||
if (pfx == null || !pfx.isDirectory) emptySet() else {
|
||||
@@ -38,7 +29,6 @@ object PrefixInstalledDetector {
|
||||
emptySet()
|
||||
}
|
||||
|
||||
/** Windows names ignore case; the prefix's folder may spell them either way. */
|
||||
private fun fileIgnoringCase(pfx: File, rel: String): Boolean {
|
||||
val target = File(pfx, rel)
|
||||
return target.parentFile?.listFiles()?.any { it.isFile && it.name.equals(target.name, ignoreCase = true) } == true
|
||||
|
||||
@@ -7,17 +7,10 @@ import com.droiddeck.launcher.session.GameStorage
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* A Steam game whose download finishes during a session, noticed by its appmanifest (a new one,
|
||||
* or StateFlags turning to 4, fully installed) with a light look every five seconds while the
|
||||
* session runs, and handed to [AutoComponents] as a single job that may run in the session, so its
|
||||
* Windows components are in place when the user plays it right after the download.
|
||||
*/
|
||||
object SessionInstalls {
|
||||
private const val TAG = "SessionInstalls"
|
||||
private const val POLL_MS = 5_000L
|
||||
|
||||
/** One appmanifest as read: the app, its name and folder, whether it is fully installed. */
|
||||
class Manifest(val appId: Int, val name: String, val installDir: String, val installed: Boolean, val steamapps: File)
|
||||
|
||||
private val APPID = Regex("\"appid\"\\s*\"(\\d+)\"", RegexOption.IGNORE_CASE)
|
||||
@@ -32,16 +25,11 @@ object SessionInstalls {
|
||||
STATE.find(text)?.groupValues?.get(1)?.toIntOrNull() == 4, file.parentFile!!)
|
||||
}.getOrNull()
|
||||
|
||||
/** The libraries the session's client installs to, as host folders. */
|
||||
internal fun steamappsDirs(context: Context): List<File> = listOfNotNull(
|
||||
File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps"),
|
||||
GameStorage.effective(context)?.let { File(it.path, "steamapps") },
|
||||
).filter { it.isDirectory }
|
||||
|
||||
/**
|
||||
* Keeps what the libraries hold between looks: a manifest re-read only when its time changed.
|
||||
* [poll] returns the apps that became fully installed since the last look (none on the first).
|
||||
*/
|
||||
internal class Watch(private val dirs: () -> List<File>) {
|
||||
private val seen = HashMap<String, Pair<Long, Manifest?>>()
|
||||
private var first = true
|
||||
@@ -60,22 +48,16 @@ object SessionInstalls {
|
||||
}
|
||||
}
|
||||
|
||||
/** A finished install as the Games tab would list it. */
|
||||
internal fun gameOf(m: Manifest): Library.SteamGame =
|
||||
Library.SteamGame(m.appId, m.name.ifEmpty { m.appId.toString() }, null, m.steamapps.parentFile?.path ?: "steam",
|
||||
gameFiles = File(m.steamapps, "common/${m.installDir}"), source = Library.SOURCE_STEAM)
|
||||
|
||||
/**
|
||||
* Looks every five seconds while the session runs, on a thread of its own at background
|
||||
* priority; each finished install becomes one job for its Windows components.
|
||||
*/
|
||||
fun watch(context: Context) {
|
||||
val app = context.applicationContext
|
||||
Thread({
|
||||
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND)
|
||||
val watch = Watch { steamappsDirs(app) }
|
||||
try {
|
||||
// The session is still starting when this is called: up to two minutes for it.
|
||||
var waited = 0L
|
||||
while (!SessionState.running && waited < 120_000L) { Thread.sleep(POLL_MS); waited += POLL_MS }
|
||||
watch.poll()
|
||||
|
||||
@@ -12,25 +12,16 @@ import java.io.RandomAccessFile
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.ByteOrder
|
||||
|
||||
/**
|
||||
* Steam's own data for an app, from the client in the runtime: its app-info cache
|
||||
* (Steam/appcache/appinfo.vdf, the PICS data the client keeps for every app it has seen). What is
|
||||
* read is which Steamworks Shared depots (the VC++, DirectX... redistributables of app 228980) the
|
||||
* app's depots point at, and its name. Kept per appid in the app's files, so it works offline; an
|
||||
* app the client has not seen is looked for again after a week.
|
||||
*/
|
||||
object SteamAppInfo {
|
||||
private const val TAG = "SteamAppInfo"
|
||||
private const val CACHE = "steam-appinfo.json"
|
||||
private const val RETRY_AFTER_MS = 7L * 24 * 3600 * 1000
|
||||
/** The Steamworks Shared app the redistributable depots belong to. */
|
||||
const val SHARED_APP = "228980"
|
||||
|
||||
class Info(val name: String, val sharedDepots: List<String>)
|
||||
|
||||
fun appinfoFile(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/appcache/appinfo.vdf")
|
||||
|
||||
/** The shared depots for [appId]: from the cache, else the client's app-info file; null when unknown. */
|
||||
@Synchronized
|
||||
fun info(context: Context, appId: Int, appinfo: File = appinfoFile(context)): Info? {
|
||||
val cacheFile = AtomicFile(File(context.filesDir, CACHE))
|
||||
@@ -40,13 +31,10 @@ object SteamAppInfo {
|
||||
val known = cache.optJSONObject(appId.toString())
|
||||
known?.let { o ->
|
||||
if (!o.optBoolean("miss")) return Info(o.optString("name"), o.optJSONArray("depots").strings())
|
||||
// A miss is read again when the client has written its cache since (the user may have
|
||||
// looked at the app in Steam), else a week later.
|
||||
if (now - o.optLong("at") < RETRY_AFTER_MS && o.optLong("mtime") == mtime) return null
|
||||
}
|
||||
val read = runCatching { read(appinfo, appId) }.onFailure { Log.w(TAG, "appinfo: ${it.javaClass.simpleName}") }.getOrNull()
|
||||
val entry = JSONObject().put("at", now).put("mtime", mtime)
|
||||
// When Steam was last asked anonymously ([lookup]), kept across re-reads of the file.
|
||||
known?.optLong("picsAt")?.takeIf { it > 0 }?.let { entry.put("picsAt", it) }
|
||||
if (read == null) entry.put("miss", true) else entry.put("name", read.name).put("depots", JSONArray(read.sharedDepots))
|
||||
cache.put(appId.toString(), entry)
|
||||
@@ -55,14 +43,9 @@ object SteamAppInfo {
|
||||
return read
|
||||
}
|
||||
|
||||
/** Steam asked anonymously ([SteamPics]); a test stands in for it. */
|
||||
@androidx.annotation.VisibleForTesting
|
||||
internal var pics: (List<Int>) -> Map<Int, Info?>? = { SteamPics.lookup(it) }
|
||||
|
||||
/**
|
||||
* Of [appIds], those neither the client's cache (appinfo.vdf, read first: free) nor an earlier
|
||||
* answer has, and that Steam was not asked about anonymously in the past week.
|
||||
*/
|
||||
fun needLookup(context: Context, appIds: List<Int>): List<Int> {
|
||||
val wanted = appIds.distinct().filter { it > 0 && info(context, it) == null }
|
||||
if (wanted.isEmpty()) return emptyList()
|
||||
@@ -71,11 +54,6 @@ object SteamAppInfo {
|
||||
return wanted.filter { now - (cache.optJSONObject(it.toString())?.optLong("picsAt") ?: 0L) >= RETRY_AFTER_MS }
|
||||
}
|
||||
|
||||
/**
|
||||
* [appIds] the client never saw, asked of Steam anonymously in one connection ([SteamPics], in
|
||||
* batches) and every answer kept like the client's: an app's depots and name, or a miss tried
|
||||
* again in a week. False when nothing needed asking or Steam could not be reached. Blocking.
|
||||
*/
|
||||
@Synchronized
|
||||
fun lookup(context: Context, appIds: List<Int>): Boolean {
|
||||
val need = needLookup(context, appIds)
|
||||
@@ -96,7 +74,6 @@ object SteamAppInfo {
|
||||
return true
|
||||
}
|
||||
|
||||
/** What is kept for [appId]: "hit", "miss" or "none" (part of a game's list fingerprint). */
|
||||
fun state(context: Context, appId: Int): String = cache(context).optJSONObject(appId.toString())?.let { if (it.optBoolean("miss")) "miss" else "hit" } ?: "none"
|
||||
|
||||
private fun cache(context: Context): JSONObject =
|
||||
@@ -104,10 +81,6 @@ object SteamAppInfo {
|
||||
|
||||
private fun JSONArray?.strings(): List<String> = if (this == null) emptyList() else (0 until length()).map { optString(it) }
|
||||
|
||||
/**
|
||||
* [appId]'s entry in an appinfo.vdf (versions 27, 28 and 29, the last with its keys in a string
|
||||
* table), or null when the file does not have it.
|
||||
*/
|
||||
internal fun read(file: File, appId: Int): Info? {
|
||||
if (!file.isFile) return null
|
||||
RandomAccessFile(file, "r").use { raf ->
|
||||
@@ -181,7 +154,6 @@ object SteamAppInfo {
|
||||
return String(bytes, Charsets.UTF_8)
|
||||
}
|
||||
|
||||
/** One binary key-value map, to its end marker; keys by name, or by index into [strings]. */
|
||||
private fun readMap(b: ByteBuffer, strings: List<String>?): Map<String, Any> {
|
||||
val out = LinkedHashMap<String, Any>()
|
||||
while (b.hasRemaining()) {
|
||||
|
||||
@@ -11,15 +11,6 @@ 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"
|
||||
@@ -31,17 +22,14 @@ object SteamGridDb {
|
||||
|
||||
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)
|
||||
@@ -56,7 +44,6 @@ object SteamGridDb {
|
||||
}
|
||||
}
|
||||
|
||||
/** 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)
|
||||
@@ -75,7 +62,6 @@ object SteamGridDb {
|
||||
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 }
|
||||
@@ -85,16 +71,11 @@ object SteamGridDb {
|
||||
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(
|
||||
@@ -116,7 +97,6 @@ object SteamGridDb {
|
||||
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"
|
||||
@@ -128,20 +108,17 @@ object SteamGridDb {
|
||||
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
|
||||
|
||||
@@ -5,20 +5,9 @@ import android.util.AtomicFile
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* Which Steam app a game added in DroidDeck is, kept once per game (by its folder) and used by
|
||||
* everything that asks: its art ([AddedGameArt]) and its Windows components ([WinCompSources]),
|
||||
* so the two never disagree.
|
||||
*
|
||||
* [Certainty.FILES]: the game's own files name the appid (steam_appid.txt, also under
|
||||
* steam_settings/ or a parent folder; an emulator ini; Steam's appmanifest) - certain.
|
||||
* [Certainty.NAME]: Steam's store search returned a game of the same name - a guess.
|
||||
* [Certainty.NONE]: neither; a miss is tried again after a week.
|
||||
*/
|
||||
object SteamMatch {
|
||||
enum class Certainty { FILES, NAME, NONE }
|
||||
|
||||
/** [source]: what gave the appid (GameIdentifier's source, or "store search"). */
|
||||
class Match(val appId: Int?, val certainty: Certainty, val source: String, val checkedAt: Long)
|
||||
|
||||
private const val FILE = "steam-matches.json"
|
||||
@@ -50,12 +39,6 @@ object SteamMatch {
|
||||
try { out.write(json.toString().toByteArray()); atomic.finishWrite(out) } catch (e: Exception) { atomic.failWrite(out) }
|
||||
}
|
||||
|
||||
/**
|
||||
* The match for the game in [key] (its folder), [exe] its exe and [name] its title: its files
|
||||
* first, always read again; else the one kept (a name match stays, a miss for a week); else
|
||||
* [legacy], an appid an earlier build's art lookup kept; else [search] on the name, when given.
|
||||
* Blocking ([search] asks the network).
|
||||
*/
|
||||
fun resolve(context: Context, key: String, exe: File, name: String, legacy: File? = null, search: ((String) -> Int?)? = null): Match {
|
||||
val now = System.currentTimeMillis()
|
||||
val identity = runCatching { GameIdentifier.identify(exe) }.getOrNull()
|
||||
|
||||
@@ -18,18 +18,9 @@ import java.util.zip.GZIPInputStream
|
||||
import javax.net.ssl.SSLSocket
|
||||
import javax.net.ssl.SSLSocketFactory
|
||||
|
||||
/**
|
||||
* Steam's own app info (PICS) for apps the client in the runtime has never seen, asked of Steam
|
||||
* anonymously: a connection to one of Steam's connection managers (the list from Steam's public
|
||||
* ISteamDirectory/GetCMListForConnect, the WebSocket transport Steam's web clients use), an
|
||||
* anonymous logon - no account, nothing of the user's Steam sign-in - a request for the apps'
|
||||
* access tokens and then their product info, the app KeyValues read for their Steamworks Shared
|
||||
* depots and name, and the connection closed. What steamcmd's anonymous `app_info_print` sees.
|
||||
*/
|
||||
object SteamPics {
|
||||
private const val TAG = "SteamPics"
|
||||
private const val CM_LIST = "https://api.steampowered.com/ISteamDirectory/GetCMListForConnect/v1/?cellid=0&format=json"
|
||||
/** At most this many apps per request. */
|
||||
const val BATCH = 25
|
||||
private const val PROTO = 0x80000000.toInt()
|
||||
private const val EMSG_MULTI = 1
|
||||
@@ -41,13 +32,8 @@ object SteamPics {
|
||||
private const val EMSG_INFO_REQUEST = 8903
|
||||
private const val EMSG_INFO_RESPONSE = 8904
|
||||
private const val PROTOCOL_VERSION = 65580
|
||||
/** An anonymous user's SteamID: universe Public, account type AnonUser, instance 0. */
|
||||
private const val ANON_STEAMID = (1L shl 56) or (10L shl 52)
|
||||
|
||||
/**
|
||||
* [appIds]' info, one connection for all of them in batches of [BATCH]: each known app's
|
||||
* info, null for an app Steam does not know. Null when Steam could not be reached. Blocking.
|
||||
*/
|
||||
fun lookup(appIds: List<Int>): Map<Int, SteamAppInfo.Info?>? {
|
||||
if (appIds.isEmpty()) return emptyMap()
|
||||
val host = runCatching { cmHost() }.getOrNull() ?: return null
|
||||
@@ -56,7 +42,6 @@ object SteamPics {
|
||||
ws.send(message(EMSG_LOGON, header(ANON_STEAMID, 0), Proto().varint(1, PROTOCOL_VERSION.toLong()).varint(7, 16).string(6, "english").bytes()))
|
||||
var steamId = 0L
|
||||
var session = 0
|
||||
// The logon's answer (other messages before it are passed over).
|
||||
loop@ while (true) for ((emsg, hdr, body) in messages(ws.receive() ?: return null)) if (emsg == EMSG_LOGON_RESPONSE) {
|
||||
val h = fields(hdr); val b = fields(body)
|
||||
if ((b[1]?.firstOrNull() as? Long ?: 0L) != 1L) { Log.w(TAG, "anonymous logon refused: ${b[1]}"); return null }
|
||||
@@ -99,10 +84,8 @@ object SteamPics {
|
||||
}
|
||||
}
|
||||
|
||||
/** [appIds] in requests of at most [BATCH], each once. */
|
||||
fun batches(appIds: List<Int>): List<List<Int>> = appIds.distinct().chunked(BATCH)
|
||||
|
||||
/** A connection manager for the WebSocket transport, least loaded first as Steam lists them. */
|
||||
private fun cmHost(): String? {
|
||||
val c = URL(CM_LIST).openConnection() as HttpURLConnection
|
||||
c.connectTimeout = 10_000; c.readTimeout = 10_000
|
||||
@@ -112,11 +95,9 @@ object SteamPics {
|
||||
.firstOrNull { it.optString("type") == "websockets" }?.optString("endpoint")?.substringBefore(':')
|
||||
}
|
||||
|
||||
// ---- the product info answer ----
|
||||
|
||||
class InfoResponse(val apps: Map<Int, SteamAppInfo.Info>, val unknown: List<Int>, val pending: Boolean)
|
||||
|
||||
/** A CMsgClientPICSProductInfoResponse: each app's KeyValues read, the unknown ones, whether more follows. */
|
||||
@VisibleForTesting
|
||||
internal fun parseInfoResponse(body: ByteArray): InfoResponse {
|
||||
val f = fields(body)
|
||||
@@ -132,17 +113,14 @@ object SteamPics {
|
||||
return InfoResponse(apps, unknown, (f[6]?.firstOrNull() as? Long ?: 0L) != 0L)
|
||||
}
|
||||
|
||||
/** An app's KeyValues text ("appinfo" { "common" {...} "depots" {...} }) to its name and shared depots. */
|
||||
@VisibleForTesting
|
||||
internal fun infoFromKeyValues(text: String): SteamAppInfo.Info? {
|
||||
// The buffer ends in a NUL, kept or not by whoever handed it over.
|
||||
val tree = runCatching { KeyValues(text.trimEnd('\u0000', ' ', '\n', '\r', '\t')).read() }.getOrNull() ?: return null
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
val app = tree["appinfo"] as? Map<String, Any> ?: return null
|
||||
return SteamAppInfo.infoOf(app)
|
||||
}
|
||||
|
||||
/** Valve's text KeyValues: quoted keys and values, nested braces. */
|
||||
private class KeyValues(private val s: String) {
|
||||
private var i = 0
|
||||
fun read(): Map<String, Any> = map(top = true)
|
||||
@@ -182,7 +160,6 @@ object SteamPics {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- messages ----
|
||||
|
||||
private fun header(steamId: Long, session: Int) = Proto().fixed64(1, steamId).varint(2, session.toLong()).bytes()
|
||||
|
||||
@@ -190,7 +167,6 @@ object SteamPics {
|
||||
ByteBuffer.allocate(8 + header.size + body.size).order(ByteOrder.LITTLE_ENDIAN)
|
||||
.putInt(emsg or PROTO).putInt(header.size).put(header).put(body).array()
|
||||
|
||||
/** One message off the wire as (emsg, header, body); a Multi unpacked (gunzipped when it says so) into the ones inside. */
|
||||
@VisibleForTesting
|
||||
internal fun messages(data: ByteArray): List<Triple<Int, ByteArray, ByteArray>> {
|
||||
if (data.size < 8) return emptyList()
|
||||
@@ -217,9 +193,7 @@ object SteamPics {
|
||||
return out
|
||||
}
|
||||
|
||||
// ---- protobuf, the little needed ----
|
||||
|
||||
/** Writes protobuf fields. */
|
||||
@VisibleForTesting
|
||||
internal class Proto {
|
||||
private val out = ByteArrayOutputStream()
|
||||
@@ -231,7 +205,6 @@ object SteamPics {
|
||||
fun bytes(): ByteArray = out.toByteArray()
|
||||
}
|
||||
|
||||
/** Reads protobuf fields: number to values (Long for varint and fixed, ByteArray for length-delimited). */
|
||||
@VisibleForTesting
|
||||
internal fun fields(b: ByteArray): Map<Int, List<Any>> {
|
||||
val out = HashMap<Int, MutableList<Any>>()
|
||||
@@ -258,16 +231,13 @@ object SteamPics {
|
||||
return out
|
||||
}
|
||||
|
||||
// ---- WebSocket over TLS, binary frames ----
|
||||
|
||||
private class Wss(host: String, timeoutMs: Int) : AutoCloseable {
|
||||
// Made with the host name, so it goes out as SNI.
|
||||
private val socket: SSLSocket = (SSLSocketFactory.getDefault().createSocket(host, 443) as SSLSocket).apply { soTimeout = timeoutMs }
|
||||
private val out: OutputStream
|
||||
private val input: DataInputStream
|
||||
|
||||
init {
|
||||
// Host name checked against the certificate, as HTTPS does.
|
||||
socket.sslParameters = socket.sslParameters.apply { endpointIdentificationAlgorithm = "HTTPS" }
|
||||
socket.startHandshake()
|
||||
out = socket.outputStream
|
||||
@@ -305,7 +275,6 @@ object SteamPics {
|
||||
out.write(frame.toByteArray()); out.flush()
|
||||
}
|
||||
|
||||
/** The next binary message (fragments joined); null on close. */
|
||||
fun receive(): ByteArray? {
|
||||
val message = ByteArrayOutputStream()
|
||||
while (true) {
|
||||
|
||||
@@ -2,14 +2,7 @@ package com.droiddeck.launcher.frontend
|
||||
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* What Steam itself installs alongside a game: the Steamworks Shared redistributables (app 228980)
|
||||
* listed under "SharedDepots" in the game's appmanifest. Those live in Steamworks Shared rather than
|
||||
* the game's folder, so the folder scan ([DependencyDetector]) cannot see them; this reads Steam's
|
||||
* list instead. Depots are matched to Bannerlator's catalog names; unknown ones are left out.
|
||||
*/
|
||||
object SteamRedists {
|
||||
/** Steamworks Shared depot -> (catalog component, what Steam calls it). 2015-2019 runtimes are one family. */
|
||||
val DEPOTS = linkedMapOf(
|
||||
"228981" to ("vcredist2005_dll" to "VC++ 2005"),
|
||||
"228982" to ("vcredist2008_dll" to "VC++ 2008"),
|
||||
@@ -25,7 +18,6 @@ object SteamRedists {
|
||||
private val BLOCK = Regex("\"SharedDepots\"\\s*\\{([^}]*)\\}", RegexOption.IGNORE_CASE)
|
||||
private val ENTRY = Regex("\"(\\d+)\"\\s+\"\\d+\"")
|
||||
|
||||
/** The game's appmanifest beside its install folder (steamapps/common/<dir> -> steamapps/). */
|
||||
fun manifest(gameDir: File?, appId: Int): File? {
|
||||
val steamapps = gameDir?.parentFile?.parentFile ?: return null
|
||||
return File(steamapps, "appmanifest_$appId.acf").takeIf { it.isFile }
|
||||
|
||||
@@ -14,47 +14,28 @@ import com.droiddeck.launcher.stores.gog.GogDownloadManager
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
|
||||
/**
|
||||
* For a GOG or Epic game installed before its sidecar kept the store's list (GOG's build
|
||||
* `dependencies`, Epic's manifest prerequisite): the list read once from the store's build
|
||||
* manifest with the saved sign-in - the manifest alone, never a game file - and kept in the sidecar
|
||||
* the way an install keeps it. Runs on the components' worker ([AutoComponents]). Without a
|
||||
* sign-in or a network it is skipped quietly and tried again a week later.
|
||||
*/
|
||||
object StoreListBackfill {
|
||||
private const val TAG = "StoreListBackfill"
|
||||
private const val FILE = "store-list-backfill.json"
|
||||
private const val RETRY_AFTER_MS = 7L * 24 * 3600 * 1000
|
||||
|
||||
/** The store's list for the game in a sidecar: GOG's dependency ids, or Epic's prerequisite {name, path}; null when it could not be had. */
|
||||
fun interface Fetcher {
|
||||
fun fetch(context: Context, sidecar: StoreGameSidecar): Map<String, String>?
|
||||
}
|
||||
|
||||
/** The store itself, with the saved sign-in. */
|
||||
internal val storeFetcher = Fetcher { context, sidecar -> fromStore(context, sidecar) }
|
||||
|
||||
@VisibleForTesting internal var fetcher: Fetcher = storeFetcher
|
||||
|
||||
/** Whether [sidecar] was written before the list was kept. */
|
||||
/**
|
||||
* Whether [sidecar] has no list read whole: written before the list was kept, or by a build
|
||||
* that could have written an empty one for a manifest it did not read right.
|
||||
*/
|
||||
fun needs(sidecar: StoreGameSidecar): Boolean =
|
||||
(sidecar.store == Store.GOG || sidecar.store == Store.EPIC) && WinCompSources.LIST_READ !in sidecar.extra
|
||||
|
||||
/**
|
||||
* The list for the game in [folder], fetched and kept when its sidecar lacks one and it was not
|
||||
* tried in the past week. True when the sidecar changed. Blocking (network).
|
||||
*/
|
||||
@Synchronized
|
||||
fun fill(context: Context, folder: File): Boolean {
|
||||
val sidecar = StoreGameSidecar.read(folder)?.takeIf { it.isInstalled && needs(it) } ?: return false
|
||||
val tries = runCatching { JSONObject(AtomicFile(File(context.filesDir, FILE)).readFully().toString(Charsets.UTF_8)) }.getOrDefault(JSONObject())
|
||||
val now = System.currentTimeMillis()
|
||||
if (now - tries.optLong(folder.path, 0L) < RETRY_AFTER_MS) return false
|
||||
// Offline is no try: it waits for a network rather than a week.
|
||||
if (!AutoComponents.online(context)) return false
|
||||
val list = runCatching { fetcher.fetch(context, sidecar) }.getOrNull()
|
||||
if (list == null) {
|
||||
@@ -65,7 +46,6 @@ object StoreListBackfill {
|
||||
Log.i(TAG, "${sidecar.title}: the ${sidecar.store.label} list could not be had; again in a week")
|
||||
return false
|
||||
}
|
||||
// Read fresh and written whole, as an install writes it: only the list is added.
|
||||
val current = StoreGameSidecar.read(folder) ?: return false
|
||||
current.copy(extra = current.extra + list + (WinCompSources.LIST_READ to "1")).write(folder)
|
||||
Log.i(TAG, "backfill: ${sidecar.title} " + when (sidecar.store) {
|
||||
|
||||
@@ -7,35 +7,11 @@ import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.util.Locale
|
||||
|
||||
/**
|
||||
* Which Windows components a game needs, from the list its source keeps - the source badge decides
|
||||
* which list is trusted:
|
||||
*
|
||||
* - **Steam**: the Steamworks Shared redistributables Steam installs with the game (its
|
||||
* appmanifest's SharedDepots, else the client's app info) - turned on by themselves.
|
||||
* - **GOG**: the build manifest's `dependencies`, kept in the sidecar at install - on by themselves.
|
||||
* - **Epic Games**: the manifest's prerequisite (usually UE4/UE5's prerequisite setup: VC++ and the
|
||||
* DirectX June 2010 runtime), kept in the sidecar at install - on by themselves.
|
||||
* - **Amazon Games**: fuel.json's PostInstall installers - on by themselves.
|
||||
* - **Custom** whose files name a Steam appid ([SteamMatch], certain): Steam's list for that app -
|
||||
* on by themselves. Matched by name only: the same list as Recommended. No match: the folder scan
|
||||
* ([DependencyDetector]) as Recommended.
|
||||
*
|
||||
* Every store entry is mapped to catalog names here, in one place; one that maps to nothing is a
|
||||
* suggestion under its own name. The folder scan is offered as Recommended for every game.
|
||||
*/
|
||||
object WinCompSources {
|
||||
/** Whose list a finding came from; the reason line says it. */
|
||||
enum class Origin { STEAM, GOG, EPIC, AMAZON, STEAM_NAME, FOLDER }
|
||||
|
||||
/**
|
||||
* One thing a list names: [component] the catalog name it maps to (null: none, a suggestion),
|
||||
* [original] what the list called it, [auto] whether it is turned on by itself, [args] what
|
||||
* the reason line names (Steam: the label, the game, the appid).
|
||||
*/
|
||||
data class Finding(val component: String?, val original: String, val origin: Origin, val auto: Boolean, val args: List<String> = emptyList())
|
||||
|
||||
// ---- mapping tables: a store's names -> catalog components ----
|
||||
|
||||
private val VC_YEAR = mapOf(
|
||||
"2005" to "vcredist2005", "2008" to "vcredist2008", "2010" to "vcredist2010", "2012" to "vcredist2012",
|
||||
@@ -47,10 +23,6 @@ object WinCompSources {
|
||||
"472" to "dotnet472", "48" to "dotnet48", "481" to "dotnet48",
|
||||
)
|
||||
|
||||
/**
|
||||
* A GOG dependency id ("MSVC2017_x64", "DirectX", "DOTNET48", "PhysX", "OpenAL", "XNA4") to its
|
||||
* components; empty for one that is none of ours (ISI scripts, GOG's own helpers).
|
||||
*/
|
||||
fun gog(id: String): List<String> {
|
||||
val key = id.uppercase(Locale.US).replace(Regex("[^A-Z0-9]"), "")
|
||||
Regex("""^(?:MSVC|VCREDIST|VC)(\d{4})""").find(key)?.let { m -> return listOfNotNull(VC_YEAR[m.groupValues[1]]) }
|
||||
@@ -67,40 +39,30 @@ object WinCompSources {
|
||||
}
|
||||
}
|
||||
|
||||
/** Unreal's prerequisite setup (UE4PrereqSetup_x64.exe, UEPrereqSetup_x64.exe): VC++ 2015-2022 and DirectX June 2010. */
|
||||
private val UE_PREREQ = Regex("""(?i)ue\d?prereqsetup""")
|
||||
|
||||
/** An Epic prerequisite ([path] the installer it runs, [name] what it is called) to its components. */
|
||||
fun epic(path: String, name: String): List<String> = when {
|
||||
UE_PREREQ.containsMatchIn(path) || name.contains("UE4 Prerequisites", true) || name.contains("UE5 Prerequisites", true) ||
|
||||
name.contains("Unreal Engine Prerequisites", true) -> listOf("vcredist2022", "d3dx9")
|
||||
else -> DependencyDetector.componentsFor(path).ifEmpty { if (path.isEmpty()) gog(name) else emptyList() }
|
||||
}
|
||||
|
||||
/** An installer a store runs after an install (Amazon's PostInstall "Command") to its components. */
|
||||
fun installer(path: String): List<String> = if (UE_PREREQ.containsMatchIn(path)) listOf("vcredist2022", "d3dx9") else DependencyDetector.componentsFor(path)
|
||||
|
||||
/** Steamworks Shared depot ids to (component, Steam's label). */
|
||||
fun steamDepots(ids: List<String>): List<Pair<String, String>> = ids.mapNotNull { SteamRedists.DEPOTS[it] }.distinctBy { it.first }
|
||||
|
||||
// ---- what each store left at install ----
|
||||
|
||||
/** Sidecar keys the store installs fill. */
|
||||
const val GOG_DEPENDENCIES = "dependencies"
|
||||
const val EPIC_PREREQ_PATH = "prereqPath"
|
||||
const val EPIC_PREREQ_NAME = "prereqName"
|
||||
/** Set beside the list when it was read whole (an empty list then means the store lists none). */
|
||||
const val LIST_READ = "listRead"
|
||||
|
||||
/** fuel.json's PostInstall commands. */
|
||||
fun amazonPostInstall(folder: File): List<String> = runCatching {
|
||||
val arr = JSONObject(File(folder, "fuel.json").readText()).optJSONArray("PostInstall") ?: return emptyList()
|
||||
(0 until arr.length()).mapNotNull { arr.optJSONObject(it)?.optString("Command")?.takeIf { c -> c.isNotEmpty() } }
|
||||
}.getOrDefault(emptyList())
|
||||
|
||||
// ---- per game ----
|
||||
|
||||
/** Steam's list for [appId]: the local appmanifest's SharedDepots, else the client's app info. */
|
||||
fun steamList(context: Context, gameDir: File?, appId: Int, gameName: String, auto: Boolean): List<Finding> {
|
||||
val local = SteamRedists.detect(gameDir, appId)
|
||||
val pairs = if (local.isNotEmpty()) local.map { it.componentName to it.label }
|
||||
@@ -110,7 +72,6 @@ object WinCompSources {
|
||||
}
|
||||
}
|
||||
|
||||
/** Everything known for [game], blocking (files; the client's app info; no network). */
|
||||
fun forGame(context: Context, game: Library.SteamGame): List<Finding> {
|
||||
val folder = game.gameFiles
|
||||
val out = ArrayList<Finding>()
|
||||
@@ -141,8 +102,6 @@ object WinCompSources {
|
||||
}
|
||||
else -> {}
|
||||
}
|
||||
// A game added in DroidDeck (Custom, or a store's) that is a Steam app: Steam's list for it,
|
||||
// on by itself when its files say so, else only recommended.
|
||||
if (game.library == Library.ADDED && folder != null) SteamMatch.get(context, folder.path)?.let { match ->
|
||||
val id = match.appId ?: return@let
|
||||
when (match.certainty) {
|
||||
@@ -151,7 +110,6 @@ object WinCompSources {
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
// The folder scan, for every game: what it bundles, as Recommended.
|
||||
folder?.let { DependencyDetector.detect(it) }?.forEach { rec ->
|
||||
out += Finding(rec.componentName, rec.reason, Origin.FOLDER, false, listOf(rec.reason, rec.kind.name))
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user