Rename the app SteamDeck → DroidDeck

App name, app ID and code package: DroidDeck, com.droiddeck.launcher
(sources moved to com/droiddeck/launcher, the 68 JNI functions renamed
with them). The new app ID installs beside SteamDeck rather than over it.

Everywhere the name was the app's own: the sidebar title, the session
report, share zips, the shell title, wake-lock and log tags, User-Agents,
the Compose theme, the Download folder and switch files (droiddeck-env,
-osc, -driver, -tu-debug, -no-pad, -pad-log, -no-hud, -wlr-renderer; the
old names are not read), and inside the runtime (droiddeck-desktop,
Firefox's droiddeck.js, the shortcuts tag, the rumble socket, debug and
cache paths). Build scripts, CI artifact (droiddeck-apk), CMake project,
README and the progress log follow.

Kept on purpose: Valve's Steam Deck (the -steamdeck flag,
steamdeck_publicbeta/stable, 'Steam Deck mode', the steamos.cloud
package URLs) and names inside the hosted desktop package (steamdeck.png,
steamdeck-steam, steamdeck-bigpicture). 'Desktop installed' now tests for
labwc instead of the launcher the app stages itself. A committed
__pycache__ .pyc is removed.
This commit is contained in:
The412Banner committed 2026-09-23 18:28:04 -04:00
1 parent a19dfb88a0
commit d160f464b6
118 files changed
+498 -487

No files matched your search

