Release Kaleido 0.4.1 with genre-led cards and unique category artwork
All checks were successful
Validate and publish Kaleido / android (push) Successful in 2m41s

This commit is contained in:
Elijah 2026-10-28 10:45:19 -07:00
parent a2c72704f5
commit eeebc9af38
13 changed files with 199 additions and 51 deletions

View file

@ -26,6 +26,8 @@ import androidx.compose.ui.geometry.Size
import androidx.compose.ui.focus.*
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.ColorMatrix
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.key.*
import androidx.compose.ui.text.font.FontWeight
@ -176,7 +178,8 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,
else if(vm.genres.isEmpty())EmptyState("No categories available","This Plex library has no genre categories.")
else {
val categoryRequesters=remember(vm.section?.id,vm.genres,categoryEntryFocus){vm.genres.mapIndexed{i,entry->entry.first to if(i==0)categoryEntryFocus else FocusRequester()}.toMap()}
LazyVerticalGrid(GridCells.Fixed(3),contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=18.dp,bottom=30.dp),horizontalArrangement=Arrangement.spacedBy(13.dp),verticalArrangement=Arrangement.spacedBy(12.dp),modifier=Modifier.fillMaxSize()) {
val categoryColor=remember{ColorFilter.colorMatrix(ColorMatrix().apply{setToSaturation(.65f)})}
LazyVerticalGrid(GridCells.Fixed(4),contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=18.dp,bottom=30.dp),horizontalArrangement=Arrangement.spacedBy(13.dp),verticalArrangement=Arrangement.spacedBy(13.dp),modifier=Modifier.fillMaxSize()) {
itemsIndexed(vm.genres,key={_,it->it.first}){index,entry->
val requester=categoryRequesters.getValue(entry.first)
val sample=vm.categoryArtwork[entry.first]
@ -184,21 +187,15 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,
var focused by remember(entry.first,vm.section?.id){mutableStateOf(false)}
val shape=RoundedCornerShape(Cinema.radius)
Box(Modifier.fillMaxWidth().aspectRatio(16f/9f).focusRequester(requester).focusProperties {
left=if(index%3==0)FocusRequester.Cancel else categoryRequesters.getValue(vm.genres[index-1].first)
right=if(index%3==2||index==vm.genres.lastIndex)FocusRequester.Cancel else categoryRequesters.getValue(vm.genres[index+1].first)
up=if(index<3)categoriesFocus else categoryRequesters.getValue(vm.genres[index-3].first)
down=if(index+3>=vm.genres.size)FocusRequester.Cancel else categoryRequesters.getValue(vm.genres[index+3].first)
}.onFocusChanged{focused=it.isFocused;if(it.isFocused)vm.focusId="category:${entry.first}"}.navigationSound().clip(shape).background(Color(0xFF171717)).border(1.dp,Color.White.copy(alpha=if(focused).9f else .09f),shape).clickable{vm.selectCategory(entry.first)}) {
if(artworkPath.isNotBlank())Artwork(vm.api,artworkPath,Modifier.fillMaxSize(),540,304)
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(listOf(Color.Black.copy(alpha=.08f),Color.Black.copy(alpha=.12f),Color.Black.copy(alpha=.9f)))))
Box(Modifier.align(Alignment.TopStart).padding(9.dp).background(Color.Black.copy(alpha=.6f),RoundedCornerShape(3.dp)).padding(horizontal=7.dp,vertical=4.dp)) {
Text(if(vm.section?.type=="movie")"FILM"else"SERIES",color=Color.White.copy(alpha=.88f),fontSize=8.sp,lineHeight=10.sp,fontWeight=FontWeight.SemiBold,letterSpacing=1.sp,maxLines=1)
}
Column(Modifier.align(Alignment.BottomStart).fillMaxWidth().padding(horizontal=17.dp,vertical=15.dp)) {
if(sample!=null)Text(sample.title,color=Color.White.copy(alpha=.78f),fontSize=11.sp,lineHeight=12.sp,fontWeight=FontWeight.Medium,maxLines=1,overflow=TextOverflow.Ellipsis)
Text(entry.second,color=Color.White,fontSize=16.sp,lineHeight=19.sp,fontWeight=FontWeight.SemiBold,maxLines=1,overflow=TextOverflow.Ellipsis)
}
if(focused)Box(Modifier.fillMaxSize().padding(3.dp).border(1.dp,Color.White.copy(alpha=.85f),shape))
left=if(index%4==0)FocusRequester.Cancel else categoryRequesters.getValue(vm.genres[index-1].first)
right=if(index%4==3||index==vm.genres.lastIndex)FocusRequester.Cancel else categoryRequesters.getValue(vm.genres[index+1].first)
up=if(index<4)categoriesFocus else categoryRequesters.getValue(vm.genres[index-4].first)
down=if(index+4>=vm.genres.size)FocusRequester.Cancel else categoryRequesters.getValue(vm.genres[index+4].first)
}.onFocusChanged{focused=it.isFocused;if(it.isFocused)vm.focusId="category:${entry.first}"}.navigationSound().clip(shape).background(Color(0xFF171717)).border(if(focused)2.dp else 1.dp,Color.White.copy(alpha=if(focused).9f else .1f),shape).clickable{vm.selectCategory(entry.first)}) {
if(artworkPath.isNotBlank())Artwork(vm.api,artworkPath,Modifier.fillMaxSize(),540,304,colorFilter=categoryColor)
Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha=if(focused).48f else .62f)))
Text(entry.second,color=Color.White,fontSize=22.sp,lineHeight=26.sp,fontWeight=FontWeight.SemiBold,maxLines=2,overflow=TextOverflow.Ellipsis,textAlign=androidx.compose.ui.text.style.TextAlign.Center,
style=LocalTextStyle.current.copy(shadow=androidx.compose.ui.graphics.Shadow(Color.Black,androidx.compose.ui.geometry.Offset(0f,1f),5f)),modifier=Modifier.align(Alignment.Center).fillMaxWidth().padding(horizontal=16.dp))
}
LaunchedEffect(vm.focusId,index){if((vm.focusId=="categories-entry"&&index==0)||vm.focusId=="category:${entry.first}"){withFrameNanos{};runCatching{requester.requestFocus()}}}
}

