feat(itch): update detection and safe updates for installed games (#1665)

## Summary

Adds update detection for installed itch.io games. This is PR4 of the
itch.io store rework (browse, filters, game page and collections are
merged; Linux support is #1589). Butler patching comes later as an
add-on pack. Updates here download the full build.

## What changed

- `ItchUpdates` (new): compares each installed itch game with the
uploads itch lists for it (`GET /games/{id}/uploads`), using what the
install already saves: `installVersion` (the upload's `updated_at`) plus
`gameId`, `downloadKeyId` and `uploadId` in `extra`.
- The installed upload is still listed and has a later `updated_at`: an
update.
- The installed upload is gone: the newest Windows upload is offered as
a replaced build.
- An install without an `uploadId` compares the newest Windows upload's
date.
- An unknown installed version, or no answer from itch, never reports an
update.
- The check walks installed games one at a time, one second apart, and
logs `itch.io: checked <n> installed games, <m> with updates`. It runs
when the itch tab opens (at most every 6 hours) and from the new button.
A game itch did not answer for keeps its last result. Results are cached
in the itch preferences until the update is installed or the account
signs out.
- Library: games with an update show an "Update" label on their tile and
row. A Check for updates button in the Library header (itch tab only)
runs the check on demand, shows progress, and ends with a toast:
"Updates available: N" or "Up to date".
- Game page: an Update button appears for installed itch games with an
update. A replaced build asks first and names the new file. A plain
newer build updates directly.
- Safe updates: an update never extracts into the live game. The archive
is unpacked into `.droiddeck-update` inside the game folder, and the new
build must contain an executable before any game file is touched. A
failed or cancelled download or extraction removes the staging folder
and leaves the game as it was. Then `ItchStaging.merge` moves the staged
files into place with renames inside one folder. A staged file replaces
the file with the same path, directories are merged, and anything the
new build doesn't contain (saves, settings, install record, launcher,
art) stays. The install record is marked updating just before the move,
so an interruption there is resumable.
- New strings `stores_itch_updates_found` and
`stores_itch_update_replaced` in all 33 locales. The button label, toast
and dialog buttons reuse existing strings.
- `docs/development/itch-updates.md` describes the feature.

## Notes

- One extra copy of the build's size must be free while an update runs.
- Files the developer removed in the new version stay in the game
folder, because everything the new build doesn't contain is kept.
- The final rename step is not an all-or-nothing swap. A crash or power
loss inside it leaves the game marked updating and resumable.
- The update reruns the normal install over the game's own folder and
storage location.

## Tests

- `ItchUpdatesTest` (Robolectric, like the other itch tests): newer,
same and older stamps, replaced upload falling back to the newest
Windows build, unknown installed version, no answer, an install without
an upload id, and the cache round trip.
- `ItchStagingTest`: new files replace old ones, other files stay, and a
file replacing a directory and the other way round.
- Not run on a device or compiled locally; relying on CI. The controller
focus behaviour of the new buttons is untested.
This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-10-28 09:36:19 -04:00
commit 8f6b2a4123
46 files changed
+656 -26

No files matched your search

@@ -63,7 +63,7 @@ class StoreGameSidecar(
val file = File(folder, FILE_NAME)
val tmp = File(folder, "$FILE_NAME.tmp")
tmp.writeText(toJson().toString(2))
if (!tmp.renameTo(file)) { file.delete(); tmp.renameTo(file) }
if (!tmp.renameTo(file)) java.nio.file.Files.move(tmp.toPath(), file.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING)
}
companion object {
@@ -30,7 +30,12 @@ object StoreInstalls {
it.write(before.copy(state = StoreGameSidecar.STATE_UPDATING, installVersion = "").toJson().toString(2).toByteArray(Charsets.UTF_8))
it.fd.sync()
}
Files.move(stage.toPath(), StoreGameSidecar.file(folder).toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
val record = StoreGameSidecar.file(folder).toPath()
try {
Files.move(stage.toPath(), record, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
} catch (e: java.nio.file.AtomicMoveNotSupportedException) {
Files.move(stage.toPath(), record, StandardCopyOption.REPLACE_EXISTING)
}
} finally {
stage.delete()
}
@@ -191,7 +191,10 @@ object StoresState {
backend?.signOut(app)
if (store == Store.GOG) com.droiddeck.launcher.stores.gog.GogComet.replaceAccount { StoreAccounts.clear(app, store) }
else if (store != Store.XBOX || backend == null) StoreAccounts.clear(app, store)
if (store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchCollections.clear()
if (store == Store.ITCH) {
com.droiddeck.launcher.stores.itch.ItchCollections.clear()
com.droiddeck.launcher.stores.itch.ItchUpdates.clear(app)
}
main.post {
if (store == Store.XBOX && StoreAccounts.signedInAs(app, store) != null) return@post
accounts.remove(store); library.remove(store); status.remove(store); problems.remove(store); libraryAsked.remove(store)
@@ -282,6 +285,7 @@ object StoresState {
main.post {
installed = installed.filterNot { it.folder.absolutePath == game.folder.absolutePath }
uninstalling.remove(key)
if (game.sidecar.store == Store.ITCH) com.droiddeck.launcher.stores.itch.ItchUpdates.applied(app, key)
}
})
main.post(onDone)
@@ -33,6 +33,10 @@ internal class ItchInstaller(
private val folder: File,
) : DownloadQueue.DownloadJob {
private val cancelled = AtomicBoolean(false)
private var work: File = folder
private var updating = false
private var previous: StoreGameSidecar? = null
private val commit = Any()
override fun run(handle: DownloadQueue.JobHandle): String? {
val key = ItchAuth.key(app)
@@ -40,7 +44,10 @@ internal class ItchInstaller(
val downloadKeyId = item.extra["downloadKeyId"].orEmpty()
if (downloadKeyId.isBlank() && !item.isFree) throw IllegalStateException(app.getString(R.string.stores_itch_not_owned))
val gameId = ItchGame.resolveId(item) ?: throw IllegalStateException(app.getString(R.string.stores_itch_no_game))
val resuming = StoreGameSidecar.read(folder)?.let { it.state == StoreGameSidecar.STATE_INSTALLING && it.id == item.id } == true
val before = StoreGameSidecar.read(folder)
previous = before
updating = before != null && (before.isInstalled || before.state == StoreGameSidecar.STATE_UPDATING)
val resuming = before?.let { it.state == StoreGameSidecar.STATE_INSTALLING && it.id == item.id } == true
StoreInstalls.begin(folder, Store.ITCH, item.id, item.title, item.imageUrl, item.imageUrl)
handle.stage(DownloadStage.MANIFEST)
val uploads = ItchApi.uploads(key, gameId, downloadKeyId)
@@ -60,12 +67,12 @@ internal class ItchInstaller(
handle.stage(DownloadStage.INSTALL)
install(archive, filename, handle, resuming)
} catch (t: Throwable) {
if (!cancelled.get()) StoreInstalls.discard(app, folder, listOf(scratch))
if (!cancelled.get()) dropCaches(scratch)
throw t
}
if (exe == null) {
if (cancelled.get()) return null
StoreInstalls.discard(app, folder, listOf(scratch))
dropCaches(scratch)
throw IllegalStateException(app.getString(R.string.stores_itch_no_exe))
}
archive.delete()
@@ -75,6 +82,8 @@ internal class ItchInstaller(
id = item.id,
title = item.title,
exe = exe,
args = previous?.args.orEmpty(),
env = previous?.env.orEmpty(),
installVersion = upload.optString("updated_at", upload.optString("updatedAt")),
installedAt = System.currentTimeMillis(),
cover = item.imageUrl,
@@ -83,12 +92,24 @@ internal class ItchInstaller(
cloud = false,
)
StoreInstalls.complete(app, folder, sidecar) { done, steps -> handle.stageProgress(done.toLong(), steps.toLong()) }
ItchUpdates.applied(app, item.key)
return folder.path
}
override fun cancel(deleteFiles: Boolean) {
cancelled.set(true)
if (deleteFiles) StoreInstalls.discard(app, folder, listOf(StoreInstallRoot.scratchDir(app, Store.ITCH, item.id)))
if (deleteFiles) dropCaches(StoreInstallRoot.scratchDir(app, Store.ITCH, item.id))
}
private fun dropCaches(scratch: File) {
if (!updating) {
StoreInstalls.discard(app, folder, listOf(scratch))
return
}
synchronized(commit) {
StoreInstalls.deleteTree(scratch)
ItchStaging.delete(File(folder, ItchStaging.DIR))
}
}
private fun download(key: String, downloadKeyId: String, uploadId: String, version: String, target: File, expected: Long,
@@ -158,23 +179,45 @@ internal class ItchInstaller(
}
private fun install(archive: File, filename: String, handle: DownloadQueue.JobHandle, resuming: Boolean): String? {
folder.mkdirs()
work = if (updating) File(folder, ItchStaging.DIR) else folder
if (updating) ItchStaging.delete(work)
work.mkdirs()
if (resuming) clearPartialInstall()
when (val kind = sniff(archive, filename)) {
"zip" -> unzip(archive, handle)
"7z" -> sevenZip(archive, handle)
"rar" -> unrar(archive, handle)
"exe" -> copy(archive, File(folder, filename.ifBlank { "game.exe" }))
"tar" -> untar(archive, null, handle)
"gz", "bz2", "xz" -> untar(archive, kind, handle) ?: single(archive, kind, handle)
else -> copy(archive, File(folder, filename.ifBlank { "game" }))
val exe = try {
when (val kind = sniff(archive, filename)) {
"zip" -> unzip(archive, handle)
"7z" -> sevenZip(archive, handle)
"rar" -> unrar(archive, handle)
"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)
else -> copy(archive, File(work, filename.ifBlank { "game" }))
}
val hint = filename.substringBeforeLast('.')
StoreExe.pick(work, hint.ifBlank { null }, item.title)
} catch (t: Throwable) {
if (updating) ItchStaging.delete(work)
throw t
}
val hint = filename.substringBeforeLast('.')
val exe = StoreExe.pick(folder, hint.ifBlank { null }, item.title)
if (exe.isBlank()) {
handle.log("itch.io: no exe found in ${folder.name}")
if (updating) ItchStaging.delete(work)
return null
}
if (updating) synchronized(commit) {
if (cancelled.get()) {
ItchStaging.delete(work)
return null
}
try {
StoreInstalls.markUpdating(folder)
} catch (t: Throwable) {
ItchStaging.delete(work)
throw t
}
ItchStaging.merge(work, folder)
ItchStaging.delete(work)
}
return exe
}
@@ -197,8 +240,8 @@ internal class ItchInstaller(
}
private fun target(name: String): File? {
val file = File(folder, name.replace('\\', '/'))
val root = folder.canonicalPath
val file = File(work, name.replace('\\', '/'))
val root = work.canonicalPath
val path = file.canonicalPath
return if (path == root || path.startsWith(root + File.separator)) file else null
}
@@ -206,8 +249,8 @@ internal class ItchInstaller(
// No JVM library reads RAR5; the runtime's bsdtar (libarchive) does.
private fun unrar(archive: File, handle: DownloadQueue.JobHandle) {
if (!LinuxRuntime.isInstalled(app)) throw IllegalStateException(app.getString(R.string.stores_itch_archive, "rar"))
val binds = if (listOf(app.filesDir, app.cacheDir).any { folder.absolutePath.startsWith(it.absolutePath + "/") }) null
else listOf(folder.absolutePath)
val binds = if (listOf(app.filesDir, app.cacheDir).any { work.absolutePath.startsWith(it.absolutePath + "/") }) null
else listOf(work.absolutePath)
fun bsdtar(args: List<String>, onLine: (String) -> Unit) =
GuestCommand.run(app, listOf("/usr/bin/bsdtar") + args, logName = "itch-unrar", extraBinds = binds, fastPath = true) { line ->
if (!line.startsWith("proot ")) onLine(line)
@@ -216,7 +259,7 @@ internal class ItchInstaller(
bsdtar(listOf("-tf", archive.absolutePath)) { entries++ }
var done = 0L
val tail = ArrayDeque<String>()
val code = bsdtar(listOf("-xvf", archive.absolutePath, "-C", folder.absolutePath)) { line ->
val code = bsdtar(listOf("-xvf", archive.absolutePath, "-C", work.absolutePath)) { line ->
if (line.startsWith("x ")) handle.stageProgress(++done, entries) else {
if (tail.size == 5) tail.removeFirst()
tail.addLast(line)
@@ -0,0 +1,30 @@
package com.droiddeck.launcher.stores.itch
import java.io.File
import java.nio.file.Files
internal object ItchStaging {
const val DIR = ".droiddeck-update"
const val RECORD = ".droiddeck-store.json"
fun merge(from: File, to: File, top: Boolean = true) {
for (child in from.listFiles().orEmpty()) {
if (top && child.name == RECORD) continue
val dest = File(to, child.name)
val destPath = dest.toPath()
if (child.isDirectory && !Files.isSymbolicLink(child.toPath()) && dest.isDirectory && !Files.isSymbolicLink(destPath)) {
merge(child, dest, false)
continue
}
if (Files.isSymbolicLink(destPath) || dest.exists()) {
delete(dest)
}
Files.move(child.toPath(), destPath)
}
}
fun delete(file: File) {
if (!Files.isSymbolicLink(file.toPath()) && file.isDirectory) file.listFiles().orEmpty().forEach { delete(it) }
file.delete()
}
}
@@ -0,0 +1,187 @@
package com.droiddeck.launcher.stores.itch
import android.content.Context
import android.widget.Toast
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoresState
import org.json.JSONArray
import org.json.JSONObject
import java.util.concurrent.atomic.AtomicBoolean
internal class ItchUpdate(val uploadId: String, val updatedAt: String, val filename: String, val replaced: Boolean)
internal object ItchUpdates {
private const val KEY_AT = "updates_checked_at"
private const val KEY_FOUND = "updates_found"
private const val THROTTLE_MS = 6 * 60 * 60 * 1000L
private const val GAP_MS = 1_000L
val available = mutableStateMapOf<String, ItchUpdate>()
var checkingKey by mutableStateOf<String?>(null)
private set
private val running = AtomicBoolean(false)
private val restored = AtomicBoolean(false)
@Volatile private var generation = 0
internal fun evaluate(uploads: JSONArray?, uploadId: String, version: String): ItchUpdate? {
if (uploads == null || version.isBlank()) return null
val current = ItchUploads.byId(uploads, uploadId)
if (current != null) {
val stamp = ItchUploads.updatedAt(current)
return if (stamp > version) ItchUpdate(uploadId, stamp, ItchUploads.filename(current), false) else null
}
val next = ItchUploads.newestWindows(uploads) ?: return null
val stamp = ItchUploads.updatedAt(next)
if (uploadId.isBlank() && stamp <= version) return null
return ItchUpdate(next.optString("id"), stamp, ItchUploads.filename(next), uploadId.isNotBlank())
}
internal fun encode(found: Map<String, ItchUpdate>): String = JSONObject().also { out ->
for ((key, u) in found) out.put(key, JSONObject().put("uploadId", u.uploadId).put("updatedAt", u.updatedAt).put("filename", u.filename).put("replaced", u.replaced))
}.toString()
internal fun decode(raw: String?): Map<String, ItchUpdate> {
val json = runCatching { JSONObject(raw.orEmpty()) }.getOrNull() ?: return emptyMap()
val out = LinkedHashMap<String, ItchUpdate>()
for (key in json.keys()) {
val u = json.optJSONObject(key) ?: continue
val id = u.optString("uploadId")
if (id.isBlank()) continue
out[key] = ItchUpdate(id, u.optString("updatedAt"), u.optString("filename"), u.optBoolean("replaced"))
}
return out
}
private fun restore(app: Context) {
if (!restored.compareAndSet(false, true)) return
val started = generation
val saved = decode(ItchPrefs.get(app).getString(KEY_FOUND, null))
StoresState.post {
if (started != generation) return@post
for ((k, v) in saved) if (k !in available) available[k] = v
}
}
private fun save(app: Context) {
ItchPrefs.get(app).edit().putString(KEY_FOUND, encode(available.toMap())).apply()
}
fun check(context: Context) {
val app = context.applicationContext
if (!running.compareAndSet(false, true)) return
val started = generation
Thread({
try {
restore(app)
val prefs = ItchPrefs.get(app)
if (System.currentTimeMillis() - prefs.getLong(KEY_AT, 0L) < THROTTLE_MS) return@Thread
val key = ItchAuth.key(app)
if (key.isBlank()) return@Thread
val games = StoresState.installed.toList().filter { it.sidecar.store == Store.ITCH && it.sidecar.isInstalled }
val found = LinkedHashMap<String, ItchUpdate>()
val answered = HashSet<String>()
val snapshot = HashMap<String, Pair<String, String>>()
var failed = false
games.forEachIndexed { i, game ->
if (i > 0) Thread.sleep(GAP_MS)
val extra = game.sidecar.extra
snapshot[game.key] = game.sidecar.installVersion to extra["uploadId"].orEmpty()
val gameId = extra["gameId"].orEmpty()
if (gameId.isNotEmpty()) {
val uploads = ItchApi.uploads(key, gameId, extra["downloadKeyId"].orEmpty())
if (uploads == null) failed = true
else {
answered += game.key
evaluate(uploads, extra["uploadId"].orEmpty(), game.sidecar.installVersion)?.let { found[game.key] = it }
}
} else failed = true
}
if (started != generation) return@Thread
StoresState.post {
if (started != generation) return@post
for (k in answered) {
val now = StoresState.installed.firstOrNull { it.key == k } ?: continue
if (snapshot[k] != now.sidecar.installVersion to now.sidecar.extra["uploadId"].orEmpty()) continue
val u = found[k]
if (u != null) available[k] = u else available.remove(k)
}
save(app)
}
if (!failed && started == generation) prefs.edit().putLong(KEY_AT, System.currentTimeMillis()).apply()
StoresState.logLine("itch.io: checked ${games.size} installed games, ${found.size} with updates")
} finally {
running.set(false)
}
}, "itch-updates").start()
}
fun checkGame(context: Context, game: InstalledStoreGame) {
val app = context.applicationContext
if (checkingKey != null) return
checkingKey = game.key
val started = generation
val version = game.sidecar.installVersion
val uploadId = game.sidecar.extra["uploadId"].orEmpty()
Thread({
try {
val key = ItchAuth.key(app)
val extra = game.sidecar.extra
val gameId = extra["gameId"].orEmpty()
val uploads = if (key.isBlank() || gameId.isEmpty()) null else ItchApi.uploads(key, gameId, extra["downloadKeyId"].orEmpty())
val found = evaluate(uploads, uploadId, version)
StoresState.post {
if (started != generation) return@post
val now = StoresState.installed.firstOrNull { it.key == game.key }
if (uploads != null && now != null && now.sidecar.installVersion == version && now.sidecar.extra["uploadId"].orEmpty() == uploadId) {
if (found != null) available[game.key] = found else available.remove(game.key)
save(app)
}
val text = when {
uploads == null -> app.getString(R.string.stores_sync_failed)
found != null -> app.getString(R.string.stores_itch_updates_found, 1)
else -> app.getString(R.string.upd_current_status)
}
Toast.makeText(app, text, Toast.LENGTH_SHORT).show()
}
StoresState.logLine("itch.io: checked ${game.sidecar.title}, ${if (found != null) "update available" else "up to date"}")
} finally {
StoresState.post { checkingKey = null }
}
}, "itch-update-check").start()
}
fun start(context: Context, game: InstalledStoreGame, update: ItchUpdate) {
val app = context.applicationContext
if (StoresState.uninstalling.containsKey(game.key)) return
val root = game.folder.parentFile?.parentFile ?: return
val extra = game.sidecar.extra + ("uploadId" to update.uploadId)
val item = CatalogItem(
Store.ITCH, game.sidecar.id, game.sidecar.title, game.sidecar.hero, tallImageUrl = game.sidecar.cover,
isFree = extra["downloadKeyId"].isNullOrBlank(), owned = true, extra = extra,
)
StoresState.install(app, item, root)
}
fun applied(context: Context, key: String) {
val app = context.applicationContext
StoresState.post {
available.remove(key)
save(app)
}
}
fun clear(context: Context) {
val app = context.applicationContext
generation++
ItchPrefs.get(app).edit().remove(KEY_AT).remove(KEY_FOUND).apply()
StoresState.post { available.clear() }
}
}
@@ -18,6 +18,14 @@ internal object ItchUploads {
return candidates.maxWithOrNull(compareBy({ it.optString("updated_at", it.optString("updatedAt")) }, { it.optLong("id") }))
}
fun newestWindows(uploads: JSONArray?): JSONObject? {
if (uploads == null) return null
val windows = (0 until uploads.length()).mapNotNull { uploads.optJSONObject(it) }
.filter { it.optString("storage") != "external" && !it.optBoolean("demo") && windows(it) }
val games = windows.filter { it.optString("type") in GAME_TYPES }
return games.ifEmpty { windows }.maxWithOrNull(compareBy({ updatedAt(it) }, { it.optLong("id") }))
}
fun windows(upload: JSONObject): Boolean {
val platforms = upload.optJSONObject("platforms")
if (platforms != null) {
@@ -52,6 +60,8 @@ internal object ItchUploads {
return (0 until uploads.length()).mapNotNull { uploads.optJSONObject(it) }.firstOrNull { it.optString("id") == id }
}
fun updatedAt(upload: JSONObject): String = upload.optString("updated_at", upload.optString("updatedAt"))
fun size(upload: JSONObject): Long = upload.optLong("size", upload.optLong("size_bytes"))
fun filename(upload: JSONObject): String = upload.optString("filename").substringAfterLast('/')
@@ -205,7 +205,12 @@ internal fun GameDetail(
GameHero(
title, item, installed, game,
Modifier.fillMaxWidth().heightIn(min = if (narrow) 170.dp else 210.dp).onGloballyPositioned { StoresMotion.heroAt = it.boundsInRoot() },
corner = { if (!s.shortcutPicker) RemoveButton(title, game, installed, a) },
corner = {
if (!s.shortcutPicker) Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
if (installed != null && installed.sidecar.store == Store.ITCH) ItchCheckButton(installed)
RemoveButton(title, game, installed, a)
}
},
scores = scores.takeIf { !stacked },
) {
HeroEyebrow(source, game, item, installed, download?.location ?: failed?.location)
@@ -357,6 +362,7 @@ internal fun GameActions(
GameShortcutMenu(game, a)
EditArtButton(game)
}
if (store == Store.ITCH && installed != null) ItchUpdateButton(installed, download == null && StoresState.uninstalling[installed.key] == null)
if (store == Store.XBOX && id != null) XboxInstalledStream(id, game?.name ?: item?.title.orEmpty(), item)
if (store == Store.XBOX && installed != null && id != null) {
SecondaryButton(stringResource(R.string.stores_xbox_update), enabled = download == null && !XboxRuntime.isActive(id)) {
@@ -529,7 +535,7 @@ private fun EditArtButton(g: Library.SteamGame) {
}
@Composable
private fun IconAction(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String, id: String, danger: Boolean = false, enabled: Boolean = true, onClick: () -> Unit) {
internal fun IconAction(icon: androidx.compose.ui.graphics.vector.ImageVector, label: String, id: String, danger: Boolean = false, enabled: Boolean = true, onClick: () -> Unit) {
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val src = remember { MutableInteractionSource() }
@@ -0,0 +1,61 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.itch.ItchUpdate
import com.droiddeck.launcher.stores.itch.ItchUpdates
@Composable
internal fun ItchCheckButton(installed: InstalledStoreGame) {
val ctx = LocalContext.current
IconAction(Icons.Filled.Refresh, stringResource(R.string.store_check_updates), "game:check-updates", enabled = ItchUpdates.checkingKey == null) {
ItchUpdates.checkGame(ctx, installed)
}
}
@Composable
internal fun ItchUpdateButton(installed: InstalledStoreGame, enabled: Boolean) {
val ctx = LocalContext.current
val update = ItchUpdates.available[installed.key] ?: return
var asking by remember { mutableStateOf(false) }
SecondaryButton(stringResource(R.string.common_update), enabled = enabled) {
if (update.replaced) asking = true else ItchUpdates.start(ctx, installed, update)
}
if (asking) ReplacedDialog(installed, update) { asking = false }
}
@Composable
private fun ReplacedDialog(installed: InstalledStoreGame, update: ItchUpdate, onDismiss: () -> Unit) {
val ctx = LocalContext.current
val shown = rememberShown(onDismiss)
val close = { shown.targetState = false }
AppDialog(shown, close, "itchUpdate", wide = false, maxWidth = 460.dp) {
DialogTitleRow(installed.sidecar.title, close)
Text(
stringResource(R.string.stores_itch_update_replaced, update.filename.ifBlank { update.uploadId }),
fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
)
Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
PrimaryButton(stringResource(R.string.common_update)) {
close()
ItchUpdates.start(ctx, installed, update)
}
SecondaryButton(stringResource(R.string.common_cancel)) { close() }
}
}
}
@@ -91,6 +91,7 @@ import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.formatBytes
import com.droiddeck.launcher.stores.itch.ItchCollection
import com.droiddeck.launcher.stores.itch.ItchCollections
import com.droiddeck.launcher.stores.itch.ItchUpdates
import com.droiddeck.launcher.stores.retainOrder
import com.droiddeck.launcher.stores.xbox.XboxLibraryFilter
import com.droiddeck.launcher.stores.sortGames
@@ -194,7 +195,10 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String,
val source = LibraryView.source.takeIf { it == LIBRARY_ALL || it in sources } ?: LIBRARY_ALL
val q = LibraryView.query.trim().lowercase()
val xboxFilter = if (source == Store.XBOX.id) XboxLibraryFilter.current else XboxLibraryFilter.ALL
LaunchedEffect(source, itchSignedIn) { if (source == Store.ITCH.id && itchSignedIn) ItchCollections.load(ctx) }
LaunchedEffect(source, itchSignedIn) { if (source == Store.ITCH.id && itchSignedIn) {
ItchCollections.load(ctx)
ItchUpdates.check(ctx)
} }
val collection = if (source == Store.ITCH.id) ItchCollections.chosen() else null
val pool = if (collection == null) all else collectionEntries(all, ItchCollections.gamesOf(collection.id).orEmpty())
val matching = pool.filter {
@@ -582,6 +586,7 @@ internal fun LibraryMarker(e: LibraryEntry, download: DownloadEntry?) {
download != null -> Text("${download.percent}%", fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
e.item != null && StoresState.isUnfinished(e.item) -> Text(stringResource(R.string.stores_resume), fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
else -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) {
if (e.installed && e.storeKey?.let { it in ItchUpdates.available } == true) Text(stringResource(R.string.common_update), fontSize = 10.sp, fontWeight = FontWeight.Bold, color = pal.signal, maxLines = 1)
if (size != null && size > 0) Text(formatBytes(size), fontSize = 11.sp, fontWeight = FontWeight.Bold, color = Color.White, maxLines = 1)
if (!e.installed) Icon(Icons.Outlined.Download, stringResource(R.string.stores_section_not_installed), tint = Color.White, modifier = Modifier.size(12.dp))
}
+2
View File
@@ -3219,6 +3219,8 @@
<string name="library_in">في المكتبة</string>
<string name="xbox_filter_show">عرض</string>
<string name="itch_collections">المجموعات</string>
<string name="stores_itch_updates_found">التحديثات المتاحة: %1$d</string>
<string name="stores_itch_update_replaced">استبدل المطوّر هذا الإصدار بـ %1$s. هل تريد التحديث إليه؟</string>
<string name="xbox_filter_cloud">سحابية</string>
<string name="stores_xbox_cloud_settings">إعدادات السحابة</string>
<string name="apps_search_hint">البحث في التطبيقات</string>
@@ -3069,6 +3069,8 @@
<string name="library_in">En Biblioteca</string>
<string name="xbox_filter_show">Mostrar</string>
<string name="itch_collections">Colecciones</string>
<string name="stores_itch_updates_found">Actualizaciones disponibles: %1$d</string>
<string name="stores_itch_update_replaced">El desarrollador reemplazó esta versión por %1$s. ¿Actualizar a ella?</string>
<string name="xbox_filter_cloud">Nube</string>
<string name="stores_xbox_cloud_settings">Configuración de nube</string>
<string name="apps_search_hint">Buscar apps</string>
+2
View File
@@ -3083,6 +3083,8 @@
<string name="library_in">В Библиотека</string>
<string name="xbox_filter_show">Показване</string>
<string name="itch_collections">Колекции</string>
<string name="stores_itch_updates_found">Налични актуализации: %1$d</string>
<string name="stores_itch_update_replaced">Разработчикът замени тази версия с %1$s. Да се актуализира ли до нея?</string>
<string name="xbox_filter_cloud">Облак</string>
<string name="stores_xbox_cloud_settings">Настройки на облака</string>
<string name="apps_search_hint">Търсене на приложения</string>
+2
View File
@@ -3151,6 +3151,8 @@
<string name="library_in">V knihovně</string>
<string name="xbox_filter_show">Zobrazit</string>
<string name="itch_collections">Kolekce</string>
<string name="stores_itch_updates_found">Dostupné aktualizace: %1$d</string>
<string name="stores_itch_update_replaced">Vývojář nahradil tuto verzi souborem %1$s. Aktualizovat na ni?</string>
<string name="xbox_filter_cloud">Cloud</string>
<string name="stores_xbox_cloud_settings">Nastavení cloudu</string>
<string name="apps_search_hint">Hledat aplikace</string>
+2
View File
@@ -3083,6 +3083,8 @@
<string name="library_in">I Bibliotek</string>
<string name="xbox_filter_show">Vis</string>
<string name="itch_collections">Samlinger</string>
<string name="stores_itch_updates_found">Opdateringer tilgængelige: %1$d</string>
<string name="stores_itch_update_replaced">Udvikleren har erstattet denne version med %1$s. Opdater til den?</string>
<string name="xbox_filter_cloud">Sky</string>
<string name="stores_xbox_cloud_settings">Skyindstillinger</string>
<string name="apps_search_hint">Søg i apps</string>
+2
View File
@@ -3083,6 +3083,8 @@
<string name="library_in">In der Bibliothek</string>
<string name="xbox_filter_show">Anzeigen</string>
<string name="itch_collections">Sammlungen</string>
<string name="stores_itch_updates_found">Verfügbare Updates: %1$d</string>
<string name="stores_itch_update_replaced">Der Entwickler hat diesen Build durch %1$s ersetzt. Darauf aktualisieren?</string>
<string name="xbox_filter_cloud">Cloud</string>
<string name="stores_xbox_cloud_settings">Cloud-Einstellungen</string>
<string name="apps_search_hint">Apps durchsuchen</string>
+2
View File
@@ -3083,6 +3083,8 @@
<string name="library_in">Στη Βιβλιοθήκη</string>
<string name="xbox_filter_show">Εμφάνιση</string>
<string name="itch_collections">Συλλογές</string>
<string name="stores_itch_updates_found">Διαθέσιμες ενημερώσεις: %1$d</string>
<string name="stores_itch_update_replaced">Ο προγραμματιστής αντικατέστησε αυτήν την έκδοση με %1$s. Να γίνει ενημέρωση σε αυτήν;</string>
<string name="xbox_filter_cloud">Cloud</string>
<string name="stores_xbox_cloud_settings">Ρυθμίσεις cloud</string>
<string name="apps_search_hint">Αναζήτηση εφαρμογών</string>
+2
View File
@@ -3119,6 +3119,8 @@
<string name="library_in">En la Biblioteca</string>
<string name="xbox_filter_show">Mostrar</string>
<string name="itch_collections">Colecciones</string>
<string name="stores_itch_updates_found">Actualizaciones disponibles: %1$d</string>
<string name="stores_itch_update_replaced">El desarrollador reemplazó esta versión por %1$s. ¿Actualizar a ella?</string>
<string name="xbox_filter_cloud">Nube</string>
<string name="stores_xbox_cloud_settings">Ajustes de nube</string>
<string name="apps_search_hint">Buscar aplicaciones</string>
+2
View File
@@ -3083,6 +3083,8 @@
<string name="library_in">Kirjastossa</string>
<string name="xbox_filter_show">Näytä</string>
<string name="itch_collections">Kokoelmat</string>
<string name="stores_itch_updates_found">Päivityksiä saatavilla: %1$d</string>
<string name="stores_itch_update_replaced">Kehittäjä korvasi tämän version tiedostolla %1$s. Päivitetäänkö siihen?</string>
<string name="xbox_filter_cloud">Pilvi</string>
<string name="stores_xbox_cloud_settings">Pilviasetukset</string>
<string name="apps_search_hint">Hae sovelluksia</string>
+2
View File
@@ -3119,6 +3119,8 @@
<string name="library_in">Dans la Bibliothèque</string>
<string name="xbox_filter_show">Afficher</string>
<string name="itch_collections">Collections</string>
<string name="stores_itch_updates_found">Mises à jour disponibles : %1$d</string>
<string name="stores_itch_update_replaced">Le développeur a remplacé cette version par %1$s. Mettre à jour vers celle-ci ?</string>
<string name="xbox_filter_cloud">Cloud</string>
<string name="stores_xbox_cloud_settings">Paramètres cloud</string>
<string name="apps_search_hint">Rechercher des applications</string>
+2
View File
@@ -3083,6 +3083,8 @@
<string name="library_in">लाइब्रेरी में</string>
<string name="xbox_filter_show">दिखाएँ</string>
<string name="itch_collections">संग्रह</string>
<string name="stores_itch_updates_found">उपलब्ध अपडेट: %1$d</string>
<string name="stores_itch_update_replaced">डेवलपर ने इस बिल्ड को %1$s से बदल दिया है। क्या उस पर अपडेट करें?</string>
<string name="xbox_filter_cloud">क्लाउड</string>
<string name="stores_xbox_cloud_settings">क्लाउड सेटिंग्स</string>
<string name="apps_search_hint">ऐप खोजें</string>
+2
View File
@@ -3083,6 +3083,8 @@
<string name="library_in">A könyvtárban</string>
<string name="xbox_filter_show">Megjelenítés</string>
<string name="itch_collections">Gyűjtemények</string>
<string name="stores_itch_updates_found">Elérhető frissítések: %1$d</string>
<string name="stores_itch_update_replaced">A fejlesztő lecserélte ezt a buildet erre: %1$s. Frissít rá?</string>
<string name="xbox_filter_cloud">Felhő</string>
<string name="stores_xbox_cloud_settings">Felhőbeállítások</string>
<string name="apps_search_hint">Alkalmazások keresése</string>
+2
View File
@@ -3073,6 +3073,8 @@
<string name="library_in">Di Pustaka</string>
<string name="xbox_filter_show">Tampilkan</string>
<string name="itch_collections">Koleksi</string>
<string name="stores_itch_updates_found">Pembaruan tersedia: %1$d</string>
<string name="stores_itch_update_replaced">Pengembang mengganti build ini dengan %1$s. Perbarui ke build itu?</string>
<string name="xbox_filter_cloud">Cloud</string>
<string name="stores_xbox_cloud_settings">Pengaturan cloud</string>
<string name="apps_search_hint">Cari aplikasi</string>
+2
View File
@@ -3117,6 +3117,8 @@
<string name="library_in">Nella Libreria</string>
<string name="xbox_filter_show">Mostra</string>
<string name="itch_collections">Raccolte</string>
<string name="stores_itch_updates_found">Aggiornamenti disponibili: %1$d</string>
<string name="stores_itch_update_replaced">Lo sviluppatore ha sostituito questa build con %1$s. Aggiornare a quella?</string>
<string name="xbox_filter_cloud">Cloud</string>
<string name="stores_xbox_cloud_settings">Impostazioni cloud</string>
<string name="apps_search_hint">Cerca app</string>
+2
View File
@@ -3060,6 +3060,8 @@
<string name="library_in">ライブラリにあります</string>
<string name="xbox_filter_show">表示</string>
<string name="itch_collections">コレクション</string>
<string name="stores_itch_updates_found">利用可能なアップデート: %1$d</string>
<string name="stores_itch_update_replaced">開発者がこのビルドを %1$s に置き換えました。更新しますか?</string>
<string name="xbox_filter_cloud">クラウド</string>
<string name="stores_xbox_cloud_settings">クラウド設定</string>
<string name="apps_search_hint">アプリを検索</string>
+2
View File
@@ -3060,6 +3060,8 @@
<string name="library_in">라이브러리에 있음</string>
<string name="xbox_filter_show">표시</string>
<string name="itch_collections">컬렉션</string>
<string name="stores_itch_updates_found">사용 가능한 업데이트: %1$d</string>
<string name="stores_itch_update_replaced">개발자가 이 빌드를 %1$s(으)로 교체했습니다. 업데이트할까요?</string>
<string name="xbox_filter_cloud">클라우드</string>
<string name="stores_xbox_cloud_settings">클라우드 설정</string>
<string name="apps_search_hint">앱 검색</string>
+2
View File
@@ -3058,6 +3058,8 @@
<string name="library_in">Dalam Pustaka</string>
<string name="xbox_filter_show">Tunjukkan</string>
<string name="itch_collections">Koleksi</string>
<string name="stores_itch_updates_found">Kemas kini tersedia: %1$d</string>
<string name="stores_itch_update_replaced">Pembangun telah menggantikan binaan ini dengan %1$s. Kemas kini kepadanya?</string>
<string name="xbox_filter_cloud">Awan</string>
<string name="stores_xbox_cloud_settings">Tetapan awan</string>
<string name="apps_search_hint">Cari apl</string>
+2
View File
@@ -3083,6 +3083,8 @@
<string name="library_in">I Bibliotek</string>
<string name="xbox_filter_show">Vis</string>
<string name="itch_collections">Samlinger</string>
<string name="stores_itch_updates_found">Oppdateringer tilgjengelig: %1$d</string>
<string name="stores_itch_update_replaced">Utvikleren har erstattet denne versjonen med %1$s. Oppdatere til den?</string>
<string name="xbox_filter_cloud">Sky</string>
<string name="stores_xbox_cloud_settings">Skyinnstillinger</string>
<string name="apps_search_hint">Søk i apper</string>
+2
View File
@@ -3083,6 +3083,8 @@
<string name="library_in">In Bibliotheek</string>
<string name="xbox_filter_show">Weergeven</string>
<string name="itch_collections">Collecties</string>
<string name="stores_itch_updates_found">Beschikbare updates: %1$d</string>
<string name="stores_itch_update_replaced">De ontwikkelaar heeft deze build vervangen door %1$s. Bijwerken naar die build?</string>
<string name="xbox_filter_cloud">Cloud</string>
<string name="stores_xbox_cloud_settings">Cloudinstellingen</string>
<string name="apps_search_hint">Apps zoeken</string>
+2
View File
@@ -3154,6 +3154,8 @@
<string name="library_in">W bibliotece</string>
<string name="xbox_filter_show">Pokaż</string>
<string name="itch_collections">Kolekcje</string>
<string name="stores_itch_updates_found">Dostępne aktualizacje: %1$d</string>
<string name="stores_itch_update_replaced">Deweloper zastąpił tę wersję plikiem %1$s. Zaktualizować do niej?</string>
<string name="xbox_filter_cloud">Chmura</string>
<string name="stores_xbox_cloud_settings">Ustawienia chmury</string>
<string name="apps_search_hint">Szukaj aplikacji</string>
@@ -3117,6 +3117,8 @@
<string name="library_in">Na Biblioteca</string>
<string name="xbox_filter_show">Mostrar</string>
<string name="itch_collections">Coleções</string>
<string name="stores_itch_updates_found">Atualizações disponíveis: %1$d</string>
<string name="stores_itch_update_replaced">O programador substituiu esta versão por %1$s. Atualizar para ela?</string>
<string name="xbox_filter_cloud">Nuvem</string>
<string name="stores_xbox_cloud_settings">Definições da nuvem</string>
<string name="apps_search_hint">Pesquisar aplicações</string>
+2
View File
@@ -3117,6 +3117,8 @@
<string name="library_in">Na Biblioteca</string>
<string name="xbox_filter_show">Mostrar</string>
<string name="itch_collections">Coleções</string>
<string name="stores_itch_updates_found">Atualizações disponíveis: %1$d</string>
<string name="stores_itch_update_replaced">O desenvolvedor substituiu esta versão por %1$s. Atualizar para ela?</string>
<string name="xbox_filter_cloud">Nuvem</string>
<string name="stores_xbox_cloud_settings">Configurações da nuvem</string>
<string name="apps_search_hint">Pesquisar apps</string>
+2
View File
@@ -3117,6 +3117,8 @@
<string name="library_in">În Bibliotecă</string>
<string name="xbox_filter_show">Afișează</string>
<string name="itch_collections">Colecții</string>
<string name="stores_itch_updates_found">Actualizări disponibile: %1$d</string>
<string name="stores_itch_update_replaced">Dezvoltatorul a înlocuit această versiune cu %1$s. Actualizezi la ea?</string>
<string name="xbox_filter_cloud">Cloud</string>
<string name="stores_xbox_cloud_settings">Setări cloud</string>
<string name="apps_search_hint">Caută aplicații</string>
+2
View File
@@ -3153,6 +3153,8 @@
<string name="library_in">В библиотеке</string>
<string name="xbox_filter_show">Показать</string>
<string name="itch_collections">Коллекции</string>
<string name="stores_itch_updates_found">Доступные обновления: %1$d</string>
<string name="stores_itch_update_replaced">Разработчик заменил эту сборку на %1$s. Обновиться до неё?</string>
<string name="xbox_filter_cloud">Облако</string>
<string name="stores_xbox_cloud_settings">Настройки облака</string>
<string name="apps_search_hint">Поиск приложений</string>
+2
View File
@@ -3083,6 +3083,8 @@
<string name="library_in">I Bibliotek</string>
<string name="xbox_filter_show">Visa</string>
<string name="itch_collections">Samlingar</string>
<string name="stores_itch_updates_found">Uppdateringar tillgängliga: %1$d</string>
<string name="stores_itch_update_replaced">Utvecklaren har ersatt den här versionen med %1$s. Uppdatera till den?</string>
<string name="xbox_filter_cloud">Moln</string>
<string name="stores_xbox_cloud_settings">Molninställningar</string>
<string name="apps_search_hint">Sök appar</string>
+2
View File
@@ -3058,6 +3058,8 @@
<string name="library_in">อยู่ในไลบรารี</string>
<string name="xbox_filter_show">แสดง</string>
<string name="itch_collections">คอลเลกชัน</string>
<string name="stores_itch_updates_found">มีอัปเดตพร้อมใช้งาน: %1$d</string>
<string name="stores_itch_update_replaced">ผู้พัฒนาได้แทนที่บิลด์นี้ด้วย %1$s ต้องการอัปเดตเป็นบิลด์นั้นไหม</string>
<string name="xbox_filter_cloud">คลาวด์</string>
<string name="stores_xbox_cloud_settings">การตั้งค่าคลาวด์</string>
<string name="apps_search_hint">ค้นหาแอป</string>
+2
View File
@@ -3085,6 +3085,8 @@
<string name="library_in">Kütüphane içinde</string>
<string name="xbox_filter_show">Göster</string>
<string name="itch_collections">Koleksiyonlar</string>
<string name="stores_itch_updates_found">Mevcut güncellemeler: %1$d</string>
<string name="stores_itch_update_replaced">Geliştirici bu sürümü %1$s ile değiştirdi. Ona güncellensin mi?</string>
<string name="xbox_filter_cloud">Bulut</string>
<string name="stores_xbox_cloud_settings">Bulut ayarları</string>
<string name="apps_search_hint">Uygulama ara</string>
+2
View File
@@ -3151,6 +3151,8 @@
<string name="library_in">У бібліотеці</string>
<string name="xbox_filter_show">Показати</string>
<string name="itch_collections">Колекції</string>
<string name="stores_itch_updates_found">Доступні оновлення: %1$d</string>
<string name="stores_itch_update_replaced">Розробник замінив цю збірку на %1$s. Оновити до неї?</string>
<string name="xbox_filter_cloud">Хмара</string>
<string name="stores_xbox_cloud_settings">Налаштування хмари</string>
<string name="apps_search_hint">Пошук застосунків</string>
+2
View File
@@ -3058,6 +3058,8 @@
<string name="library_in">Trong Thư viện</string>
<string name="xbox_filter_show">Hiển thị</string>
<string name="itch_collections">Bộ sưu tập</string>
<string name="stores_itch_updates_found">Có bản cập nhật: %1$d</string>
<string name="stores_itch_update_replaced">Nhà phát triển đã thay bản dựng này bằng %1$s. Cập nhật lên bản đó?</string>
<string name="xbox_filter_cloud">Đám mây</string>
<string name="stores_xbox_cloud_settings">Cài đặt đám mây</string>
<string name="apps_search_hint">Tìm ứng dụng</string>
@@ -3066,6 +3066,8 @@
<string name="library_in">已在游戏库</string>
<string name="xbox_filter_show">显示</string>
<string name="itch_collections">收藏集</string>
<string name="stores_itch_updates_found">可用更新:%1$d</string>
<string name="stores_itch_update_replaced">开发者已将此版本替换为 %1$s。要更新到该版本吗?</string>
<string name="xbox_filter_cloud">云</string>
<string name="stores_xbox_cloud_settings">云设置</string>
<string name="apps_search_hint">搜索应用</string>
@@ -3065,6 +3065,8 @@
<string name="library_in">已在收藏庫</string>
<string name="xbox_filter_show">顯示</string>
<string name="itch_collections">收藏集</string>
<string name="stores_itch_updates_found">可用更新:%1$d</string>
<string name="stores_itch_update_replaced">開發者已將此版本替換為 %1$s。要更新到該版本嗎?</string>
<string name="xbox_filter_cloud">雲端</string>
<string name="stores_xbox_cloud_settings">雲端設定</string>
<string name="apps_search_hint">搜尋應用程式</string>
@@ -3065,6 +3065,8 @@
<string name="library_in">已在收藏庫</string>
<string name="xbox_filter_show">顯示</string>
<string name="itch_collections">收藏集</string>
<string name="stores_itch_updates_found">可用更新:%1$d</string>
<string name="stores_itch_update_replaced">開發者已將此版本替換為 %1$s。要更新到該版本嗎?</string>
<string name="xbox_filter_cloud">雲端</string>
<string name="stores_xbox_cloud_settings">雲端設定</string>
<string name="apps_search_hint">搜尋應用程式</string>
+2
View File
@@ -3291,6 +3291,8 @@
<string name="library_in">In Library</string>
<string name="xbox_filter_show">Show</string>
<string name="itch_collections">Collections</string>
<string name="stores_itch_updates_found">Updates available: %1$d</string>
<string name="stores_itch_update_replaced">The developer replaced this build with %1$s. Update to it?</string>
<string name="xbox_filter_cloud">Cloud</string>
<string name="stores_xbox_cloud_settings">Cloud settings</string>
<string name="xbox_cloud_gaming" translatable="false">Xbox Cloud Gaming</string>
@@ -0,0 +1,85 @@
package com.droiddeck.launcher.stores.itch
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 java.io.File
class ItchStagingTest {
@get:Rule val tmp = TemporaryFolder()
private fun file(root: File, path: String, text: String) = File(root, path).also { it.parentFile?.mkdirs(); it.writeText(text) }
@Test fun newFilesReplaceOldOnesAndEverythingElseStays() {
val game = tmp.newFolder("game")
val staged = tmp.newFolder("staged")
file(game, "game.exe", "old")
file(game, "data/level.dat", "old")
file(game, "saves/slot1.sav", "mine")
file(game, ".droiddeck-store.json", "record")
file(staged, "game.exe", "new")
file(staged, "data/level.dat", "new")
file(staged, "data/extra.dat", "new")
file(staged, "saves/default.sav", "new")
ItchStaging.merge(staged, game)
assertEquals("new", File(game, "game.exe").readText())
assertEquals("new", File(game, "data/level.dat").readText())
assertEquals("new", File(game, "data/extra.dat").readText())
assertEquals("mine", File(game, "saves/slot1.sav").readText())
assertEquals("new", File(game, "saves/default.sav").readText())
assertEquals("record", File(game, ".droiddeck-store.json").readText())
assertTrue(staged.listFiles().orEmpty().all { it.isDirectory && it.listFiles().orEmpty().isEmpty() })
}
@Test fun aFileReplacingADirectoryAndTheOtherWayRound() {
val game = tmp.newFolder("game")
val staged = tmp.newFolder("staged")
file(game, "a/inner.txt", "old")
file(game, "b", "old")
file(staged, "a", "new")
file(staged, "b/inner.txt", "new")
ItchStaging.merge(staged, game)
assertTrue(File(game, "a").isFile)
assertEquals("new", File(game, "a").readText())
assertEquals("new", File(game, "b/inner.txt").readText())
assertFalse(File(game, "a/inner.txt").exists())
}
@Test fun deletingFollowsNoLinkOutOfTheTree() {
val outside = tmp.newFolder("outside")
file(outside, "keep.txt", "keep")
val staged = tmp.newFolder("staged")
file(staged, "own.txt", "x")
java.nio.file.Files.createSymbolicLink(File(staged, "link").toPath(), outside.toPath())
ItchStaging.delete(staged)
assertFalse(staged.exists())
assertEquals("keep", File(outside, "keep.txt").readText())
}
@Test fun aLinkInTheGameIsReplacedNotFollowed() {
val outside = tmp.newFolder("outside")
file(outside, "keep.txt", "keep")
val game = tmp.newFolder("game")
java.nio.file.Files.createSymbolicLink(File(game, "data").toPath(), outside.toPath())
val staged = tmp.newFolder("staged")
file(staged, "data/level.dat", "new")
ItchStaging.merge(staged, game)
assertEquals("keep", File(outside, "keep.txt").readText())
assertFalse(File(outside, "level.dat").exists())
assertEquals("new", File(game, "data/level.dat").readText())
}
@Test fun theInstallRecordIsNeverReplacedByTheArchive() {
val game = tmp.newFolder("game")
val staged = tmp.newFolder("staged")
file(game, ".droiddeck-store.json", "record")
file(staged, ".droiddeck-store.json", "forged")
file(staged, "sub/.droiddeck-store.json", "nested")
ItchStaging.merge(staged, game)
assertEquals("record", File(game, ".droiddeck-store.json").readText())
assertEquals("nested", File(game, "sub/.droiddeck-store.json").readText())
}
}
@@ -0,0 +1,84 @@
package com.droiddeck.launcher.stores.itch
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
@org.junit.runner.RunWith(org.robolectric.RobolectricTestRunner::class)
@org.robolectric.annotation.Config(sdk = [33], application = android.app.Application::class)
class ItchUpdatesTest {
private fun upload(id: String, updated: String, filename: String = "game-$id.zip", windows: Boolean = true, type: String = "default") =
JSONObject().put("id", id).put("filename", filename).put("updated_at", updated).put("type", type).put("storage", "hosted")
.put("platforms", JSONObject().put("windows", windows).put("linux", !windows))
private fun list(vararg uploads: JSONObject) = JSONArray().also { a -> uploads.forEach { a.put(it) } }
@Test fun aNewerStampOnTheSameUploadIsAnUpdate() {
val update = ItchUpdates.evaluate(list(upload("7", "2026-10-20T10:00:00Z")), "7", "2026-09-01T10:00:00Z")!!
assertEquals("7", update.uploadId)
assertEquals("2026-10-20T10:00:00Z", update.updatedAt)
assertFalse(update.replaced)
}
@Test fun theSameStampIsNotAnUpdate() {
assertNull(ItchUpdates.evaluate(list(upload("7", "2026-09-01T10:00:00Z")), "7", "2026-09-01T10:00:00Z"))
}
@Test fun anOlderStampIsNotAnUpdate() {
assertNull(ItchUpdates.evaluate(list(upload("7", "2026-08-01T10:00:00Z")), "7", "2026-09-01T10:00:00Z"))
}
@Test fun aMissingUploadFallsBackToTheNewestWindowsOneAndAsksFirst() {
val update = ItchUpdates.evaluate(
list(upload("8", "2026-10-01T10:00:00Z"), upload("9", "2026-10-05T10:00:00Z"), upload("10", "2026-10-09T10:00:00Z", windows = false)),
"7", "2026-09-01T10:00:00Z",
)!!
assertEquals("9", update.uploadId)
assertTrue(update.replaced)
}
@Test fun aReplacedUploadWithNoWindowsBuildLeftIsNotOffered() {
val linux = list(upload("8", "2026-10-01T10:00:00Z", windows = false))
assertNull(ItchUpdates.evaluate(linux, "7", "2026-09-01T10:00:00Z"))
assertNull(ItchUpdates.evaluate(linux, "", "2026-09-01T10:00:00Z"))
}
@Test fun aWindowsBuildOfAnotherTypeBeatsALinuxDefaultOne() {
val update = ItchUpdates.evaluate(
list(upload("8", "2026-10-09T10:00:00Z", windows = false), upload("9", "2026-10-01T10:00:00Z", type = "other")),
"7", "2026-09-01T10:00:00Z",
)!!
assertEquals("9", update.uploadId)
assertTrue(update.replaced)
}
@Test fun anUnknownInstalledVersionNeverReportsAnUpdate() {
assertNull(ItchUpdates.evaluate(list(upload("7", "2026-10-20T10:00:00Z")), "7", ""))
}
@Test fun noAnswerOrNoWindowsBuildMeansNoUpdate() {
assertNull(ItchUpdates.evaluate(null, "7", "2026-09-01T10:00:00Z"))
assertNull(ItchUpdates.evaluate(JSONArray(), "7", "2026-09-01T10:00:00Z"))
}
@Test fun anInstallWithoutAnUploadIdComparesTheNewestWindowsBuild() {
val update = ItchUpdates.evaluate(list(upload("8", "2026-10-01T10:00:00Z")), "", "2026-09-01T10:00:00Z")!!
assertEquals("8", update.uploadId)
assertFalse(update.replaced)
assertNull(ItchUpdates.evaluate(list(upload("8", "2026-08-01T10:00:00Z")), "", "2026-09-01T10:00:00Z"))
}
@Test fun foundUpdatesSurviveTheCache() {
val found = mapOf("itch:a/b" to ItchUpdate("9", "2026-10-05T10:00:00Z", "b.zip", true))
val back = ItchUpdates.decode(ItchUpdates.encode(found))
assertEquals(setOf("itch:a/b"), back.keys)
assertEquals("9", back.getValue("itch:a/b").uploadId)
assertTrue(back.getValue("itch:a/b").replaced)
assertEquals(emptyMap<String, ItchUpdate>(), ItchUpdates.decode(null))
assertEquals(emptyMap<String, ItchUpdate>(), ItchUpdates.decode("not json"))
}
}