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:
MaxsTechReview authored and GitHub committed 2026-11-23 03:15:53 -05:00
1 parent f43cc43d05
commit 84c877813f
12 files changed
+1029 -75

No files matched your search

@@ -166,9 +166,16 @@ class CurseForgeAppTest {
}
@Test
fun installedIdsAndExitCodes() {
assertEquals(setOf("486246", "2"), CurseForgeApp.projectIds(JSONArray("""["486246","2",null]""")))
assertEquals(emptySet<String>(), CurseForgeApp.projectIds(JSONObject()))
fun installedProjectsAndExitCodes() {
val projects = CurseForgeApp.parseProjects(JSONArray("""[
{"id":"486246","installedModId":"a_486246","status":3,"locked":false,"folders":["RXPGuides","RXPGuides_Extra"]},
{"id":"2","installedModId":"b_2","status":2,"locked":true,"folders":[]},
{"id":null}]"""))
assertEquals(listOf("486246", "2"), projects.map { it.id })
assertEquals("486246", CurseForgeApp.owner(projects, "RXPGuides_Extra")?.id)
assertNull(CurseForgeApp.owner(projects, "TomTom"))
assertFalse(projects[1].update)
assertTrue(CurseForgeApp.parseProjects(JSONObject()).isEmpty())
assertEquals(CurseForgeApp.Start.READY, CurseForgeApp.startState(0))
assertEquals(CurseForgeApp.Start.BUSY, CurseForgeApp.startState(3))
assertEquals(CurseForgeApp.Start.FAILED, CurseForgeApp.startState(4))
@@ -293,6 +300,268 @@ class CurseForgeAppTest {
assertTrue(!GuestCommand.redacted(url, CurseForgeApp.INSPECTOR).contains(url))
}
private class Curse(val addOns: File, val flavor: String = "") {
val projects = java.util.concurrent.CopyOnWriteArrayList<JSONObject>()
val methods = java.util.Collections.synchronizedList(mutableListOf<String>())
@Volatile var unreachableAfterDelete = false
@Volatile var unreachable = false
fun add(id: String, folder: String, status: Int) = add(id, listOf(folder), status)
fun add(id: String, folders: List<String>, status: Int, onDisk: List<String> = folders) {
onDisk.forEach { File(addOns, it).mkdirs() }
projects += JSONObject().put("id", id).put("installedModId", "m_$id").put("status", status).put("locked", false).put("folders", JSONArray(folders))
}
private fun folders(p: JSONObject) = (0 until p.getJSONArray("folders").length()).map { p.getJSONArray("folders").getString(it) }
fun answer(expression: String): Any? {
val method = Regex("s\\[\\\\\"(\\w+)\\\\\"\\]").find(expression)?.groupValues?.get(1) ?: return true
methods += method
return when (method) {
"scanGameInstance" -> {
projects.removeAll { p -> !File(addOns, p.getJSONArray("folders").getString(0)).isDirectory }
true
}
"getProjects" -> JSONArray(projects.map { JSONObject(it.toString()) })
"updateMod" -> {
projects.forEach { it.put("status", 1) }
true
}
"detectGameFromPath" -> JSONObject().put("gameInstanceGuid", "g")
"getGameInstances" -> JSONArray().put(JSONObject().put("guid", "g").put("installPath", flavor))
"deleteMods" -> {
projects.removeAll { p ->
(p.getString("installedModId") in expression).also { gone ->
if (gone) folders(p).forEach { name -> WowAddons.folder(addOns, name)?.deleteRecursively() }
}
}
if (unreachableAfterDelete) unreachable = true
JSONArray()
}
else -> true
}
}
}
private fun fakeCurse(addOns: File = temp.newFolder("AddOns"), flavor: String = "", calls: MutableList<List<String>> = mutableListOf()): Curse {
val curse = Curse(addOns, flavor)
CurseForgeApp.guest = { _, argv, cancelled, onLine ->
calls += argv
when {
argv[0] == CurseForgeApp.HELPER && argv[1] == "start" -> {
onLine(url)
while (cancelled?.get() != true) Thread.sleep(10)
0
}
argv[0] == CurseForgeApp.HELPER -> 0
curse.unreachable -> {
onLine(JSONObject().put("ok", false).put("error", JSONObject().put("code", "DEVTOOLS_UNREACHABLE").put("message", "gone")).toString())
0
}
else -> {
val value = JSONObject().put("value", curse.answer(argv[4]) ?: JSONObject.NULL)
onLine(JSONObject().put("ok", true).put("value", value.toString()).toString())
0
}
}
}
return curse
}
private fun wow(): WowAddons.Target {
val context = org.robolectric.RuntimeEnvironment.getApplication()
val games = temp.newFolder("Games")
val addOns = File(games, "World of Warcraft/_retail_/Interface/AddOns").apply { mkdirs() }
com.droiddeck.launcher.session.SessionPrefs.setGameFolderBinds(context, listOf(games.absolutePath to "/root/Games"))
return WowAddons.Target("_retail_", addOns)
}
@Test
fun anEntryCurseForgeStillListsShowsAsNotInstalledOnceItsFolderIsGone() {
val curse = fakeCurse()
val context = org.robolectric.RuntimeEnvironment.getApplication()
curse.add("298842", "Leatrix_Maps", 1)
curse.add("18808", "TomTom", 1)
assertTrue(File(curse.addOns, "Leatrix_Maps").deleteRecursively())
val listed = CurseForgeApp.projects(context, url, "g")
assertEquals(listOf("298842", "18808"), listed.map { it.id })
assertEquals(listOf("18808"), CurseForgeApp.onDisk(listed, curse.addOns).map { it.id })
}
@Test
fun aProjectWithAnyFolderMissingOrNoFoldersIsNotInstalled() {
val addOns = temp.newFolder("Split")
File(addOns, "DBM-Core").mkdirs()
val split = CurseForgeApp.Project("3358", "m_3358", listOf("DBM-Core", "DBM-StatusBarTimers"), false)
val bare = CurseForgeApp.Project("1", "m_1", emptyList(), false)
assertTrue(CurseForgeApp.onDisk(listOf(split, bare), addOns).isEmpty())
File(addOns, "DBM-StatusBarTimers").mkdirs()
assertEquals(listOf("3358"), CurseForgeApp.onDisk(listOf(split, bare), addOns).map { it.id })
}
@Test
fun aDeleteWhileCurseForgeIsLinkedGoesThroughItsUninstall() {
val context = org.robolectric.RuntimeEnvironment.getApplication()
val target = wow()
val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_")
curse.add("298842", "Leatrix_Maps", 1)
curse.add("18808", "TomTom", 1)
val link = com.droiddeck.launcher.ui.CurseLink(app)
try {
link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) }
assertTrue(com.droiddeck.launcher.ui.CurseLink.live() === link)
com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps")
assertTrue("deleteMods" in curse.methods)
assertFalse(File(target.addOns, "Leatrix_Maps").exists())
assertEquals(listOf("18808"), CurseForgeApp.projects(context, url, "g").map { it.id })
} finally {
link.close(context)
}
assertNull(com.droiddeck.launcher.ui.CurseLink.live())
}
@Test
fun aDeleteWithoutALiveLinkRemovesTheFolderAtOnceWithoutStartingCurseForge() {
val context = org.robolectric.RuntimeEnvironment.getApplication()
val target = wow()
val calls = java.util.Collections.synchronizedList(mutableListOf<List<String>>())
val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_", calls)
curse.add("298842", "Leatrix_Maps", 1)
assertNull(com.droiddeck.launcher.ui.CurseLink.live())
com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps")
assertFalse(File(target.addOns, "Leatrix_Maps").exists())
assertTrue(calls.isEmpty())
assertTrue(CurseForgeApp.projects(context, url, "g", rescan = true).none { it.id == "298842" })
}
@Test
fun aLinkThatNeverStartedIsNotUsedToDelete() {
val context = org.robolectric.RuntimeEnvironment.getApplication()
val target = wow()
val calls = java.util.Collections.synchronizedList(mutableListOf<List<String>>())
val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_", calls)
curse.add("298842", "Leatrix_Maps", 1)
com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps", com.droiddeck.launcher.ui.CurseLink(app))
assertFalse(File(target.addOns, "Leatrix_Maps").exists())
assertTrue(calls.isEmpty())
}
@Test
fun anAddonWhoseFolderWasDeletedShowsAsNotInstalledAfterTheRescan() {
val curse = fakeCurse()
val context = org.robolectric.RuntimeEnvironment.getApplication()
curse.add("298842", "Leatrix_Maps", 1)
assertEquals(listOf("298842"), CurseForgeApp.projects(context, url, "g", rescan = true).map { it.id })
assertTrue(File(curse.addOns, "Leatrix_Maps").deleteRecursively())
assertTrue(CurseForgeApp.projects(context, url, "g").isNotEmpty())
assertTrue(CurseForgeApp.projects(context, url, "g", rescan = true).isEmpty())
assertTrue("scanGameInstance" in curse.methods)
}
@Test
fun aNewerFileShowsAsAnUpdateUntilCurseForgeUpdatesIt() {
val curse = fakeCurse()
val context = org.robolectric.RuntimeEnvironment.getApplication()
curse.add("298842", "Leatrix_Maps", 2)
curse.add("18808", "TomTom", 1)
val before = CurseForgeApp.projects(context, url, "g", rescan = true).associate { it.id to it.update }
assertEquals(mapOf("298842" to true, "18808" to false), before)
assertTrue(CurseForgeApp.update(context, url, "g", "298842"))
assertTrue("updateMod" in curse.methods)
assertTrue(CurseForgeApp.projects(context, url, "g").none { it.update })
}
@Test
fun uninstallingThroughCurseForgeClearsItsListAndTheFolder() {
val curse = fakeCurse()
val context = org.robolectric.RuntimeEnvironment.getApplication()
curse.add("298842", "Leatrix_Maps", 1)
curse.add("18808", "TomTom", 1)
val project = CurseForgeApp.owner(CurseForgeApp.projects(context, url, "g"), "Leatrix_Maps")!!
assertTrue(CurseForgeApp.uninstall(context, url, "g", project))
assertEquals(listOf("18808"), CurseForgeApp.projects(context, url, "g").map { it.id })
assertFalse(File(curse.addOns, "Leatrix_Maps").exists())
assertTrue(File(curse.addOns, "TomTom").isDirectory)
}
@Test
fun anUninstallThatRemovedTheFolderBeforeCurseForgeWentAwayCountsAsDeleted() {
val context = org.robolectric.RuntimeEnvironment.getApplication()
val target = wow()
val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_")
curse.add("298842", "Leatrix_Maps", 1)
curse.unreachableAfterDelete = true
val link = com.droiddeck.launcher.ui.CurseLink(app)
try {
link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) }
val before = WowAddons.imports
com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps")
assertTrue("deleteMods" in curse.methods)
assertFalse(File(target.addOns, "Leatrix_Maps").exists())
assertTrue(WowAddons.imports > before)
} finally {
kotlinx.coroutines.runBlocking { link.close(context).join() }
}
}
@Test
fun aLocalDeleteInAProjectWithAMissingFolderKeepsItsOtherFolders() {
val context = org.robolectric.RuntimeEnvironment.getApplication()
val target = wow()
val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_")
curse.add("3358", listOf("DBM-Core", "DBM-GUI", "DBM-StatusBarTimers"), 1, onDisk = listOf("DBM-Core", "DBM-GUI"))
curse.add("298842", "Leatrix_Maps", 1)
val link = com.droiddeck.launcher.ui.CurseLink(app)
try {
link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) }
com.droiddeck.launcher.ui.deleteAddon(context, target, "DBM-Core")
assertFalse("deleteMods" in curse.methods)
assertFalse(File(target.addOns, "DBM-Core").exists())
assertTrue(File(target.addOns, "DBM-GUI").isDirectory)
com.droiddeck.launcher.ui.deleteAddon(context, target, "Leatrix_Maps")
assertTrue("deleteMods" in curse.methods)
assertFalse(File(target.addOns, "Leatrix_Maps").exists())
} finally {
kotlinx.coroutines.runBlocking { link.close(context).join() }
}
}
@Test
fun foldersMatchCurseForgesNamesWhateverTheirCase() {
val context = org.robolectric.RuntimeEnvironment.getApplication()
val target = wow()
val curse = fakeCurse(target.addOns, "/root/Games/World of Warcraft/_retail_")
curse.add("12345", listOf("Questie"), 1, onDisk = listOf("questie"))
val listed = CurseForgeApp.projects(context, url, "g")
assertEquals(listOf("12345"), CurseForgeApp.onDisk(listed, target.addOns).map { it.id })
assertEquals("12345", CurseForgeApp.byFolder(listed)["questie"]?.id)
assertEquals("questie", WowAddons.folder(target.addOns, "Questie")?.name)
val link = com.droiddeck.launcher.ui.CurseLink(app)
try {
link.call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid) }
com.droiddeck.launcher.ui.deleteAddon(context, target, "Questie")
assertTrue("deleteMods" in curse.methods)
assertNull(WowAddons.folder(target.addOns, "Questie"))
} finally {
kotlinx.coroutines.runBlocking { link.close(context).join() }
}
}
@Test
fun aLocalDeleteFindsTheFolderWhateverItsCaseAndAnAbsentFolderIsAlreadyDeleted() {
val context = org.robolectric.RuntimeEnvironment.getApplication()
val target = wow()
File(target.addOns, "questie").mkdirs()
File(target.addOns, "TomTom").mkdirs()
com.droiddeck.launcher.ui.deleteAddon(context, target, "Questie", null)
assertNull(WowAddons.folder(target.addOns, "Questie"))
assertTrue(File(target.addOns, "TomTom").isDirectory)
val before = WowAddons.imports
com.droiddeck.launcher.ui.deleteAddon(context, target, "Gone", null)
assertTrue(WowAddons.imports > before)
}
@Test
fun theAgentAnswerIsTheLastJsonLine() {
assertEquals("a", CurseForgeApp.lastJson(listOf("noise", """{"v":"a"}""", "== done"))?.getString("v"))
@@ -15,7 +15,7 @@ class WowAddonCatalogTest {
private val context get() = RuntimeEnvironment.getApplication()
private val files = """[
{"UID":"1","UICATID":"19","UIVersion":"1.0","UIDate":300,"UIName":"Bartender","UIAuthorName":"Nevcairiel","UIDownloadTotal":"500","UICompatibility":[{"version":"12.0.0","name":"Midnight"}],"UIIMG_Thumbs":["https://cdn.example/a.jpg"]},
{"UID":"1","UICATID":"19","UIVersion":"1.0","UIDate":300,"UIName":"Bartender","UIAuthorName":"Nevcairiel","UIDownloadTotal":"500","UICompatibility":[{"version":"12.0.0","name":"Midnight"}],"UIIMG_Thumbs":["https://cdn.example/a.jpg"],"UIDir":["Bartender4"," Bartender4_Options "]},
{"UID":"2","UICATID":"20","UIVersion":"2.0","UIDate":100,"UIName":"Zygor","UIAuthorName":"Kappa","UIDownloadTotal":"900","UICompatibility":[{"version":"1.15.7","name":"Classic"},{"version":"4.4.2","name":"Cataclysm Classic"}],"UIIMG_Thumbs":null},
{"UID":"3","UICATID":"21","UIVersion":"3.0","UIDate":200,"UIName":"Alpha","UIAuthorName":"bartuser","UIDownloadTotal":"10","UIDownloadMonthly":"9","UICompatibility":null},
{"UID":"4","UICATID":"19","UIVersion":"4.0","UIDate":400,"UIName":"TBCOnly","UIAuthorName":"x","UIDownloadTotal":"20","UIDownloadMonthly":"5","UICompatibility":[{"version":"2.5.4","name":"The Burning Crusade Classic"}]}
@@ -44,6 +44,12 @@ class WowAddonCatalogTest {
assertEquals("19", e[0].category)
}
@Test fun fileListEntriesCarryTheirAddonFolders() {
val e = WowAddonCatalog.parseWowiFiles(files)
assertEquals(listOf("Bartender4", "Bartender4_Options"), e[0].addon.folders)
assertEquals(emptyList<String>(), e[1].addon.folders)
}
@Test fun versionsMapToFlavors() {
assertEquals("_retail_", WowAddonCatalog.flavorOf("12.1.0"))
assertEquals("_retail_", WowAddonCatalog.flavorOf("11.0.5"))
@@ -198,6 +204,32 @@ us|1|aa|bb|cc||tpr/wow|h|s|t||1|12.1.0.65000|kk|wowf
assertFalse(WowAddonCatalog.sameVersion("1.2.3", "1.2.4"))
}
@Test fun versionsCompareNumericSegmentsFirst() {
assertEquals(true, WowAddonCatalog.newer("v4.11.38-7-ge56e9d8", "4.11.39"))
assertEquals(true, WowAddonCatalog.newer("1.9", "1.10"))
assertEquals(true, WowAddonCatalog.newer("2", "2.0.1"))
assertEquals(false, WowAddonCatalog.newer("11.2.0", "6.2.5"))
assertEquals(false, WowAddonCatalog.newer("2.0", "2"))
assertNull(WowAddonCatalog.newer("11.4.10-beta1", "11.4.10"))
assertNull(WowAddonCatalog.newer("release", "1.0"))
}
@Test fun anUpdateIsOfferedOnlyForANewerVersionOrTheSameSourcesCurrentFile() {
assertTrue(WowAddonCatalog.offersUpdate("1.9", "1.10", sameSource = false))
assertFalse(WowAddonCatalog.offersUpdate("11.2.0", "6.2.5", sameSource = true))
assertFalse(WowAddonCatalog.offersUpdate("v1.2", "1.2", sameSource = true))
assertTrue(WowAddonCatalog.offersUpdate("11.4.10-beta1", "11.4.10", sameSource = true))
assertFalse(WowAddonCatalog.offersUpdate("11.4.10-beta1", "11.4.10", sameSource = false))
assertFalse(WowAddonCatalog.offersUpdate(null, "1.0", sameSource = true))
assertFalse(WowAddonCatalog.offersUpdate("1.0", "", sameSource = true))
}
@Test fun findUpdatesNeverOffersADowngrade() {
val installed = listOf(WowAddons.Installed("Ahead", "3.0", "10"), WowAddons.Installed("Tagged", "r55-alpha", "20"))
val updates = WowAddonCatalog.findUpdates(listOf(entry("10", "2.9"), entry("20", "r56")), installed)
assertEquals(setOf("Tagged"), updates.keys)
}
@Test fun md5Check() {
val f = File(context.cacheDir, "wowaddon-md5-test.zip")
f.writeText("hello")
@@ -0,0 +1,94 @@
package com.droiddeck.launcher.ui
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.test.assertCountEquals
import androidx.compose.ui.test.onAllNodesWithText
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.WowAddonCatalog
import com.droiddeck.launcher.runtime.WowAddons
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], qualifiers = "w960dp-h540dp-land", application = android.app.Application::class)
class AddonRowTest {
@get:Rule val compose = createRobolectricComposeRule()
private val addon = WowAddonCatalog.Addon("298842", "Leatrix Maps", "Leatrix", "", 0, 0, null)
private fun text(id: Int) = RuntimeEnvironment.getApplication().getString(id)
private fun show(status: AddonStatus, uninstalls: MutableList<String> = mutableListOf(), installs: MutableList<String> = mutableListOf()) {
val state = mutableStateOf(status)
compose.setContent {
DroidDeckTheme {
AddonRow(addon, state.value, null, Modifier, { uninstalls += addon.id }) { installs += addon.id }
}
}
}
@Test fun aMissingAddonOffersOnlyInstall() {
val installs = mutableListOf<String>()
show(AddonStatus.INSTALL, installs = installs)
compose.onAllNodesWithText(text(R.string.common_uninstall)).assertCountEquals(0)
compose.onAllNodesWithText(text(R.string.common_update)).assertCountEquals(0)
compose.onNodeWithText(text(R.string.store_install)).performClick()
assertEquals(listOf("298842"), installs)
}
@Test fun aCurrentAddonOffersOnlyUninstallAfterAConfirm() {
val uninstalls = mutableListOf<String>()
show(AddonStatus.INSTALLED, uninstalls)
compose.onAllNodesWithText(text(R.string.store_install)).assertCountEquals(0)
compose.onAllNodesWithText(text(R.string.common_update)).assertCountEquals(0)
compose.onAllNodesWithText(text(R.string.stores_installed_chip)).assertCountEquals(0)
compose.onNodeWithText(text(R.string.common_uninstall)).performClick()
assertEquals(emptyList<String>(), uninstalls)
compose.onAllNodesWithText(text(R.string.common_uninstall))[1].performClick()
assertEquals(listOf("298842"), uninstalls)
}
@Test fun anOutdatedAddonOffersUpdateAndUninstall() {
val installs = mutableListOf<String>()
show(AddonStatus.UPDATE, installs = installs)
compose.onAllNodesWithText(text(R.string.common_uninstall)).assertCountEquals(1)
compose.onNodeWithText(text(R.string.common_update)).performClick()
assertEquals(listOf("298842"), installs)
}
private fun disk(vararg addons: WowAddons.Installed) = addons.associateBy { it.name.lowercase() }
@Test fun anotherSourcesAddonOnDiskIsUpdatableOnlyToANewerVersion() {
val onDisk = disk(WowAddons.Installed("Questie", "11.2.0", null), WowAddons.Installed("QuestieDB", null, null))
assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("Questie"), onDisk, "6.2.5", "1"))
assertEquals(AddonStatus.UPDATE, diskStatus(listOf("Questie"), onDisk, "11.3.0", "1"))
assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("Questie"), onDisk, "v11.2.0", "1"))
assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("QuestieDB"), onDisk, "1.0", "1"))
}
@Test fun anIncomparableVersionIsAnUpdateOnlyFromTheSameSource() {
val onDisk = disk(WowAddons.Installed("TomTom", "v4.0.1-release", "12"))
assertEquals(AddonStatus.UPDATE, diskStatus(listOf("TomTom"), onDisk, "v4.0.1-beta", "12"))
assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("TomTom"), onDisk, "v4.0.1-beta", "99"))
assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("TomTom"), onDisk, "4.0.0", "12"))
}
@Test fun foldersOnDiskMatchWhateverTheirCase() {
val onDisk = disk(WowAddons.Installed("questie", "11.2.0", null))
assertEquals(AddonStatus.INSTALLED, diskStatus(listOf("Questie"), onDisk, "11.2.0", "1"))
}
@Test fun anAddonCountsAsInstalledOnlyWhenEveryFolderIsOnDisk() {
val onDisk = disk(WowAddons.Installed("Bartender4", "4.19.2", null))
assertEquals(AddonStatus.INSTALL, diskStatus(listOf("Bartender4", "Bartender4_Options"), onDisk, "4.19.2", "1"))
assertEquals(AddonStatus.INSTALL, diskStatus(emptyList(), onDisk, "4.19.2", "1"))
assertEquals(AddonStatus.INSTALL, diskStatus(listOf("TomTom"), onDisk, "4.4.1", "1"))
}
}
@@ -0,0 +1,193 @@
package com.droiddeck.launcher.ui
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.test.assertCountEquals
import androidx.compose.ui.test.onAllNodesWithContentDescription
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.AppImageManager
import com.droiddeck.launcher.runtime.CurseForgeApp
import com.droiddeck.launcher.runtime.UserApps
import com.droiddeck.launcher.runtime.WowAddonCatalog
import com.droiddeck.launcher.runtime.WowAddons
import com.droiddeck.launcher.session.SessionPrefs
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import kotlinx.coroutines.withContext
import org.json.JSONArray
import org.json.JSONObject
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
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
import java.util.Collections
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], qualifiers = "w960dp-h540dp-land", application = android.app.Application::class)
class CurseLinkTabTest {
@get:Rule val compose = createRobolectricComposeRule()
@get:Rule val temp = TemporaryFolder()
private val original = CurseForgeApp.guest
private val url = "ws://127.0.0.1:43117/0f8fad5b-d9cb-469f-a165-70867728950e"
private val app = UserApps.App("appimage:c", UserApps.Kind.APPIMAGE, "CurseForge", null, null, AppImageManager.LAUNCHER, listOf("/root/apps/curseforge"), feed = CurseForgeApp.FEED)
private val helper = Collections.synchronizedList(mutableListOf<String>())
private val methods = Collections.synchronizedList(mutableListOf<String>())
private val context get() = RuntimeEnvironment.getApplication()
@After
fun restore() {
CurseForgeApp.guest = original
}
private fun text(id: Int) = context.getString(id)
private fun wow(): WowAddons.Target {
val games = temp.newFolder("Games")
val addOns = File(games, "World of Warcraft/_retail_/Interface/AddOns").apply { mkdirs() }
File(addOns, "Leatrix_Maps").mkdirs()
SessionPrefs.setGameFolderBinds(context, listOf(games.absolutePath to "/root/Games"))
CurseForgeApp.guest = { _, argv, cancelled, onLine ->
if (argv[0] == CurseForgeApp.HELPER) {
helper += argv[1]
if (argv[1] == "start") {
onLine(url)
while (cancelled?.get() != true) Thread.sleep(10)
}
0
} else {
val method = Regex("s\\[\\\\\"(\\w+)\\\\\"\\]").find(argv[4])?.groupValues?.get(1)
method?.let { methods += it }
val answer: Any = when (method) {
"detectGameFromPath" -> JSONObject().put("gameInstanceGuid", "g")
"getGameInstances" -> JSONArray().put(JSONObject().put("guid", "g").put("installPath", "/root/Games/World of Warcraft/_retail_"))
"getProjects" -> JSONArray().put(JSONObject().put("id", "298842").put("installedModId", "m").put("status", 1).put("locked", false).put("folders", JSONArray().put("Leatrix_Maps")))
else -> true
}
onLine(JSONObject().put("ok", true).put("value", JSONObject().put("value", answer).toString()).toString())
0
}
}
return WowAddons.Target("_retail_", addOns)
}
@Test
fun theTabAndItsDialogShareOneCurseForgeThatStopsWhenTheTabLeaves() {
val target = wow()
val shown = mutableStateOf(true)
val seen = Collections.synchronizedList(mutableListOf<List<String>>())
var opened: CurseLink? = null
compose.setContent {
if (shown.value) {
val link = rememberCurseLink(app, sessionRunning = false)
opened = link
LaunchedEffect(link) { withContext(Dispatchers.IO) { link?.let { seen += it.installed(context, target, 0).map { p -> p.id } } } }
LaunchedEffect(link) { withContext(Dispatchers.IO) { link?.let { seen += it.installed(context, target, 0).map { p -> p.id } } } }
}
}
compose.waitUntil(20_000) { seen.size == 2 }
assertEquals(listOf(listOf("298842"), listOf("298842")), seen.toList())
assertEquals(listOf("start"), helper.toList())
assertEquals(1, methods.count { it == "scanGameInstance" })
assertTrue(CurseLink.live() != null)
compose.runOnIdle { shown.value = false }
compose.waitForIdle()
compose.waitUntil(20_000) { "stop" in helper }
assertNull(CurseLink.live())
assertTrue("shutdown" in methods)
assertEquals(1, helper.count { it == "start" })
runBlocking { withTimeout(20_000) { opened!!.stopped.join() } }
compose.waitUntil(5_000) { Thread.getAllStackTraces().keys.none { it.isAlive && it.name.startsWith("curseforge") } }
val calls = helper.size + methods.size
Thread.sleep(1_500)
assertEquals(calls, helper.size + methods.size)
}
@Test
fun aNewGenerationRescansButReusesTheRunningCurseForge() {
val target = wow()
val link = CurseLink(app)
try {
link.installed(context, target, 0)
link.installed(context, target, 0)
link.refresh()
link.installed(context, target, link.generation)
assertEquals(2, methods.count { it == "scanGameInstance" })
assertEquals(1, helper.count { it == "start" })
} finally {
runBlocking { link.close(context).join() }
}
}
@Test
fun noCurseForgeStartsWhileASessionRuns() {
wow()
var link: CurseLink? = CurseLink(app)
compose.setContent { link = rememberCurseLink(app, sessionRunning = true) }
compose.waitForIdle()
assertNull(link)
assertTrue(helper.isEmpty())
}
@Test
fun aStaleEntryWhoseFolderIsGoneIsNotManaged() {
val target = wow()
assertTrue(File(target.addOns, "Leatrix_Maps").deleteRecursively())
val link = CurseLink(app)
try {
assertTrue(link.installed(context, target, 0).isEmpty())
} finally {
runBlocking { link.close(context).join() }
}
}
private val actions = FrontEndActions(
onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {},
onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {},
onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {},
onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {},
onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {},
onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> },
onSetPhantomProcessLimit = { _, _ -> },
)
private fun row(update: Boolean?, wowi: Boolean) {
val target = WowAddons.Target("_retail_", temp.newFolder("AddOns"))
val item = WowAddons.Installed("Leatrix_Maps", "1.60.35", null)
val newer = WowAddonCatalog.Addon("1", "Leatrix Maps", "Leatrix", "1.60.36", 0, 0, null).takeIf { wowi }
val curse = update?.let { CurseForgeApp.Project("298842", "m", listOf("Leatrix_Maps"), it) to CurseLink(app) }
compose.setContent { DroidDeckTheme { AddonRow(item, newer, target, actions, curse) } }
}
@Test
fun aManagedRowWithAnUpdateOffersUpdateAndUninstall() {
row(update = true, wowi = false)
compose.onAllNodesWithContentDescription(text(R.string.common_update)).assertCountEquals(1)
compose.onAllNodesWithContentDescription(text(R.string.common_uninstall)).assertCountEquals(1)
compose.onAllNodesWithContentDescription(text(R.string.common_delete)).assertCountEquals(0)
}
@Test
fun aCurrentManagedRowIgnoresOtherSourcesAndOffersOnlyUninstall() {
row(update = false, wowi = true)
compose.onAllNodesWithContentDescription(text(R.string.common_update)).assertCountEquals(0)
compose.onAllNodesWithContentDescription(text(R.string.common_uninstall)).assertCountEquals(1)
}
@Test
fun anUnmanagedRowKeepsTheLocalUpdateAndDelete() {
row(update = null, wowi = true)
compose.onAllNodesWithContentDescription(text(R.string.common_update)).assertCountEquals(1)
compose.onAllNodesWithContentDescription(text(R.string.common_delete)).assertCountEquals(1)
compose.onAllNodesWithContentDescription(text(R.string.common_uninstall)).assertCountEquals(0)
}
}
@@ -1,11 +1,15 @@
package com.droiddeck.launcher.ui
import android.content.ComponentName
import android.os.Handler
import android.view.Choreographer
import androidx.activity.ComponentActivity
import androidx.compose.ui.platform.AndroidUiDispatcher
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.runtime.snapshots.Snapshot
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows.shadowOf
import kotlin.coroutines.ContinuationInterceptor
fun createRobolectricComposeRule() = createComposeRule().also {
RingVeil.reset()
@@ -13,5 +17,46 @@ fun createRobolectricComposeRule() = createComposeRule().also {
shadowOf(context.packageManager).addActivityIfNotPresent(
ComponentName(context, ComponentActivity::class.java),
)
resumeDroppedUiDispatch()
Snapshot.sendApplyNotifications()
}
internal class UiDispatch {
private val type = AndroidUiDispatcher::class.java
private val dispatcher = AndroidUiDispatcher.Main[ContinuationInterceptor] as AndroidUiDispatcher
private fun field(name: String) = type.getDeclaredField(name).apply { isAccessible = true }
val lock: Any = field("lock").get(dispatcher)!!
val handler = field("handler").get(dispatcher) as Handler
val choreographer = field("choreographer").get(dispatcher) as Choreographer
val callback: Any = field("dispatchCallback").get(dispatcher)!!
private val trampolineFlag = field("scheduledTrampolineDispatch")
private val frameFlag = field("scheduledFrameDispatch")
fun trampolineDropped() = trampolineFlag.getBoolean(dispatcher) && !handler.hasMessages(0)
fun frameDropped() = frameFlag.getBoolean(dispatcher) && !frameQueued()
private fun frameQueued(): Boolean {
val queues = Choreographer::class.java.getDeclaredField("mCallbackQueues").apply { isAccessible = true }.get(choreographer) as Array<*>
return queues.any { queue ->
var record = queue?.let { q -> q.javaClass.getDeclaredField("mHead").apply { isAccessible = true }.get(q) }
var found = false
while (record != null && !found) {
val recordType = record.javaClass
found = recordType.getDeclaredField("action").apply { isAccessible = true }.get(record) === callback
record = recordType.getDeclaredField("next").apply { isAccessible = true }.get(record)
}
found
}
}
}
internal fun uiDispatchDropped(): Boolean = UiDispatch().run { synchronized(lock) { trampolineDropped() || frameDropped() } }
internal fun resumeDroppedUiDispatch() {
val ui = UiDispatch()
synchronized(ui.lock) {
if (ui.trampolineDropped()) ui.handler.post(ui.callback as Runnable)
if (ui.frameDropped()) ui.choreographer.postFrameCallback(ui.callback as Choreographer.FrameCallback)
}
}
@@ -0,0 +1,90 @@
package com.droiddeck.launcher.ui
import android.os.Looper
import android.view.Choreographer
import androidx.compose.runtime.MutableIntState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.platform.AndroidUiDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import java.time.Duration
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34], application = android.app.Application::class)
class RobolectricComposeRuleTest {
private fun dropPendingUiDispatch() {
val ui = UiDispatch()
ui.handler.removeCallbacksAndMessages(null)
dropPendingFrame()
}
private fun dropPendingFrame() {
val ui = UiDispatch()
ui.choreographer.removeFrameCallback(ui.callback as Choreographer.FrameCallback)
}
private fun awaitFrameAfterTrampoline(ran: MutableIntState) {
CoroutineScope(AndroidUiDispatcher.Main).launch { withFrameNanos { ran.intValue++ } }
shadowOf(Looper.getMainLooper()).runOneTask()
}
@Test
fun uiWorkDroppedByAnEarlierTestsLooperResetRunsAgainForTheNextComposeTest() {
val ran = mutableIntStateOf(0)
CoroutineScope(AndroidUiDispatcher.Main).launch { ran.intValue++ }
dropPendingUiDispatch()
shadowOf(Looper.getMainLooper()).idle()
assertEquals(0, ran.intValue)
assertTrue(uiDispatchDropped())
createRobolectricComposeRule()
shadowOf(Looper.getMainLooper()).idle()
assertEquals(1, ran.intValue)
assertFalse(uiDispatchDropped())
}
@Test
fun aDispatchStillQueuedIsLeftAlone() {
val ran = mutableIntStateOf(0)
CoroutineScope(AndroidUiDispatcher.Main).launch { ran.intValue++ }
assertFalse(uiDispatchDropped())
resumeDroppedUiDispatch()
shadowOf(Looper.getMainLooper()).idle()
assertEquals(1, ran.intValue)
assertFalse(uiDispatchDropped())
}
@Test
fun aFrameDroppedAfterTheTrampolineDrainedRunsAgainForTheNextComposeTest() {
val ran = mutableIntStateOf(0)
awaitFrameAfterTrampoline(ran)
dropPendingFrame()
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1))
assertEquals(0, ran.intValue)
assertTrue(uiDispatchDropped())
createRobolectricComposeRule()
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1))
assertEquals(1, ran.intValue)
assertFalse(uiDispatchDropped())
}
@Test
fun aFrameStillQueuedIsLeftAlone() {
val ran = mutableIntStateOf(0)
awaitFrameAfterTrampoline(ran)
assertEquals(0, ran.intValue)
assertFalse(uiDispatchDropped())
resumeDroppedUiDispatch()
shadowOf(Looper.getMainLooper()).idleFor(Duration.ofSeconds(1))
assertEquals(1, ran.intValue)
assertFalse(uiDispatchDropped())
}
}