Release Kaleido 0.6.1 with smoother browsing
All checks were successful
Validate and publish Kaleido / android (push) Successful in 2m24s

Home, Movies and TV stay composed once shown and are revealed instead of
rebuilt; hidden screens are unplaced, have no semantics and take no focus.
The hero stays composed as a zero-alpha layer. Lazy-list prefetch runs on
FramePrefetch, which uses only spare frame time (unlimited only when truly
idle) instead of Compose's scheduler, which gave late frames unlimited time
and composed whole rows mid-scroll. CacheWindows keeps Compose's cache-window
strategy on that scheduler and premeasures nested cards.

With any accessibility service enabled, Compose walked and sorted every
composed node every 100 ms while browsing; rows and cards outside the
viewport now carry no semantics. Cards use a lighter artwork path, lay out
both title weights up front, and models are @Immutable. Preview and hero copy
compose over the transparent start of their fade. Library sync applies its
snapshot after 2 s without input, and moveToRow retries focus so a refreshed
card is never left unfocused.

profile_transitions.py now counts frames actually dropped on the display.
On the onn the 42 measured transitions dropped 24-38 frames, versus 55 for
0.6.0; details are in docs/runtime-verification.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-10-29 00:24:07 -07:00
parent ca5f0e20e5
commit 30e0f30bca
20 changed files with 502 additions and 111 deletions

View file

@ -14,3 +14,6 @@ HPLtv/kaleido/app/TitleActionsNode;->**(**)**
HPLtv/kaleido/app/TitleActionsElement;->**(**)**
HPLtv/kaleido/app/Title;->**(**)**
HPLtv/kaleido/app/Media;->**(**)**
HPLtv/kaleido/app/FramePrefetch;->**(**)**
HPLtv/kaleido/app/FramePrefetchKt;->**(**)**
HPLtv/kaleido/app/CacheWindows;->**(**)**

View file

