Compare commits

..
Author SHA1 Message Date
The412Banner b50dfa76d1 Game saves: show Manage saves only on added games 2026-09-29 23:36:49 -04:00
The412Banner 3f81ddff9b Game saves: Manage saves on each game's page instead of a separate page
The floppy disk beside the Steam cog and its Game saves page are gone. A game's
page now has Manage saves beside Proton prefix, a menu with Import saves (a
GameHub or Winlator zip, picked in the app's file picker; the saves there now are
backed up first), Export as GameHub zip, Export as Winlator zip (a folder picked
the same way) and Open save folder. The game's saves are looked for when the menu
opens. The Proton list and config.vdf reader only that page needed are removed.
2026-09-29 23:21:40 -04:00
The412Banner d1dec8d7a4 Game saves: import and export save zips per game
A floppy disk beside the Steam page's cog opens a Game saves page, laid out like
Components: the Proton at the top (from the client's compatibility tools, with
bannerlator-proton-arm64 shown as Proton Experimental), the zip type beside it
(GameHub or Winlator, LB / RB turn it), and the games the client runs with that
Proton (CompatToolMapping, its default for the rest), each with Import and Export.

Import picks a zip in the app's file picker, backs up the game's steamuser profile
to Download/DroidDeck/Saves/backups, then unzips drive_c with any user folder but
Public renamed to steamuser, so GameHub and Winlator zips both land. Export finds
the save folders by name under the usual roots (Bannerlator's SaveLocator), or
takes the whole profile, and writes <Game>_<date>.zip to a folder picked the same
way, under steamuser (GameHub) or xuser (Winlator). Imports wait while a session
runs. Ported from Bannerlator's GameSaveBackup and SaveLocator.
2026-09-29 23:01:21 -04:00
The412Banner e60097e5cb Merge pull request #89 from Droid-Deck/fix/resume-restore-minimized
Restore a game that minimized itself behind the Steam menu
2026-09-29 22:14:53 -04:00
5 changed files with 347 additions and 2 deletions

No files matched your search

@@ -38,6 +38,7 @@ import com.droiddeck.launcher.session.OfflineMode
import com.droiddeck.launcher.session.ProtonExtras
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.ui.ComponentsPage
import com.droiddeck.launcher.session.GameSaves
import com.droiddeck.launcher.session.SessionLogShare
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.ui.ProtonPage
@@ -111,6 +112,9 @@ class MainActivity : ComponentActivity() {
private var showComponents by mutableStateOf(false)
private var focusComponentsContent by mutableStateOf(true)
private var showMapping by mutableStateOf(false)
private var saveBusy: String? = null
/** What to do with the zip or folder the file picker hands back after a game page's Manage saves. */
private var onSavePicked: ((File) -> Unit)? = null
private var controllerSettings by mutableStateOf<ControllerPrefs.Settings?>(null)
private var catalog by mutableStateOf<List<DesktopCatalog.Entry>?>(null)
private var catalogLoading by mutableStateOf(false)
@@ -151,6 +155,42 @@ class MainActivity : ComponentActivity() {
private val pickAndroidDriver = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedUri(r.data)?.let { drivers.importDriver(it, linux = false) }
}
private val pickSaveZip = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
val then = onSavePicked.also { onSavePicked = null } ?: return@registerForActivityResult
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let(then)
}
private val pickSaveDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
val then = onSavePicked.also { onSavePicked = null } ?: return@registerForActivityResult
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let(then)
}
/** Import a save zip into [game]: pick it in the app's file picker, then back up and unzip off the main thread. */
private fun importSaves(name: String, game: () -> GameSaves.Game) {
if (SessionState.running) {
android.widget.Toast.makeText(this, "Close the Steam session first, so the game can't save over the import", android.widget.Toast.LENGTH_LONG).show()
return
}
onSavePicked = { zip ->
saveAction("Importing into $name") {
val (written, backup) = GameSaves.import(game(), zip)
val kind = GameSaves.layoutOf(zip)?.label ?: "zip"
"Imported $written files from the $kind into $name" + (backup?.let { ". Old saves backed up to Download/DroidDeck/Saves/backups" } ?: "")
}
}
pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip"), "Choose a save zip for $name", GameSaves.savesDir().parentFile?.parentFile?.path))
}
/** Export [game]'s saves in [layout] to a folder picked in the app's file picker. */
private fun exportSaves(name: String, layout: GameSaves.Layout, game: () -> GameSaves.Game) {
onSavePicked = { dir ->
saveAction("Exporting $name") {
val (zip, count) = GameSaves.export(game(), layout, dir)
"Exported $count files as a ${layout.label}: ${zip.path.removePrefix("/storage/emulated/0/")}"
}
}
GameSaves.savesDir().mkdirs()
pickSaveDir.launch(InAppFilePicker.buildDirIntent(this, "Choose where to save $name (${layout.label})", GameSaves.savesDir().path))
}
private val pickAddedGamesDir = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path ->
SessionPrefs.setAddedGamesDirs(this, addedGamesDirs + path)
@@ -348,6 +388,9 @@ class MainActivity : ComponentActivity() {
},
onProtons = { openProtons() },
onComponents = { focusContent -> openComponents(focusContent) },
// A game page's Manage saves: the game's Proton and saves are read when the work runs, off the main thread.
onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(sg) } },
onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(sg) } },
onPerformance = { refreshCores(); showProtons = false; showComponents = false; showMapping = false; showPerformance = true },
onRoms = { showRoms = true },
onFiles = { startActivity(Intent(this, com.droiddeck.launcher.files.FileManagerActivity::class.java)) },
@@ -659,6 +702,19 @@ class MainActivity : ComponentActivity() {
}, "catalog-desktop").start()
}
/** Runs a save import or export off the main thread, one at a time, and says how it went. */
private fun saveAction(label: String, work: () -> String) {
if (saveBusy != null) return
saveBusy = label
Thread({
val message = runCatching(work).getOrElse { e -> "$label failed: ${e.message ?: e.javaClass.simpleName}" }
ui.post {
saveBusy = null
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_LONG).show()
}
}, "game-saves-action").start()
}
private fun openProtons() {
settingsMode = null
showPerformance = false
@@ -1028,7 +1084,7 @@ class MainActivity : ComponentActivity() {
val games = if (ready) Library.steamGames(this) + com.droiddeck.launcher.frontend.AddedGames.scan(this).map { g ->
com.droiddeck.launcher.frontend.AddedGameArt.resolve(this, g).let { art ->
Library.SteamGame(
g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, "added", g.gameId,
g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, Library.ADDED, g.gameId,
hero = art.hero ?: art.header, gameFiles = g.folder,
protonPrefix = Library.protonPrefix(this, g.steamAppId?.toLong() ?: g.appId),
)
@@ -23,6 +23,9 @@ object Library {
val hero: File? = null, val lastPlayed: Long = 0L,
val gameFiles: File? = null, val protonPrefix: File? = null,
)
/** The [SteamGame.library] of a game added to the library rather than installed by Steam. */
const val ADDED = "added"
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). */
@@ -0,0 +1,238 @@
package com.droiddeck.launcher.session
import android.os.Environment
import com.droiddeck.launcher.frontend.Library
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
import java.util.zip.ZipOutputStream
/**
* Game saves in and out of a game's Proton prefix, as zips other apps read: GameHub keeps a prefix's
* drive_c rooted at "/drive_c/users/steamuser/…", Winlator / WinNative / Bannerlator at
* "drive_c/users/xuser/…". Proton here runs as steamuser too, so on the way in any user folder but
* Public becomes steamuser, and on the way out the chosen layout decides the user segment.
*
* Saves belong to the game's prefix (compatdata/<appid>/pfx), whichever Proton it runs with.
* Ported from Bannerlator's GameSaveBackup and SaveLocator.
*/
object GameSaves {
enum class Layout(val label: String, val rootPrefix: String, val user: String) {
GAMEHUB("GameHub zip", "/drive_c/", "steamuser"),
WINLATOR("Winlator zip", "drive_c/", "xuser"),
}
/** A game, its prefix, and the save folders found in it. */
data class Game(val game: Library.SteamGame, val prefix: File?, val saves: List<SaveDir>) {
val launched get() = prefix?.let { File(it, "drive_c").isDirectory } == true
}
/** A folder of saves, relative to the steamuser profile. */
data class SaveDir(val relPath: String, val files: Int, val bytes: Long)
private const val USER = "steamuser"
fun savesDir(): File = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "DroidDeck/Saves")
private fun backupsDir(): File = File(savesDir(), "backups")
/** [game] with its prefix and the saves found there; reads files, so not on the main thread. */
fun game(game: Library.SteamGame): Game = Game(game, game.protonPrefix, game.protonPrefix?.let { locate(it, game) } ?: emptyList())
// ------------------------------------------------------------------ finding saves
/** Roots of the steamuser profile that hold most PC game saves, in the order they are trusted. */
private val SAVE_ROOTS = listOf("Documents/My Games", "Saved Games", "AppData/Roaming", "Documents", "AppData/Local", "AppData/LocalLow")
private const val KEEP_THRESHOLD = 50
private fun profile(prefix: File) = File(prefix, "drive_c/users/$USER")
/**
* Folders under the save roots, one and two deep, whose names match the game's name or its folder's.
* Nested matches keep the outer folder only.
*/
fun locate(prefix: File, game: Library.SteamGame): List<SaveDir> {
val profile = profile(prefix)
if (!profile.isDirectory) return emptyList()
val ids = listOfNotNull(game.name, game.gameFiles?.name).map(::ident).filter { it.norm.isNotEmpty() }
if (ids.isEmpty()) return emptyList()
val hits = LinkedHashMap<String, Int>()
fun consider(dir: File) {
val d = ident(dir.name)
if (d.norm.isEmpty()) return
val s = ids.maxOf { score(it, d) }
if (s < KEEP_THRESHOLD) return
val rel = dir.relativeTo(profile).path.replace(File.separatorChar, '/')
if ((hits[rel] ?: -1) < s) hits[rel] = s
}
for (root in SAVE_ROOTS) {
File(profile, root).listFiles()?.filter { it.isDirectory }?.forEach { d1 ->
consider(d1)
d1.listFiles()?.filter { it.isDirectory }?.forEach(::consider)
}
}
val kept = ArrayList<String>()
for (rel in hits.entries.sortedByDescending { it.value }.map { it.key }) {
if (kept.none { rel == it || rel.startsWith("$it/") }) kept.add(rel)
}
return kept.map { rel ->
var files = 0
var bytes = 0L
File(profile, rel).walkTopDown().filter { it.isFile }.forEach { files++; bytes += it.length() }
SaveDir(rel, files, bytes)
}.filter { it.files > 0 }
}
private data class Ident(val norm: String, val tokens: Set<String>)
private fun ident(raw: String): Ident {
val cleaned = raw.lowercase().replace("®", "").replace("™", "").replace("©", "")
return Ident(cleaned.filter { it.isLetterOrDigit() }, cleaned.split(Regex("[^a-z0-9]+")).filter { it.isNotEmpty() }.toSet())
}
/** exact 100, one contains the other 70, half the words shared 50, close spelling 40. */
private fun score(a: Ident, b: Ident): Int {
if (a.norm.isEmpty() || b.norm.isEmpty()) return 0
if (a.norm == b.norm) return 100
if (a.norm.contains(b.norm) || b.norm.contains(a.norm)) return 70
if (a.tokens.isNotEmpty() && b.tokens.isNotEmpty() &&
a.tokens.intersect(b.tokens).size.toDouble() / minOf(a.tokens.size, b.tokens.size) >= 0.5) return 50
return if (1.0 - levenshtein(a.norm, b.norm).toDouble() / maxOf(a.norm.length, b.norm.length) >= 0.85) 40 else 0
}
private fun levenshtein(a: String, b: String): Int {
val prev = IntArray(b.length + 1) { it }
val cur = IntArray(b.length + 1)
for (i in 1..a.length) {
cur[0] = i
for (j in 1..b.length) cur[j] = minOf(cur[j - 1] + 1, prev[j] + 1, prev[j - 1] + if (a[i - 1] == b[j - 1]) 0 else 1)
System.arraycopy(cur, 0, prev, 0, cur.size)
}
return prev[b.length]
}
// ------------------------------------------------------------------ export
private fun stamp() = SimpleDateFormat("yyyy-MM-dd_HHmm", Locale.US).format(Date())
private fun safe(name: String) = name.replace(Regex("[/\\\\:*?\"<>|]"), "_").trim().ifEmpty { "game" }
/**
* Zips the game's saves into [dir] as "<Game>_<date>.zip" in [layout]. The found save folders when
* there are any, else the whole steamuser profile minus Temp and crash dumps. Returns the zip.
*/
fun export(game: Game, layout: Layout, dir: File): Pair<File, Int> {
val prefix = game.prefix ?: error("${game.game.name} has not been launched yet")
dir.mkdirs()
val out = File(dir, "${safe(game.game.name)}_${stamp()}.zip")
val count = zipProfile(profile(prefix), game.saves.map { it.relPath }.ifEmpty { null }, layout, out)
if (count == 0) { out.delete(); error("No save files found for ${game.game.name}") }
return out to count
}
private fun zipProfile(profile: File, roots: List<String>?, layout: Layout, out: File): Int {
if (!profile.isDirectory) return 0
val scope = roots?.map { File(profile, it) }?.filter { it.exists() } ?: listOf(profile)
var count = 0
ZipOutputStream(BufferedOutputStream(FileOutputStream(out))).use { zos ->
for (top in scope) top.walkTopDown()
.onEnter { d -> d.relativeTo(profile).path.replace(File.separatorChar, '/').let { !it.equals("AppData/Local/Temp", true) && !it.equals("AppData/Local/CrashDumps", true) } }
.filter { it.isFile }
.forEach { f ->
val rel = f.relativeTo(profile).path.replace(File.separatorChar, '/')
zos.putNextEntry(ZipEntry("${layout.rootPrefix}users/${layout.user}/$rel"))
f.inputStream().use { it.copyTo(zos) }
zos.closeEntry()
count++
}
}
return count
}
// ------------------------------------------------------------------ import
/**
* Unzips a GameHub or Winlator save zip into the game's drive_c, after zipping what its steamuser
* profile holds now into Download/DroidDeck/Saves/backups. Entries outside drive_c, launcher
* shortcuts and anything escaping drive_c are skipped. Returns (files written, backup or null).
*/
fun import(game: Game, zip: File): Pair<Int, File?> {
val prefix = game.prefix ?: error("${game.game.name} has not been launched yet")
val driveC = File(prefix, "drive_c")
if (!driveC.isDirectory) error("${game.game.name} has not been launched yet")
if (!looksLikeSaveZip(zip)) error("${zip.name} has no drive_c folder, so it isn't a GameHub or Winlator save zip")
backupsDir().mkdirs()
val backup = File(backupsDir(), "${safe(game.game.name)}_${stamp()}.zip")
val backedUp = zipProfile(profile(prefix), null, Layout.GAMEHUB, backup)
if (backedUp == 0) backup.delete()
val base = driveC.canonicalFile
var written = 0
ZipInputStream(BufferedInputStream(zip.inputStream())).use { zis ->
var e = zis.nextEntry
while (e != null) {
remap(e.name)?.let { rel ->
val out = File(driveC, rel).canonicalFile
if (out.path.startsWith(base.path + File.separator)) {
if (e.isDirectory) out.mkdirs()
else {
out.parentFile?.mkdirs()
Files.copy(zis, out.toPath(), StandardCopyOption.REPLACE_EXISTING)
written++
}
}
}
zis.closeEntry()
e = zis.nextEntry
}
}
return written to backup.takeIf { it.exists() }
}
/** Which layout a zip was written in, from its first user folder; null when it has none. */
fun layoutOf(zip: File): Layout? = runCatching {
ZipInputStream(BufferedInputStream(zip.inputStream())).use { zis ->
var e = zis.nextEntry
while (e != null) {
val segs = driveCSegments(e.name)
if (segs != null && segs.size >= 2 && segs[0].equals("users", true) && !segs[1].equals("Public", true))
return@use if (segs[1].equals("xuser", true)) Layout.WINLATOR else Layout.GAMEHUB
e = zis.nextEntry
}
null
}
}.getOrNull()
private fun looksLikeSaveZip(zip: File): Boolean = runCatching {
ZipInputStream(BufferedInputStream(zip.inputStream())).use { zis ->
var e = zis.nextEntry
while (e != null) { if (driveCSegments(e.name) != null) return@use true; e = zis.nextEntry }
false
}
}.getOrDefault(false)
/** An entry's path below drive_c, with any user folder but Public renamed to steamuser. */
private fun remap(raw: String): String? {
val segs = driveCSegments(raw)?.takeIf { it.isNotEmpty() } ?: return null
if (segs.any { it == ".." }) return null
// GameHub also packs its own launcher shortcuts; they are never saves.
if (segs[0].equals("proton_shortcuts", true)) return null
val last = segs.last().lowercase()
if ((last.endsWith(".lnk") || last.endsWith(".desktop") || last.endsWith(".url")) && segs.any { it.equals("Desktop", true) }) return null
if (segs.size >= 2 && segs[0].equals("users", true) && !segs[1].equals("Public", true)) segs[1] = USER
return segs.joinToString("/")
}
private fun driveCSegments(raw: String): MutableList<String>? {
val segs = raw.replace('\\', '/').trimStart('/').split("/").filter { it.isNotEmpty() && it != "." }
if (segs.isEmpty() || !segs[0].equals("drive_c", true)) return null
return segs.drop(1).toMutableList()
}
}
@@ -120,11 +120,56 @@ private fun GameActions(g: Library.SteamGame, s: FrontEndState, a: FrontEndActio
}
g.protonPrefix?.takeIf { it.isDirectory }?.let { dir ->
SecondaryButton("Proton prefix", compact = true) { a.onBrowseFiles(dir) }
// Only games added to the library; Steam titles keep their saves with Steam Cloud.
if (g.library == Library.ADDED) ManageSaves(g, dir, a)
}
BusyChip(s)
}
}
/**
* Manage saves: import a GameHub or Winlator save zip into this game's prefix, export its saves as
* either, or open the save folder found for it. The saves are looked for when the menu opens.
*/
@Composable
private fun ManageSaves(g: Library.SteamGame, prefix: java.io.File, a: FrontEndActions) {
var open by remember(g.gameId) { androidx.compose.runtime.mutableStateOf(false) }
val saves by androidx.compose.runtime.produceState<List<com.droiddeck.launcher.session.GameSaves.SaveDir>?>(null, g.gameId, open) {
if (open) value = kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
runCatching { com.droiddeck.launcher.session.GameSaves.locate(prefix, g) }.getOrDefault(emptyList())
}
}
val found = saves
val summary = when {
found == null -> "Looking for this game's saves…"
found.isEmpty() -> "No save folder found by name: an export takes the whole user folder."
else -> {
val mb = found.sumOf { it.bytes } / 1048576.0
(if (found.size == 1) found[0].relPath else "${found.size} save folders") + " · ${found.sumOf { it.files }} files · " +
(if (mb < 1) "${(mb * 1024).toInt()} KB" else String.format("%.1f MB", mb))
}
}
Box {
SecondaryButton("Manage saves", compact = true) { open = !open }
AnchoredMenu(open, onDismiss = { open = false }, title = "Game saves", note = summary) { first ->
MenuItem("Import saves…", checked = false, detail = "A GameHub or Winlator zip · the saves there now are backed up first", focusRequester = first) {
open = false; a.onSaveImport(g)
}
MenuItem("Export as GameHub zip…", checked = false, detail = "Saves under steamuser, for GameHub and BannerHub") {
open = false; a.onSaveExport(g, com.droiddeck.launcher.session.GameSaves.Layout.GAMEHUB)
}
MenuItem("Export as Winlator zip…", checked = false, detail = "Saves under xuser, for Winlator, WinNative and Bannerlator") {
open = false; a.onSaveExport(g, com.droiddeck.launcher.session.GameSaves.Layout.WINLATOR)
}
found?.firstOrNull()?.let { d ->
MenuItem("Open save folder", checked = false, detail = d.relPath) {
open = false; a.onBrowseFiles(java.io.File(prefix, "drive_c/users/steamuser/" + d.relPath))
}
}
}
}
}
/** When it was last played (or where it is, if never) over its name, then room for Launch. */
@Composable
private fun ColumnScope.GameHeroCopy(g: Library.SteamGame, titleSize: androidx.compose.ui.unit.TextUnit) {
@@ -234,7 +279,7 @@ private fun lastPlayedText(lastPlayed: Long): String? {
private fun libraryLabel(library: String): String = when (library) {
"internal" -> "Internal storage"
"added" -> "Added game"
Library.ADDED -> "Added game"
else -> library
}
@@ -133,6 +133,9 @@ class FrontEndActions(
val onProtons: () -> Unit,
/** The Components page: FEX / DXVK / VKD3D-Proton per Proton. */
val onComponents: (focusContent: Boolean) -> Unit,
/** A game page's Manage saves: import a save zip into this game, or export its saves in a layout. */
val onSaveImport: (Library.SteamGame) -> Unit = {},
val onSaveExport: (Library.SteamGame, com.droiddeck.launcher.session.GameSaves.Layout) -> Unit = { _, _ -> },
val onPerformance: () -> Unit,
val onRoms: () -> Unit,
val onFiles: () -> Unit,