diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreCatalog.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreCatalog.kt index 80e091dab2..debaf4ad04 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreCatalog.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreCatalog.kt @@ -108,6 +108,19 @@ fun mergeItems(old: List?, new: List): List?, patched: List): List { + if (old.isNullOrEmpty()) return patched + val byKey = patched.associateBy { it.key } + val kept = old.map { byKey[it.key] ?: it } + val added = patched.filter { n -> old.none { it.key == n.key } } + return if (added.isEmpty()) kept else (kept + added).sortedBy { it.title.lowercase() } +} + class InstalledStoreGame(val sidecar: StoreGameSidecar, val folder: java.io.File) { val key: String get() = "${sidecar.store.id}:${sidecar.id}" } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreNet.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreNet.kt index 8517a1aa0f..f3a4e495f8 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreNet.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreNet.kt @@ -25,7 +25,7 @@ internal object StoreNet { headers.forEach { (k, v) -> setRequestProperty(k, v) } } val code = conn.responseCode - if (code !in 200..299) { Log.w(TAG, "GET $code ${StoreLog.redactUrl(url)}"); null } else readAll(conn) + if (code !in 200..299) { StoresState.logLine("GET $code ${StoreLog.redactUrl(url)}"); null } else readAll(conn) } catch (e: Exception) { Log.w(TAG, "GET failed ${StoreLog.redactUrl(url)}: ${e.javaClass.simpleName}") null diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogBackend.kt index 1003921c04..cf162cc6f2 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogBackend.kt @@ -37,7 +37,16 @@ object GogBackend : StoreBackend { if (cached.isNotEmpty()) StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], cached) if (!quiet) StoresState.status[store] = app.getString(com.droiddeck.launcher.R.string.stores_sync_library) } - val result = GogLibrary.sync(app, force) { line -> if (!quiet) StoresState.post { StoresState.status[store] = line } } + val result = GogLibrary.sync(app, force, onStatus = { line -> if (!quiet) StoresState.post { StoresState.status[store] = line } }, onList = { list -> + // Mapped here, off the main thread: the listing paints the tab before any product is asked about. + val items = list.map { GogLibrary.toCatalogItem(app, it) } + // An empty listing is not news: posting it would drop the cards already on screen. + if (items.isNotEmpty()) StoresState.post { StoresState.library[store] = com.droiddeck.launcher.stores.mergeItems(StoresState.library[store], items) } + }, onItems = { changed -> + // Only the products that came back are touched: a card already on screen keeps its object, and a product the grid has not seen yet is added where its title belongs. + val items = changed.map { GogLibrary.toCatalogItem(app, it) } + StoresState.post { StoresState.library[store] = com.droiddeck.launcher.stores.patchItems(StoresState.library[store], items) } + }) StoresState.post { StoresState.status.remove(store) when (result) { diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogLibrary.kt b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogLibrary.kt index 61fae1a40f..0e76d2fab2 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogLibrary.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogLibrary.kt @@ -7,6 +7,7 @@ import com.droiddeck.launcher.R import com.droiddeck.launcher.stores.CatalogItem import com.droiddeck.launcher.stores.Store import com.droiddeck.launcher.stores.StoreNet +import com.droiddeck.launcher.stores.StoresState import com.droiddeck.launcher.stores.cleanStoreText import org.json.JSONArray import org.json.JSONObject @@ -20,6 +21,14 @@ object GogLibrary { private const val LAST_SYNC_KEY = "library_synced_at" private const val SKIPPED_KEY = "library_skipped" private const val THROTTLE_MS = 6L * 60L * 60L * 1000L + // mediaType=1 leaves the movies and soundtracks out, hiddenFlag=0 the hidden ones. + private const val LIST_URL = "https://embed.gog.com/account/getFilteredProducts?mediaType=1&hiddenFlag=0&sortBy=title" + private const val LIST_MAX_PAGES = 100 + // The listing's image is a bare hash, and the CDN serves it only through Galaxy's own formatters: the + // vertical cover is the one card art it carries. The wide background only the per-game fetch knows. + private const val COVER_SUFFIX = "_glx_vertical_cover.webp" + // The older account endpoint: owned ids only. The fallback for a listing that cannot be read. + private const val OWNED_URL = "https://embed.gog.com/user/data/games" private val syncing = AtomicBoolean(false) @@ -45,42 +54,44 @@ object GogLibrary { fun sizeOf(context: Context, gameId: String): Long = GogPrefs.get(context).getLong("size_$gameId", 0L) - fun sync(context: Context, force: Boolean = false, onStatus: (String) -> Unit = {}): SyncResult { + fun sync(context: Context, force: Boolean = false, onStatus: (String) -> Unit = {}, onList: (List) -> Unit = {}, onItems: (List) -> Unit = {}): SyncResult { if (!syncing.compareAndSet(false, true)) return SyncResult.Busy try { val app = context.applicationContext val p = GogPrefs.get(app) val token = GogAuth.validToken(app) ?: return SyncResult.NotLoggedIn onStatus(app.getString(R.string.stores_sync_game_list)) - val gamesJson = StoreNet.get("https://embed.gog.com/user/data/games", bearer = token, userAgent = GogAuth.GALAXY_UA) + val listing = ownedListing(token) + // The listing is the only source of titles: without it the owned ids still sync, just without the early paint. + val listed: List = listing?.games + ?: ownedIds(token)?.map { GogGame(it, "", "", "", "", "", 1, null, "", "") } ?: return SyncResult.Failed(app.getString(R.string.stores_sync_gog_unreachable)) - val ids = ArrayList() - val parsed = runCatching { - val owned = JSONObject(gamesJson).optJSONArray("owned") - if (owned != null) for (i in 0 until owned.length()) { - val id = owned.optLong(i).toString() - if (id != "1801418160" && id != "0") ids.add(id) - } - }.isSuccess - if (!parsed) return SyncResult.Failed(app.getString(R.string.stores_sync_gog_unreadable)) - - val ownedSet = ids.toHashSet() + val named = listing != null + StoresState.logLine(if (named) "GOG: listing ${listed.size} games" else "GOG: listing unreadable, ${listed.size} owned ids") + // A page that failed leaves games unnamed: they are still owned, so their cards and cached details stay. + val ownedSet = listing?.owned ?: listed.mapTo(HashSet()) { it.gameId } val cachedList = cached(app) val stale = System.currentTimeMillis() - p.getLong(LAST_SYNC_KEY, 0L) >= THROTTLE_MS val heavy = force || cachedList.isEmpty() || stale val cachedIds = cachedList.mapTo(HashSet()) { it.gameId } + // A product the last sync found uninstallable stays out of the list while it is re-checked. val skipped = java.util.Collections.newSetFromMap(java.util.concurrent.ConcurrentHashMap()) - if (!heavy) skipped.addAll(p.getStringSet(SKIPPED_KEY, emptySet()).orEmpty()) - val idsToFetch = if (heavy) ids else ids.filter { it !in cachedIds && it !in skipped } - val fetchSet = idsToFetch.toHashSet() + skipped.addAll(p.getStringSet(SKIPPED_KEY, emptySet()).orEmpty()) + val idsToFetch = if (heavy) ownedSet.toList() else ownedSet.filter { it !in cachedIds && it !in skipped } val merged = LinkedHashMap() - for (g in cachedList) if (g.gameId in ownedSet && g.gameId !in fetchSet) merged[g.gameId] = g + // The cache's own entry stays even when the game is re-fetched: its details beat the listing's. + for (g in cachedList) if (g.gameId in ownedSet && g.gameId !in skipped) merged[g.gameId] = g + // A game the sync has not reached keeps the listing's entry, so its card is there from the start. + for (g in listed) if (g.gameId !in merged && g.gameId !in skipped) merged[g.gameId] = g + // Only products that were asked about are cached: a bare listing entry is asked about again. + val detailed = HashSet(cachedIds) + if (named) onList(sorted(merged)) if (idsToFetch.isEmpty()) { val list = merged.values.toList() skipped.retainAll(ownedSet) p.edit().putStringSet(SKIPPED_KEY, HashSet(skipped)).apply() - saveCache(p, list) - return SyncResult.Ok(list.sortedBy { it.title.lowercase() }, 0) + saveCache(p, list.filter { it.gameId in detailed }) + return SyncResult.Ok(sorted(merged), 0) } onStatus(app.resources.getQuantityString(R.plurals.stores_sync_games, idsToFetch.size, idsToFetch.size)) val pool = Executors.newFixedThreadPool(5) @@ -89,16 +100,24 @@ object GogLibrary { var fetched = 0 for ((idx, f) in futures.withIndex()) { val g = runCatching { f.get() }.getOrNull() - if (g != null) { merged[g.gameId] = g; fetched++ } + if (g != null) { + // The cover the card already shows stays, so the wide art lands over it instead of over a gap. + val filled = g.withCover(merged[g.gameId]?.verticalCover) + merged[g.gameId] = filled; detailed.add(g.gameId); fetched++; skipped.remove(g.gameId); onItems(listOf(filled)) + } if ((idx + 1) % 5 == 0) onStatus(app.getString(R.string.stores_sync_progress, idx + 1, futures.size)) + // Saved as it goes: a sync the user closes the app on still leaves a library to paint next launch. + if ((idx + 1) % 20 == 0) saveCache(p, merged.values.filter { it.gameId in detailed }) } + // A product this round found uninstallable leaves when the round is over, not in the middle of it. + for (id in skipped) merged.remove(id) val finalList = merged.values.toList() - saveCache(p, finalList) + saveCache(p, finalList.filter { it.gameId in detailed }) skipped.retainAll(ownedSet) p.edit().putStringSet(SKIPPED_KEY, HashSet(skipped)).apply() if (heavy) p.edit().putLong(LAST_SYNC_KEY, System.currentTimeMillis()).apply() - Log.i(TAG, "sync: owned=${ids.size} fetched=$fetched cached=${finalList.size} heavy=$heavy") - return SyncResult.Ok(finalList.sortedBy { it.title.lowercase() }, fetched) + Log.i(TAG, "sync: owned=${ownedSet.size} fetched=$fetched cached=${finalList.size} heavy=$heavy") + return SyncResult.Ok(sorted(merged), fetched) } catch (e: Exception) { Log.w(TAG, "sync failed: ${e.message}") return SyncResult.Failed(e.message ?: context.getString(R.string.stores_sync_failed)) @@ -107,6 +126,68 @@ object GogLibrary { } } + private fun ownedListing(token: String): Listing? { + val all = ArrayList() + val owned = HashSet() + var page = 1 + var pages = 1 + while (page <= pages && page <= LIST_MAX_PAGES) { + // A page that cannot be read ends the listing; the pages already read still name most of the library. + val listed = StoreNet.get("$LIST_URL&page=$page", bearer = token, userAgent = GogAuth.GALAXY_UA)?.let { parseListing(it) } + if (listed == null) { + StoresState.logLine("GOG: listing page $page of $pages unreadable") + // The unread pages hold games too: without their ids those games would leave the library and the cache. + owned.addAll(ownedIds(token) ?: return null) + break + } + all.addAll(listed.games) + owned.addAll(listed.games.map { it.gameId }) + pages = listed.totalPages + page++ + } + // Not one page read: the caller falls back to the owned ids. + return all.ifEmpty { null }?.let { Listing(it, owned) } + } + + private fun ownedIds(token: String): List? { + val json = StoreNet.get(OWNED_URL, bearer = token, userAgent = GogAuth.GALAXY_UA) ?: return null + val owned = runCatching { JSONObject(json).optJSONArray("owned") }.getOrNull() ?: return null + val ids = ArrayList(owned.length()) + for (i in 0 until owned.length()) { + val id = owned.optLong(i).toString() + if (id != "1801418160" && id != "0") ids.add(id) + } + return ids + } + + fun parseListing(json: String): ListingPage? = runCatching { + val root = JSONObject(json) + val arr = root.optJSONArray("products") ?: return@runCatching null + val games = ArrayList(arr.length()) + for (i in 0 until arr.length()) { + val o = arr.optJSONObject(i) ?: continue + // 1801418160 is GOG's own "Galaxy" entry, in every library. + val id = o.optLong("id", 0L).toString() + if (id == "0" || id == "1801418160") continue + if (o.optBoolean("isMovie", false) || !o.optBoolean("isGame", true)) continue + val title = o.optString("title", "").trim() + if (title.isEmpty()) continue + val worksOn = o.optJSONObject("worksOn") + if (worksOn != null && !worksOn.optBoolean("Windows", true)) continue + val released = o.optJSONObject("releaseDate")?.optString("date", "").orEmpty().substringBefore(' ') + val image = o.optString("image", "").ifBlank { null } + games.add(GogGame(id, title, "", "", "", o.optString("category", ""), 1, + image?.let { GogStoreCatalog.absolutize(it + COVER_SUFFIX) }, released, "")) + } + ListingPage(games, maxOf(1, root.optInt("totalPages", 1))) + }.getOrNull() + + class ListingPage(val games: List, val totalPages: Int) + + private class Listing(val games: List, val owned: Set) + + private fun sorted(merged: Map): List = merged.values.sortedBy { it.title.lowercase() } + private fun fetchGame(prefs: SharedPreferences, id: String, token: String, skipped: MutableSet): GogGame? { fun skip(): GogGame? { skipped.add(id); return null } try { @@ -198,6 +279,10 @@ object GogLibrary { } } + private fun GogGame.withCover(cover: String?): GogGame = + if (cover.isNullOrBlank() || cover == verticalCover) this + else GogGame(gameId, title, imageUrl, description, developer, category, generation, cover, releaseDate, publisher) + fun toCatalogItem(context: Context, g: GogGame): CatalogItem = CatalogItem( store = Store.GOG, id = g.gameId, title = g.title, imageUrl = GogStoreCatalog.absolutize(g.imageUrl).ifBlank { null }, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresDetail.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresDetail.kt index a00a5a46ed..b377f02ec1 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresDetail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresDetail.kt @@ -85,7 +85,9 @@ internal fun StoreGameDetail(store: Store, key: String, s: FrontEndState, a: Fro .clip(Shape16).background(artBrush(hueOf(title))), ) { val art = item?.imageUrl ?: installed?.sidecar?.hero ?: installed?.sidecar?.cover - if (art != null) AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize()) + // The card it came from keeps its own bitmap under the hero until the wide art is decoded. + val heroArt = cardArtRequest(art, item?.tallImageUrl) + if (heroArt != null) AsyncImage(model = heroArt, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize()) Spacer(Modifier.matchParentSize().background(Brush.horizontalGradient(0f to colors.background.copy(alpha = 0.94f), 0.5f to colors.background.copy(alpha = 0.55f), 1f to Color.Transparent))) if (scores != null && !stacked) { Spacer(Modifier.matchParentSize().background(Brush.horizontalGradient(0.45f to Color.Transparent, 1f to colors.background.copy(alpha = 0.75f)))) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt index 02897f2507..c84e0ededa 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt @@ -1007,8 +1007,11 @@ private fun Storefront( val density = androidx.compose.ui.platform.LocalDensity.current val focus = LocalFrontFocus.current val scope = rememberCoroutineScope() - val headerItems = 1 + (if (sizeSortPending) 1 else 0) + - (if (StoresState.status[store] != null) 1 else 0) + (if (StoresState.problems[store] != null) 1 else 0) + // A bar only where the tab has nothing else on it: shelves, the shelf of owned games, or a grid still loading. + val gridEmpty = if (showGrid) visible.isEmpty() else (shelves == null || shelves.isEmpty) && library.isEmpty() + val barLine = StoresState.status[store]?.takeIf { gridEmpty && syncCount(it) != null } + val headerItems = 1 + (if (sizeSortPending) 1 else 0) + (if (barLine != null) 1 else 0) + + (if (StoresState.problems[store] != null) 1 else 0) val listMode = s.storesView == "list" && tab == "library" val capsules = s.storesView == "capsules" && tab == "library" val tileWidth = if (capsules) CapsuleWidth else CardWidth @@ -1091,7 +1094,7 @@ private fun Storefront( Text(stringResource(R.string.store_section_loading), fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant) } } - StoresState.status[store]?.let { line -> item(key = "sync", span = { GridItemSpan(maxLineSpan) }) { Rise(3) { SyncBar(line) } } } + barLine?.let { line -> item(key = "sync", span = { GridItemSpan(maxLineSpan) }) { Rise(3) { SyncBar(line) } } } StoresState.problems[store]?.let { line -> item(key = "problem", span = { GridItemSpan(maxLineSpan) }) { Rise(3) { Box(Modifier.padding(bottom = 8.dp)) { Note(line) } } } } when (tab) { "library" -> if (!loaded) Unit @@ -1480,22 +1483,35 @@ private fun GameCard( } } +private fun syncCount(line: String): Pair? { + val match = Regex("(\\d+)\\s*/\\s*(\\d+)").find(line) ?: return null + val done = match.groupValues[1].toIntOrNull() ?: return null + val total = match.groupValues[2].toIntOrNull()?.takeIf { it > 0 } ?: return null + return done to total +} + @Composable private fun SyncBar(line: String) { - val count = Regex("(\\d+)\\s*/\\s*(\\d+)").find(line) - val done = count?.groupValues?.get(1)?.toIntOrNull() - val total = count?.groupValues?.get(2)?.toIntOrNull()?.takeIf { it > 0 } + val count = syncCount(line) ?: return + val done = count.first + val total = count.second Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) { - Box(Modifier.weight(1f)) { - if (done != null && total != null) androidx.compose.material3.LinearProgressIndicator(progress = { (done.toFloat() / total).coerceIn(0f, 1f) }, modifier = Modifier.fillMaxWidth().height(3.dp)) - else androidx.compose.material3.LinearProgressIndicator(modifier = Modifier.fillMaxWidth().height(3.dp)) - } - if (done != null && total != null) Text("$done/$total", fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1) + Box(Modifier.weight(1f)) { androidx.compose.material3.LinearProgressIndicator(progress = { (done.toFloat() / total).coerceIn(0f, 1f) }, modifier = Modifier.fillMaxWidth().height(3.dp)) } + Text("$done/$total", fontSize = 11.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1) } } private val CardStrip = 26.dp +@Composable +internal fun cardArtRequest(url: String?, cover: String?): coil.request.ImageRequest? { + val ctx = LocalContext.current + val under = cover?.takeIf { it != url } + return remember(url, under) { + url?.let { coil.request.ImageRequest.Builder(ctx).data(it).apply { if (under != null) placeholderMemoryCacheKey(under) }.build() } + } +} + @OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) @Composable private fun CardFace( @@ -1503,26 +1519,27 @@ private fun CardFace( marker: @Composable () -> Unit, ) { val url = if (capsule) item.tallImageUrl ?: item.imageUrl else item.imageUrl ?: item.tallImageUrl + val art = cardArtRequest(url, item.tallImageUrl) val blurs = android.os.Build.VERSION.SDK_INT >= 31 var landscape by remember(url) { mutableStateOf(false) } BoxWithConstraints(Modifier.fillMaxWidth()) { val total = if (capsule) maxWidth * 7f / 5f + CardStrip else maxWidth * 9f / 16f + CardStrip Box(Modifier.fillMaxWidth().height(total).background(Color(0xFF101318)).then(if (url == null) Modifier.background(artBrush(hueOf(item.title))) else Modifier)) { - if (url != null && capsule && landscape) { + if (art != null && capsule && landscape) { // Stores without portrait covers (itch) would lose most of the art to a portrait crop. - AsyncImage(model = url, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize().blur(24.dp)) + AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize().blur(24.dp)) Spacer(Modifier.matchParentSize().background(Color.Black.copy(alpha = if (blurs) 0.35f else 0.7f))) - AsyncImage(model = url, contentDescription = null, contentScale = ContentScale.Fit, modifier = Modifier.matchParentSize().padding(bottom = CardStrip)) - } else if (url != null) AsyncImage( - model = url, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize(), + AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Fit, modifier = Modifier.matchParentSize().padding(bottom = CardStrip)) + } else if (art != null) AsyncImage( + model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize(), onSuccess = { r -> - val art = r.result.drawable - if (capsule && art.intrinsicWidth > 0 && art.intrinsicHeight > 0) landscape = art.intrinsicWidth > art.intrinsicHeight * 0.95f + val drawn = r.result.drawable + if (capsule && drawn.intrinsicWidth > 0 && drawn.intrinsicHeight > 0) landscape = drawn.intrinsicWidth > drawn.intrinsicHeight * 0.95f }, ) Box(Modifier.align(Alignment.BottomCenter).fillMaxWidth().height(CardStrip).clipToBounds()) { - if (url != null) AsyncImage( - model = url, contentDescription = null, contentScale = ContentScale.Crop, + if (art != null) AsyncImage( + model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxWidth().wrapContentHeight(Alignment.Bottom, unbounded = true).height(total).blur(24.dp), ) Spacer(Modifier.matchParentSize().background(Color.Black.copy(alpha = if (blurs) 0.45f else 0.7f))) @@ -1575,9 +1592,10 @@ private fun CardMarker(item: CatalogItem, installed: Boolean, download: com.droi @Composable internal fun CardArt(item: CatalogItem, modifier: Modifier) { val url = item.imageUrl ?: item.tallImageUrl + val art = cardArtRequest(url, item.tallImageUrl) val colors = MaterialTheme.colorScheme Box(modifier.background(colors.surfaceVariant).then(if (url == null) Modifier.background(artBrush(hueOf(item.title))) else Modifier)) { - if (url != null) AsyncImage(model = url, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize()) + if (art != null) AsyncImage(model = art, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.matchParentSize()) else Text(item.title, fontSize = 10.sp, fontWeight = FontWeight.Black, color = Color.White, maxLines = 3, overflow = TextOverflow.Ellipsis, modifier = Modifier.align(Alignment.BottomStart).padding(6.dp)) Spacer(Modifier.matchParentSize().background(androidx.compose.ui.graphics.Brush.verticalGradient(0.6f to Color.Transparent, 1f to colors.surface.copy(alpha = 0.85f)))) } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/StoreCatalogPatchTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/StoreCatalogPatchTest.kt new file mode 100644 index 0000000000..e545cc77d1 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/StoreCatalogPatchTest.kt @@ -0,0 +1,29 @@ +package com.droiddeck.launcher.stores + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame +import org.junit.Test + +/** Filling a grid one card at a time: what is on screen stays put, what is new lands where its title belongs. */ +class StoreCatalogPatchTest { + private fun item(id: String, title: String, image: String? = null) = CatalogItem(Store.GOG, id, title, imageUrl = image, owned = true) + + @Test fun onlyTheCardItWasGivenIsReplaced() { + val alpha = item("1", "Alpha") + val beta = item("2", "Beta") + val next = patchItems(listOf(alpha, beta), listOf(item("2", "Beta", "wide.jpg"))) + assertEquals(2, next.size) + assertSame(alpha, next[0]) + assertEquals("wide.jpg", next[1].imageUrl) + } + + @Test fun aCardTheGridDoesNotHaveYetIsAddedInTitleOrder() { + val next = patchItems(listOf(item("1", "Alpha"), item("3", "Gamma")), listOf(item("2", "Beta"))) + assertEquals(listOf("Alpha", "Beta", "Gamma"), next.map { it.title }) + } + + @Test fun anEmptyGridTakesTheCardAsItComes() { + val next = patchItems(null, listOf(item("2", "Beta"))) + assertEquals(listOf("Beta"), next.map { it.title }) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/gog/GogListingTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/gog/GogListingTest.kt new file mode 100644 index 0000000000..0c6502e939 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/gog/GogListingTest.kt @@ -0,0 +1,79 @@ +package com.droiddeck.launcher.stores.gog + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +/** The account listing: everything the tab needs to draw a library before a product is asked about. */ +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class GogListingTest { + @Test + fun aPageCarriesTheGamesTheAppCanInstall() { + val page = GogLibrary.parseListing(PAGE)!! + assertEquals(2, page.totalPages) + assertEquals(listOf("Shadowrun Returns", "Witcher 3: Wild Hunt, The"), page.games.map { it.title }) + val shadowrun = page.games[0] + assertEquals("1207660413", shadowrun.gameId) + assertEquals("https://images-2.gog.com/6c35ecb988f57725cc0f385acf860241082da16eda9fab66115f4da883dae3d1_glx_vertical_cover.webp", shadowrun.verticalCover) + assertEquals("", shadowrun.imageUrl) + assertEquals("Role-playing", shadowrun.category) + assertEquals("2013-07-25", shadowrun.releaseDate) + assertEquals("", shadowrun.description) + } + + @Test + fun moviesOtherPlatformsAndGalaxysOwnEntryAreLeftOut() { + assertEquals(listOf("1207660413", "1207664663"), GogLibrary.parseListing(PAGE)!!.games.map { it.gameId }) + } + + @Test + fun aResponseThatIsNotAListingIsNull() { + assertNull(GogLibrary.parseListing("""{"error":"unauthorized"}""")) + assertNull(GogLibrary.parseListing("not json")) + } + + private companion object { + val PAGE = """ + { + "sortBy": "title", + "page": 1, + "totalProducts": 6, + "totalPages": 2, + "productsPerPage": 100, + "products": [ + { + "id": 1207660413, + "title": "Shadowrun Returns", + "image": "//images-2.gog.com/6c35ecb988f57725cc0f385acf860241082da16eda9fab66115f4da883dae3d1", + "worksOn": { "Windows": true, "Mac": true, "Linux": true }, + "category": "Role-playing", + "isComingSoon": false, + "isMovie": false, + "isGame": true, + "slug": "shadowrun_returns", + "dlcCount": 0, + "releaseDate": { "date": "2013-07-25 00:00:00.000000", "timezone_type": 3, "timezone": "Europe/Nicosia" } + }, + { + "id": 1207664663, + "title": " Witcher 3: Wild Hunt, The ", + "image": "//images-3.gog.com/60c724a052275a049d857d53957dc38e9347742f52372bb956d992b43efa8fb5", + "worksOn": { "Windows": true, "Mac": false, "Linux": false }, + "category": "Role-playing", + "isMovie": false, + "isGame": true, + "releaseDate": { "date": "2015-05-19 02:00:00.000000", "timezone_type": 3, "timezone": "Europe/Nicosia" } + }, + { "id": 1582718039, "title": "A Movie", "image": "//images-1.gog.com/movie", "isMovie": true, "isGame": false }, + { "id": 1430747193, "title": "Mac Only", "image": "//images-1.gog.com/mac", "worksOn": { "Windows": false, "Mac": true }, "isMovie": false, "isGame": true }, + { "id": 1801418160, "title": "GOG Galaxy", "image": "//images-1.gog.com/galaxy", "worksOn": { "Windows": true }, "isMovie": false, "isGame": true }, + { "id": 1401362385, "title": "Soundtrack", "image": "//images-1.gog.com/ost", "worksOn": { "Windows": true }, "isMovie": false, "isGame": false } + ] + } + """.trimIndent() + } +} diff --git a/docs/progress-log.md b/docs/progress-log.md index 81ec5bc3a3..30b558b86b 100644 --- a/docs/progress-log.md +++ b/docs/progress-log.md @@ -358,6 +358,58 @@ stay as they were (`afa479ee`). - **Open:** newer-runtime Linux games (sniper) untested; the arm64 client untested on this build; the Steam import watcher untested; an SD-card library for the x86 client deferred. +## 2026-10-14 - `gog-library-listing`: the GOG library is drawn from the account listing, details follow + +- **The listing** (`GogLibrary`): the library came from `embed.gog.com/user/data/games`, which is the owned + ids and nothing else - no title, no art - so the tab stayed empty until every product had been asked about + one by one. It now comes from `account/getFilteredProducts` (`mediaType=1`, `hiddenFlag=0`, `sortBy=title`), + a hundred to a page, which carries the title, the category and the release date. Its `image` is a bare + hash the CDN serves only through Galaxy's own formatters, so a listing entry's card art is + `_glx_vertical_cover.webp` until the per-product fetch brings the wide background. +- **The listing can fail** (`GogLibrary`): when it cannot be read the sync falls back to the older + owned-ids endpoint and keeps the old behaviour - there are no titles to draw, so nothing is painted + until the products come back. +- **The tab paints first** (`GogLibrary.sync`): the whole library goes to `GogBackend` the moment the listing + is in, so the grid is on screen in seconds instead of after the last product. +- **Each card fills itself in** (`GogLibrary.sync`, `GogBackend`): every product that comes back is handed + over on its own and only that entry is replaced, so a card swaps to its own art and title as soon as its + product has been asked about while the cards around it keep their objects - no list-wide repaint, no reset + of the scroll or the focus. A product this round finds uninstallable is dropped when the round ends, not in + the middle of it. The progress bar is gone once the grid has games, so a sync in progress no longer reads + as a list still loading. +- **The art swap has no gap** (`GogLibrary.sync`, `StoresPage`): a card that swaps from the listing's cover to + the wide background keeps the cover while the new one decodes - the fetched record carries the cover the + card already shows, and the card's request names it as the memory-cache placeholder - so no card goes dark + in the middle of a sync. +- **The per-product fetch stays** (`fetchGame`): `api.gog.com` is what has the description, the developer, + the publisher, the Galaxy portrait and the build generation, and the detail page reads all of those from + the library entry, so the listing alone cannot replace it. +- **The cache keeps only what was fetched**: a listing entry that never got its details is asked about again + next sync rather than kept as a bare title, and a product the last sync found uninstallable stays out of + the list while it is re-checked. The cache's own entry stays on screen even while it is re-fetched, so a + forced refresh does not drop back to box art. +- **A card patch adds what it brought** (`patchItems`, `GogBackend`): a product that comes back is patched into the +grid where its title belongs, whether or not the grid already had that card. Replacing only the entries already +there left a sync with nothing painted - the owned-ids fallback - showing an empty grid for the whole round. An +empty listing is no longer posted either: that dropped the cards already on screen. +- **A bar needs an empty tab** (`StoresPage`): the bar is drawn only for a sync line that carries a count ("25/55") + and only where the tab has nothing else on it - the storefront's shelves and the Installed tab's own cards are + content - so a library sync no longer creeps along above cards that are already there, and a line that only says + what it is doing leaves the empty state to say it. +- **A page that fails keeps the pages that came** (`GogLibrary`): a listing page that cannot be read ends the +listing instead of discarding it, so a page lost to a flaky request no longer costs the whole early paint. The +cache is saved as the round goes, so a sync the user closes the app on still leaves a library to paint next launch. +- **The hero waits under the card's art** (`StoresDetail`): the library's hero asked for the wide art with no + placeholder of its own, so a card that opened showed its own bitmap only for the length of the opening + animation and then fell back to the title's colour until 300-540KB had been decoded. It now builds the same + request a card does, naming the card's art as the memory-cache placeholder, so the cover stays under the hero + until the wide one lands. +- **The listing says what it gave** (`GogLibrary`, `StoreNet`): one line per sync in the stores' log - how many + games the listing carried, or the page that could not be read - and every failed store GET, which used to + reach logcat only. A shared log can now show whether the account listing came back at all. +- **Tests** (`GogListingTest`, `StoreCatalogPatchTest`): the filters - movies, other platforms, Galaxy's own entry, empty titles - the + fields a card needs, and a response that is not a listing. + ## 2026-10-10 - `feat/wincomp-auto-sources`: Windows components picked by the game's source - **Per source** (`WinCompSources`): Steam - Steamworks Shared depots from the appmanifest or the