@ -78,10 +78,10 @@ import androidx.compose.ui.text.input.TextFieldValue
if(navigation!=null&&it.type==KeyEventType.KeyDown&&it.key==Key.DirectionDown){
pendingTab[0]?.cancel()
val target=focusedTab[0]
if(vm.page.kind!=target){navigation.pendingEntry=target;vm.tab(target);vm.focusId=if(target=="home")"home-feature"else "discovery-entry"}else navigation.enter?.invoke()
if(vm.page.kind!=target){navigation.pendingEntry=target;vm.tab(target);vm.focusId=if(target=="home")"home-feature"else "discovery-entry"}else navigation.of(target).enter?.invoke()
true
}else false
}.focusProperties{if(navigation!=null)down=navigation.entry},horizontalArrangement=Arrangement.spacedBy(16.dp),verticalAlignment=Alignment.CenterVertically) {
}.focusProperties{if(navigation!=null)down=navigation.of(vm.page.kind).entry},horizontalArrangement=Arrangement.spacedBy(16.dp),verticalAlignment=Alignment.CenterVertically) {
listOf("home" to "Home","movies" to "Movies","tv" to "TV Shows").forEach{(kind,label)->
NavigationLabel(label,vm.page.kind==kind,modifier=if(navigation!=null&&vm.page.kind==kind)Modifier.focusRequester(navigation.top)else Modifier,initialFocus=vm.page.kind==kind&&initialFocus,onFocused={
focusedTab[0]=kind
@ -153,7 +153,8 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,
}
@Composable fun LibraryScreen(vm:KaleidoViewModel,navigation:DiscoveryNavigation) {
if(!vm.allTitles){DiscoveryScreen(vm,home=false,navigation=navigation);return}
// Discover is a retained DiscoveryScreen (see KaleidoApp); this is only the A–Z library.
if(!vm.allTitles)return
val name=if(vm.page.kind=="movies")"Movies"else "TV Shows"
LaunchedEffect(vm.categories,vm.section?.id,vm.genres){vm.loadCategoryArtworks()}
var sortMenu by remember{mutableStateOf(false)}

View file

@ -0,0 +1,58 @@
package tv.kaleido.app;
import androidx.annotation.NonNull;
import androidx.annotation.OptIn;
import androidx.compose.foundation.ExperimentalFoundationApi;
import androidx.compose.foundation.lazy.LazyListCacheWindowScope;
import androidx.compose.foundation.lazy.LazyListLayoutInfo;
import androidx.compose.foundation.lazy.LazyListPrefetchScope;
import androidx.compose.foundation.lazy.LazyListPrefetchStrategy;
import androidx.compose.foundation.lazy.layout.CacheWindowLogic;
import androidx.compose.foundation.lazy.layout.LazyLayoutCacheWindow;
import androidx.compose.foundation.lazy.layout.NestedPrefetchScope;
import androidx.compose.foundation.lazy.layout.PrefetchScheduler;
/**
* Compose's cache-window strategy for lazy lists (LazyListCacheWindowStrategy, Compose 1.10),
* prefetching on {@link FramePrefetch} instead of Compose's scheduler. It must itself be a
* CacheWindowLogic: the list's measure policy only keeps items in the window composed after they
* scroll out when its strategy is one, so a delegating wrapper disposed every row leaving view.
* These classes are Kotlin-internal but public in bytecode; a Compose update that changes them
* fails this build instead of changing behaviour silently.
*/
@OptIn(markerClass = ExperimentalFoundationApi.class)
@SuppressWarnings("deprecation") // Compose marks parts of the prefetch API deprecated for Java callers.
final class CacheWindows extends CacheWindowLogic implements LazyListPrefetchStrategy {
private final LazyListCacheWindowScope scope = new LazyListCacheWindowScope();
CacheWindows(LazyLayoutCacheWindow window) {
super(window, true);
}
@NonNull
@Override
public PrefetchScheduler getPrefetchScheduler() {
return FramePrefetch.INSTANCE;
}
@Override
public void onScroll(@NonNull LazyListPrefetchScope prefetch, float delta, @NonNull LazyListLayoutInfo layoutInfo) {
scope.setLayoutInfo(layoutInfo);
scope.setPrefetchScope(prefetch);
onScroll(scope, delta);
}
@Override
public void onVisibleItemsUpdated(@NonNull LazyListPrefetchScope prefetch, @NonNull LazyListLayoutInfo layoutInfo) {
scope.setLayoutInfo(layoutInfo);
scope.setPrefetchScope(prefetch);
onVisibleItemsUpdated(scope);
}
@Override
public void onNestedPrefetch(@NonNull NestedPrefetchScope nested, int firstVisibleItemIndex) {
// Every card the row showed when last measured (Compose: precompose two); see premeasure.
int count = nested.getNestedPrefetchItemCount() == -1 ? 2 : nested.getNestedPrefetchItemCount();
for (int i = 0; i < count; i++) FramePrefetchKt.premeasure(nested, firstVisibleItemIndex + i);
}
}

View file

@ -40,11 +40,16 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class DiscoveryNavigation {
val entry=FocusRequester()
val section=FocusRequester()
val top=FocusRequester()
var scrolled by mutableStateOf(false)
var pendingEntry by mutableStateOf<String?>(null)
private val destinations=mutableMapOf<String,DestinationNavigation>()
/** Home, Movies and TV stay composed while hidden, so each needs its own targets: a hidden one must never take focus. */
fun of(destination:String)=destinations.getOrPut(destination){DestinationNavigation()}
}
class DestinationNavigation {
val entry=FocusRequester()
val section=FocusRequester()
var enter:(()->Unit)?=null
}
/** Preserve server-supplied recommendations, but give each destination an editorial purpose. */

View file

@ -4,7 +4,6 @@ package tv.kaleido.app
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.*
import androidx.compose.foundation.lazy.layout.LazyLayoutCacheWindow
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.gestures.BringIntoViewSpec
import androidx.compose.foundation.gestures.LocalBringIntoViewSpec
@ -16,6 +15,7 @@ import androidx.compose.animation.core.tween
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.CompositingStrategy
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.unit.DpSize
import coil.imageLoader
import kotlinx.coroutines.flow.collectLatest
@ -36,6 +36,11 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.key.*
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.semantics.*
import androidx.compose.ui.node.invalidateSemantics
import androidx.compose.ui.node.observeReads
import androidx.compose.ui.node.ObserverModifierNode
import androidx.compose.ui.node.SemanticsModifierNode
import androidx.compose.ui.node.ModifierNodeElement
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
@ -52,7 +57,10 @@ import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Shadow
import androidx.compose.material.icons.outlined.GridView
@Composable fun HomeScreen(vm:KaleidoViewModel,navigation:DiscoveryNavigation)=DiscoveryScreen(vm,true,navigation)
/** Movies, TV and Home's second row show posters; the rest landscape cards (wider TV episodes). */
private fun posterRow(hub:Hub,row:Int,destination:String)=hub.items.firstOrNull()?.type in listOf("movie","show","season")&&!hub.title.contains("Continue",true)&&(destination=="movies"||destination=="tv"||row==1)
/** A card's width plus the rail's spacing. */
private fun railPitch(poster:Boolean,tv:Boolean)=if(poster)130.dp else if(tv)274.dp else 224.dp
/** Column id of a row's trailing "View all" card. */
internal const val VIEW_ALL="view-all"
@ -69,10 +77,17 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
if(visible!=null)animateScrollBy(visible.offset.toFloat(),tween(220))else animateScrollToItem(index)
}
/** The preview never scrolls. Only the bounded catalog below it moves. */
@Composable fun DiscoveryScreen(vm:KaleidoViewModel,home:Boolean,navigation:DiscoveryNavigation) {
val destination=if(home)"home"else vm.page.kind
val source=if(home)vm.homeHubs else vm.discoverHubs
/**
* The preview never scrolls. Only the bounded catalog below it moves.
*
* Home, Movies and TV stay composed once shown: while [active] is false the screen is neither placed
* nor drawn (see KaleidoApp), and must not take focus. Switching tabs or returning from details then
* shows it again instead of disposing and composing whole sections (a 50–80 ms frame on the onn).
*/
@Composable fun DiscoveryScreen(vm:KaleidoViewModel,destination:String,navigation:DiscoveryNavigation,active:()->Boolean) {
val home=destination=="home"
val local=remember(destination){navigation.of(destination)}
val source=vm.discoveryHubs(destination)
val hubs=remember(source,destination){editorialHubs(source,destination)}
var previousHubs by remember(destination){mutableStateOf(hubs)}
val restore=remember(hubs){
@ -80,27 +95,28 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
hubs.withIndex().firstNotNullOfOrNull{(row,h)->val column=if(focused=="${h.id}:$VIEW_ALL")h.items.size else h.items.indexOfFirst{"${h.id}:${it.id}"==focused};if(column>=0)Triple(h.id,row,column)else null}
}
val initialRow=restore?.second ?: 0
// Keep the hero/preview and adjacent rows prepared across vertical moves.
// Without a behind window, every return discards and recomposes those cards.
val list=rememberLazyListState(initialFirstVisibleItemIndex=initialRow,
cacheWindow=remember{LazyLayoutCacheWindow(aheadFraction=1f,behindFraction=1f)})
// The window only fills ahead after the list has scrolled, so the first move down after
// a section appeared composed the next rows mid-animation (a ~200 ms stall on the onn).
// Once the screen settles, nudge it so those rows compose in idle frames, then undo it.
LaunchedEffect(list,hubs.isNotEmpty()){
if(hubs.isEmpty()||list.firstVisibleItemIndex!=0||list.firstVisibleItemScrollOffset!=0)return@LaunchedEffect
// Keep the hero/preview and two rows either side prepared across vertical moves (about two
// viewports). Prefetch only uses spare or idle frame time (FramePrefetch), so a wider window
// costs no frames; a one-viewport window composed rows mid-scroll when moving back up.
val list=rememberLazyListState(initialFirstVisibleItemIndex=initialRow,prefetchStrategy=remember{budgetedCacheWindow(ahead=2f,behind=2f)})
// The window only fills after the list has scrolled, and a change of rows resets it, so the
// next move composed rows mid-animation (a ~200 ms stall on the onn). Once the screen settles,
// nudge it so those rows compose in idle frames, then undo it.
LaunchedEffect(list,hubs){
if(hubs.isEmpty())return@LaunchedEffect
snapshotFlow{active()}.first{it}
awaitSteadyFrames(4)
if(list.isScrollInProgress||list.firstVisibleItemScrollOffset!=0)return@LaunchedEffect
list.scrollBy(1f)
if(list.isScrollInProgress)return@LaunchedEffect
val moved=list.scrollBy(1f)
val at=list.firstVisibleItemIndex to list.firstVisibleItemScrollOffset
repeat(45){withFrameNanos{}}
if(!list.isScrollInProgress&&list.firstVisibleItemIndex==0&&list.firstVisibleItemScrollOffset==1)list.scrollBy(-1f)
if(moved!=0f&&!list.isScrollInProgress&&(list.firstVisibleItemIndex to list.firstVisibleItemScrollOffset)==at)list.scrollBy(-moved)
}
// Hub order and membership can change during a live refresh. Keep each rail's scroll
// state and each card's requester by stable Plex IDs so surviving rows/cards retain them.
val rowStateByHub=remember(destination){mutableMapOf<String,LazyListState>()}
val rowStates=remember(hubs){hubs.associate{hub->hub.id to rowStateByHub.getOrPut(hub.id){LazyListState(
cacheWindow=LazyLayoutCacheWindow(aheadFraction=1f,behindFraction=.5f),
firstVisibleItemIndex=if(restore?.first==hub.id)restore.third else 0)}}}
firstVisibleItemIndex=if(restore?.first==hub.id)restore.third else 0,prefetchStrategy=budgetedCacheWindow(ahead=1f,behind=.5f))}}}
val requesters=remember(destination){mutableMapOf<String,FocusRequester>()}
val columns=remember(destination){mutableMapOf<String,String>()}
val pendingColumns=remember(destination){mutableMapOf<String,String>()}
@ -109,7 +125,7 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
val scope=rememberCoroutineScope()
val density=LocalDensity.current
val hovered=remember{mutableStateOf<Title?>(null)}
val sectionEntry by remember{derivedStateOf{vm.focusId=="discovery-entry"}}
val sectionEntry by remember{derivedStateOf{vm.focusId=="discovery-entry"&&active()}}
val features=vm.homeFeatures
var featureIndex by rememberSaveable{mutableIntStateOf(0)}
val nextFeature=features.getOrNull(featureIndex % features.size.coerceAtLeast(1))
@ -136,7 +152,7 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
fun anticipateCard(item:Title)=vm.anticipate(item,path=previewArt(item),header=true)
var rotating by remember{mutableStateOf(true)}
LaunchedEffect(home,features,rotating,featureIndex){
snapshotFlow{heroMode.value}.collectLatest{if(home&&it&&rotating&&features.size>1){delay(12000);featureIndex=(featureIndex+1)%features.size}}
snapshotFlow{heroMode.value&&active()}.collectLatest{if(home&&it&&rotating&&features.size>1){delay(12000);featureIndex=(featureIndex+1)%features.size}}
}
val heroFocus=remember{FocusRequester()}
val staging=remember{CardStaging()}
@ -155,8 +171,9 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
if(!state.layoutInfo.visibleItemsInfo.any{it.index==column})state.requestScrollToItem(column)
if(!focused) {
snapshotFlow{list.layoutInfo.visibleItemsInfo.any{it.index==row}&&state.layoutInfo.visibleItemsInfo.any{it.index==column}}.first{it}
withFrameNanos{}
runCatching{requesters.getOrPut(focusKey){FocusRequester()}.requestFocus()}
// A card that replaced another (a live refresh) may compose a frame or two later; until it
// does, its requester is unattached and the request fails, which left nothing focused.
for(attempt in 0 until 8){withFrameNanos{};if(runCatching{requesters.getOrPut(focusKey){FocusRequester()}.requestFocus()}.getOrDefault(false))break}
}
scrolling.join()
}
@ -187,6 +204,8 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
if(pendingColumns[hub.id]?.let{id->hub.items.any{it.id==id}}!=true)hub.items.firstOrNull()?.let{pendingColumns[hub.id]=it.id} ?: pendingColumns.remove(hub.id)
}
previousHubs=hubs
// A hidden screen moves no focus; it finds its card again when shown.
if(!active())return@LaunchedEffect
if(oldHub!=null&&oldTitle!=null) {
val sameHub=hubs.firstOrNull{it.id==oldHub.id}
@ -209,7 +228,7 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
navigationJob[0]=scope.launch{list.scrollToItem(0);focusHero()}
}else if(!home) {
vm.focusId="discovery-entry"
navigationJob[0]=scope.launch{withFrameNanos{};runCatching{navigation.section.requestFocus()}}
navigationJob[0]=scope.launch{withFrameNanos{};runCatching{local.section.requestFocus()}}
}else {
vm.focusId=""
navigationJob[0]=scope.launch{withFrameNanos{};runCatching{navigation.top.requestFocus()}}
@ -217,24 +236,27 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
}
}
}
LaunchedEffect(home,features.isNotEmpty()){if(home&&vm.focusId=="home-feature"){heroActive=true;list.scrollToItem(0);focusHero()}}
DisposableEffect(navigation,list,hubs){
LaunchedEffect(home,features.isNotEmpty()){if(home&&active()&&vm.focusId=="home-feature"){heroActive=true;list.scrollToItem(0);focusHero()}}
DisposableEffect(local,list,hubs){
navigation.scrolled=false
navigation.enter={
local.enter={
navigationJob[0]?.cancel()
// Discover is fixed above the catalog. Enter it immediately, without resetting
// or waiting for two lazy lists to lay out. The next Down explicitly enters row 0.
if(!home)runCatching{navigation.section.requestFocus()}
if(!home)runCatching{local.section.requestFocus()}
else {
if(heroActive)runCatching{heroFocus.requestFocus()}
navigationJob[0]=scope.launch{moveToHero()}
activeFeature.value?.let{vm.anticipate(it,cinematic=true)}
}
}
onDispose{navigation.enter=null}
onDispose{local.enter=null}
}
LaunchedEffect(navigation.pendingEntry,destination) {
if(navigation.pendingEntry==destination){navigation.pendingEntry=null;navigation.enter?.invoke()}
if(navigation.pendingEntry!=destination)return@LaunchedEffect
// A retained screen is shown by the same change; enter it once it is placed again.
if(!active()){snapshotFlow{active()}.first{it};withFrameNanos{}}
navigation.pendingEntry=null;local.enter?.invoke()
}
// Back from the catalog first returns to the hero (Home) or Discover; only then leaves.
var catalogFocus by remember{mutableStateOf(false)}
@ -243,22 +265,57 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
navigationJob[0]?.cancel()
if(home&&feature!=null){vm.anticipate(feature,cinematic=true);navigationJob[0]=scope.launch{moveToHero()}}
// Move focus out of the rows before they scroll away, or the removed card clears it.
else navigationJob[0]=scope.launch{runCatching{(if(home)navigation.top else navigation.section).requestFocus()};withFrameNanos{};list.scrollToItem(0)}
else navigationJob[0]=scope.launch{runCatching{(if(home)navigation.top else local.section).requestFocus()};withFrameNanos{};list.scrollToItem(0)}
}
// Focus the hero or card that started playback once the player closes.
val seenReturn=remember{intArrayOf(vm.playbackReturn)}
LaunchedEffect(vm.playbackReturn) {
if(vm.playbackReturn==seenReturn[0])return@LaunchedEffect
seenReturn[0]=vm.playbackReturn
if(!active())return@LaunchedEffect
withFrameNanos{}
val key=vm.focusId
runCatching{if(key=="home-feature")heroFocus.requestFocus()else requesters[key]?.requestFocus()}
}
// Hidden, the screen keeps its state but gives up focus: an unplaced card must not take key
// events. Shown again, it focuses what a freshly composed screen would.
val screenFocus=remember{booleanArrayOf(false)}
val focusManager=LocalFocusManager.current
suspend fun reveal() {
withFrameNanos{}
val key=vm.focusId
if(key.isBlank()||key.startsWith("tab:")||key=="discovery-entry") {
// Entered from the top bar or Library: the screen opens at its start, as when first shown.
hovered.value=null;if(home)heroActive=true
if(list.firstVisibleItemIndex!=0||list.firstVisibleItemScrollOffset!=0)list.scrollToItem(0)
if(key=="discovery-entry"&&!home)runCatching{local.section.requestFocus()}
return
}
if(key=="home-feature"){if(home&&feature!=null)moveToHero();return}
val card=hubs.firstNotNullOfOrNull{hub->hub.items.firstOrNull{"${hub.id}:${it.id}"==key}?.let{hub to it}}
if(card!=null){moveToRow(card.first.id,card.second.id);return}
if(requesters[key]?.let{runCatching{it.requestFocus()}.getOrDefault(false)}==true)return
// Its card left while hidden (e.g. finished from Continue Watching): that row's first card.
val row=hubs.firstOrNull{key.startsWith("${it.id}:")&&it.items.isNotEmpty()}
if(row!=null)moveToRow(row.id,row.items.first().id)
else if(home&&feature!=null)moveToHero()
else runCatching{(if(home)navigation.top else local.section).requestFocus()}
}
LaunchedEffect(Unit) {
var shown=active()
snapshotFlow{active()}.collect{now->
if(now==shown)return@collect
shown=now
navigationJob[0]?.cancel();navigationJob[0]=null
if(!now){if(screenFocus[0])focusManager.clearFocus(force=true)}
else if(navigation.pendingEntry!=destination)navigationJob[0]=scope.launch{reveal()}
}
}
var sectionMenu by remember{mutableStateOf(false)}
val sectionChoices=vm.sections.filter{it.type==vm.section?.type}
val sectionFocus=remember{FocusRequester()};val categoriesFocus=remember{FocusRequester()}
val title=when(destination){"movies"->"Movies";"tv"->"TV Shows";else->"Home"}
BoxWithConstraints(Modifier.fillMaxSize()) {
BoxWithConstraints(Modifier.fillMaxSize().onFocusChanged{screenFocus[0]=it.hasFocus}) {
val heroHeight=maxHeight*.80f-62.dp
if(home)HomeBackdrop(vm.api,preview,feature,heroMode,vm.colourWash)
else FocusedPreviewCanvas(vm,preview,hubs.firstOrNull()?.items?.firstOrNull(),vm.colourWash)
@ -291,14 +348,14 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
Row(Modifier.fillMaxWidth().height(39.dp).padding(horizontal=Cinema.gutter),verticalAlignment=Alignment.CenterVertically) {
Text(title,color=Accent,fontSize=19.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(end=20.dp))
if(!home) {
NavigationLabel("Discover",true,modifier=Modifier.focusRequester(navigation.section).focusProperties{up=navigation.top;down=navigation.entry}.onPreviewKeyEvent {
NavigationLabel("Discover",true,modifier=Modifier.focusRequester(local.section).focusProperties{up=navigation.top;down=local.entry}.onPreviewKeyEvent {
if(it.type==KeyEventType.KeyDown&&it.key==Key.DirectionDown){
hubs.firstOrNull()?.items?.firstOrNull()?.let{item->anticipateCard(item)}
navigationJob[0]?.cancel();navigationJob[0]=scope.launch{hubs.firstOrNull()?.let{hub->hub.items.firstOrNull()?.let{moveToRow(hub.id,it.id)}}};true
}else false
},initialFocus=sectionEntry){}
NavigationLabel("Library",false,modifier=Modifier.focusProperties{up=navigation.top;down=navigation.entry;right=categoriesFocus}){vm.setAll(true)}
NavigationLabel("Categories",false,modifier=Modifier.focusRequester(categoriesFocus).focusProperties{up=navigation.top;down=navigation.entry;right=if(sectionChoices.size>1)sectionFocus else FocusRequester.Cancel}.onPreviewKeyEvent{
NavigationLabel("Library",false,modifier=Modifier.focusProperties{up=navigation.top;down=local.entry;right=categoriesFocus}){vm.setAll(true)}
NavigationLabel("Categories",false,modifier=Modifier.focusRequester(categoriesFocus).focusProperties{up=navigation.top;down=local.entry;right=if(sectionChoices.size>1)sectionFocus else FocusRequester.Cancel}.onPreviewKeyEvent{
if(it.type==KeyEventType.KeyDown&&it.key==Key.DirectionDown){
navigationJob[0]?.cancel();navigationJob[0]=scope.launch{hubs.firstOrNull()?.let{hub->hub.items.firstOrNull()?.let{moveToRow(hub.id,it.id)}}};true
}else false
@ -321,7 +378,7 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
CompositionLocalProvider(LocalBringIntoViewSpec provides BrowseScroll) {
LazyColumn(state=list,modifier=Modifier.fillMaxWidth().weight(1f).then(if(home)Modifier.graphicsLayer{translationY=heroDrop*(1f-compact.value)}else Modifier).onFocusChanged{catalogFocus=it.hasFocus},verticalArrangement=Arrangement.spacedBy(15.dp),contentPadding=PaddingValues(bottom=22.dp)) {
itemsIndexed(hubs,key={_,h->h.id},contentType={_,h->if(h.items.firstOrNull()?.type=="episode")"episodes"else "titles"}) {row,hub->
val poster=hub.items.firstOrNull()?.type in listOf("movie","show","season")&&!hub.title.contains("Continue",true)&&(destination=="movies"||destination=="tv"||row==1)
val poster=posterRow(hub,row,destination)
val wideEpisode=destination=="tv"&&!poster
val continuing=isContinueHub(hub)
// A row with more titles than Plex returned ends with a "View all" card.
@ -351,7 +408,7 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
val anchor=(target-1).coerceAtLeast(0)
if(visible&&!rapid) {
runCatching{requesters.getOrPut("${hub.id}:${idAt(target)}"){FocusRequester()}.requestFocus()}
val pitch=with(density){(if(poster)130.dp else if(wideEpisode)274.dp else 224.dp).toPx()}
val pitch=with(density){railPitch(poster,wideEpisode).toPx()}
val delta=(anchor-state.firstVisibleItemIndex)*pitch-state.firstVisibleItemScrollOffset
if(kotlin.math.abs(delta)>1)state.animateScrollBy(delta,tween(140))
}else{
@ -372,7 +429,7 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
if(event.key==Key.DirectionUp&&row==0) {
if(home)feature?.let{vm.anticipate(it,cinematic=true)}
navigationJob[0]?.cancel()
navigationJob[0]=scope.launch{if(home&&feature!=null)moveToHero()else{withFrameNanos{};runCatching{(if(home)navigation.top else navigation.section).requestFocus()}}}
navigationJob[0]=scope.launch{if(home&&feature!=null)moveToHero()else{withFrameNanos{};runCatching{(if(home)navigation.top else local.section).requestFocus()}}}
}
else {
navigationJob[0]?.cancel()
@ -388,14 +445,15 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) {
true
}else false
}
Column {
Column(Modifier.semanticsOnScreen{list.layoutInfo.visibleItemsInfo.any{it.index==row}}) {
Text(hub.title,color=Accent,fontSize=16.sp,lineHeight=21.sp,fontWeight=FontWeight.SemiBold,style=LocalTextStyle.current.copy(shadow=CaptionShadow),modifier=Modifier.padding(start=Cinema.gutter,bottom=5.dp))
LazyRow(state=rowStates[hub.id]!!,contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=3.dp,bottom=3.dp),horizontalArrangement=Arrangement.spacedBy(10.dp)) {
itemsIndexed(hub.items,key={_,t->t.id},contentType={_,_->poster}) {column,item->
val focusKey="${hub.id}:${item.id}"
val requester=requesters.getOrPut(focusKey){FocusRequester()}
BrowseCard(vm,item,"${hub.id}:${item.id}",poster,wideEpisode,if(row==0&&column==0)navigation.entry else null,requester,staging,continuing,
rowKeys(column),onHovered={columns[hub.id]=item.id;pendingColumns[hub.id]=item.id;hovered.value=it;heroActive=false})
val rail=rowStates[hub.id]!!
BrowseCard(vm,item,"${hub.id}:${item.id}",poster,wideEpisode,if(row==0&&column==0)local.entry else null,requester,staging,continuing,
rowKeys(column).semanticsOnScreen{rail.layoutInfo.visibleItemsInfo.any{it.index==column}},onHovered={columns[hub.id]=item.id;pendingColumns[hub.id]=item.id;hovered.value=it;heroActive=false})
}
if(viewAll)item(key=VIEW_ALL,contentType="viewAll") {
val focusKey="${hub.id}:$VIEW_ALL"
@ -451,12 +509,13 @@ internal fun previewArt(item:Title)=if(item.type=="episode")item.still.ifBlank{i
/**
* The hero ([hero]) or the compact preview, faded and lifted by [progress] in its own layer: one
* animation, no per-frame composition or layout. The hero is composed only while shown or leaving;
* the preview stays composed, invisible under the hero.
* animation, no per-frame composition or layout. Both stay composed: the hidden one is a zero-alpha
* layer, which the renderer skips, without semantics. Composing the hero again on every return to it
* cost a frame there.
*/
@Composable private fun HeaderLayer(progress:()->Float,heroShown:()->Boolean,hero:Boolean,lift:Float,modifier:Modifier,content:@Composable ()->Unit) {
val composed by remember{derivedStateOf{!hero||heroShown()||progress()<1f}}
if(composed)Box(modifier.graphicsLayer{
val shown by remember{derivedStateOf{!hero||heroShown()||progress()<1f}}
Box(modifier.then(if(shown)Modifier else Modifier.clearAndSetSemantics{}).graphicsLayer{
val c=progress()
compositingStrategy=CompositingStrategy.ModulateAlpha
if(hero){alpha=(1f-c*1.6f).coerceIn(0f,1f);translationY=-lift*c}
@ -493,12 +552,26 @@ internal fun previewArt(item:Title)=if(item.type=="episode")item.still.ifBlank{i
compositingStrategy=CompositingStrategy.ModulateAlpha
if(outgoing){alpha=(1f-t*2.5f).coerceAtLeast(0f);translationY=-lift*.66f*t}
else{alpha=((t-.2f)/.8f).coerceIn(0f,1f);translationY=lift*(1f-t)}
}){content(entry)}
}){CompositionLocalProvider(LocalStagedCopy provides(!outgoing&&leaving!=null)){content(entry)}}
}
}
}
}
/** True for a [FadingCopy] entry that is fading in: it stays transparent for its first five or so frames. */
private val LocalStagedCopy=staticCompositionLocalOf{false}
/**
* How many of a copy's [total] parts to compose. An incoming copy adds one per frame while it is
* still transparent: composing and measuring all of a preview's text at once took 12 ms on the onn.
*/
@Composable private fun copyParts(total:Int):Int {
val staged=LocalStagedCopy.current
var parts by remember{mutableIntStateOf(if(staged)1 else total)}
if(parts<total)LaunchedEffect(Unit){while(parts<total){withFrameNanos{};parts++}}
return parts
}
/** Focus changes invalidate this small preview scope, never the catalog hierarchy. */
@Composable private fun HomeBackdrop(api:PlexApi,preview:State<Title?>,feature:Title?,heroMode:State<Boolean>,wash:Boolean) {
val target=if(heroMode.value)feature?.let{it.art.ifBlank{it.thumb} to true}else preview.value?.let{previewArt(it) to false}
@ -536,14 +609,15 @@ internal fun previewArt(item:Title)=if(item.type=="episode")item.still.ifBlank{i
val formats=formatLabels(metadata.media.firstOrNull())
val runtime=when{item.duration<=0->"";item.offset>0->runtimeLabel(item.duration-item.offset)+" left";else->runtimeLabel(item.duration)}
Column(Modifier.width(420.dp).clearAndSetSemantics{contentDescription=listOf(item.displayTitle,metadata.rating,item.summary).filter{it.isNotBlank()}.joinToString(". ")}) {
val parts=copyParts(4)
TitleIdentity(vm.api,item,Modifier.size(logo))
Row(Modifier.fillMaxWidth().padding(top=10.dp,bottom=7.dp).height(17.dp),verticalAlignment=Alignment.CenterVertically) {
if(parts>=2)Row(Modifier.fillMaxWidth().padding(top=10.dp,bottom=7.dp).height(17.dp),verticalAlignment=Alignment.CenterVertically) {
if(item.contentRating.isNotBlank())FormatBadge(item.contentRating,Modifier.padding(end=8.dp))
Text(listOf(if(item.type=="episode")"S${item.parentIndex} · E${item.index} ${item.title}"else item.year,item.genres.firstOrNull().orEmpty(),runtime).filter{it.isNotBlank()}.joinToString(" · "),fontSize=11.sp,lineHeight=15.sp,color=Cinema.secondary,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f,fill=false))
AudienceRatings(metadata,Modifier.padding(start=10.dp))
}
Text(item.summary,color=Cinema.secondary,fontSize=12.sp,lineHeight=17.5.sp,maxLines=3,overflow=TextOverflow.Ellipsis)
Column(Modifier.graphicsLayer{alpha=details.value}) {
if(parts>=3)Text(item.summary,color=Cinema.secondary,fontSize=12.sp,lineHeight=17.5.sp,maxLines=3,overflow=TextOverflow.Ellipsis)
if(parts>=4)Column(Modifier.graphicsLayer{alpha=details.value}) {
Text(metadata.cast.take(3).joinToString(", "),color=Muted,fontSize=10.5.sp,lineHeight=14.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=6.dp).height(14.dp))
Row(Modifier.padding(top=8.dp).height(16.dp),horizontalArrangement=Arrangement.spacedBy(6.dp),verticalAlignment=Alignment.CenterVertically) {
formats.forEach{FormatBadge(it)}
@ -567,27 +641,30 @@ internal fun runtimeLabel(ms:Long):String {val minutes=(ms/60000).coerceAtLeast(
val item=feature.item
val metadata by produceState(item,item.id){value=item;value=vm.previewDetails(item)}
Column {
val parts=copyParts(3)
Eyebrow(feature.reason)
Spacer(Modifier.height(9.dp))
TitleIdentity(vm.api,item,Modifier.width(264.dp).height(80.dp))
Row(Modifier.fillMaxWidth().padding(top=8.dp,bottom=8.dp),verticalAlignment=Alignment.CenterVertically) {
if(parts>=2)Row(Modifier.fillMaxWidth().padding(top=8.dp,bottom=8.dp),verticalAlignment=Alignment.CenterVertically) {
Text(listOf(item.year,item.genres.firstOrNull().orEmpty(),item.contentRating).filter{it.isNotBlank()}.joinToString(" · "),color=Cinema.secondary,fontSize=10.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f,fill=false))
AudienceRatings(metadata,Modifier.padding(start=10.dp))
}
Text(item.summary,color=Cinema.secondary,fontSize=12.sp,lineHeight=18.sp,maxLines=3,overflow=TextOverflow.Ellipsis)
if(parts>=3)Text(item.summary,color=Cinema.secondary,fontSize=12.sp,lineHeight=18.sp,maxLines=3,overflow=TextOverflow.Ellipsis)
}
}
/**
* A newly shown section composed every visible card in one 100–200 ms frame. While it is
* entering, each card first lays out at its fixed size and fills in its artwork and titles a
* few cards per frame, under the page's fade-in. Later offscreen cards spread their
* artwork/text work over three frames too, keeping lazy-layout work short during input.
* few cards per frame, under the page's fade-in. Later cards are composed whole: they come from
* the lazy lists' cache windows, which compose and measure them in idle time. Deferring their
* content instead moved that text layout into the next frames' synchronous layout, in the middle
* of the row scroll (about 1 ms per title on the onn).
*/
private class CardStaging {
var entering=true
private var count=0
fun frames()=if(entering)count++/3 else count++%3
fun frames()=if(entering)count++/3 else -1
}
@Composable private fun BrowseCard(vm:KaleidoViewModel,item:Title,focusKey:String,poster:Boolean,wideEpisode:Boolean,entry:FocusRequester?,requester:FocusRequester,staging:CardStaging,continuing:Boolean,modifier:Modifier,onHovered:(Title)->Unit) {
@ -611,7 +688,7 @@ private class CardStaging {
}) {
Box(Modifier.fillMaxWidth().aspectRatio(if(poster)2f/3f else 16f/9f).clip(RoundedCornerShape(4.dp))) {
if(filled) {
Artwork(vm.api,image,Modifier.fillMaxSize(),if(poster)300 else 480,if(poster)450 else 270,animate=false)
CardArtwork(vm.api,image,Modifier.fillMaxSize(),if(poster)300 else 480,if(poster)450 else 270)
if(item.offset>0)Box(Modifier.align(Alignment.BottomCenter).padding(6.dp).fillMaxWidth().height(2.dp).background(Color.Black.copy(alpha=.65f))) {
Box(Modifier.fillMaxWidth(item.progress.coerceAtLeast(.01f)).fillMaxHeight().background(Accent))
}
@ -623,7 +700,13 @@ private class CardStaging {
// Placeholder height matches the titles' fixed heights, so card bounds never change.
if(!filled)Spacer(Modifier.height(if(poster)21.dp else 35.dp))
else {
Text(item.displayTitle,color=if(focused)Accent else Cinema.secondary,fontSize=10.5.sp,lineHeight=14.sp,fontWeight=if(focused)FontWeight.SemiBold else FontWeight.Normal,maxLines=1,overflow=TextOverflow.Ellipsis,style=LocalTextStyle.current.copy(shadow=CaptionShadow),modifier=Modifier.padding(top=5.dp).height(16.dp))
// Both weights are laid out with the card (in prefetch); focus only swaps their layers.
// Changing the weight re-measured two titles in the first frame of every move.
Box(Modifier.padding(top=5.dp).height(16.dp)) {
val title=LocalTextStyle.current.copy(shadow=CaptionShadow)
Text(item.displayTitle,color=Cinema.secondary,fontSize=10.5.sp,lineHeight=14.sp,fontWeight=FontWeight.Normal,maxLines=1,overflow=TextOverflow.Ellipsis,style=title,modifier=Modifier.graphicsLayer{alpha=if(focused)0f else 1f})
Text(item.displayTitle,color=Accent,fontSize=10.5.sp,lineHeight=14.sp,fontWeight=FontWeight.SemiBold,maxLines=1,overflow=TextOverflow.Ellipsis,style=title,modifier=Modifier.graphicsLayer{alpha=if(focused)1f else 0f})
}
if(!poster)Text(if(item.type=="episode")"S${item.parentIndex} · E${item.index} ${item.title}"else if(item.type=="season")item.subtitle else if(item.offset>0)"${((item.duration-item.offset)/60000).coerceAtLeast(0)} min left"else item.year,color=Cinema.secondary.copy(alpha=.85f),fontSize=9.sp,lineHeight=12.sp,maxLines=1,overflow=TextOverflow.Ellipsis,style=LocalTextStyle.current.copy(shadow=CaptionShadow),modifier=Modifier.height(14.dp))
}
}
@ -648,3 +731,32 @@ private class CardStaging {
Spacer(Modifier.height(if(poster)21.dp else 35.dp))
}
}
/**
* Semantics only while [onScreen]. With any accessibility service enabled, Compose walks and
* geometry-sorts every composed node, placed or not, after each layout change (every 100 ms while
* rows scroll): the rows and cards the lazy lists keep composed off screen made that the largest
* main-thread cost on the onn. Observed in the node, so entering or leaving view never recomposes.
*/
internal fun Modifier.semanticsOnScreen(onScreen:()->Boolean):Modifier=this then OnScreenSemanticsElement(onScreen)
private class OnScreenSemanticsElement(val onScreen:()->Boolean):ModifierNodeElement<OnScreenSemanticsNode>() {
override fun create()=OnScreenSemanticsNode(onScreen)
override fun update(node:OnScreenSemanticsNode){node.onScreen=onScreen;node.check()}
override fun equals(other:Any?)=other is OnScreenSemanticsElement&&other.onScreen===onScreen
override fun hashCode()=System.identityHashCode(onScreen)
}
private class OnScreenSemanticsNode(var onScreen:()->Boolean):Modifier.Node(),SemanticsModifierNode,ObserverModifierNode {
private var shown=true
override val shouldClearDescendantSemantics get()=!shown
override fun SemanticsPropertyReceiver.applySemantics(){}
override fun onAttach()=check()
override fun onObservedReadsChanged()=check()
fun check() {
if(!isAttached)return
var now=true
observeReads{now=onScreen()}
if(now!=shown){shown=now;invalidateSemantics()}
}
}

View file

@ -0,0 +1,77 @@
@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
package tv.kaleido.app
import android.os.Handler
import android.os.Looper
import android.view.Choreographer
import androidx.compose.foundation.lazy.LazyListPrefetchStrategy
import androidx.compose.foundation.lazy.layout.LazyLayoutCacheWindow
import androidx.compose.foundation.lazy.layout.NestedPrefetchScope
import androidx.compose.ui.unit.Constraints
import androidx.compose.foundation.lazy.layout.PrefetchRequest
import androidx.compose.foundation.lazy.layout.PrefetchRequestScope
import androidx.compose.foundation.lazy.layout.PrefetchScheduler
/**
* Runs lazy-list prefetch in what is left of each frame. Compose's scheduler treats a frame that
* follows a late one as idle and gives its request unlimited time: on the onn it then composed a
* whole row of cards (35–45 ms) in the middle of the row scroll, dropping the frames it meant to
* save. Here a request that needs more than the frame has left waits for the next; only when
* nothing has been drawn for two frames (truly idle) may it take as long as it needs, since a
* whole row is more than one frame's work and must be ready before the next move.
*/
internal object FramePrefetch:PrefetchScheduler,Choreographer.FrameCallback,Runnable,PrefetchRequestScope {
/** The display's frame interval; MainActivity sets it from the actual refresh rate. */
var frameNanos=16_666_667L
/** Left for input and the frame's own late work. */
private const val MarginNanos=2_000_000L
private val requests=ArrayDeque<PrefetchRequest>()
private val handler=Handler(Looper.getMainLooper())
private var scheduled=false
private var deadline=0L
private var lastDraw=0L
private val stalls=java.util.IdentityHashMap<PrefetchRequest,Int>()
/** About two seconds of frames without progress before a request is dropped. */
private const val StallFrames=120
/** Called for every window draw (MainActivity's draw listener). */
fun drew(){lastDraw=System.nanoTime()}
override fun schedulePrefetch(prefetchRequest:PrefetchRequest) {
requests.addLast(prefetchRequest)
if(!scheduled){scheduled=true;Choreographer.getInstance().postFrameCallback(this)}
}
// Posted from the frame callback, this runs once the frame's layout and draw are done.
override fun doFrame(frameTimeNanos:Long) {
deadline=if(frameTimeNanos-lastDraw>2*frameNanos)Long.MAX_VALUE else frameTimeNanos+frameNanos-MarginNanos
handler.post(this)
}
override fun availableTimeNanos()=(deadline-System.nanoTime()).coerceAtLeast(0L)
override fun run() {
var skipped=0
while(requests.isNotEmpty()&&skipped<requests.size&&availableTimeNanos()>0) {
val request=requests.removeFirst()
val start=System.nanoTime()
// True means it has more work, but not enough time for its next step in this frame.
val more=with(request){execute()}
val worked=System.nanoTime()-start>200_000L
if(!more){stalls.remove(request);skipped=0;continue}
if(worked){stalls.remove(request);requests.addFirst(request);break}
// No progress: let the rest go first. A request for a list nobody lays out (a hidden
// screen's) never progresses, and must not hold up the visible screen's rows.
val misses=(stalls[request] ?: 0)+1
if(misses>=StallFrames)stalls.remove(request)else{stalls[request]=misses;requests.addLast(request)}
skipped++
}
if(requests.isNotEmpty())Choreographer.getInstance().postFrameCallback(this)else scheduled=false
}
}
/** Compose's cache window ([ahead] and [behind] in viewports), prefetching on [FramePrefetch]. */
internal fun budgetedCacheWindow(ahead:Float,behind:Float):LazyListPrefetchStrategy=
CacheWindows(LazyLayoutCacheWindow(aheadFraction=ahead,behindFraction=behind))
/**
* For [CacheWindows]: compose and measure a rail's card while the catalog prefetches its row.
* Only composing it left its text layout to the row's first frame on screen, mid-scroll.
*/
internal fun NestedPrefetchScope.premeasure(index:Int)=schedulePrecompositionAndPremeasure(index,Constraints())

View file

@ -34,6 +34,7 @@ private fun categoryArtworkHint(section:Section,genre:String):String?=when {
section.type=="movie"&&genre.equals("Action",ignoreCase=true)->"Batman"
else->null
}
private const val SyncQuietMillis=2000L
class KaleidoViewModel(app: Application): AndroidViewModel(app) {
val application = app as KaleidoApplication
val api = application.api
@ -47,7 +48,27 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
var sections by mutableStateOf(emptyList<Section>()); private set
var homeHubs by mutableStateOf(emptyList<Hub>()); private set
var homeFeatures by mutableStateOf(emptyList<HomeFeature>()); private set
var discoverHubs by mutableStateOf(emptyList<Hub>()); private set
private var discoverHubsState by mutableStateOf(emptyList<Hub>())
var discoverHubs:List<Hub>
get()=discoverHubsState
private set(value){discoverHubsState=value;publishDiscovery(value)}
/**
* Rows per destination, for the Movies and TV screens that stay composed while hidden. A reload of
* the same library keeps its previous rows until the fresh ones arrive (equal rows keep their
* instances), so a retained screen neither empties nor recomposes its cards.
*/
var movieHubs by mutableStateOf(emptyList<Hub>()); private set
var showHubs by mutableStateOf(emptyList<Hub>()); private set
private val discoverySections=mutableMapOf<String,String?>()
fun discoveryHubs(destination:String)=when(destination){"home"->homeHubs;"movies"->movieHubs;else->showHubs}
private fun publishDiscovery(hubs:List<Hub>) {
val destination=when(section?.type){"movie"->"movies";"show"->"tv";else->pages.first().kind.takeIf{it in listOf("movies","tv")}} ?: return
val sectionId=section?.id
if(hubs.isEmpty()&&sectionId!=null&&discoverySections[destination]==sectionId)return
discoverySections[destination]=sectionId
if(destination=="movies")movieHubs=hubs else showHubs=hubs
}
private fun clearDiscovery(){discoverySections.clear();movieHubs=emptyList();showHubs=emptyList()}
var library by mutableStateOf(emptyList<Title>()); private set
var total by mutableStateOf(0); private set
var genres by mutableStateOf(emptyList<Pair<String,String>>()); private set
@ -124,6 +145,8 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
private var loadJob: Job? = null
private var initializeJob:Job?=null
private var librarySyncJob:Job?=null
/** Uptime of the latest remote key, from the UI; library sync applies its snapshot only after a quiet spell. */
var lastInteraction=0L
private var foreground=false
private var loadGeneration=0
private var authJob: Job? = null
@ -249,6 +272,9 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
}
val detailSnapshot=detail?.takeIf{expectedPage.kind in listOf("details","group")&&it.type in listOf("show","season","collection")}
val freshChildren=detailSnapshot?.let{api.children(it.id)}
// Applying rebuilds every changed row (Plex varies some hubs on each request), which dropped
// frames when it landed mid-move. Wait until the remote has been quiet, then validate.
while(android.os.SystemClock.uptimeMillis()-lastInteraction<SyncQuietMillis)delay(250)
// All loads above are staged. A tab/filter/session change must win over this snapshot.
if(!foreground||session!=expectedSession||page!=expectedPage||generation!=loadGeneration||
section!=expectedSection||sort!=expectedSort||genre!=expectedGenre||unwatched!=expectedUnwatched||categories!=expectedCategories||allTitles!=expectedAllTitles||
@ -299,17 +325,17 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
fun beginAccountLink(){linkingAccount=true;linkAccount()}
fun cancelAccountLink(){authJob?.cancel();pin=null;servers=emptyList();accountToken=session?.accountToken.orEmpty();linkingAccount=false}
fun chooseServer(server: Server) = launchLoad {
sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation()
sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();clearDiscovery()
val s=api.connect(server,accountToken); application.secure.save(s);api.session=s;session=s;servers=emptyList();linkingAccount=false;pages=listOf(Page());sections=api.sections();homeHubs=loadHome()
}
fun manualConnect(address: String, token: String) = launchLoad {
sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation()
sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();clearDiscovery()
require(address.startsWith("https://")||address.startsWith("http://")){"Enter a complete http:// or https:// server address."}
require(token.isNotBlank()){ "Enter an access token." }
val s=api.validate(Session("",token.trim(),address.trim().trimEnd('/'),"Plex",""))
authJob?.cancel();application.secure.save(s);api.session=s;session=s;linkingAccount=false;pages=listOf(Page());sections=api.sections();homeHubs=loadHome()
}
fun signOut(){loadJob?.cancel();initializeJob?.cancel();application.secure.clear();api.session=null;session=null;homeHubs=emptyList();discoverHubs=emptyList();sections=emptyList();library=emptyList();sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();pages=listOf(Page());servers=emptyList();accountToken="";linkAccount()}
fun signOut(){loadJob?.cancel();initializeJob?.cancel();application.secure.clear();api.session=null;session=null;homeHubs=emptyList();discoverHubs=emptyList();clearDiscovery();sections=emptyList();library=emptyList();sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();pages=listOf(Page());servers=emptyList();accountToken="";linkAccount()}
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
@ -408,14 +434,17 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
val cached=sectionCache[s.id]
if(cached!=null){discoverHubs=cached.hubs;genres=cached.genres;library=cached.library.items;total=cached.library.total;busy=false;return}
discoverHubs=emptyList();library=emptyList();total=0;genres=emptyList()
launchLoad({loadSection(s)}) {coroutineScope {
val g=async{api.genres(s.id)};val h=async{api.hubs(s.id)};val l=async{api.library(s.id,type=plexLibraryType(s.type))}
val seasons:kotlinx.coroutines.Deferred<List<Title>>?=if(s.type=="show")async{runCatching{api.recentSeasons(s.id)}.getOrDefault(emptyList())}else null
val raw=h.await();val genreList=g.await();val p=l.await();val newSeasons=seasons?.await().orEmpty()
val rows=(if(raw.isEmpty()&&p.items.isNotEmpty())listOf(Hub("library-${s.id}","From your library",p.items.take(18)))else raw)+if(newSeasons.isNotEmpty())listOf(Hub("tv.newseasons.${s.id}","New seasons",newSeasons))else emptyList()
sectionCache[s.id]=SectionContent(rows,genreList,p)
if(section?.id==s.id){discoverHubs=rows;genres=genreList;library=p.items;total=p.total}
}}
launchLoad({loadSection(s)}) {
val content=loadSectionContent(s).also{sectionCache[s.id]=it}
if(section?.id==s.id){discoverHubs=content.hubs;genres=content.genres;library=content.library.items;total=content.library.total}
}
}
private suspend fun loadSectionContent(s:Section):SectionContent=coroutineScope {
val g=async{api.genres(s.id)};val h=async{api.hubs(s.id)};val l=async{api.library(s.id,type=plexLibraryType(s.type))}
val seasons:kotlinx.coroutines.Deferred<List<Title>>?=if(s.type=="show")async{runCatching{api.recentSeasons(s.id)}.getOrDefault(emptyList())}else null
val raw=h.await();val genreList=g.await();val p=l.await();val newSeasons=seasons?.await().orEmpty()
val rows=(if(raw.isEmpty()&&p.items.isNotEmpty())listOf(Hub("library-${s.id}","From your library",p.items.take(18)))else raw)+if(newSeasons.isNotEmpty())listOf(Hub("tv.newseasons.${s.id}","New seasons",newSeasons))else emptyList()
SectionContent(rows,genreList,p)
}
fun chooseSection(s: Section){
if(s.id==section?.id)return

View file

@ -36,7 +36,10 @@ class MainActivity: ComponentActivity() {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window,false)
WindowInsetsControllerCompat(window,window.decorView).apply{hide(WindowInsetsCompat.Type.systemBars());systemBarsBehavior=WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE}
@Suppress("DEPRECATION")
FramePrefetch.frameNanos=(1_000_000_000/windowManager.defaultDisplay.refreshRate.coerceAtLeast(24f)).toLong()
setContent { KaleidoApp(model,::installApk) }
window.decorView.viewTreeObserver.addOnDrawListener{FramePrefetch.drew()}
// Compose paints Ink over the whole window; the theme background only covers launch.
window.setBackgroundDrawable(null)
debugPlayback(intent)

View file

@ -1,13 +1,14 @@
package tv.kaleido.app
import androidx.compose.runtime.Immutable
import org.json.JSONArray
import org.json.JSONObject
fun JSONArray?.objects(): List<JSONObject> = if (this == null) emptyList() else (0 until length()).mapNotNull { optJSONObject(it) }
data class Section(val id: String, val title: String, val type: String)
data class Stream(val id: String, val type: Int, val codec: String, val language: String, val title: String, val selected: Boolean, val key: String, val channels: Int, val index: Int)
data class Part(val id: String, val key: String, val streams: List<Stream>,val indexes:String="",val duration:Long=0,val size:Long=0)
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>,
@Immutable data class Stream(val id: String, val type: Int, val codec: String, val language: String, val title: String, val selected: Boolean, val key: String, val channels: Int, val index: Int)
@Immutable data class Part(val id: String, val key: String, val streams: List<Stream>,val indexes:String="",val duration:Long=0,val size:Long=0)
@Immutable 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>,
val dynamicRange:String="",val audioChannels:Int=0) {
val resolutionLabel get()=when(resolution.lowercase()){"4k"->"4K";"sd"->"SD";""->"";else->if(resolution.all(Char::isDigit))"${resolution}p"else resolution.uppercase()}
val channelLabel get()=when(audioChannels){0->"";1->"Mono";2->"Stereo";6->"5.1";8->"7.1";else->"$audioChannels ch"}
@ -23,14 +24,14 @@ data class Media(val id: String, val container: String, val videoCodec: String,
if(bitrate>0)"${(bitrate+500)/1000} Mbps"else "",if(parts.size>1)"${parts.size} parts"else "").filter{it.isNotBlank()}.joinToString(" · ")
}
internal fun fileSize(bytes:Long):String = if(bytes>=1_000_000_000L)String.format(java.util.Locale.US,"%.1f GB",bytes/1e9)else "${bytes/1_000_000} MB"
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) {
@Immutable data class Marker(val type: String, val start: Long, val end: Long)
@Immutable data class Chapter(val index:Int,val title:String,val start:Long,val end:Long,val thumb:String)
@Immutable 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(
@Immutable 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,
val watched: Boolean, val rating: String, val contentRating: String, val parentTitle: String,
@ -102,7 +103,7 @@ data class Title(
}
/** Plex normalizes external ratings to 0–10. Never substitute the critic `rating` field. */
data class AudienceScore(val source:String,val value:Double) {
@Immutable data class AudienceScore(val source:String,val value:Double) {
val displayValue get() = if(source=="Rotten Tomatoes")"${kotlin.math.round(value*10).toInt()}%"else "${String.format(java.util.Locale.US,"%.1f",value)}/10"
val label get() = "$source ${if(source=="Rotten Tomatoes")"audience "else ""}$displayValue"
companion object {
@ -129,9 +130,9 @@ data class AudienceScore(val source:String,val value:Double) {
internal fun reachedWatchedThreshold(position:Long,duration:Long,percent:Int):Boolean =
duration>0&&position.toDouble()/duration>=percent.coerceIn(50,100)/100.0
/** [key] and [more] come from Plex: a row with more titles than shown can open its full list. */
data class Hub(val id: String, val title: String, val items: List<Title>,val key:String="",val more:Boolean=false)
data class LibraryPage(val items: List<Title>,val total: Int)
data class SearchResults(val titles:List<Title> = emptyList(),val people:List<CastMember> = emptyList())
@Immutable data class Hub(val id: String, val title: String, val items: List<Title>,val key:String="",val more:Boolean=false)
@Immutable data class LibraryPage(val items: List<Title>,val total: Int)
@Immutable data class SearchResults(val titles:List<Title> = emptyList(),val people:List<CastMember> = emptyList())
data class Server(val id: String, val name: String, val token: String, val connections: List<String>)
data class Session(val accountToken: String, val serverToken: String, val server: String, val serverName: String, val machineId: String)
data class Pin(val id: String,val code: String)

View file

@ -26,6 +26,8 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.CompositingStrategy
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.semantics.clearAndSetSemantics
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
@ -34,6 +36,13 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import coil.compose.AsyncImage
import coil.imageLoader
import android.graphics.drawable.BitmapDrawable
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.graphics.FilterQuality
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import coil.request.ImageRequest
import coil.size.Precision
import androidx.compose.foundation.gestures.BringIntoViewSpec
@ -56,12 +65,34 @@ import java.io.File
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,colorFilter=colorFilter,modifier=modifier.background(Panel))
}
/**
* A browse card's artwork, without Coil's painter machinery (a painter, a snapshot flow and a
* request run per card cost about 2.5 ms of each card's composition on the onn). A memory-cache
* hit is drawn straight away; otherwise the image loads, then draws without recomposing. Like
* [Artwork] with ContentScale.Crop and no crossfade.
*/
@Composable fun CardArtwork(api:PlexApi,path:String,modifier:Modifier,width:Int,height:Int) {
val context=LocalContext.current
val loader=context.imageLoader
val request=remember(path,api.session?.server,width,height){api.image(path,width,height)?.let{u->ImageRequest.Builder(context).data(u).memoryCacheKey("card:$u")
.apply{api.headers().forEach{(k,v)->addHeader(k,v)}}.size(width,height).precision(Precision.INEXACT).build()}}
val image=remember(request){mutableStateOf(request?.memoryCacheKey?.let{loader.memoryCache?.get(it)?.bitmap?.asImageBitmap()})}
if(image.value==null&&request!=null)LaunchedEffect(request){(loader.execute(request).drawable as? BitmapDrawable)?.bitmap?.let{image.value=it.asImageBitmap()}}
Box(modifier.background(Panel).drawBehind{
val bitmap=image.value ?: return@drawBehind
// Centre crop: scale to cover the card, trim the overflow.
val scale=maxOf(size.width/bitmap.width,size.height/bitmap.height)
val srcWidth=(size.width/scale).toInt().coerceIn(1,bitmap.width);val srcHeight=(size.height/scale).toInt().coerceIn(1,bitmap.height)
drawImage(bitmap,IntOffset((bitmap.width-srcWidth)/2,(bitmap.height-srcHeight)/2),IntSize(srcWidth,srcHeight),dstSize=IntSize(size.width.toInt(),size.height.toInt()),filterQuality=FilterQuality.Low)
})
}
@Composable fun KaleidoApp(vm: KaleidoViewModel,install: (File)->Unit) {
KaleidoTheme {
ThemeMusic(vm)
val stateHolder=rememberSaveableStateHolder()
val discoveryFocus=remember{DiscoveryNavigation()}
val immersive=vm.page.kind=="home"||(vm.page.kind in listOf("movies","tv")&&!vm.allTitles)
val immersive=isDiscovery(vm)
val discoveries=remember{LinkedHashSet<String>()}
val screenKey=vm.page.kind+":"+vm.page.id+if(vm.page.kind in listOf("movies","tv")) ":${vm.allTitles}:${vm.categories}:${vm.genre}"else ""
val entrance=remember{Animatable(1f)}
val density=LocalDensity.current
@ -91,7 +122,7 @@ import java.io.File
if(vm.linkingAccount)vm.cancelAccountLink()else vm.back()
}
NavigationSounds(vm.navigationSounds&&!startup) {
Box(Modifier.fillMaxSize().background(Ink).onPreviewKeyEvent{startup}) {
Box(Modifier.fillMaxSize().background(Ink).onPreviewKeyEvent{vm.lastInteraction=android.os.SystemClock.uptimeMillis();startup}) {
// The app settles into place behind the splash as its aperture opens.
Box(Modifier.fillMaxSize().then(if(startup)Modifier.graphicsLayer{val s=startupArrivalScale(splashExit.value);scaleX=s;scaleY=s}else Modifier)) {
if(vm.servers.isNotEmpty()) ServerPicker(vm) else if(vm.session==null||vm.linkingAccount) SignIn(vm) else {
@ -102,16 +133,35 @@ import java.io.File
translationX=with(density){28.dp.toPx()}*direction*(1f-entrance.value)
}) {
if(!immersive&&vm.page.kind !in listOf("details","group","actor","hub")) 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)
"hub"->HubScreen(vm)
"search"->SearchScreen(vm)
"settings"->CohesiveSettingsScreen(vm,install)
}
// Home, Movies and TV stay composed once shown; only the one on screen is measured,
// placed and drawn. Unplaced, the others take no focus and draw nothing, and
// showing one again costs no composition. Other pages compose as before.
if(immersive)discoveries+=vm.page.kind
val shown=if(immersive)discoveries.indexOf(vm.page.kind)else -1
Layout({
discoveries.forEach{destination->key(destination){
// Unplaced screens are still walked whenever accessibility rebuilds its tree
// (every 100 ms while anything moves, with the onn's services); clearing
// their semantics stops that walk at the root.
Box(if(isDiscovery(vm)&&vm.page.kind==destination)Modifier else Modifier.clearAndSetSemantics{}) {
stateHolder.SaveableStateProvider("discovery:$destination") {
DiscoveryScreen(vm,destination,discoveryFocus){isDiscovery(vm)&&vm.page.kind==destination}
}
}
}}
if(!immersive)Box{stateHolder.SaveableStateProvider(screenKey) {
when(vm.page.kind){
"movies","tv"->LibraryScreen(vm,discoveryFocus)
"details","group"->DetailsScreen(vm)
"actor"->ActorScreen(vm)
"hub"->HubScreen(vm)
"search"->SearchScreen(vm)
"settings"->CohesiveSettingsScreen(vm,install)
}
}}
},Modifier.fillMaxSize()){measurables,constraints->
val page=(if(shown>=0)measurables.getOrNull(shown)else measurables.lastOrNull())?.measure(constraints)
layout(constraints.maxWidth,constraints.maxHeight){page?.place(0,0)}
}
}
if(immersive)TopBar(vm,discoveryFocus)
@ -126,6 +176,8 @@ import java.io.File
}
}
}
/** Home, or Movies/TV showing Discover rather than the A–Z library: the full-screen browse destinations. */
internal fun isDiscovery(vm:KaleidoViewModel)=vm.page.kind=="home"||(vm.page.kind in listOf("movies","tv")&&!vm.allTitles)
val sortLabels=listOf("titleSort:asc" to "Title: A–Z","titleSort:desc" to "Title: Z–A","addedAt:desc" to "Recently added","year:desc" to "Newest release","year:asc" to "Oldest release","audienceRating:desc" to "Audience rating","duration:asc" to "Shortest first")
@Composable fun SignIn(vm: KaleidoViewModel) {
var manual by rememberSaveable{mutableStateOf(false)}