View file

@ -0,0 +1,29 @@
package tv.kaleido.app
/** Match genres to distinct artwork sources, moving an earlier choice when a later genre needs it. */
internal fun <T> selectCategoryArtwork(candidates:Map<String,List<T>>,identity:(T)->String):Map<String,T> {
val options=candidates.mapValues{(_,items)->items.filter{identity(it).isNotBlank()}.distinctBy(identity)}
val owners=mutableMapOf<String,String>()
val selected=mutableMapOf<String,T>()
fun assign(genre:String,visited:MutableSet<String>):Boolean {
// Keep preferred choices where possible; try free sources before moving another genre.
val choices=options.getValue(genre)
choices.firstOrNull{identity(it) !in owners&&identity(it) !in visited}?.let {
owners[identity(it)]=genre;selected[genre]=it;return true
}
for(item in choices) {
val key=identity(item)
if(!visited.add(key))continue
val previous=owners[key] ?: continue
if(assign(previous,visited)){owners[key]=genre;selected[genre]=item;return true}
}
return false
}
// Give narrow genres first choice, so a broad category cannot exhaust their only source.
options.keys.sortedBy{options.getValue(it).size}.forEach{assign(it,mutableSetOf())}
return candidates.keys.mapNotNull{genre->selected[genre]?.let{genre to it}}.toMap()
}
/** Plex timestamps/query strings do not make a refreshed image a different artwork source. */
private val artworkVersion=Regex("(/(?:art|thumb))/[0-9]+$")
internal fun categoryArtworkIdentity(path:String):String = path.substringBefore('?').replace(artworkVersion,"\$1")

View file