@@ -0,0 +1,173 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import android.graphics.Bitmap
import android.util.Log
import com.droiddeck.launcher.files.PeIconExtractor
import com.droiddeck.launcher.session.SessionPrefs
import org.json.JSONObject
import java.io.File
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLEncoder
/**
* Artwork for an added game: what the user put in the game's folder first, else what Steam's
* store has for the same title, fetched once into the app's cache. Four pieces, named the way
* the client names them in its grid folder: the portrait capsule, the wide header, the hero
* background and the logo; plus an icon pulled out of the game's own .exe. The session hands
* the paths to the runtime's shortcuts writer, which copies them into the client's grid.
*/
object AddedGameArt {
private const val TAG = "AddedGameArt"
private const val STORE_SEARCH = "https://store.steampowered.com/api/storesearch/?l=english&cc=US&term="
private const val CDN = "https://cdn.cloudflare.steamstatic.com/steam/apps/"
private const val RETRY_AFTER_MS = 7L * 24 * 3600 * 1000
class Art(val portrait: File?, val header: File?, val hero: File?, val logo: File?, val icon: File?) {
val any get() = portrait != null || header != null || hero != null || logo != null
}
private val IMAGE = listOf("png", "jpg", "jpeg")
private val PORTRAIT = listOf("cover", "poster", "grid", "boxart", "capsule", "folder", "library_600x900", "portrait")
private val HEADER = listOf("header", "banner", "library_header", "wide")
private val HERO = listOf("hero", "background", "library_hero")
private val LOGO = listOf("logo")
private fun cacheDir(context: Context, game: AddedGames.Game) = File(context.filesDir, "added-art/${game.appId}")
/** An image in the folder (or its `art` subfolder) under one of the given names, any image extension. */
private fun find(folder: File, names: List<String>): File? {
val dirs = listOf(folder, File(folder, "art"), File(folder, ".art"))
for (dir in dirs) for (name in names) for (ext in IMAGE) {
val f = File(dir, "$name.$ext")
if (f.isFile) return f
}
return null
}
/** What the folder itself offers; the file named after the folder counts as the portrait. */
private fun local(game: AddedGames.Game): Art {
val folder = game.folder
return Art(
portrait = find(folder, PORTRAIT + listOf(folder.name)),
header = find(folder, HEADER),
hero = find(folder, HERO),
logo = find(folder, LOGO),
icon = listOf("icon.png", "icon.ico").map { File(folder, it) }.firstOrNull { it.isFile },
)
}
/** The folder's art, else the cached Steam art, without touching the network. */
fun resolve(context: Context, game: AddedGames.Game): Art {
val own = local(game)
val cache = cacheDir(context, game)
fun cached(name: String) = File(cache, name).takeIf { it.isFile }
return Art(
portrait = own.portrait ?: cached("p.jpg"),
header = own.header ?: cached("header.jpg"),
hero = own.hero ?: cached("hero.jpg"),
logo = own.logo ?: cached("logo.png"),
icon = own.icon ?: exeIcon(context, game),
)
}
/** The first icon inside the game's .exe, kept as a PNG beside the cached art. */
private fun exeIcon(context: Context, game: AddedGames.Game): File? {
val cache = cacheDir(context, game)
val png = File(cache, "icon.png")
if (png.isFile) return png
val none = File(cache, "icon.none")
if (none.isFile) return null
cache.mkdirs()
val bitmap = runCatching { PeIconExtractor.extract(game.exe) }.getOrNull()
if (bitmap == null) { none.writeText(""); return null }
val tmp = File(cache, "icon.png.tmp")
tmp.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
return if (tmp.renameTo(png)) png else null
}
/**
* Looks the games up on Steam's store and fetches the art that is missing, once per game
* (a miss is retried after a week). Blocking: run it off the main thread. Returns true when
* anything new arrived.
*/
fun fetchMissing(context: Context, games: List<AddedGames.Game>): Boolean {
if (!SessionPrefs.addedGamesArt(context)) return false
var changed = false
for (game in games) {
if (local(game).portrait != null) continue
val cache = cacheDir(context, game)
val lookup = File(cache, "steam-appid")
if (File(cache, "p.jpg").isFile) continue
if (lookup.isFile && (lookup.readText().trim() != "none" || System.currentTimeMillis() - lookup.lastModified() < RETRY_AFTER_MS)) {
val id = lookup.readText().trim()
if (id == "none") continue
if (download(id, cache)) changed = true
continue
}
cache.mkdirs()
val id = runCatching { search(game.name) }.onFailure { Log.w(TAG, "${game.name}: store search failed (${it.message})") }.getOrNull()
if (id == null) { lookup.writeText("none"); continue }
lookup.writeText(id)
Log.i(TAG, "${game.name}: Steam app $id")
if (download(id, cache)) changed = true
}
return changed
}
private fun normalize(s: String) = s.lowercase().replace(Regex("[^a-z0-9]"), "")
/** The Steam appid whose store name matches the folder name best, or null for no match. */
private fun search(name: String): String? {
val term = name.replace(Regex("(?i)\\b(complete|definitive|legendary|goty|game of the year|deluxe|ultimate|remastered)( edition)?\\b"), " ").trim().ifEmpty { name }
val json = get(STORE_SEARCH + URLEncoder.encode(term, "UTF-8"))?.toString(Charsets.UTF_8) ?: return null
val items = JSONObject(json).optJSONArray("items") ?: return null
val want = normalize(name)
val wantShort = normalize(term)
var best: String? = null
var bestScore = 0
for (i in 0 until items.length()) {
val item = items.getJSONObject(i)
val got = normalize(item.optString("name"))
val score = when {
got == want -> 4
got == wantShort -> 3
got.startsWith(wantShort) || wantShort.startsWith(got) -> 2
i == 0 -> 1
else -> 0
}
if (score > bestScore) { bestScore = score; best = item.optString("id") }
}
return best?.takeIf { it.isNotEmpty() && bestScore >= 1 }
}
private fun download(id: String, cache: File): Boolean {
var got = false
for ((remote, localName) in listOf(
"library_600x900.jpg" to "p.jpg", "header.jpg" to "header.jpg", "library_hero.jpg" to "hero.jpg", "logo.png" to "logo.png",
)) {
val dst = File(cache, localName)
if (dst.isFile) continue
val bytes = get("$CDN$id/$remote") ?: continue
val tmp = File(cache, "$localName.tmp")
tmp.writeBytes(bytes)
if (tmp.renameTo(dst)) got = true
}
return got
}
private fun get(url: String): ByteArray? {
val c = URL(url).openConnection() as HttpURLConnection
c.connectTimeout = 10_000
c.readTimeout = 15_000
c.setRequestProperty("User-Agent", "DroidDeck-launcher")
return try {
if (c.responseCode != 200) null else c.inputStream.use { it.readBytes() }
} catch (e: Exception) {
Log.w(TAG, "$url: ${e.message}"); null
} finally {
c.disconnect()
}
}
}
@@ -0,0 +1,149 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import android.os.Environment
import android.util.Log
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.util.zip.CRC32
/**
* The user's own Windows games, added to the Steam client's library.
*
* A Games folder is scanned one level deep: each subfolder is one game, and the program to launch
* is the .exe in it that looks most like the game - the one named after the folder, else the
* largest, never an installer, redistributable or crash reporter - unless the user picked one
* for that game. Each game becomes a non-Steam shortcut in the client, under the ARM64 Proton,
* with the appid the client itself would derive, so launching from the rail and from the
* client's own library are the same thing. Any number of Games folders, from anywhere on the
* device: each is bound into the session under /root/Games on its own.
*/
object AddedGames {
private const val TAG = "AddedGames"
class Game(
val folder: File, val name: String, val exe: File, 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>,
) {
fun folderName(): String = folder.name
}
/** One Games folder and where the session sees it. */
class Root(val host: File, val guest: String)
/**
* The chosen folders with their guest paths: /root/Games/<folder name>, or with a short hash of
* the host path when two chosen folders share a name (so a folder's guest path, and with it
* every shortcut's appid, does not change when another folder is added or removed).
*/
fun roots(context: Context): List<Root> {
val hosts = SessionPrefs.addedGamesDirs(context).map { File(it) }
val names = hosts.groupingBy { it.name.lowercase() }.eachCount()
return hosts.map { host ->
val name = host.name.ifEmpty { "games" }
val guestName = if ((names[name.lowercase()] ?: 0) > 1) name + "-" + "%08x".format(CRC32().apply { update(host.path.toByteArray()) }.value).take(4) else name
Root(host, "$GUEST_DIR/$guestName")
}
}
private val SKIP = Regex(
"(?i)^(unins.*|setup.*|.*redist.*|vcredist.*|dxsetup.*|dxwebsetup.*|.*crash.*|.*report.*|dotnet.*|directx.*|.*prereq.*" +
"|.*installer.*|.*uninstall.*|.*updater?.*|.*config(ur.*)?|.*settings.*|.*editor.*|.*server.*|.*benchmark.*|.*helper.*|.*eac.*|.*easyanticheat.*|.*battleye.*)\\.exe$",
)
/** Where a host path appears inside the session, or null when the session cannot see it. */
/** Under here the chosen Games folders are bound inside the session, one each. */
const val GUEST_DIR = "/root/Games"
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
if (path.startsWith("$dir/")) return root.guest + "/" + path.removePrefix("$dir/")
}
SessionPrefs.romsDir(context).takeIf { it.isNotEmpty() }?.let { roms ->
if (path.startsWith("$roms/")) return "/root/ROMs/" + path.removePrefix("$roms/")
}
GameStorage.effective(context)?.let { lib ->
if (path.startsWith("${lib.path}/")) return "/mnt/bannerlator-sd/" + path.removePrefix("${lib.path}/")
}
return null
}
/** The .exe files a game folder offers, best first. */
fun candidates(folder: File): List<File> {
val exes = ArrayList<File>()
val roots = listOf(folder) + (folder.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList())
for (dir in roots) {
dir.listFiles { f -> f.isFile && f.name.endsWith(".exe", ignoreCase = true) && !SKIP.matches(f.name) }
?.let { exes.addAll(it) }
}
val key = folder.name.lowercase().replace(Regex("[^a-z0-9]"), "")
return exes.sortedWith(
compareByDescending<File> { it.parentFile == folder }
.thenByDescending { it.nameWithoutExtension.lowercase().replace(Regex("[^a-z0-9]"), "").let { n -> n == key || key.startsWith(n) || n.startsWith(key) } }
.thenByDescending { it.length() },
)
}
fun scan(context: Context): List<Game> {
val out = ArrayList<Game>()
for (root in roots(context)) {
val dir = root.host
if (!dir.isDirectory) { Log.w(TAG, "$dir is not a folder; skipped"); continue }
for (folder in dir.listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList()) scanGame(context, folder, out)
}
return out
}
private fun scanGame(context: Context, folder: File, out: MutableList<Game>) {
run {
val candidates = candidates(folder)
val chosen = SessionPrefs.addedGameExe(context, folder.path).takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
val exe = chosen ?: candidates.firstOrNull() ?: return
val guestExe = guestPath(context, exe)
if (guestExe == null) { Log.w(TAG, "${folder.name}: the session cannot see ${exe.path}"); return }
val guestDir = guestPath(context, exe.parentFile ?: folder) ?: return
val name = folder.name
val crc = CRC32().apply { update(("\"$guestExe\"" + name).toByteArray()) }.value
val appId = crc or 0x80000000L
out.add(Game(folder, name, exe, guestExe, guestDir, appId, (appId shl 32) or 0x02000000L, candidates))
}
}
/** 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("[")
games.forEachIndexed { i, g ->
if (i > 0) json.append(',')
json.append("{\"name\":").append(quote(g.name)).append(",\"exe\":").append(quote(g.guestExe))
.append(",\"dir\":").append(quote(g.guestDir)).append(",\"appid\":").append(g.appId)
// The art, as the session sees it: the app's cache is bound at its own path, a file in
// the game's folder at the folder's guest path.
val art = AddedGameArt.resolve(context, g)
val pieces = listOf("p" to art.portrait, "header" to art.header, "hero" to art.hero, "logo" to art.logo, "icon" to art.icon)
.mapNotNull { (k, f) -> f?.let { file -> artGuestPath(context, file)?.let { k to it } } }
if (pieces.isNotEmpty()) json.append(",\"art\":{").append(pieces.joinToString(",") { (k, v) -> quote(k) + ":" + quote(v) }).append('}')
json.append('}')
}
file.writeText(json.append(']').toString())
return file
}
private fun artGuestPath(context: Context, file: File): String? {
val files = context.filesDir.absolutePath
if (file.absolutePath.startsWith("$files/")) return file.absolutePath
return guestPath(context, file)
}
private fun quote(s: String) = "\"" + s.replace("\\", "\\\\").replace("\"", "\\\"") + "\""
}
@@ -0,0 +1,175 @@
package com.droiddeck.launcher.frontend
import android.content.Context
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SessionPrefs
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. */
class SteamGame(val appId: Int, val name: String, val art: File?, val library: String, val gameId: Long = appId.toLong())
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 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; "pcsx2" -> R.drawable.emu_pcsx2; "dolphin" -> R.drawable.emu_dolphin
"duckstation" -> R.drawable.emu_duckstation; "melonds" -> R.drawable.emu_melonds; "cemu" -> R.drawable.emu_cemu
"ppsspp" -> R.drawable.emu_ppsspp; else -> R.drawable.emu_retroarch
}
}
/** The client's own tools and runtimes live in steamapps beside the games; they are not titles. */
private val NOT_GAMES = setOf(228980, 1493710, 3127680, 4183110, 4427310, 4185400)
private val NAME = Regex("^\\s*\"name\"\\s*\"([^\"]*)\"", RegexOption.MULTILINE)
private val STATE = Regex("^\\s*\"StateFlags\"\\s*\"(\\d+)\"", RegexOption.MULTILINE)
fun steamGames(context: Context): List<SteamGame> {
val root = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam")
val cache = File(root, "appcache/librarycache")
val libraries = listOfNotNull(
root to "internal",
GameStorage.effective(context)?.let { File(it.path) to it.label },
)
val out = LinkedHashMap<Int, SteamGame>()
for ((library, label) in libraries) {
val steamapps = File(library, "steamapps")
steamapps.listFiles { f -> f.isFile && f.name.startsWith("appmanifest_") && f.name.endsWith(".acf") }
?.sortedBy { it.name }?.forEach { manifest ->
val appId = manifest.name.removePrefix("appmanifest_").removeSuffix(".acf").toIntOrNull() ?: return@forEach
if (appId in NOT_GAMES || out.containsKey(appId)) return@forEach
val text = try { manifest.readText() } catch (e: Exception) { 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 dir = File(cache, appId.toString())
val art = listOf("library_600x900.jpg", "logo.png", "library_header.jpg", "header.jpg")
.map { File(dir, it) }.firstOrNull { it.isFile }
out[appId] = SteamGame(appId, name, art, label)
}
}
return out.values.toList()
}
private class Spec(val id: String, val name: String, val system: String, val program: String, val folders: List<String>, val exts: Set<String>)
private val specs = listOf(
Spec("rpcs3", "RPCS3", "PS3", "/opt/appimages/rpcs3.AppImage", listOf("ps3"), setOf("iso")),
Spec("pcsx2", "PCSX2", "PS2", "/opt/appimages/pcsx2.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")),
Spec("melonds", "melonDS", "DS", "/opt/appimages/melonds.AppImage", listOf("ds", "nds"), setOf("nds", "dsi")),
Spec("cemu", "Cemu", "Wii U", "/opt/appimages/cemu.AppImage", listOf("wiiu", "wii u"), setOf("wua", "wud", "wux", "rpx")),
Spec("ppsspp", "PPSSPP", "PSP", "/usr/bin/PPSSPPSDL", listOf("psp"), setOf("iso", "cso", "pbp", "chd")),
Spec("retroarch", "RetroArch", "many systems", "/usr/bin/retroarch", emptyList(), emptySet()),
)
private val installedIds = mapOf(
"rpcs3" to "rpcs3", "pcsx2" to "pcsx2", "dolphin" to "dolphin", "duckstation" to "duckstation",
"melonds" to "melonds", "cemu" to "cemu", "ppsspp" to "emulators", "retroarch" to "emulators",
)
/** 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, then the root itself for
// a file left loose there - and one folder deeper, since a dump usually comes as a
// folder named for the game with the image inside it.
val systemDirs = romsRoot.listFiles { f -> f.isDirectory && f.name.lowercase() in spec.folders }.orEmpty().toList()
val dirs = LinkedHashSet<File>()
for (top in systemDirs + romsRoot) {
dirs.add(top)
top.listFiles { f -> f.isDirectory }?.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(dir.name, dir, "/root/ROMs/$rel", spec.id))
continue
}
dir.listFiles()?.sortedBy { it.name.lowercase() }?.forEach { f ->
val ext = f.extension.lowercase()
// A .bin beside a .cue is a track, not a game.
if (f.isFile && ext in spec.exts && !(ext == "bin" && File(dir, f.nameWithoutExtension + ".cue").isFile)) {
val rel = f.relativeTo(romsRoot).path
games.add(Rom(f.nameWithoutExtension.removeSuffix(".dec"), f, "/root/ROMs/$rel", spec.id))
}
}
}
}
if (spec.id == "rpcs3") games.addAll(rpcs3Installed(context))
Emulator(spec.id, spec.name, spec.system, spec.program, installedPackage(installedIds.getValue(spec.id)), games)
}
}
/**
* 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 ->
val eboot = File(dir, "USRDIR/EBOOT.BIN")
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",
art = File(dir, "ICON0.PNG").takeIf { it.isFile })
} ?: 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 {
val b = file.readBytes()
if (b.size < 20 || b[0] != 0.toByte() || b[1] != 'P'.code.toByte()) return out
fun u32(at: Int) = (b[at].toInt() and 0xff) or ((b[at + 1].toInt() and 0xff) shl 8) or ((b[at + 2].toInt() and 0xff) shl 16) or ((b[at + 3].toInt() and 0xff) shl 24)
fun u16(at: Int) = (b[at].toInt() and 0xff) or ((b[at + 1].toInt() and 0xff) shl 8)
val keys = u32(8); val data = u32(12); val count = u32(16)
for (i in 0 until count) {
val e = 20 + i * 16
if (e + 16 > b.size) break
val keyOff = u16(e); val fmt = u16(e + 2); val len = u32(e + 4); val dataOff = u32(e + 12)
val keyStart = keys + keyOff
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)
val start = data + dataOff
val end = minOf(b.size, start + len)
var stop = start
while (stop < end && b[stop] != 0.toByte()) stop++
out[key] = String(b, start, stop - start, Charsets.UTF_8)
}
}
} 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)
"dolphin" -> listOf("-e", guestPath)
"cemu" -> listOf("-g", guestPath)
else -> listOf(guestPath)
}
}