feat(storage): name, select and remove every prefix and store game (#2565)

* feat(storage): name, select and remove every prefix and store game

* feat(storage): bulk remove picks prefixes, shader caches or both

* fix(storage): count and clear a game's shader cache in every library

* fix(storage): guard shared prefixes, batches and active downloads

* fix(storage): count each shader cache once across games

* fix(storage): hold store uninstalls against downloads and keep every shortcut's options

* fix(stores): keep download cleanup and uninstall from overlapping

* fix(stores): wait for an installer's file discard before uninstalling

* fix(stores): a reinstall waits for the cancelled download's file cleanup

* fix(storage): fast first scan, readable 4:3 layout and every shader cache counted

* fix(storage): keep store sizes current and track discards from failing jobs

* fix(stores): uninstall waits for a cancelled update's cleanup

* test(stores): a reinstall waits for a failed job's discard
This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-11-13 12:32:24 -05:00
1 parent 69b612be1f
commit 58af2e136b
45 files changed
+1494 -146

No files matched your search

@@ -529,6 +529,17 @@ object AddedGames {
}
}
class Listed(val appId: Long, val name: String, val launchOptions: String)
fun listed(context: Context): List<Listed>? = runCatching {
val file = File(context.filesDir, "session/added-games.json")
if (!file.isFile) return null
val entries = org.json.JSONArray(file.readText())
(0 until entries.length()).mapNotNull { i ->
entries.optJSONObject(i)?.takeIf { it.has("appid") }?.let { Listed(it.optLong("appid") and 0xFFFFFFFFL, it.optString("name"), it.optString("launch")) }
}
}.getOrNull()
fun writeListing(context: Context, games: List<Game>,
extra: List<JSONObject> = listOfNotNull(com.droiddeck.launcher.stores.epic.EpicClient.steamListing(context))): File {
val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() }
@@ -1281,6 +1281,11 @@ object SessionPrefs {
fun addedGameStoredAppId(context: Context, folderPath: String): Long? =
prefs(context).getLong("addedAppId:$folderPath", 0L).takeIf { it != 0L }
fun addedGameFolders(context: Context): Map<Long, String> = prefs(context).all.mapNotNull { (key, value) ->
val id = (value as? Long)?.takeIf { key.startsWith("addedAppId:") && it != 0L } ?: return@mapNotNull null
(id and 0xFFFFFFFFL) to key.removePrefix("addedAppId:")
}.toMap()
fun followStoreGame(context: Context, key: String, folderPath: String, gone: (String) -> Boolean) = synchronized(addedGameLock) {
val p = prefs(context)
val previous = p.getString("storeFolder:$key", null)
@@ -155,6 +155,42 @@ object SteamStorage {
fun leftoverId(name: String): Int? = name.toLongOrNull()?.takeIf { it in 1 until (1L shl 31) }?.toInt()
fun shortcutId(name: String): Long? = name.toLongOrNull()
?.takeIf { it in Int.MIN_VALUE until 0 || it in (1L shl 31) until (1L shl 32) }?.and(0xFFFFFFFFL)
private val COMPAT_PATH = Regex("""STEAM_COMPAT_DATA_PATH=(?:"([^"]*)"|'([^']*)'|(\S+))""")
private val COMPAT_ID = Regex("""/compatdata/(-?\d+)/*$""")
fun sharedPrefixId(launchOptions: String): Long? {
val path = COMPAT_PATH.find(launchOptions)?.groupValues?.drop(1)?.firstOrNull { it.isNotEmpty() } ?: return null
return COMPAT_ID.find(path.trim())?.groupValues?.get(1)?.let(::shortcutId)
}
private val GAME_FOLDER = Regex("""Z:\\\\(?:[^"\\]+\\\\)*?(?:steamapps\\\\common|Games\\\\Stores\\\\[^"\\]+)\\\\([^"\\]+)""")
fun gameFolderHint(prefix: File): String? = runCatching {
listOf("pfx/system.reg", "pfx/user.reg").map { File(prefix, it) }.filter { it.isFile && it.length() < 64L * 1024 * 1024 }
.flatMap { f -> f.useLines { lines -> lines.flatMap { GAME_FOLDER.findAll(it).map { m -> m.groupValues[1] } }.toList() } }
.groupingBy { it }.eachCount().maxByOrNull { it.value }?.key
}.getOrNull()
class Shortcut(val name: String, val launchOptions: List<String>)
fun shortcuts(root: File): Map<Long, Shortcut>? = runCatching {
val userdata = File(root, "userdata")
val users = if (userdata.exists()) userdata.listFiles() ?: return null else emptyArray()
users.mapNotNull { File(it, "config/shortcuts.vdf").takeIf(File::isFile) }.flatMap { file ->
val vdf = com.droiddeck.launcher.frontend.SteamAppInfo.readMap(java.nio.ByteBuffer.wrap(file.readBytes()).order(java.nio.ByteOrder.LITTLE_ENDIAN), null)
(vdf["shortcuts"] as? Map<*, *>)?.values?.filterIsInstance<Map<*, *>>()?.mapNotNull { s ->
fun value(key: String) = s.entries.firstOrNull { (it.key as? String).equals(key, ignoreCase = true) }?.value as? String
val id = value("appid")?.toLongOrNull()?.and(0xFFFFFFFFL) ?: return@mapNotNull null
id to Shortcut(value("AppName") ?: "", listOfNotNull(value("LaunchOptions")))
}.orEmpty()
}.groupBy({ it.first }, { it.second }).mapValues { (_, all) ->
Shortcut(all.firstOrNull { it.name.isNotEmpty() }?.name.orEmpty(), all.flatMap { it.launchOptions })
}
}.getOrNull()
fun isStubPrefix(prefix: File): Boolean = prefix.walkTopDown().onEnter { !java.nio.file.Files.isSymbolicLink(it.toPath()) }
.none { it.isFile && it.name != "steam_autocloud.vdf" && !java.nio.file.Files.isSymbolicLink(it.toPath()) }
}
@@ -18,7 +18,7 @@ enum class Bucket { GAMES, GAME_DATA, TOOLS, COMPONENTS, STORES, DESKTOP, SYSTEM
class GameUsage(
val appId: Int, val name: String, val art: File?, val library: String, val internal: Boolean, val lastPlayed: Long,
val game: Long, val prefix: Long, val shaders: Long, val workshop: Long, val shaderDir: File?,
val game: Long, val prefix: Long, val shaders: Long, val workshop: Long, val shaderDirs: List<File>,
val x64: Boolean = false, val prefixDir: File? = null,
) {
val data: Long get() = prefix + shaders + workshop
@@ -33,7 +33,16 @@ class ToolUsage(
val games: Int, val isDefault: Boolean, val manifests: List<File>, val dirs: List<File>,
)
class Leftover(val appId: Int, val prefix: File?, val shaders: File?, val bytes: Long, val safe: Boolean)
class Leftover(val appId: Long, val prefix: File?, val shaders: File?, val bytes: Long, val safe: Boolean, val shortcut: Boolean = false, val name: String? = null, val prefixBytes: Long = 0)
enum class PrefixOwner { SHARED, LAUNCHER, GAME, UNKNOWN }
class KeptPrefix(
val dir: File, val owner: PrefixOwner, val name: String?, val bytes: Long, val library: String, val x64: Boolean, val users: List<String> = emptyList(),
val shaders: File? = null, val shaderBytes: Long = 0,
)
class StoreGameUsage(val game: com.droiddeck.launcher.stores.InstalledStoreGame, val bytes: Long, val internal: Boolean)
class ComponentUsage(
val comp: String, val version: String, val bytes: Long, val inUse: Boolean,
@@ -59,9 +68,11 @@ class StorageReport(
val components: List<ComponentUsage>,
val flatpakApps: List<FlatpakUsage>,
val flatpakRuntimes: Long,
val otherPrefixes: Long,
val kept: List<KeptPrefix>,
val leftoversChecked: Boolean,
val storeGames: List<StoreGameUsage> = emptyList(),
) {
val otherPrefixes: Long get() = kept.sumOf { it.bytes }
val droiddeck: Long get() = buckets.values.sum()
val installedShaders: Long get() = games.sumOf { it.shaders }
val unusedTools: List<ToolUsage> get() = tools.filter { it.state == ToolState.UNUSED }
@@ -91,7 +102,16 @@ object StorageScan {
fun steamRoot(context: Context) = SessionPrefs.steamRoot(context, "arm64")
fun measure(file: File): Long = Walker().measure(file)
fun scan(context: Context): StorageReport {
val phases = ArrayList<String>()
var mark = android.os.SystemClock.elapsedRealtime()
fun phase(name: String) {
val now = android.os.SystemClock.elapsedRealtime()
phases.add("$name ${now - mark}")
mark = now
}
val walker = Walker()
val files = context.filesDir
val rootfs = LinuxRuntime.rootDir(context)
@@ -99,6 +119,7 @@ object StorageScan {
val x64Root = SessionPrefs.steamRoot(context, "x86_64").takeIf { SteamStorage.x64ClientPresent(it) }
val clients = listOfNotNull("arm64", "x86_64".takeIf { x64Root != null })
fun canonical(f: File) = runCatching { f.canonicalPath }.getOrDefault(f.path)
phase("setup")
val art = clients.associate { arch ->
(arch == "x86_64") to runCatching { Library.steamGames(context, arch = arch) }.getOrDefault(emptyList()).associateBy { it.appId }
}
@@ -106,6 +127,7 @@ object StorageScan {
class Lib(val root: File, val label: String, val internal: Boolean, val data: File, val listing: SteamStorage.Listing?, val x64: Boolean) {
val manifests: List<SteamStorage.Manifest>? get() = listing?.manifests
}
phase("steam games")
val libs = clients.flatMap { arch ->
val x64 = arch == "x86_64"
val primary = canonical(SessionPrefs.steamRoot(context, arch))
@@ -123,6 +145,7 @@ object StorageScan {
val clientIds = libs.groupBy { it.x64 }.mapValues { (_, own) -> own.flatMap { it.listing?.ids.orEmpty() }.toSet() }
fun installedGames(x64: Boolean) = libs.filter { it.x64 == x64 }.flatMap { it.manifests.orEmpty() }
.filter { !SteamStorage.isTool(it) && it.installed }.map { it.appId.toString() }.toSet()
phase("libraries")
val armUse = runCatching { SteamStorage.compatMappings(File(steamRoot, "config/config.vdf").readText()) }.getOrNull()
?.let { SteamStorage.ToolUse(it, installedGames(false)) }
val x64Vdf = x64Root?.let { File(it, "config/config.vdf") }
@@ -132,8 +155,10 @@ object StorageScan {
val uses = listOfNotNull(armUse, x64Use)
fun gamesOn(tool: String) = uses.sumOf { it.games(tool) }
val libraryDataRoots = File(files, "steam-libraries").listFiles().orEmpty().filter { it.isDirectory }
val tools = LinkedHashMap<String, ToolUsage>()
val games = ArrayList<GameUsage>()
val countedShaders = HashSet<String>()
for (lib in libs) {
for (m in lib.manifests.orEmpty()) {
val dir = m.installDir
@@ -176,17 +201,19 @@ object StorageScan {
val compatRoot = File(lib.data, "steamapps/compatdata").takeIf { it.isDirectory } ?: File(lib.root, "steamapps/compatdata")
val prefixDir = File(compatRoot, m.appId.toString()).takeIf { it.isDirectory }
val prefix = prefixDir?.let { walker.measure(it) } ?: 0
val shaderDir = File(lib.data, "steamapps/shadercache/${m.appId}").takeIf { it.isDirectory }
val shaders = shaderDir?.let { walker.measure(it) } ?: 0
val shaderDirs = ((listOf(lib) + libs.filter { it !== lib && it.x64 == lib.x64 }).map { it.data } + libraryDataRoots)
.map { File(it, "steamapps/shadercache/${m.appId}") }.filter { it.isDirectory }.distinctBy { canonical(it) }
val shaders = shaderDirs.filter { countedShaders.add(canonical(it)) }.sumOf { walker.measure(it) }
val workshop = File(lib.root, "steamapps/workshop/content/${m.appId}").takeIf { it.isDirectory }?.let { walker.measure(it) } ?: 0
val known = art[lib.x64]?.get(m.appId)
games.add(GameUsage(
m.appId, known?.name ?: m.name, known?.art, lib.label, lib.internal, m.lastPlayed,
gameBytes, prefix, shaders, workshop, shaderDir, lib.x64, prefixDir,
gameBytes, prefix, shaders, workshop, shaderDirs, lib.x64, prefixDir,
))
}
}
phase("manifests and games")
File(steamRoot, "compatibilitytools.d").listFiles()?.sortedBy { it.name }?.forEach { dir ->
if (!dir.isDirectory) return@forEach
val bytes = walker.measure(dir)
@@ -206,6 +233,7 @@ object StorageScan {
)
}
phase("compat tools")
val leftovers = ArrayList<Leftover>()
for (lib in libs) {
if (!everyLibraryRead) break
@@ -217,16 +245,22 @@ object StorageScan {
for (id in (prefixes.keys + caches.keys).sorted()) {
val prefix = prefixes[id]
val cache = caches[id]
val bytes = (prefix?.let { walker.measure(it) } ?: 0) + (cache?.let { walker.measure(it) } ?: 0)
val prefixBytes = prefix?.let { walker.measure(it) } ?: 0
val bytes = prefixBytes + (cache?.let { walker.measure(it) } ?: 0)
val safe = prefix == null || SteamStorage.isStubPrefix(prefix)
leftovers.add(Leftover(id, prefix, cache, bytes, safe))
val name = if (safe) null else runCatching {
com.droiddeck.launcher.frontend.SteamAppInfo.info(context, id, File(if (lib.x64) x64Root ?: steamRoot else steamRoot, "appcache/appinfo.vdf"))?.name
}.getOrNull()?.ifEmpty { null }
leftovers.add(Leftover(id.toLong(), prefix, cache, bytes, safe, name = name, prefixBytes = prefixBytes))
}
}
phase("leftovers")
val logs = SessionPaths.sessionFolders(context).filter { it != SessionPaths.current() } +
listOf(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR)).filter { it.exists() }
val logBytes = logs.sumOf { walker.measure(it) }
phase("logs")
val flatpakDir = File(rootfs, "root/.local/share/flatpak")
val flatpakNames = runCatching { FlatpakManager.installedApps(context) }.getOrDefault(emptyList()).associate { it.id to it.name }
val flatpakApps = File(flatpakDir, "app").listFiles().orEmpty().filter { it.isDirectory }.map { dir ->
@@ -234,6 +268,7 @@ object StorageScan {
}.sortedByDescending { it.bytes }
val flatpakRuntimes = File(flatpakDir, "runtime").takeIf { it.isDirectory }?.let { walker.measure(it) } ?: 0
phase("flatpak")
val componentsDir = File(files, "components")
val stored = runCatching { ComponentsManager.stored(context) }.onFailure { Log.w("StorageScan", "components", it) }.getOrNull()
val components = stored?.let { st ->
@@ -241,10 +276,70 @@ object StorageScan {
st.originals.map { ComponentUsage(it.comp, it.protonVersion, it.size, it.kept, protonId = it.protonId, protonName = it.protonName) }
}.orEmpty()
val otherPrefixes = libs.flatMap { lib ->
File(lib.data, "steamapps/compatdata").listFiles().orEmpty().filter { it.isDirectory && SteamStorage.leftoverId(it.name) == null }
}.sumOf { walker.measure(it) }
phase("components")
val added = com.droiddeck.launcher.frontend.AddedGames.listed(context)
val shortcuts = listOfNotNull(steamRoot, x64Root).map { SteamStorage.shortcuts(it) }
val ownersRead = added != null && shortcuts.all { it != null }
val live = HashMap<Long, String>()
shortcuts.forEach { it?.forEach { (id, s) -> live[id] = s.name } }
added?.forEach { live[it.appId] = it.name }
val folders = SessionPrefs.addedGameFolders(context)
val removedFolders = SessionPrefs.removedAddedGames(context).toSet()
folders.forEach { (id, path) -> if (id !in live && path !in removedFolders && File(path).exists()) live[id] = File(path).name }
val launchers = mapOf(
com.droiddeck.launcher.runtime.BattleNet.APP_ID to com.droiddeck.launcher.stores.Store.BATTLENET.label,
com.droiddeck.launcher.stores.ubisoft.UbisoftConnect.APP_ID to com.droiddeck.launcher.stores.Store.UBISOFT.label,
com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId to Library.EPIC_LAUNCHER_NAME,
)
val users = HashMap<Long, MutableSet<String>>()
fun shares(own: Long, name: String, launchOptions: String) {
SteamStorage.sharedPrefixId(launchOptions)?.takeIf { it != own }?.let { users.getOrPut(it) { LinkedHashSet() }.add(name) }
}
added?.forEach { shares(it.appId, it.name, it.launchOptions) }
shortcuts.forEach { it?.forEach { (id, s) -> s.launchOptions.forEach { shares(id, s.name, it) } } }
phase("added games and shortcuts")
val kept = ArrayList<KeptPrefix>()
for (lib in libs) {
val dirs = File(lib.data, "steamapps/compatdata").listFiles().orEmpty().filter { it.isDirectory && SteamStorage.leftoverId(it.name) == null }
val caches = File(lib.data, "steamapps/shadercache").listFiles().orEmpty()
.mapNotNull { f -> SteamStorage.shortcutId(f.name)?.takeIf { f.isDirectory }?.let { it to f } }.toMap()
for (dir in dirs) {
val bytes = walker.measure(dir)
val id = SteamStorage.shortcutId(dir.name)
val cache = id?.let { caches[it] }
val cacheBytes = cache?.let { walker.measure(it) } ?: 0
when {
dir.name == "0" -> kept.add(KeptPrefix(dir, PrefixOwner.SHARED, null, bytes, lib.label, lib.x64))
id != null && (id in launchers || id in users) -> kept.add(KeptPrefix(dir, PrefixOwner.LAUNCHER,
launchers[id] ?: live[id]?.ifEmpty { null }, bytes, lib.label, lib.x64, users[id].orEmpty().toList(), cache, cacheBytes))
id != null && id in live -> kept.add(KeptPrefix(dir, PrefixOwner.GAME, live[id]?.ifEmpty { null }, bytes, lib.label, lib.x64, shaders = cache, shaderBytes = cacheBytes))
id != null && ownersRead -> {
leftovers.add(Leftover(id, dir, cache, bytes + cacheBytes, SteamStorage.isStubPrefix(dir),
shortcut = true, name = folders[id]?.let { File(it).name } ?: SteamStorage.gameFolderHint(dir), prefixBytes = bytes))
}
else -> kept.add(KeptPrefix(dir, PrefixOwner.UNKNOWN, id?.toString() ?: dir.name, bytes, lib.label, lib.x64))
}
}
if (!ownersRead) continue
val prefixIds = dirs.mapNotNullTo(HashSet()) { SteamStorage.shortcutId(it.name) }
for ((id, cache) in caches) {
if (id in prefixIds || id in live || id in launchers || id in users) continue
leftovers.add(Leftover(id, null, cache, walker.measure(cache), true, shortcut = true, name = folders[id]?.let { File(it).name }))
}
}
phase("kept prefixes")
val storeGames = (com.droiddeck.launcher.stores.StoreInstallRoot.gameFolders(context).mapNotNull { folder ->
com.droiddeck.launcher.stores.StoreGameSidecar.read(folder)
?.takeIf { it.isInstalled || it.state == com.droiddeck.launcher.stores.StoreGameSidecar.STATE_UPDATING }
?.let { com.droiddeck.launcher.stores.InstalledStoreGame(it, folder) }
} + runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetBackend.installedGames(context) }.getOrDefault(emptyList()))
.map { g ->
val internal = g.folder.path.startsWith(files.path + "/")
StoreGameUsage(g, if (internal) walker.measure(g.folder) else -1L, internal)
}.sortedByDescending { it.bytes }
phase("store games")
val clientRoots = listOfNotNull(steamRoot, x64Root)
val apps = clientRoots.map { File(it, "steamapps") }
val privateRoots = File(files, "steam-libraries").listFiles().orEmpty().filter { it.isDirectory }
@@ -269,6 +364,8 @@ object StorageScan {
val componentBytes = m(componentsDir)
val droiddeck = m(files) + m(context.cacheDir) - rootfsBytes - privateBytes - componentBytes +
(privateBytes - toolsPrivate - privatePrefixes - privateShaders)
phase("totals")
Log.i("StorageScan", "scan ms: " + phases.joinToString(", "))
val stat = StatFs(files.path)
return StorageReport(
System.currentTimeMillis(), stat.totalBytes, stat.availableBytes,
@@ -284,7 +381,7 @@ object StorageScan {
),
prefixes, shaders, workshop, flatpak,
games.sortedByDescending { it.total }, tools.values.toList(), leftovers, logs, logBytes,
components, flatpakApps, flatpakRuntimes, otherPrefixes, everyLibraryRead,
components, flatpakApps, flatpakRuntimes, kept, everyLibraryRead, storeGames,
)
}
}
@@ -13,6 +13,7 @@ import com.droiddeck.launcher.files.FileOps
import com.droiddeck.launcher.runtime.FlatpakManager
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.StoreGameSidecar
enum class CleanItem { OLD_TOOLS, LEFTOVERS, LEFTOVERS_UNSURE, LOGS, UNUSED_CUSTOM, UNUSED_COMPONENTS, SHADERS }
@@ -27,6 +28,45 @@ object StorageState {
private set
var cleaning by mutableStateOf(false)
private set
var storeBatch by mutableStateOf(false)
private set
val busy: Boolean get() = cleaning || storeBatch
private var refreshAgain = false
val storeSizes = androidx.compose.runtime.mutableStateMapOf<String, Long>()
private var measuringStores = false
private fun sizeKey(usage: StoreGameUsage): String = with(usage.game) {
"${folder.path}|${sidecar.installVersion}|${sidecar.installedAt}|${StoreGameSidecar.file(folder).lastModified()}"
}
fun storeBytes(usage: StoreGameUsage): Long = if (usage.bytes >= 0) usage.bytes else storeSizes[sizeKey(usage)] ?: -1L
private fun measureStoreGames(app: Context) {
val current = report ?: return
if (measuringStores) return
val wanted = current.storeGames.filter { it.bytes < 0 && sizeKey(it) !in storeSizes }.map { sizeKey(it) to it.game.folder }
if (wanted.isEmpty()) return
measuringStores = true
Thread({
val started = android.os.SystemClock.elapsedRealtime()
for ((key, folder) in wanted) {
val bytes = runCatching { StorageScan.measure(folder) }.getOrDefault(0L)
main.post { storeSizes[key] = bytes }
}
Log.i(TAG, "measured ${wanted.size} store games on removable storage in ${android.os.SystemClock.elapsedRealtime() - started} ms")
main.post {
measuringStores = false
measureStoreGames(app)
}
}, "storage-store-sizes").start()
}
private fun publish(app: Context, result: StorageReport) {
report = result
val live = result.storeGames.mapTo(HashSet()) { sizeKey(it) }
storeSizes.keys.retainAll(live)
measureStoreGames(app)
}
var lastFreed by mutableStateOf<Long?>(null)
var progress by mutableStateOf<String?>(null)
private set
@@ -48,16 +88,21 @@ object StorageState {
fun refresh(context: Context, force: Boolean = false) {
val current = report
if (scanning || cleaning) return
if (scanning || cleaning) {
if (force) refreshAgain = true
return
}
if (!force && current != null && System.currentTimeMillis() - current.at < FRESH_MS) return
refreshAgain = false
val app = context.applicationContext
scanning = true
Thread({
val result = runCatching { StorageScan.scan(app) }
.onFailure { Log.w(TAG, "storage scan failed", it) }.getOrNull()
main.post {
if (result != null) report = result
if (result != null) publish(app, result)
scanning = false
if (refreshAgain) refresh(app, force = true)
}
}, "storage-scan").start()
}
@@ -84,7 +129,7 @@ object StorageState {
fun safeBytes(report: StorageReport): Long = SAFE.sumOf { bytes(report, it) }
fun clean(context: Context, items: Set<CleanItem>, onDone: (Long?) -> Unit) {
if (cleaning || SessionState.running) { onDone(null); return }
if (busy || SessionState.running) { onDone(null); return }
val app = context.applicationContext
appContext = app
cleaning = true
@@ -101,7 +146,7 @@ object StorageState {
}
fun removeTool(context: Context, tool: ToolUsage, onDone: (Long?) -> Unit) {
if (tool.state != ToolState.UNUSED || cleaning || SessionState.running) { onDone(null); return }
if (tool.state != ToolState.UNUSED || busy || SessionState.running) { onDone(null); return }
val app = context.applicationContext
cleaning = true
Thread({
@@ -119,7 +164,7 @@ object StorageState {
}
private fun act(context: Context, name: String, action: (Context, StorageReport) -> Boolean, onDone: (Long?) -> Unit = {}) {
if (cleaning || SessionState.running) { onDone(null); return }
if (busy || SessionState.running) { onDone(null); return }
val app = context.applicationContext
appContext = app
cleaning = true
@@ -137,8 +182,8 @@ object StorageState {
}
fun clearShaders(context: Context, appId: Int, x64: Boolean = false) = act(context, "shaders-$appId", { _, fresh ->
val dir = fresh.games.firstOrNull { it.appId == appId && it.x64 == x64 }?.shaderDir ?: return@act false
FileOps.delete(dir)
val dirs = fresh.games.firstOrNull { it.appId == appId && it.x64 == x64 }?.shaderDirs.orEmpty()
dirs.isNotEmpty() && dirs.map { FileOps.delete(it) }.all { it }
})
fun resetPrefix(context: Context, game: GameUsage) = act(context, "prefix-${game.appId}", { _, fresh ->
@@ -155,6 +200,41 @@ object StorageState {
true
})
fun resetKept(context: Context, prefix: KeptPrefix) = act(context, "kept-${prefix.dir.name}", { _, fresh ->
val dir = fresh.kept.firstOrNull { it.dir.path == prefix.dir.path && it.owner == prefix.owner }
?.takeIf { it.owner == PrefixOwner.SHARED || it.owner == PrefixOwner.GAME }?.dir ?: return@act false
check(FileOps.delete(dir)) { "cannot delete $dir" }
true
})
fun uninstallStoreGames(context: Context, games: List<StoreGameUsage>) {
if (busy || SessionState.running || games.isEmpty()) return
storeBatch = true
uninstallNext(context.applicationContext, games)
}
private fun uninstallNext(app: Context, games: List<StoreGameUsage>) {
val rest = games.dropWhile { com.droiddeck.launcher.stores.download.DownloadQueue.isActive(it.game.key) }
val next = rest.firstOrNull()
if (next == null || SessionState.running) {
storeBatch = false
com.droiddeck.launcher.stores.StoresState.notifyLibraryChanged(app)
refresh(app, force = true)
return
}
com.droiddeck.launcher.stores.StoresState.uninstall(app, next.game) { uninstallNext(app, rest.drop(1)) }
}
fun removeDirs(context: Context, dirs: List<java.io.File>) = act(context, "remove-${dirs.size}", { _, fresh ->
val allowed = (fresh.games.flatMap { it.shaderDirs + listOfNotNull(it.prefixDir) } + fresh.leftovers.flatMap { listOfNotNull(it.prefix, it.shaders) } +
fresh.kept.filter { it.owner == PrefixOwner.SHARED || it.owner == PrefixOwner.GAME }.flatMap { listOfNotNull(it.dir, it.shaders) }).mapTo(HashSet()) { it.path }
val wanted = dirs.distinctBy { it.path }
val targets = wanted.filter { it.path in allowed }
if (targets.size < wanted.size) Log.w(TAG, "kept ${wanted.size - targets.size} folders that are no longer safe to remove")
targets.forEach { check(FileOps.delete(it)) { "cannot delete $it" } }
targets.isNotEmpty()
})
fun removeComponent(context: Context, usage: ComponentUsage) = act(context, "component", { app, fresh ->
val current = fresh.components.firstOrNull { it.packageFile == usage.packageFile && it.protonId == usage.protonId &&
it.comp == usage.comp && it.version == usage.version } ?: return@act false
@@ -186,10 +266,11 @@ object StorageState {
private fun finish(app: Context, freed: Long?, onDone: (Long?) -> Unit) {
val rescanned = runCatching { StorageScan.scan(app) }.getOrNull()
main.post {
if (rescanned != null) report = rescanned
if (rescanned != null) publish(app, rescanned)
cleaning = false
lastFreed = freed
onDone(freed)
if (refreshAgain) refresh(app, force = true)
}
}
@@ -201,7 +282,7 @@ object StorageState {
CleanItem.LEFTOVERS -> report.leftovers.filter { it.safe }.forEach(::deleteLeftover)
CleanItem.LEFTOVERS_UNSURE -> report.leftovers.filter { !it.safe }.forEach(::deleteLeftover)
CleanItem.LOGS -> report.logs.forEach { FileOps.delete(it) }
CleanItem.SHADERS -> report.games.mapNotNull { it.shaderDir }.forEach { FileOps.delete(it) }
CleanItem.SHADERS -> report.games.flatMap { it.shaderDirs }.forEach { FileOps.delete(it) }
}
}
@@ -89,16 +89,62 @@ object StoreInstalls {
StoresState.logLine("uninstalled \"${game.sidecar.title}\"")
}
private val discarding = HashMap<String, Int>()
fun isDiscarding(folder: File): Boolean = synchronized(discarding) { folder.absolutePath in discarding }
internal fun beginDiscard(folder: File) { synchronized(discarding) { discarding.merge(folder.absolutePath, 1, Int::plus) } }
internal fun endDiscard(folder: File) {
synchronized(discarding) {
discarding.computeIfPresent(folder.absolutePath) { _, n -> (n - 1).takeIf { it > 0 } }
(discarding as Object).notifyAll()
}
}
fun awaitDiscard(folder: File) {
synchronized(discarding) { while (folder.absolutePath in discarding) (discarding as Object).wait() }
}
private val started = ThreadLocal<MutableList<Thread>?>()
fun collectingDiscards(into: MutableList<Thread> = ArrayList(), block: () -> Unit): List<Thread> {
val previous = started.get()
started.set(into)
try {
block()
} finally {
started.set(previous)
previous?.addAll(into)
}
return into
}
fun discard(context: Context, folder: File, caches: List<File>) {
val app = context.applicationContext
Thread({
val sidecar = StoreGameSidecar.read(folder)
val keep = sidecar?.isInstalled == true || sidecar?.state == StoreGameSidecar.STATE_UPDATING
caches.forEach { deleteTree(it) }
if (!keep) deleteTree(folder)
StoresState.logLine(if (keep) "removed update caches for ${folder.name}; verified file swaps are retained" else "removed ${folder.name}")
StoresState.notifyLibraryChanged(app)
}, "store-cancel-clean").start()
beginDiscard(folder)
val worker = Thread({
try {
discardNow(app, folder, caches)
} finally {
endDiscard(folder)
}
}, "store-cancel-clean")
started.get()?.add(worker)
worker.start()
}
@androidx.annotation.VisibleForTesting
internal var beforeDiscard: (File) -> Unit = {}
private fun discardNow(app: Context, folder: File, caches: List<File>) {
beforeDiscard(folder)
val sidecar = StoreGameSidecar.read(folder)
val keep = sidecar?.isInstalled == true || sidecar?.state == StoreGameSidecar.STATE_UPDATING
caches.forEach { deleteTree(it) }
if (!keep) deleteTree(folder)
StoresState.logLine(if (keep) "removed update caches for ${folder.name}; verified file swaps are retained" else "removed ${folder.name}")
StoresState.notifyLibraryChanged(app)
}
fun deleteTree(dir: File) {
@@ -314,23 +314,37 @@ object StoresState {
val key = "${game.sidecar.store.id}:${game.sidecar.id}"
uninstalling[key] = 0f
background("stores-uninstall", onFailure = { main.post { uninstalling.remove(key); onDone() } }) {
runCatching { backends[game.sidecar.store]?.uninstall(app, game) }
if (game.sidecar.store == Store.BATTLENET && com.droiddeck.launcher.runtime.BattleNet.games(app).any { it.folder.absolutePath == game.folder.absolutePath }) {
if (!com.droiddeck.launcher.stores.download.DownloadQueue.holdForRemovalWhenFree(key)) {
logLine("kept \"${game.sidecar.title}\": its download or update is still running")
main.post { uninstalling.remove(key); onDone() }
return@background
}
StoreInstalls.uninstall(app, game, progress = { f -> main.post { if (key in uninstalling) uninstalling[key] = f } }, removed = {
main.post {
installed = installed.filterNot { it.folder.absolutePath == game.folder.absolutePath }
uninstalling.remove(key)
if (game.sidecar.store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchUpdates.applied(app, key)
if (game.sidecar.store == Store.GAMEJOLT) com.droiddeck.launcher.stores.gamejolt.GameJoltUpdates.applied(app, key)
}
})
main.post(onDone)
try {
StoreInstalls.awaitDiscard(game.folder)
uninstallHeld(app, game, key, onDone)
} finally {
com.droiddeck.launcher.stores.download.DownloadQueue.releaseRemoval(key)
}
}
}
private fun uninstallHeld(app: Context, game: InstalledStoreGame, key: String, onDone: () -> Unit) {
runCatching { backends[game.sidecar.store]?.uninstall(app, game) }
if (game.sidecar.store == Store.BATTLENET && com.droiddeck.launcher.runtime.BattleNet.games(app).any { it.folder.absolutePath == game.folder.absolutePath }) {
main.post { uninstalling.remove(key); onDone() }
return
}
StoreInstalls.uninstall(app, game, progress = { f -> main.post { if (key in uninstalling) uninstalling[key] = f } }, removed = {
main.post {
installed = installed.filterNot { it.folder.absolutePath == game.folder.absolutePath }
uninstalling.remove(key)
if (game.sidecar.store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchUpdates.applied(app, key)
if (game.sidecar.store == Store.GAMEJOLT) com.droiddeck.launcher.stores.gamejolt.GameJoltUpdates.applied(app, key)
}
})
main.post(onDone)
}
@Volatile var libraryListener: (() -> Unit)? = null
fun notifyLibraryChanged(context: Context) {
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.stores.download
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.StoresState
import java.util.concurrent.atomic.AtomicBoolean
@@ -102,6 +103,55 @@ object DownloadQueue {
private val lock = Any()
private val items = LinkedHashMap<String, Item>()
private val heldPaused = HashSet<String>()
private val removing = HashSet<String>()
private val cleaningUp = HashMap<String, Int>()
fun holdForRemoval(key: String): Boolean = synchronized(lock) {
val item = items[key]
if (item?.entry?.isActive == true || item?.job != null || key in cleaningUp || key in removing) return@synchronized false
removing.add(key)
true
}
fun releaseRemoval(key: String) { synchronized(lock) { removing.remove(key); (lock as Object).notifyAll() } }
fun holdForRemovalWhenFree(key: String): Boolean = synchronized(lock) {
while (true) {
val item = items[key]
if (item?.entry?.isActive == true || item?.job != null) return@synchronized false
if (key !in cleaningUp && key !in removing) break
(lock as Object).wait()
}
removing.add(key)
true
}
private fun beginCleanup(key: String): Boolean = synchronized(lock) {
if (key in removing) return@synchronized false
cleaningUp.merge(key, 1, Int::plus)
true
}
private fun holdCleanup(key: String) { synchronized(lock) { cleaningUp.merge(key, 1, Int::plus) } }
private fun endCleanup(key: String) {
synchronized(lock) {
cleaningUp.computeIfPresent(key) { _, n -> (n - 1).takeIf { it > 0 } }
(lock as Object).notifyAll()
}
}
private fun cleanUpLater(context: Context, key: String, name: String, work: () -> Unit) {
Thread({
try {
val deleting = ArrayList<Thread>()
try { StoreInstalls.collectingDiscards(deleting, work) } finally { deleting.forEach { it.join() } }
} finally {
endCleanup(key)
advance(context)
}
}, name).start()
}
fun holdPaused(key: String) = synchronized(lock) { heldPaused.add(key) }
private var running = 0
@@ -131,6 +181,7 @@ object DownloadQueue {
fun enqueue(context: Context, entry: DownloadEntry, factory: () -> DownloadJob) {
val app = context.applicationContext
synchronized(lock) {
if (entry.key in removing) { Log.i(TAG, "${entry.key}: being uninstalled"); return }
items[entry.key]?.let { if (it.entry.isActive) { Log.i(TAG, "${entry.key}: already queued"); return } }
items.remove(entry.key)
val state = if (heldPaused.remove(entry.key)) DownloadState.PAUSED else DownloadState.QUEUED
@@ -185,6 +236,7 @@ object DownloadQueue {
val retry: (() -> Unit)?
synchronized(lock) {
val item = items[key] ?: return
if (key in removing) return
if (item.entry.state != DownloadState.PAUSED && item.entry.state != DownloadState.FAILED) return
retry = item.retry
if (retry == null && item.factory == null) return
@@ -206,23 +258,28 @@ object DownloadQueue {
val app = context.applicationContext
val item: Item
val wasRunning: Boolean
var cleanup = false
var awaitDeletion: List<Thread> = emptyList()
synchronized(lock) {
item = items[key] ?: return
if (!item.entry.interruptible) return
wasRunning = item.entry.state == DownloadState.RUNNING
if (wasRunning) {
item.cancelled.set(true)
item.job?.cancel(deleteFiles = true)
val deleting = StoreInstalls.collectingDiscards { runCatching { item.job?.cancel(deleteFiles = true) } }
if (deleting.isNotEmpty()) { holdCleanup(key); awaitDeletion = deleting }
}
if (!wasRunning) {
cleanup = beginCleanup(key)
item.entry = item.entry.copy(state = DownloadState.CANCELLED, queuePosition = 0, finishedAt = System.currentTimeMillis())
renumber()
publishLocked()
}
}
if (!wasRunning) {
Thread({ runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }, "store-dl-cancel").start()
if (cleanup) {
cleanUpLater(app, key, "store-dl-cancel") { runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }
}
if (awaitDeletion.isNotEmpty()) cleanUpLater(app, key, "store-dl-cancel-wait") { awaitDeletion.forEach { it.join() } }
StoresState.logLine("cancelled \"${item.entry.name}\"")
StoreDownloadService.finish(app, key)
advance(app)
@@ -230,12 +287,16 @@ object DownloadQueue {
}
fun clear(context: Context, key: String) {
val item = synchronized(lock) { items[key] } ?: return
if (item.entry.state == DownloadState.RUNNING || item.entry.state == DownloadState.QUEUED) return
if (item.entry.state == DownloadState.FAILED || item.entry.state == DownloadState.PAUSED) {
Thread({ runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }, "store-dl-clear").start()
val item: Item
val cleanup: Boolean
synchronized(lock) {
item = items[key] ?: return
if (item.entry.state == DownloadState.RUNNING || item.entry.state == DownloadState.QUEUED) return
cleanup = (item.entry.state == DownloadState.FAILED || item.entry.state == DownloadState.PAUSED) && beginCleanup(key)
items.remove(key)
publishLocked()
}
synchronized(lock) { items.remove(key); publishLocked() }
if (cleanup) cleanUpLater(context.applicationContext, key, "store-dl-clear") { runCatching { item.factory?.invoke()?.cancel(deleteFiles = true) } }
StoreDownloadService.finish(context.applicationContext, key)
}
@@ -298,7 +359,7 @@ object DownloadQueue {
val next: Item
synchronized(lock) {
if (running >= parallel(context)) return
next = items.values.firstOrNull { it.entry.state == DownloadState.QUEUED } ?: return
next = items.values.firstOrNull { it.entry.state == DownloadState.QUEUED && it.entry.key !in cleaningUp } ?: return
running++
next.entry = next.entry.copy(state = DownloadState.RUNNING, stage = DownloadStage.MANIFEST, queuePosition = 0)
renumber()
@@ -318,7 +379,15 @@ object DownloadQueue {
val job = checkNotNull(item.factory).invoke()
synchronized(lock) { item.job = job }
StoresState.logLine("${item.entry.store.label}: fetching manifest for \"${item.entry.name}\"")
result = job.run(handle)
val deleting = ArrayList<Thread>()
try {
StoreInstalls.collectingDiscards(deleting) { result = job.run(handle) }
} finally {
if (deleting.isNotEmpty()) {
holdCleanup(item.entry.key)
cleanUpLater(context, item.entry.key, "store-dl-run-discard") { deleting.forEach { it.join() } }
}
}
if (result == null && !item.cancelled.get()) error = "install failed"
} catch (t: Throwable) {
error = t.message ?: t.javaClass.simpleName
@@ -17,6 +17,7 @@ import androidx.compose.foundation.interaction.collectIsHoveredAsState
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
@@ -86,6 +87,9 @@ import com.droiddeck.launcher.storage.Bucket
import com.droiddeck.launcher.storage.CleanItem
import com.droiddeck.launcher.storage.ComponentUsage
import com.droiddeck.launcher.storage.GameUsage
import com.droiddeck.launcher.storage.KeptPrefix
import com.droiddeck.launcher.storage.PrefixOwner
import com.droiddeck.launcher.storage.StoreGameUsage
import com.droiddeck.launcher.storage.StorageReport
import com.droiddeck.launcher.storage.StorageState
import com.droiddeck.launcher.storage.ToolReason
@@ -148,6 +152,7 @@ internal fun StoragePanel(s: FrontEndState, a: FrontEndActions) {
"data" -> GameDataView(report, s.sessionRunning) { view = "overview" }
"components" -> ComponentsView(report, s.sessionRunning) { view = "overview" }
"desktop" -> DesktopView(report, s.sessionRunning) { view = "overview" }
"stores" -> StoreGamesView(report, s.sessionRunning) { view = "overview" }
"tools" -> ToolsView(report, s.sessionRunning) { view = "overview" }
else -> Overview(report, s.sessionRunning, onCleanUp = { cleanup = true }, onOpen = { view = it })
}
@@ -260,12 +265,23 @@ private fun DefaultStorageGroup() {
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun Overview(report: StorageReport, sessionRunning: Boolean, onCleanUp: () -> Unit, onOpen: (String) -> Unit) {
val narrowPane = LocalNarrowPane.current
BoxWithConstraints(Modifier.fillMaxWidth()) {
val wide = !narrowPane && maxWidth >= WIDE_OVERVIEW
Column { OverviewContent(report, sessionRunning, wide, onCleanUp, onOpen) }
}
}
private val WIDE_OVERVIEW = 700.dp
private val NARROW_ROW = 640.dp
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun OverviewContent(report: StorageReport, sessionRunning: Boolean, wide: Boolean, onCleanUp: () -> Unit, onOpen: (String) -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val wide = !LocalNarrowPane.current
val used = report.total - report.free
val safe = StorageState.safeBytes(report)
val low = report.free < StorageState.LOW_SPACE_BYTES
@@ -275,7 +291,7 @@ private fun Overview(report: StorageReport, sessionRunning: Boolean, onCleanUp:
val usage: @Composable (Modifier) -> Unit = { m -> Column(m) {
FlowRow(verticalArrangement = Arrangement.spacedBy(4.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(stringResource(R.string.storage_internal), fontSize = 17.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
Text("· " + stringResource(R.string.storage_used_of, gb(used), gb(report.total)), fontSize = 15.sp, color = colors.onSurfaceVariant)
Text(stringResource(R.string.storage_used_of, gb(used), gb(report.total)), fontSize = 15.sp, color = colors.onSurfaceVariant)
Pill(stringResource(R.string.storage_free, gb(report.free)), if (low) AttentionAmber else pal.good)
}
val time = DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(report.at))
@@ -294,7 +310,7 @@ private fun Overview(report: StorageReport, sessionRunning: Boolean, onCleanUp:
Text(stringResource(R.string.storage_safe_now), fontSize = 13.sp, color = colors.onSurfaceVariant)
Text(gb(safe), fontSize = 26.sp, fontWeight = FontWeight.Bold, color = if (safe > 0) pal.good else colors.onBackground)
Text(stringResource(R.string.storage_safe_hint), fontSize = 12.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(bottom = 10.dp))
PrimaryButton(stringResource(R.string.storage_clean_up), enabled = !sessionRunning && !StorageState.cleaning, compact = true, onClick = onCleanUp)
PrimaryButton(stringResource(R.string.storage_clean_up), enabled = !sessionRunning && !StorageState.busy, compact = true, onClick = onCleanUp)
} }
if (wide) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(18.dp), modifier = summary) {
usage(Modifier.weight(1f))
@@ -338,7 +354,8 @@ private fun Overview(report: StorageReport, sessionRunning: Boolean, onCleanUp:
},
{ m ->
BucketCard(Bucket.STORES, Icons.Outlined.ShoppingBag, stringResource(R.string.storage_stores),
stringResource(R.string.storage_stores_hint), report.buckets.getValue(Bucket.STORES), m)
pluralStringResource(R.plurals.storage_games_installed, report.storeGames.size, report.storeGames.size),
report.buckets.getValue(Bucket.STORES), m) { onOpen("stores") }
},
{ m ->
BucketCard(Bucket.DESKTOP, Icons.Outlined.Monitor, stringResource(R.string.storage_desktop),
@@ -485,7 +502,7 @@ private fun CleanUpDialog(report: StorageReport, sessionRunning: Boolean, onDism
}
},
confirmButton = {
if (picked.isNotEmpty() && !sessionRunning && !StorageState.cleaning) {
if (picked.isNotEmpty() && !sessionRunning && !StorageState.busy) {
FocusText(stringResource(R.string.storage_free_button, gb(total)), pal.signal) {
StorageState.clean(ctx, picked) { onDismiss() }
}
@@ -501,8 +518,6 @@ private fun CleanUpDialog(report: StorageReport, sessionRunning: Boolean, onDism
private fun CleanRow(item: CleanItem, report: StorageReport, on: Boolean, modifier: Modifier, onToggle: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
val unsureCount = report.leftovers.count { !it.safe }
val safeCount = report.leftovers.count { it.safe }
val oldTools = report.unusedTools.filter { it.reason != ToolReason.CUSTOM }
@@ -517,6 +532,23 @@ private fun CleanRow(item: CleanItem, report: StorageReport, on: Boolean, modifi
CleanItem.UNUSED_COMPONENTS -> Triple(stringResource(R.string.storage_item_components), unusedLabels.joinToString(", "), 1)
CleanItem.SHADERS -> Triple(stringResource(R.string.storage_item_shaders), stringResource(R.string.storage_item_shaders_detail), 2)
}
ToggleRow(
title, detail, StorageState.bytes(report, item), on, modifier,
when (tag) {
0 -> stringResource(R.string.storage_tag_safe) to pal.good
1 -> stringResource(R.string.storage_tag_unused) to colors.onSurfaceVariant
else -> stringResource(if (item == CleanItem.SHADERS) R.string.storage_tag_stutter else R.string.storage_tag_saves) to AttentionAmber
},
onToggle,
)
}
@Composable
private fun ToggleRow(title: String, detail: String, bytes: Long, on: Boolean, modifier: Modifier, pill: Pair<String, Color>, onToggle: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
val shape = RoundedCornerShape(12.dp)
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
@@ -535,16 +567,12 @@ private fun CleanRow(item: CleanItem, report: StorageReport, on: Boolean, modifi
) { if (on) Icon(Icons.Filled.Check, contentDescription = null, tint = Color.White, modifier = Modifier.size(16.dp)) }
Column(Modifier.weight(1f)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(title, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
when (tag) {
0 -> Pill(stringResource(R.string.storage_tag_safe), pal.good)
1 -> Pill(stringResource(R.string.storage_tag_unused), colors.onSurfaceVariant)
else -> Pill(stringResource(if (item == CleanItem.SHADERS) R.string.storage_tag_stutter else R.string.storage_tag_saves), AttentionAmber)
}
Text(title, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false))
Pill(pill.first, pill.second)
}
Text(detail, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
Text(gb(StorageState.bytes(report, item)), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Text(gb(bytes), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
}
}
@@ -583,6 +611,8 @@ private fun GamesView(report: StorageReport, sessionRunning: Boolean, a: FrontEn
Column(Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
if (games.isEmpty()) Text(stringResource(R.string.storage_no_games), fontSize = 14.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(16.dp))
games.forEachIndexed { i, g ->
BoxWithConstraints(Modifier.fillMaxWidth()) {
val narrow = maxWidth < NARROW_ROW
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(14.dp),
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp),
@@ -594,13 +624,14 @@ private fun GamesView(report: StorageReport, sessionRunning: Boolean, a: FrontEn
Text(gameName(g), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(
listOfNotNull(
stringResource(R.string.storage_game_parts, gb(g.game), gb(g.data)).takeIf { narrow },
g.library.takeIf { !g.internal },
if (g.lastPlayed > 0) stringResource(R.string.storage_played, DateFormat.getDateInstance(DateFormat.MEDIUM).format(Date(g.lastPlayed * 1000))) else stringResource(R.string.storage_never_played),
).joinToString(" · "),
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = if (narrow) 2 else 1, overflow = TextOverflow.Ellipsis,
)
}
Column(Modifier.weight(1f)) {
if (!narrow) Column(Modifier.weight(1f)) {
Row(Modifier.fillMaxWidth().height(8.dp).clip(RoundedCornerShape(4.dp)).background(Color(0xFF0A0C0F))) {
listOf(g.game to BucketColors.getValue(Bucket.GAMES), g.prefix to BucketColors.getValue(Bucket.GAME_DATA), (g.shaders + g.workshop) to Color(0xFFC5B8FF))
.forEach { (v, c) -> if (v > 0) Box(Modifier.weight(v.toFloat() / max).fillMaxHeight().background(c)) }
@@ -615,6 +646,7 @@ private fun GamesView(report: StorageReport, sessionRunning: Boolean, a: FrontEn
Text(gb(g.total), fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, modifier = Modifier.widthIn(min = 72.dp))
SecondaryButton(stringResource(R.string.storage_uninstall), compact = true, enabled = !sessionRunning) { confirm = g }
}
}
if (i < games.lastIndex) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
}
@@ -662,7 +694,7 @@ private fun ToolsView(report: StorageReport, sessionRunning: Boolean, onBack: ()
stringResource(R.string.storage_tools_detail, gb(report.tools.sumOf { it.bytes }), gb(unused.sumOf { it.bytes })), onBack,
) {
if (unused.isNotEmpty()) PrimaryButton(stringResource(R.string.storage_remove_unused, gb(unused.sumOf { it.bytes })), compact = true,
enabled = !sessionRunning && !StorageState.cleaning) { confirmAll = true }
enabled = !sessionRunning && !StorageState.busy) { confirmAll = true }
}
if (sessionRunning) { Note(stringResource(R.string.storage_session_running)); Spacer(Modifier.height(4.dp)) }
SectionTitle(stringResource(R.string.storage_in_use), null)
@@ -731,26 +763,22 @@ private fun toolDetail(t: ToolUsage): String = when (t.reason) {
private fun ToolList(tools: List<ToolUsage>, sessionRunning: Boolean, onRemove: (ToolUsage) -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Column(Modifier.fillMaxWidth().clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
ListCard {
tools.forEachIndexed { i, t ->
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().heightIn(min = 56.dp).padding(horizontal = 14.dp, vertical = 8.dp),
) {
Column(Modifier.weight(1f)) {
Text(t.name, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(toolDetail(t), fontSize = 12.5.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
}
when (t.state) {
ToolState.IN_USE -> Pill(if (t.isDefault) stringResource(R.string.storage_tag_default) else pluralStringResource(R.plurals.storage_tag_games, t.games, t.games), pal.signal)
ToolState.REQUIRED -> Pill(stringResource(R.string.storage_tag_required), colors.onSurfaceVariant)
ToolState.UNUSED -> Pill(stringResource(R.string.storage_tag_not_used), AttentionAmber)
}
Text(gb(t.bytes), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, modifier = Modifier.widthIn(min = 70.dp))
if (t.state == ToolState.UNUSED) SecondaryButton(stringResource(R.string.storage_remove), compact = true, enabled = !sessionRunning && !StorageState.cleaning) { onRemove(t) }
else Icon(Icons.Outlined.Lock, contentDescription = null, tint = colors.onSurfaceVariant, modifier = Modifier.size(16.dp))
}
if (i < tools.lastIndex) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
ItemRow(
t.name, toolDetail(t), t.bytes, i == tools.lastIndex,
pill = {
when (t.state) {
ToolState.IN_USE -> Pill(if (t.isDefault) stringResource(R.string.storage_tag_default) else pluralStringResource(R.plurals.storage_tag_games, t.games, t.games), pal.signal)
ToolState.REQUIRED -> Pill(stringResource(R.string.storage_tag_required), colors.onSurfaceVariant)
ToolState.UNUSED -> Pill(stringResource(R.string.storage_tag_not_used), AttentionAmber)
}
},
action = {
if (t.state == ToolState.UNUSED) SecondaryButton(stringResource(R.string.storage_remove), compact = true, enabled = !sessionRunning && !StorageState.busy) { onRemove(t) }
else Icon(Icons.Outlined.Lock, contentDescription = null, tint = colors.onSurfaceVariant, modifier = Modifier.size(16.dp))
},
)
}
}
}
@@ -811,24 +839,72 @@ private fun ListCard(content: @Composable () -> Unit) {
}
@Composable
private fun ItemRow(title: String, detail: String?, bytes: Long, last: Boolean, pill: (@Composable () -> Unit)? = null, action: (@Composable () -> Unit)? = null) {
private fun ItemRow(
title: String, detail: String?, bytes: Long, last: Boolean, pill: (@Composable () -> Unit)? = null,
selected: Boolean? = null, onSelect: () -> Unit = {}, selectable: Boolean = true, slot: Boolean = false,
stack: Boolean = pill != null, action: (@Composable () -> Unit)? = null,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().heightIn(min = 56.dp).padding(horizontal = 14.dp, vertical = 8.dp),
) {
Column(Modifier.weight(1f)) {
Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (detail != null) Text(detail, fontSize = 12.5.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
BoxWithConstraints(Modifier.fillMaxWidth()) {
val tight = maxWidth < NARROW_ROW
val narrow = tight && stack
val size = @Composable {
Text(if (bytes < 0) "…" else gb(bytes), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
modifier = if (narrow) Modifier else Modifier.widthIn(min = 70.dp))
}
Column(Modifier.fillMaxWidth().heightIn(min = 56.dp).padding(horizontal = 14.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
if (selected != null) SelectBox(selected, selectable, onSelect) else if (slot) Spacer(Modifier.size(40.dp))
Column(Modifier.weight(1f)) {
Text(title, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = if (narrow) 2 else 1, overflow = TextOverflow.Ellipsis)
if (detail != null) Text(detail, fontSize = 12.5.sp, color = colors.onSurfaceVariant, maxLines = if (tight) 2 else 1, overflow = TextOverflow.Ellipsis)
}
if (narrow) size() else {
pill?.invoke()
size()
action?.invoke()
}
}
if (narrow) Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End),
modifier = Modifier.fillMaxWidth(),
) {
pill?.invoke()
action?.invoke()
}
}
pill?.invoke()
Text(gb(bytes), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, modifier = Modifier.widthIn(min = 70.dp))
action?.invoke()
}
if (!last) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
}
@Composable
private fun SelectBox(on: Boolean, enabled: Boolean, onToggle: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
val hot = enabled && (src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value)
val shape = RoundedCornerShape(6.dp)
val edge = when {
on || hot -> pal.signal
enabled -> colors.onSurfaceVariant
else -> colors.onSurfaceVariant.copy(alpha = 0.35f)
}
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.size(40.dp).clip(RoundedCornerShape(10.dp))
.background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent)
.then(if (enabled) Modifier.hoverable(src)
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Checkbox, onClick = onToggle)
.controllerConfirm(onClick = onToggle) else Modifier),
) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.size(22.dp).clip(shape).background(if (on) pal.signal else Color.Transparent).border(2.dp, edge, shape),
) { if (on) Icon(Icons.Filled.Check, contentDescription = null, tint = Color.White, modifier = Modifier.size(16.dp)) }
}
}
@Composable
private fun ConfirmDialog(title: String, body: String, confirm: String, danger: Boolean = true, onConfirm: () -> Unit, onDismiss: () -> Unit) {
val colors = MaterialTheme.colorScheme
@@ -846,22 +922,53 @@ private fun ConfirmDialog(title: String, body: String, confirm: String, danger:
)
}
private class DataTarget(val key: String, val label: String, val prefixes: List<Pair<java.io.File, Long>>, val shaders: List<Pair<java.io.File, Long>>)
@Composable
private fun GameDataView(report: StorageReport, sessionRunning: Boolean, onBack: () -> Unit) {
val ctx = LocalContext.current
val busy = sessionRunning || StorageState.cleaning
val busy = sessionRunning || StorageState.busy
var confirm by remember { mutableStateOf<com.droiddeck.launcher.storage.Leftover?>(null) }
var confirmPrefix by remember { mutableStateOf<com.droiddeck.launcher.storage.GameUsage?>(null) }
SubHeader(stringResource(R.string.storage_game_data), stringResource(R.string.storage_game_data_hint, gb(report.prefixes), gb(report.workshop), gb(report.shaders)), onBack)
var confirmKept by remember { mutableStateOf<KeptPrefix?>(null) }
var picked by remember { mutableStateOf(emptySet<String>()) }
var confirmBulk by remember { mutableStateOf(false) }
val games = report.games.filter { it.data >= ONE_MB || it.prefixDir != null }.sortedByDescending { it.data }
val leftovers = report.leftovers.sortedByDescending { it.bytes }
val safe = leftovers.filter { it.safe }
val unsure = leftovers.filter { !it.safe }
val kept = report.kept.filter { it.bytes + it.shaderBytes >= ONE_MB }.sortedByDescending { it.bytes + it.shaderBytes }
val safeLabel = pluralStringResource(R.plurals.storage_item_leftovers_detail, safe.size, safe.size)
val gameNames = games.associate { gameKey(it) to gameName(it) }
val unsureNames = unsure.associate { leftoverKey(it) to leftoverName(it) }
val keptNames = kept.associate { it.dir.path to keptName(it) }
val targets = buildList {
games.forEach { g ->
add(DataTarget(gameKey(g), gameNames[gameKey(g)].orEmpty(),
listOfNotNull(g.prefixDir?.let { it to g.prefix }), g.shaderDirs.takeIf { g.shaders > 0 }.orEmpty().mapIndexed { i, d -> d to if (i == 0) g.shaders else 0L }))
}
if (safe.isNotEmpty()) add(DataTarget("safe", safeLabel, safe.mapNotNull { l -> l.prefix?.let { it to l.prefixBytes } }, safe.mapNotNull { l -> l.shaders?.let { it to l.bytes - l.prefixBytes } }))
unsure.forEach { l -> add(DataTarget("left:${leftoverKey(l)}", unsureNames[leftoverKey(l)].orEmpty(), listOfNotNull(l.prefix?.let { it to l.prefixBytes }), listOfNotNull(l.shaders?.let { it to l.bytes - l.prefixBytes }))) }
kept.filter { it.owner == PrefixOwner.SHARED || it.owner == PrefixOwner.GAME }
.forEach { k -> add(DataTarget("kept:${k.dir.path}", keptNames[k.dir.path].orEmpty(), listOf(k.dir to k.bytes), listOfNotNull(k.shaders?.let { it to k.shaderBytes }))) }
}.associateBy { it.key }
val chosen = picked.mapNotNull { targets[it] }
fun bytesOf(t: DataTarget, prefixes: Boolean, shaders: Boolean): Long =
(if (prefixes) t.prefixes.sumOf { it.second } else 0L) + (if (shaders) t.shaders.sumOf { it.second } else 0L)
fun toggle(key: String) { picked = if (key in picked) picked - key else picked + key }
SubHeader(stringResource(R.string.storage_game_data), stringResource(R.string.storage_game_data_hint, gb(report.prefixes), gb(report.workshop), gb(report.shaders)), onBack) {
if (chosen.isNotEmpty()) PrimaryButton(stringResource(R.string.storage_remove_selected, gb(chosen.sumOf { bytesOf(it, true, true) })), compact = true, enabled = !busy) { confirmBulk = true }
}
ActionStatus()
if (sessionRunning) { Note(stringResource(R.string.storage_session_running)); Spacer(Modifier.height(4.dp)) }
val games = report.games.filter { it.data >= ONE_MB || it.prefixDir != null }.sortedByDescending { it.data }
SectionTitle(stringResource(R.string.storage_data_installed), gb(games.sumOf { it.data }))
ListCard {
if (games.isEmpty()) Text(stringResource(R.string.storage_no_games), fontSize = 14.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(16.dp))
games.forEachIndexed { i, g ->
val key = gameKey(g)
ItemRow(
gameName(g), stringResource(R.string.storage_data_parts, gb(g.prefix), gb(g.shaders), gb(g.workshop)), g.data, i == games.lastIndex,
selected = key in picked, selectable = !busy && (g.prefixDir != null || g.shaders > 0), onSelect = { toggle(key) }, stack = true,
action = {
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
SecondaryButton(stringResource(R.string.storage_clear_shaders), compact = true, enabled = !busy && g.shaders >= ONE_MB) { StorageState.clearShaders(ctx, g.appId, g.x64) }
@@ -871,33 +978,73 @@ private fun GameDataView(report: StorageReport, sessionRunning: Boolean, onBack:
)
}
}
val leftovers = report.leftovers.sortedByDescending { it.bytes }
if (!report.leftoversChecked) {
SectionTitle(stringResource(R.string.storage_data_leftovers), null)
Note(stringResource(R.string.storage_leftovers_unchecked))
}
if (leftovers.isNotEmpty()) {
SectionTitle(stringResource(R.string.storage_data_leftovers), gb(leftovers.sumOf { it.bytes }))
val safe = leftovers.filter { it.safe }
ListCard {
if (safe.isNotEmpty()) ItemRow(
pluralStringResource(R.plurals.storage_item_leftovers_detail, safe.size, safe.size), null, safe.sumOf { it.bytes }, leftovers.none { !it.safe },
safeLabel, null, safe.sumOf { it.bytes }, unsure.isEmpty(),
pill = { Pill(stringResource(R.string.storage_tag_safe), LocalPalette.current.good) },
selected = "safe" in picked, selectable = !busy, onSelect = { toggle("safe") },
action = { SecondaryButton(stringResource(R.string.storage_remove), compact = true, enabled = !busy) { StorageState.clean(ctx, setOf(CleanItem.LEFTOVERS)) { } } },
)
val unsure = leftovers.filter { !it.safe }
unsure.forEachIndexed { i, l ->
val key = "left:${leftoverKey(l)}"
ItemRow(
stringResource(R.string.storage_steam_app, l.appId), stringResource(R.string.storage_leftover_unsure_detail), l.bytes, i == unsure.lastIndex,
leftoverName(l), stringResource(R.string.storage_leftover_unsure_detail), l.bytes, i == unsure.lastIndex,
pill = { Pill(stringResource(R.string.storage_tag_saves), AttentionAmber) },
selected = key in picked, selectable = !busy, onSelect = { toggle(key) },
action = { SecondaryButton(stringResource(R.string.storage_remove), compact = true, enabled = !busy) { confirm = l } },
)
}
}
}
if (report.otherPrefixes > 0) {
SectionTitle(stringResource(R.string.storage_data_other), null)
ListCard { ItemRow(stringResource(R.string.storage_data_other_title), stringResource(R.string.storage_data_other_detail), report.otherPrefixes, true) }
if (kept.isNotEmpty()) {
SectionTitle(stringResource(R.string.storage_data_other), gb(kept.sumOf { it.bytes + it.shaderBytes }))
ListCard {
kept.forEachIndexed { i, k ->
val resettable = k.owner == PrefixOwner.SHARED || k.owner == PrefixOwner.GAME
val key = "kept:${k.dir.path}"
ItemRow(
keptName(k),
listOfNotNull(when (k.owner) {
PrefixOwner.SHARED -> stringResource(R.string.storage_shared_prefix_detail)
PrefixOwner.LAUNCHER -> if (k.users.isEmpty()) stringResource(R.string.storage_launcher_prefix)
else stringResource(R.string.storage_launcher_used_by, k.users.distinct().joinToString(", "))
PrefixOwner.GAME -> stringResource(R.string.storage_prefix_shaders, gb(k.bytes), gb(k.shaderBytes))
PrefixOwner.UNKNOWN -> stringResource(R.string.storage_unknown_prefix_detail)
}, k.shaderBytes.takeIf { it >= ONE_MB && k.owner != PrefixOwner.GAME }?.let { stringResource(R.string.storage_bulk_shaders) + " " + gb(it).replace(' ', ' ') }).joinToString(" · "),
k.bytes + k.shaderBytes, i == kept.lastIndex,
pill = if (k.owner == PrefixOwner.LAUNCHER) { { Pill(stringResource(R.string.storage_tag_required), MaterialTheme.colorScheme.onSurfaceVariant) } } else null,
selected = if (resettable) key in picked else null, slot = true, selectable = !busy, onSelect = { toggle(key) },
action = if (resettable) {
{ SecondaryButton(stringResource(R.string.storage_reset_prefix), compact = true, enabled = !busy) { confirmKept = k } }
} else null,
)
}
}
}
if (confirmBulk) BulkRemoveDialog(
chosen,
hasPrefixes = chosen.any { it.prefixes.isNotEmpty() }, hasShaders = chosen.any { it.shaders.isNotEmpty() },
bytesOf = ::bytesOf,
onConfirm = { prefixes, shaders ->
StorageState.removeDirs(ctx, chosen.flatMap { (if (prefixes) it.prefixes.map { p -> p.first } else emptyList()) + (if (shaders) it.shaders.map { c -> c.first } else emptyList()) })
picked = emptySet()
},
onDismiss = { confirmBulk = false },
)
confirmKept?.let { k ->
ConfirmDialog(
stringResource(R.string.storage_reset_prefix_title, keptName(k)),
if (k.owner == PrefixOwner.SHARED) stringResource(R.string.storage_reset_shared_confirm, gb(k.bytes))
else stringResource(R.string.storage_reset_prefix_confirm, gb(k.bytes), k.library),
stringResource(R.string.storage_reset_prefix),
onConfirm = { StorageState.resetKept(ctx, k) }, onDismiss = { confirmKept = null },
)
}
confirmPrefix?.let { g ->
ConfirmDialog(
@@ -908,19 +1055,125 @@ private fun GameDataView(report: StorageReport, sessionRunning: Boolean, onBack:
}
confirm?.let { l ->
ConfirmDialog(
stringResource(R.string.storage_remove_title, stringResource(R.string.storage_steam_app, l.appId)),
stringResource(R.string.storage_remove_title, leftoverName(l)),
stringResource(R.string.storage_leftover_confirm, gb(l.bytes)), stringResource(R.string.storage_remove),
onConfirm = { StorageState.removeLeftover(ctx, l) }, onDismiss = { confirm = null },
)
}
}
@Composable
private fun BulkRemoveDialog(
chosen: List<DataTarget>, hasPrefixes: Boolean, hasShaders: Boolean, bytesOf: (DataTarget, Boolean, Boolean) -> Long,
onConfirm: (prefixes: Boolean, shaders: Boolean) -> Unit, onDismiss: () -> Unit,
) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
var prefixes by remember { mutableStateOf(hasPrefixes) }
var shaders by remember { mutableStateOf(hasShaders) }
val total = chosen.sumOf { bytesOf(it, prefixes, shaders) }
val first = remember { FocusRequester() }
LaunchedEffect(Unit) { runCatching { first.requestFocus() } }
AlertDialog(
properties = androidx.compose.ui.window.DialogProperties(usePlatformDefaultWidth = false),
modifier = Modifier.fillMaxWidth(0.62f).widthIn(min = 420.dp, max = 760.dp),
onDismissRequest = onDismiss,
title = { Text(stringResource(R.string.storage_remove_selected, gb(total))) },
text = {
Column(Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(chosen.joinToString("\n") { "• " + it.label }, fontSize = 14.sp, color = colors.onBackground)
Spacer(Modifier.height(4.dp))
if (hasPrefixes) ToggleRow(
stringResource(R.string.storage_bulk_prefixes), stringResource(R.string.storage_bulk_prefixes_detail),
chosen.sumOf { bytesOf(it, true, false) }, prefixes, Modifier.focusRequester(first),
stringResource(R.string.storage_tag_saves) to AttentionAmber,
) { prefixes = !prefixes }
if (hasShaders) ToggleRow(
stringResource(R.string.storage_bulk_shaders), stringResource(R.string.storage_item_shaders_detail),
chosen.sumOf { bytesOf(it, false, true) }, shaders, if (hasPrefixes) Modifier else Modifier.focusRequester(first),
stringResource(R.string.storage_tag_stutter) to AttentionAmber,
) { shaders = !shaders }
}
},
confirmButton = {
if (prefixes || shaders) FocusText(stringResource(R.string.storage_remove), colors.error) { onDismiss(); onConfirm(prefixes, shaders) }
},
dismissButton = { FocusText(stringResource(R.string.common_cancel), colors.onBackground, onClick = onDismiss) },
)
}
private fun gameKey(g: com.droiddeck.launcher.storage.GameUsage) = "game:${g.x64}:${g.appId}:${g.prefixDir?.path}"
private fun leftoverKey(l: com.droiddeck.launcher.storage.Leftover) = l.prefix?.path ?: l.shaders?.path ?: l.appId.toString()
@Composable
private fun keptName(k: KeptPrefix): String {
val name = when (k.owner) {
PrefixOwner.SHARED -> stringResource(R.string.storage_shared_prefix)
PrefixOwner.GAME -> k.name ?: stringResource(R.string.storage_data_other_title)
else -> k.name ?: k.dir.name
}
return if (k.x64) stringResource(R.string.storage_game_x64, name) else name
}
@Composable
private fun leftoverName(l: com.droiddeck.launcher.storage.Leftover): String = when {
l.name != null -> l.name
l.shortcut -> stringResource(R.string.storage_shortcut_app, l.appId.toString())
else -> stringResource(R.string.storage_steam_app, l.appId)
}
@Composable
private fun StoreGamesView(report: StorageReport, sessionRunning: Boolean, onBack: () -> Unit) {
val ctx = LocalContext.current
val uninstalling = com.droiddeck.launcher.stores.StoresState.uninstalling
val busy = sessionRunning || StorageState.busy || uninstalling.isNotEmpty()
var confirm by remember { mutableStateOf<List<StoreGameUsage>>(emptyList()) }
var picked by remember { mutableStateOf(emptySet<String>()) }
val games = report.storeGames
val chosen = games.filter { it.game.folder.path in picked && !com.droiddeck.launcher.stores.download.DownloadQueue.isActive(it.game.key) }
SubHeader(stringResource(R.string.storage_stores),
pluralStringResource(R.plurals.storage_games_installed, games.size, games.size) + " · " + gb(games.sumOf { StorageState.storeBytes(it).coerceAtLeast(0) }), onBack) {
if (chosen.isNotEmpty()) PrimaryButton(stringResource(R.string.storage_uninstall_selected, gb(chosen.sumOf { StorageState.storeBytes(it).coerceAtLeast(0) })), compact = true, enabled = !busy) { confirm = chosen }
}
ActionStatus()
if (sessionRunning) { Note(stringResource(R.string.storage_session_running)); Spacer(Modifier.height(4.dp)) }
ListCard {
if (games.isEmpty()) Text(stringResource(R.string.storage_no_games), fontSize = 14.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(16.dp))
games.forEachIndexed { i, g ->
val removing = g.game.key in uninstalling
val downloading = com.droiddeck.launcher.stores.download.DownloadQueue.isActive(g.game.key)
val key = g.game.folder.path
ItemRow(
g.game.sidecar.title,
if (g.internal) g.game.sidecar.store.label else g.game.sidecar.store.label + " · " + stringResource(R.string.fm_drive_sd),
StorageState.storeBytes(g), i == games.lastIndex,
selected = key in picked && !downloading, selectable = !busy && !downloading, onSelect = { picked = if (key in picked) picked - key else picked + key },
action = {
SecondaryButton(stringResource(if (removing) R.string.stores_uninstalling else R.string.storage_uninstall), compact = true,
enabled = !busy && !downloading) { confirm = listOf(g) }
},
)
}
}
if (confirm.isNotEmpty()) {
val list = confirm
val total = gb(list.sumOf { StorageState.storeBytes(it).coerceAtLeast(0) })
ConfirmDialog(
if (list.size == 1) stringResource(R.string.stores_uninstall_title, list[0].game.sidecar.title) else stringResource(R.string.storage_uninstall_selected, total),
(if (list.size == 1) "" else list.joinToString("\n") { "• " + it.game.sidecar.title } + "\n\n") + stringResource(R.string.stores_uninstall_body_size, total),
stringResource(R.string.storage_uninstall),
onConfirm = { StorageState.uninstallStoreGames(ctx, list); picked = emptySet() }, onDismiss = { confirm = emptyList() },
)
}
}
@Composable
internal fun ComponentsView(report: StorageReport, sessionRunning: Boolean, onBack: () -> Unit) {
val ctx = LocalContext.current
val pal = LocalPalette.current
val colors = MaterialTheme.colorScheme
val busy = sessionRunning || StorageState.cleaning
val busy = sessionRunning || StorageState.busy
var confirm by remember { mutableStateOf<ComponentUsage?>(null) }
var confirmAll by remember { mutableStateOf(false) }
val unused = report.unusedComponents
@@ -978,7 +1231,7 @@ internal fun ComponentsView(report: StorageReport, sessionRunning: Boolean, onBa
@Composable
private fun DesktopView(report: StorageReport, sessionRunning: Boolean, onBack: () -> Unit) {
val ctx = LocalContext.current
val busy = sessionRunning || StorageState.cleaning
val busy = sessionRunning || StorageState.busy
var confirm by remember { mutableStateOf<com.droiddeck.launcher.storage.FlatpakUsage?>(null) }
var confirmPrune by remember { mutableStateOf(false) }
SubHeader(stringResource(R.string.storage_desktop), stringResource(R.string.storage_desktop_detail, gb(report.flatpak)), onBack) {