mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-22 06:15:58 +00:00
feat(addons): install the CurseForge app and update addons per game (#2986)
* feat(addons): install the CurseForge app and update addons per game The Addons tab installs the official CurseForge Linux app from its own update feed, checks it against the feed's SHA-512, shows its version, offers updates and removes it with the components delete button. Installed addons show their .toc version and are checked against WoWInterface by X-WoWI-ID or the recorded source of addons installed from the Download window; Update replaces them in place. The CurseForge web search chip is replaced by the app. * fix(addons): address review on update ordering, flavor filter, origins lock and failed checks * fix(addons): compact scrollable addon browser with list rows * fix(addons): compare release times as instants and replace the sources file atomically * fix(addons): open the addon browser at the top of the list * Keep the addon browser's search focus and installed version in sync * Track the search field's own focus in the addon browser * Key the installed addon version by install target * Install rar and 7z addon archives
This commit is contained in:
1 parent
3577073ab9
commit
d6496b2f96
16 files changed
+765
-153
No files matched your search
@@ -530,7 +530,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
saveAction(getString(R.string.main_addons_importing, name)) {
|
||||
if (SessionState.running) return@saveAction getString(R.string.main_addons_close_session)
|
||||
val imported = try {
|
||||
com.droiddeck.launcher.runtime.WowAddons.import(zip, target)
|
||||
com.droiddeck.launcher.runtime.WowAddons.import(zip, target, context = this@FrontEndActivity)
|
||||
} catch (_: com.droiddeck.launcher.runtime.WowAddons.TooLarge) {
|
||||
return@saveAction getString(R.string.main_addons_too_large, zip.name)
|
||||
}
|
||||
@@ -539,7 +539,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
}
|
||||
val downloads = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS).path
|
||||
pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip"), getString(R.string.main_addons_pick_zip, name), downloads))
|
||||
pickSaveZip.launch(InAppFilePicker.buildIntent(this, listOf("zip", "rar", "7z"), getString(R.string.main_addons_pick_zip, name), downloads))
|
||||
}
|
||||
|
||||
private fun exportSaves(name: String, layout: GameSaves.Layout, game: () -> GameSaves.Game) {
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
object CurseForgeApp {
|
||||
const val NAME = "CurseForge"
|
||||
const val FEED = "https://curseforge.overwolf.com/electron/linux/latest-linux.yml"
|
||||
|
||||
fun find(apps: List<UserApps.App>): UserApps.App? = apps.firstOrNull { it.feed == FEED }
|
||||
|
||||
fun request(): UserApps.Request = UserApps.Request(UserApps.Source.Feed(FEED), NAME, null)
|
||||
}
|
||||
@@ -36,6 +36,7 @@ object UserApps {
|
||||
private const val GITHUB_TAG = "github-tag"
|
||||
private const val GITHUB_PUBLISHED = "github-published"
|
||||
private const val GITHUB_ASSET = "github-asset"
|
||||
private const val FEED = "update-feed"
|
||||
|
||||
enum class Kind { SCRIPT, APPIMAGE, FLATPAK }
|
||||
|
||||
@@ -43,10 +44,15 @@ object UserApps {
|
||||
val key: String, val kind: Kind, val name: String, val icon: Any?, val detail: String?,
|
||||
val program: String, val args: List<String>, val copied: Boolean = false,
|
||||
val repo: String? = null, val version: String? = null,
|
||||
val fex: String = LinuxFex.AUTO, val arch: String? = null,
|
||||
)
|
||||
val fex: String = LinuxFex.AUTO, val arch: String? = null, val feed: String? = null,
|
||||
) {
|
||||
val updatable get() = repo != null || feed != null
|
||||
}
|
||||
|
||||
class Release(val tag: String, val published: String, val asset: String, val url: String, val sha256: String? = null)
|
||||
class Release(
|
||||
val tag: String, val published: String, val asset: String, val url: String,
|
||||
val sha256: String? = null, val sha512: String? = null,
|
||||
)
|
||||
|
||||
sealed class UpdateCheck {
|
||||
class Current(val tag: String) : UpdateCheck()
|
||||
@@ -58,6 +64,7 @@ object UserApps {
|
||||
class Script(val file: File) : Source()
|
||||
class AppImage(val file: File) : Source()
|
||||
class GitHub(val repo: String, val asset: String? = null) : Source()
|
||||
class Feed(val url: String) : Source()
|
||||
class Flatpak(val id: String) : Source()
|
||||
class FlatpakBundle(val file: File) : Source()
|
||||
}
|
||||
@@ -91,6 +98,7 @@ object UserApps {
|
||||
"appimage:${item.id}", Kind.APPIMAGE, item.name, item.icon, item.comment, AppImageManager.LAUNCHER, listOf(item.guestDir),
|
||||
repo = FileUtils.readString(File(dir, GITHUB_REPO))?.trim(), version = FileUtils.readString(File(dir, GITHUB_TAG))?.trim(),
|
||||
fex = LinuxFex.mode(dir), arch = FileUtils.readString(File(dir, "arch"))?.trim()?.takeIf { it.isNotEmpty() },
|
||||
feed = FileUtils.readString(File(dir, FEED))?.trim()?.takeIf { it.isNotEmpty() },
|
||||
)
|
||||
}
|
||||
val flatpaks = FlatpakManager.installedApps(context).map { app ->
|
||||
@@ -115,6 +123,7 @@ object UserApps {
|
||||
is Source.Script -> addScript(context, s.file, name, icon, request.meta, onProgress)
|
||||
is Source.AppImage -> AppImageManager.import(context, s.file, name, icon, request.meta) { onProgress(it, -1) }
|
||||
is Source.GitHub -> addFromGitHub(context, s.repo, s.asset, name, icon, onProgress)
|
||||
is Source.Feed -> addFromFeed(context, s.url, name, icon, onProgress)
|
||||
is Source.Flatpak -> addFlatpak(context, s.id, name, icon, onProgress)
|
||||
is Source.FlatpakBundle -> addFlatpakBundle(context, s.file, name, icon, onProgress)
|
||||
}
|
||||
@@ -346,11 +355,15 @@ object UserApps {
|
||||
}
|
||||
|
||||
private fun withDownload(context: Context, release: Release, onProgress: (String, Int) -> Unit, use: (File) -> String?): String? {
|
||||
val download = File(context.cacheDir, "github-${release.asset}")
|
||||
val download = File(File(context.cacheDir, "user-apps").apply { mkdirs() }, release.asset)
|
||||
try {
|
||||
val label = context.getString(R.string.user_apps_downloading, release.asset)
|
||||
val ok = Downloader.downloadFile(release.url, download, false, release.sha256) { f -> onProgress(label, if (f < 0) -1 else Math.round(f * 100f)) }
|
||||
return if (ok) use(download) else context.getString(R.string.user_apps_download_failed)
|
||||
if (!ok) return context.getString(R.string.user_apps_download_failed)
|
||||
if (release.sha512 != null && !Hashes.sha512(download).equals(release.sha512, ignoreCase = true)) {
|
||||
return context.getString(R.string.selfinst_checksum_mismatch)
|
||||
}
|
||||
return use(download)
|
||||
} finally {
|
||||
download.delete()
|
||||
}
|
||||
@@ -392,20 +405,57 @@ object UserApps {
|
||||
return urls + listOfNotNull(avatar)
|
||||
}
|
||||
|
||||
internal fun parseFeed(feed: String, body: String): Release? {
|
||||
val top = body.lineSequence().filter { it.isNotEmpty() && !it[0].isWhitespace() && ':' in it }
|
||||
.associate { it.substringBefore(':').trim() to it.substringAfter(':').trim().trim('\'', '"') }
|
||||
val version = top["version"]?.takeIf { it.isNotEmpty() } ?: return null
|
||||
val path = top["path"]?.takeIf { it.endsWith(".AppImage", ignoreCase = true) && '/' !in it && ".." !in it } ?: return null
|
||||
val sha512 = top["sha512"]?.let { runCatching { java.util.Base64.getDecoder().decode(it) }.getOrNull() }
|
||||
?.takeIf { it.size == 64 }?.joinToString("") { "%02x".format(it) } ?: return null
|
||||
val base = feed.substringBeforeLast('/', "").takeIf { it.startsWith("https://") } ?: return null
|
||||
return Release(version, top["releaseDate"].orEmpty(), path, "$base/$path", sha512 = sha512)
|
||||
}
|
||||
|
||||
private fun feedRelease(context: Context, feed: String): Release? =
|
||||
Downloader.downloadString(feed)?.let { parseFeed(feed, it) }
|
||||
|
||||
private fun feedMeta(feed: String, release: Release) =
|
||||
mapOf(FEED to feed, GITHUB_TAG to release.tag, GITHUB_PUBLISHED to release.published, GITHUB_ASSET to release.asset)
|
||||
|
||||
private fun addFromFeed(context: Context, feed: String, name: String?, icon: File?, onProgress: (String, Int) -> Unit): String? {
|
||||
onProgress(context.getString(R.string.user_apps_github_checking, name ?: feed), -1)
|
||||
val release = feedRelease(context, feed) ?: return context.getString(R.string.user_apps_update_failed)
|
||||
return withDownload(context, release, onProgress) { file ->
|
||||
AppImageManager.import(context, file, name ?: release.asset.substringBefore('-'), icon, feedMeta(feed, release)) { onProgress(it, -1) }
|
||||
}
|
||||
}
|
||||
|
||||
internal fun isNewer(release: Release, published: String, installed: String?): Boolean =
|
||||
if (published.isNotEmpty() && release.published.isNotEmpty()) {
|
||||
val feed = runCatching { java.time.Instant.parse(release.published) }.getOrNull()
|
||||
val have = runCatching { java.time.Instant.parse(published) }.getOrNull()
|
||||
if (feed != null && have != null) feed > have else release.published > published
|
||||
} else release.tag != installed
|
||||
|
||||
fun checkUpdate(context: Context, app: App): UpdateCheck {
|
||||
app.feed?.let { feed ->
|
||||
val release = feedRelease(context, feed) ?: return UpdateCheck.Failed(context.getString(R.string.user_apps_update_failed))
|
||||
val published = FileUtils.readString(File(AppImageManager.dir(context, app.key.substringAfter(':')), GITHUB_PUBLISHED))?.trim().orEmpty()
|
||||
return if (isNewer(release, published, app.version)) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag)
|
||||
}
|
||||
val repo = app.repo ?: return UpdateCheck.Failed(context.getString(R.string.user_apps_update_failed))
|
||||
val dir = AppImageManager.dir(context, app.key.substringAfter(':'))
|
||||
val (release, problem) = latestRelease(context, repo, FileUtils.readString(File(dir, GITHUB_ASSET))?.trim()?.takeIf { it.isNotEmpty() })
|
||||
if (release == null) return UpdateCheck.Failed(problem ?: context.getString(R.string.user_apps_update_failed))
|
||||
val published = FileUtils.readString(File(dir, GITHUB_PUBLISHED))?.trim().orEmpty()
|
||||
val newer = if (published.isNotEmpty() && release.published.isNotEmpty()) release.published > published else release.tag != app.version
|
||||
return if (newer) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag)
|
||||
return if (isNewer(release, published, app.version)) UpdateCheck.Available(release) else UpdateCheck.Current(app.version ?: release.tag)
|
||||
}
|
||||
|
||||
fun update(context: Context, app: App, release: Release, onProgress: (String, Int) -> Unit): String? {
|
||||
val repo = app.repo ?: return context.getString(R.string.user_apps_update_failed)
|
||||
val meta = app.feed?.let { feedMeta(it, release) }
|
||||
?: app.repo?.let { githubMeta(it, release) } ?: return context.getString(R.string.user_apps_update_failed)
|
||||
return withDownload(context, release, onProgress) { file ->
|
||||
AppImageManager.replace(context, app.key.substringAfter(':'), file, githubMeta(repo, release)) { onProgress(it, -1) }
|
||||
AppImageManager.replace(context, app.key.substringAfter(':'), file, meta) { onProgress(it, -1) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,7 +38,6 @@ object WowAddonCatalog {
|
||||
internal class Cat(val id: String, val name: String, val parents: List<String>)
|
||||
|
||||
private const val WOWI = "https://api.mmoui.com/v3/game/WOW/"
|
||||
private const val CURSEFORGE = "https://www.curseforge.com/wow/search?class=addons"
|
||||
private const val WOWI_FILES = "wowi-filelist.json"
|
||||
internal const val FRESH_MS = 6L * 60 * 60 * 1000
|
||||
|
||||
@@ -209,10 +208,12 @@ object WowAddonCatalog {
|
||||
|
||||
fun categories(context: Context): List<Category> = wowiCategories(context).map { Category(it.id, it.name) }
|
||||
|
||||
internal fun parseWowiDetails(json: String): Pair<String, String?>? {
|
||||
internal class Details(val url: String, val md5: String?, val version: String?)
|
||||
|
||||
internal fun parseWowiDetails(json: String): Details? {
|
||||
val o = JSONArray(json).optJSONObject(0) ?: return null
|
||||
val url = o.optString("UIDownload").ifEmpty { return null }
|
||||
return url to o.optString("UIMD5").ifEmpty { null }
|
||||
return Details(url, o.optString("UIMD5").ifEmpty { null }, o.optString("UIVersion").trim().ifEmpty { null })
|
||||
}
|
||||
|
||||
internal fun isHttps(url: String) = url.startsWith("https://", ignoreCase = true)
|
||||
@@ -220,10 +221,11 @@ object WowAddonCatalog {
|
||||
internal fun md5Matches(file: File, expected: String?): Boolean =
|
||||
expected.isNullOrBlank() || Hashes.md5(file).equals(expected.trim(), ignoreCase = true)
|
||||
|
||||
fun download(context: Context, addon: Addon, dest: File, progress: (Int) -> Unit): File {
|
||||
fun download(context: Context, addon: Addon, dest: File, progress: (Int) -> Unit): String? {
|
||||
val body = StoreNet.get(WOWI + "filedetails/${URLEncoder.encode(addon.id, "UTF-8")}.json", timeoutMs = 30_000)
|
||||
?: throw unreachable(context)
|
||||
val (url, md5) = parseWowiDetails(body) ?: throw IOException(context.getString(R.string.addons_no_file))
|
||||
val details = parseWowiDetails(body) ?: throw IOException(context.getString(R.string.addons_no_file))
|
||||
val url = details.url
|
||||
if (!isHttps(url)) throw IOException(context.getString(R.string.addons_no_file))
|
||||
dest.parentFile?.mkdirs()
|
||||
dest.delete()
|
||||
@@ -232,14 +234,33 @@ object WowAddonCatalog {
|
||||
dest.delete()
|
||||
throw unreachable(context)
|
||||
}
|
||||
if (!md5Matches(dest, md5)) {
|
||||
if (!md5Matches(dest, details.md5)) {
|
||||
dest.delete()
|
||||
throw IOException(context.getString(R.string.selfinst_checksum_mismatch))
|
||||
}
|
||||
progress(100)
|
||||
return dest
|
||||
return details.version
|
||||
}
|
||||
|
||||
internal fun curseForgeUrl(text: String): String =
|
||||
text.trim().let { if (it.isEmpty()) CURSEFORGE else CURSEFORGE + "&search=" + URLEncoder.encode(it, "UTF-8") }
|
||||
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)
|
||||
}
|
||||
|
||||
internal fun findUpdates(entries: List<Entry>, installed: List<WowAddons.Installed>): Map<String, Addon> {
|
||||
val byId = entries.associateBy { it.addon.id }
|
||||
val seen = HashSet<String>()
|
||||
return installed.mapNotNull { item ->
|
||||
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
|
||||
}.toMap()
|
||||
}
|
||||
|
||||
fun updates(context: Context, installed: List<WowAddons.Installed>, target: WowAddons.Target): Map<String, Addon> {
|
||||
if (installed.none { it.wowiId != null }) return emptyMap()
|
||||
val family = client(target).family
|
||||
return runCatching { findUpdates(wowiEntries(context).filter { flavorMatches(it.flavors, family) }, installed) }.getOrDefault(emptyMap())
|
||||
}
|
||||
}
|
||||
@@ -2,15 +2,25 @@ package com.droiddeck.launcher.runtime
|
||||
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableIntStateOf
|
||||
import android.content.Context
|
||||
import androidx.compose.runtime.setValue
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
import com.droiddeck.launcher.stores.StoreArchiveUnpacker
|
||||
import com.droiddeck.launcher.stores.StoreInstalls
|
||||
import com.droiddeck.launcher.stores.itch.ItchArchives
|
||||
import org.apache.commons.compress.archivers.zip.ZipFile
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.io.InputStream
|
||||
import java.nio.file.FileVisitResult
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.LinkOption
|
||||
import java.nio.file.Path
|
||||
import java.nio.file.SimpleFileVisitor
|
||||
import java.nio.file.attribute.BasicFileAttributes
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
object WowAddons {
|
||||
var imports by mutableIntStateOf(0)
|
||||
@@ -22,6 +32,12 @@ object WowAddons {
|
||||
|
||||
class Addon(val name: String, val root: String)
|
||||
|
||||
class Installed(val name: String, val version: String?, val wowiId: String?)
|
||||
|
||||
class Origin(val id: String, val version: String)
|
||||
|
||||
private const val ORIGINS = ".droiddeck-sources"
|
||||
|
||||
internal const val MAX_EXPANDED_BYTES = 4L * 1024 * 1024 * 1024
|
||||
|
||||
private val SUFFIX = Regex("[-_](standard|mainline|classic|vanilla|tbc|bcc|wrath|wotlkc|cata|mists|forever)$", RegexOption.IGNORE_CASE)
|
||||
@@ -45,53 +61,149 @@ object WowAddons {
|
||||
target.addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }
|
||||
.map { it.name }.sortedBy { it.lowercase() }
|
||||
|
||||
fun details(target: Target): List<Installed> {
|
||||
val origins = origins(target)
|
||||
return installed(target).map { name ->
|
||||
val toc = toc(File(target.addOns, name))
|
||||
val origin = origins[name]
|
||||
Installed(name, origin?.version ?: toc["Version"], origin?.id ?: toc["X-WoWI-ID"])
|
||||
}
|
||||
}
|
||||
|
||||
internal fun tocFields(text: String): Map<String, String> {
|
||||
val out = LinkedHashMap<String, String>()
|
||||
for (raw in text.lineSequence()) {
|
||||
val line = raw.trim().removePrefix("\uFEFF")
|
||||
if (!line.startsWith("##") || ':' !in line) continue
|
||||
val key = line.removePrefix("##").substringBefore(':').trim()
|
||||
val value = line.substringAfter(':').trim()
|
||||
if (key.isNotEmpty() && value.isNotEmpty() && '@' !in value) out.putIfAbsent(key, value)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private fun toc(folder: File): Map<String, String> {
|
||||
val tocs = folder.listFiles().orEmpty().filter { it.isFile && it.name.endsWith(".toc", ignoreCase = true) }
|
||||
val main = tocs.firstOrNull { it.name.dropLast(4).equals(folder.name, ignoreCase = true) }
|
||||
?: tocs.firstOrNull { it.name.dropLast(4).replace(SUFFIX, "").equals(folder.name, ignoreCase = true) }
|
||||
?: tocs.minByOrNull { it.name.length } ?: return emptyMap()
|
||||
return runCatching { tocFields(main.readText()) }.getOrDefault(emptyMap())
|
||||
}
|
||||
|
||||
internal fun parseOrigins(text: String): Map<String, Origin> = text.lineSequence().mapNotNull { line ->
|
||||
val parts = line.split('\t')
|
||||
if (parts.size != 3 || parts.any { it.isBlank() }) null else parts[0] to Origin(parts[1], parts[2])
|
||||
}.toMap()
|
||||
|
||||
internal fun formatOrigins(origins: Map<String, Origin>): String =
|
||||
origins.entries.sortedBy { it.key.lowercase() }.joinToString("") { (name, o) -> "$name\t${o.id}\t${o.version.replace(Regex("\\s+"), " ")}\n" }
|
||||
|
||||
private fun originsFile(target: Target) = File(target.addOns, ORIGINS)
|
||||
|
||||
private fun origins(target: Target): Map<String, Origin> =
|
||||
runCatching { parseOrigins(originsFile(target).readText()) }.getOrDefault(emptyMap())
|
||||
|
||||
private val originsLock = Any()
|
||||
|
||||
private fun keepOrigins(target: Target, names: List<String>, origin: Origin?) = synchronized(originsLock) {
|
||||
val current = origins(target)
|
||||
val next = current - names.toSet() + (origin?.let { o -> names.associateWith { o } } ?: emptyMap())
|
||||
if (next != current) {
|
||||
val file = originsFile(target)
|
||||
if (next.isEmpty()) file.delete() else {
|
||||
val temp = File(target.addOns, "$ORIGINS.tmp")
|
||||
temp.writeText(formatOrigins(next))
|
||||
if (!temp.renameTo(file)) {
|
||||
temp.delete()
|
||||
throw IOException("Cannot save $ORIGINS")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun delete(target: Target, name: String) {
|
||||
val folder = target.addOns.listFiles()?.firstOrNull { it.name == name && !it.name.startsWith(".") }
|
||||
?: throw IOException("Cannot find $name")
|
||||
StoreInstalls.deleteTree(folder)
|
||||
if (Files.exists(folder.toPath(), LinkOption.NOFOLLOW_LINKS)) throw IOException("Cannot delete $name")
|
||||
runCatching { keepOrigins(target, listOf(name), null) }
|
||||
imports++
|
||||
}
|
||||
|
||||
fun import(zipFile: File, target: Target): List<String> {
|
||||
fun import(archive: File, target: Target, origin: Origin? = null, context: Context? = null): List<String> {
|
||||
if (context == null || ItchArchives.kind(archive, archive.name) == "zip") return importZip(archive, target, origin)
|
||||
val work = File(File(context.cacheDir, "wowaddons"), "unpack-${System.nanoTime()}")
|
||||
try {
|
||||
if (!work.mkdirs()) throw IOException("Cannot create ${work.path}")
|
||||
val unpacker = StoreArchiveUnpacker(context, AtomicBoolean(), "Addons", R.string.stores_itch_archive, R.string.stores_itch_extract_failed, "addon-unpack")
|
||||
unpacker.work = work
|
||||
unpacker.limit = MAX_EXPANDED_BYTES
|
||||
try {
|
||||
unpacker.unpack(archive, archive.name, { _, _ -> }, {})
|
||||
} catch (_: StoreArchiveUnpacker.TooLarge) {
|
||||
throw TooLarge()
|
||||
}
|
||||
return importFolder(work, target, origin)
|
||||
} finally {
|
||||
StoreInstalls.deleteTree(work)
|
||||
}
|
||||
}
|
||||
|
||||
private class Entry(val path: String, val open: () -> InputStream)
|
||||
|
||||
private fun importZip(zipFile: File, target: Target, origin: Origin?): List<String> =
|
||||
ZipFile.builder().setFile(zipFile).get().use { zip ->
|
||||
val all = zip.entries.toList()
|
||||
if (all.any { it.isUnixSymlink }) return emptyList()
|
||||
val entries = all.filter { clean(it.name) != null }
|
||||
val addons = addons(entries.filter { !it.isDirectory }.mapNotNull { clean(it.name) })
|
||||
if (addons.isEmpty()) return emptyList()
|
||||
val addOns = target.addOns
|
||||
if (!addOns.isDirectory && !addOns.mkdirs()) throw IOException("Cannot create ${addOns.path}")
|
||||
val stage = File(addOns.parentFile, ".addon-import-${System.nanoTime()}")
|
||||
try {
|
||||
val fresh = File(stage, "new")
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
var written = 0L
|
||||
for (entry in entries) {
|
||||
if (entry.isDirectory) continue
|
||||
val path = clean(entry.name) ?: continue
|
||||
val addon = addons.firstOrNull { path.startsWith(it.root) } ?: continue
|
||||
val out = inside(fresh, addon.name + "/" + path.removePrefix(addon.root)) ?: continue
|
||||
out.parentFile?.mkdirs()
|
||||
zip.getInputStream(entry).use { input ->
|
||||
out.outputStream().use { output ->
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
written += read
|
||||
if (written > MAX_EXPANDED_BYTES) throw TooLarge()
|
||||
output.write(buffer, 0, read)
|
||||
}
|
||||
importEntries(all.filter { !it.isDirectory }.mapNotNull { entry -> clean(entry.name)?.let { Entry(it) { zip.getInputStream(entry) } } }, target, origin)
|
||||
}
|
||||
|
||||
internal fun importFolder(folder: File, target: Target, origin: Origin?): List<String> {
|
||||
val entries = ArrayList<Entry>()
|
||||
var links = false
|
||||
Files.walkFileTree(folder.toPath(), object : SimpleFileVisitor<Path>() {
|
||||
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
|
||||
if (!attrs.isRegularFile) links = true
|
||||
else clean(folder.toPath().relativize(file).joinToString("/"))?.let { entries.add(Entry(it) { Files.newInputStream(file, LinkOption.NOFOLLOW_LINKS) }) }
|
||||
return if (links) FileVisitResult.TERMINATE else FileVisitResult.CONTINUE
|
||||
}
|
||||
})
|
||||
return if (links) emptyList() else importEntries(entries, target, origin)
|
||||
}
|
||||
|
||||
private fun importEntries(entries: List<Entry>, target: Target, origin: Origin?): List<String> {
|
||||
val addons = addons(entries.map { it.path })
|
||||
if (addons.isEmpty()) return emptyList()
|
||||
val addOns = target.addOns
|
||||
if (!addOns.isDirectory && !addOns.mkdirs()) throw IOException("Cannot create ${addOns.path}")
|
||||
val stage = File(addOns.parentFile, ".addon-import-${System.nanoTime()}")
|
||||
try {
|
||||
val fresh = File(stage, "new")
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
var written = 0L
|
||||
for (entry in entries) {
|
||||
val addon = addons.firstOrNull { entry.path.startsWith(it.root) } ?: continue
|
||||
val out = inside(fresh, addon.name + "/" + entry.path.removePrefix(addon.root)) ?: continue
|
||||
out.parentFile?.mkdirs()
|
||||
entry.open().use { input ->
|
||||
out.outputStream().use { output ->
|
||||
while (true) {
|
||||
val read = input.read(buffer)
|
||||
if (read < 0) break
|
||||
written += read
|
||||
if (written > MAX_EXPANDED_BYTES) throw TooLarge()
|
||||
output.write(buffer, 0, read)
|
||||
}
|
||||
}
|
||||
}
|
||||
swap(addons.map { File(fresh, it.name) to it.name }, addOns, File(stage, "old").apply { mkdirs() })
|
||||
} finally {
|
||||
StoreInstalls.deleteTree(stage)
|
||||
}
|
||||
imports++
|
||||
return addons.map { it.name }
|
||||
swap(addons.map { File(fresh, it.name) to it.name }, addOns, File(stage, "old").apply { mkdirs() })
|
||||
} finally {
|
||||
StoreInstalls.deleteTree(stage)
|
||||
}
|
||||
runCatching { keepOrigins(target, addons.map { it.name }, origin) }
|
||||
imports++
|
||||
return addons.map { it.name }
|
||||
}
|
||||
|
||||
internal fun addons(files: List<String>): List<Addon> {
|
||||
|
||||
@@ -28,20 +28,26 @@ internal class StoreArchiveUnpacker(
|
||||
private val logName: String,
|
||||
) {
|
||||
var work: File = File("")
|
||||
var limit = Long.MAX_VALUE
|
||||
|
||||
fun unpack(archive: File, filename: String, handle: DownloadQueue.JobHandle) {
|
||||
class TooLarge : java.io.IOException()
|
||||
|
||||
fun unpack(archive: File, filename: String, handle: DownloadQueue.JobHandle) =
|
||||
unpack(archive, filename, { done, total -> handle.stageProgress(done, total) }, handle::log)
|
||||
|
||||
fun unpack(archive: File, filename: String, progress: (Long, Long) -> Unit, log: (String) -> Unit) {
|
||||
when (val kind = ItchArchives.kind(archive, filename)) {
|
||||
"zip" -> unzip(archive, handle)
|
||||
"zip" -> unzip(archive, progress, log)
|
||||
"7z" -> try {
|
||||
sevenZip(archive, handle)
|
||||
sevenZip(archive, progress, log)
|
||||
} catch (e: MemoryLimitException) {
|
||||
handle.log("$label: ${archive.name} needs more memory than the app has, unpacking it in the runtime")
|
||||
unrar(archive, handle, kind)
|
||||
log("$label: ${archive.name} needs more memory than the app has, unpacking it in the runtime")
|
||||
unrar(archive, progress, log, kind)
|
||||
}
|
||||
"rar" -> unrar(archive, handle, kind)
|
||||
"rar" -> unrar(archive, progress, log, kind)
|
||||
"exe" -> copy(archive, File(work, filename.ifBlank { "game.exe" }))
|
||||
"tar" -> untar(archive, null, handle)
|
||||
"gz", "bz2", "xz" -> untar(archive, kind, handle) ?: single(archive, kind, handle)
|
||||
"tar" -> untar(archive, null, progress, log)
|
||||
"gz", "bz2", "xz" -> untar(archive, kind, progress, log) ?: single(archive, kind, progress, log)
|
||||
else -> copy(archive, File(work, filename.ifBlank { "game" }))
|
||||
}
|
||||
}
|
||||
@@ -53,7 +59,7 @@ internal class StoreArchiveUnpacker(
|
||||
return if (path == root || path.startsWith(root + File.separator)) file else null
|
||||
}
|
||||
|
||||
private fun unrar(archive: File, handle: DownloadQueue.JobHandle, kind: String) {
|
||||
private fun unrar(archive: File, progress: (Long, Long) -> Unit, log: (String) -> Unit, kind: String) {
|
||||
if (!LinuxRuntime.isInstalled(app)) throw IllegalStateException(app.getString(unsupported, kind))
|
||||
val binds = if (listOf(app.filesDir, app.cacheDir).any { work.absolutePath.startsWith(it.absolutePath + "/") }) null
|
||||
else listOf(work.absolutePath)
|
||||
@@ -62,23 +68,28 @@ internal class StoreArchiveUnpacker(
|
||||
if (!line.startsWith("proot ")) onLine(line)
|
||||
}
|
||||
var entries = 0L
|
||||
bsdtar(listOf("-tf", archive.absolutePath)) { entries++ }
|
||||
var size = 0L
|
||||
bsdtar(listOf("-tvf", archive.absolutePath)) { line ->
|
||||
entries++
|
||||
size += LISTED_SIZE.find(line)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
|
||||
}
|
||||
if (size > limit) throw TooLarge()
|
||||
var done = 0L
|
||||
val tail = ArrayDeque<String>()
|
||||
val code = bsdtar(listOf("-xvf", archive.absolutePath, "-C", work.absolutePath)) { line ->
|
||||
if (line.startsWith("x ")) handle.stageProgress(++done, entries) else {
|
||||
if (line.startsWith("x ")) progress(++done, entries) else {
|
||||
if (tail.size == 5) tail.removeFirst()
|
||||
tail.addLast(line)
|
||||
}
|
||||
}
|
||||
if (cancelled.get()) return
|
||||
if (code != 0) {
|
||||
handle.log("$label: bsdtar exited $code: ${tail.joinToString(" | ")}")
|
||||
log("$label: bsdtar exited $code: ${tail.joinToString(" | ")}")
|
||||
throw IllegalStateException(app.getString(extractFailed, code))
|
||||
}
|
||||
}
|
||||
|
||||
private fun sevenZip(archive: File, handle: DownloadQueue.JobHandle) {
|
||||
private fun sevenZip(archive: File, progress: (Long, Long) -> Unit, log: (String) -> Unit) {
|
||||
val total = archive.length()
|
||||
var written = 0L
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
@@ -90,7 +101,7 @@ internal class StoreArchiveUnpacker(
|
||||
val entry = seven.nextEntry ?: break
|
||||
val file = target(entry.name)
|
||||
if (file == null) {
|
||||
handle.log("$label: skipped an entry outside the game folder")
|
||||
log("$label: skipped an entry outside the game folder")
|
||||
continue
|
||||
}
|
||||
if (entry.isDirectory) {
|
||||
@@ -105,7 +116,8 @@ internal class StoreArchiveUnpacker(
|
||||
if (read < 0) break
|
||||
out.write(buffer, 0, read)
|
||||
written += read
|
||||
handle.stageProgress(written, total)
|
||||
if (written > limit) throw TooLarge()
|
||||
progress(written, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -113,7 +125,7 @@ internal class StoreArchiveUnpacker(
|
||||
}
|
||||
}
|
||||
|
||||
private fun untar(archive: File, codec: String?, handle: DownloadQueue.JobHandle): Unit? {
|
||||
private fun untar(archive: File, codec: String?, progress: (Long, Long) -> Unit, log: (String) -> Unit): Unit? {
|
||||
val total = archive.length()
|
||||
var written = 0L
|
||||
var entries = 0
|
||||
@@ -134,7 +146,7 @@ internal class StoreArchiveUnpacker(
|
||||
entries++
|
||||
val file = target(entry.name)
|
||||
if (file == null) {
|
||||
handle.log("$label: skipped an entry outside the game folder")
|
||||
log("$label: skipped an entry outside the game folder")
|
||||
continue
|
||||
}
|
||||
if (entry.isDirectory) {
|
||||
@@ -149,7 +161,8 @@ internal class StoreArchiveUnpacker(
|
||||
if (read < 0) break
|
||||
out.write(buffer, 0, read)
|
||||
written += read
|
||||
handle.stageProgress(written, total)
|
||||
if (written > limit) throw TooLarge()
|
||||
progress(written, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -163,7 +176,7 @@ internal class StoreArchiveUnpacker(
|
||||
return null
|
||||
}
|
||||
|
||||
private fun single(archive: File, codec: String, handle: DownloadQueue.JobHandle) {
|
||||
private fun single(archive: File, codec: String, progress: (Long, Long) -> Unit, log: (String) -> Unit) {
|
||||
val name = archive.name.substringBeforeLast('.')
|
||||
val file = target(name.ifBlank { "game" }) ?: throw IllegalStateException("archive")
|
||||
file.parentFile?.mkdirs()
|
||||
@@ -184,7 +197,8 @@ internal class StoreArchiveUnpacker(
|
||||
if (read < 0) break
|
||||
out.write(buffer, 0, read)
|
||||
written += read
|
||||
handle.stageProgress(written, total)
|
||||
if (written > limit) throw TooLarge()
|
||||
progress(written, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -196,7 +210,7 @@ internal class StoreArchiveUnpacker(
|
||||
FileInputStream(source).use { input -> FileOutputStream(target).use { out -> input.copyTo(out, 128 * 1024) } }
|
||||
}
|
||||
|
||||
private fun unzip(archive: File, handle: DownloadQueue.JobHandle) {
|
||||
private fun unzip(archive: File, progress: (Long, Long) -> Unit, log: (String) -> Unit) {
|
||||
val total = archive.length()
|
||||
var written = 0L
|
||||
val buffer = ByteArray(64 * 1024)
|
||||
@@ -205,7 +219,7 @@ internal class StoreArchiveUnpacker(
|
||||
if (cancelled.get()) return
|
||||
val target = target(entry.name)
|
||||
if (target == null) {
|
||||
handle.log("$label: skipped an entry outside the game folder")
|
||||
log("$label: skipped an entry outside the game folder")
|
||||
continue
|
||||
}
|
||||
if (entry.isDirectory) {
|
||||
@@ -221,11 +235,16 @@ internal class StoreArchiveUnpacker(
|
||||
if (read < 0) break
|
||||
out.write(buffer, 0, read)
|
||||
written += read
|
||||
handle.stageProgress(written, total)
|
||||
if (written > limit) throw TooLarge()
|
||||
progress(written, total)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private companion object {
|
||||
val LISTED_SIZE = Regex("""^\S+\s+\d+\s+\S+\s+\S+\s+(\d+)\s""")
|
||||
}
|
||||
}
|
||||
@@ -311,6 +311,7 @@ internal fun AppDialog(
|
||||
width: Dp? = null, fitContent: Boolean = false,
|
||||
back: (() -> Unit)? = null,
|
||||
scrollable: Boolean = true,
|
||||
fillHeight: Boolean = false,
|
||||
scrollState: androidx.compose.foundation.ScrollState = rememberScrollState(),
|
||||
side: (@Composable () -> Unit)? = null,
|
||||
sideRoom: Dp = 0.dp,
|
||||
@@ -348,6 +349,7 @@ internal fun AppDialog(
|
||||
},
|
||||
)
|
||||
.heightIn(max = (LocalConfiguration.current.screenHeightDp - 24).dp)
|
||||
.then(if (fillHeight) Modifier.fillMaxHeight() else Modifier)
|
||||
.shadow(24.dp, Shape16, ambientColor = Color.Black, spotColor = Color.Black)
|
||||
.clip(Shape16)
|
||||
.background(pal.surfaceVariant.copy(alpha = 0.97f))
|
||||
|
||||
@@ -1,28 +1,32 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.widget.Toast
|
||||
import androidx.compose.foundation.LocalIndication
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.hoverable
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.PaddingValues
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.lazy.grid.GridCells
|
||||
import androidx.compose.foundation.lazy.grid.GridItemSpan
|
||||
import androidx.compose.foundation.lazy.grid.LazyGridState
|
||||
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
|
||||
import androidx.compose.foundation.lazy.grid.items
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Check
|
||||
import androidx.compose.material3.Icon
|
||||
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.material3.LinearProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Close
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
@@ -34,16 +38,29 @@ import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberCoroutineScope
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.snapshotFlow
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.platform.LocalConfiguration
|
||||
import androidx.compose.ui.draw.drawWithContent
|
||||
import androidx.compose.ui.focus.FocusRequester
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.geometry.CornerRadius
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.geometry.Size
|
||||
import androidx.compose.ui.graphics.Color
|
||||
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.res.stringResource
|
||||
import androidx.compose.ui.semantics.Role
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
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 coil.compose.AsyncImage
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.runtime.WowAddonCatalog
|
||||
import com.droiddeck.launcher.runtime.WowAddons
|
||||
@@ -62,6 +79,10 @@ private class AddonResults {
|
||||
var more by mutableStateOf(false)
|
||||
}
|
||||
|
||||
private enum class AddonStatus { INSTALL, UPDATE, INSTALLED }
|
||||
|
||||
private const val PAGES_AHEAD = 8
|
||||
|
||||
@Composable
|
||||
internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAddons.Target, onDismiss: () -> Unit) {
|
||||
val context = LocalContext.current.applicationContext
|
||||
@@ -74,10 +95,19 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
var sort by remember { mutableStateOf(WowAddonCatalog.Sort.POPULAR) }
|
||||
val results = remember(text, category, sort, target) { AddonResults() }
|
||||
val installing = remember { mutableStateMapOf<String, Int>() }
|
||||
val installed = remember { mutableStateMapOf<String, Boolean>() }
|
||||
val installed = remember { mutableStateMapOf<String, Pair<String, String>>() }
|
||||
val categories by produceState(emptyList<WowAddonCatalog.Category>()) {
|
||||
value = withContext(Dispatchers.IO) { runCatching { WowAddonCatalog.categories(context) }.getOrDefault(emptyList()) }
|
||||
}
|
||||
val present by produceState(emptyMap<String, String?>(), target.addOns, WowAddons.imports) {
|
||||
value = withContext(Dispatchers.IO) { WowAddons.details(target).mapNotNull { item -> item.wowiId?.let { it to item.version } }.toMap() }
|
||||
}
|
||||
fun status(addon: WowAddonCatalog.Addon): AddonStatus {
|
||||
if (addon.id !in present) return AddonStatus.INSTALL
|
||||
val have = present[addon.id]
|
||||
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
|
||||
}
|
||||
fun load(page: Int) {
|
||||
if (results.loading) return
|
||||
results.loading = true
|
||||
@@ -115,48 +145,93 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
scope.launch {
|
||||
val message = withContext(Dispatchers.IO) { installAddon(context, addon, into) { pct -> scope.launch { if (key in installing) installing[key] = pct } } }
|
||||
installing.remove(key)
|
||||
if (message.second) installed[key] = true
|
||||
message.second?.let { installed[key] = addon.summary to it }
|
||||
Toast.makeText(context, message.first, Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
val sourceName = stringResource(R.string.addons_source_wowi)
|
||||
AppDialog(shown, close, "addonBrowser", wide = true, scrollable = false) {
|
||||
DialogTitleRow(stringResource(R.string.addons_download), close)
|
||||
ModeHeader(sourceName, text, { text = it }, stringResource(R.string.stores_search_catalog, sourceName)) {
|
||||
BrowseChip(stringResource(R.string.addons_source_curse), false) {
|
||||
runCatching { context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(WowAddonCatalog.curseForgeUrl(text))).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) }
|
||||
}
|
||||
val grid = rememberLazyGridState()
|
||||
LaunchedEffect(results, grid) {
|
||||
snapshotFlow { grid.layoutInfo.visibleItemsInfo.lastOrNull()?.index to grid.layoutInfo.totalItemsCount }.collect { (last, total) ->
|
||||
if (last != null && results.more && results.failed == null && last >= total - PAGES_AHEAD) load(results.page + 1)
|
||||
}
|
||||
ChipRow {
|
||||
}
|
||||
val firstAction = remember(results) { FocusRequester() }
|
||||
val inputMode = LocalInputModeManager.current
|
||||
var searching by remember { mutableStateOf(false) }
|
||||
LaunchedEffect(results, results.items.isNotEmpty()) {
|
||||
if (results.items.isNotEmpty() && !searching && inputMode.inputMode == InputMode.Keyboard) focusSoon { firstAction }
|
||||
}
|
||||
AppDialog(shown, close, "addonBrowser", wide = true, maxWidth = 980.dp, scrollable = false, fillHeight = true) {
|
||||
val sortChip: @Composable () -> Unit = {
|
||||
BrowseDropdown(sortLabel(sort)) { first, done ->
|
||||
WowAddonCatalog.Sort.entries.forEachIndexed { index, option ->
|
||||
MenuItem(sortLabel(option), sort == option, focusRequester = if (index == 0) first else null) { sort = option; done() }
|
||||
}
|
||||
}
|
||||
}
|
||||
val categoryChip: @Composable () -> Unit = {
|
||||
if (categories.isNotEmpty()) BrowseDropdown(category?.name ?: stringResource(R.string.addons_category_all)) { first, done ->
|
||||
MenuItem(stringResource(R.string.addons_category_all), category == null, focusRequester = first) { category = null; done() }
|
||||
categories.forEach { option -> MenuItem(option.name, category?.id == option.id) { category = option; done() } }
|
||||
}
|
||||
}
|
||||
val flavorChip: @Composable () -> Unit = {
|
||||
if (targets.size > 1) BrowseDropdown(target.flavor) { first, done ->
|
||||
targets.forEachIndexed { index, option ->
|
||||
MenuItem(option.flavor, option.addOns == target.addOns, focusRequester = if (index == 0) first else null) { target = option; done() }
|
||||
}
|
||||
}
|
||||
}
|
||||
val height = (LocalConfiguration.current.screenHeightDp * 0.62f).dp
|
||||
val search: @Composable (Modifier) -> Unit = { modifier ->
|
||||
AdbTextField(
|
||||
value = text, onValueChange = { text = it }, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search,
|
||||
placeholder = stringResource(R.string.stores_search_catalog, sourceName), compact = true, showLabel = false, modifier = modifier, onFocusChange = { searching = it },
|
||||
)
|
||||
}
|
||||
val closeButton: @Composable () -> Unit = {
|
||||
SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = MaterialTheme.colorScheme.error, onClick = close)
|
||||
}
|
||||
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||
if (maxWidth >= 640.dp) Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
search(Modifier.weight(1f))
|
||||
sortChip()
|
||||
categoryChip()
|
||||
flavorChip()
|
||||
closeButton()
|
||||
} else Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
search(Modifier.weight(1f))
|
||||
closeButton()
|
||||
}
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||
modifier = Modifier.horizontalScroll(rememberScrollState()),
|
||||
) {
|
||||
sortChip()
|
||||
categoryChip()
|
||||
flavorChip()
|
||||
}
|
||||
}
|
||||
}
|
||||
val thumb = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
|
||||
LazyVerticalGrid(
|
||||
GridCells.Adaptive(libraryTileWidth() + 40.dp), Modifier.fillMaxWidth().height(height),
|
||||
horizontalArrangement = Arrangement.spacedBy(10.dp), verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
GridCells.Adaptive(400.dp), Modifier.fillMaxWidth().weight(1f).scrollThumb(grid, thumb), state = grid,
|
||||
contentPadding = PaddingValues(end = 8.dp),
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||
) {
|
||||
items(results.items, key = { it.id }) { addon ->
|
||||
AddonCard(addon, installing[installKey(addon, target)], installed[installKey(addon, target)] == true) { install(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) }
|
||||
}
|
||||
item(key = "tail", span = { GridItemSpan(maxLineSpan) }) {
|
||||
Box(Modifier.fillMaxWidth().padding(vertical = 8.dp), contentAlignment = Alignment.Center) {
|
||||
item(span = { GridItemSpan(maxLineSpan) }) {
|
||||
Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
when {
|
||||
results.loading -> LinearProgressIndicator(Modifier.fillMaxWidth())
|
||||
results.failed != null -> BrowseChip(stringResource(R.string.stores_dl_retry), false) { load(if (results.items.isEmpty()) 0 else results.page + 1) }
|
||||
results.more -> BrowseChip(stringResource(R.string.stores_itch_load_more), false) { load(results.page + 1) }
|
||||
results.failed != null -> {
|
||||
Text(stringResource(R.string.addons_unreachable, sourceName), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
BrowseChip(stringResource(R.string.stores_dl_retry), false) { load(if (results.items.isEmpty()) 0 else results.page + 1) }
|
||||
}
|
||||
results.items.isEmpty() -> Text(stringResource(R.string.addons_none_found), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
@@ -166,29 +241,45 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AddonCard(addon: WowAddonCatalog.Addon, progress: Int?, done: Boolean, onInstall: () -> Unit) {
|
||||
private fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress: Int?, action: Modifier, onInstall: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val src = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }
|
||||
val hot = rememberHot(src)
|
||||
val shape = androidx.compose.foundation.shape.RoundedCornerShape(10.dp)
|
||||
Column(
|
||||
Modifier.fillMaxWidth().clip(shape).glideBorder(hot, shape, pal.signal, pal.line)
|
||||
.hoverable(src)
|
||||
.clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onInstall)
|
||||
.controllerConfirm(onClick = onInstall),
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||
modifier = Modifier.fillMaxWidth().clip(Shape12).background(colors.surface.copy(alpha = 0.6f)).border(1.dp, pal.line, Shape12)
|
||||
.padding(start = 8.dp, end = 8.dp, top = 6.dp, bottom = 6.dp),
|
||||
) {
|
||||
ArtCard(addon.name, addon.thumb, null, null, hot, capsule = false, chip = progress?.let { "$it%" }) {
|
||||
if (done) Icon(Icons.Filled.Check, stringResource(R.string.stores_installed_chip), tint = pal.good, modifier = Modifier.height(11.dp))
|
||||
else Text(stringResource(if (progress != null) R.string.store_installing else R.string.store_install), fontSize = 10.sp, color = pal.signal, maxLines = 1)
|
||||
Box(Modifier.size(44.dp).clip(Shape12).background(artBrush(hueOf(addon.name)))) {
|
||||
if (addon.thumb != null) AsyncImage(model = addon.thumb, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize())
|
||||
}
|
||||
Column(Modifier.weight(1f)) {
|
||||
Text(addon.name, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(
|
||||
listOf(addon.author, addon.summary, formatCount(addon.downloads)).filter { it.isNotEmpty() }.joinToString(" · "),
|
||||
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
}
|
||||
val size = Modifier.widthIn(min = 104.dp).then(action)
|
||||
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)
|
||||
}
|
||||
Text(
|
||||
listOf(addon.author, formatCount(addon.downloads)).filter { it.isNotEmpty() }.joinToString(" · "),
|
||||
fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
|
||||
modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private fun Modifier.scrollThumb(state: LazyGridState, color: Color): Modifier = drawWithContent {
|
||||
drawContent()
|
||||
val info = state.layoutInfo
|
||||
val visible = info.visibleItemsInfo
|
||||
if (visible.isEmpty() || visible.size >= info.totalItemsCount) return@drawWithContent
|
||||
val total = info.totalItemsCount.toFloat()
|
||||
val length = (size.height * visible.size / total).coerceAtLeast(24.dp.toPx())
|
||||
val top = (size.height - length) * (visible.first().index / (total - visible.size).coerceAtLeast(1f)).coerceIn(0f, 1f)
|
||||
val width = 3.dp.toPx()
|
||||
drawRoundRect(color, Offset(size.width - width, top), Size(width, length), CornerRadius(width / 2))
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun sortLabel(sort: WowAddonCatalog.Sort): String = stringResource(
|
||||
when (sort) {
|
||||
@@ -206,18 +297,18 @@ private fun formatCount(count: Long): String = when {
|
||||
else -> count.toString()
|
||||
}
|
||||
|
||||
private fun installAddon(context: Context, addon: WowAddonCatalog.Addon, target: WowAddons.Target, progress: (Int) -> Unit): Pair<String, Boolean> {
|
||||
internal fun installAddon(context: Context, addon: WowAddonCatalog.Addon, target: WowAddons.Target, progress: (Int) -> Unit): Pair<String, String?> {
|
||||
val zip = File(File(context.cacheDir, "wowaddons"), "download-wowi-${addon.id.filter(Char::isLetterOrDigit)}-${java.util.UUID.randomUUID()}.zip")
|
||||
return try {
|
||||
WowAddonCatalog.download(context, addon, zip, progress)
|
||||
if (SessionState.running) return context.getString(R.string.main_addons_close_session) to false
|
||||
val names = WowAddons.import(zip, target)
|
||||
if (names.isEmpty()) context.getString(R.string.main_addons_none, addon.name) to false
|
||||
else context.resources.getQuantityString(R.plurals.main_addons_imported, names.size, names.size, target.flavor) to true
|
||||
val version = WowAddonCatalog.download(context, addon, zip, progress) ?: addon.summary
|
||||
if (SessionState.running) return context.getString(R.string.main_addons_close_session) to null
|
||||
val names = WowAddons.import(zip, target, WowAddons.Origin(addon.id, version).takeIf { version.isNotBlank() }, context)
|
||||
if (names.isEmpty()) context.getString(R.string.main_addons_none, addon.name) to null
|
||||
else context.resources.getQuantityString(R.plurals.main_addons_imported, names.size, names.size, target.flavor) to version
|
||||
} catch (_: WowAddons.TooLarge) {
|
||||
context.getString(R.string.main_addons_too_large, addon.name) to false
|
||||
context.getString(R.string.main_addons_too_large, addon.name) to null
|
||||
} catch (e: Exception) {
|
||||
context.getString(R.string.stores_dl_failed_reason, e.message ?: e.javaClass.simpleName) to false
|
||||
context.getString(R.string.stores_dl_failed_reason, e.message ?: e.javaClass.simpleName) to null
|
||||
} finally {
|
||||
zip.delete()
|
||||
}
|
||||
|
||||
@@ -1495,22 +1495,26 @@ private fun ChoiceLine(
|
||||
if (progress != null) ProgressBit(progress)
|
||||
}
|
||||
if (!removable) Spacer(Modifier.padding(end = 6.dp).size(44.dp))
|
||||
else {
|
||||
val delSrc = remember { MutableInteractionSource() }
|
||||
val delHot = rememberHot(delSrc)
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.padding(end = 6.dp).size(44.dp).clip(ROW_SHAPE)
|
||||
.background(if (delHot) colors.error.copy(alpha = 0.14f) else Color.Transparent)
|
||||
.glideBorder(delHot, ROW_SHAPE, colors.error)
|
||||
.hoverable(delSrc).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = delSrc, indication = null, onClick = onDelete)
|
||||
.controllerConfirm(onClick = onDelete),
|
||||
) { Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, name), tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(19.dp)) }
|
||||
}
|
||||
else DeleteButton(name, onDelete = onDelete)
|
||||
}
|
||||
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun DeleteButton(name: String, modifier: Modifier = Modifier, enabled: Boolean = true, onDelete: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val delSrc = remember { MutableInteractionSource() }
|
||||
val delHot = rememberHot(delSrc) && enabled
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = modifier.padding(end = 6.dp).size(44.dp).clip(ROW_SHAPE)
|
||||
.background(if (delHot) colors.error.copy(alpha = 0.14f) else Color.Transparent)
|
||||
.glideBorder(delHot, ROW_SHAPE, colors.error)
|
||||
.hoverable(delSrc).clickable(role = androidx.compose.ui.semantics.Role.Button, interactionSource = delSrc, indication = null, enabled = enabled, onClick = onDelete)
|
||||
.controllerConfirm(enabled = enabled, onClick = onDelete),
|
||||
) { Icon(Icons.Outlined.Delete, contentDescription = stringResource(R.string.common_delete_named, name), tint = if (delHot) colors.error else colors.onSurfaceVariant, modifier = Modifier.size(19.dp)) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GetLine(
|
||||
name: String, detail: String, progress: Int?, enabled: Boolean,
|
||||
|
||||
@@ -477,7 +477,7 @@ private fun UserAppIcon(app: UserApps.App, size: Int) {
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun UserAppsProgress() {
|
||||
internal fun UserAppsProgress() {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val working = UserAppsState.working
|
||||
Column(verticalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
|
||||
@@ -514,7 +514,9 @@ private fun UserAppPage(app: UserApps.App, s: FrontEndState, a: FrontEndActions,
|
||||
Column {
|
||||
Text(app.name, fontSize = if (narrow) 22.sp else 26.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
|
||||
Text(
|
||||
(app.repo?.let { stringResource(R.string.user_apps_github_version, it, app.version.orEmpty()) } ?: stringResource(app.kind.label())) +
|
||||
(app.repo?.let { stringResource(R.string.user_apps_github_version, it, app.version.orEmpty()) }
|
||||
?: app.version?.takeIf { app.feed != null }?.let { stringResource(R.string.user_apps_github_version, stringResource(app.kind.label()), it) }
|
||||
?: stringResource(app.kind.label())) +
|
||||
(if (app.arch == "x86_64" || app.arch == "i386") " · " + stringResource(R.string.app_fex_x86, app.arch) else ""),
|
||||
fontSize = 14.sp, color = colors.onSurfaceVariant,
|
||||
)
|
||||
@@ -526,7 +528,7 @@ private fun UserAppPage(app: UserApps.App, s: FrontEndState, a: FrontEndActions,
|
||||
PrimaryButton(stringResource(R.string.user_apps_open, app.name), enabled = !s.busy, main = true) { a.onUserApp(app) }
|
||||
BusyChip(s)
|
||||
SecondaryButton(stringResource(R.string.user_apps_edit), enabled = UserAppsState.working == null) { editing = true }
|
||||
if (app.repo != null) UpdateButton(app, s)
|
||||
if (app.updatable) UpdateButton(app, s)
|
||||
RemoveAppButton(app, enabled = !s.busy && !s.sessionRunning && UserAppsState.working == null) {
|
||||
UserAppsState.remove(ctx, app); onSelect("desktop")
|
||||
}
|
||||
|
||||
@@ -42,6 +42,7 @@ import androidx.compose.material.icons.Icons
|
||||
import androidx.compose.material.icons.filled.Favorite
|
||||
import androidx.compose.material.icons.filled.FavoriteBorder
|
||||
import androidx.compose.material.icons.filled.PlayArrow
|
||||
import androidx.compose.material.icons.outlined.Download
|
||||
import androidx.compose.material.icons.outlined.Delete
|
||||
import androidx.compose.material.icons.outlined.Edit
|
||||
import androidx.compose.material.icons.outlined.VideogameAsset
|
||||
@@ -54,6 +55,7 @@ import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.SideEffect
|
||||
import androidx.compose.runtime.key
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.produceState
|
||||
import androidx.compose.runtime.remember
|
||||
@@ -94,7 +96,11 @@ import coil.compose.AsyncImage
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.GameRemoval
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
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.store.UserAppsState
|
||||
import com.droiddeck.launcher.session.GameSaves
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
@@ -960,9 +966,14 @@ private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, a:
|
||||
var browsing by remember(g.gameId) { mutableStateOf<WowAddons.Target?>(null) }
|
||||
browsing?.let { AddonBrowserDialog(targets, it) { browsing = null } }
|
||||
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
|
||||
CurseForgeEntry(a)
|
||||
targets.forEach { target ->
|
||||
val names by produceState(emptyList<String>(), target.addOns, WowAddons.imports) {
|
||||
value = withContext(Dispatchers.IO) { WowAddons.installed(target) }
|
||||
val names by produceState(emptyList<WowAddons.Installed>(), target.addOns, WowAddons.imports) {
|
||||
value = withContext(Dispatchers.IO) { WowAddons.details(target) }
|
||||
}
|
||||
val context = LocalContext.current
|
||||
val updates by produceState(emptyMap<String, WowAddonCatalog.Addon>(), names) {
|
||||
value = withContext(Dispatchers.IO) { WowAddonCatalog.updates(context, names, target) }
|
||||
}
|
||||
if (targets.size > 1) SectionLabel(target.flavor)
|
||||
MenuItem(stringResource(R.string.addons_download), checked = false) { browsing = target }
|
||||
@@ -974,17 +985,85 @@ private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, a:
|
||||
target.addOns.mkdirs()
|
||||
a.onBrowseFiles(target.addOns)
|
||||
}
|
||||
names.forEach { name -> AddonRow(name, target, a) }
|
||||
names.forEach { item -> key(target.addOns, item.name) { AddonRow(item, updates[item.name], target, a) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AddonRow(name: String, target: WowAddons.Target, a: FrontEndActions) {
|
||||
private fun CurseForgeEntry(a: FrontEndActions) {
|
||||
val ctx = LocalContext.current
|
||||
val name = stringResource(R.string.addons_source_curse)
|
||||
LaunchedEffect(Unit) { UserAppsState.refresh(ctx) }
|
||||
val app = CurseForgeApp.find(UserAppsState.items)
|
||||
val idle = UserAppsState.working == null
|
||||
if (app == null) {
|
||||
MenuItem(stringResource(R.string.content_install_named, name), checked = false, enabled = idle && !SessionState.running) {
|
||||
UserAppsState.add(ctx, CurseForgeApp.request(), name)
|
||||
}
|
||||
} else {
|
||||
var asking by remember(app.key) { mutableStateOf(false) }
|
||||
var checked by remember { mutableStateOf<String?>(null) }
|
||||
val checkKey = app.key + "@" + app.version
|
||||
LaunchedEffect(checkKey, UserAppsState.checking) {
|
||||
if (UserAppsState.checking == null && checked != checkKey) {
|
||||
checked = checkKey
|
||||
UserAppsState.checkUpdate(ctx, app)
|
||||
}
|
||||
}
|
||||
val update = (UserAppsState.updates[app.key] as? UserApps.UpdateCheck.Available)?.release
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
|
||||
MenuItem(
|
||||
stringResource(R.string.user_apps_open, name), checked = false, enabled = idle,
|
||||
detail = app.version, modifier = Modifier.weight(1f),
|
||||
) { a.onUserApp(app) }
|
||||
DeleteButton(name, enabled = idle && !SessionState.running) { asking = true }
|
||||
}
|
||||
if (update != null) MenuItem(stringResource(R.string.user_apps_update_to, update.tag), checked = false, enabled = idle && !SessionState.running) {
|
||||
UserAppsState.update(ctx, app, update)
|
||||
}
|
||||
(UserAppsState.updates[app.key] as? UserApps.UpdateCheck.Failed)?.let { failed ->
|
||||
MenuItem(stringResource(R.string.user_apps_check_updates), checked = false, enabled = idle && UserAppsState.checking == null, detail = failed.message) {
|
||||
UserAppsState.checkUpdate(ctx, app)
|
||||
}
|
||||
}
|
||||
if (asking) ConfirmDialog(
|
||||
title = stringResource(R.string.flathub_remove_title, name),
|
||||
text = stringResource(R.string.flathub_remove_note),
|
||||
confirm = stringResource(R.string.user_apps_remove),
|
||||
onConfirm = { asking = false; UserAppsState.remove(ctx, app) },
|
||||
onDismiss = { asking = false },
|
||||
)
|
||||
}
|
||||
if (UserAppsState.working == name || (UserAppsState.lastError?.startsWith(name) == true)) UserAppsProgress()
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AddonRow(item: WowAddons.Installed, update: WowAddonCatalog.Addon?, target: WowAddons.Target, a: FrontEndActions) {
|
||||
val name = item.name
|
||||
var asking by remember(target.addOns, name) { mutableStateOf(false) }
|
||||
var progress by remember(target.addOns, name) { mutableStateOf<Int?>(null) }
|
||||
val context = LocalContext.current
|
||||
val scope = rememberCoroutineScope()
|
||||
val delete = stringResource(R.string.common_delete)
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(start = 16.dp, top = 2.dp, bottom = 2.dp)) {
|
||||
Text(name, fontSize = 14.sp, color = MaterialTheme.colorScheme.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f))
|
||||
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(" · ")
|
||||
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,
|
||||
)
|
||||
}
|
||||
if (update != null && !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 } } }
|
||||
progress = null
|
||||
android.widget.Toast.makeText(context, message.first, android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
if (!SessionState.running) IconAction(Icons.Outlined.Delete, delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true }
|
||||
}
|
||||
if (asking) ConfirmDialog(
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNull
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
|
||||
class UserAppsFeedTest {
|
||||
private val feed = "https://example.com/apps/linux/latest-linux.yml"
|
||||
private val sha = "ajcSve2Wq1CgocS5zWlmdfb0pI0C+JqNvbFx6Vm9j9/fW1Q/u2dnnNvNGmi0gulEXp7tnRkYCCc7rfwtjKcoNw=="
|
||||
|
||||
private fun body(path: String = "App-1.2.0-7.AppImage", hash: String = sha) = """
|
||||
version: 1.2.0-7
|
||||
files:
|
||||
- url: App-1.2.0-7.AppImage
|
||||
sha512: $hash
|
||||
size: 100
|
||||
- url: App_1.2.0-7_amd64.deb
|
||||
sha512: other
|
||||
path: $path
|
||||
sha512: $hash
|
||||
releaseDate: '2026-11-15T18:08:09.118Z'
|
||||
""".trimIndent()
|
||||
|
||||
@Test fun feedGivesTheAppImageRelease() {
|
||||
val release = UserApps.parseFeed(feed, body())!!
|
||||
assertEquals("1.2.0-7", release.tag)
|
||||
assertEquals("App-1.2.0-7.AppImage", release.asset)
|
||||
assertEquals("https://example.com/apps/linux/App-1.2.0-7.AppImage", release.url)
|
||||
assertEquals("2026-11-15T18:08:09.118Z", release.published)
|
||||
assertEquals(128, release.sha512!!.length)
|
||||
assertEquals("6a3712bded96ab50a0a1c4b9cd696675f6f4a48d02f89a8dbdb171e959bd8fdfdf5b543fbb67679cdbcd1a68b482e9445e9eed9d191808273badfc2d8ca72837", release.sha512)
|
||||
assertNull(release.sha256)
|
||||
}
|
||||
|
||||
@Test fun feedWithoutAnAppImageOrHashIsRefused() {
|
||||
assertNull(UserApps.parseFeed(feed, body(path = "App_1.2.0-7_amd64.deb")))
|
||||
assertNull(UserApps.parseFeed(feed, body(path = "../App.AppImage")))
|
||||
assertNull(UserApps.parseFeed(feed, body(path = "sub/App.AppImage")))
|
||||
assertNull(UserApps.parseFeed(feed, body(hash = "c2hvcnQ=")))
|
||||
assertNull(UserApps.parseFeed("http://example.com/latest-linux.yml", body()))
|
||||
assertNull(UserApps.parseFeed(feed, "path: App.AppImage\n"))
|
||||
}
|
||||
|
||||
@Test fun curseForgeIsFoundByItsFeed() {
|
||||
val other = UserApps.App("appimage:a", UserApps.Kind.APPIMAGE, "CurseForge", null, null, AppImageManager.LAUNCHER, emptyList())
|
||||
val official = UserApps.App("appimage:b", UserApps.Kind.APPIMAGE, "Mods", null, null, AppImageManager.LAUNCHER, emptyList(), feed = CurseForgeApp.FEED)
|
||||
assertEquals("appimage:b", CurseForgeApp.find(listOf(other, official))?.key)
|
||||
assertNull(CurseForgeApp.find(listOf(other)))
|
||||
}
|
||||
|
||||
@Test fun olderOrEqualFeedReleasesAreNotOffered() {
|
||||
val release = UserApps.parseFeed(feed, body())!!
|
||||
assertTrue(UserApps.isNewer(release, "2026-11-01T00:00:00.000Z", "1.0"))
|
||||
assertFalse(UserApps.isNewer(release, "2099-01-01T00:00:00.000Z", "9.9"))
|
||||
assertFalse(UserApps.isNewer(release, "", release.tag))
|
||||
assertTrue(UserApps.isNewer(release, "", "0.1"))
|
||||
}
|
||||
|
||||
@Test fun publicationTimesCompareAsInstantsWhateverTheirPrecision() {
|
||||
val release = UserApps.parseFeed(feed, body())!!
|
||||
assertTrue(UserApps.isNewer(release, "2026-11-15T18:08:09Z", "1.0"))
|
||||
assertFalse(UserApps.isNewer(release, "2026-11-15T18:08:09.118000Z", "1.0"))
|
||||
assertFalse(UserApps.isNewer(release, "2026-11-15T18:08:10Z", "1.0"))
|
||||
}
|
||||
}
|
||||
@@ -150,8 +150,8 @@ us|1|aa|bb|cc||tpr/wow|h|s|t||1|12.1.0.65000|kk|wowf
|
||||
|
||||
@Test fun wowiDetailsGiveUrlAndMd5() {
|
||||
val d = WowAddonCatalog.parseWowiDetails("""[{"UID":"1","UIMD5":"abc","UIDownload":"https://cdn.wowinterface.com/downloads/getfile.php?id=1"}]""")
|
||||
assertEquals("https://cdn.wowinterface.com/downloads/getfile.php?id=1", d?.first)
|
||||
assertEquals("abc", d?.second)
|
||||
assertEquals("https://cdn.wowinterface.com/downloads/getfile.php?id=1", d?.url)
|
||||
assertEquals("abc", d?.md5)
|
||||
assertNull(WowAddonCatalog.parseWowiDetails("""[{"UID":"1","UIDownload":""}]"""))
|
||||
assertNull(WowAddonCatalog.parseWowiDetails("[]"))
|
||||
}
|
||||
@@ -162,9 +162,40 @@ us|1|aa|bb|cc||tpr/wow|h|s|t||1|12.1.0.65000|kk|wowf
|
||||
assertTrue(WowAddonCatalog.isHttps("https://example.com/a.zip"))
|
||||
}
|
||||
|
||||
@Test fun curseForgeUrlAddsTheSearchText() {
|
||||
assertEquals("https://www.curseforge.com/wow/search?class=addons", WowAddonCatalog.curseForgeUrl(" "))
|
||||
assertEquals("https://www.curseforge.com/wow/search?class=addons&search=deadly+boss+%26+mods", WowAddonCatalog.curseForgeUrl(" deadly boss & mods "))
|
||||
private fun entry(id: String, version: String) =
|
||||
WowAddonCatalog.Entry(WowAddonCatalog.Addon(id, "Addon $id", "author", version, 0L, 0L, null), "1", null)
|
||||
|
||||
@Test fun updatesComeFromTheInstalledSourceVersion() {
|
||||
val entries = listOf(entry("10", "2.1.0"), entry("20", "v5"), entry("30", ""))
|
||||
val installed = listOf(
|
||||
WowAddons.Installed("Old", "2.0.9", "10"),
|
||||
WowAddons.Installed("OldPart", "2.0.9", "10"),
|
||||
WowAddons.Installed("Same", "5", "20"),
|
||||
WowAddons.Installed("NoLatest", "1", "30"),
|
||||
WowAddons.Installed("Unknown", "1", "99"),
|
||||
WowAddons.Installed("Local", "1", null),
|
||||
WowAddons.Installed("NoVersion", null, "10"),
|
||||
)
|
||||
val updates = WowAddonCatalog.findUpdates(entries, installed)
|
||||
assertEquals(setOf("Old"), updates.keys)
|
||||
assertEquals("2.1.0", updates.getValue("Old").summary)
|
||||
}
|
||||
|
||||
@Test fun aCurrentRowDoesNotHideAnOutdatedRowWithTheSameSource() {
|
||||
val installed = listOf(WowAddons.Installed("A", "2", "10"), WowAddons.Installed("B", "1", "10"))
|
||||
assertEquals(setOf("B"), WowAddonCatalog.findUpdates(listOf(entry("10", "2")), installed).keys)
|
||||
}
|
||||
|
||||
@Test fun wowiDetailsCarryTheDownloadedVersion() {
|
||||
val d = WowAddonCatalog.parseWowiDetails("""[{"UIDownload":"https://cdn.wowinterface.com/a.zip","UIVersion":" 2.0 "}]""")
|
||||
assertEquals("2.0", d?.version)
|
||||
assertNull(WowAddonCatalog.parseWowiDetails("""[{"UIDownload":"https://cdn.wowinterface.com/a.zip"}]""")?.version)
|
||||
}
|
||||
|
||||
@Test fun versionsCompareWithoutPrefixOrCase() {
|
||||
assertTrue(WowAddonCatalog.sameVersion("v1.2.3", "1.2.3"))
|
||||
assertTrue(WowAddonCatalog.sameVersion(" 1.2-Beta ", "1.2-beta"))
|
||||
assertFalse(WowAddonCatalog.sameVersion("1.2.3", "1.2.4"))
|
||||
}
|
||||
|
||||
@Test fun md5Check() {
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.droiddeck.launcher.runtime
|
||||
|
||||
import org.apache.commons.compress.archivers.sevenz.SevenZOutputFile
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
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.nio.file.Files
|
||||
|
||||
@RunWith(RobolectricTestRunner::class)
|
||||
@Config(sdk = [33])
|
||||
class WowAddonsArchiveTest {
|
||||
@get:Rule val temp = TemporaryFolder()
|
||||
|
||||
private fun target(): WowAddons.Target {
|
||||
val root = temp.newFolder("World of Warcraft")
|
||||
File(root, "_retail_").mkdirs()
|
||||
return WowAddons.targets(BattleNet.title("wow")!!, root).single()
|
||||
}
|
||||
|
||||
private fun sevenZip(vararg files: Pair<String, String>): File {
|
||||
val file = temp.newFile("addon-${System.nanoTime()}.bin")
|
||||
SevenZOutputFile(file).use { out ->
|
||||
for ((name, text) in files) {
|
||||
val entry = out.createArchiveEntry(File(name), name)
|
||||
out.putArchiveEntry(entry)
|
||||
out.write(text.toByteArray())
|
||||
out.closeArchiveEntry()
|
||||
}
|
||||
}
|
||||
return file
|
||||
}
|
||||
|
||||
private fun unpacked() = File(RuntimeEnvironment.getApplication().cacheDir, "wowaddons").listFiles().orEmpty().filter { it.name.startsWith("unpack-") }
|
||||
|
||||
@Test fun sevenZipArchivesImportLikeZips() {
|
||||
val target = target()
|
||||
val names = WowAddons.import(sevenZip("Pack/Foo/Foo.toc" to "toc", "Pack/Foo/core.lua" to "lua", "Pack/Bar/Bar.toc" to "toc"), target, context = RuntimeEnvironment.getApplication())
|
||||
assertEquals(listOf("Bar", "Foo"), names.sorted())
|
||||
assertEquals("lua", File(target.addOns, "Foo/core.lua").readText())
|
||||
assertTrue(File(target.addOns, "Bar/Bar.toc").isFile)
|
||||
assertTrue(unpacked().isEmpty())
|
||||
}
|
||||
|
||||
@Test fun sevenZipArchivesWithoutAnAddonChangeNothing() {
|
||||
val target = target()
|
||||
assertEquals(emptyList<String>(), WowAddons.import(sevenZip("readme.txt" to "x"), target, context = RuntimeEnvironment.getApplication()))
|
||||
assertFalse(target.addOns.exists())
|
||||
assertTrue(unpacked().isEmpty())
|
||||
}
|
||||
|
||||
@Test fun aFolderWithAnyLinkIsRefusedWhole() {
|
||||
val target = target()
|
||||
val folder = temp.newFolder("unpacked")
|
||||
File(folder, "Foo").mkdirs()
|
||||
File(folder, "Foo/Foo.toc").writeText("toc")
|
||||
Files.createSymbolicLink(File(folder, "Foo/link.lua").toPath(), File(folder, "Foo/Foo.toc").toPath())
|
||||
assertEquals(emptyList<String>(), WowAddons.importFolder(folder, target, null))
|
||||
assertFalse(target.addOns.exists())
|
||||
}
|
||||
|
||||
@Test fun aFolderImportKeepsEveryFile() {
|
||||
val target = target()
|
||||
val folder = temp.newFolder("unpacked")
|
||||
File(folder, "Foo/Libs").mkdirs()
|
||||
File(folder, "Foo/Foo.toc").writeText("toc")
|
||||
File(folder, "Foo/Libs/lib.lua").writeText("lib")
|
||||
assertEquals(listOf("Foo"), WowAddons.importFolder(folder, target, null))
|
||||
assertEquals("lib", File(target.addOns, "Foo/Libs/lib.lua").readText())
|
||||
}
|
||||
}
|
||||
@@ -218,4 +218,50 @@ class WowAddonsTest {
|
||||
File(root, "_retail_").mkdirs()
|
||||
assertEquals(emptyList<String>(), WowAddons.targets(BattleNet.title("fenris")!!, root).map { it.flavor })
|
||||
}
|
||||
|
||||
@Test fun tocFieldsReadVersionAndSourceIds() {
|
||||
val fields = WowAddons.tocFields("\uFEFF## Interface: 110002\n## Title: Foo\n## Version: 1.4.2\n## X-WoWI-ID: 1234\n## Version: 9\n## X-Curse-Project-ID: @curse-id@\nFoo.lua\n")
|
||||
assertEquals("1.4.2", fields["Version"])
|
||||
assertEquals("1234", fields["X-WoWI-ID"])
|
||||
assertEquals(null, fields["X-Curse-Project-ID"])
|
||||
}
|
||||
|
||||
@Test fun detailsUseTheTocAndTheRecordedSource() {
|
||||
val target = target()
|
||||
val foo = File(target.addOns, "Foo").apply { mkdirs() }
|
||||
File(foo, "Foo_Mainline.toc").writeText("## Version: 1.0\n## X-WoWI-ID: 77\n")
|
||||
File(target.addOns, "Bar").mkdirs()
|
||||
val details = WowAddons.details(target).associateBy { it.name }
|
||||
assertEquals(setOf("Bar", "Foo"), details.keys)
|
||||
assertEquals("1.0", details.getValue("Foo").version)
|
||||
assertEquals("77", details.getValue("Foo").wowiId)
|
||||
assertEquals(null, details.getValue("Bar").version)
|
||||
}
|
||||
|
||||
@Test fun importRecordsTheSourceAndPlainImportsClearIt() {
|
||||
val target = target()
|
||||
WowAddons.import(zip("Foo/Foo.toc" to "## Version: 1.0\n"), target, WowAddons.Origin("55", "2.0"))
|
||||
val recorded = WowAddons.details(target).single()
|
||||
assertEquals("2.0", recorded.version)
|
||||
assertEquals("55", recorded.wowiId)
|
||||
WowAddons.import(zip("Foo/Foo.toc" to "## Version: 3.0\n"), target)
|
||||
val plain = WowAddons.details(target).single()
|
||||
assertEquals("3.0", plain.version)
|
||||
assertEquals(null, plain.wowiId)
|
||||
assertFalse(File(target.addOns, ".droiddeck-sources").exists())
|
||||
}
|
||||
|
||||
@Test fun deleteForgetsTheRecordedSource() {
|
||||
val target = target()
|
||||
WowAddons.import(zip("Foo/Foo.toc" to "x", "Bar/Bar.toc" to "y"), target, WowAddons.Origin("55", "2.0"))
|
||||
WowAddons.delete(target, "Foo")
|
||||
assertEquals(mapOf("Bar" to "55"), WowAddons.parseOrigins(File(target.addOns, ".droiddeck-sources").readText()).mapValues { it.value.id })
|
||||
assertEquals(listOf("Bar"), WowAddons.installed(target))
|
||||
}
|
||||
|
||||
@Test fun originsRoundTripAndSkipBrokenLines() {
|
||||
val text = WowAddons.formatOrigins(mapOf("A" to WowAddons.Origin("1", "1.0 beta\t2")))
|
||||
assertEquals("1.0 beta 2", WowAddons.parseOrigins(text).getValue("A").version)
|
||||
assertEquals(emptyMap<String, WowAddons.Origin>(), WowAddons.parseOrigins("bad line\nA\t\t1\n"))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user