@ -126,6 +126,8 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
private var categoryArtworkJob: Job? = null
private var categoryArtworkSectionId = ""
private var categoryArtworkGeneration = 0
private var categoryArtworkGenres=emptyList<Pair<String,String>>()
private var categoryArtworkComplete=false
private val detailsCache = mutableMapOf<String,Title>()
private val sectionCache=mutableMapOf<String,SectionContent>()
private val characterOffsetCache=mutableMapOf<LibraryCharacterQuery,Map<String,Int>>()
@ -272,6 +274,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
categoryArtworkJob?.cancel();categoryArtworkJob=null
categoryArtworkSectionId=sectionId.orEmpty()
categoryArtwork=emptyMap()
categoryArtworkGenres=emptyList();categoryArtworkComplete=false
}
override fun onCleared(){cancelAnticipation();artworkPrefetchDispatcher.close();super.onCleared()}
fun linkAccount() {
@ -421,38 +424,84 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
fun loadCategoryArtworks() {
val selectedSection=section ?: return
if(!categories||genre.isNotBlank()||genres.isEmpty())return
if(categoryArtworkSectionId!=selectedSection.id)resetCategoryArtwork(selectedSection.id)
val localSamples=genres.mapNotNull{entry->
val hint=categoryArtworkHint(selectedSection,entry.second)
val sample=library.firstOrNull{item->
item.type==selectedSection.type&&item.genres.any{it.equals(entry.second,ignoreCase=true)}&&
item.artworkPath().isNotBlank()&&(hint==null||item.title.contains(hint,ignoreCase=true))
}
sample?.let{entry.first to it}
}.toMap()
if(localSamples.isNotEmpty())categoryArtwork=categoryArtwork+localSamples
val missing=genres.filter{entry->entry.first !in categoryArtwork}
if(missing.isEmpty()||categoryArtworkJob?.isActive==true)return
if(categoryArtworkSectionId!=selectedSection.id||categoryArtworkGenres!=genres)resetCategoryArtwork(selectedSection.id)
categoryArtworkGenres=genres.toList()
if(categoryArtworkComplete||categoryArtworkJob?.isActive==true)return
val sectionId=selectedSection.id
val sectionType=selectedSection.type
val generation=categoryArtworkGeneration
val entries=genres.toList()
fun ordered(entry:Pair<String,String>,items:List<Title>):List<Title> {
val hint=categoryArtworkHint(selectedSection,entry.second)
return items.filter{it.type==sectionType&&it.artworkPath().isNotBlank()}.distinctBy{it.id}
.sortedBy{if(hint!=null&&it.title.contains(hint,ignoreCase=true))0 else 1}
}
val candidates=entries.associate{entry->entry.first to ordered(entry,library.filter{item->item.genres.any{it.equals(entry.second,ignoreCase=true)}})}.toMutableMap()
fun choose()=selectCategoryArtwork(candidates){categoryArtworkIdentity(it.artworkPath())}
// The initial cached samples follow the same uniqueness rule as network results.
if(categoryArtwork.isEmpty())categoryArtwork=choose()
categoryArtworkJob=viewModelScope.launch {
val requestGate=Semaphore(3)
coroutineScope {
missing.map{entry->async {
val offsets=mutableMapOf<String,Int>()
val totals=mutableMapOf<String,Int>()
var failed=false
fun current()=generation==categoryArtworkGeneration&&categoryArtworkSectionId==sectionId&&section?.id==sectionId
suspend fun fetch(batch:List<Pair<String,String>>,first:Boolean=false) {
val pages=coroutineScope {batch.map{entry->async {
requestGate.withPermit {
val hint=categoryArtworkHint(selectedSection,entry.second)
val results=try {
api.library(sectionId,sort="titleSort:asc",genre=entry.first,size=if(hint!=null)80 else 12,type=plexLibraryType(sectionType)).items
}catch(e:CancellationException){throw e}catch(_:Exception){emptyList()}
val matching=results.filter{it.type==sectionType}
val sample=matching.firstOrNull{hint!=null&&it.title.contains(hint,ignoreCase=true)&&it.artworkPath().isNotBlank()}
?:matching.firstOrNull{it.artworkPath().isNotBlank()}
if(sample!=null&&generation==categoryArtworkGeneration&&categoryArtworkSectionId==sectionId&&section?.id==sectionId)
categoryArtwork=categoryArtwork+(entry.first to sample)
entry to try {
api.library(sectionId,start=offsets[entry.first] ?: 0,sort="titleSort:asc",genre=entry.first,size=if(first&&hint!=null)80 else 32,type=plexLibraryType(sectionType))
}catch(e:CancellationException){throw e}catch(_:Exception){null}
}
}}.awaitAll()
}}.awaitAll()}
for((entry,page) in pages) {
if(page==null){failed=true;totals[entry.first]=offsets[entry.first] ?: 0;continue}
offsets[entry.first]=(offsets[entry.first] ?: 0)+page.items.size
totals[entry.first]=if(page.items.isEmpty())offsets.getValue(entry.first)else page.total
candidates[entry.first]=ordered(entry,candidates[entry.first].orEmpty()+page.items)
}
}
fetch(entries,first=true)
if(!current())return@launch
var chosen=choose()
categoryArtwork=chosen
// Expand only overlapping candidate groups that could free a missing genre.
while(chosen.size<entries.size) {
val needed=(entries.map{it.first}-chosen.keys).toMutableSet()
var expanded=true
while(expanded) {
val count=needed.size
val sources=needed.flatMap{candidates[it].orEmpty()}.map{categoryArtworkIdentity(it.artworkPath())}.toSet()
candidates.forEach{(genre,items)->if(items.any{categoryArtworkIdentity(it.artworkPath()) in sources})needed+=genre}
expanded=needed.size>count
}
val more=entries.filter{it.first in needed&&(offsets[it.first] ?: 0)<(totals[it.first] ?: 0)}
if(more.isEmpty())break
fetch(more)
if(!current())return@launch
chosen=choose();categoryArtwork=chosen
}
if(chosen.size<entries.size) {
// Some Plex genres are aliases with only one shared title. Preserve the
// distinct-title assignment and give remaining genres different landscape art.
val remaining=entries.filter{it.first !in chosen}
val used=chosen.values.map{categoryArtworkIdentity(it.artworkPath())}.toSet()
val alternatives=coroutineScope {remaining.map{entry->async {
val variants=mutableListOf<Title>()
for(item in candidates[entry.first].orEmpty()) {
val paths=try {requestGate.withPermit{api.categoryArtAlternatives(item.id)}}
catch(e:CancellationException){throw e}catch(_:Exception){failed=true;emptyList()}
variants+=paths.filter{categoryArtworkIdentity(it) !in used}.map{item.copy(art=it)}
if(variants.size>=remaining.size)break
}
entry.first to variants
}}.awaitAll().toMap()}
if(!current())return@launch
chosen=chosen+selectCategoryArtwork(alternatives){categoryArtworkIdentity(it.artworkPath())}
categoryArtwork=chosen
}
categoryArtworkComplete=!failed
}
}
fun selectCategory(value:String){if(value.isBlank())return;categories=true;allTitles=true;genre=value;sort="titleSort:asc";focusId="category-grid";libraryJumpIndex=-1;libraryJumpLetter=null;refreshLibrary()}

View file

@ -75,6 +75,11 @@ class PlexApi(val clientId: String) {
val seasons=container("/library/sections/$section/all",mapOf("type" to "3","sort" to "addedAt:desc","X-Plex-Container-Size" to "100")).optJSONArray("Metadata").objects().map(Title::parse)
groupRecentSeasons(seasons,::details)
}
/** Alternative landscape art, used when two narrow genres only contain the same title. */
suspend fun categoryArtAlternatives(id:String):List<String> = container("/library/metadata/$id/arts")
.optJSONArray("Metadata").objects().filterNot{it.optBoolean("selected")}
.map{it.optString("key")}.filter{it.startsWith('/')||it.startsWith("https://")}.distinct()
suspend fun library(section: String, start: Int = 0, sort: String = "titleSort:asc", genre: String = "", unwatched: Boolean = false, size:Int=100, type:String=""): LibraryPage = withContext(Dispatchers.Default){
val p=mutableMapOf("X-Plex-Container-Start" to start.toString(),"X-Plex-Container-Size" to size.coerceAtLeast(1).toString(),"sort" to sort)
p.putAll(libraryFilterParameters(genre,unwatched,type))

View file

@ -49,12 +49,12 @@ import androidx.compose.ui.node.ModifierNodeElement
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
import java.io.File
@Composable fun Artwork(api: PlexApi,path: String,modifier: Modifier=Modifier,width: Int=600,height: Int=900,animate:Boolean=true,contentScale:ContentScale=ContentScale.Crop) {
@Composable fun Artwork(api: PlexApi,path: String,modifier: Modifier=Modifier,width: Int=600,height: Int=900,animate:Boolean=true,contentScale:ContentScale=ContentScale.Crop,colorFilter:androidx.compose.ui.graphics.ColorFilter?=null) {
val context=LocalContext.current
// The server already scales to width × height. Stating that size lets Coil resolve cache
// hits while composing, instead of each painter waiting for layout to measure it.
val model=remember(path,api.session?.server,width,height,animate){api.image(path,width,height)?.let {u -> ImageRequest.Builder(context).data(u).apply {api.headers().forEach{(k,v)->addHeader(k,v)}}.size(width,height).precision(Precision.INEXACT).crossfade(if(animate)180 else 0).build()}}
AsyncImage(model=model,contentDescription=null,contentScale=contentScale,modifier=modifier.background(Panel))
AsyncImage(model=model,contentDescription=null,contentScale=contentScale,colorFilter=colorFilter,modifier=modifier.background(Panel))
}
@Composable fun KaleidoApp(vm: KaleidoViewModel,install: (File)->Unit) {
KaleidoTheme {

View file

@ -0,0 +1,55 @@
package tv.kaleido.app
import org.junit.Assert.*
import org.junit.Assume.assumeTrue
import org.junit.Test
import java.io.File
class CategoryArtworkTest {
@Test fun overlappingGenresUseDifferentShows() {
val chosen=selectCategoryArtwork(linkedMapOf("Adventure" to listOf("Adventure Time","Silo"),"Children" to listOf("Adventure Time","Bluey"))){it}
assertEquals(2,chosen.values.toSet().size)
assertEquals("Adventure Time",chosen["Adventure"])
assertEquals("Bluey",chosen["Children"])
}
@Test fun narrowGenresKeepTheirOnlySource() {
val chosen=selectCategoryArtwork(linkedMapOf("Action" to listOf("Shared","Action only"),"Children" to listOf("Shared"))){it}
assertEquals(mapOf("Action" to "Action only","Children" to "Shared"),chosen)
}
@Test fun unavailableUniqueSourcesNeverProduceDuplicates() {
val chosen=selectCategoryArtwork(mapOf("A" to listOf("Same","Same"),"B" to listOf("Same"),"Empty" to listOf(""))){it}
assertEquals(1,chosen.size)
assertEquals(1,chosen.values.toSet().size)
assertFalse(chosen.containsKey("Empty"))
assertEquals("/library/metadata/12/art",categoryArtworkIdentity("/library/metadata/12/art/123?cache=1"))
}
@Test fun matchingFindsEveryAvailableAssignmentInSmallOverlappingCatalogs() {
// Exhaust all 512 three-genre/three-source graphs against a brute-force reference.
for(mask in 0 until 512) {
val candidates=(0..2).associate{i->i.toString() to (0..2).filter{j->mask and (1 shl (i*3+j))!=0}.map(Int::toString)}
fun maximum(index:Int,used:Set<String>):Int = if(index==3)0 else maxOf(
maximum(index+1,used),candidates.getValue(index.toString()).filter{it !in used}.maxOfOrNull{1+maximum(index+1,used+it)} ?: 0)
val selected=selectCategoryArtwork(candidates){it}
assertEquals("catalog $mask",maximum(0,emptySet()),selected.size)
assertEquals(selected.size,selected.values.toSet().size)
}
}
@Test fun realPlexCategoryCandidatesHaveCompleteUniqueAssignments() {
val path=System.getenv("KALEIDO_CATEGORY_FIXTURE")
assumeTrue("Optional private, read-only Plex fixture",!path.isNullOrBlank())
val rows=File(path!!).readLines().map{it.split('\t',limit=5)}
for((kind,section) in rows.groupBy{it[0]}) {
val candidates=section.groupBy{it[1]}.mapValues{(_,items)->items}
val selected=selectCategoryArtwork(candidates){categoryArtworkIdentity(it[3])}
assertEquals("Every $kind category needs artwork",candidates.size,selected.size)
val distinctTitles=selectCategoryArtwork(candidates){it[2]}.size
assertEquals("Use as many distinct titles as the library allows",distinctTitles,selected.values.map{it[2]}.toSet().size)
assertEquals(selected.size,selected.values.map{categoryArtworkIdentity(it[3])}.toSet().size)
println("PASS $kind: ${selected.size} distinct backgrounds from $distinctTitles different titles")
}
}
}