feat: games show their logo, and store games get one from the store (#999)

This commit is contained in:
Kurt Himebauch authored and GitHub committed 2026-10-22 14:48:23 -04:00
commit f61525162d
24 files changed
+561 -55

No files matched your search

@@ -2029,7 +2029,7 @@ class MainActivity : ComponentActivity() {
steamGamesX64 = scannedX64
steamGames = all.map { g ->
val newer = current[g.appId]
if (newer != null && g.library != Library.ADDED && steamArtRefreshes[g.appId] != artRefreshesAtStart[g.appId]) g.withArt(newer.art, newer.hero, newer.icon) else g
if (newer != null && g.library != Library.ADDED && steamArtRefreshes[g.appId] != artRefreshesAtStart[g.appId]) g.withArt(newer.art, newer.hero, newer.icon, newer.logo) else g
}
shortcutLibraryScanning = false
handleGameLink(all)
@@ -5,6 +5,8 @@ import android.graphics.Bitmap
import android.util.Log
import com.droiddeck.launcher.files.PeIconExtractor
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.StoreArt
import com.droiddeck.launcher.stores.StoreGameSidecar
import org.json.JSONObject
import java.io.File
import java.net.HttpURLConnection
@@ -228,41 +230,93 @@ object AddedGameArt {
return if (tmp.renameTo(png)) png else null
}
fun fetchMissing(context: Context, games: List<AddedGames.Game>): Boolean {
internal class Sources(
val storeLogo: (AddedGames.Game) -> Boolean,
val steamSearch: (String) -> Int?,
val steam: (String, File, Set<Slot>) -> Boolean,
val sgdbGame: (String, Int?, String) -> Int?,
val sgdb: (String, Int, File, Set<Slot>) -> Boolean,
)
private val network = Sources(
storeLogo = ::storeLogo,
steamSearch = { name -> search(name)?.toIntOrNull() },
steam = ::download,
sgdbGame = SteamGridDb::gameId,
sgdb = SteamGridDb::download,
)
private val EXTRAS = setOf(Slot.LOGO, Slot.ICON)
private val STEAM_SLOTS = setOf(Slot.COVER, Slot.WIDE, Slot.BACKGROUND, Slot.LOGO)
internal const val EXTRAS_TRIED = "extras-tried"
internal fun missing(context: Context, game: AddedGames.Game): Set<Slot> {
val own = local(game)
val cache = cacheDir(context, game)
fun has(slot: Slot, mine: File?, cached: String) = chosen(cache, slot) != null || mine != null || File(cache, cached).isFile
return Slot.values().filterNot { slot ->
when (slot) {
Slot.COVER -> has(slot, own.portrait, "p.jpg")
Slot.WIDE -> has(slot, own.header, "header.jpg")
Slot.BACKGROUND -> has(slot, own.hero, "hero.jpg")
Slot.LOGO -> has(slot, own.logo, "logo.png")
Slot.ICON -> has(slot, own.icon, "icon-sgdb.png")
}
}.toSet()
}
private fun storeLogo(game: AddedGames.Game): Boolean {
val url = StoreGameSidecar.read(game.folder)?.logo ?: return false
return StoreArt.fetchLogo(game.folder, url)
}
fun fetchMissing(context: Context, games: List<AddedGames.Game>): Boolean =
fetchMissing(context, games, SteamGridDb.key(context), network)
internal fun fetchMissing(context: Context, games: List<AddedGames.Game>, sgdbKey: String, sources: Sources): Boolean {
if (!SessionPrefs.addedGamesArt(context)) return false
val sgdbKey = SteamGridDb.key(context)
val keyChangedAt = SteamGridDb.keyChangedAt(context)
var sgdbDown = false
var changed = false
for (game in games) {
if (local(game).portrait != null) continue
val start = missing(context, game)
val full = Slot.COVER in start
val allowed = if (full) Slot.values().toSet() else EXTRAS
var need = start intersect allowed
if (need.isEmpty() || (need == setOf(Slot.ICON) && sgdbKey.isEmpty())) continue
val cache = cacheDir(context, game)
if (File(cache, "p.jpg").isFile) continue
val tried = File(cache, EXTRAS_TRIED)
if (!full && tried.isFile && tried.lastModified() >= keyChangedAt && System.currentTimeMillis() - tried.lastModified() < RETRY_AFTER_MS) continue
cache.mkdirs()
val match = steamMatch(context, game) { name ->
runCatching { search(name) }.onFailure { Log.w(TAG, "${game.name}: store search failed (${it.message})") }.getOrNull()?.toIntOrNull()
if (Slot.LOGO in need && game.source != Library.ADDED && runCatching { sources.storeLogo(game) }.getOrDefault(false)) {
changed = true
need = need - Slot.LOGO
}
val appId = match.appId?.takeIf { match.certainty == SteamMatch.Certainty.FILES }
val id = match.appId?.toString()
if (id != null && download(id, cache)) changed = true
if (File(cache, "p.jpg").isFile || sgdbKey.isEmpty() || sgdbDown) continue
val stored: String? = try {
remembered(File(cache, "sgdb-id"), keyChangedAt) {
SteamGridDb.gameId(sgdbKey, appId ?: id?.toIntOrNull(), game.name)?.toString()
val match by lazy {
steamMatch(context, game) { name ->
runCatching { sources.steamSearch(name) }.onFailure { Log.w(TAG, "${game.name}: store search failed (${it.message})") }.getOrNull()
}
} catch (e: Exception) {
Log.w(TAG, "${game.name}: SteamGridDB lookup failed (${e.javaClass.simpleName}); not asking again this pass")
sgdbDown = true
null
}
val gridId = stored?.toIntOrNull() ?: continue
val grabbed = try {
SteamGridDb.download(sgdbKey, gridId, cache)
} catch (e: Exception) {
sgdbDown = true
false
val steamWant = need intersect STEAM_SLOTS
if (steamWant.isNotEmpty()) {
val id = match.appId?.toString()
if (id != null && sources.steam(id, cache, steamWant)) changed = true
need = missing(context, game) intersect allowed
}
if (grabbed) changed = true
var asked = true
if (need.isNotEmpty() && sgdbKey.isNotEmpty()) {
if (sgdbDown) asked = false else try {
val gridId = remembered(File(cache, "sgdb-id"), keyChangedAt) {
sources.sgdbGame(sgdbKey, match.appId, game.name)?.toString()
}?.toIntOrNull()
if (gridId != null && sources.sgdb(sgdbKey, gridId, cache, need)) changed = true
} catch (e: Exception) {
Log.w(TAG, "${game.name}: SteamGridDB failed (${e.javaClass.simpleName}); not asking again this pass")
sgdbDown = true
asked = false
}
}
if ((missing(context, game) intersect EXTRAS).isEmpty()) tried.delete() else if (asked) tried.writeText("")
}
return changed
}
@@ -314,11 +368,13 @@ object AddedGameArt {
return pickStoreResult(name, (0 until items.length()).map { items.getJSONObject(it) }.map { it.optString("id") to it.optString("name") })
}
private fun download(id: String, cache: File): Boolean {
private fun download(id: String, cache: File, slots: Set<Slot>): Boolean {
var got = false
for ((remote, localName) in listOf(
"library_600x900.jpg" to "p.jpg", "header.jpg" to "header.jpg", "library_hero.jpg" to "hero.jpg", "logo.png" to "logo.png",
for ((slot, remote, localName) in listOf(
Triple(Slot.COVER, "library_600x900.jpg", "p.jpg"), Triple(Slot.WIDE, "header.jpg", "header.jpg"),
Triple(Slot.BACKGROUND, "library_hero.jpg", "hero.jpg"), Triple(Slot.LOGO, "logo.png", "logo.png"),
)) {
if (slot !in slots) continue
val dst = File(cache, localName)
if (dst.isFile) continue
val bytes = get("$CDN$id/$remote") ?: steamAssetUrl(id, remote)?.let { get(it) } ?: continue
@@ -16,9 +16,10 @@ object Library {
val icon: File? = null,
val source: String = SOURCE_STEAM,
val storeId: String? = null,
val logo: File? = null,
) {
fun withArt(art: File?, hero: File?, icon: File?) =
SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId)
fun withArt(art: File?, hero: File?, icon: File?, logo: File? = this.logo) =
SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId, logo)
val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId)
val profileKey: String get() = if (library == ADDED) java.lang.Integer.toUnsignedString(appId) else appId.toString()
@@ -68,6 +69,7 @@ object Library {
)
private val STEAM_CAPSULES = listOf("library_capsule.jpg", "library_600x900.jpg")
private val STEAM_HEROES = listOf("library_hero.jpg")
internal val STEAM_LOGOS = listOf("logo.png")
private val STEAM_ICON = Regex("[a-fA-F0-9]{40}\\.(jpg|png)")
private val NAME = Regex("^\\s*\"name\"\\s*\"([^\"]*)\"", RegexOption.MULTILINE)
private val STATE = Regex("^\\s*\"StateFlags\"\\s*\"(\\d+)\"", RegexOption.MULTILINE)
@@ -131,6 +133,7 @@ object Library {
protonPrefix = protonPrefix(context, appId.toLong(), library, roots),
icon = steamCacheImage(cache, appId, listOf("icon.jpg", "icon.png"))
?: File(cache, appId.toString()).listFiles()?.firstOrNull { it.isFile && STEAM_ICON.matches(it.name) },
logo = steamCacheImage(cache, appId, STEAM_LOGOS),
))
}
}
@@ -203,6 +206,7 @@ object Library {
protonPrefix = protonPrefix(context, g.steamAppId?.toLong() ?: g.appId, libraries = roots),
icon = art.icon?.takeIf { it.extension.lowercase() != "ico" },
source = g.source, storeId = g.storeId,
logo = art.logo,
)
}
@@ -27,6 +27,7 @@ object LibraryCache {
icon = o.file("icon"),
source = o.optString("source").ifEmpty { if (o.getString("library") == Library.ADDED) Library.ADDED else Library.SOURCE_STEAM },
storeId = o.optString("storeId").ifEmpty { null },
logo = o.file("logo"),
)
} to x64
}.getOrElse { e -> Log.w(TAG, "unreadable, ignored: ${e.message}"); Pair(emptyList(), false) }
@@ -44,7 +45,7 @@ object LibraryCache {
for (g in games) array.put(
JSONObject().put("appId", g.appId).put("name", g.name).put("library", g.library).put("gameId", g.gameId)
.put("lastPlayed", g.lastPlayed).putFile("art", g.art).putFile("hero", g.hero)
.putFile("gameFiles", g.gameFiles).putFile("protonPrefix", g.protonPrefix).putFile("icon", g.icon)
.putFile("gameFiles", g.gameFiles).putFile("protonPrefix", g.protonPrefix).putFile("icon", g.icon).putFile("logo", g.logo)
.put("source", g.source).apply { g.storeId?.let { put("storeId", it) } },
)
val f = file(context)
@@ -22,10 +22,12 @@ object SteamGameArt {
val cover = chosenFile(context, game.appId, AddedGameArt.Slot.COVER)
val hero = chosenFile(context, game.appId, AddedGameArt.Slot.BACKGROUND)
val icon = chosenFile(context, game.appId, AddedGameArt.Slot.ICON)
if (cover == null && hero == null && icon == null) return game
val logo = chosenFile(context, game.appId, AddedGameArt.Slot.LOGO)
if (cover == null && hero == null && icon == null && logo == null) return game
return Library.SteamGame(
game.appId, game.name, cover ?: game.art, game.library, game.gameId,
hero ?: game.hero, game.lastPlayed, game.gameFiles, game.protonPrefix, icon ?: game.icon, game.source, game.storeId,
logo ?: game.logo,
)
}
@@ -84,18 +84,23 @@ object SteamGridDb {
.filter { it.second > 0 && it.first > 0 }
.maxByOrNull { it.second }?.first
fun download(key: String, id: Int, cache: File): Boolean {
internal fun cacheName(slot: AddedGameArt.Slot): String =
when (slot) {
AddedGameArt.Slot.COVER -> "p.jpg"
AddedGameArt.Slot.WIDE -> "header.jpg"
AddedGameArt.Slot.BACKGROUND -> "hero.jpg"
AddedGameArt.Slot.LOGO -> "logo.png"
AddedGameArt.Slot.ICON -> "icon-sgdb.png"
}
fun download(key: String, id: Int, cache: File, slots: Set<AddedGameArt.Slot> = AddedGameArt.Slot.values().toSet()): Boolean {
var got = false
for ((path, local) in listOf(
"grids/game/$id?dimensions=600x900&$QUERY" to "p.jpg",
"grids/game/$id?dimensions=460x215,920x430&$QUERY" to "header.jpg",
"heroes/game/$id?$QUERY" to "hero.jpg",
"logos/game/$id?$QUERY" to "logo.png",
"icons/game/$id?$QUERY" to "icon-sgdb.png",
)) {
for (slot in AddedGameArt.Slot.values()) {
if (slot !in slots) continue
val local = cacheName(slot)
val dst = File(cache, local)
if (dst.isFile) continue
val items = json(key, "$API/$path")?.optJSONArray("data") ?: continue
val items = json(key, "$API/${path(id, slot)}")?.optJSONArray("data") ?: continue
val url = best(items, local.endsWith(".png")) ?: continue
val bytes = AddedGameArt.get(url) ?: continue
val tmp = File(cache, "$local.tmp")
@@ -14,13 +14,45 @@ object StoreArt {
fun fetchInto(folder: File, sidecar: StoreGameSidecar) {
sidecar.cover?.let { place(it, File(folder, "cover.jpg")) }
val wide = sidecar.hero ?: return
if (place(wide, File(folder, "hero.jpg"))) {
val header = File(folder, "header.jpg")
if (!header.isFile) runCatching { File(folder, "hero.jpg").copyTo(header, overwrite = true) }
sidecar.hero?.let { wide ->
if (place(wide, File(folder, "hero.jpg"))) {
val header = File(folder, "header.jpg")
if (!header.isFile) runCatching { File(folder, "hero.jpg").copyTo(header, overwrite = true) }
}
}
sidecar.logo?.let { fetchLogo(folder, it) }
}
fun fetchLogo(folder: File, url: String): Boolean {
val dst = File(folder, LOGO)
if (dst.isFile && dst.length() > 0) return true
return writeLogo(get(url) ?: return false, dst)
}
/** A logo is drawn over the hero, so it stays a PNG with its transparency instead of going through [place]. */
internal fun writeLogo(bytes: ByteArray, dst: File): Boolean {
if (dst.isFile && dst.length() > 0) return true
val bitmap = runCatching { BitmapFactory.decodeByteArray(bytes, 0, bytes.size) }.getOrNull() ?: return false
val tmp = File(dst.path + ".tmp")
return try {
if (bitmap.width <= 0 || bitmap.height <= 0) return false
if (isPng(bytes)) tmp.writeBytes(bytes) else tmp.outputStream().use { bitmap.compress(Bitmap.CompressFormat.PNG, 100, it) }
tmp.renameTo(dst)
} catch (e: Exception) {
Log.w(TAG, "${dst.name}: ${e.javaClass.simpleName}")
false
} finally {
tmp.delete()
bitmap.recycle()
}
}
private val PNG_MAGIC = byteArrayOf(0x89.toByte(), 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A)
private fun isPng(bytes: ByteArray): Boolean = bytes.size > PNG_MAGIC.size && PNG_MAGIC.indices.all { bytes[it] == PNG_MAGIC[it] }
const val LOGO = "logo.png"
private fun place(url: String, dst: File): Boolean {
if (dst.isFile && dst.length() > 0) return true
val bytes = get(url) ?: return false
@@ -23,6 +23,7 @@ data class CatalogItem(
val mature: Boolean = false,
val subscription: Boolean = false,
val includedWith: String = "",
val logoUrl: String? = null,
) {
val accessible: Boolean get() = owned || subscription
/** Licensed now, or a supported package the account's subscription can install. */
@@ -22,6 +22,7 @@ class StoreGameSidecar(
val epic: EpicOptions = EpicOptions(),
val cloud: Boolean = true,
val achievements: Boolean = true,
val logo: String? = null,
) {
val isInstalled: Boolean get() = state == STATE_INSTALLED
@@ -33,7 +34,8 @@ class StoreGameSidecar(
env: Map<String, String> = this.env, installVersion: String = this.installVersion,
installedAt: Long = this.installedAt, cover: String? = this.cover, hero: String? = this.hero,
extra: Map<String, String> = this.extra, state: String = this.state, epic: EpicOptions = this.epic, cloud: Boolean = this.cloud, achievements: Boolean = this.achievements,
) = StoreGameSidecar(store, id, title, exe, launcher, args, env, installVersion, installedAt, cover, hero, extra, state, epic, cloud, achievements)
logo: String? = this.logo,
) = StoreGameSidecar(store, id, title, exe, launcher, args, env, installVersion, installedAt, cover, hero, extra, state, epic, cloud, achievements, logo)
fun toJson(): JSONObject = JSONObject().apply {
put("version", VERSION)
@@ -52,6 +54,7 @@ class StoreGameSidecar(
if (installedAt > 0L) put("installedAt", installedAt)
if (!cover.isNullOrEmpty()) put("cover", cover)
if (!hero.isNullOrEmpty()) put("hero", hero)
if (!logo.isNullOrEmpty()) put("logo", logo)
if (extra.isNotEmpty()) put("extra", JSONObject(extra as Map<*, *>))
}
@@ -129,6 +132,7 @@ class StoreGameSidecar(
epic = o.optJSONObject("epic")?.let { e -> EpicOptions(eos = e.optBoolean("eos", true), offline = e.optBoolean("offline", false)) } ?: EpicOptions(),
cloud = o.optBoolean("cloud", true),
achievements = o.optBoolean("achievements", true),
logo = o.optString("logo", "").ifEmpty { null },
)
}
@@ -40,7 +40,7 @@ object StoreInstalls {
val app = context.applicationContext
onStep?.invoke(0, STEPS)
val before = StoreGameSidecar.read(folder)
val finished = StoreLaunch.writeLauncher(folder, sidecar.copy(state = StoreGameSidecar.STATE_INSTALLED, epic = before?.epic ?: sidecar.epic, cloud = before?.cloud ?: sidecar.cloud, achievements = before?.achievements ?: sidecar.achievements))
val finished = StoreLaunch.writeLauncher(folder, sidecar.copy(state = StoreGameSidecar.STATE_INSTALLED, epic = before?.epic ?: sidecar.epic, cloud = before?.cloud ?: sidecar.cloud, achievements = before?.achievements ?: sidecar.achievements, logo = sidecar.logo ?: before?.logo))
finished.write(folder)
if (StoreGameSidecar.read(folder)?.isInstalled != true) throw java.io.IOException("the install record could not be written in ${folder.name}")
onStep?.invoke(1, STEPS)
@@ -124,6 +124,7 @@ internal class AmazonInstaller(
installVersion = versionId, installedAt = System.currentTimeMillis(),
cover = cover, hero = item.imageUrl,
extra = mapOf("entitlementId" to entitlementId, "sku" to sku),
logo = item.logoUrl,
)
StoreInstalls.complete(app, folder, sidecar, onStep = { done, steps -> handle.stageProgress(done.toLong(), steps.toLong()) })
return folder.path
@@ -24,6 +24,7 @@ data class AmazonGame(
val publisher: String = "",
val productSku: String = "",
val versionId: String = "",
val logoUrl: String = "",
)
object AmazonLibrary {
@@ -42,7 +43,8 @@ object AmazonLibrary {
JSONObject()
.put("productId", g.productId).put("entitlementId", g.entitlementId).put("title", g.title)
.put("artUrl", g.artUrl).put("heroUrl", g.heroUrl).put("developer", g.developer)
.put("publisher", g.publisher).put("productSku", g.productSku).put("versionId", g.versionId),
.put("publisher", g.publisher).put("productSku", g.productSku).put("versionId", g.versionId)
.apply { if (g.logoUrl.isNotEmpty()) put("logoUrl", g.logoUrl) },
)
}.toString()
@@ -60,6 +62,7 @@ object AmazonLibrary {
publisher = o.optString("publisher", ""),
productSku = o.optString("productSku", ""),
versionId = o.optString("versionId", ""),
logoUrl = o.optString("logoUrl", ""),
)
}
return tidy(games)
@@ -94,6 +97,7 @@ object AmazonLibrary {
sizeBytes = prefs.getLong("size_${game.productId}", 0L).takeIf { it > 0 } ?: 0L,
storeUrl = STORE_URL,
extra = mapOf("entitlementId" to game.entitlementId, "sku" to game.productSku, "version" to ""),
logoUrl = game.logoUrl.ifEmpty { null },
)
}
@@ -106,7 +110,7 @@ object AmazonLibrary {
}
}
private fun gameFrom(o: JSONObject, before: AmazonGame?): AmazonGame = AmazonGame(
internal fun gameFrom(o: JSONObject, before: AmazonGame?): AmazonGame = AmazonGame(
productId = o.optString("productId"),
entitlementId = o.optString("entitlementId"),
title = o.optString("title"),
@@ -116,6 +120,7 @@ object AmazonLibrary {
publisher = o.optString("publisher"),
productSku = o.optString("sku"),
versionId = before?.versionId.orEmpty(),
logoUrl = o.optString("logo").ifEmpty { before?.logoUrl.orEmpty() },
)
private fun backfillPosters(app: Context, games: List<AmazonGame>) {
@@ -77,6 +77,7 @@ object SavedQueue {
private fun itemJson(i: CatalogItem) = JSONObject().apply {
put("store", i.store.id); put("id", i.id); put("title", i.title)
put("image", i.imageUrl ?: ""); put("tall", i.tallImageUrl ?: "")
i.logoUrl?.let { put("logo", it) }
put("tags", i.tags); put("developer", i.developer); put("description", i.description)
put("size", i.sizeBytes); put("owned", i.owned); put("subscription", i.subscription)
put("extra", JSONObject(i.extra))
@@ -91,6 +92,7 @@ object SavedQueue {
tags = o.optString("tags"), developer = o.optString("developer"), description = o.optString("description"),
owned = o.optBoolean("owned", true), subscription = o.optBoolean("subscription"), sizeBytes = o.optLong("size"),
extra = extra?.keys()?.asSequence()?.associateWith { extra.getString(it) } ?: emptyMap(),
logoUrl = o.optString("logo").ifEmpty { null },
)
}
}
@@ -133,7 +133,7 @@ internal class EpicInstaller(
val sidecar = StoreGameSidecar(
Store.EPIC, item.id, item.title, exe = picked.ifEmpty { "game.exe" }, args = args,
installVersion = result.optString("buildVersion"), installedAt = System.currentTimeMillis(),
cover = cover, hero = item.imageUrl, extra = extra,
cover = cover, hero = item.imageUrl, extra = extra, logo = item.logoUrl,
)
StoreInstalls.complete(app, folder, sidecar, onStep = { done, steps -> handle.stageProgress(done.toLong(), steps.toLong()) })
val disk = result.optLong("diskBytes", 0L)
@@ -25,6 +25,7 @@ data class EpicGame(
val releaseDate: String = "",
val publisher: String = "",
val isDlc: Boolean = false,
val artLogo: String = "",
)
object EpicLibrary {
@@ -50,7 +51,8 @@ object EpicLibrary {
.put("title", g.title).put("artCover", g.artCover).put("artSquare", g.artSquare)
.put("developer", g.developer).put("description", g.description).put("version", g.version)
.put("installSize", g.installSize).put("canRunOffline", g.canRunOffline)
.put("releaseDate", g.releaseDate).put("publisher", g.publisher),
.put("releaseDate", g.releaseDate).put("publisher", g.publisher)
.apply { if (g.artLogo.isNotEmpty()) put("artLogo", g.artLogo) },
)
}.toString()
@@ -73,6 +75,7 @@ object EpicLibrary {
canRunOffline = o.optBoolean("canRunOffline", true),
releaseDate = o.optString("releaseDate", ""),
publisher = o.optString("publisher", ""),
artLogo = o.optString("artLogo", ""),
)
}
return tidy(games)
@@ -106,6 +109,7 @@ object EpicLibrary {
sizeBytes = prefs.getLong("size_${game.appName}", 0L).takeIf { it > 0 } ?: game.installSize,
storeUrl = "https://store.epicgames.com/en-US/browse?q=" + URLEncoder.encode(title, "UTF-8"),
extra = mapOf("namespace" to game.namespace, "catalogItemId" to game.catalogItemId, "version" to game.version),
logoUrl = game.artLogo.ifEmpty { null },
)
}
@@ -128,6 +132,7 @@ object EpicLibrary {
releaseDate = pick("releaseDate", before?.releaseDate.orEmpty()),
publisher = pick("publisher", before?.publisher.orEmpty()),
isDlc = d.optBoolean("dlc", false),
artLogo = pick("logo", before?.artLogo.orEmpty()),
)
}
@@ -11,10 +11,12 @@ import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.StoreInstalls
import com.droiddeck.launcher.stores.StoreLanguage
import com.droiddeck.launcher.stores.StoreLoginActivity
import com.droiddeck.launcher.stores.StoreNet
import com.droiddeck.launcher.stores.StoresState
import com.droiddeck.launcher.stores.download.DownloadEntry
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import org.json.JSONObject
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
@@ -85,6 +87,13 @@ object GogBackend : StoreBackend {
override fun uninstall(context: Context, game: InstalledStoreGame) {}
private fun fetchLogo(id: String): String? =
runCatching { StoreNet.get("https://api.gog.com/v2/games/$id?locale=en-US")?.let { logoOf(JSONObject(it)) } }.getOrNull()
/** `images.logo2x` from the products API is an opaque banner, not a logo; the v2 `logo` link is a transparent PNG. */
internal fun logoOf(v2: JSONObject): String? =
GogStoreCatalog.absolutize(v2.optJSONObject("_links")?.optJSONObject("logo")?.optString("href")).takeIf { it.startsWith("https://") }
private class InstallJob(val app: Context, val game: GogGame, val item: CatalogItem, val folder: File) : DownloadQueue.DownloadJob {
private val cancelled = AtomicBoolean(false)
@@ -118,6 +127,7 @@ object GogBackend : StoreBackend {
Store.GOG, game.gameId, game.title, exe = result.exeRelative.ifEmpty { "" },
installVersion = result.buildId, installedAt = System.currentTimeMillis(),
cover = item.tallImageUrl ?: item.imageUrl, hero = item.imageUrl,
logo = item.logoUrl ?: fetchLogo(game.gameId),
extra = mapOf(com.droiddeck.launcher.frontend.WinCompSources.GOG_DEPENDENCIES to result.dependencies.joinToString(","))
+ (if (result.dependenciesRead) mapOf(com.droiddeck.launcher.frontend.WinCompSources.LIST_READ to "1") else emptyMap())
+ mapOf(StoreLanguage.EXTRA to installedLanguage),
@@ -27,6 +27,7 @@ import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
@@ -341,11 +342,24 @@ private fun ColumnScope.GameHeroCopy(g: Library.SteamGame, titleSize: androidx.c
maxLines = 1, overflow = TextOverflow.Ellipsis,
)
}
Text(
GameTitle(g, titleSize)
Spacer(Modifier.height(8.dp))
}
@Composable
private fun GameTitle(g: Library.SteamGame, titleSize: androidx.compose.ui.unit.TextUnit) {
val logo = g.logo
var failed by remember(logo) { androidx.compose.runtime.mutableStateOf(false) }
if (logo != null && !failed) {
AsyncImage(
model = logo, contentDescription = g.name, contentScale = ContentScale.Fit, alignment = Alignment.CenterStart,
onError = { failed = true },
modifier = Modifier.padding(vertical = 4.dp).height((titleSize.value * 2.2f).dp).widthIn(max = (titleSize.value * 9f).dp).testTag("game-logo"),
)
} else Text(
g.name, fontSize = titleSize, lineHeight = titleSize * 1.15f, fontWeight = FontWeight.Bold,
color = MaterialTheme.colorScheme.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis,
)
Spacer(Modifier.height(8.dp))
}
@Composable
@@ -21,6 +21,7 @@ pub struct Game {
pub parent_product_id: String,
pub art: String,
pub hero: String,
pub logo: String,
pub developer: String,
pub publisher: String,
}
@@ -39,6 +40,7 @@ impl Game {
"sku": self.sku,
"art": self.art,
"hero": self.hero,
"logo": self.logo,
"developer": self.developer,
"publisher": self.publisher,
"dlc": self.is_dlc(),
@@ -83,6 +85,7 @@ pub fn read_entitlement(e: &Value) -> Option<Game> {
],
)
.to_string(),
logo: str_at(product, &["productDetail", "details", "logoUrl"]).to_string(),
developer: str_at(product, &["productDetail", "details", "developer"]).to_string(),
publisher: str_at(product, &["productDetail", "details", "publisher"]).to_string(),
})
@@ -178,17 +181,20 @@ mod tests {
fn entitlement_fields_and_fallbacks() {
let e = json!({"id":"ent-1","product":{"id":"amzn1.adg.product.x","title":"Game","sku":"SKU1",
"productDetail":{"iconUrl":"","details":{"pgCrownImageUrl":"crown","backgroundUrl1":"bg1",
"developer":"Dev","publisher":"Pub","productType":"GAME"}}}});
"logoUrl":"logo","developer":"Dev","publisher":"Pub","productType":"GAME"}}}});
let g = read_entitlement(&e).unwrap();
assert_eq!(g.entitlement_id, "ent-1");
assert_eq!(g.art, "crown");
assert_eq!(g.hero, "bg1");
assert_eq!(g.logo, "logo");
assert_eq!(g.to_json()["logo"], "logo");
assert_eq!(g.product_type, "GAME");
assert!(!g.is_dlc());
let untitled = read_entitlement(&json!({"product":{"id":"p","type":"DLC","baseProductId":"q"}})).unwrap();
assert_eq!(untitled.title, "Unknown");
assert_eq!(untitled.entitlement_id, "");
assert_eq!(untitled.parent_product_id, "q");
assert_eq!(untitled.logo, "");
assert!(untitled.is_dlc());
assert!(read_entitlement(&json!({"id":"x"})).is_none());
assert!(read_entitlement(&json!({"id":"x","product":{"id":""}})).is_none());
+5 -1
View File
@@ -71,6 +71,7 @@ pub fn details_of(entry: &Value) -> Value {
"releaseDate": release,
"tall": image(entry, &["DieselGameBoxTall"]),
"wide": image(entry, &["DieselGameBox", "Thumbnail"]),
"logo": image(entry, &["DieselGameBoxLogo"]),
"canRunOffline": offline,
"dlc": main_game.is_some_and(|m| !m.is_null()),
"mainGameId": main_game.map(|m| net::str_of(m, "id")).unwrap_or(""),
@@ -102,7 +103,8 @@ mod tests {
"keyImages": [
{"type": "Thumbnail", "url": "thumb"},
{"type": "DieselGameBox", "url": ""},
{"type": "DieselGameBoxTall", "url": "tall"}
{"type": "DieselGameBoxTall", "url": "tall"},
{"type": "DieselGameBoxLogo", "url": "logo"}
],
"customAttributes": {"CanRunOffline": {"value": "FALSE"}, "publisherName": {"value": " Pub "}},
"seller": {"name": "Seller"},
@@ -113,6 +115,7 @@ mod tests {
assert_eq!(d["title"], "Game");
assert_eq!(d["tall"], "tall");
assert_eq!(d["wide"], "thumb");
assert_eq!(d["logo"], "logo");
assert_eq!(d["publisher"], "Pub");
assert_eq!(d["canRunOffline"], false);
assert_eq!(d["releaseDate"], "2020-01-01T00:00:00.000Z");
@@ -123,6 +126,7 @@ mod tests {
assert_eq!(dlc["publisher"], "S");
assert_eq!(dlc["releaseDate"], "v");
assert_eq!(dlc["canRunOffline"], true);
assert_eq!(dlc["logo"], "");
assert_eq!(pick_entry(&json!({"x": {"title": "Only"}}), "y").unwrap()["title"], "Only");
}
}
@@ -0,0 +1,163 @@
package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.frontend.AddedGameArt.Slot
import com.droiddeck.launcher.session.SessionPrefs
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Assert.fail
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
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class AddedGameArtFillTest {
private val app get() = RuntimeEnvironment.getApplication()
@get:Rule val tmp = TemporaryFolder()
private val coverBytes = byteArrayOf(9, 9, 9)
private fun game(name: String, appId: Long, cover: Boolean = true, source: String = Library.ADDED): AddedGames.Game {
val dir = tmp.newFolder(name)
File(dir, "steam_appid.txt").writeText("504230")
if (cover) File(dir, "cover.jpg").writeBytes(coverBytes)
val exe = File(dir, "$name.exe").apply { writeText("x") }
return AddedGames.Game(dir, name, exe, "/g/$name.exe", "/g", appId, appId, emptyList(), source = source)
}
private class Calls {
val steam = ArrayList<Set<Slot>>()
val sgdb = ArrayList<Set<Slot>>()
var lookups = 0
var store = 0
}
private val steamNames = mapOf(Slot.COVER to "p.jpg", Slot.WIDE to "header.jpg", Slot.BACKGROUND to "hero.jpg", Slot.LOGO to "logo.png")
private fun sources(
calls: Calls, steamHas: Set<Slot> = emptySet(), sgdbHas: Set<Slot> = emptySet(),
storeHas: Boolean = false, sgdbFails: Boolean = false,
) = AddedGameArt.Sources(
storeLogo = { g ->
calls.store++
if (storeHas) File(g.folder, "logo.png").writeBytes(byteArrayOf(4))
storeHas
},
steamSearch = { fail("searched although the game names its appid"); null },
steam = { id, cache, slots ->
assertEquals("504230", id)
calls.steam += slots
(slots intersect steamHas).onEach { File(cache, steamNames.getValue(it)).writeBytes(byteArrayOf(1)) }.isNotEmpty()
},
sgdbGame = { _, steamId, _ ->
calls.lookups++
assertEquals(504230, steamId)
77
},
sgdb = { _, id, cache, slots ->
assertEquals(77, id)
if (sgdbFails) throw SteamGridDb.Failed(SteamGridDb.Status.OFFLINE)
calls.sgdb += slots
(slots intersect sgdbHas).onEach { File(cache, SteamGridDb.cacheName(it)).writeBytes(byteArrayOf(2)) }.isNotEmpty()
},
)
@Test fun aGameWithItsOwnCoverStillGetsItsLogoAndIcon() {
val g = game("Celeste", 0x81000001L)
val calls = Calls()
assertTrue(AddedGameArt.fetchMissing(app, listOf(g), "key", sources(calls, steamHas = setOf(Slot.LOGO), sgdbHas = setOf(Slot.ICON))))
assertEquals(listOf(setOf(Slot.LOGO)), calls.steam)
assertEquals(listOf(setOf(Slot.ICON)), calls.sgdb)
assertEquals(0, calls.store)
val cache = AddedGameArt.cacheDir(app, g)
assertFalse(File(cache, "p.jpg").exists())
assertArrayEquals(coverBytes, File(g.folder, "cover.jpg").readBytes())
val art = AddedGameArt.resolve(app, g)
assertEquals(File(g.folder, "cover.jpg"), art.portrait)
assertEquals(File(cache, "logo.png"), art.logo)
assertEquals(File(cache, "icon-sgdb.png"), art.icon)
assertFalse(File(cache, AddedGameArt.EXTRAS_TRIED).exists())
}
@Test fun filledOrChosenSlotsAreNeverAskedFor() {
val g = game("Hades", 0x81000002L)
File(g.folder, "logo.png").writeBytes(byteArrayOf(5))
val picked = File(tmp.root, "mine.png").apply { writeBytes(byteArrayOf(6)) }
assertTrue(AddedGameArt.store(AddedGameArt.cacheDir(app, g), Slot.ICON, AddedGameArt.Option(AddedGameArt.FILE, picked.path, picked.path)))
val calls = Calls()
assertFalse(AddedGameArt.fetchMissing(app, listOf(g), "key", sources(calls, steamHas = Slot.values().toSet(), sgdbHas = Slot.values().toSet())))
assertTrue(calls.steam.isEmpty() && calls.sgdb.isEmpty() && calls.lookups == 0)
assertArrayEquals(byteArrayOf(5), File(g.folder, "logo.png").readBytes())
}
@Test fun withoutAKeyAMissingIconAloneAsksNothing() {
val g = game("Inside", 0x81000003L)
File(g.folder, "logo.png").writeBytes(byteArrayOf(5))
val calls = Calls()
assertFalse(AddedGameArt.fetchMissing(app, listOf(g), "", sources(calls)))
assertTrue(calls.steam.isEmpty() && calls.sgdb.isEmpty() && calls.lookups == 0)
assertFalse(AddedGameArt.cacheDir(app, g).exists())
}
@Test fun aMissIsAskedAgainOnlyAfterAWeek() {
val g = game("Limbo", 0x81000004L)
val calls = Calls()
assertFalse(AddedGameArt.fetchMissing(app, listOf(g), "key", sources(calls)))
assertEquals(listOf(setOf(Slot.LOGO)), calls.steam)
assertEquals(listOf(setOf(Slot.LOGO, Slot.ICON)), calls.sgdb)
AddedGameArt.fetchMissing(app, listOf(g), "key", sources(calls))
assertEquals(1, calls.steam.size)
assertEquals(1, calls.sgdb.size)
val tried = File(AddedGameArt.cacheDir(app, g), AddedGameArt.EXTRAS_TRIED)
assertTrue(tried.setLastModified(System.currentTimeMillis() - 8L * 24 * 3600 * 1000))
assertTrue(AddedGameArt.fetchMissing(app, listOf(g), "key", sources(calls, steamHas = setOf(Slot.LOGO), sgdbHas = setOf(Slot.ICON))))
assertEquals(2, calls.steam.size)
assertEquals(setOf(Slot.ICON), calls.sgdb.last())
assertFalse(tried.exists())
}
@Test fun theStoresOwnLogoComesFirst() {
val g = game("Metalstorm", 0x81000005L, source = "gog")
val calls = Calls()
assertTrue(AddedGameArt.fetchMissing(app, listOf(g), "key", sources(calls, storeHas = true, steamHas = setOf(Slot.LOGO), sgdbHas = setOf(Slot.ICON))))
assertEquals(1, calls.store)
assertTrue(calls.steam.isEmpty())
assertEquals(listOf(setOf(Slot.ICON)), calls.sgdb)
assertEquals(File(g.folder, "logo.png"), AddedGameArt.resolve(app, g).logo)
}
@Test fun aGameWithoutACoverStillGetsEverySlot() {
val g = game("Tunic", 0x81000006L, cover = false)
val calls = Calls()
assertTrue(AddedGameArt.fetchMissing(app, listOf(g), "key",
sources(calls, steamHas = setOf(Slot.COVER, Slot.WIDE, Slot.BACKGROUND), sgdbHas = setOf(Slot.LOGO, Slot.ICON))))
assertEquals(listOf(setOf(Slot.COVER, Slot.WIDE, Slot.BACKGROUND, Slot.LOGO)), calls.steam)
assertEquals(listOf(setOf(Slot.LOGO, Slot.ICON)), calls.sgdb)
assertTrue(AddedGameArt.missing(app, g).isEmpty())
}
@Test fun aSteamGridDbFailureIsNotRememberedAndStopsThePass() {
val first = game("Gris", 0x81000007L)
val second = game("Hollow", 0x81000008L)
val calls = Calls()
AddedGameArt.fetchMissing(app, listOf(first, second), "key", sources(calls, sgdbFails = true))
assertEquals(2, calls.steam.size)
assertEquals(1, calls.lookups)
assertFalse(File(AddedGameArt.cacheDir(app, first), AddedGameArt.EXTRAS_TRIED).exists())
assertFalse(File(AddedGameArt.cacheDir(app, second), AddedGameArt.EXTRAS_TRIED).exists())
}
@Test fun nothingIsFetchedWhenArtIsOff() {
SessionPrefs.setAddedGamesArt(app, false)
val calls = Calls()
assertFalse(AddedGameArt.fetchMissing(app, listOf(game("Off", 0x81000009L)), "key", sources(calls)))
assertTrue(calls.steam.isEmpty())
}
}
@@ -0,0 +1,80 @@
package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.session.SessionPrefs
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
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
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class GameLogoTest {
private val app get() = RuntimeEnvironment.getApplication()
@get:Rule val tmp = TemporaryFolder()
@Before fun noGamesFolders() {
AddedGamesPublisher.now = true
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
SessionPrefs.setAddedGamesDirs(app, emptyList())
}
private fun image(name: String) = File(tmp.root, name).apply { parentFile?.mkdirs(); writeBytes(ByteArray(8) { 1 }) }
@Test fun steamsCachedLogoIsFoundInTheAppFolderOrAHashedOne() {
val cache = tmp.newFolder("librarycache")
val logo = File(cache, "620/3f1c/logo.png").apply { parentFile?.mkdirs(); writeBytes(ByteArray(4) { 1 }) }
assertEquals(logo, Library.steamCacheImage(cache, 620, Library.STEAM_LOGOS))
File(cache, "730").mkdirs()
File(cache, "730/logo.png").writeBytes(ByteArray(0))
assertNull(Library.steamCacheImage(cache, 730, Library.STEAM_LOGOS))
}
@Test fun aChosenLogoWinsOverSteamsAndKeepsTheRest() {
val stock = image("logo.png")
val game = Library.SteamGame(620, "Portal 2", null, "Steam library", logo = stock)
assertTrue(SteamGameArt.withOverrides(app, game) === game)
val picked = image("mine.png")
assertTrue(SteamGameArt.choose(app, game, AddedGameArt.Slot.LOGO, AddedGameArt.Option(AddedGameArt.FILE, picked.path, picked.path)))
val shown = SteamGameArt.withOverrides(app, game)
assertTrue(shown.logo!!.name.startsWith("chosen-logo"))
assertNull(shown.art)
SteamGameArt.reset(app, game, AddedGameArt.Slot.LOGO)
assertEquals(stock, SteamGameArt.withOverrides(app, game).logo)
}
@Test fun anAddedGameShowsItsFolderLogoUnlessOneWasChosen() {
val dir = tmp.newFolder("Celeste")
val own = File(dir, "logo.png").apply { writeBytes(ByteArray(4) { 1 }) }
val exe = File(dir, "Celeste.exe").apply { writeText("x") }
val g = AddedGames.Game(dir, "Celeste", exe, "/g/Celeste.exe", "/g", 0x82000001L, 0x82000001L, emptyList(), source = "gog")
assertEquals(own, Library.addedGame(app, g, emptyList()).logo)
val picked = image("pick.png")
assertTrue(AddedGameArt.choose(app, g, AddedGameArt.Slot.LOGO, AddedGameArt.Option(AddedGameArt.FILE, picked.path, picked.path)))
assertTrue(Library.addedGame(app, g, emptyList()).logo!!.name.startsWith("chosen-logo"))
val bare = AddedGames.Game(tmp.newFolder("Bare"), "Bare", exe, "/g/Bare.exe", "/g", 0x82000002L, 0x82000002L, emptyList())
assertNull(Library.addedGame(app, bare, emptyList()).logo)
}
@Test fun theLibraryCacheKeepsTheLogoAndReadsOlderEntries() {
val logo = image("logo.png")
val game = Library.SteamGame(620, "Portal 2", null, "Steam library", logo = logo)
LibraryCache.save(app, listOf(game, Library.SteamGame(730, "CS2", null, "Steam library")))
val back = LibraryCache.load(app)
assertEquals(logo, back[0].logo)
assertNull(back[1].logo)
assertEquals(logo, game.withArt(null, null, null).logo)
val file = File(app.filesDir, "library-cache.json")
file.writeText(JSONArray().put(JSONObject().put("appId", 1).put("name", "Old").put("library", "x").put("gameId", 1L)).toString())
assertNull(LibraryCache.load(app).single().logo)
}
}
@@ -34,6 +34,17 @@ class StoreGameSidecarTest {
assertEquals("ns", back.extra["namespace"])
}
@Test fun theStoreLogoRoundTripsAndOlderFilesHaveNone() {
val withLogo = sample.copy(logo = "https://x/logo.png")
val back = StoreGameSidecar.parse(withLogo.toJson().toString())!!
assertEquals("https://x/logo.png", back.logo)
assertEquals("https://x/logo.png", back.copy(state = StoreGameSidecar.STATE_UPDATING).logo)
assertFalse(sample.toJson().has("logo"))
assertNull(StoreGameSidecar.parse(sample.toJson().toString())!!.logo)
assertNull(StoreGameSidecar.parse("""{"store":"gog","id":"1","title":"T","exe":"game.exe","cover":"c","hero":"h"}""")!!.logo)
assertNull(StoreGameSidecar.parse("""{"store":"gog","id":"1","title":"T","exe":"game.exe","logo":""}""")!!.logo)
}
@Test fun defaultsWhenFieldsAreAbsent() {
val back = StoreGameSidecar.parse("""{"store":"gog","id":"1","title":"T","exe":"bin\\game.exe","addToSteam":false}""")!!
assertEquals("bin/game.exe", back.exe)
@@ -0,0 +1,88 @@
package com.droiddeck.launcher.stores
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import com.droiddeck.launcher.stores.amazon.AmazonLibrary
import com.droiddeck.launcher.stores.gog.GogBackend
import org.json.JSONObject
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
import java.io.ByteArrayOutputStream
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
@GraphicsMode(GraphicsMode.Mode.NATIVE)
class StoreLogoTest {
@get:Rule val tmp = TemporaryFolder()
private fun encoded(format: Bitmap.CompressFormat): ByteArray {
val bmp = Bitmap.createBitmap(8, 4, Bitmap.Config.ARGB_8888)
bmp.eraseColor(Color.TRANSPARENT)
bmp.setPixel(1, 1, Color.RED)
return ByteArrayOutputStream().also { bmp.compress(format, 100, it) }.toByteArray()
}
@Test fun aPngLogoIsKeptAsItCameWithItsTransparency() {
val png = encoded(Bitmap.CompressFormat.PNG)
val dst = File(tmp.root, StoreArt.LOGO)
assertTrue(StoreArt.writeLogo(png, dst))
assertArrayEquals(png, dst.readBytes())
val back = BitmapFactory.decodeFile(dst.path)
assertEquals(0, Color.alpha(back.getPixel(0, 0)))
assertEquals(Color.RED, back.getPixel(1, 1))
assertFalse(File(dst.path + ".tmp").exists())
}
@Test fun anotherImageFormatIsStoredAsPng() {
val dst = File(tmp.root, StoreArt.LOGO)
assertTrue(StoreArt.writeLogo(encoded(Bitmap.CompressFormat.JPEG), dst))
val head = dst.readBytes().take(4)
assertEquals(listOf(0x89.toByte(), 'P'.code.toByte(), 'N'.code.toByte(), 'G'.code.toByte()), head)
assertEquals(8, BitmapFactory.decodeFile(dst.path).width)
}
@Test fun whatIsNotAnImageIsRefusedAndAnExistingLogoStays() {
val dst = File(tmp.root, StoreArt.LOGO)
assertFalse(StoreArt.writeLogo("<html>not found</html>".toByteArray(), dst))
assertFalse(dst.exists())
dst.writeBytes(byteArrayOf(1, 2, 3))
assertTrue(StoreArt.writeLogo(encoded(Bitmap.CompressFormat.PNG), dst))
assertArrayEquals(byteArrayOf(1, 2, 3), dst.readBytes())
assertTrue(StoreArt.fetchLogo(tmp.root, "https://invalid.example/logo.png"))
}
@Test fun gogTakesTheV2LogoLinkOnly() {
val v2 = JSONObject("""{"_links":{"logo":{"href":"https://images.gog-statics.com/abc_logo.png"},"galaxyBackgroundImage":{"href":"https://x/bg.jpg"}}}""")
assertEquals("https://images.gog-statics.com/abc_logo.png", GogBackend.logoOf(v2))
assertEquals("https://images.gog-statics.com/rel.png", GogBackend.logoOf(JSONObject("""{"_links":{"logo":{"href":"//images.gog-statics.com/rel.png"}}}""")))
assertNull(GogBackend.logoOf(JSONObject("""{"_links":{}}""")))
assertNull(GogBackend.logoOf(JSONObject("""{"images":{"logo2x":"https://x/glx_logo_2x.jpg"}}""")))
assertNull(GogBackend.logoOf(JSONObject("""{"_links":{"logo":{"href":"http://x/logo.png"}}}""")))
}
@Test fun amazonKeepsTheLogoFromTheLibraryAndItsCache() {
val app = RuntimeEnvironment.getApplication()
val fresh = AmazonLibrary.gameFrom(JSONObject().put("productId", "p").put("title", "Game").put("logo", "https://m/logo.png"), null)
assertEquals("https://m/logo.png", fresh.logoUrl)
assertEquals("https://m/logo.png", AmazonLibrary.toCatalogItem(app, fresh).logoUrl)
assertEquals(listOf(fresh), AmazonLibrary.fromCacheJson(AmazonLibrary.toCacheJson(listOf(fresh))))
val kept = AmazonLibrary.gameFrom(JSONObject().put("productId", "p").put("title", "Game"), fresh)
assertEquals("https://m/logo.png", kept.logoUrl)
val none = AmazonLibrary.gameFrom(JSONObject().put("productId", "q").put("title", "Other"), null)
assertNull(AmazonLibrary.toCatalogItem(app, none).logoUrl)
assertEquals("", AmazonLibrary.fromCacheJson("""[{"productId":"old","title":"Old"}]""").single().logoUrl)
}
}
@@ -83,6 +83,18 @@ class EpicLibraryTest {
assertEquals("Fig", EpicLibrary.gameFrom(record, null, null).title)
}
@Test fun theCatalogLogoIsKeptInTheCacheAndHandedToTheInstall() {
val record = JSONObject().put("appName", "Fig").put("namespace", "ns").put("catalogItemId", "cat")
val fresh = EpicLibrary.gameFrom(record, JSONObject().put("logo", "https://e/logo.png"), null)
assertEquals("https://e/logo.png", fresh.artLogo)
assertEquals("https://e/logo.png", EpicLibrary.gameFrom(record, JSONObject().put("title", "Fig"), fresh).artLogo)
assertEquals(listOf(fresh), EpicLibrary.fromCacheJson(EpicLibrary.toCacheJson(listOf(fresh))))
assertEquals("https://e/logo.png", EpicLibrary.toCatalogItem(app, fresh).logoUrl)
val plain = EpicGame("Old", "ns", "c", "Old")
assertFalse(JSONArray(EpicLibrary.toCacheJson(listOf(plain))).getJSONObject(0).has("artLogo"))
assertEquals(null, EpicLibrary.toCatalogItem(app, plain).logoUrl)
}
@Test fun signOutForgetsOnlyTheLibrary() {
EpicPrefs.get(app).edit().putString(EpicLibrary.KEY_CACHE, "[]").putLong(EpicLibrary.KEY_SYNCED_AT, 1L)
.putString("cloud_template_Fig", "{AppData}/x").commit()