fix: refresh repaired components and render Ubisoft Connect (#2090)

* fix: refresh repaired components and render Ubisoft Connect

* fix: address component repair and Wine registry review

* fix: repair manually enabled components and check registry writes

* fix: serialize component repairs and use Proton runinprefix

* fix: report queued component repair failures

* fix: preserve newer component repair waits

* Make component queue transitions atomic

* Isolate component apply failures by game

* Preserve pending repair when catalog is stale

* Restore persisted component repair revisions

* Update pending requirements atomically

* Respect disabled pending components per game

* Keep queue key state atomic while worker waits

* Pass selected game to component repairs

* Preserve pending repair when component is absent

* Preserve pending revision on catalog failure

* Test legacy pending repair revision recovery

* Isolate fake worker Steam app info lookup

* Merge queued Steam app info lookups

* Persist launch component revisions before repair

* Gate launch on component repair discovery

* Expand and refresh launch repair discovery

* Include new automatic picks in launch requirements

* Log repair persistence failures and align repair keys

* Use runtime key for Battle.net component repairs

* Retain failed component reapplications for retry

* Harden pending repairs and launch preparation

* Isolate wait-cool sleep mocking

* Allow launches without catalog when no repair is pending

* Queue launch repairs even if persistence fails

* Block launch when repair state cannot persist

* Allow launch when no component repair is needed

* Persist selected repairs when catalog is offline

* Drain offline component repair in test
This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-11-04 21:54:00 -05:00
1 parent ab92033b90
commit 516e3862fa
14 files changed
+756 -83

No files matched your search

@@ -198,6 +198,7 @@ class FrontEndActivity : ComponentActivity() {
private var gameStoresEnabled by mutableStateOf(true)
private var gameStoresSpeedTier by mutableStateOf("fast")
private var navRequest by mutableStateOf<String?>(null)
private val gameLaunchRequest = java.util.concurrent.atomic.AtomicLong()
private var storesShowMature by mutableStateOf(false)
private var storesSort by mutableStateOf(SessionPrefs.STORES_SORTS.first())
private var storesView by mutableStateOf(SessionPrefs.DEFAULT_STORES_VIEW)
@@ -1185,8 +1186,13 @@ class FrontEndActivity : ComponentActivity() {
onSteamGame = { g ->
if (shortcutPicker) chooseGameShortcut(g)
else {
com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g)
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) { launchGame(g) }
val request = gameLaunchRequest.incrementAndGet()
com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g) {
if (request != gameLaunchRequest.get() || isFinishing || isDestroyed) return@beforeLaunch
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) {
if (request == gameLaunchRequest.get() && !isFinishing && !isDestroyed) launchGame(g)
}
}
}
},
onEpicLauncher = { openEpicLauncher() },
@@ -1860,6 +1866,7 @@ class FrontEndActivity : ComponentActivity() {
else @Suppress("DEPRECATION") state.getParcelable(key)
override fun onDestroy() {
gameLaunchRequest.incrementAndGet()
cancelCompatLaunch()
updates.unregister()
super.onDestroy()
@@ -3,6 +3,8 @@ package com.droiddeck.launcher.frontend
import android.content.Context
import android.net.ConnectivityManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.PowerManager
import android.util.AtomicFile
import android.util.Log
@@ -20,7 +22,11 @@ object AutoComponents {
private const val TAG = "AutoComponents"
fun appKey(game: Library.SteamGame): String? =
if (game.library == Library.ADDED) Integer.toUnsignedString(game.appId) else game.appId.takeIf { it > 0 }?.toString()
when {
game.source == com.droiddeck.launcher.stores.Store.BATTLENET.id -> game.profileKey
game.library == Library.ADDED -> Integer.toUnsignedString(game.appId)
else -> game.appId.takeIf { it > 0 }?.toString()
}
fun autoPicks(findings: List<WinCompSources.Finding>, catalog: Map<String, WinComponents.Component>): Map<String, WinComponents.AutoReason> {
val out = LinkedHashMap<String, WinComponents.AutoReason>()
@@ -48,6 +54,8 @@ object AutoComponents {
val downloading = MutableStateFlow<Map<String, WinComponents.Progress>>(emptyMap())
val repairFailures = MutableStateFlow<Map<String, String>>(emptyMap())
val pendingGames = MutableStateFlow<Set<String>>(emptySet())
val pendingComponents = MutableStateFlow<Set<String>>(emptySet())
@@ -56,12 +64,12 @@ object AutoComponents {
if (job.pics != null) return
val flow = if (job.component != null) pendingComponents else pendingGames
val id = job.component ?: job.game?.let { appKey(it) } ?: return
flow.value = if (on) flow.value + id else flow.value - id
flow.value = if (on || job.component != null && job.key in queuedKeys) flow.value + id else flow.value - id
}
internal class Job(
val game: Library.SteamGame?, val component: String?, val asked: Boolean, val seq: Long, val pics: List<Int>? = null,
val inSession: Boolean = false,
val inSession: Boolean = false, val revision: Int? = null,
) {
val key get() = when {
pics != null -> "pics"
@@ -79,29 +87,45 @@ object AutoComponents {
@Volatile private var worker: Thread? = null
private const val PAUSE_MS = 15_000L
private fun waitFor(game: Library.SteamGame, id: String) {
val key = appKey(game) ?: return
synchronized(waiting) { waiting.getOrPut(id) { ArrayList() }.let { if (it.none { g -> appKey(g) == key }) it.add(game) } }
}
fun queueGame(context: Context, game: Library.SteamGame, asked: Boolean) {
if (appKey(game) == null) return
enqueue(context, Job(game, null, asked, seq.incrementAndGet()))
}
private fun queueDownload(context: Context, id: String, asked: Boolean, inSession: Boolean = false) =
enqueue(context, Job(null, id, asked, seq.incrementAndGet(), inSession = inSession))
fun queueRepair(context: Context, id: String, gameKey: String?, revision: Int) {
if (!WinComponents.validId(id)) return
gameKey?.let { Pending.add(context, it, listOf(id), mapOf(id to revision)) }
queueDownload(context, id, asked = true, inSession = gameKey != null,
revision = maxOf(revision, Pending.revision(context, id) ?: 0))
}
private fun queueDownload(context: Context, id: String, asked: Boolean, inSession: Boolean = false, revision: Int? = null) =
enqueue(context, Job(null, id, asked, seq.incrementAndGet(), inSession = inSession, revision = revision))
private fun enqueue(context: Context, job: Job) {
if (!queuedKeys.add(job.key)) {
synchronized(jobs) {
val added = synchronized(jobs) {
if (!queuedKeys.add(job.key)) {
val old = jobs.firstOrNull { it.key == job.key }
if (old != null && ((job.asked && !old.asked) || (job.inSession && !old.inSession)) && jobs.remove(old)) {
val revision = listOfNotNull(old?.revision, job.revision).maxOrNull()
val pics = listOfNotNull(old?.pics, job.pics).flatten().distinct().takeIf { old?.pics != null || job.pics != null }
if (old != null && ((job.asked && !old.asked) || (job.inSession && !old.inSession) || revision != old.revision || pics != old.pics) && jobs.remove(old)) {
jobs.add(Job(old.game ?: job.game, old.component, old.asked || job.asked,
if (job.asked && !old.asked) job.seq else old.seq, old.pics ?: job.pics, old.inSession || job.inSession))
if (job.asked && !old.asked) job.seq else old.seq, pics,
old.inSession || job.inSession, revision))
}
}
if (runNow && !draining) drain(context)
return
false
} else {
jobs.add(job)
mark(job, true)
true
}.also { (jobs as java.lang.Object).notifyAll() }
}
if (job.component != null) Log.i(TAG, "wincomp: queued ${job.component}")
mark(job, true)
jobs.add(job)
if (added && job.component != null) Log.i(TAG, "wincomp: queued ${job.component}")
if (runNow) { if (!draining) drain(context) } else ensureWorker(context.applicationContext)
}
@@ -113,8 +137,15 @@ object AutoComponents {
private fun gameProcessRunning(): Boolean = com.droiddeck.launcher.session.SteamGameProcess.running()
private fun queuePending(context: Context, key: String) {
Pending.ids(context, key).forEach { id ->
queueDownload(context, id, asked = true, inSession = true, revision = Pending.revision(context, id))
}
}
fun queueInSession(context: Context, game: Library.SteamGame) {
if (appKey(game) == null) return
val key = appKey(game) ?: return
queuePending(context, key)
enqueue(context, Job(game, null, true, seq.incrementAndGet(), inSession = true))
}
@@ -124,7 +155,6 @@ object AutoComponents {
try {
while (true) {
val job = next(context) ?: return
queuedKeys.remove(job.key)
run(context, job)
}
} finally {
@@ -135,6 +165,7 @@ object AutoComponents {
private fun next(context: Context): Job? = synchronized(jobs) {
val job = jobs.sortedWith(order).firstOrNull { !mustWait(context, it) } ?: return null
jobs.remove(job)
queuedKeys.remove(job.key)
job
}
@@ -148,13 +179,17 @@ object AutoComponents {
worker = Thread({
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND)
while (true) {
try { jobs.put(jobs.take()) } catch (e: InterruptedException) { return@Thread }
val job = next(app)
if (job == null) {
try { Thread.sleep(PAUSE_MS) } catch (e: InterruptedException) { return@Thread }
continue
val job = try {
synchronized(jobs) {
next(app) ?: run {
(jobs as java.lang.Object).wait(PAUSE_MS)
next(app)
}
}
} catch (e: InterruptedException) {
return@Thread
}
queuedKeys.remove(job.key)
if (job == null) continue
WinComponents.background { run(app, job) }
}
}, "auto-components").apply { isDaemon = true; start() }
@@ -164,18 +199,23 @@ object AutoComponents {
try {
when {
job.pics != null -> SteamAppInfo.lookup(context, job.pics)
job.component != null -> download(context, job.component, job.asked, job.inSession)
job.component != null -> download(context, job.component, job.asked, job.inSession, job.revision)
else -> job.game?.let { apply(context, it, job.asked, job.inSession) }
}
} catch (e: Exception) {
Log.w(TAG, "wincomp: ${job.key}: ${e.javaClass.simpleName}: ${e.message}")
job.component?.let {
repairFailures.value = repairFailures.value + (it to (e.message ?: "Install failed"))
Pending.drop(context, it, job.revision)
}
} finally {
mark(job, false)
changes.value = changes.value + 1
}
}
private fun apply(context: Context, game: Library.SteamGame, asked: Boolean, inSession: Boolean = false) {
private fun apply(context: Context, game: Library.SteamGame, asked: Boolean, inSession: Boolean = false,
knownCatalog: Map<String, WinComponents.Component>? = null) {
val key = appKey(game) ?: return
val folder = game.gameFiles
if (game.library == Library.ADDED && game.source == Library.ADDED && folder != null && SteamMatch.get(context, folder.path) == null) {
@@ -183,9 +223,10 @@ object AutoComponents {
}
val store = com.droiddeck.launcher.stores.Store.byId(game.source)
if (folder != null && (store == com.droiddeck.launcher.stores.Store.GOG || store == com.droiddeck.launcher.stores.Store.EPIC)) StoreListBackfill.fill(context, folder)
if (asked && online(context)) steamAppOf(context, game)?.let { SteamAppInfo.lookup(context, listOf(it)) }
if (knownCatalog == null && asked && online(context)) steamAppOf(context, game)?.let { SteamAppInfo.lookup(context, listOf(it)) }
val findings = findings(context, game)
val catalog = (catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name } ?: return
val refreshed = if (knownCatalog == null && asked && online(context)) catalogOf(context, true) else null
val catalog = knownCatalog ?: (refreshed ?: catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name } ?: return
val wanted = autoPicks(findings, catalog)
val user = WinComponents.selection(context, key).user
val before = WinComponents.selection(context, key).auto
@@ -196,22 +237,37 @@ object AutoComponents {
if (user[id] == false) { kept[id] = reason; continue }
if (id in installed) { kept[id] = reason; continue }
if (id in before) kept[id] = reason
synchronized(waiting) { waiting.getOrPut(id) { ArrayList() }.let { if (it.none { g -> appKey(g) == key }) it.add(game) } }
queueDownload(context, id, asked, inSession)
waitFor(game, id)
missing.add(id)
}
if (inSession) Pending.set(context, key, (Pending.ids(context, key).filter { it !in installed && it !in wanted } + missing).distinct())
if (before.keys != kept.keys) {
WinComponents.setAuto(context, key, kept)
Log.i(TAG, "${game.name}: on by itself ${kept.keys.joinToString().ifEmpty { "(none)" }}")
}
Pending.update(context, key, catalog.mapValues { it.value.revision }) { ids ->
ids.filter { id -> user[id] != false && (id !in installed && id !in wanted || (Pending.revision(context, id) ?: 0) > (catalog[id]?.revision ?: 0)) } + missing
}
missing.forEach { id -> queueDownload(context, id, asked, inSession, catalog[id]?.revision) }
changes.value = changes.value + 1
}
private fun download(context: Context, id: String, asked: Boolean, inSession: Boolean = false) {
val catalog = catalogOf(context, true)?.associateBy { it.name } ?: run { Pending.drop(context, id); return }
private fun download(context: Context, id: String, asked: Boolean, inSession: Boolean = false, requestedRevision: Int? = null) {
val catalog = catalogOf(context, true)?.associateBy { it.name } ?: run {
repairFailures.value = repairFailures.value + (id to "Could not load the component catalog")
return
}
val catalogComponent = catalog[id]
val requiredRevision = maxOf(requestedRevision ?: 0, Pending.revision(context, id) ?: 0)
if (catalogComponent != null && catalogComponent.revision < requiredRevision) {
repairFailures.value = repairFailures.value + (id to "The component catalog is older than the requested revision")
return
}
if (id !in installedOf(context)) {
val c = catalog[id] ?: run { Pending.drop(context, id); return }
val c = catalogComponent ?: run {
repairFailures.value = repairFailures.value + (id to "Component is no longer available")
Pending.drop(context, id, requestedRevision)
return
}
val started = System.currentTimeMillis()
downloading.value = downloading.value + (id to WinComponents.Progress(id, "", WinComponents.Phase.DOWNLOAD, -1))
val problem = try {
@@ -219,12 +275,28 @@ object AutoComponents {
} finally {
downloading.value = downloading.value - id
}
if (problem != null) { Log.w(TAG, "wincomp: $id did not install: $problem"); Pending.drop(context, id); return }
if (problem != null) {
repairFailures.value = repairFailures.value + (id to problem)
Log.w(TAG, "wincomp: $id did not install: $problem")
Pending.drop(context, id, maxOf(requestedRevision ?: 0, c.revision))
return
}
Log.i(TAG, "wincomp: $id installed in ${System.currentTimeMillis() - started}ms")
}
val games = synchronized(waiting) { waiting.remove(id).orEmpty() }
games.forEach { apply(context, it, asked, inSession) }
Pending.drop(context, id)
var applied = true
games.forEach { game ->
try {
apply(context, game, asked, inSession, knownCatalog = catalog)
} catch (e: Exception) {
applied = false
appKey(game)?.let { key -> Pending.add(context, key, listOf(id), mapOf(id to (catalog[id]?.revision ?: requestedRevision ?: 0))) }
waitFor(game, id)
Log.w(TAG, "wincomp: $id installed, but ${game.name} was not updated: ${e.javaClass.simpleName}: ${e.message}")
}
}
if (applied) Pending.drop(context, id, maxOf(requestedRevision ?: 0, catalog[id]?.revision ?: 0))
repairFailures.value = repairFailures.value - id
}
internal object Pending {
@@ -233,24 +305,37 @@ object AutoComponents {
@Synchronized fun read(context: Context): JSONObject =
runCatching { JSONObject(file(context).readText()) }.getOrDefault(JSONObject()).let { it.optJSONObject("games") ?: JSONObject() }
@Synchronized fun set(context: Context, key: String, ids: List<String>) {
@Synchronized fun set(context: Context, key: String, ids: List<String>, revisions: Map<String, Int> = emptyMap()) {
val games = read(context)
if (ids.isEmpty()) games.remove(key) else games.put(key, JSONArray(ids))
write(context, games)
write(context, games, revisions)
}
@Synchronized fun ids(context: Context, key: String): List<String> =
read(context).optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty()
@Synchronized fun add(context: Context, key: String, ids: List<String>) {
@Synchronized fun update(context: Context, key: String, revisions: Map<String, Int>, transform: (List<String>) -> List<String>): Boolean {
val games = read(context)
val current = games.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty()
val ids = transform(current).distinct()
if (ids.isEmpty()) games.remove(key) else games.put(key, JSONArray(ids))
return write(context, games, revisions)
}
@Synchronized fun revision(context: Context, id: String): Int? =
runCatching { JSONObject(file(context).readText()).optJSONObject("revisions")?.optInt(id) }.getOrNull()
@Synchronized fun add(context: Context, key: String, ids: List<String>, revisions: Map<String, Int> = emptyMap()) {
val games = read(context)
val have = games.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty()
games.put(key, JSONArray((have + ids).distinct()))
write(context, games)
write(context, games, revisions)
}
@Synchronized fun drop(context: Context, id: String) {
@Synchronized fun drop(context: Context, id: String, throughRevision: Int? = null) {
val games = read(context)
val required = runCatching { JSONObject(file(context).readText()).optJSONObject("revisions")?.optInt(id, 0) ?: 0 }.getOrDefault(0)
if (throughRevision != null && required > throughRevision) return
for (k in games.keys().asSequence().toList()) {
val left = games.optJSONArray(k)?.let { a -> (0 until a.length()).map { a.optString(it) } }.orEmpty() - id
if (left.isEmpty()) games.remove(k) else games.put(k, JSONArray(left))
@@ -258,13 +343,29 @@ object AutoComponents {
write(context, games)
}
private fun write(context: Context, games: JSONObject) {
private fun write(context: Context, games: JSONObject, required: Map<String, Int> = emptyMap()): Boolean {
val f = file(context)
runCatching {
return runCatching {
f.parentFile?.mkdirs()
val tmp = File(f.path + ".tmp")
tmp.writeText(JSONObject().put("games", games).toString())
if (!tmp.renameTo(f)) { f.delete(); tmp.renameTo(f) }
val before = runCatching { JSONObject(f.readText()).optJSONObject("revisions") }.getOrNull()
val revisions = JSONObject()
for (key in games.keys()) {
val ids = games.getJSONArray(key)
for (i in 0 until ids.length()) {
val id = ids.getString(i)
revisions.put(id, maxOf(before?.optInt(id, 0) ?: 0, required[id] ?: 0))
}
}
tmp.writeText(JSONObject().put("games", games).put("revisions", revisions).toString())
if (!tmp.renameTo(f)) {
f.delete()
if (!tmp.renameTo(f)) throw java.io.IOException("Could not replace pending repair file")
}
true
}.getOrElse {
Log.w(TAG, "wincomp: could not save pending repairs: ${it.javaClass.simpleName}: ${it.message}")
false
}
}
}
@@ -329,21 +430,76 @@ object AutoComponents {
}
fun beforeLaunch(context: Context, game: Library.SteamGame) = queueGame(context, game, asked = false)
internal fun prepareLaunch(context: Context, game: Library.SteamGame): Boolean {
val key = appKey(game) ?: return false
val findings = findings(context, game)
val cached = catalogOf(context, false)
val current = if (online(context)) catalogOf(context, true) else null
val catalog = (current ?: cached)?.associateBy { it.name } ?: run {
val missing = WinComponents.selection(context, key).effective
.filter { WinComponents.validId(it) && it !in installedOf(context) }
val pendingSaved = missing.isEmpty() || Pending.update(context, key, emptyMap()) { ids -> (ids + missing).distinct() }
val pending = Pending.ids(context, key)
pending.forEach { waitFor(game, it) }
queuePending(context, key)
if (!pendingSaved) {
missing.forEach { id ->
waitFor(game, id)
queueDownload(context, id, asked = true, inSession = true, revision = Pending.revision(context, id))
repairFailures.value = repairFailures.value + (id to "Could not save pending repairs")
}
}
return pendingSaved && pending.isEmpty()
}
val wanted = autoPicks(findings, catalog)
val selection = WinComponents.selection(context, key)
val user = selection.user
val installed = installedOf(context)
val roots = selection.effective + wanted.keys.filter { user[it] != false }
val required = withParts(roots.filter { WinComponents.validId(it) }, catalog)
val missing = required.filter { user[it] != false && it !in installed }
val pendingSaved = Pending.update(context, key, catalog.mapValues { it.value.revision }) { ids ->
ids.filter { id -> user[id] != false && (id !in installed && id !in wanted || (Pending.revision(context, id) ?: 0) > (catalog[id]?.revision ?: 0)) } + missing
}
missing.forEach { id ->
waitFor(game, id)
queueDownload(context, id, asked = true, inSession = true,
revision = maxOf(catalog[id]?.revision ?: 0, Pending.revision(context, id) ?: 0))
}
Pending.ids(context, key).forEach { waitFor(game, it) }
queuePending(context, key)
if (!pendingSaved && missing.isNotEmpty()) {
missing.forEach { id -> repairFailures.value = repairFailures.value + (id to "Could not save pending repairs") }
return false
}
return true
}
fun beforeLaunch(context: Context, game: Library.SteamGame, onReady: () -> Unit) {
val app = context.applicationContext
Thread({
val ready = runCatching { prepareLaunch(app, game) }.getOrElse {
Log.w(TAG, "${game.name}: launch repair discovery failed: ${it.javaClass.simpleName}: ${it.message}")
false
}
queueGame(app, game, asked = false)
if (ready) Handler(Looper.getMainLooper()).post(onReady)
}, "auto-components-launch").apply { isDaemon = true; start() }
}
fun restoreMissing(context: Context): List<String> {
val selections = WinComponents.selections(context)
if (selections.isEmpty()) return emptyList()
val catalog = (catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name } ?: return emptyList()
val catalog = (catalogOf(context, false) ?: catalogOf(context, true))?.associateBy { it.name }
val installed = installedOf(context)
val lostFor = selections.mapValues { (_, selection) ->
val lostFor = if (catalog == null) emptyMap() else selections.mapValues { (_, selection) ->
withParts(selection.effective.filter { WinComponents.validId(it) }, catalog).filter { it !in installed && it in catalog }
}.filterValues { it.isNotEmpty() }
if (lostFor.isEmpty()) return emptyList()
val lost = lostFor.values.flatten().distinct()
Log.i(TAG, "wincomp: reinstalling ${lost.joinToString()}, picked for games but missing from the runtime")
lostFor.forEach { (key, ids) -> Pending.add(context, key, ids) }
lost.forEach { queueDownload(context, it, asked = true, inSession = true) }
if (lost.isNotEmpty()) {
Log.i(TAG, "wincomp: reinstalling ${lost.joinToString()}, picked for games but missing from the runtime")
lostFor.forEach { (key, ids) -> Pending.add(context, key, ids, catalog!!.mapValues { it.value.revision }) }
}
Pending.read(context).keys().asSequence().toList().forEach { queuePending(context, it) }
return lost
}
@@ -38,6 +38,7 @@ object WinComponents {
private const val MSI_CACHE = "$STORE/.packages"
private val PROTON_PROVIDES = setOf("gecko", "mono", "cjkfonts", "powershell", "VulkanRT")
private val NESTED_KEYS = setOf("url", "file_name", "file_checksum", "file_size")
private val installLock = Any()
fun validId(id: String): Boolean = ID.matches(id) && ".." !in id
@@ -61,7 +62,7 @@ object WinComponents {
class Component(
val name: String, val description: String, val provider: String, val status: String,
val dependencies: List<String>, val steps: List<Step>,
val snapshot: String = "",
val snapshot: String = "", val revision: Int = 0,
)
enum class Support { READY, NEEDS_INSTALLER, UNSUPPORTED }
@@ -127,7 +128,7 @@ object WinComponents {
name, o.optString("description"), o.optString("provider"), o.optString("status"),
(0 until deps.length()).map { deps.getString(it) }.filter { validId(it) },
(0 until steps.length()).map { steps.getJSONObject(it).let { s -> Step(s.optString("action"), s) } },
o.optString("snapshot"),
o.optString("snapshot"), o.optInt("revision", 0).coerceAtLeast(0),
)
}
if (listed.any { it.name == VCREDIST_ARM64 }) listed else listed + builtInArm64Runtime()
@@ -170,15 +171,31 @@ object WinComponents {
else -> true
}
fun installed(context: Context, id: String): String? = runCatching {
JSONObject(File(LinuxRuntime.rootDir(context), "$STORE/$id/component.json").readText()).optString("version", "?")
internal fun installedVersion(directory: File, revision: Int): String? = runCatching {
val meta = JSONObject(File(directory, "component.json").readText())
if (meta.optInt("revision", 0) < revision) null else meta.optString("version", "?")
}.getOrNull()
fun installedIds(context: Context): List<String> =
File(LinuxRuntime.rootDir(context), STORE).listFiles { f -> f.isDirectory && validId(f.name) }
.orEmpty().map { it.name }.filter { installed(context, it) != null }.sorted()
fun installed(context: Context, id: String): String? = installedVersion(
File(LinuxRuntime.rootDir(context), "$STORE/$id"), cached(context)?.firstOrNull { it.name == id }?.revision ?: 0,
)
fun install(context: Context, c: Component, all: Map<String, Component>, onProgress: (Progress) -> Unit): String? {
internal fun downloadedIds(store: File): List<String> =
store.listFiles { f -> f.isDirectory && validId(f.name) }.orEmpty()
.filter { installedVersion(it, 0) != null }.map { it.name }.sorted()
fun downloadedIds(context: Context): List<String> = downloadedIds(File(LinuxRuntime.rootDir(context), STORE))
fun installedIds(context: Context): List<String> {
val revisions = cached(context).orEmpty().associate { it.name to it.revision }
return File(LinuxRuntime.rootDir(context), STORE).listFiles { f -> f.isDirectory && validId(f.name) }
.orEmpty().filter { installedVersion(it, revisions[it.name] ?: 0) != null }.map { it.name }.sorted()
}
fun install(context: Context, c: Component, all: Map<String, Component>, onProgress: (Progress) -> Unit): String? =
synchronized(installLock) { installLocked(context, c, all, onProgress) }
private fun installLocked(context: Context, c: Component, all: Map<String, Component>, onProgress: (Progress) -> Unit): String? {
if (support(c, all) != Support.READY) return "${c.name} cannot be installed here yet"
val order = ArrayList<Component>()
fun visit(x: Component, depth: Int) {
@@ -353,7 +370,7 @@ object WinComponents {
val version = msi?.optString("version")?.takeIf { it.isNotEmpty() }
?: Regex("""\b(\d+\.\d+(\.\d+)*)\b""").find(c.description)?.value ?: "catalog"
val meta = JSONObject()
.put("id", c.name).put("version", version)
.put("id", c.name).put("version", version).put("revision", c.revision)
.put("overrides", JSONArray(overrides.distinct()))
.put("requires", JSONArray(c.dependencies))
msi?.let { meta.put("kind", it.optString("kind", "msi")).put("product", it.optString("product")).put("notes", it.optJSONArray("notes") ?: JSONArray()) }
@@ -556,8 +573,7 @@ object WinComponents {
matches.forEach { f -> f.copyTo(File(dest, f.name.lowercase()), overwrite = true) }
}
@Synchronized
fun uninstall(context: Context, id: String) {
fun uninstall(context: Context, id: String) = synchronized(installLock) {
require(validId(id))
FileUtils.delete(File(LinuxRuntime.rootDir(context), "$STORE/$id"))
save(context, selections(context).mapValues { (_, sel) -> Selection(sel.auto - id, sel.user - id) })
@@ -900,6 +900,7 @@ fun ComponentsPage(
winOpen,
compat = selectedGame.protonPrefix,
steamAppId = selectedGame.appId.takeIf { selectedGame.library != Library.ADDED },
game = selectedGame,
) {
winComponentsOpen = null
winComponentsRevision++
@@ -104,6 +104,7 @@ internal fun WinComponentsDialog(
var slowCatalog by remember { mutableStateOf(false) }
LaunchedEffect(Unit) { kotlinx.coroutines.delay(300); slowCatalog = true }
var installed by remember { mutableStateOf(emptySet<String>()) }
var freshInstalled by remember { mutableStateOf(emptySet<String>()) }
var present by remember { mutableStateOf(emptySet<String>()) }
var selection by remember { mutableStateOf(WinComponents.selection(context, appKey)) }
val picks = selection.effective
@@ -141,9 +142,11 @@ internal fun WinComponentsDialog(
findings = found
selection = withContext(Dispatchers.IO) { WinComponents.selection(context, appKey) }
present = withContext(Dispatchers.IO) { PrefixInstalledDetector.detect(compat) }
installed = withContext(Dispatchers.IO) { WinComponents.installedIds(context).toSet() }
installed = withContext(Dispatchers.IO) { WinComponents.downloadedIds(context).toSet() }
freshInstalled = withContext(Dispatchers.IO) { WinComponents.installedIds(context).toSet() }
}
val autoDownloading by com.droiddeck.launcher.frontend.AutoComponents.downloading.collectAsState()
val repairFailures by com.droiddeck.launcher.frontend.AutoComponents.repairFailures.collectAsState()
val online = rememberOnline()
val autoChanges by com.droiddeck.launcher.frontend.AutoComponents.changes.collectAsState()
val pendingGames by com.droiddeck.launcher.frontend.AutoComponents.pendingGames.collectAsState()
@@ -152,7 +155,8 @@ internal fun WinComponentsDialog(
if (game != null) withContext(Dispatchers.IO) { com.droiddeck.launcher.frontend.AutoComponents.cachedFindings(context, appKey) }
?.let { findings = it; if (appKey !in pendingGames) findingsKnown = true }
selection = withContext(Dispatchers.IO) { WinComponents.selection(context, appKey) }
installed = withContext(Dispatchers.IO) { WinComponents.installedIds(context).toSet() }
installed = withContext(Dispatchers.IO) { WinComponents.downloadedIds(context).toSet() }
freshInstalled = withContext(Dispatchers.IO) { WinComponents.installedIds(context).toSet() }
}
fun setUser(id: String, on: Boolean) {
selection = WinComponents.Selection(selection.auto, selection.user + (id to on))
@@ -173,15 +177,25 @@ internal fun WinComponentsDialog(
}
val all = catalog.orEmpty()
val c = all[id]
if (id in installed || c == null) { setUser(id, true); return }
if (id in installed) {
setUser(id, true)
if (c != null && id !in freshInstalled) {
com.droiddeck.launcher.frontend.AutoComponents.queueRepair(context, id,
game?.let { com.droiddeck.launcher.frontend.AutoComponents.appKey(it) }, c.revision)
}
return
}
if (c == null) { setUser(id, true); return }
busyId = id; reverting = false
progress = WinComponents.Progress(id, "", WinComponents.Phase.DOWNLOAD, -1)
progress = null
coroutine.launch {
val problem = withContext(Dispatchers.IO) {
WinComponents.install(context, c, all) { p -> progress = p }
if (WinComponents.installed(context, id) != null) null
else WinComponents.install(context, c, all) { p -> progress = p }
}
progress = null
installed = withContext(Dispatchers.IO) { WinComponents.installedIds(context).toSet() }
installed = withContext(Dispatchers.IO) { WinComponents.downloadedIds(context).toSet() }
freshInstalled = withContext(Dispatchers.IO) { WinComponents.installedIds(context).toSet() }
if (problem != null) { error = problem; failed = id } else setUser(id, true)
busyId = null
}
@@ -244,6 +258,9 @@ internal fun WinComponentsDialog(
val status = when {
!online && id !in installed && support == Support.READY -> stringResource(R.string.wincomp_when_online)
id == failed && error != null -> stringResource(R.string.wincomp_failed, error.orEmpty())
id in repairFailures -> stringResource(R.string.wincomp_failed, repairFailures.getValue(id))
id in pendingComponents && id in installed && id !in freshInstalled -> stringResource(R.string.wincomp_repair_queued)
id in installed && id !in freshInstalled -> stringResource(R.string.wincomp_repair_required)
id in here && id !in picks -> stringResource(R.string.wincomp_already_here)
id in installed -> stringResource(R.string.wincomp_downloaded)
support == Support.NEEDS_INSTALLER -> stringResource(R.string.wincomp_needs_installer)
@@ -275,6 +292,12 @@ internal fun WinComponentsDialog(
modifier = (if (usable && focus != null) Modifier.focusRequester(focus) else Modifier)
.onFocusChanged { if (it.isFocused) switchFocused = true },
) { on -> toggle(id, on) }
if (id in repairFailures && c != null) {
SecondaryButton(stringResource(R.string.wincomp_retry), compact = true) {
com.droiddeck.launcher.frontend.AutoComponents.queueRepair(context, id,
game?.let { com.droiddeck.launcher.frontend.AutoComponents.appKey(it) }, c.revision)
}
}
}
fun firstUsable(ids: List<String>, focus: FocusRequester): (String) -> FocusRequester? {
val first = ids.firstOrNull { supportOf(it) == Support.READY }
+3
View File
@@ -428,6 +428,9 @@
<string name="wincomp_unsupported">Not supported here yet</string>
<string name="wincomp_loading">Loading the components…</string>
<string name="wincomp_failed">Could not install: %1$s</string>
<string name="wincomp_repair_required">This download needs an update.</string>
<string name="wincomp_repair_queued">Update queued.</string>
<string name="wincomp_retry">Retry update</string>
<string name="wincomp_downloaded">Downloaded</string>
<string name="wincomp_downloading">Downloading %1$s</string>
<string name="wincomp_installing">Installing: %1$s</string>
@@ -34,6 +34,14 @@ class WinCompSourcesTest {
private fun auto(findings: List<WinCompSources.Finding>) = findings.filter { it.auto }.map { it.component to it.origin }
@Test fun battleNetRepairKeysMatchRuntimeProfileKeys() {
val battlenet = game(null, Store.BATTLENET.id, 4242, library = "battlenet")
val steam = game(null, Library.SOURCE_STEAM, 4242, library = "steam")
assertEquals(battlenet.profileKey, AutoComponents.appKey(battlenet))
assertEquals("4242", AutoComponents.appKey(steam))
}
@Test fun gogDependencyIdsMapToComponents() {
assertEquals(listOf("vcredist2015"), WinCompSources.gog("MSVC2017_x64"))
@@ -233,16 +241,19 @@ class WinCompSourcesTest {
private var session = false
private var gameUp = false
private fun payback(): Library.SteamGame {
private fun payback(appId: Int = 1262580): Library.SteamGame {
val steamapps = tmp.newFolder("steamapps")
val folder = File(steamapps, "common/Payback").apply { mkdirs() }
File(steamapps, "appmanifest_1262580.acf").writeText(
File(steamapps, "appmanifest_$appId.acf").writeText(
"\"AppState\"\n{\n\t\"SharedDepots\"\n\t{\n\t\t\"228985\"\t\t\"228980\"\n\t\t\"228988\"\t\t\"228980\"\n\t\t\"228990\"\t\t\"228980\"\n\t}\n}\n",
)
return game(folder, Library.SOURCE_STEAM, 1262580, library = "steam", name = "Need for Speed Payback")
return game(folder, Library.SOURCE_STEAM, appId, library = "steam", name = "Need for Speed Payback")
}
private fun <T> withFakeWorker(block: () -> T): T {
val steamPics = SteamAppInfo.pics
SteamAppInfo.pics = { null }
AutoComponents.repairFailures.value = emptyMap()
AutoComponents.catalogOf = { _, _ -> catalog3 }
AutoComponents.installedOf = { installedNow.toSet() }
AutoComponents.installer = { _, c, _, _ -> downloaded.add(c.name); installedNow.add(c.name); null }
@@ -255,6 +266,8 @@ class WinCompSourcesTest {
return block()
} finally {
AutoComponents.runNow = false
SteamAppInfo.pics = steamPics
AutoComponents.repairFailures.value = emptyMap()
AutoComponents.catalogOf = { c, network -> if (network) WinComponents.fetch(c) else WinComponents.cached(c) }
AutoComponents.installedOf = { WinComponents.installedIds(it).toSet() }
AutoComponents.installer = { c, comp, all, progress -> WinComponents.install(c, comp, all, progress) }
@@ -264,6 +277,19 @@ class WinCompSourcesTest {
}
}
@Test fun anExplicitCheckRefreshesTheCatalogAndAnOfflineCheckUsesTheCache() = withFakeWorker {
installedNow.addAll(catalog3.map { it.name })
val requests = ArrayList<Boolean>()
AutoComponents.catalogOf = { _, network -> requests.add(network); catalog3 }
val game = payback()
AutoComponents.queueGame(app, game, asked = true)
assertTrue(requests.first())
requests.clear()
AutoComponents.online = { false }
AutoComponents.queueGame(app, game, asked = true)
assertFalse(requests.first())
}
@Test fun aSteamListedComponentNotYetDownloadedTurnsOnWhenItLands() = withFakeWorker {
installedNow.add("d3dx9")
val game = payback()
@@ -277,6 +303,244 @@ class WinCompSourcesTest {
assertEquals(3, AutoComponents.cachedFindings(app, "1262580")!!.count { it.auto })
}
@Test fun downloadCallbacksReuseTheCatalogInsteadOfRefreshingAgain() = withFakeWorker {
val requests = ArrayList<Boolean>()
AutoComponents.catalogOf = { _, network -> requests.add(network); catalog3 }
AutoComponents.queueGame(app, payback(), asked = true)
assertEquals(3, downloaded.size)
assertEquals(1 + downloaded.size, requests.count { it })
}
@Test fun normalLaunchRecordsPendingComponentsBeforeQueueingTheirRepairs() = withFakeWorker {
AutoComponents.installer = { _, c, _, _ ->
assertTrue(c.name in AutoComponents.Pending.ids(app, "1262580"))
assertEquals(c.revision, AutoComponents.Pending.revision(app, c.name))
downloaded.add(c.name)
installedNow.add(c.name)
null
}
AutoComponents.queueGame(app, payback(), asked = true)
assertTrue(AutoComponents.Pending.ids(app, "1262580").isEmpty())
}
@Test fun launchDiscoveryPersistsMissingComponentsWhileAWorkerWaitsForTheSession() = withFakeWorker {
session = true
gameUp = true
val appId = 9876543
assertTrue(AutoComponents.prepareLaunch(app, payback(appId)))
assertEquals(setOf("d3dx9", "vcredist2013_dll", "vcredist2019_dll"), AutoComponents.Pending.ids(app, appId.toString()).toSet())
session = false
gameUp = false
AutoComponents.drain(app)
}
@Test fun launchDiscoveryUsesFreshCatalogAndIncludesManualDependencies() = withFakeWorker {
session = true
gameUp = true
val appId = 9876544
val manual = WinComponents.Component("manual_component", "", "", "ready", listOf("d3dx9"), emptyList(), revision = 3)
val catalog = catalog3 + manual
val requests = ArrayList<Boolean>()
AutoComponents.catalogOf = { _, network -> requests.add(network); catalog }
WinComponents.setUser(app, appId.toString(), manual.name, true)
assertTrue(AutoComponents.prepareLaunch(app, game(null, Library.SOURCE_STEAM, appId, library = "steam")))
assertTrue(requests.contains(true))
assertEquals(setOf("manual_component", "d3dx9"), AutoComponents.Pending.ids(app, appId.toString()).toSet())
session = false
gameUp = false
AutoComponents.drain(app)
}
@Test fun pendingRepairsSurviveTemporaryCatalogFetchFailure() = withFakeWorker {
val id = "vcredist2010_dll"
AutoComponents.catalogOf = { _, _ -> null }
AutoComponents.queueRepair(app, id, "4242", revision = 2)
assertEquals(listOf(id), AutoComponents.Pending.ids(app, "4242"))
assertEquals(2, AutoComponents.Pending.revision(app, id))
}
@Test fun launchCanProceedWithoutCatalogOnlyWhenNoRepairIsPending() = withFakeWorker {
AutoComponents.catalogOf = { _, _ -> null }
val noPending = game(null, Library.SOURCE_STEAM, 9876545, library = "steam")
assertTrue(AutoComponents.prepareLaunch(app, noPending))
AutoComponents.Pending.add(app, "9876546", listOf("vcredist2010_dll"), mapOf("vcredist2010_dll" to 2))
val pending = game(null, Library.SOURCE_STEAM, 9876546, library = "steam")
assertFalse(AutoComponents.prepareLaunch(app, pending))
assertEquals(listOf("vcredist2010_dll"), AutoComponents.Pending.ids(app, "9876546"))
}
@Test fun offlineLaunchPersistsMissingSelectedComponentsWithoutACatalog() = withFakeWorker {
AutoComponents.catalogOf = { _, _ -> null }
AutoComponents.online = { false }
val appId = 9876547
val id = "vcredist2010_dll"
WinComponents.setUser(app, appId.toString(), id, true)
assertFalse(AutoComponents.prepareLaunch(app, game(null, Library.SOURCE_STEAM, appId, library = "steam")))
assertEquals(listOf(id), AutoComponents.Pending.ids(app, appId.toString()))
AutoComponents.catalogOf = { _, _ -> catalog3 + ready(id) }
AutoComponents.online = { true }
AutoComponents.drain(app)
}
@Test fun pendingRepairsKeepTheirRequiredRevisionUntilTheyFinish() = withFakeWorker {
val repair = WinComponents.Component("vcredist2010_dll", "", "", "ready", emptyList(), emptyList(), revision = 2)
AutoComponents.catalogOf = { _, _ -> catalog3 + repair }
WinComponents.setUser(app, "4242", repair.name, true)
session = true
gameUp = true
AutoComponents.restoreMissing(app)
val pending = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app), "root/.config/droiddeck/wincomponents-pending.json")
fun revision() = JSONObject(pending.readText()).getJSONObject("revisions").getInt(repair.name)
assertEquals(2, revision())
AutoComponents.Pending.add(app, "other", listOf(repair.name), mapOf(repair.name to 1))
AutoComponents.Pending.set(app, "4242", listOf(repair.name))
assertEquals(2, revision())
gameUp = false
AutoComponents.drain(app)
assertFalse(JSONObject(pending.readText()).getJSONObject("revisions").has(repair.name))
}
@Test fun manualRepairKeepsPendingWhenCatalogIsOlderThanRequestedRevision() = withFakeWorker {
val repair = WinComponents.Component("vcredist2010_dll", "", "", "ready", emptyList(), emptyList(), revision = 1)
AutoComponents.catalogOf = { _, _ -> catalog3 + repair }
installedNow.add(repair.name)
AutoComponents.Pending.add(app, "4242", listOf(repair.name), mapOf(repair.name to 2))
AutoComponents.queueRepair(app, repair.name, "4242", revision = 1)
AutoComponents.drain(app)
assertEquals("The component catalog is older than the requested revision", AutoComponents.repairFailures.value[repair.name])
assertEquals(listOf(repair.name), AutoComponents.Pending.ids(app, "4242"))
val pendingFile = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app), "root/.config/droiddeck/wincomponents-pending.json")
assertEquals(2, JSONObject(pendingFile.readText()).getJSONObject("revisions").getInt(repair.name))
}
@Test fun restoreRequeuesPersistedRevisionEvenWhenOlderComponentIsInstalled() = withFakeWorker {
val repair = WinComponents.Component("vcredist2010_dll", "", "", "ready", emptyList(), emptyList(), revision = 1)
AutoComponents.catalogOf = { _, _ -> catalog3 + repair }
installedNow.add(repair.name)
AutoComponents.Pending.add(app, "4242", listOf(repair.name), mapOf(repair.name to 2))
assertTrue(WinComponents.selections(app).isEmpty())
assertTrue(AutoComponents.restoreMissing(app).isEmpty())
assertEquals("The component catalog is older than the requested revision", AutoComponents.repairFailures.value[repair.name])
assertEquals(listOf(repair.name), AutoComponents.Pending.ids(app, "4242"))
assertEquals(2, AutoComponents.Pending.revision(app, repair.name))
WinComponents.setUser(app, "4242", repair.name, false)
AutoComponents.queueInSession(app, game(null, Library.SOURCE_STEAM, 4242, library = "steam"))
assertTrue(AutoComponents.Pending.ids(app, "4242").isEmpty())
}
@Test fun missingCatalogComponentCannotDropANewerPendingRepair() = withFakeWorker {
val id = "vcredist2010_dll"
AutoComponents.catalogOf = { _, _ -> catalog3 }
session = true
gameUp = true
AutoComponents.queueRepair(app, id, "4242", revision = 1)
AutoComponents.Pending.add(app, "other", listOf(id), mapOf(id to 2))
gameUp = false
AutoComponents.drain(app)
assertEquals(listOf(id), AutoComponents.Pending.ids(app, "4242"))
assertEquals(listOf(id), AutoComponents.Pending.ids(app, "other"))
assertEquals(2, AutoComponents.Pending.revision(app, id))
}
@Test fun restoredLegacyPendingRepairUsesThePersistedRevision() = withFakeWorker {
val id = "vcredist2010_dll"
val repair = WinComponents.Component(id, "", "", "ready", emptyList(), emptyList(), revision = 1)
AutoComponents.catalogOf = { _, _ -> catalog3 + repair }
var attempts = 0
AutoComponents.installer = { _, _, _, _ -> attempts++; null }
val pendingFile = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app), "root/.config/droiddeck/wincomponents-pending.json")
pendingFile.parentFile?.mkdirs()
pendingFile.writeText(JSONObject().put("games", JSONObject().put("4242", org.json.JSONArray(listOf(id)))).toString())
session = true
gameUp = true
AutoComponents.queueInSession(app, game(null, Library.SOURCE_STEAM, 4242, library = "steam"))
AutoComponents.Pending.add(app, "other", listOf(id), mapOf(id to 2))
gameUp = false
AutoComponents.drain(app)
assertEquals("The component catalog is older than the requested revision", AutoComponents.repairFailures.value[id])
assertEquals(0, attempts)
assertEquals(2, AutoComponents.Pending.revision(app, id))
}
@Test fun catalogLoadFailureCannotDropANewerPendingRepair() = withFakeWorker {
val id = "vcredist2010_dll"
AutoComponents.catalogOf = { _, _ -> null }
session = true
gameUp = true
AutoComponents.queueRepair(app, id, "4242", revision = 1)
AutoComponents.Pending.add(app, "other", listOf(id), mapOf(id to 2))
gameUp = false
AutoComponents.drain(app)
assertEquals("Could not load the component catalog", AutoComponents.repairFailures.value[id])
assertEquals(listOf(id), AutoComponents.Pending.ids(app, "4242"))
assertEquals(listOf(id), AutoComponents.Pending.ids(app, "other"))
assertEquals(2, AutoComponents.Pending.revision(app, id))
}
@Test fun manualRepairsRecordTheirRevisionAndExposeFailuresForRetry() = withFakeWorker {
val repair = WinComponents.Component("vcredist2010_dll", "", "", "ready", emptyList(), emptyList(), revision = 2)
AutoComponents.catalogOf = { _, _ -> catalog3 + repair }
var attempts = 0
AutoComponents.installer = { _, c, _, _ ->
attempts++
if (attempts == 1) throw IllegalStateException("network unavailable") else { installedNow.add(c.name); null }
}
session = true
gameUp = true
AutoComponents.queueRepair(app, repair.name, "4242", repair.revision)
val pending = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app), "root/.config/droiddeck/wincomponents-pending.json")
assertEquals(2, JSONObject(pending.readText()).getJSONObject("revisions").getInt(repair.name))
gameUp = false
AutoComponents.drain(app)
assertEquals("network unavailable", AutoComponents.repairFailures.value[repair.name])
assertEquals(1, attempts)
assertFalse(JSONObject(pending.readText()).getJSONObject("games").has("4242"))
session = false
AutoComponents.queueRepair(app, repair.name, "4242", repair.revision)
assertEquals(2, attempts)
assertEquals(null, AutoComponents.repairFailures.value[repair.name])
assertTrue(repair.name in installedNow)
assertFalse(JSONObject(pending.readText()).getJSONObject("revisions").has(repair.name))
}
@Test fun anEarlierRepairCannotDropANewerGamesPendingRevision() = withFakeWorker {
session = false
gameUp = false
val first = WinComponents.Component("vcredist2010_dll", "", "", "ready", emptyList(), emptyList(), revision = 2)
val newer = WinComponents.Component("vcredist2010_dll", "", "", "ready", emptyList(), emptyList(), revision = 3)
AutoComponents.catalogOf = { _, _ -> catalog3 + first }
var attempts = 0
AutoComponents.installer = { _, c, _, _ ->
attempts++
if (attempts == 1) {
AutoComponents.catalogOf = { _, _ -> catalog3 + newer }
session = true
gameUp = true
AutoComponents.queueRepair(app, c.name, "other", newer.revision)
} else installedNow.add(c.name)
null
}
AutoComponents.queueRepair(app, first.name, "first", first.revision)
val pending = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app), "root/.config/droiddeck/wincomponents-pending.json")
assertEquals(3, JSONObject(pending.readText()).getJSONObject("revisions").getInt(first.name))
assertEquals(listOf(first.name), AutoComponents.Pending.ids(app, "other"))
gameUp = false
session = false
AutoComponents.drain(app)
assertEquals(2, attempts)
assertFalse(JSONObject(pending.readText()).getJSONObject("revisions").has(first.name))
}
@Test fun theQueueWaitsWhileASessionRunsAndResumesAfter() = withFakeWorker {
val game = payback()
session = true
@@ -310,6 +574,21 @@ class WinCompSourcesTest {
assertEquals(downloaded.distinct(), downloaded)
}
@Test fun queuedPicsLookupsMergeAppIdsFromLaterSweeps() = withFakeWorker {
val lookedUp = ArrayList<List<Int>>()
SteamAppInfo.pics = { ids -> lookedUp.add(ids); ids.associateWith { null } }
session = true
val first = game(null, Library.SOURCE_STEAM, 810001, library = "steam")
val second = game(null, Library.SOURCE_STEAM, 810002, library = "steam")
AutoComponents.sweep(app, listOf(first))
AutoComponents.sweep(app, listOf(second))
session = false
AutoComponents.drain(app)
assertEquals(listOf(listOf(810001, 810002)), lookedUp)
}
@Test fun aDownloadWaitsForANetwork() = withFakeWorker {
val game = payback()
AutoComponents.online = { false }
@@ -0,0 +1,73 @@
package com.droiddeck.launcher.session
import com.droiddeck.launcher.runtime.LinuxRuntime
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class WinComponentRevisionTest {
@get:Rule val temp = TemporaryFolder()
private fun installed(revision: Int? = null): File = temp.newFolder().also { directory ->
val meta = JSONObject().put("version", "10.0.40219")
revision?.let { meta.put("revision", it) }
File(directory, "component.json").writeText(meta.toString())
}
@Test fun legacyComponentsStayInstalledUntilTheCatalogRequestsARepair() {
val directory = installed()
assertEquals("10.0.40219", WinComponents.installedVersion(directory, 0))
assertNull(WinComponents.installedVersion(directory, 1))
}
@Test fun repairedComponentsStayInstalledAndAreNotDowngradedByAnOlderCatalog() {
val directory = installed(2)
assertEquals("10.0.40219", WinComponents.installedVersion(directory, 2))
assertEquals("10.0.40219", WinComponents.installedVersion(directory, 1))
assertNull(WinComponents.installedVersion(directory, 3))
}
@Test fun outdatedComponentsRemainDownloadedForOfflineControls() {
val directory = installed()
assertNull(WinComponents.installedVersion(directory, 1))
assertEquals(listOf(directory.name), WinComponents.downloadedIds(directory.parentFile))
}
@Test fun enablingDownloadedComponentsRequiresTheCatalogRevision() {
val context = RuntimeEnvironment.getApplication()
val id = "vcredist2010_dll"
val directory = File(LinuxRuntime.rootDir(context), "opt/droiddeck/wincomponents/$id").apply { mkdirs() }
val metadata = File(directory, "component.json")
metadata.writeText("""{"version":"10.0.40219"}""")
val catalog = File(context.filesDir, "wincomponents-catalog.json")
catalog.writeText("""{"components":[{"name":"$id","revision":1}]}""")
try {
assertEquals(listOf(id), WinComponents.downloadedIds(context))
assertNull(WinComponents.installed(context, id))
metadata.writeText("""{"version":"10.0.40219","revision":1}""")
assertEquals("10.0.40219", WinComponents.installed(context, id))
catalog.delete()
assertEquals("10.0.40219", WinComponents.installed(context, id))
} finally {
directory.deleteRecursively()
catalog.delete()
}
}
@Test fun missingOrInvalidInstallMetadataNeedsInstallation() {
val directory = temp.newFolder()
assertNull(WinComponents.installedVersion(directory, 0))
File(directory, "component.json").writeText("{")
assertNull(WinComponents.installedVersion(directory, 1))
}
}