mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-24 15:26:04 +00:00
fix(addons): CurseForge rows follow CurseForge's own installed list (#3042)
* fix(addons): CurseForge rows follow CurseForge's own installed list The CurseForge source reads installed state and available updates from CurseForge's installed projects after asking it to rescan the game instance, so addons removed from disk show Install again and out of date ones show Update, which updates through CurseForge. Deleting an addon from the addon list uninstalls it through CurseForge when CurseForge manages it, so its list and the files stay in step. * Delete addons through CurseForge only while it is already linked * Link CurseForge on the Addons tab and give its rows Update and Uninstall * Match WoWInterface addons to the AddOns folders on disk The WoWInterface source now reads each addon's folder list and marks it installed when every folder is on disk, whichever source installed it. Deletes from that source go through CurseForge while it is linked. * Fix Compose tests hanging after a dropped UI dispatch and stop CurseForge on tab dispose A non-Compose test that runs the real App after a Compose test in the same Robolectric sandbox leaves AndroidUiDispatcher flagged as scheduled while its looper message is dropped by the sandbox reset, so global snapshot changes are never applied and every later Compose test times out waiting for idle. The shared compose rule now detects that state and re-arms the dispatcher. CurseLink.close runs the stop on a job owned by the link, so the tab test can join it and prove no CurseForge work remains after the tab is disposed. * Match add-on folders by case, offer only real updates, settle deletes on disk A delete that CurseForge finished before its link dropped now counts as done when the folder is already gone. Managed uninstalls only consider projects whose folders are all present, and folder names resolve case-insensitively everywhere. Update is offered only for a newer version, falling back to the source's current file when versions do not compare. The test compose rule also re-posts a dropped frame dispatch.
This commit is contained in:
1 parent
f43cc43d05
commit
84c877813f
12 files changed
+1029
-75
No files matched your search
@@ -1531,7 +1531,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
onAddonImport = { sg, target -> importAddons(sg.name, target) },
|
||||
onAddonDelete = { target, name ->
|
||||
saveAction(getString(R.string.main_addons_deleting, name)) {
|
||||
com.droiddeck.launcher.runtime.WowAddons.delete(target, name)
|
||||
com.droiddeck.launcher.ui.deleteAddon(this, target, name)
|
||||
getString(R.string.main_addons_deleted, name)
|
||||
}
|
||||
},
|
||||
|
||||
@@ -4,6 +4,7 @@ import android.content.Context
|
||||
import com.droiddeck.launcher.stores.battlenet.BattleNetInstall
|
||||
import org.json.JSONArray
|
||||
import org.json.JSONObject
|
||||
import java.io.File
|
||||
import java.time.Instant
|
||||
import java.util.concurrent.ConcurrentHashMap
|
||||
import java.util.concurrent.LinkedBlockingQueue
|
||||
@@ -18,11 +19,14 @@ object CurseForgeApp {
|
||||
internal const val AGENT = "/usr/local/bin/droiddeck-agent"
|
||||
private const val READY_MS = 120_000L
|
||||
private const val INSTALL_MS = 300_000L
|
||||
private const val OUT_OF_DATE = 2
|
||||
|
||||
enum class Start { READY, BUSY, FAILED }
|
||||
|
||||
class Started(val state: Start, val inspector: String? = null)
|
||||
|
||||
class Project(val id: String, val installedModId: String, val folders: List<String>, val update: Boolean)
|
||||
|
||||
internal val INSPECTOR = Regex("ws://127\\.0\\.0\\.1:[0-9]{4,5}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
|
||||
|
||||
class Failure(message: String, val code: String? = null) : Exception(message) {
|
||||
@@ -141,9 +145,23 @@ object CurseForgeApp {
|
||||
return detected?.takeIf { it.isNotBlank() }
|
||||
}
|
||||
|
||||
internal fun projectIds(value: Any?): Set<String> {
|
||||
val list = value as? JSONArray ?: return emptySet()
|
||||
return (0 until list.length()).mapNotNull { list.opt(it)?.toString()?.takeIf { id -> id.isNotBlank() && id != "null" } }.toSet()
|
||||
internal fun parseProjects(value: Any?): List<Project> {
|
||||
val list = value as? JSONArray ?: return emptyList()
|
||||
return (0 until list.length()).mapNotNull { list.optJSONObject(it) }.mapNotNull { p ->
|
||||
val id = p.optString("id").takeIf { it.isNotBlank() && it != "null" } ?: return@mapNotNull null
|
||||
val folders = p.optJSONArray("folders")?.let { f -> (0 until f.length()).mapNotNull { f.optString(it).takeIf(String::isNotBlank) } }.orEmpty()
|
||||
Project(id, p.optString("installedModId"), folders, p.optInt("status") == OUT_OF_DATE && !p.optBoolean("locked"))
|
||||
}
|
||||
}
|
||||
|
||||
internal fun owner(projects: List<Project>, folder: String): Project? =
|
||||
projects.firstOrNull { project -> project.folders.any { it.equals(folder, ignoreCase = true) } }
|
||||
|
||||
internal fun byFolder(projects: List<Project>): Map<String, Project> = projects.flatMap { project -> project.folders.map { it.lowercase() to project } }.toMap()
|
||||
|
||||
internal fun onDisk(projects: List<Project>, addOns: File): List<Project> {
|
||||
val names = addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }.map { it.name.lowercase() }.toSet()
|
||||
return projects.filter { project -> WowAddons.present(project.folders) { it.lowercase() in names } }
|
||||
}
|
||||
|
||||
internal var guest: (Context, List<String>, AtomicBoolean?, (String) -> Unit) -> Int = { context, argv, cancelled, onLine ->
|
||||
@@ -232,22 +250,44 @@ object CurseForgeApp {
|
||||
fun search(context: Context, inspector: String, guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): WowAddonCatalog.Page =
|
||||
parseSearch(call(context, inspector, "ProjectAppService", "search", JSONArray().put(searchRequest(guid, text, sort, page)), 60_000))
|
||||
|
||||
fun installed(context: Context, inspector: String, guid: String): Set<String> {
|
||||
fun projects(context: Context, inspector: String, guid: String, rescan: Boolean = false): List<Project> {
|
||||
connect(context, inspector)
|
||||
return projectIds(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, "r => (r || []).map(p => String(p.id))"))
|
||||
if (rescan) call(context, inspector, "GameDetectionAppService", "scanGameInstance", JSONArray().put(guid), 120_000)
|
||||
return parseProjects(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, PROJECTS))
|
||||
}
|
||||
|
||||
private const val PROJECTS = "r => (r || []).map(p => ({ id: String(p.id), installedModId: p.installedModId, status: p.status, " +
|
||||
"locked: !!(p.installedVersion && p.installedVersion.isLocked), " +
|
||||
"folders: ((p.installedVersion && p.installedVersion.addonFolders) || []).map(f => f.name) }))"
|
||||
|
||||
private fun settle(context: Context, inspector: String, guid: String, done: (List<Project>) -> Boolean): Boolean {
|
||||
val deadline = System.currentTimeMillis() + INSTALL_MS
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
val listed = runCatching { projects(context, inspector, guid) }
|
||||
val error = listed.exceptionOrNull()
|
||||
if (error is Failure && error.gone) throw error
|
||||
listed.getOrNull()?.let { if (done(it)) return true }
|
||||
Thread.sleep(1_000)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
fun install(context: Context, inspector: String, guid: String, projectId: String): Boolean {
|
||||
connect(context, inspector)
|
||||
if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return false
|
||||
val deadline = System.currentTimeMillis() + INSTALL_MS
|
||||
while (System.currentTimeMillis() < deadline) {
|
||||
val listed = runCatching { installed(context, inspector, guid) }
|
||||
val error = listed.exceptionOrNull()
|
||||
if (error is Failure && error.gone) throw error
|
||||
if (projectId in listed.getOrDefault(emptySet())) return true
|
||||
Thread.sleep(1_000)
|
||||
}
|
||||
return false
|
||||
return settle(context, inspector, guid) { list -> list.any { it.id == projectId } }
|
||||
}
|
||||
|
||||
fun update(context: Context, inspector: String, guid: String, projectId: String): Boolean {
|
||||
connect(context, inspector)
|
||||
if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return false
|
||||
return settle(context, inspector, guid) { list -> list.any { it.id == projectId && !it.update } }
|
||||
}
|
||||
|
||||
fun uninstall(context: Context, inspector: String, guid: String, project: Project): Boolean {
|
||||
connect(context, inspector)
|
||||
val failed = call(context, inspector, "InstalledProjectsAppService", "deleteMods", JSONArray().put(guid).put(JSONArray().put(project.installedModId)), 120_000) as? JSONArray
|
||||
if (failed == null || failed.length() > 0) return false
|
||||
return settle(context, inspector, guid) { list -> list.none { it.id == project.id } }
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,7 @@ object WowAddonCatalog {
|
||||
val downloads: Long,
|
||||
val updated: Long,
|
||||
val thumb: String?,
|
||||
val folders: List<String> = emptyList(),
|
||||
)
|
||||
|
||||
class Page(val items: List<Addon>, val more: Boolean)
|
||||
@@ -114,9 +115,11 @@ object WowAddonCatalog {
|
||||
}
|
||||
val thumbs = o.optJSONArray("UIIMG_Thumbs")
|
||||
val thumb = if (thumbs != null && thumbs.length() > 0) thumbs.optString(0).ifEmpty { null } else null
|
||||
val dirs = o.optJSONArray("UIDir")
|
||||
val folders = if (dirs == null) emptyList() else (0 until dirs.length()).map { dirs.optString(it).trim() }.filter { it.isNotEmpty() }
|
||||
val addon = Addon(
|
||||
id, o.optString("UIName"), o.optString("UIAuthorName"), o.optString("UIVersion"),
|
||||
o.optString("UIDownloadTotal").toLongOrNull() ?: 0L, o.optLong("UIDate"), thumb,
|
||||
o.optString("UIDownloadTotal").toLongOrNull() ?: 0L, o.optLong("UIDate"), thumb, folders,
|
||||
)
|
||||
out.add(Entry(addon, o.optString("UICATID"), flavors, o.optString("UIDownloadMonthly").toLongOrNull() ?: 0L))
|
||||
}
|
||||
@@ -241,9 +244,32 @@ object WowAddonCatalog {
|
||||
return details.version
|
||||
}
|
||||
|
||||
internal fun sameVersion(a: String, b: String): Boolean {
|
||||
fun norm(v: String) = v.trim().removePrefix("v").removePrefix("V").trim().lowercase()
|
||||
return norm(a) == norm(b)
|
||||
private fun normVersion(v: String) = v.trim().removePrefix("v").removePrefix("V").trim().lowercase()
|
||||
|
||||
internal fun sameVersion(a: String, b: String): Boolean = normVersion(a) == normVersion(b)
|
||||
|
||||
private val NUMERIC_VERSION = Regex("""^(\d+(?:\.\d+)*)(.*)$""")
|
||||
|
||||
private fun numericVersion(v: String): Pair<List<Long>, String>? {
|
||||
val match = NUMERIC_VERSION.matchEntire(normVersion(v)) ?: return null
|
||||
val parts = match.groupValues[1].split('.').map { it.toLongOrNull() ?: return null }
|
||||
return parts to match.groupValues[2]
|
||||
}
|
||||
|
||||
internal fun newer(have: String, latest: String): Boolean? {
|
||||
val (a, aRest) = numericVersion(have) ?: return null
|
||||
val (b, bRest) = numericVersion(latest) ?: return null
|
||||
for (i in 0 until maxOf(a.size, b.size)) {
|
||||
val x = a.getOrElse(i) { 0L }
|
||||
val y = b.getOrElse(i) { 0L }
|
||||
if (x != y) return y > x
|
||||
}
|
||||
return if (aRest == bRest) false else null
|
||||
}
|
||||
|
||||
internal fun offersUpdate(have: String?, latest: String, sameSource: Boolean): Boolean {
|
||||
if (have.isNullOrBlank() || latest.isBlank() || sameVersion(have, latest)) return false
|
||||
return newer(have, latest) ?: sameSource
|
||||
}
|
||||
|
||||
internal fun findUpdates(entries: List<Entry>, installed: List<WowAddons.Installed>): Map<String, Addon> {
|
||||
@@ -253,7 +279,7 @@ object WowAddonCatalog {
|
||||
val id = item.wowiId ?: return@mapNotNull null
|
||||
val version = item.version ?: return@mapNotNull null
|
||||
val latest = byId[id]?.addon?.takeIf { it.summary.isNotBlank() } ?: return@mapNotNull null
|
||||
if (sameVersion(version, latest.summary) || !seen.add(id)) null else item.name to latest
|
||||
if (!offersUpdate(version, latest.summary, sameSource = true) || !seen.add(id)) null else item.name to latest
|
||||
}.toMap()
|
||||
}
|
||||
|
||||
|
||||
@@ -69,6 +69,13 @@ object WowAddons {
|
||||
target.addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }
|
||||
.map { it.name }.sortedBy { it.lowercase() }
|
||||
|
||||
fun present(folders: List<String>, exists: (String) -> Boolean): Boolean = folders.isNotEmpty() && folders.all(exists)
|
||||
|
||||
fun folder(addOns: File, name: String): File? {
|
||||
val dirs = addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }
|
||||
return dirs.firstOrNull { it.name == name } ?: dirs.firstOrNull { it.name.equals(name, ignoreCase = true) }
|
||||
}
|
||||
|
||||
fun details(target: Target): List<Installed> {
|
||||
val origins = origins(target)
|
||||
return installed(target).map { name ->
|
||||
|
||||
@@ -37,6 +37,7 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.withFrameNanos
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.snapshotFlow
|
||||
import androidx.compose.ui.Alignment
|
||||
@@ -53,6 +54,7 @@ import androidx.compose.ui.input.InputMode
|
||||
import androidx.compose.ui.layout.ContentScale
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalInputModeManager
|
||||
import androidx.compose.ui.platform.LocalLifecycleOwner
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
@@ -60,6 +62,8 @@ import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import androidx.lifecycle.Lifecycle
|
||||
import androidx.lifecycle.LifecycleEventObserver
|
||||
import coil.compose.AsyncImage
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
@@ -68,12 +72,16 @@ import com.droiddeck.launcher.runtime.UserApps
|
||||
import com.droiddeck.launcher.runtime.WowAddonCatalog
|
||||
import com.droiddeck.launcher.runtime.WowAddons
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicReference
|
||||
|
||||
private class AddonResults {
|
||||
val items = mutableStateListOf<WowAddonCatalog.Addon>()
|
||||
@@ -83,23 +91,40 @@ private class AddonResults {
|
||||
var more by mutableStateOf(false)
|
||||
}
|
||||
|
||||
private enum class AddonStatus { INSTALL, UPDATE, INSTALLED }
|
||||
internal enum class AddonStatus { INSTALL, UPDATE, INSTALLED }
|
||||
|
||||
private enum class AddonSource { WOWI, CURSE }
|
||||
|
||||
private class CurseState(val notice: Int? = null) : Exception()
|
||||
internal class CurseState(val notice: Int? = null) : Exception()
|
||||
|
||||
private class CurseLink(val app: UserApps.App) {
|
||||
internal class CurseLink(val app: UserApps.App) {
|
||||
class Linked(val inspector: String, val guid: String)
|
||||
|
||||
private val lock = Object()
|
||||
private val work = SupervisorJob()
|
||||
@Volatile private var closed = false
|
||||
@Volatile private var hold: AtomicBoolean? = null
|
||||
@Volatile private var inspector: String? = null
|
||||
private val guids = HashMap<String, String>()
|
||||
private val scanLock = Object()
|
||||
private val scans = HashMap<String, Pair<Any, List<CurseForgeApp.Project>>>()
|
||||
var generation by mutableIntStateOf(0)
|
||||
private set
|
||||
|
||||
fun <T> call(context: Context, target: WowAddons.Target, block: (Linked) -> T): T {
|
||||
val linked = synchronized(lock) { link(context, target) }
|
||||
fun refresh() {
|
||||
generation++
|
||||
}
|
||||
|
||||
fun installed(context: Context, target: WowAddons.Target, key: Any): List<CurseForgeApp.Project> = CurseForgeApp.onDisk(
|
||||
synchronized(scanLock) {
|
||||
scans[target.addOns.path]?.takeIf { it.first == key }?.second
|
||||
?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }.also { scans[target.addOns.path] = key to it }
|
||||
},
|
||||
target.addOns,
|
||||
)
|
||||
|
||||
fun <T> call(context: Context, target: WowAddons.Target, launch: Boolean = true, block: (Linked) -> T): T {
|
||||
val linked = synchronized(lock) { link(context, target, launch) }
|
||||
try {
|
||||
return block(linked)
|
||||
} catch (e: CurseForgeApp.Failure) {
|
||||
@@ -107,22 +132,25 @@ private class CurseLink(val app: UserApps.App) {
|
||||
if (inspector == linked.inspector) {
|
||||
inspector = null
|
||||
guids.clear()
|
||||
current.compareAndSet(this, null)
|
||||
}
|
||||
}
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
private fun link(context: Context, target: WowAddons.Target): Linked {
|
||||
private fun link(context: Context, target: WowAddons.Target, launch: Boolean): Linked {
|
||||
if (closed) throw CurseState()
|
||||
val url = inspector ?: run {
|
||||
val launch = AtomicBoolean(false)
|
||||
hold = launch
|
||||
if (!launch) throw CurseState()
|
||||
val hold = AtomicBoolean(false)
|
||||
this.hold = hold
|
||||
if (closed) throw CurseState()
|
||||
val done = CurseForgeApp.start(context, app, launch)
|
||||
val done = CurseForgeApp.start(context, app, hold)
|
||||
when (done.state) {
|
||||
CurseForgeApp.Start.READY -> {
|
||||
inspector = done.inspector
|
||||
if (!closed) current.set(this)
|
||||
done.inspector ?: throw CurseState()
|
||||
}
|
||||
CurseForgeApp.Start.BUSY -> throw CurseState(R.string.addons_curse_busy)
|
||||
@@ -138,23 +166,66 @@ private class CurseLink(val app: UserApps.App) {
|
||||
return Linked(url, guid)
|
||||
}
|
||||
|
||||
fun close(context: Context) {
|
||||
fun uninstall(context: Context, target: WowAddons.Target, folder: String): Boolean = call(context, target, launch = false) { linked ->
|
||||
val projects = CurseForgeApp.onDisk(CurseForgeApp.projects(context, linked.inspector, linked.guid), target.addOns)
|
||||
val project = CurseForgeApp.owner(projects, folder) ?: return@call false
|
||||
if (!CurseForgeApp.uninstall(context, linked.inspector, linked.guid, project)) throw CurseState()
|
||||
true
|
||||
}
|
||||
|
||||
internal val stopped: Job get() = work
|
||||
|
||||
fun close(context: Context): Job {
|
||||
closed = true
|
||||
val launch = hold ?: return
|
||||
Thread {
|
||||
CurseForgeApp.stop(context, app, inspector, launch)
|
||||
current.compareAndSet(this, null)
|
||||
val launch = hold
|
||||
return CoroutineScope(work + Dispatchers.IO).launch {
|
||||
if (launch != null) CurseForgeApp.stop(context, app, inspector, launch)
|
||||
synchronized(lock) {
|
||||
hold = null
|
||||
inspector = null
|
||||
}
|
||||
}.start()
|
||||
}.also { work.complete() }
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val current = AtomicReference<CurseLink?>()
|
||||
|
||||
fun live(): CurseLink? = current.get()
|
||||
}
|
||||
}
|
||||
|
||||
private const val PAGES_AHEAD = 8
|
||||
private const val CURSE_UPDATE = "update"
|
||||
private const val UNINSTALLING = -1
|
||||
|
||||
private fun curseMark(project: CurseForgeApp.Project): String? = CURSE_UPDATE.takeIf { project.update }
|
||||
|
||||
private class Present(val curse: Map<String, String?> = emptyMap(), val disk: Map<String, WowAddons.Installed> = emptyMap())
|
||||
|
||||
@Composable
|
||||
internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAddons.Target, curseForge: UserApps.App?, onDismiss: () -> Unit) {
|
||||
internal fun rememberCurseLink(app: UserApps.App?, sessionRunning: Boolean): CurseLink? {
|
||||
val context = LocalContext.current.applicationContext
|
||||
val owner = LocalLifecycleOwner.current
|
||||
var visible by remember(owner) { mutableStateOf(owner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) }
|
||||
DisposableEffect(owner) {
|
||||
val observer = LifecycleEventObserver { _, event ->
|
||||
if (event == Lifecycle.Event.ON_START) visible = true
|
||||
if (event == Lifecycle.Event.ON_STOP) visible = false
|
||||
}
|
||||
owner.lifecycle.addObserver(observer)
|
||||
onDispose { owner.lifecycle.removeObserver(observer) }
|
||||
}
|
||||
val active = visible && !sessionRunning
|
||||
val link = remember(app?.key, active) { app?.takeIf { active }?.let(::CurseLink) }
|
||||
DisposableEffect(link) {
|
||||
onDispose { link?.close(context) }
|
||||
}
|
||||
return link
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAddons.Target, curseForge: UserApps.App?, link: CurseLink?, onDismiss: () -> Unit) {
|
||||
val context = LocalContext.current.applicationContext
|
||||
val scope = rememberCoroutineScope()
|
||||
val shown = rememberShown(onDismiss)
|
||||
@@ -164,11 +235,8 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
var category by remember { mutableStateOf<WowAddonCatalog.Category?>(null) }
|
||||
var sort by remember { mutableStateOf(WowAddonCatalog.Sort.POPULAR) }
|
||||
var source by remember { mutableStateOf(AddonSource.WOWI) }
|
||||
val curse = if (source == AddonSource.CURSE) curseForge else null
|
||||
val link = remember(curseForge?.key) { curseForge?.let(::CurseLink) }
|
||||
DisposableEffect(link) {
|
||||
onDispose { link?.close(context) }
|
||||
}
|
||||
val curse = if (source == AddonSource.CURSE && link != null) curseForge else null
|
||||
LaunchedEffect(link) { link?.refresh() }
|
||||
var notice by remember { mutableStateOf<Int?>(null) }
|
||||
var curseInstalls by remember { mutableIntStateOf(0) }
|
||||
val results = remember(text, category, sort, target, curse) { AddonResults() }
|
||||
@@ -178,20 +246,22 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
value = withContext(Dispatchers.IO) { runCatching { WowAddonCatalog.categories(context) }.getOrDefault(emptyList()) }
|
||||
}
|
||||
val presentKey = curse to target.addOns
|
||||
val snapshot by produceState(presentKey to emptyMap<String, String?>(), target.addOns, WowAddons.imports, curse, curseInstalls, results.items.isEmpty()) {
|
||||
val scanKey = link?.generation to WowAddons.imports
|
||||
val snapshot by produceState(presentKey to Present(), target.addOns, scanKey, curse, curseInstalls, curse == null && results.items.isEmpty()) {
|
||||
val into = target
|
||||
val key = curse to into.addOns
|
||||
value = key to withContext(Dispatchers.IO) {
|
||||
if (curse != null && link != null) runCatching { link.call(context, into) { CurseForgeApp.installed(context, it.inspector, it.guid) }.associateWith { null } }.getOrDefault(emptyMap())
|
||||
else WowAddons.details(into).mapNotNull { item -> item.wowiId?.let { it to item.version } }.toMap()
|
||||
if (curse != null && link != null) Present(curse = runCatching {
|
||||
link.installed(context, into, scanKey).associate { it.id to curseMark(it) }
|
||||
}.getOrDefault(emptyMap()))
|
||||
else Present(disk = WowAddons.details(into).associateBy { it.name.lowercase() })
|
||||
}
|
||||
}
|
||||
val present = snapshot.second.takeIf { snapshot.first == presentKey } ?: emptyMap()
|
||||
val present = snapshot.second.takeIf { snapshot.first == presentKey } ?: Present()
|
||||
fun status(addon: WowAddonCatalog.Addon): AddonStatus {
|
||||
if (addon.id !in present) return AddonStatus.INSTALL
|
||||
val have = present[addon.id]
|
||||
if (curse != null) return if (addon.id !in present.curse) AddonStatus.INSTALL else if (present.curse[addon.id] == CURSE_UPDATE) AddonStatus.UPDATE else AddonStatus.INSTALLED
|
||||
val latest = installed[installKey(addon, target)]?.takeIf { it.first == addon.summary }?.second ?: addon.summary
|
||||
return if (have == null || latest.isBlank() || WowAddonCatalog.sameVersion(have, latest)) AddonStatus.INSTALLED else AddonStatus.UPDATE
|
||||
return diskStatus(addon.folders, present.disk, latest, addon.id)
|
||||
}
|
||||
fun load(page: Int) {
|
||||
if (results.loading) return
|
||||
@@ -230,16 +300,23 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
val via = link?.takeIf { curse != null }
|
||||
if (via != null) {
|
||||
val into = target
|
||||
val updating = status(addon) == AddonStatus.UPDATE
|
||||
installing[key] = 0
|
||||
scope.launch {
|
||||
val done = withContext(Dispatchers.IO) { runCatching { via.call(context, into) { CurseForgeApp.install(context, it.inspector, it.guid, addon.id) } } }
|
||||
val done = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
via.call(context, into) {
|
||||
if (updating) CurseForgeApp.update(context, it.inspector, it.guid, addon.id)
|
||||
else CurseForgeApp.install(context, it.inspector, it.guid, addon.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
installing.remove(key)
|
||||
val ok = done.getOrNull() == true
|
||||
if (ok) {
|
||||
WowAddons.changed()
|
||||
curseInstalls++
|
||||
}
|
||||
WowAddons.changed()
|
||||
curseInstalls++
|
||||
val message = when {
|
||||
ok && updating -> context.getString(R.string.user_apps_updated, addon.name)
|
||||
ok -> context.resources.getQuantityString(R.plurals.main_addons_imported, 1, 1, into.flavor)
|
||||
else -> (done.exceptionOrNull() as? CurseState)?.notice?.let(context::getString)
|
||||
?: context.getString(R.string.stores_dl_failed_reason, done.exceptionOrNull()?.message ?: addon.name)
|
||||
@@ -261,6 +338,32 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
Toast.makeText(context, message.first, Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
fun uninstall(addon: WowAddonCatalog.Addon) {
|
||||
val key = installKey(addon, target)
|
||||
if (key in installing) return
|
||||
if (SessionState.running) {
|
||||
Toast.makeText(context, R.string.main_addons_close_session, Toast.LENGTH_LONG).show()
|
||||
return
|
||||
}
|
||||
val into = target
|
||||
val via = link?.takeIf { curse != null }
|
||||
installing[key] = UNINSTALLING
|
||||
scope.launch {
|
||||
val done = withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
val folders = if (via != null) via.call(context, into) { linked ->
|
||||
CurseForgeApp.projects(context, linked.inspector, linked.guid).firstOrNull { it.id == addon.id }?.folders.orEmpty()
|
||||
} else addon.folders
|
||||
folders.forEach { name -> WowAddons.folder(into.addOns, name)?.let { deleteAddon(context, into, it.name, link) } }
|
||||
}
|
||||
}
|
||||
installing.remove(key)
|
||||
installed.remove(key)
|
||||
WowAddons.changed()
|
||||
curseInstalls++
|
||||
if (done.isFailure) Toast.makeText(context, R.string.fm_delete_failed, Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
val sourceName = stringResource(if (curse != null) R.string.addons_source_curse else R.string.addons_source_wowi)
|
||||
val grid = rememberLazyGridState()
|
||||
LaunchedEffect(results, grid) {
|
||||
@@ -342,7 +445,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
) {
|
||||
items(results.items, key = { it.id }) { addon ->
|
||||
val key = installKey(addon, target)
|
||||
AddonRow(addon, status(addon), installing[key], if (addon.id == results.items.firstOrNull()?.id) Modifier.focusRequester(firstAction) else Modifier) { install(addon) }
|
||||
AddonRow(addon, status(addon), installing[key], if (addon.id == results.items.firstOrNull()?.id) Modifier.focusRequester(firstAction) else Modifier, { uninstall(addon) }) { install(addon) }
|
||||
}
|
||||
item(span = { GridItemSpan(maxLineSpan) }) {
|
||||
Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
@@ -365,7 +468,22 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress: Int?, action: Modifier, onInstall: () -> Unit) {
|
||||
internal fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress: Int?, action: Modifier, onUninstall: () -> Unit, onInstall: () -> Unit) {
|
||||
var asking by remember(addon.id) { mutableStateOf(false) }
|
||||
val first = remember(addon.id) { FocusRequester() }
|
||||
var refocus by remember(addon.id) { mutableStateOf(false) }
|
||||
val inputMode = LocalInputModeManager.current
|
||||
LaunchedEffect(status, progress) {
|
||||
if (!refocus) return@LaunchedEffect
|
||||
withFrameNanos { }
|
||||
runCatching { first.requestFocus() }
|
||||
if (progress == null) refocus = false
|
||||
}
|
||||
fun act(block: () -> Unit) {
|
||||
refocus = inputMode.inputMode == InputMode.Keyboard
|
||||
block()
|
||||
}
|
||||
val lead = action.focusRequester(first)
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Row(
|
||||
@@ -383,13 +501,24 @@ private fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress
|
||||
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
val size = action
|
||||
val uninstall = stringResource(R.string.common_uninstall)
|
||||
when {
|
||||
progress != null -> SecondaryButton(stringResource(R.string.store_installing), compact = true, modifier = size, progress = progress / 100f, onClick = onInstall)
|
||||
status == AddonStatus.INSTALLED -> SecondaryButton(stringResource(R.string.stores_installed_chip), enabled = false, compact = true, modifier = size) {}
|
||||
else -> PrimaryButton(stringResource(if (status == AddonStatus.UPDATE) R.string.common_update else R.string.store_install), compact = true, modifier = size, onClick = onInstall)
|
||||
progress == UNINSTALLING -> SecondaryButton(stringResource(R.string.stores_uninstalling), compact = true, modifier = lead) {}
|
||||
progress != null -> SecondaryButton(stringResource(R.string.store_installing), compact = true, modifier = lead, progress = progress / 100f, onClick = onInstall)
|
||||
status == AddonStatus.INSTALL -> PrimaryButton(stringResource(R.string.store_install), compact = true, modifier = lead) { act(onInstall) }
|
||||
else -> {
|
||||
if (status == AddonStatus.UPDATE) PrimaryButton(stringResource(R.string.common_update), compact = true, modifier = lead) { act(onInstall) }
|
||||
SecondaryButton(uninstall, compact = true, modifier = if (status == AddonStatus.UPDATE) Modifier else lead) { asking = true }
|
||||
}
|
||||
}
|
||||
}
|
||||
if (asking) ConfirmDialog(
|
||||
title = stringResource(R.string.stores_uninstall_title, addon.name),
|
||||
text = stringResource(R.string.games_delete_addon_body),
|
||||
confirm = stringResource(R.string.common_uninstall),
|
||||
onConfirm = { asking = false; act(onUninstall) },
|
||||
onDismiss = { asking = false },
|
||||
)
|
||||
}
|
||||
|
||||
private fun Modifier.scrollThumb(state: LazyGridState, color: Color): Modifier = drawWithContent {
|
||||
@@ -438,4 +567,16 @@ internal fun installAddon(context: Context, addon: WowAddonCatalog.Addon, target
|
||||
}
|
||||
}
|
||||
|
||||
internal fun diskStatus(folders: List<String>, onDisk: Map<String, WowAddons.Installed>, latest: String, id: String): AddonStatus {
|
||||
if (!WowAddons.present(folders) { it.lowercase() in onDisk }) return AddonStatus.INSTALL
|
||||
val have = onDisk.getValue(folders.first().lowercase())
|
||||
return if (WowAddonCatalog.offersUpdate(have.version, latest, sameSource = have.wowiId == id)) AddonStatus.UPDATE else AddonStatus.INSTALLED
|
||||
}
|
||||
|
||||
internal fun deleteAddon(context: Context, target: WowAddons.Target, folder: String, link: CurseLink? = CurseLink.live()) {
|
||||
val managed = link?.let { runCatching { it.uninstall(context, target, folder) }.getOrDefault(false) } == true
|
||||
val left = WowAddons.folder(target.addOns, folder)
|
||||
if (managed || left == null) WowAddons.changed() else WowAddons.delete(target, left.name)
|
||||
}
|
||||
|
||||
private fun installKey(addon: WowAddonCatalog.Addon, target: WowAddons.Target) = addon.id + "|" + target.addOns.path
|
||||
@@ -295,7 +295,7 @@ internal fun GameDetail(
|
||||
GameTab.ACHIEVEMENTS -> achievementState?.let { st -> AchievementsTab(StoreAchievements.forSource(store?.id)?.label.orEmpty(), st) }
|
||||
GameTab.LAUNCH -> if (game != null) LaunchTab(game, s, a, hopRail)
|
||||
GameTab.SAVES -> if (game != null && prefix != null) SavesTab(game, prefix, a)
|
||||
GameTab.ADDONS -> if (game != null) AddonsTab(game, addonTargets, a)
|
||||
GameTab.ADDONS -> if (game != null) AddonsTab(game, addonTargets, s.sessionRunning, a)
|
||||
GameTab.INSTALL -> InstallTab(game, installed, item, store)
|
||||
}
|
||||
}
|
||||
@@ -1047,9 +1047,11 @@ private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, a: FrontEndActions) {
|
||||
private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, sessionRunning: Boolean, a: FrontEndActions) {
|
||||
var browsing by remember(g.gameId) { mutableStateOf<WowAddons.Target?>(null) }
|
||||
browsing?.let { AddonBrowserDialog(targets, it, CurseForgeApp.find(UserAppsState.items)) { browsing = null } }
|
||||
val curseForge = CurseForgeApp.find(UserAppsState.items)
|
||||
val link = rememberCurseLink(curseForge, sessionRunning)
|
||||
browsing?.let { AddonBrowserDialog(targets, it, curseForge, link) { browsing = null } }
|
||||
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
CurseForgeEntry(a)
|
||||
targets.forEach { target ->
|
||||
@@ -1060,6 +1062,12 @@ private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, a:
|
||||
val updates by produceState(emptyMap<String, WowAddonCatalog.Addon>(), names) {
|
||||
value = withContext(Dispatchers.IO) { WowAddonCatalog.updates(context, names, target) }
|
||||
}
|
||||
val scanKey = link?.generation to WowAddons.imports
|
||||
val managed by produceState(emptyMap<String, CurseForgeApp.Project>(), link, target.addOns, scanKey) {
|
||||
value = if (link == null) emptyMap() else withContext(Dispatchers.IO) {
|
||||
runCatching { CurseForgeApp.byFolder(link.installed(context, target, scanKey)) }.getOrDefault(emptyMap())
|
||||
}
|
||||
}
|
||||
if (targets.size > 1) SectionLabel(target.flavor)
|
||||
MenuItem(stringResource(R.string.addons_download), checked = false) { browsing = target }
|
||||
MenuItem(
|
||||
@@ -1070,7 +1078,7 @@ private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, a:
|
||||
target.addOns.mkdirs()
|
||||
a.onBrowseFiles(target.addOns)
|
||||
}
|
||||
names.forEach { item -> key(target.addOns, item.name) { AddonRow(item, updates[item.name], target, a) } }
|
||||
names.forEach { item -> key(target.addOns, item.name) { AddonRow(item, updates[item.name], target, a, link?.let { l -> managed[item.name.lowercase()]?.let { it to l } }) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1124,8 +1132,10 @@ private fun CurseForgeEntry(a: FrontEndActions) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AddonRow(item: WowAddons.Installed, update: WowAddonCatalog.Addon?, target: WowAddons.Target, a: FrontEndActions) {
|
||||
internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Addon?, target: WowAddons.Target, a: FrontEndActions, curse: Pair<CurseForgeApp.Project, CurseLink>? = null) {
|
||||
val name = item.name
|
||||
val update = wowiUpdate.takeIf { curse == null }
|
||||
val outdated = update != null || curse?.first?.update == true
|
||||
var asking by remember(target.addOns, name) { mutableStateOf(false) }
|
||||
var progress by remember(target.addOns, name) { mutableStateOf<Int?>(null) }
|
||||
val context = LocalContext.current
|
||||
@@ -1135,26 +1145,33 @@ private fun AddonRow(item: WowAddons.Installed, update: WowAddonCatalog.Addon?,
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(start = 16.dp, top = 2.dp, bottom = 2.dp)) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(name, fontSize = 14.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
val detail = listOfNotNull(item.version, update?.let { stringResource(R.string.upd_available) }).joinToString(" · ")
|
||||
val detail = listOfNotNull(item.version, if (outdated) stringResource(R.string.upd_available) else null).joinToString(" · ")
|
||||
if (detail.isNotEmpty()) Text(
|
||||
progress?.let { stringResource(R.string.ctrl_percent, it) } ?: detail, fontSize = 12.sp,
|
||||
color = if (update != null) LocalPalette.current.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
color = if (outdated) LocalPalette.current.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
if (update != null && !SessionState.running) IconAction(Icons.Outlined.Download, stringResource(R.string.common_update), "addon:update:${target.flavor}:$name", enabled = progress == null) {
|
||||
if (outdated && !SessionState.running) IconAction(Icons.Outlined.Download, stringResource(R.string.common_update), "addon:update:${target.flavor}:$name", enabled = progress == null) {
|
||||
progress = 0
|
||||
scope.launch {
|
||||
val message = withContext(Dispatchers.IO) { installAddon(context, update, target) { pct -> scope.launch { progress = pct } } }
|
||||
val message = withContext(Dispatchers.IO) {
|
||||
if (curse != null) {
|
||||
val (project, link) = curse
|
||||
val done = runCatching { link.call(context, target) { CurseForgeApp.update(context, it.inspector, it.guid, project.id) } }.getOrDefault(false)
|
||||
WowAddons.changed()
|
||||
if (done) context.getString(R.string.user_apps_updated, name) else context.getString(R.string.stores_dl_failed_reason, name)
|
||||
} else update?.let { installAddon(context, it, target) { pct -> scope.launch { progress = pct } }.first }
|
||||
}
|
||||
progress = null
|
||||
android.widget.Toast.makeText(context, message.first, android.widget.Toast.LENGTH_LONG).show()
|
||||
if (message != null) android.widget.Toast.makeText(context, message, android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
if (!SessionState.running) IconAction(Icons.Outlined.Delete, delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true }
|
||||
if (!SessionState.running) IconAction(Icons.Outlined.Delete, if (curse != null) stringResource(R.string.common_uninstall) else delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true }
|
||||
}
|
||||
if (asking) ConfirmDialog(
|
||||
title = stringResource(R.string.games_delete_addon_title, name),
|
||||
title = if (curse != null) stringResource(R.string.stores_uninstall_title, name) else stringResource(R.string.games_delete_addon_title, name),
|
||||
text = stringResource(R.string.games_delete_addon_body),
|
||||
confirm = delete,
|
||||
confirm = if (curse != null) stringResource(R.string.common_uninstall) else delete,
|
||||
onConfirm = { a.onAddonDelete(target, name) },
|
||||
onDismiss = { asking = false },
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user