Release Kaleido 0.1.8 with cast browsing and refreshed title pages
All checks were successful
Validate and publish Kaleido / android (push) Successful in 2m8s

This commit is contained in:
Elijah 2026-10-25 21:49:24 -07:00
parent 119f1ae5a9
commit 5199bb0928
28 changed files with 982 additions and 187 deletions

View file

@ -6,3 +6,5 @@ HPLtv/kaleido/app/DiscoveryScreensKt**->**(**)**
HPLtv/kaleido/app/ThemeKt**->**(**)**
HPLtv/kaleido/app/NavigationSoundsKt**->**(**)**
HPLtv/kaleido/app/NavigationSoundController;->**(**)**
HPLtv/kaleido/app/TitleDetailsKt**->**(**)**
HPLtv/kaleido/app/SettingsScreenKt**->**(**)**

View file

@ -72,16 +72,16 @@ import kotlinx.coroutines.delay
}
}
@Composable fun MediaRow(vm:KaleidoViewModel,title:String,items:List<Title>,rowId:String,landscape:Boolean=false,subtitle:String?=null) {
@Composable fun MediaRow(vm:KaleidoViewModel,title:String,items:List<Title>,rowId:String,landscape:Boolean=false,subtitle:String?=null,entryFocus:FocusRequester?=null) {
Column {
Box(Modifier.padding(horizontal=Cinema.gutter)){SectionHeading(title,subtitle)}
LazyRow(contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=5.dp,bottom=5.dp),horizontalArrangement=Arrangement.spacedBy(if(landscape)13.dp else 12.dp),modifier=Modifier.focusRestorer()) {
itemsIndexed(items,key={_,it->it.id}){index,item->MediaTile(vm,item,"$rowId:${item.id}",landscape,onMove={anticipateTileMove(vm,items,index,it,0)})}
itemsIndexed(items,key={_,it->it.id}){index,item->MediaTile(vm,item,"$rowId:${item.id}",landscape,modifier=if(index==0&&entryFocus!=null)Modifier.focusRequester(entryFocus)else Modifier,onMove={anticipateTileMove(vm,items,index,it,0)})}
}
}
}
private fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,direction:Key,columns:Int) {
internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,direction:Key,columns:Int) {
val target=when(direction){
Key.DirectionLeft->if(columns==0||index%columns>0)index-1 else -1
Key.DirectionRight->if(columns==0||index%columns<columns-1)index+1 else -1
@ -92,12 +92,12 @@ private fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,d
items.getOrNull(target)?.let{vm.anticipate(it,backdrop=false)}
}
@Composable fun MediaTile(vm:KaleidoViewModel,item:Title,focusKey:String,landscape:Boolean=false,fillWidth:Boolean=false,onMove:(Key)->Unit={}) {
@Composable fun MediaTile(vm:KaleidoViewModel,item:Title,focusKey:String,landscape:Boolean=false,fillWidth:Boolean=false,initialFocus:Boolean=false,modifier:Modifier=Modifier,onMove:(Key)->Unit={}) {
var focused by remember{mutableStateOf(false)}
val requester=remember{FocusRequester()}
val scale by animateFloatAsState(if(focused)1.035f else 1f,tween(180),label="artworkFocus")
LaunchedEffect(Unit){if(vm.focusId==focusKey){delay(220);runCatching{requester.requestFocus()}}}
Column((if(fillWidth)Modifier.fillMaxWidth()else Modifier.width(if(landscape)216.dp else 132.dp)).onPreviewKeyEvent{if(it.type==KeyEventType.KeyDown)onMove(it.key);false}.graphicsLayer{scaleX=scale;scaleY=scale}.focusRequester(requester).navigationSound().onFocusChanged{focused=it.isFocused;if(it.isFocused)vm.focusId=focusKey}.clickable{vm.open(item)}) {
LaunchedEffect(Unit){if(vm.focusId==focusKey||initialFocus){delay(220);runCatching{requester.requestFocus()}}}
Column(modifier.then(if(fillWidth)Modifier.fillMaxWidth()else Modifier.width(if(landscape)216.dp else 132.dp)).onPreviewKeyEvent{if(it.type==KeyEventType.KeyDown)onMove(it.key);false}.graphicsLayer{scaleX=scale;scaleY=scale}.focusRequester(requester).navigationSound().onFocusChanged{focused=it.isFocused;if(it.isFocused)vm.focusId=focusKey}.clickable{vm.open(item)}) {
Box(Modifier.fillMaxWidth().aspectRatio(if(landscape)16f/9f else 2f/3f).graphicsLayer{shadowElevation=if(focused)12.dp.toPx()else 0f;shape=RoundedCornerShape(Cinema.radius)}.clip(RoundedCornerShape(Cinema.radius))) {
val artwork=if(landscape&&item.type=="episode")item.thumb.ifBlank{item.art}else if(landscape)item.art.ifBlank{item.thumb}else item.thumb
Artwork(vm.api,artwork,Modifier.fillMaxSize(),if(landscape)720 else 450,if(landscape)405 else 675)
@ -154,37 +154,6 @@ private fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,d
if(sectionMenu){val options=vm.sections.filter{it.type==vm.section?.type};ChoiceDialog("Libraries",options.map{it.title},options.indexOf(vm.section),{sectionMenu=false}){vm.chooseSection(options[it]);sectionMenu=false}}
}
@Composable fun DetailsScreen(vm:KaleidoViewModel) {
val item=vm.detail ?: return
LazyColumn(contentPadding=PaddingValues(bottom=32.dp),verticalArrangement=Arrangement.spacedBy(15.dp),modifier=Modifier.fillMaxSize()) {
item(key="details") {
Box(Modifier.fillMaxWidth().height(if(item.type in listOf("movie","episode"))432.dp else 304.dp)) {
Artwork(vm.api,item.art,Modifier.fillMaxSize(),1920,1080)
Box(Modifier.fillMaxSize().background(Brush.horizontalGradient(listOf(Ink.copy(alpha=.98f),Ink.copy(alpha=.83f),Ink.copy(alpha=.05f)))))
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(0f to Color.Black.copy(alpha=.12f),.5f to Color.Transparent,1f to Ink)))
IconControl(Icons.AutoMirrored.Outlined.ArrowBack,"Back",modifier=Modifier.padding(start=36.dp,top=18.dp)){vm.back()}
Column(Modifier.align(Alignment.CenterStart).padding(start=Cinema.gutter,top=30.dp).width(490.dp)) {
if(item.type=="episode")Text(item.grandparentTitle,color=Cinema.secondary,fontSize=12.sp,lineHeight=17.sp,fontWeight=FontWeight.Medium)
Text(item.title,color=Accent,fontSize=34.sp,lineHeight=37.sp,fontWeight=FontWeight.Bold,letterSpacing=(-1).sp,maxLines=2,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(bottom=9.dp))
Row(Modifier.fillMaxWidth(),verticalAlignment=Alignment.CenterVertically) {
Text(listOf(item.subtitle,item.contentRating).filter{it.isNotBlank()}.joinToString(" · "),color=Muted,fontSize=10.5.sp,lineHeight=16.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f,fill=false))
AudienceRatings(item,Modifier.padding(start=12.dp))
}
Text(item.summary,color=Cinema.secondary,fontSize=12.5.sp,lineHeight=19.sp,maxLines=if(item.type in listOf("movie","episode"))4 else 3,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=11.dp,bottom=18.dp))
if(item.type!="collection")Row(horizontalArrangement=Arrangement.spacedBy(8.dp)) {
ActionButton(if(item.offset>0)"Resume · ${item.offset/60000} min"else if(item.type=="show")"Watch next"else "Play",Icons.Filled.PlayArrow,primary=true,initialFocus=true){vm.play(item)}
if(item.offset>0)ActionButton("Start over",Icons.Outlined.Replay){vm.play(item,true)}
if(item.type in listOf("movie","episode"))IconControl(if(item.isWatched(vm.watchedPercent))Icons.Outlined.CheckCircle else Icons.Outlined.Check,"Mark ${if(item.isWatched(vm.watchedPercent))"unwatched"else "watched"}",selected=item.isWatched(vm.watchedPercent)){vm.mark(item)}
}
if(item.media.isNotEmpty())Text(item.media.first().let{m->listOf(m.resolution.uppercase(),m.videoCodec.uppercase(),m.audioCodec.uppercase()).joinToString(" · ")},color=Muted,fontSize=9.sp,lineHeight=13.sp,modifier=Modifier.padding(top=16.dp))
if(item.cast.isNotEmpty())Text(item.cast.take(5).joinToString(" · "),color=Cinema.quiet,fontSize=10.sp,lineHeight=15.sp,maxLines=2,modifier=Modifier.padding(top=8.dp))
}
}
}
if(vm.children.isNotEmpty())item{MediaRow(vm,if(item.type=="show")"Seasons"else if(item.type=="season")"Episodes"else "In this collection",vm.children,"children:${item.id}",landscape=item.type=="season")}
}
}
@Composable fun SearchScreen(vm:KaleidoViewModel) {
Column(Modifier.fillMaxSize().padding(horizontal=Cinema.gutter)) {
Row(Modifier.fillMaxWidth().padding(top=12.dp,bottom=18.dp),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(25.dp)) {

View file

@ -21,7 +21,7 @@ import coil.request.Disposable
import java.util.concurrent.Executors
import kotlinx.coroutines.asCoroutineDispatcher
data class Page(val kind: String="home",val id: String="",val name: String="",val returnFocus: String="")
data class Page(val kind: String="home",val id: String="",val name: String="",val returnFocus: String="",val actor:CastMember?=null)
private data class SectionContent(val hubs:List<Hub>,val genres:List<Pair<String,String>>,val library:LibraryPage)
class KaleidoViewModel(app: Application): AndroidViewModel(app) {
val application = app as KaleidoApplication
@ -47,6 +47,9 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
var allTitles by mutableStateOf(false); private set
var detail by mutableStateOf<Title?>(null); private set
var children by mutableStateOf(emptyList<Title>()); private set
var detailRelated by mutableStateOf(emptyList<Title>()); private set
var actorTitles by mutableStateOf(emptyList<Title>()); private set
var markingId by mutableStateOf<String?>(null); private set
var searchResults by mutableStateOf(emptyList<Title>()); private set
var query by mutableStateOf(""); private set
var pin by mutableStateOf<Pin?>(null); private set
@ -174,6 +177,10 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
fun switchServer()=launchLoad { require(accountToken.isNotBlank()){ "This connection uses a server token. Sign out to link a Plex account." };servers=api.servers(accountToken) }
fun tab(kind: String){if(pages.size==1&&page.kind==kind)return;cancelAnticipation();loadJob?.cancel();busy=false;focusId="";if(kind in listOf("movies","tv"))allTitles=false;pages=listOf(Page(kind));loadPage(true)}
fun open(item: Title){detailsCache[item.id]=item;pages=pages+Page(if(item.type in listOf("collection","season")) "group" else "details",item.id,item.title,focusId);loadPage()}
fun openActor(actor:CastMember){
if(actor.id.isBlank())return
pages=pages+Page("actor",actor.id,actor.name,focusId,actor);focusId="";loadPage()
}
fun back(): Boolean {
if(playing!=null){stopPlayback();return true}
if(pages.size>1){focusId=page.returnFocus;pages=pages.dropLast(1);loadPage();return true}
@ -202,7 +209,23 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
discoverHubs=rows;genres=genreList;library=p.items;total=p.total
}}
}
"details","group" -> { detail=detailsCache[page.id];children=emptyList();launchLoad { val id=page.id;val d=detailsCache[id]?.let{previews.details(it)} ?: api.details(id);detail=d;detailsCache[id]=d;previews.remember(d);if(d.type in listOf("show","season","collection"))children=api.children(id) } }
"details","group" -> {
detail=detailsCache[page.id];children=emptyList();detailRelated=emptyList()
launchLoad {
val id=page.id;val d=detailsCache[id]?.let{previews.details(it)} ?: api.details(id)
detail=d;detailsCache[id]=d;previews.remember(d)
coroutineScope {
val groups=async{if(d.type in listOf("show","season","collection"))api.children(id)else emptyList()}
val related=async{if(d.type=="show")try{api.relatedShows(id).filter{it.id!=id}}catch(e:CancellationException){throw e}catch(_:Exception){emptyList()}else emptyList()}
children=groups.await();detailRelated=related.await()
}
}
}
"actor" -> {
val actor=page.actor ?: return
actorTitles=emptyList()
launchLoad {actorTitles=api.actorTitles(actor,sections)}
}
"search" -> {busy=false;error=null}
"settings" -> {busy=false;error=null}
}
@ -213,22 +236,44 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
private fun refreshLibrary()=launchLoad { val p=api.library(section?.id ?: return@launchLoad,0,sort,genre,unwatched);library=p.items;total=p.total }
fun more(){if(busy||library.size>=total)return;launchLoad {val p=api.library(section?.id ?: return@launchLoad,library.size,sort,genre,unwatched);library=(library+p.items).distinctBy {it.id};total=p.total}}
fun search(text: String){query=text;searchJob?.cancel();searchJob=viewModelScope.launch {delay(350);if(text.isBlank()){searchResults=emptyList();return@launch};busy=true;error=null;try{searchResults=api.search(text)}catch(e:CancellationException){throw e}catch(e:Exception){error=e.message}finally{busy=false}}}
fun mark(item: Title)=launchLoad {
api.watched(item,!item.isWatched(watchedPercent));refreshWatchedItems(item)
fun mark(item: Title) {
if(markingId!=null)return
markingId=item.id
// A navigation request must not cancel an already submitted Plex watched write.
viewModelScope.launch {
try {
api.watched(item,!item.isWatched(watchedPercent));refreshWatchedItems(item)
homeHubs=loadHome()
}catch(e:CancellationException){throw e}catch(e:Exception){error=e.message ?: "Plex could not update this title."}finally{markingId=null}
}
}
fun refreshWatched(item:Title){viewModelScope.launch{try{refreshWatchedItems(item)}catch(e:CancellationException){throw e}catch(_:Exception){sectionCache.clear();detailsCache.clear();previews.clear();cancelAnticipation()}}}
private suspend fun refreshWatchedItems(item:Title) {
val d=api.details(item.id)
val updated=mutableMapOf(d.id to d)
if(d.type in listOf("show","season")) {
api.children(d.id).forEach{updated[it.id]=it}
api.allEpisodes(d.id).forEach{updated[it.id]=it}
}
if(d.type=="episode")for(id in listOf(d.parentId,d.grandparentId).filter{it.isNotBlank()}) {
try{updated[id]=api.details(id)}catch(e:CancellationException){throw e}catch(_:Exception){detailsCache.remove(id)}
}
previews.clear();updated.values.forEach{previews.remember(it)};detailsCache.putAll(updated);detail=detail?.let{updated[it.id] ?: it}
fun refreshed(hubs:List<Hub>)=hubs.map{h->h.copy(items=h.items.map{updated[it.id] ?: it})}
// Only /metadata details are complete; children/allLeaves are summary records.
// Merge their watched fields without poisoning full metadata/cast caches.
val fullIds=if(d.type=="episode")setOf(d.id,d.parentId,d.grandparentId)else setOf(d.id)
fun refreshedTitle(existing:Title):Title {
val fresh=updated[existing.id] ?: return existing
return if(existing.id in fullIds)fresh else existing.copy(watched=fresh.watched,offset=fresh.offset,leafCount=fresh.leafCount,viewedLeafCount=fresh.viewedLeafCount)
}
previews.clear();updated.keys.forEach{detailsCache.remove(it)}
updated.filterKeys{it in fullIds}.values.forEach{previews.remember(it);detailsCache[it.id]=it}
detail=detail?.let(::refreshedTitle)
fun refreshed(hubs:List<Hub>)=hubs.map{h->h.copy(items=h.items.map(::refreshedTitle))}
homeHubs=refreshed(homeHubs);discoverHubs=refreshed(discoverHubs)
library=library.map{updated[it.id] ?: it};children=children.map{updated[it.id] ?: it}
searchResults=searchResults.map{updated[it.id] ?: it}
homeFeatures=homeFeatures.map{it.copy(item=updated[it.item.id] ?: it.item)}.filterNot{it.item.fullyWatched}
library=library.map(::refreshedTitle);children=children.map(::refreshedTitle)
searchResults=searchResults.map(::refreshedTitle)
actorTitles=actorTitles.map(::refreshedTitle);detailRelated=detailRelated.map(::refreshedTitle)
homeFeatures=homeFeatures.map{it.copy(item=refreshedTitle(it.item))}.filterNot{it.item.fullyWatched}
sectionCache.clear()
}
fun play(item: Title,fromStart: Boolean=false)=launchLoad {

View file

@ -10,6 +10,11 @@ data class Part(val id: String, val key: String, val streams: List<Stream>,val i
data class Media(val id: String, val container: String, val videoCodec: String, val audioCodec: String, val resolution: String, val width: Int, val height: Int, val bitrate: Int, val parts: List<Part>)
data class Marker(val type: String, val start: Long, val end: Long)
data class Chapter(val index:Int,val title:String,val start:Long,val end:Long,val thumb:String)
data class CastMember(val id:String,val name:String,val role:String,val thumb:String) {
companion object {
fun parse(j:JSONObject)=CastMember(j.optString("id").ifBlank{j.optString("filter").removePrefix("actor=")}.takeIf{it.all(Char::isDigit)}.orEmpty(),j.optString("tag"),j.optString("role"),j.optString("thumb"))
}
}
data class Title(
val id: String, val key: String, val type: String, val title: String, val summary: String,
val thumb: String, val art: String, val year: String, val duration: Long, val offset: Long,
@ -18,7 +23,8 @@ data class Title(
val index: Int, val parentIndex: Int, val leafCount: Int, val viewedLeafCount: Int,
val genres: List<String>, val cast: List<String>, val media: List<Media>, val markers: List<Marker>,
val logo: String = "", val poster: String = "", val still: String = "",val chapters:List<Chapter> = emptyList(),
val audienceScore: AudienceScore? = null, val releaseDate: String = "",val audienceScores:List<AudienceScore> = emptyList()
val audienceScore: AudienceScore? = null, val releaseDate: String = "",val audienceScores:List<AudienceScore> = emptyList(),
val castMembers:List<CastMember> = emptyList()
) {
val remainingEpisodes get() = (leafCount-viewedLeafCount).coerceAtLeast(0)
val fullyWatched get() = isWatched()
@ -45,7 +51,8 @@ data class Title(
j.optJSONArray("Image").objects().firstOrNull{it.optString("type")=="coverPoster"}?.optString("url").orEmpty(),
j.optJSONArray("Image").objects().firstOrNull{it.optString("type")=="snapshot"}?.optString("url").orEmpty(),
j.optJSONArray("Chapter").objects().map{Chapter(it.optInt("index"),it.optString("title","Chapter ${it.optInt("index")+1}"),it.optLong("startTimeOffset"),it.optLong("endTimeOffset"),it.optString("thumb"))},
AudienceScore.parse(j),j.optString("originallyAvailableAt"),AudienceScore.parseAll(j)
AudienceScore.parse(j),j.optString("originallyAvailableAt"),AudienceScore.parseAll(j),
j.optJSONArray("Role").objects().map(CastMember::parse).filter{it.name.isNotBlank()}.distinctBy{it.id.ifBlank{it.name}}
)
}
}

View file

@ -77,15 +77,28 @@ class PlexApi(val clientId: String) {
LibraryPage(d.optJSONArray("Metadata").objects().map(Title::parse),d.optInt("totalSize",d.optInt("size")))
}
suspend fun genres(section: String): List<Pair<String,String>> = container("/library/sections/$section/genre").optJSONArray("Directory").objects().map { it.optString("key") to it.optString("title") }
suspend fun details(id: String): Title = container("/library/metadata/$id",mapOf("includeMarkers" to "1","includeChapters" to "1","includeExtras" to "1")).optJSONArray("Metadata").objects().firstOrNull()?.let(Title::parse) ?: throw PlexException("This title is unavailable.")
suspend fun relatedShows(id:String):List<Title> = container("/library/metadata/$id/related").optJSONArray("Hub").objects().flatMap{it.optJSONArray("Metadata").objects()}.map(Title::parse).filter{it.type=="show"}.distinctBy{it.id}
suspend fun details(id: String): Title = withContext(Dispatchers.Default){container("/library/metadata/$id",mapOf("includeMarkers" to "1","includeChapters" to "1","includeExtras" to "1")).optJSONArray("Metadata").objects().firstOrNull()?.let(Title::parse) ?: throw PlexException("This title is unavailable.")}
suspend fun relatedShows(id:String):List<Title> = withContext(Dispatchers.Default){container("/library/metadata/$id/related").optJSONArray("Hub").objects().flatMap{it.optJSONArray("Metadata").objects()}.map(Title::parse).filter{it.type=="show"}.distinctBy{it.id}}
/** Actor tags are server-local. Query each accessible movie/show library, with pagination. */
suspend fun actorTitles(actor:CastMember,sections:List<Section>):List<Title> = coroutineScope {
require(actor.id.isNotBlank()){"This cast member has no Plex library identifier."}
sections.filter{it.type in listOf("movie","show")}.map { section->async {
val found=mutableListOf<Title>();var start=0
do {
val data=container("/library/sections/${section.id}/all",mapOf("actor" to actor.id,"sort" to "titleSort:asc","X-Plex-Container-Start" to start.toString(),"X-Plex-Container-Size" to "100"))
val batch=withContext(Dispatchers.Default){data.optJSONArray("Metadata").objects().map(Title::parse)}
found.addAll(batch.filter{it.type in listOf("movie","show")});start+=batch.size
}while(batch.isNotEmpty()&&start<data.optInt("totalSize",start))
found
}}.awaitAll().flatten().distinctBy{it.id}.sortedBy{it.title.lowercase(java.util.Locale.ROOT)}
}
fun previewPath(item:Title,time:Long):String? {
val part=item.media.firstOrNull()?.parts?.firstOrNull()
if(part!=null&&part.indexes.split(',').contains("sd"))return "/library/parts/${part.id}/indexes/sd/${time.coerceAtLeast(0)/5000*5000}"
return item.chapters.lastOrNull{it.start<=time}?.thumb?.takeIf{it.isNotBlank()}
}
suspend fun children(id: String): List<Title> = container("/library/metadata/$id/children").optJSONArray("Metadata").objects().map(Title::parse)
suspend fun allEpisodes(id: String): List<Title> = container("/library/metadata/$id/allLeaves").optJSONArray("Metadata").objects().map(Title::parse)
suspend fun allEpisodes(id: String): List<Title> = withContext(Dispatchers.Default){container("/library/metadata/$id/allLeaves").optJSONArray("Metadata").objects().map(Title::parse)}
suspend fun collections(section: String): List<Title> = container("/library/sections/$section/collections").optJSONArray("Metadata").objects().map(Title::parse)
suspend fun search(query: String): List<Title> = container("/hubs/search",mapOf("query" to query,"limit" to "60","includeCollections" to "1")).optJSONArray("Hub").objects().flatMap { it.optJSONArray("Metadata").objects().map(Title::parse) }.filter { it.type in listOf("movie","show","episode","collection") }.distinctBy { it.id }
suspend fun watched(item: Title, watched: Boolean) { container(if(watched) "/:/scrobble" else "/:/unscrobble",mapOf("key" to item.id,"identifier" to "com.plexapp.plugins.library")) }

View file

@ -46,12 +46,12 @@ import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.input.key.onPreviewKeyEvent
import java.io.File
@Composable fun Artwork(api: PlexApi,path: String,modifier: Modifier=Modifier,width: Int=600,height: Int=900,animate:Boolean=true) {
@Composable fun Artwork(api: PlexApi,path: String,modifier: Modifier=Modifier,width: Int=600,height: Int=900,animate:Boolean=true,contentScale:ContentScale=ContentScale.Crop) {
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.Crop,modifier=modifier.background(Panel))
AsyncImage(model=model,contentDescription=null,contentScale=contentScale,modifier=modifier.background(Panel))
}
@Composable fun KaleidoApp(vm: KaleidoViewModel,install: (File)->Unit) {
KaleidoTheme {
@ -97,14 +97,15 @@ import java.io.File
alpha=.18f+.82f*entrance.value
translationX=with(density){28.dp.toPx()}*direction*(1f-entrance.value)
}) {
if(!immersive&&vm.page.kind !in listOf("details","group")) TopBar(vm)
if(!immersive&&vm.page.kind !in listOf("details","group","actor")) TopBar(vm)
stateHolder.SaveableStateProvider(screenKey) {
when(vm.page.kind){
"home"->HomeScreen(vm,discoveryFocus)
"movies","tv"->LibraryScreen(vm,discoveryFocus)
"details","group"->DetailsScreen(vm)
"actor"->ActorScreen(vm)
"search"->SearchScreen(vm)
"settings"->SettingsScreen(vm,install)
"settings"->CohesiveSettingsScreen(vm,install)
}
}
}
@ -140,81 +141,6 @@ val sortLabels=listOf("titleSort:asc" to "Title: A–Z","titleSort:desc" to "Tit
@Composable fun ServerPicker(vm: KaleidoViewModel) {
Column(Modifier.fillMaxSize().padding(60.dp),verticalArrangement=Arrangement.spacedBy(18.dp)){Brand();Spacer(Modifier.height(20.dp));Text("Choose your Plex server",color=Color.White,fontSize=32.sp,fontWeight=FontWeight.Bold);vm.servers.forEachIndexed{i,s->TvButton(s.name,initialFocus=i==0,onClick={vm.chooseServer(s)})}}
}
@Composable fun SettingsScreen(vm: KaleidoViewModel,install: (File)->Unit) {
var confirmSignOut by remember{mutableStateOf(false)};var qualityDialog by remember{mutableStateOf(false)};var watchedDialog by remember{mutableStateOf(false)}
LaunchedEffect(vm.downloadedApk){vm.downloadedApk?.let(install)}
// Returning from the package installer can leave nothing focused; the next D-pad press
// would then search from the top bar and open Home. Put focus back on the update actions.
var settingsFocused by remember{mutableStateOf(false)}
val updateFocus=remember{FocusRequester()}
val paused=remember{booleanArrayOf(false)}
LifecycleResumeEffect(Unit){
if(paused[0]){vm.installerReturned();if(!settingsFocused)runCatching{updateFocus.requestFocus()}}
onPauseOrDispose{paused[0]=true}
}
// TV's default scrolling pins focus a third of the way down, so even sideways moves
// shifted this page. Scroll only as far as needed to keep the focused control visible.
val density=LocalDensity.current
val scroll=remember(density){MinimalScroll(with(density){56.dp.toPx()})}
CompositionLocalProvider(LocalBringIntoViewSpec provides scroll) {
LazyColumn(Modifier.onFocusChanged{settingsFocused=it.hasFocus},contentPadding=PaddingValues(horizontal=Cinema.gutter,vertical=17.dp),verticalArrangement=Arrangement.spacedBy(16.dp)) {
item {Text("Settings",color=Accent,fontSize=29.sp,lineHeight=34.sp,fontWeight=FontWeight.SemiBold,letterSpacing=(-.8).sp)}
item{SettingsPanel("Plex connection") {Text(vm.session?.serverName.orEmpty(),color=Color.White,fontSize=20.sp,fontWeight=FontWeight.Bold);Text(if(vm.accountToken.isBlank())"Server connection · Link your Plex account to discover your servers"else "Plex account linked · Session encrypted with Android Keystore",color=Muted,fontSize=12.sp);Spacer(Modifier.height(14.dp));Row(horizontalArrangement=Arrangement.spacedBy(10.dp)){TvButton("Sign in with Plex",initialFocus=true,onClick={vm.beginAccountLink()});if(vm.accountToken.isNotBlank())TvButton("Choose server",onClick={vm.switchServer()});TvButton("Sign out",onClick={confirmSignOut=true})}}}
item{SettingsPanel("Playback") {
TvButton("Quality: "+vm.streamQuality.label,onClick={qualityDialog=true})
Text("Original quality plays the source video without conversion and is the default. A resolution asks Plex to convert, which helps on slower connections. Quality, audio, subtitles and speed can also be changed in the player.",color=Muted,fontSize=12.sp,lineHeight=18.sp,modifier=Modifier.padding(top=10.dp))
}}
item{SettingsPanel("Watched status") {
TvButton("Mark watched at ${vm.watchedPercent}%",onClick={watchedDialog=true})
Text("A resumed title gets its checkmark at this playback percentage. Completed titles keep their Plex watched status.",color=Muted,fontSize=12.sp,lineHeight=18.sp,modifier=Modifier.padding(top=10.dp))
}}
item{SettingsPanel("Interface") {
TvButton("Navigation sounds: "+if(vm.navigationSounds)"On"else "Off",onClick={vm.chooseNavigationSounds(!vm.navigationSounds)})
Text("Play the TV's system tap when focus moves. Follows your TV's sound-effects setting.",color=Muted,fontSize=12.sp,lineHeight=18.sp,modifier=Modifier.padding(top=10.dp))
}}
item{SettingsPanel("Software updates") {
Text("Kaleido ${BuildConfig.VERSION_NAME}",color=Color.White,fontSize=20.sp,fontWeight=FontWeight.Bold)
Text(vm.updateStatus,color=Muted,fontSize=12.sp,modifier=Modifier.padding(vertical=8.dp))
Text("Updates are checked automatically every six hours while Kaleido is in use.",color=Muted,fontSize=12.sp)
// Notes sit above the actions, so scrolling to the buttons always reveals them.
vm.update?.let{if(it.notes.isNotBlank()){
Spacer(Modifier.height(16.dp));Eyebrow("What's new in ${it.version}")
Text(it.notes.take(1800),color=Cinema.secondary,fontSize=11.sp,lineHeight=17.sp,modifier=Modifier.padding(top=7.dp))
}}
Spacer(Modifier.height(16.dp))
Row(Modifier.focusRequester(updateFocus).focusRestorer(),horizontalArrangement=Arrangement.spacedBy(10.dp)) {
TvButton("Check for updates",onClick={vm.checkUpdate()})
// The update action never leaves while focused; it reports progress in place.
vm.update?.let{release->
val label=when{vm.downloading->"Downloading… ${(vm.downloadProgress*100).toInt()}%";vm.readyApk!=null->"Install ${release.version}";else->"Download & install ${release.version}"}
TvButton(label,primary=true,onClick={vm.downloadUpdate()})
}
}
if(vm.downloading)LinearProgressIndicator(progress={vm.downloadProgress},modifier=Modifier.padding(top=14.dp).width(340.dp).height(3.dp),color=Accent,trackColor=Color.White.copy(alpha=.14f),gapSize=0.dp,drawStopIndicator={})
Text("git.elijahkuntz.com/Elijah/Kaleido",color=Accent,fontSize=10.sp,modifier=Modifier.padding(top=14.dp))
}}
}
}
if(confirmSignOut)ChoiceDialog("Sign out of Plex?",listOf("Keep watching","Sign out"),0,{confirmSignOut=false}){if(it==1)vm.signOut();confirmSignOut=false}
if(watchedDialog) {
val thresholds=listOf(50,60,70,75,80,85,90,95,100)
ChoiceDialog("Mark watched after",thresholds.map{"$it%"},thresholds.indexOf(vm.watchedPercent),{watchedDialog=false}){vm.chooseWatchedPercent(thresholds[it]);watchedDialog=false}
}
if(qualityDialog)ChoiceDialog("Playback quality",StreamQuality.entries.map{it.label},vm.streamQuality.ordinal,{qualityDialog=false}){vm.chooseStreamQuality(StreamQuality.entries[it]);qualityDialog=false}
}
/** Scroll only as far as needed to reveal the focused control, keeping [margin] px clear of the edges. */
private class MinimalScroll(private val margin:Float):BringIntoViewSpec {
override fun calculateScrollDistance(offset:Float,size:Float,containerSize:Float):Float {
val leading=offset-margin;val trailing=offset+size+margin
return when {
leading>=0f&&trailing<=containerSize->0f
leading<0f&&trailing>containerSize->0f
kotlin.math.abs(leading)<kotlin.math.abs(trailing-containerSize)->leading
else->trailing-containerSize
}
}
}
@Composable fun SettingsPanel(title: String,content: @Composable ColumnScope.()->Unit) {Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(9.dp)).background(Panel.copy(alpha=.65f)).padding(18.dp)){Eyebrow(title);Spacer(Modifier.height(11.dp));content()}}
@Composable fun EmptyState(title: String,message: String){Column(Modifier.padding(52.dp),verticalArrangement=Arrangement.spacedBy(12.dp)){Text(title,color=Color.White,fontSize=26.sp,fontWeight=FontWeight.Bold);Text(message,color=Muted,fontSize=14.sp)}}
@Composable fun ErrorDialog(message: String,dismiss: ()->Unit,retry: ()->Unit) {Dialog(onDismissRequest=dismiss){Column(Modifier.width(390.dp).clip(RoundedCornerShape(12.dp)).background(Panel).padding(23.dp)){Text("Something needs attention",color=Accent,fontSize=20.sp,lineHeight=26.sp,fontWeight=FontWeight.SemiBold);Text(message,color=Muted,fontSize=12.sp,lineHeight=19.sp,modifier=Modifier.padding(vertical=17.dp));Row(horizontalArrangement=Arrangement.spacedBy(9.dp)){TvButton("Try again",primary=true,initialFocus=true,onClick={dismiss();retry()});TvButton("Dismiss",onClick=dismiss)}}}}
@Composable fun ChoiceDialog(title: String,options: List<String>,selected: Int,dismiss: ()->Unit,choose: (Int)->Unit) {Dialog(onDismissRequest=dismiss){Column(Modifier.width(360.dp).heightIn(max=390.dp).clip(RoundedCornerShape(12.dp)).background(Panel).padding(21.dp)){Text(title,color=Accent,fontSize=20.sp,lineHeight=26.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(bottom=14.dp));LazyColumn(verticalArrangement=Arrangement.spacedBy(4.dp)){items(options.size){i->TvButton(options[i],Modifier.fillMaxWidth(),selected=i==selected,initialFocus=i==selected||selected<0&&i==0,onClick={choose(i)})}}}}}

View file

@ -0,0 +1,464 @@
@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
package tv.kaleido.app
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.gestures.BringIntoViewSpec
import androidx.compose.foundation.gestures.LocalBringIntoViewSpec
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.focusRestorer
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.LifecycleResumeEffect
import kotlinx.coroutines.delay
import java.io.File
/** Compact TV settings with a stable category rail and explicit left/right focus routing. */
@Composable
fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
val categories = remember { listOf("Connection", "Playback", "Interface", "Updates") }
var selectedCategory by rememberSaveable { mutableIntStateOf(0) }
var confirmSignOut by remember { mutableStateOf(false) }
var qualityDialog by remember { mutableStateOf(false) }
var watchedDialog by remember { mutableStateOf(false) }
val categoryFocus = remember { List(categories.size) { FocusRequester() } }
val entryFocus = remember { List(categories.size) { FocusRequester() } }
val watchedFocus = remember { FocusRequester() }
val serverActionFocus = remember { FocusRequester() }
val signOutActionFocus = remember { FocusRequester() }
val updateFocus = remember { FocusRequester() }
val updateDownloadFocus = remember { FocusRequester() }
var settingsFocused by remember { mutableStateOf(false) }
val paused = remember { booleanArrayOf(false) }
LaunchedEffect(vm.downloadedApk) { vm.downloadedApk?.let(install) }
LaunchedEffect(Unit) {
delay(140)
runCatching { entryFocus[selectedCategory].requestFocus() }
}
LifecycleResumeEffect(Unit) {
if (paused[0]) {
vm.installerReturned()
if (!settingsFocused) runCatching { updateFocus.requestFocus() }
}
onPauseOrDispose { paused[0] = true }
}
Column(
Modifier.fillMaxSize()
.background(Ink)
.onFocusChanged { settingsFocused = it.hasFocus }
.padding(horizontal = Cinema.gutter, vertical = 22.dp)
) {
Row(verticalAlignment = Alignment.Bottom) {
Column(Modifier.weight(1f)) {
Text(
"Settings",
color = Accent,
fontSize = 29.sp,
lineHeight = 34.sp,
fontWeight = FontWeight.SemiBold,
letterSpacing = (-.8).sp
)
Text(
"Playback, preferences and software updates",
color = Muted,
fontSize = 11.sp,
lineHeight = 15.sp,
modifier = Modifier.padding(top = 3.dp)
)
}
Eyebrow(categories[selectedCategory])
}
Spacer(Modifier.height(25.dp))
Row(Modifier.weight(1f).fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(28.dp)) {
Column(
Modifier.width(205.dp).fillMaxHeight().focusGroup(),
verticalArrangement = Arrangement.spacedBy(5.dp)
) {
Eyebrow("Categories")
Spacer(Modifier.height(7.dp))
categories.forEachIndexed { index, category ->
SettingsCategoryItem(
label = category,
selected = selectedCategory == index,
requester = categoryFocus[index],
upTarget = categoryFocus[(index - 1).coerceAtLeast(0)],
downTarget = categoryFocus[(index + 1).coerceAtMost(categories.lastIndex)],
rightTarget = entryFocus[index],
onFocused = { selectedCategory = index },
onClick = { selectedCategory = index }
)
}
}
Box(Modifier.width(1.dp).fillMaxHeight().background(Color.White.copy(alpha = .10f)))
CompositionLocalProvider(LocalBringIntoViewSpec provides SettingsScroll) {
Column(
Modifier.weight(1f).fillMaxHeight()
.verticalScroll(remember(selectedCategory) { ScrollState(0) })
.focusGroup(),
verticalArrangement = Arrangement.spacedBy(20.dp)
) {
when (selectedCategory) {
0 -> {
SettingsSectionTitle("Plex account", "Manage the server and account used by Kaleido.")
Column(verticalArrangement = Arrangement.spacedBy(5.dp)) {
Text(
vm.session?.serverName.orEmpty().ifBlank { "Plex connection" },
color = Accent,
fontSize = 19.sp,
lineHeight = 24.sp,
fontWeight = FontWeight.SemiBold
)
Text(
if (vm.accountToken.isBlank()) {
"Server connection · Link your Plex account to discover your servers"
} else {
"Plex account linked · Session encrypted with Android Keystore"
},
color = Muted,
fontSize = 11.sp,
lineHeight = 16.sp
)
}
Row(horizontalArrangement = Arrangement.spacedBy(9.dp)) {
SettingsActionButton(
"Sign in with Plex",
requester = entryFocus[0],
leftTarget = categoryFocus[0],
rightTarget = if (vm.accountToken.isNotBlank()) serverActionFocus else signOutActionFocus,
onClick = { vm.beginAccountLink() }
)
if (vm.accountToken.isNotBlank()) {
SettingsActionButton(
"Choose server",
requester = serverActionFocus,
leftTarget = categoryFocus[0],
rightTarget = signOutActionFocus,
onClick = { vm.switchServer() }
)
}
SettingsActionButton(
"Sign out",
requester = signOutActionFocus,
leftTarget = categoryFocus[0],
onClick = { confirmSignOut = true }
)
}
}
1 -> {
SettingsSectionTitle("Playback", "Choose how Plex delivers video and when a title counts as watched.")
SettingsValueRow(
title = "Playback quality",
description = "Original plays the source; a resolution asks Plex to convert.",
value = vm.streamQuality.label,
requester = entryFocus[1],
leftTarget = categoryFocus[1],
onClick = { qualityDialog = true }
)
SettingsValueRow(
title = "Watched status",
description = "A resumed title receives its checkmark at this playback percentage.",
value = "${vm.watchedPercent}%",
requester = watchedFocus,
leftTarget = categoryFocus[1],
onClick = { watchedDialog = true }
)
Text(
"Completed titles keep their Plex watched status.",
color = Cinema.quiet,
fontSize = 10.sp,
lineHeight = 14.sp,
modifier = Modifier.padding(start = 1.dp, top = 1.dp)
)
}
2 -> {
SettingsSectionTitle("Interface", "Control the small cues Kaleido plays as you browse.")
SettingsValueRow(
title = "Navigation sounds",
description = "Play the TV's system tap when focus moves. Follows the TV sound-effects setting.",
value = if (vm.navigationSounds) "On" else "Off",
requester = entryFocus[2],
leftTarget = categoryFocus[2],
onClick = { vm.chooseNavigationSounds(!vm.navigationSounds) }
)
}
else -> {
SettingsSectionTitle("Software updates", "Install the latest updates published for Kaleido.")
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text("Kaleido ${BuildConfig.VERSION_NAME}", color = Accent, fontSize = 18.sp, lineHeight = 23.sp, fontWeight = FontWeight.SemiBold)
Text(vm.updateStatus, color = Muted, fontSize = 11.sp, lineHeight = 16.sp)
Text("Updates are checked automatically every six hours while Kaleido is in use.", color = Muted, fontSize = 10.sp, lineHeight = 15.sp)
}
vm.update?.let { release ->
if (release.notes.isNotBlank()) {
Column(verticalArrangement = Arrangement.spacedBy(5.dp)) {
Eyebrow("What's new in ${release.version}")
Text(
release.notes.take(1800),
color = Cinema.secondary,
fontSize = 10.sp,
lineHeight = 15.sp
)
}
}
}
Row(
Modifier.focusRequester(updateFocus).focusRestorer(),
horizontalArrangement = Arrangement.spacedBy(9.dp)
) {
SettingsActionButton(
"Check for updates",
requester = entryFocus[3],
leftTarget = categoryFocus[3],
rightTarget = if (vm.update != null) updateDownloadFocus else null,
onClick = { vm.checkUpdate() }
)
vm.update?.let { release ->
val label = when {
vm.downloading -> "Downloading… ${(vm.downloadProgress * 100).toInt()}%"
vm.readyApk != null -> "Install ${release.version}"
else -> "Download & install ${release.version}"
}
SettingsActionButton(
label,
requester = updateDownloadFocus,
leftTarget = categoryFocus[3],
primary = true,
onClick = { vm.downloadUpdate() }
)
}
}
if (vm.downloading) {
androidx.compose.material3.LinearProgressIndicator(
progress = { vm.downloadProgress },
modifier = Modifier.width(340.dp).height(3.dp),
color = Accent,
trackColor = Color.White.copy(alpha = .14f),
gapSize = 0.dp,
drawStopIndicator = {}
)
}
Text("git.elijahkuntz.com/Elijah/Kaleido", color = Accent, fontSize = 10.sp)
}
}
}
}
}
}
if (confirmSignOut) {
ChoiceDialog("Sign out of Plex?", listOf("Keep watching", "Sign out"), 0, { confirmSignOut = false }) {
if (it == 1) vm.signOut()
confirmSignOut = false
}
}
if (watchedDialog) {
val thresholds = listOf(50, 60, 70, 75, 80, 85, 90, 95, 100)
ChoiceDialog("Mark watched after", thresholds.map { "$it%" }, thresholds.indexOf(vm.watchedPercent), { watchedDialog = false }) {
vm.chooseWatchedPercent(thresholds[it])
watchedDialog = false
}
}
if (qualityDialog) {
ChoiceDialog("Playback quality", StreamQuality.entries.map { it.label }, vm.streamQuality.ordinal, { qualityDialog = false }) {
vm.chooseStreamQuality(StreamQuality.entries[it])
qualityDialog = false
}
}
}
/** Keep sideways moves still, scrolling only when a control is outside the pane. */
private object SettingsScroll:BringIntoViewSpec {
override fun calculateScrollDistance(offset:Float,size:Float,containerSize:Float):Float = when {
offset<0f->offset
offset+size>containerSize->offset+size-containerSize
else->0f
}
}
@Composable
private fun SettingsSectionTitle(title: String, subtitle: String) {
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(title, color = Accent, fontSize = 21.sp, lineHeight = 27.sp, fontWeight = FontWeight.SemiBold, letterSpacing = (-.3).sp)
Text(subtitle, color = Muted, fontSize = 11.sp, lineHeight = 16.sp)
}
}
@Composable
private fun SettingsCategoryItem(
label: String,
selected: Boolean,
requester: FocusRequester,
upTarget: FocusRequester,
downTarget: FocusRequester,
rightTarget: FocusRequester,
onFocused: () -> Unit,
onClick: () -> Unit
) {
var focused by remember { mutableStateOf(false) }
val background by animateColorAsState(
if (focused) Accent else if (selected) Color.White.copy(alpha = .09f) else Color.Transparent,
tween(150),
label = "settingsCategoryBackground"
)
val scale by animateFloatAsState(if (focused) 1.025f else 1f, tween(160), label = "settingsCategoryScale")
Row(
Modifier.fillMaxWidth().height(40.dp)
.graphicsLayer { scaleX = scale; scaleY = scale }
.focusRequester(requester)
.focusProperties {
left = FocusRequester.Cancel
right = rightTarget
up = upTarget
down = downTarget
}
.navigationSound()
.onFocusChanged {
focused = it.isFocused
if (it.isFocused) onFocused()
}
.clip(RoundedCornerShape(Cinema.radius))
.background(background)
.clickable(onClick = onClick)
.padding(horizontal = 11.dp),
verticalAlignment = Alignment.CenterVertically
) {
Box(
Modifier.width(2.dp).height(17.dp)
.background(if (selected) (if (focused) Ink else Accent.copy(alpha = .72f)) else Color.Transparent, RoundedCornerShape(2.dp))
)
Text(
label,
color = if (focused) Ink else if (selected) Accent else Muted,
fontSize = 12.sp,
lineHeight = 16.sp,
fontWeight = if (focused || selected) FontWeight.SemiBold else FontWeight.Medium,
modifier = Modifier.padding(start = 10.dp)
)
}
}
@Composable
private fun SettingsValueRow(
title: String,
description: String,
value: String,
requester: FocusRequester,
leftTarget: FocusRequester,
rightTarget: FocusRequester? = null,
onClick: () -> Unit
) {
var focused by remember { mutableStateOf(false) }
val background by animateColorAsState(if (focused) Accent else Color.White.copy(alpha = .045f), tween(150), label = "settingsValueBackground")
val foreground = if (focused) Ink else Accent
Row(
Modifier.fillMaxWidth().heightIn(min = 58.dp)
.focusRequester(requester)
.focusProperties {
left = leftTarget
right = rightTarget ?: FocusRequester.Cancel
}
.navigationSound()
.onFocusChanged { focused = it.isFocused }
.clip(RoundedCornerShape(Cinema.radius))
.background(background)
.clickable(onClick = onClick)
.padding(horizontal = 14.dp, vertical = 9.dp),
verticalAlignment = Alignment.CenterVertically
) {
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(title, color = foreground, fontSize = 12.sp, lineHeight = 16.sp, fontWeight = FontWeight.SemiBold)
Text(
description,
color = if (focused) Ink.copy(alpha = .72f) else Muted,
fontSize = 10.sp,
lineHeight = 14.sp,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
}
Spacer(Modifier.width(15.dp))
Text(
value,
color = if (focused) Ink else Accent,
fontSize = 11.sp,
lineHeight = 15.sp,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.widthIn(max = 190.dp).padding(start = 5.dp)
)
}
}
@Composable
private fun SettingsActionButton(
label: String,
requester: FocusRequester,
leftTarget: FocusRequester,
rightTarget: FocusRequester? = null,
primary: Boolean = false,
onClick: () -> Unit
) {
var focused by remember { mutableStateOf(false) }
val background by animateColorAsState(
if (focused) Accent else if (primary) Color.White.copy(alpha = .21f) else Color.White.copy(alpha = .09f),
tween(150),
label = "settingsActionBackground"
)
val scale by animateFloatAsState(if (focused) 1.025f else 1f, tween(160), label = "settingsActionScale")
Box(
Modifier.height(36.dp).graphicsLayer { scaleX = scale; scaleY = scale }
.focusRequester(requester)
.focusProperties {
left = leftTarget
right = rightTarget ?: FocusRequester.Cancel
}
.navigationSound()
.onFocusChanged { focused = it.isFocused }
.clip(RoundedCornerShape(Cinema.radius))
.background(background)
.clickable(onClick = onClick)
.padding(horizontal = 13.dp),
contentAlignment = Alignment.Center
) {
Text(
label,
color = if (focused) Ink else Accent,
fontSize = 11.sp,
lineHeight = 15.sp,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
}

View file

@ -0,0 +1,174 @@
@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
package tv.kaleido.app
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.*
import androidx.compose.foundation.gestures.BringIntoViewSpec
import androidx.compose.foundation.gestures.LocalBringIntoViewSpec
import androidx.compose.foundation.lazy.grid.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.outlined.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.*
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shadow
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.semantics.*
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import coil.request.ImageRequest
@Composable fun DetailsScreen(vm:KaleidoViewModel) {
val item=vm.detail ?: return
val actionFocus=remember(item.id){FocusRequester()}
val childFocus=remember(item.id){FocusRequester()}
val restoreFocus=remember(item.id){vm.focusId}
val restoreRow=remember(item.id){listOf("cast:","children:","related:").any{restoreFocus.startsWith("$it${item.id}:")}}
val list=rememberLazyListState()
LaunchedEffect(item.id,vm.children.isNotEmpty(),vm.detailRelated.isNotEmpty()) {
val castCount=if(item.castMembers.isNotEmpty())1 else 0
val target=when {
restoreFocus.startsWith("related:${item.id}:")&&vm.detailRelated.isNotEmpty()->1+castCount+if(vm.children.isNotEmpty())1 else 0
restoreFocus.startsWith("children:${item.id}:")&&vm.children.isNotEmpty()->1
restoreFocus.startsWith("cast:${item.id}:")&&vm.children.isNotEmpty()->2
else->null
}
// Async rows may not exist during the first restored layout. Reveal the
// requested row after it loads, then its card restores the exact focus.
if(target!=null)list.scrollToItem(target)
}
Box(Modifier.fillMaxSize().background(Ink)) {
if(item.type=="show") {
BrowseBackdrop(vm.api,item.art.ifBlank{item.thumb},Modifier.fillMaxSize(),cinematic=true)
// Keep long descriptions and provider badges legible across bright artwork.
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(0f to Ink.copy(alpha=.4f),.48f to Ink.copy(alpha=.4f),.75f to Color.Transparent)))
}
CompositionLocalProvider(LocalBringIntoViewSpec provides DetailsScroll) {
LazyColumn(state=list,contentPadding=PaddingValues(bottom=30.dp),verticalArrangement=Arrangement.spacedBy(18.dp),modifier=Modifier.fillMaxSize()) {
item(key="details-${item.id}") {
Box(Modifier.fillMaxWidth().height(if(item.type in listOf("movie","episode"))322.dp else 286.dp)) {
if(item.type!="show") {
Artwork(vm.api,item.art,Modifier.fillMaxSize(),1920,1080)
Box(Modifier.fillMaxSize().background(Brush.horizontalGradient(listOf(Ink.copy(alpha=.98f),Ink.copy(alpha=.8f),Color.Transparent))))
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(listOf(Color.Black.copy(alpha=.12f),Color.Transparent,Ink))))
}
IconControl(Icons.AutoMirrored.Outlined.ArrowBack,"Back",modifier=Modifier.padding(start=36.dp,top=14.dp)){vm.back()}
if(item.type=="show") {
Row(Modifier.fillMaxWidth().padding(start=Cinema.gutter,end=Cinema.gutter,top=68.dp),horizontalArrangement=Arrangement.spacedBy(24.dp),verticalAlignment=Alignment.Top) {
Artwork(vm.api,item.poster.ifBlank{item.thumb},Modifier.width(128.dp).height(192.dp).clip(androidx.compose.foundation.shape.RoundedCornerShape(6.dp)),384,576,animate=false,contentScale=ContentScale.Fit)
TitleInformation(vm,item,actionFocus,childFocus,!restoreRow,Modifier.weight(1f))
}
}else TitleInformation(vm,item,actionFocus,childFocus,!restoreRow,Modifier.align(Alignment.CenterStart).padding(start=Cinema.gutter,top=30.dp).width(560.dp))
}
}
if(vm.children.isNotEmpty())item(key="children-${item.id}"){MediaRow(vm,if(item.type=="show")"Seasons"else if(item.type=="season")"Episodes"else "In this collection",vm.children,"children:${item.id}",landscape=item.type=="season",entryFocus=childFocus)}
if(item.castMembers.isNotEmpty())item(key="cast-${item.id}"){CastRail(vm,item,actionFocus)}
if(vm.detailRelated.isNotEmpty())item(key="related-${item.id}"){MediaRow(vm,"Related shows",vm.detailRelated,"related:${item.id}")}
}
}
}
}
/** Do not pin an already visible action a third of the way down the screen. */
private object DetailsScroll:BringIntoViewSpec {
override fun calculateScrollDistance(offset:Float,size:Float,containerSize:Float):Float = when {
offset<12f->offset-12f
offset+size>containerSize-12f->offset+size-containerSize+12f
else->0f
}
}
@Composable private fun TitleInformation(vm:KaleidoViewModel,item:Title,actionFocus:FocusRequester,childFocus:FocusRequester,initialFocus:Boolean,modifier:Modifier) {
val actionNavigation=Modifier.focusProperties{if(vm.children.isNotEmpty())down=childFocus}
Column(modifier) {
CompositionLocalProvider(LocalTextStyle provides LocalTextStyle.current.copy(shadow=Shadow(Color.Black.copy(alpha=.95f),Offset(0f,2f),6f))) {
if(item.type=="episode")Text(item.grandparentTitle,color=Cinema.secondary,fontSize=11.sp)
Text(item.title,color=Accent,fontSize=32.sp,lineHeight=36.sp,fontWeight=FontWeight.Bold,maxLines=2,overflow=TextOverflow.Ellipsis)
Row(Modifier.fillMaxWidth().padding(top=9.dp),verticalAlignment=Alignment.CenterVertically) {
Text(listOf(item.subtitle,item.contentRating).filter{it.isNotBlank()}.joinToString(" · "),color=Muted,fontSize=10.5.sp,lineHeight=16.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f,fill=false))
AudienceRatings(item,Modifier.padding(start=12.dp))
}
Text(item.summary,color=Cinema.secondary,fontSize=12.sp,lineHeight=18.sp,maxLines=3,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=10.dp,bottom=17.dp))
}
if(item.type!="collection")Row(horizontalArrangement=Arrangement.spacedBy(9.dp),verticalAlignment=Alignment.CenterVertically) {
ActionButton(if(item.offset>0)"Resume · ${item.offset/60000} min"else if(item.type=="show")"Watch next"else "Play",Icons.Filled.PlayArrow,modifier=actionNavigation.focusRequester(actionFocus),primary=true,initialFocus=initialFocus){vm.play(item)}
if(item.offset>0)ActionButton("Start over",Icons.Outlined.Replay,modifier=actionNavigation){vm.play(item,true)}
if(item.type in listOf("movie","show","season","episode")) {
val watched=item.isWatched(vm.watchedPercent)
ActionButton(if(vm.markingId==item.id)"Updating…"else if(watched)"Mark unwatched"else "Mark watched",if(watched)Icons.Outlined.CheckCircle else Icons.Outlined.Check,modifier=actionNavigation){vm.mark(item)}
}
}
if(item.type!="show")item.media.firstOrNull()?.let{media->Text(listOf(media.resolution.uppercase(),media.videoCodec.uppercase(),media.audioCodec.uppercase()).filter{it.isNotBlank()}.joinToString(" · "),color=Cinema.quiet,fontSize=9.sp,modifier=Modifier.padding(top=12.dp))}
}
}
@Composable private fun CastRail(vm:KaleidoViewModel,item:Title,actionFocus:FocusRequester) {
val initial=remember(item.id){item.castMembers.indexOfFirst{"cast:${item.id}:${it.id.ifBlank{it.name}}"==vm.focusId}.coerceAtLeast(0)}
val row=rememberLazyListState(initialFirstVisibleItemIndex=initial)
Column {
Text("Cast",color=Accent,fontSize=17.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(start=Cinema.gutter,bottom=10.dp))
LazyRow(state=row,contentPadding=PaddingValues(horizontal=Cinema.gutter),horizontalArrangement=Arrangement.spacedBy(16.dp),modifier=Modifier.focusRestorer()) {
itemsIndexed(item.castMembers,key={index,actor->actor.id.ifBlank{"${actor.name}-$index"}}){_,actor->
val key="cast:${item.id}:${actor.id.ifBlank{actor.name}}"
var focused by remember{mutableStateOf(false)}
val requester=remember{FocusRequester()}
LaunchedEffect(Unit){if(vm.focusId==key){withFrameNanos{};runCatching{requester.requestFocus()}}}
Column(Modifier.width(108.dp).focusRequester(requester).focusProperties{if(item.type!="collection"&&vm.children.isEmpty())up=actionFocus}.navigationSound().onFocusChanged{
focused=it.isFocused;if(it.isFocused)vm.focusId=key
}.clickable(enabled=actor.id.isNotBlank()){vm.openActor(actor)}.clearAndSetSemantics{
contentDescription=listOf(actor.name,actor.role).filter{it.isNotBlank()}.joinToString(". ")
this.focused=focused;role=Role.Button
if(actor.id.isNotBlank())onClick{vm.openActor(actor);true}
},horizontalAlignment=Alignment.CenterHorizontally) {
ActorPortrait(vm.api,actor,Modifier.size(86.dp).then(if(focused)Modifier.border(2.dp,Accent,CircleShape)else Modifier))
Text(actor.name,color=if(focused)Accent else Cinema.secondary,fontSize=11.sp,lineHeight=14.sp,maxLines=2,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=7.dp).height(28.dp))
Text(actor.role,color=Muted,fontSize=9.sp,lineHeight=12.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.height(12.dp))
}
}
}
}
}
@Composable private fun ActorPortrait(api:PlexApi,actor:CastMember,modifier:Modifier) {
val context=LocalContext.current
val request=remember(actor.thumb,api.session?.server){api.image(actor.thumb,256,256)?.let{url->ImageRequest.Builder(context).data(url).apply{api.headers().forEach{(k,v)->addHeader(k,v)}}.crossfade(false).build()}}
Box(modifier.clip(CircleShape).background(Panel),contentAlignment=Alignment.Center) {
Icon(Icons.Outlined.Person,null,tint=Muted,modifier=Modifier.fillMaxSize(.5f))
AsyncImage(request,null,modifier=Modifier.fillMaxSize(),contentScale=ContentScale.Crop)
}
}
@Composable fun ActorScreen(vm:KaleidoViewModel) {
val actor=vm.page.actor ?: return
Column(Modifier.fillMaxSize().background(Ink).padding(top=20.dp)) {
Row(Modifier.fillMaxWidth().padding(start=34.dp,end=Cinema.gutter,bottom=22.dp),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(18.dp)) {
IconControl(Icons.AutoMirrored.Outlined.ArrowBack,"Back"){vm.back()}
ActorPortrait(vm.api,actor,Modifier.size(65.dp))
Column {
Eyebrow("In your libraries")
Text(actor.name,color=Accent,fontSize=29.sp,lineHeight=34.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(vertical=3.dp))
Text(if(vm.busy)"Finding movies and shows…"else "${vm.actorTitles.size} titles",color=Muted,fontSize=11.sp)
}
}
if(vm.actorTitles.isEmpty()&&!vm.busy)Text("No titles with this actor in your libraries.",color=Muted,fontSize=14.sp,modifier=Modifier.padding(horizontal=Cinema.gutter))
LazyVerticalGrid(GridCells.Fixed(6),contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,bottom=28.dp),horizontalArrangement=Arrangement.spacedBy(13.dp),verticalArrangement=Arrangement.spacedBy(18.dp)) {
itemsIndexed(vm.actorTitles,key={_,item->item.id}){index,item->
MediaTile(vm,item,"actor:${actor.id}:${item.id}",fillWidth=true,initialFocus=index==0&&!vm.focusId.startsWith("actor:${actor.id}:"),onMove={anticipateTileMove(vm,vm.actorTitles,index,it,6)})
}
}
}
}