diff --git a/AGENTS.md b/AGENTS.md index 22392e6..69eb215 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -77,6 +77,7 @@ These require the private test session. Playback test intents (`testTitleId`, `t - Preserve explicit D-pad row/column targets and fixed card geometry. Avoid expensive beyond-bounds focus searches, per-focus catalog recomposition and full-screen gradient overdraw. Contrast is baked into cached backdrop bitmaps off the main thread. - Give every Media3 session a unique ID: next-episode creation can overlap the old controller's disposal. Plex HLS position is absolute; **do not add the requested resume offset again**. - Handle remote Back explicitly before default focus handling. Wait for menu focus restoration in tests instead of sending blind rapid button sequences. +- A text field keeps the D-pad: route Down/IME actions out of Search's field explicitly. Give every `focusRestorer()` a fallback, or it overrides explicit focus targets. Per-card modifiers on browse rows must be `Modifier.Node`s, not `composed {}`, and must not animate per card. - Playback has one quality preference (`StreamQuality`): **Original quality** (the default) tries the original file, then Plex HLS, then a 1080p conversion if needed; 4K/1080p/720p/480p ask Plex to convert. A nonempty audio-only track list for a declared video must trigger fallback. Earlier preferences migrate on first read. Debug `testMode` still forces a delivery mode. Augment Plex's existing HEVC target; competing targets previously forced unnecessary conversion. A server copy decision does not prove rendering. Preserve the selected Plex tracks and check actual delivered formats. - **ADB screenshots can omit HEVC video on this onn while the actual TV displays it. The user confirmed this.** Do not force transcoding based solely on a blank capture. `scripts/check_video.py` has a pixel assertion that can falsely fail for this reason; use playback logs/rendered-frame evidence and physical TV confirmation as appropriate. Never infer universal HDR/codec support from one test. - Preview thumbnails and intro/credit markers depend on server-generated data. Do not fabricate them. diff --git a/CHANGELOG.md b/CHANGELOG.md index b0b9127..e10d864 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Kaleido releases +## 0.2.0 + +- Search works fully with the remote: press Down or the keyboard's Search key to reach results, grouped into Movies, TV shows, Episodes and People. Search by voice with the microphone, the remote's search key or the Assistant. +- Hold OK (or press Menu) on any title for quick actions: play or resume, start over, mark watched, remove from Continue Watching, or go to the season or show. +- Title pages add a Trailer button and a Trailers & extras row, a version picker for titles with several files, and a fuller media line with HDR/Dolby Vision, audio channels and bitrate. Season pages list episodes with synopses and air dates; episode pages show the rest of their season and link to the show. +- Rows with more titles end in View all. Back from the rows returns to the top before leaving Kaleido. A second movie or TV library can be chosen from Discover and is remembered. +- New settings: a separate remote-connection quality (1080p by default), autoplay countdown or off, automatic intro and credit skipping, and subtitle size and style with a preview. OK skips a visible intro or credits. +- Stacked multi-part movies play through every part. Kaleido finds your server again if its address changes. A finished movie returns to its page, and focus returns to Play after playback. +- Fix chapter numbering, menus that opened away from the current choice, a misleading checkmark in Playback options, season cards without their show name, faint focus on light posters, and Try again repeating the action that failed. + ## 0.1.11 - Give movie information the fitted poster, cinematic backdrop and safe header placement used by TV shows. Add related movies from Plex beneath the cast. diff --git a/README.md b/README.md index e323252..b58a60d 100644 --- a/README.md +++ b/README.md @@ -10,20 +10,22 @@ A Plex client for Android TV, designed for browsing from the couch. Kaleido puts - **Home** brings together featured titles, Plex recommendations and Continue Watching. Resume a movie or get back to your current series without digging through your library. - **Movies** starts with recent releases and recommendations. **TV Shows** leads with your next episodes, new seasons and newly added episodes. -- **Library** gives you an A–Z poster grid with genre, watched-status and sorting controls. Search finds movies, shows and episodes across your libraries. -- **Title pages** include ratings, a synopsis and cast portraits with character names. Select an actor to see their available movies and shows. Series pages put seasons first, with cast and related shows below. +- **Library** gives you an A–Z poster grid with genre, watched-status and sorting controls. If you have more than one movie or TV library, choose which one each section shows. +- **Search** finds movies, shows, episodes and people across your libraries. Type with the remote or search by voice. +- **Title pages** include ratings, a synopsis, trailers and extras, and cast portraits with character names. Select an actor to see their available movies and shows. Series pages put seasons first; season pages list every episode with its synopsis. +- **Quick actions**: hold OK (or press Menu) on any title to play, start over, mark it watched, remove it from Continue Watching, or jump to its season or show. ### Watch the way you want -Original quality plays the source video where your TV supports it. You can also ask Plex to convert to 4K, 1080p, 720p or 480p for a slower connection or a different device. +Original quality plays the source video where your TV supports it. You can also ask Plex to convert to 4K, 1080p, 720p or 480p, with a separate limit for remote connections away from home. Titles with several versions let you pick one. -Choose audio tracks, subtitles, playback speed and chapters from the player. Tap Left or Right to skip ten seconds, or hold to scrub through the timeline with thumbnail previews. Skip intros and credits, and let the next episode start after a short, cancellable countdown. Previews and skip markers appear when Plex supplies them; HDR and format support depend on your TV and server. +Choose audio tracks, subtitles, playback speed and chapters from the player. Tap Left or Right to skip ten seconds, or hold to scrub through the timeline with thumbnail previews. Skip intros and credits with a button or automatically, and let the next episode start after a countdown you choose. Subtitle size and style are adjustable. Previews and skip markers appear when Plex supplies them; HDR and format support depend on your TV and server. ### Keep your place Playback progress and watched status sync with Plex, so your place carries across clients. Mark a movie, season or whole show watched or unwatched from its information page. You can set the playback percentage that counts as watched, too. -Settings groups connection, playback, interface and updates in one place. Navigation tap sounds can be turned on or off. The built-in updater checks for releases and downloads new versions without another manual sideload. +Settings groups connection, playback, subtitles, interface and updates in one place. Navigation tap sounds can be turned on or off. The built-in updater checks for releases and downloads new versions without another manual sideload. ## Install diff --git a/app/src/androidTest/java/tv/kaleido/app/LivePlexTest.kt b/app/src/androidTest/java/tv/kaleido/app/LivePlexTest.kt index a30c597..1a6792c 100644 --- a/app/src/androidTest/java/tv/kaleido/app/LivePlexTest.kt +++ b/app/src/androidTest/java/tv/kaleido/app/LivePlexTest.kt @@ -30,7 +30,7 @@ class LivePlexTest { assertTrue(filtered.items.isNotEmpty());assertTrue(filtered.total<=first.total) val title=first.items.first();val detail=api.details(title.id) assertEquals(title.title,detail.title);assertTrue(detail.media.first().parts.first().key.startsWith("/library/parts/")) - assertTrue(api.search(title.title).any{it.id==title.id}) + assertTrue(api.search(title.title).titles.any{it.id==title.id}) assertTrue(api.hubs().isNotEmpty());assertTrue(api.hubs(section.id).isNotEmpty()) } @Test fun liveShowsSeasonsEpisodesAndMarkers()=runBlocking { diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 1bd8dc6..2c9f558 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -4,9 +4,15 @@ + + + + + + diff --git a/app/src/main/baseline-prof.txt b/app/src/main/baseline-prof.txt index 105b423..fcc221c 100644 --- a/app/src/main/baseline-prof.txt +++ b/app/src/main/baseline-prof.txt @@ -8,3 +8,8 @@ HPLtv/kaleido/app/NavigationSoundsKt**->**(**)** HPLtv/kaleido/app/NavigationSoundController;->**(**)** HPLtv/kaleido/app/TitleDetailsKt**->**(**)** HPLtv/kaleido/app/SettingsScreenKt**->**(**)** +HPLtv/kaleido/app/ScreensKt**->**(**)** +HPLtv/kaleido/app/TitleActionsNode;->**(**)** +HPLtv/kaleido/app/TitleActionsElement;->**(**)** +HPLtv/kaleido/app/Title;->**(**)** +HPLtv/kaleido/app/Media;->**(**)** diff --git a/app/src/main/java/tv/kaleido/app/BrowseScreens.kt b/app/src/main/java/tv/kaleido/app/BrowseScreens.kt index 90980be..e829780 100644 --- a/app/src/main/java/tv/kaleido/app/BrowseScreens.kt +++ b/app/src/main/java/tv/kaleido/app/BrowseScreens.kt @@ -33,6 +33,18 @@ import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlinx.coroutines.delay +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalSoftwareKeyboardController +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.TextRange +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.TextFieldValue @Composable fun Brand() { Row(verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(7.dp)) { @@ -89,11 +101,14 @@ import kotlinx.coroutines.delay } } -@Composable fun MediaRow(vm:KaleidoViewModel,title:String,items:List,rowId:String,landscape:Boolean=false,subtitle:String?=null,entryFocus:FocusRequester?=null) { +/** [episodeTitles] labels episodes by number and name, for rows already inside their show. [onClick] replaces opening details. */ +@Composable fun MediaRow(vm:KaleidoViewModel,title:String,items:List<Title>,rowId:String,landscape:Boolean=false,subtitle:String?=null,entryFocus:FocusRequester?=null,episodeTitles:Boolean=false,initialItem:String?=null,onClick:((Title)->Unit)?=null) { + val initial=remember(rowId){items.indexOfFirst{it.id==initialItem}.coerceAtLeast(0)} + val row=rememberLazyListState(initialFirstVisibleItemIndex=(initial-1).coerceAtLeast(0)) 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,modifier=if(index==0&&entryFocus!=null)Modifier.focusRequester(entryFocus)else Modifier,onMove={anticipateTileMove(vm,items,index,it,0)})} + LazyRow(state=row,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(fallback=entryFocus ?: FocusRequester.Default)) { + itemsIndexed(items,key={_,it->it.id}){index,item->MediaTile(vm,item,"$rowId:${item.id}",landscape,modifier=if(index==initial&&entryFocus!=null)Modifier.focusRequester(entryFocus)else Modifier,onMove={anticipateTileMove(vm,items,index,it,0)},episodeTitle=episodeTitles,current=item.id==initialItem,onClick=onClick)} } } } @@ -109,12 +124,12 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int, items.getOrNull(target)?.let{vm.anticipate(it,backdrop=false)} } -@Composable fun MediaTile(vm:KaleidoViewModel,item:Title,focusKey:String,landscape:Boolean=false,fillWidth:Boolean=false,initialFocus:Boolean=false,modifier:Modifier=Modifier,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={},episodeTitle:Boolean=false,current:Boolean=false,onClick:((Title)->Unit)?=null) { 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||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)}) { + 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}.titleActions{vm.showActions(item)}.clickable{if(onClick!=null)onClick(item)else 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) @@ -122,10 +137,12 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int, Box(Modifier.fillMaxWidth(item.progress.coerceAtLeast(.015f)).fillMaxHeight().background(Accent,RoundedCornerShape(1.dp))) } WatchBadge(item,vm.watchedPercent) - if(focused)Box(Modifier.fillMaxSize().border(1.5.dp,Accent,RoundedCornerShape(Cinema.radius))) + if(current&&!focused)Box(Modifier.align(Alignment.TopStart).padding(6.dp).background(Color.Black.copy(alpha=.7f),RoundedCornerShape(3.dp)).padding(horizontal=6.dp,vertical=2.dp)){Text("Now viewing",color=Accent,fontSize=9.sp,lineHeight=12.sp)} + if(focused)Box(Modifier.fillMaxSize().border(2.dp,Accent,RoundedCornerShape(Cinema.radius)).padding(2.dp).border(1.dp,Color.Black.copy(alpha=.55f),RoundedCornerShape(Cinema.radius))) } - Text(if(landscape)item.displayTitle else item.title,color=if(focused)Accent else Cinema.secondary,fontSize=12.sp,lineHeight=16.sp,fontWeight=FontWeight.Medium,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=7.dp)) - Text(if(landscape)item.subtitle else item.year.ifBlank{item.subtitle},color=Muted,fontSize=10.sp,lineHeight=14.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=1.dp)) + Text(if(episodeTitle&&item.type=="episode")"${item.index}. ${item.title}"else if(item.type=="clip")item.title else if(landscape)item.displayTitle else item.title,color=if(focused)Accent else Cinema.secondary,fontSize=12.sp,lineHeight=16.sp,fontWeight=FontWeight.Medium,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=7.dp)) + Text(if(episodeTitle&&item.type=="episode")listOf(if(item.duration>0)"${item.duration/60000} min"else "",item.watchStatus(vm.watchedPercent)).filter{it.isNotBlank()}.joinToString(" · ") + else if(landscape)item.subtitle else item.year.ifBlank{item.subtitle},color=Muted,fontSize=10.sp,lineHeight=14.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=1.dp)) } } @@ -172,17 +189,77 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int, } @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)) { - Text("Search",color=Accent,fontSize=29.sp,lineHeight=34.sp,fontWeight=FontWeight.SemiBold,letterSpacing=(-.8).sp) - val requester=remember{FocusRequester()} - LaunchedEffect(Unit){delay(150);requester.requestFocus()} - OutlinedTextField(vm.query,{vm.search(it)},placeholder={Text("Movies, shows, episodes",fontSize=12.sp)},leadingIcon={Icon(Icons.Outlined.Search,null,Modifier.size(19.dp))},singleLine=true,modifier=Modifier.weight(1f).height(49.dp).focusRequester(requester),shape=RoundedCornerShape(6.dp),textStyle=androidx.compose.ui.text.TextStyle(fontSize=13.sp),colors=OutlinedTextFieldDefaults.colors(unfocusedBorderColor=Color.White.copy(alpha=.15f),focusedBorderColor=Accent)) - Text(if(vm.query.isBlank())"Your collection"else "${vm.searchResults.size} results",color=Muted,fontSize=11.sp) + val field=remember{FocusRequester()};val resultsFocus=remember{FocusRequester()};val micFocus=remember{FocusRequester()} + val keyboard=LocalSoftwareKeyboardController.current + val context=LocalContext.current + var value by remember{mutableStateOf(TextFieldValue(vm.query,TextRange(vm.query.length)))} + fun query(text:String){value=TextFieldValue(text,TextRange(text.length));vm.search(text)} + val voiceIntent=remember{android.content.Intent(android.speech.RecognizerIntent.ACTION_RECOGNIZE_SPEECH) + .putExtra(android.speech.RecognizerIntent.EXTRA_LANGUAGE_MODEL,android.speech.RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) + .putExtra(android.speech.RecognizerIntent.EXTRA_PROMPT,"Search your Plex libraries")} + // Fire TV and some TVs have no speech recognizer for apps; hide the microphone there. Google TV + // offers its TV voice input and a speech service: prefer the TV one rather than show a chooser. + val canSpeak=remember{ + val recognizers=context.packageManager.queryIntentActivities(voiceIntent,0).map{it.activityInfo.packageName}.distinct() + (listOf("com.google.android.katniss","com.google.android.googlequicksearchbox").firstOrNull{it in recognizers} ?: recognizers.firstOrNull().takeIf{recognizers.size==1}) + ?.let{voiceIntent.setPackage(it)} + recognizers.isNotEmpty() + } + val voice=rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()){result-> + result.data?.getStringArrayListExtra(android.speech.RecognizerIntent.EXTRA_RESULTS)?.firstOrNull()?.takeIf{it.isNotBlank()}?.let{query(it);runCatching{field.requestFocus()}} + } + fun listen(){keyboard?.hide();runCatching{voice.launch(voiceIntent)}} + LaunchedEffect(vm.voicePending){if(vm.voicePending){vm.voiceStarted();if(canSpeak)listen()}} + LaunchedEffect(vm.query){if(vm.query!=value.text)value=TextFieldValue(vm.query,TextRange(vm.query.length))} + val groups=remember(vm.searchResults){searchGroups(vm.searchResults.titles)} + val people=vm.searchResults.people + val hasResults=groups.isNotEmpty()||people.isNotEmpty() + fun enterResults(){keyboard?.hide();runCatching{resultsFocus.requestFocus()}} + Column(Modifier.fillMaxSize()) { + Row(Modifier.fillMaxWidth().padding(start=Cinema.gutter,end=Cinema.gutter,top=12.dp,bottom=12.dp),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(18.dp)) { + Text("Search",color=Accent,fontSize=29.sp,lineHeight=34.sp,fontWeight=FontWeight.SemiBold,letterSpacing=(-.8).sp,modifier=Modifier.padding(end=7.dp)) + // Returning from a result's details restores that result instead. + LaunchedEffect(Unit){if(!vm.focusId.startsWith("search-")){delay(150);runCatching{field.requestFocus()}}} + OutlinedTextField(value,{value=it;if(it.text!=vm.query)vm.search(it.text)},placeholder={Text("Movies, shows, episodes, people",fontSize=12.sp)},leadingIcon={Icon(Icons.Outlined.Search,null,Modifier.size(19.dp))},singleLine=true, + keyboardOptions=KeyboardOptions(imeAction=ImeAction.Search),keyboardActions=KeyboardActions(onSearch={if(hasResults)enterResults()else keyboard?.hide()}), + // A text field keeps the D-pad for its cursor: Down enters the results, Right at the end reaches the microphone. + modifier=Modifier.weight(1f).height(49.dp).focusRequester(field).onPreviewKeyEvent{ + if(it.type!=KeyEventType.KeyDown)false + else if(it.key==Key.DirectionDown){if(hasResults)enterResults()else if(canSpeak)runCatching{micFocus.requestFocus()};true} + else if(it.key==Key.DirectionRight&&canSpeak&&value.selection.collapsed&&value.selection.end==value.text.length){runCatching{micFocus.requestFocus()};true} + else false + },shape=RoundedCornerShape(6.dp),textStyle=androidx.compose.ui.text.TextStyle(fontSize=13.sp),colors=OutlinedTextFieldDefaults.colors(unfocusedBorderColor=Color.White.copy(alpha=.15f),focusedBorderColor=Accent)) + if(canSpeak)IconControl(Icons.Outlined.Mic,"Voice search",requester=micFocus,modifier=Modifier.focusProperties{left=field;if(hasResults)down=resultsFocus}){listen()} + Text(if(vm.query.isBlank())"Your collection"else (vm.searchResults.titles.size+people.size).let{if(it==1)"1 result" else "$it results"},color=Muted,fontSize=11.sp) } - if(vm.query.isBlank())Text("Find something worth watching.",color=Muted,fontSize=12.sp,modifier=Modifier.padding(top=8.dp)) - LazyVerticalGrid(GridCells.Fixed(3),horizontalArrangement=Arrangement.spacedBy(13.dp),verticalArrangement=Arrangement.spacedBy(18.dp),contentPadding=PaddingValues(top=8.dp,bottom=30.dp)) { - itemsIndexed(vm.searchResults,key={_,it->it.id}){index,item->MediaTile(vm,item,"search:${item.id}",landscape=true,fillWidth=true,onMove={anticipateTileMove(vm,vm.searchResults,index,it,3)})} + if(vm.query.isBlank())Text(if(canSpeak)"Type, or select the microphone to search by voice."else "Find something worth watching.",color=Muted,fontSize=12.sp,modifier=Modifier.padding(start=Cinema.gutter,top=8.dp)) + else if(!hasResults&&!vm.busy)Text("No matches for “${vm.query}”.",color=Muted,fontSize=12.sp,modifier=Modifier.padding(start=Cinema.gutter,top=8.dp)) + // Grouped rows, like Home: Movies, TV shows, collections, episodes, then people. + LazyColumn(Modifier.fillMaxSize(),contentPadding=PaddingValues(top=4.dp,bottom=30.dp),verticalArrangement=Arrangement.spacedBy(16.dp)) { + groups.forEachIndexed{index,group-> + item(key="search-${group.first}"){MediaRow(vm,group.first,group.second,"search-${group.first}",landscape=group.first=="Episodes",entryFocus=if(index==0)resultsFocus else null)} + } + if(people.isNotEmpty())item(key="search-people"){PeopleRow(vm,people,if(groups.isEmpty())resultsFocus else null)} + } + } +} + +internal fun searchGroups(titles:List<Title>):List<Pair<String,List<Title>>> = + listOf("movie" to "Movies","show" to "TV shows","season" to "Seasons","collection" to "Collections","episode" to "Episodes") + .map{(type,label)->label to titles.filter{it.type==type}}.filter{it.second.isNotEmpty()} + +@Composable private fun PeopleRow(vm:KaleidoViewModel,people:List<CastMember>,entryFocus:FocusRequester?) { + Column { + Box(Modifier.padding(horizontal=Cinema.gutter)){SectionHeading("People")} + LazyRow(contentPadding=PaddingValues(horizontal=Cinema.gutter),horizontalArrangement=Arrangement.spacedBy(16.dp),modifier=Modifier.focusRestorer(fallback=entryFocus ?: FocusRequester.Default)) { + itemsIndexed(people,key={_,it->it.id}){index,actor-> + var focused by remember{mutableStateOf(false)} + Column(Modifier.width(108.dp).then(if(index==0&&entryFocus!=null)Modifier.focusRequester(entryFocus)else Modifier).navigationSound().onFocusChanged{focused=it.isFocused} + .clickable{vm.openActor(actor)}.semantics{contentDescription=actor.name},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)) + } + } } } } diff --git a/app/src/main/java/tv/kaleido/app/FocusedBrowse.kt b/app/src/main/java/tv/kaleido/app/FocusedBrowse.kt index 99a00cb..7d94b5e 100644 --- a/app/src/main/java/tv/kaleido/app/FocusedBrowse.kt +++ b/app/src/main/java/tv/kaleido/app/FocusedBrowse.kt @@ -39,9 +39,20 @@ import kotlinx.coroutines.Job import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.first import androidx.compose.runtime.saveable.rememberSaveable +import androidx.activity.compose.BackHandler +import androidx.compose.animation.core.animateFloatAsState +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) +/** Column id of a row's trailing "View all" card. */ +internal const val VIEW_ALL="view-all" +/** Captions sit over artwork-led backdrops; a soft shadow keeps them readable on bright scenes. */ +internal val CaptionShadow=Shadow(Color.Black.copy(alpha=.9f),Offset(0f,1.5f),6f) +internal fun isContinueHub(hub:Hub)=listOf("continue","ondeck","inprogress").any{hub.id.contains(it,true)} + private object BrowseScroll:BringIntoViewSpec { override fun calculateScrollDistance(offset:Float,size:Float,containerSize:Float)=0f } @@ -59,7 +70,7 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) { var previousHubs by remember(destination){mutableStateOf(hubs)} val restore=remember(hubs){ val focused=Snapshot.withoutReadObservation{vm.focusId} - hubs.withIndex().firstNotNullOfOrNull{(row,h)->val column=h.items.indexOfFirst{"${h.id}:${it.id}"==focused};if(column>=0)Triple(h.id,row,column)else null} + 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?.let{it.second+if(home)1 else 0} ?: 0 // Keep the hero/preview and adjacent rows prepared across vertical moves. @@ -148,7 +159,7 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) { val oldTitle=oldHub?.items?.getOrNull(oldColumn) val hubIds=hubs.map{it.id}.toSet() - val cardKeys=hubs.flatMap{hub->hub.items.map{"${hub.id}:${it.id}"}}.toSet() + val cardKeys=hubs.flatMap{hub->hub.items.map{"${hub.id}:${it.id}"}+"${hub.id}:$VIEW_ALL"}.toSet() rowStateByHub.keys.retainAll(hubIds) requesters.keys.retainAll(cardKeys) columns.keys.retainAll(hubIds) @@ -209,6 +220,27 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) { LaunchedEffect(navigation.pendingEntry,destination) { if(navigation.pendingEntry==destination){navigation.pendingEntry=null;navigation.enter?.invoke()} } + // Back from the catalog first returns to the hero (Home) or Discover; only then leaves. + var catalogFocus by remember{mutableStateOf(false)} + val inCatalog by remember{derivedStateOf{catalogFocus&&vm.focusId!="home-feature"}} + BackHandler(enabled=inCatalog&&vm.playing==null) { + 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)} + } + // 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 + withFrameNanos{} + val key=vm.focusId + runCatching{if(key=="home-feature")heroFocus.requestFocus()else requesters[key]?.requestFocus()} + } + var sectionMenu by remember{mutableStateOf(false)} + val sectionChoices=vm.sections.filter{it.type==vm.section?.type} + val sectionFocus=remember{FocusRequester()} val title=when(destination){"movies"->"Movies";"tv"->"TV Shows";else->"Home"} BoxWithConstraints(Modifier.fillMaxSize()) { val heroHeight=maxHeight*.80f-62.dp @@ -226,13 +258,20 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) { }else false },initialFocus=sectionEntry){} // Nothing sits right of Library; an unbounded search would open Home from the top bar. - NavigationLabel("Library",false,modifier=Modifier.focusProperties{up=navigation.top;down=navigation.entry;right=FocusRequester.Cancel}){vm.setAll(true)} + NavigationLabel("Library",false,modifier=Modifier.focusProperties{up=navigation.top;down=navigation.entry;right=if(sectionChoices.size>1)sectionFocus else FocusRequester.Cancel}){vm.setAll(true)} + Spacer(Modifier.weight(1f)) + // A second movie or TV library (e.g. 4K, Kids) is chosen here and remembered. + if(sectionChoices.size>1)TvButton((vm.section?.title ?: title)+" ⌄",Modifier.focusRequester(sectionFocus).focusProperties{up=navigation.top;right=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 + }){sectionMenu=true} } } Spacer(Modifier.fillMaxWidth().height(if(destination=="movies")137.dp else 119.dp)) } CompositionLocalProvider(LocalBringIntoViewSpec provides BrowseScroll) { - LazyColumn(state=list,modifier=Modifier.fillMaxWidth().weight(1f),verticalArrangement=Arrangement.spacedBy(15.dp),contentPadding=PaddingValues(bottom=22.dp)) { + LazyColumn(state=list,modifier=Modifier.fillMaxWidth().weight(1f).onFocusChanged{catalogFocus=it.hasFocus},verticalArrangement=Arrangement.spacedBy(15.dp),contentPadding=PaddingValues(bottom=22.dp)) { if(home)item(key="home-feature") { Box(Modifier.fillMaxWidth().height(heroHeight)) { feature?.let{item-> @@ -265,73 +304,83 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) { 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 wideEpisode=destination=="tv"&&!poster + val continuing=isContinueHub(hub) + // A row with more titles than Plex returned ends with a "View all" card. + val viewAll=hub.more&&hub.key.isNotBlank() + fun idAt(index:Int)=if(index==hub.items.size)VIEW_ALL else hub.items[index].id + fun indexOf(id:String)=if(id==VIEW_ALL)hub.items.size else hub.items.indexOfFirst{it.id==id} + fun rowKeys(column:Int)=Modifier.onPreviewKeyEvent{event-> + if(event.type==KeyEventType.KeyDown&&event.key in listOf(Key.DirectionLeft,Key.DirectionRight)) { + val pendingId=pendingColumns[hub.id] + val pendingIndex=pendingId?.let(::indexOf)?.takeIf{it>=0} ?: column + val target=pendingIndex+if(event.key==Key.DirectionLeft)-1 else 1 + if(target in 0 until hub.items.size+if(viewAll)1 else 0) { + val now=event.nativeKeyEvent.eventTime + val rapid=now-(horizontalTimes[hub.id] ?: 0L)<160L + horizontalTimes[hub.id]=now + pendingColumns[hub.id]=idAt(target) + navigationJob[0]?.cancel() + val state=rowStates[hub.id]!! + navigationJob[0]=scope.launch { + // KeyDown/KeyUp can arrive between frames. Commit focus once + // on the next frame, so accessibility doesn't force an extra + // catalog layout between those events. Bursts keep the latest + // logical column instead of dropping a move while awaiting layout. + withFrameNanos{} + if(!rapid)hub.items.getOrNull(target)?.let{vm.anticipate(it,cinematic=home)} + val visible=state.layoutInfo.visibleItemsInfo.any{it.index==target} + 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 delta=(anchor-state.firstVisibleItemIndex)*pitch-state.firstVisibleItemScrollOffset + if(kotlin.math.abs(delta)>1)state.animateScrollBy(delta,tween(140)) + }else{ + // Schedule one layout for the next frame instead of forcing + // synchronous composition between rapid remote events. + state.requestScrollToItem(anchor) + snapshotFlow{state.layoutInfo.visibleItemsInfo.any{it.index==target}}.first{it} + withFrameNanos{};runCatching{requesters.getOrPut("${hub.id}:${idAt(target)}"){FocusRequester()}.requestFocus()} + } + // A held direction snaps to the latest anchor. Repeatedly + // cancelling pixel animations and decoding transient backdrops + // costs more than the focus move; predict only after it settles. + if(rapid){delay(70);hub.items.getOrNull(target)?.let{vm.anticipate(it,cinematic=home)}} + } + } + true + }else if(event.type==KeyEventType.KeyDown&&event.key in listOf(Key.DirectionUp,Key.DirectionDown)) { + 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)moveToHero()else{withFrameNanos{};runCatching{navigation.section.requestFocus()}}} + } + else { + navigationJob[0]?.cancel() + val target=row+if(event.key==Key.DirectionUp)-1 else 1 + if(target in hubs.indices) { + val targetHub=hubs[target] + val selectedId=columns[targetHub.id] + val col=targetHub.items.indexOfFirst{it.id==selectedId}.takeIf{it>=0} ?: 0 + vm.anticipate(hubs[target].items[col],cinematic=home) + navigationJob[0]=scope.launch{moveToRow(targetHub.id,targetHub.items[col].id)} + } + } + true + }else false + } Column { - Text(hub.title,color=Accent,fontSize=16.sp,lineHeight=21.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(start=Cinema.gutter,bottom=5.dp)) + 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, - Modifier.onPreviewKeyEvent{event-> - if(event.type==KeyEventType.KeyDown&&event.key in listOf(Key.DirectionLeft,Key.DirectionRight)) { - val pendingId=pendingColumns[hub.id] - val pendingIndex=pendingId?.let{id->hub.items.indexOfFirst{it.id==id}}?.takeIf{it>=0} ?: column - val target=pendingIndex+if(event.key==Key.DirectionLeft)-1 else 1 - if(target in hub.items.indices) { - val now=event.nativeKeyEvent.eventTime - val rapid=now-(horizontalTimes[hub.id] ?: 0L)<160L - horizontalTimes[hub.id]=now - pendingColumns[hub.id]=hub.items[target].id - navigationJob[0]?.cancel() - val state=rowStates[hub.id]!! - navigationJob[0]=scope.launch { - // KeyDown/KeyUp can arrive between frames. Commit focus once - // on the next frame, so accessibility doesn't force an extra - // catalog layout between those events. Bursts keep the latest - // logical column instead of dropping a move while awaiting layout. - withFrameNanos{} - if(!rapid)vm.anticipate(hub.items[target],cinematic=home) - val visible=state.layoutInfo.visibleItemsInfo.any{it.index==target} - val anchor=(target-1).coerceAtLeast(0) - if(visible&&!rapid) { - runCatching{requesters.getOrPut("${hub.id}:${hub.items[target].id}"){FocusRequester()}.requestFocus()} - val pitch=with(density){(if(poster)130.dp else if(wideEpisode)274.dp else 224.dp).toPx()} - val delta=(anchor-state.firstVisibleItemIndex)*pitch-state.firstVisibleItemScrollOffset - if(kotlin.math.abs(delta)>1)state.animateScrollBy(delta,tween(140)) - }else{ - // Schedule one layout for the next frame instead of forcing - // synchronous composition between rapid remote events. - state.requestScrollToItem(anchor) - snapshotFlow{state.layoutInfo.visibleItemsInfo.any{it.index==target}}.first{it} - withFrameNanos{};runCatching{requesters.getOrPut("${hub.id}:${hub.items[target].id}"){FocusRequester()}.requestFocus()} - } - // A held direction snaps to the latest anchor. Repeatedly - // cancelling pixel animations and decoding transient backdrops - // costs more than the focus move; predict only after it settles. - if(rapid){delay(70);vm.anticipate(hub.items[target],cinematic=home)} - } - } - true - }else if(event.type==KeyEventType.KeyDown&&event.key in listOf(Key.DirectionUp,Key.DirectionDown)) { - 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)moveToHero()else{withFrameNanos{};runCatching{navigation.section.requestFocus()}}} - } - else { - navigationJob[0]?.cancel() - val target=row+if(event.key==Key.DirectionUp)-1 else 1 - if(target in hubs.indices) { - val targetHub=hubs[target] - val selectedId=columns[targetHub.id] - val col=targetHub.items.indexOfFirst{it.id==selectedId}.takeIf{it>=0} ?: 0 - vm.anticipate(hubs[target].items[col],cinematic=home) - navigationJob[0]=scope.launch{moveToRow(targetHub.id,targetHub.items[col].id)} - } - } - true - }else false - },onHovered={columns[hub.id]=item.id;pendingColumns[hub.id]=item.id;hovered.value=it;heroActive=false}) + 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}) + } + if(viewAll)item(key=VIEW_ALL,contentType="viewAll") { + val focusKey="${hub.id}:$VIEW_ALL" + ViewAllCard(vm,hub,focusKey,poster,wideEpisode,requesters.getOrPut(focusKey){FocusRequester()},rowKeys(hub.items.size)) } } } @@ -345,6 +394,7 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) { Spacer(Modifier.height(14.dp));TvButton("Open library",onClick={vm.setAll(true)});Spacer(Modifier.height(8.dp));TvButton("Try again",onClick={vm.retry()}) } } + if(sectionMenu)ChoiceDialog("Libraries",sectionChoices.map{it.title},sectionChoices.indexOf(vm.section),{sectionMenu=false}){vm.chooseSection(sectionChoices[it]);sectionMenu=false} } /** Focus changes invalidate this small preview scope, never the catalog hierarchy. */ @@ -388,7 +438,7 @@ private class CardStaging { fun frames()=if(entering)count++/3 else count++%3 } -@Composable private fun BrowseCard(vm:KaleidoViewModel,item:Title,focusKey:String,poster:Boolean,wideEpisode:Boolean,entry:FocusRequester?,requester:FocusRequester,staging:CardStaging,modifier:Modifier,onHovered:(Title)->Unit) { +@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) { var focused by remember{mutableStateOf(false)} val stage=remember{staging.frames()} var filled by remember{mutableStateOf(stage<0)} @@ -398,10 +448,11 @@ private class CardStaging { // Only the card being restored launches an effect; checking inside one per card cost a // coroutine for every card in a newly shown section. if(remember{Snapshot.withoutReadObservation{vm.focusId==focusKey}})LaunchedEffect(Unit){withFrameNanos{};runCatching{requester.requestFocus()};onHovered(item)} - Column(modifier.width(width).then(if(entry!=null)Modifier.focusRequester(entry)else Modifier).focusRequester(requester).navigationSound().onFocusChanged{ + // A slight lift read in the layer: no animation or recomposition per card, bounds never move. + Column(modifier.width(width).graphicsLayer{val lift=if(focused)1.05f else 1f;scaleX=lift;scaleY=lift}.then(if(entry!=null)Modifier.focusRequester(entry)else Modifier).focusRequester(requester).navigationSound().onFocusChanged{ focused=it.isFocused if(it.isFocused){vm.focusId=focusKey;onHovered(item)} - }.clickable{vm.open(item)}.clearAndSetSemantics{ + }.titleActions{vm.showActions(item,continuing)}.clickable{vm.open(item)}.clearAndSetSemantics{ contentDescription=listOf(item.displayTitle,item.subtitle,item.watchStatus(vm.watchedPercent)).filter{it.isNotBlank()}.joinToString(". ") this.focused=focused;role=Role.Button onClick{vm.open(item);true} @@ -409,18 +460,39 @@ 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) - if(item.offset>0&&!poster)Box(Modifier.align(Alignment.BottomCenter).padding(6.dp).fillMaxWidth().height(2.dp).background(Color.Black.copy(alpha=.65f))) { + 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)) } WatchBadge(item,vm.watchedPercent) }else Box(Modifier.fillMaxSize().background(Panel)) - if(focused)Box(Modifier.fillMaxSize().border(2.dp,Color.White,RoundedCornerShape(4.dp))) + // A white ring with a dark inner edge stays visible on white and black artwork alike. + if(focused)Box(Modifier.fillMaxSize().border(3.dp,Color.White,RoundedCornerShape(4.dp)).padding(3.dp).border(1.dp,Color.Black.copy(alpha=.6f),RoundedCornerShape(2.dp))) } // 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,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=5.dp).height(16.dp)) - if(!poster)Text(if(item.type=="episode")"S${item.parentIndex} · E${item.index} ${item.title}"else if(item.offset>0)"${((item.duration-item.offset)/60000).coerceAtLeast(0)} min left"else item.year,color=Muted,fontSize=9.sp,lineHeight=12.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.height(14.dp)) + 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)) + 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)) } } } + +/** The last card of a row with more titles: opens the hub's full list. */ +@Composable private fun ViewAllCard(vm:KaleidoViewModel,hub:Hub,focusKey:String,poster:Boolean,wideEpisode:Boolean,requester:FocusRequester,modifier:Modifier) { + var focused by remember{mutableStateOf(false)} + val lift by animateFloatAsState(if(focused)1.05f else 1f,tween(150),label="viewAllFocus") + if(remember{Snapshot.withoutReadObservation{vm.focusId==focusKey}})LaunchedEffect(Unit){withFrameNanos{};runCatching{requester.requestFocus()}} + Column(modifier.width(if(poster)120.dp else if(wideEpisode)264.dp else 214.dp).graphicsLayer{scaleX=lift;scaleY=lift}.focusRequester(requester).navigationSound().onFocusChanged{ + focused=it.isFocused;if(it.isFocused)vm.focusId=focusKey + }.clickable{vm.openHub(hub)}.clearAndSetSemantics{ + contentDescription="View all ${hub.title}";this.focused=focused;role=Role.Button;onClick{vm.openHub(hub);true} + }) { + Box(Modifier.fillMaxWidth().aspectRatio(if(poster)2f/3f else 16f/9f).clip(RoundedCornerShape(4.dp)).background(if(focused)Accent else Color.White.copy(alpha=.08f)),contentAlignment=Alignment.Center) { + Column(horizontalAlignment=Alignment.CenterHorizontally,verticalArrangement=Arrangement.spacedBy(6.dp)) { + Icon(Icons.Outlined.GridView,null,tint=if(focused)Ink else Accent,modifier=Modifier.size(22.dp)) + Text("View all",color=if(focused)Ink else Accent,fontSize=11.sp,fontWeight=FontWeight.SemiBold) + } + } + Spacer(Modifier.height(if(poster)21.dp else 35.dp)) + } +} diff --git a/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt b/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt index 4b08727..903c353 100644 --- a/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt +++ b/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt @@ -7,6 +7,7 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.setValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableIntStateOf import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Job import kotlinx.coroutines.async @@ -52,7 +53,18 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { 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 searchResults by mutableStateOf(SearchResults()); private set + /** A voice search should start when Search opens, e.g. from the remote's search key. */ + var voicePending by mutableStateOf(false); private set + /** The long-press/Menu actions sheet, and the row it came from (for Remove from Continue Watching). */ + var contextItem by mutableStateOf<Title?>(null); private set + var contextFromContinue by mutableStateOf(false); private set + var hubTitles by mutableStateOf(emptyList<Title>()); private set + /** Bumped when playback closes, so the screen below can restore its focus. */ + var playbackReturn by mutableIntStateOf(0); private set + private var retryAction:(()->Unit)?=null + private var previousTab="home" + private val mediaChoices=mutableMapOf<String,Int>() var query by mutableStateOf(""); private set var pin by mutableStateOf<Pin?>(null); private set var servers by mutableStateOf(emptyList<Server>()); private set @@ -69,6 +81,13 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { /** A verified APK for [update], kept so a cancelled installer can be reopened without downloading again. */ var readyApk by mutableStateOf<File?>(null); private set var streamQuality by mutableStateOf(savedStreamQuality()); private set + var remoteQuality by mutableStateOf(preferences.getString("remoteQuality",null)?.let{n->StreamQuality.entries.firstOrNull{it.name==n}} ?: StreamQuality.FullHD); private set + /** Seconds before the next episode starts; 0 turns autoplay off. */ + var autoplaySeconds by mutableIntStateOf(preferences.getInt("autoplaySeconds",5)); private set + var autoSkipIntro by mutableStateOf(preferences.getBoolean("autoSkipIntro",false)); private set + var autoSkipCredits by mutableStateOf(preferences.getBoolean("autoSkipCredits",false)); private set + var subtitleSize by mutableStateOf(preferences.getString("subtitleSize",null)?.let{n->SubtitleSize.entries.firstOrNull{it.name==n}} ?: SubtitleSize.Normal); private set + var subtitleStyle by mutableStateOf(preferences.getString("subtitleStyle",null)?.let{n->SubtitleStyle.entries.firstOrNull{it.name==n}} ?: SubtitleStyle.Box); private set /** Debug test intents force a delivery mode (0 file, 1 direct stream, 2 convert); never set in release. */ var debugMode by mutableStateOf<Int?>(null); private set var debugValidation=false; private set @@ -109,21 +128,26 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { if(session!=null) initialize() else linkAccount() checkUpdate(false) } - private fun launchLoad(block: suspend () -> Unit) { + /** [retry] repeats this action from the error dialog; without it, Try again reloads the page. */ + private fun launchLoad(retry:(()->Unit)?=null,block: suspend () -> Unit) { val generation=++loadGeneration loadJob?.cancel() loadJob=viewModelScope.launch { busy=true;error=null - try { block() } catch(e: CancellationException){throw e} catch(e: Exception){error=e.message ?: "Something went wrong. Please try again."} finally {if(generation==loadGeneration)busy=false} + try { block() } catch(e: CancellationException){throw e} catch(e: Exception){retryAction=retry;error=e.message ?: "Something went wrong. Please try again."} finally {if(generation==loadGeneration)busy=false} } } - fun dismissError(){error=null} + private fun fail(message:String,retry:(()->Unit)?){retryAction=retry;error=message} + fun dismissError(){error=null;retryAction=null} + /** The connection in use is on this network; remote connections use [remoteQuality]. */ + val localConnection get()=session?.server?.let(::isLocalAddress) ?: true + val activeQuality get()=if(localConnection)streamQuality else remoteQuality fun initialize() { if(initializeJob?.isActive==true)return initializeJob=viewModelScope.launch { busy=true;error=null try { - val validated=api.validate(session ?: return@launch) + val validated=reconnect(session ?: return@launch) api.session=validated;session=validated;application.secure.save(validated) sections=api.sections();homeHubs=loadHome() if(page.kind in listOf("movies","tv"))loadPage(true) @@ -131,6 +155,17 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { finally{if(loadJob?.isActive!=true)busy=false} } } + /** + * Validate the saved address. If it no longer answers (a changed LAN address, a rotated + * plex.direct name, or leaving the network), ask plex.tv for this server's current connections. + */ + private suspend fun reconnect(saved:Session):Session = try{api.validate(saved)}catch(e:CancellationException){throw e}catch(e:Exception){ + if(saved.accountToken.isBlank()||e is PlexException&&e.status in listOf(401,403))throw e + val server=runCatching{api.servers(saved.accountToken)}.getOrNull()?.let{list-> + list.firstOrNull{it.id==saved.machineId&&saved.machineId.isNotBlank()} ?: list.firstOrNull{it.name==saved.serverName} + } ?: throw e + api.connect(server,saved.accountToken) + } private suspend fun loadHome():List<Hub> { val fresh=fetchHome(sections);homeFeatures=fresh.features;return fresh.hubs } @@ -241,8 +276,32 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { } fun signOut(){loadJob?.cancel();initializeJob?.cancel();application.secure.clear();api.session=null;session=null;homeHubs=emptyList();discoverHubs=emptyList();sections=emptyList();library=emptyList();sectionCache.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;cancelAnticipation();loadJob?.cancel();busy=false;focusId="";if(kind in listOf("movies","tv"))allTitles=false;pages=listOf(Page(kind));loadPage(true)} + fun tab(kind: String){ + if(pages.size==1&&page.kind==kind)return + // Search and Settings return to the browsing tab they were opened from. + if(kind in listOf("search","settings")&&pages.first().kind in listOf("home","movies","tv"))previousTab=pages.first().kind + 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()} + /** Opens an episode's show, or a season's show. */ + fun openShow(item:Title){val id=if(item.type=="episode")item.grandparentId else item.parentId;if(id.isBlank())return;pages=pages+Page("details",id,if(item.type=="episode")item.grandparentTitle else item.parentTitle,focusId);loadPage()} + fun openSeason(item:Title){if(item.parentId.isBlank())return;pages=pages+Page("group",item.parentId,item.parentTitle,focusId);loadPage()} + /** "View all" for a Plex hub row. */ + fun openHub(hub:Hub){if(hub.key.isBlank())return;pages=pages+Page("hub",hub.key,hub.title,focusId);focusId="";loadPage()} + fun openSearch(text:String=""){if(page.kind!="search")tab("search");if(text.isNotBlank())search(text)} + fun requestVoiceSearch(){openSearch();voicePending=true} + fun voiceStarted(){voicePending=false} + fun showActions(item:Title,fromContinue:Boolean=false){contextItem=item;contextFromContinue=fromContinue} + fun dismissActions(){contextItem=null;contextFromContinue=false} + fun removeFromContinueWatching(item:Title){ + viewModelScope.launch { + try{api.removeFromContinueWatching(item);homeHubs=loadHome();sectionCache.clear()} + catch(e:CancellationException){throw e}catch(e:Exception){fail(e.message ?: "Plex could not update Continue Watching."){removeFromContinueWatching(item)}} + } + } + /** The version (Plex Media) chosen for this title in this session; the first version by default. */ + fun mediaIndex(item:Title)=(mediaChoices[item.id] ?: 0).coerceIn(0,(item.media.size-1).coerceAtLeast(0)) + fun chooseMedia(item:Title,index:Int){mediaChoices[item.id]=index;detail=detail?.let{if(it.id==item.id)it.copy()else it}} fun openActor(actor:CastMember){ if(actor.id.isBlank())return pages=pages+Page("actor",actor.id,actor.name,focusId,actor);focusId="";loadPage() @@ -250,10 +309,11 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { fun back(): Boolean { if(playing!=null){stopPlayback();return true} if(pages.size>1){focusId=page.returnFocus;pages=pages.dropLast(1);loadPage();return true} + if(page.kind in listOf("search","settings")){tab(previousTab);return true} if(page.kind!="home"){tab("home");return true} return false } - fun retry(){if(session==null)linkAccount() else if(sections.isEmpty())initialize() else loadPage()} + fun retry(){val action=retryAction;retryAction=null;error=null;if(action!=null)action() else if(session==null)linkAccount() else if(sections.isEmpty())initialize() else loadPage()} private fun loadPage(resetLibrary: Boolean=false) { when(page.kind){ "home" -> if(homeHubs.isEmpty())launchLoad { homeHubs=loadHome() } @@ -262,19 +322,14 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { val type=if(page.kind=="movies")"movie"else "show" if(!resetLibrary&&!sectionStale&§ion?.type==type&&library.isNotEmpty()&&discoverHubs.isNotEmpty())return sectionStale=false - loadJob?.cancel();section=sections.firstOrNull{it.type==type};sort="titleSort:asc";genre="";unwatched=false;allTitles=false - val s=section ?: return - 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 - launchLoad {coroutineScope { - val g=async{api.genres(s.id)};val h=async{api.hubs(s.id)};val l=async{api.library(s.id)} - val seasons:kotlinx.coroutines.Deferred<List<Title>>?=if(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) - discoverHubs=rows;genres=genreList;library=p.items;total=p.total - }} + // Each destination remembers the library chosen for it, e.g. "4K Movies". + val preferred=preferences.getString("section.$type",null) + loadSection(sections.firstOrNull{it.type==type&&it.id==preferred} ?: sections.firstOrNull{it.type==type}) + } + "hub" -> { + hubTitles=emptyList() + val key=page.id + launchLoad({loadPage()}) {hubTitles=api.hubItems(key)} } "details","group" -> { detail=detailsCache[page.id];children=emptyList();detailRelated=emptyList() @@ -282,7 +337,9 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { 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()} + // An episode lists its season's episodes, so neighbours are one move away. + val groups=async{if(d.type in listOf("show","season","collection"))api.children(id) + else if(d.type=="episode"&&d.parentId.isNotBlank())runCatching{api.children(d.parentId)}.getOrDefault(emptyList())else emptyList()} val related=async{try{when(d.type){"show"->api.relatedShows(id).filter{it.id!=id};"movie"->api.relatedMovies(id);else->emptyList()}}catch(e:CancellationException){throw e}catch(_:Exception){emptyList()}} children=groups.await();detailRelated=related.await() } @@ -297,12 +354,32 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { "settings" -> {busy=false;error=null} } } - fun chooseSection(s: Section){section=s;genre="";sort="titleSort:asc";launchLoad {genres=api.genres(s.id);discoverHubs=api.hubs(s.id);val p=api.library(s.id);library=p.items;total=p.total}} + /** Shows [s] in its destination, from cache when possible, with default filters. */ + private fun loadSection(s:Section?) { + loadJob?.cancel();section=s;sort="titleSort:asc";genre="";unwatched=false + if(s==null){discoverHubs=emptyList();library=emptyList();total=0;genres=emptyList();return} + 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 + 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)} + 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} + }} + } + fun chooseSection(s: Section){ + if(s.id==section?.id)return + preferences.edit().putString("section.${s.type}",s.id).apply() + cancelAnticipation();focusId=if(allTitles)"library-entry"else "discovery-entry";loadSection(s) + } fun setAll(value: Boolean){focusId=if(value)"library-entry"else "discovery-entry";allTitles=value} fun filter(sortValue: String=sort,genreValue: String=genre,unwatchedValue: Boolean=unwatched){sort=sortValue;genre=genreValue;unwatched=unwatchedValue;refreshLibrary()} 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 search(text: String){query=text;searchJob?.cancel();searchJob=viewModelScope.launch {delay(350);if(text.isBlank()){searchResults=SearchResults();return@launch};busy=true;error=null;try{searchResults=api.search(text)}catch(e:CancellationException){throw e}catch(e:Exception){fail(e.message ?: "Search is unavailable."){search(text)}}finally{busy=false}}} fun mark(item: Title) { if(markingId!=null)return markingId=item.id @@ -311,7 +388,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { 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} + }catch(e:CancellationException){throw e}catch(e:Exception){fail(e.message ?: "Plex could not update this title."){mark(item)}}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()}}} @@ -338,12 +415,13 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { fun refreshed(hubs:List<Hub>)=hubs.map{h->h.copy(items=h.items.map(::refreshedTitle))} homeHubs=refreshed(homeHubs);discoverHubs=refreshed(discoverHubs) library=library.map(::refreshedTitle);children=children.map(::refreshedTitle) - searchResults=searchResults.map(::refreshedTitle) + searchResults=searchResults.copy(titles=searchResults.titles.map(::refreshedTitle)) + hubTitles=hubTitles.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 { + fun play(item: Title,fromStart: Boolean=false):Unit=launchLoad({play(item,fromStart)}) { debugMode=null;debugValidation=false;debugValidationFile=null val playable=if(item.type=="show" || item.type=="season") { val episodes=api.allEpisodes(item.id);episodes.firstOrNull {it.offset>0&&!it.watched} ?: episodes.firstOrNull {!it.watched} ?: episodes.firstOrNull() ?: throw PlexException("No playable episodes are available.") @@ -373,14 +451,22 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { val i=episodes.indexOfFirst{it.id==item.id};val next=if(i>=0)episodes.getOrNull(i+1)else null if(next!=null){val metadata=api.details(next.id);if(playing?.id==item.id){startFromZero=true;playing=metadata}} else if(playing?.id==item.id)stopPlayback() - }catch(e:CancellationException){throw e}catch(e:Exception){error=e.message ?: "The next episode could not be loaded."}finally{transitioningEpisode=false} + }catch(e:CancellationException){throw e}catch(e:Exception){fail(e.message ?: "The next episode could not be loaded."){nextEpisode(item)}}finally{transitioningEpisode=false} } } - fun stopPlayback(){playing=null;sectionCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();launchLoad {homeHubs=loadHome();detail?.let {if(it.type in listOf("movie","episode"))detail=api.details(it.id)}}} + fun stopPlayback(){if(playing!=null)playbackReturn++;playing=null;sectionCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();launchLoad {homeHubs=loadHome();detail?.let {if(it.type in listOf("movie","episode"))detail=api.details(it.id)}}} // Earlier versions stored a mode (Original/Direct stream/Transcode) and a separate transcode quality. private fun savedStreamQuality()=preferences.getString("streamQuality",null)?.let{name->StreamQuality.entries.firstOrNull{it.name==name}} ?: if(preferences.getInt("playbackModeV2",1)==2)(if(preferences.getInt("quality",20000)>20000)StreamQuality.UltraHD else StreamQuality.FullHD)else StreamQuality.Original fun chooseStreamQuality(value: StreamQuality){streamQuality=value;preferences.edit().putString("streamQuality",value.name).apply()} + fun chooseRemoteQuality(value: StreamQuality){remoteQuality=value;preferences.edit().putString("remoteQuality",value.name).apply()} + /** The player's quality menu changes the preference for the connection in use. */ + fun chooseActiveQuality(value: StreamQuality)=if(localConnection)chooseStreamQuality(value)else chooseRemoteQuality(value) + fun chooseAutoplaySeconds(value:Int){autoplaySeconds=value.coerceAtLeast(0);preferences.edit().putInt("autoplaySeconds",autoplaySeconds).apply()} + fun chooseAutoSkipIntro(value:Boolean){autoSkipIntro=value;preferences.edit().putBoolean("autoSkipIntro",value).apply()} + fun chooseAutoSkipCredits(value:Boolean){autoSkipCredits=value;preferences.edit().putBoolean("autoSkipCredits",value).apply()} + fun chooseSubtitleSize(value:SubtitleSize){subtitleSize=value;preferences.edit().putString("subtitleSize",value.name).apply()} + fun chooseSubtitleStyle(value:SubtitleStyle){subtitleStyle=value;preferences.edit().putString("subtitleStyle",value.name).apply()} fun chooseWatchedPercent(value:Int){watchedPercent=value.coerceIn(50,100);preferences.edit().putInt("watchedPercent",watchedPercent).apply()} fun chooseNavigationSounds(value:Boolean){navigationSounds=value;preferences.edit().putBoolean("navigationSounds",value).apply()} fun checkUpdate(manual: Boolean=true){viewModelScope.launch { diff --git a/app/src/main/java/tv/kaleido/app/MainActivity.kt b/app/src/main/java/tv/kaleido/app/MainActivity.kt index 6e14a4c..9b32dff 100644 --- a/app/src/main/java/tv/kaleido/app/MainActivity.kt +++ b/app/src/main/java/tv/kaleido/app/MainActivity.kt @@ -40,8 +40,24 @@ class MainActivity: ComponentActivity() { // Compose paints Ink over the whole window; the theme background only covers launch. window.setBackgroundDrawable(null) debugPlayback(intent) + searchIntent(intent) + } + override fun onNewIntent(intent: Intent) {super.onNewIntent(intent);setIntent(intent);debugPlayback(intent);searchIntent(intent)} + /** System and Assistant searches ("search for Silo in Kaleido") open Search with their query. */ + private fun searchIntent(intent: Intent) { + if(intent.action!=Intent.ACTION_SEARCH&&intent.action!="com.google.android.gms.actions.SEARCH_ACTION")return + val query=intent.getStringExtra(android.app.SearchManager.QUERY).orEmpty().trim() + if(model.session!=null)model.openSearch(query) + } + /** The remote's search key (and the system's search request) starts a voice search inside Kaleido. */ + override fun onKeyDown(keyCode: Int, event: android.view.KeyEvent): Boolean { + if(keyCode==android.view.KeyEvent.KEYCODE_SEARCH&&model.session!=null&&model.playing==null){if(event.repeatCount==0)model.requestVoiceSearch();return true} + return super.onKeyDown(keyCode,event) + } + override fun onSearchRequested(): Boolean { + if(model.session==null||model.playing!=null)return false + model.requestVoiceSearch();return true } - override fun onNewIntent(intent: Intent) {super.onNewIntent(intent);setIntent(intent);debugPlayback(intent)} private fun debugPlayback(intent: Intent) {if(BuildConfig.DEBUG){ intent.getStringExtra("testFixture")?.let{model.debugPlayFixture(it);return} intent.getStringExtra("testTitleId")?.let{model.debugPlay(it,intent.getLongExtra("testOffset",90000),intent.getIntExtra("testMode",0),intent.getBooleanExtra("testValidation",false))} diff --git a/app/src/main/java/tv/kaleido/app/Models.kt b/app/src/main/java/tv/kaleido/app/Models.kt index b30be85..141f986 100644 --- a/app/src/main/java/tv/kaleido/app/Models.kt +++ b/app/src/main/java/tv/kaleido/app/Models.kt @@ -6,8 +6,20 @@ 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="") -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 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>, + 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"} + val atmos get()=parts.firstOrNull()?.streams.orEmpty().any{it.type==2&&it.title.contains("Atmos",true)} + val size get()=parts.sumOf{it.size} + /** One line describing this version, e.g. "4K · Dolby Vision · HEVC · EAC3 7.1 Atmos · 17 Mbps". */ + fun description(includeSize:Boolean=false):String = listOf(resolutionLabel,dynamicRange,videoCodec.uppercase(), + listOf(audioCodec.uppercase(),channelLabel,if(atmos)"Atmos"else "").filter{it.isNotBlank()}.joinToString(" "), + if(bitrate>0)"${(bitrate+500)/1000} Mbps"else "",if(includeSize&&size>0)fileSize(size)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) { @@ -24,7 +36,7 @@ data class Title( 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 castMembers:List<CastMember> = emptyList() + val castMembers:List<CastMember> = emptyList(),val subtype:String="",val extras:List<Title> = emptyList() ) { val remainingEpisodes get() = (leafCount-viewedLeafCount).coerceAtLeast(0) val fullyWatched get() = isWatched() @@ -36,24 +48,51 @@ data class Title( type in listOf("show","season")&&leafCount>0 -> "$remainingEpisodes episodes remaining" else -> "" } - val displayTitle get() = if (type == "episode") grandparentTitle.ifBlank { title } else title - val subtitle get() = when(type) { "episode" -> "S${parentIndex} · E${index} $title"; "season" -> "$leafCount episodes"; "show" -> "${year} · $leafCount episodes"; else -> listOf(year, if(duration>0) "${duration/60000} min" else "", genres.firstOrNull().orEmpty()).filter { it.isNotBlank() }.joinToString(" · ") } + /** Seasons and episodes are ambiguous without their show, except where the show is already shown. */ + val displayTitle get() = when(type) { + "episode" -> grandparentTitle.ifBlank { title } + "season" -> if(parentTitle.isNotBlank()&&!title.startsWith(parentTitle))"$parentTitle · $title" else title + else -> title + } + val subtitle get() = when(type) { "episode" -> "S${parentIndex} · E${index} $title"; "season" -> "$leafCount episodes"; "show" -> "${year} · $leafCount episodes"; "clip" -> listOf(extraLabel,if(duration>0)clockTime(duration)else "").filter{it.isNotBlank()}.joinToString(" · "); else -> listOf(year, if(duration>0) "${duration/60000} min" else "", genres.firstOrNull().orEmpty()).filter { it.isNotBlank() }.joinToString(" · ") } val progress get() = if(duration>0) (offset.toFloat()/duration).coerceIn(0f,1f) else 0f + val extraLabel get() = when(subtype) { + "trailer"->"Trailer";"behindTheScenes"->"Behind the scenes";"deletedScene"->"Deleted scene";"featurette"->"Featurette" + "interview"->"Interview";"sceneOrSample"->"Scene";"short"->"Short";else->if(type=="clip")"Extra"else "" + } + /** Extras Kaleido can play: local or proxied clips with a media file. */ + val playableExtras get() = extras.filter{it.media.firstOrNull()?.parts?.isNotEmpty()==true} + val trailer get() = playableExtras.firstOrNull{it.subtype=="trailer"} companion object { fun parse(j: JSONObject): Title = Title( j.optString("ratingKey",j.optString("key")), j.optString("key"), j.optString("type"), j.optString("title"), j.optString("summary"), j.optString("thumb",j.optString("parentThumb",j.optString("grandparentThumb"))), j.optString("art",j.optString("grandparentArt")), j.optString("year"),j.optLong("duration"),j.optLong("viewOffset"), j.optInt("viewCount")>0,AudienceScore.parseAll(j).joinToString(" · "){it.label},j.optString("contentRating"),j.optString("parentTitle"),j.optString("grandparentTitle"),j.optString("parentRatingKey"),j.optString("grandparentRatingKey"), j.optInt("index"),j.optInt("parentIndex"),j.optInt("leafCount"),j.optInt("viewedLeafCount"),j.optJSONArray("Genre").objects().map { it.optString("tag") },j.optJSONArray("Role").objects().take(10).map { it.optString("tag") }, - j.optJSONArray("Media").objects().map { m -> Media(m.optString("id"),m.optString("container"),m.optString("videoCodec"),m.optString("audioCodec"),m.optString("videoResolution"),m.optInt("width"),m.optInt("height"),m.optInt("bitrate"),m.optJSONArray("Part").objects().map { p -> Part(p.optString("id"),p.optString("key"),p.optJSONArray("Stream").objects().map { s -> Stream(s.optString("id"),s.optInt("streamType"),s.optString("codec"),s.optString("language",s.optString("languageCode","Unknown")),s.optString("displayTitle",s.optString("title",s.optString("language","Unknown"))),s.optBoolean("selected"),s.optString("key"),s.optInt("channels"),s.optInt("index",-1)) },p.optString("indexes")) }) }, + j.optJSONArray("Media").objects().map(::parseMedia), j.optJSONArray("Marker").objects().map { Marker(it.optString("type"),it.optLong("startTimeOffset"),it.optLong("endTimeOffset")) }, j.optJSONArray("Image").objects().firstOrNull{it.optString("type")=="clearLogo"}?.optString("url").orEmpty(), 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"))}, + j.optJSONArray("Chapter").objects().mapIndexed{position,c->Chapter(c.optInt("index"),chapterTitle(c.optString("title"),position),c.optLong("startTimeOffset"),c.optLong("endTimeOffset"),c.optString("thumb"))}, 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}} + j.optJSONArray("Role").objects().map(CastMember::parse).filter{it.name.isNotBlank()}.distinctBy{it.id.ifBlank{it.name}}, + j.optString("subtype"),j.optJSONObject("Extras")?.optJSONArray("Metadata").objects().map(::parse) ) + private fun parseMedia(m:JSONObject):Media { + val parts=m.optJSONArray("Part").objects().map { p -> Part(p.optString("id"),p.optString("key"),p.optJSONArray("Stream").objects().map { s -> Stream(s.optString("id"),s.optInt("streamType"),s.optString("codec"),s.optString("language",s.optString("languageCode","Unknown")),s.optString("displayTitle",s.optString("title",s.optString("language","Unknown"))),s.optBoolean("selected"),s.optString("key"),s.optInt("channels"),s.optInt("index",-1)) },p.optString("indexes"),p.optLong("duration"),p.optLong("size")) } + val video=m.optJSONArray("Part").objects().flatMap{it.optJSONArray("Stream").objects()}.firstOrNull{it.optInt("streamType")==1} + return Media(m.optString("id"),m.optString("container"),m.optString("videoCodec"),m.optString("audioCodec"),m.optString("videoResolution"),m.optInt("width"),m.optInt("height"),m.optInt("bitrate"),parts, + video?.let(::dynamicRange).orEmpty(),m.optInt("audioChannels")) + } + internal fun dynamicRange(video:JSONObject):String = when { + video.optBoolean("DOVIPresent") -> "Dolby Vision" + video.optString("colorTrc")=="smpte2084" -> "HDR10" + video.optString("colorTrc")=="arib-std-b67" -> "HLG" + else -> "" + } + /** Plex chapter indexes are already 1-based; untitled chapters are numbered by position. */ + internal fun chapterTitle(title:String,position:Int)=title.ifBlank{"Chapter ${position+1}"} } } @@ -84,8 +123,21 @@ 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 -data class Hub(val id: String, val title: String, val items: List<Title>) +/** [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()) 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) + +/** Whether a server address is on this network: plex.direct names encode the server's IP. */ +internal fun isLocalAddress(url:String):Boolean { + val host=runCatching{java.net.URI(url).host}.getOrNull()?.lowercase()?.trim('[',']') ?: return false + val ip=if(host.endsWith(".plex.direct"))host.substringBefore('.').replace('-','.')else host + if(host=="localhost"||host.endsWith(".local")||!host.contains('.')&&!host.contains(':'))return true + val octets=ip.split('.').map{it.toIntOrNull() ?: return ip.startsWith("fd")||ip.startsWith("fe80")} + if(octets.size!=4||octets.any{it !in 0..255})return false + val (a,b)=octets + return a==10||a==127||a==192&&b==168||a==172&&b in 16..31||a==169&&b==254||a==100&&b in 64..127 +} diff --git a/app/src/main/java/tv/kaleido/app/Playback.kt b/app/src/main/java/tv/kaleido/app/Playback.kt index 3cdce91..6b4b05c 100644 --- a/app/src/main/java/tv/kaleido/app/Playback.kt +++ b/app/src/main/java/tv/kaleido/app/Playback.kt @@ -66,12 +66,18 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) { private val validation=BuildConfig.DEBUG&&vm.debugValidation private val localValidationFile=if(validation)vm.debugValidationFile else null private val audit=if(validation)PlaybackValidationLog(app,item,player)else null + /** The version chosen on the details page, and its parts (stacked files) on one combined timeline. */ + val mediaIndex=vm.mediaIndex(item) + val media=item.media.getOrElse(mediaIndex){item.media.first()} + private val parts=media.parts + private val local=vm.localConnection + private val quality get()=vm.activeQuality // Preserve the actual file first; Plex's generic HLS profile can convert even with directStream=1. - var mode by mutableIntStateOf(vm.debugMode ?: if(vm.streamQuality==StreamQuality.Original)0 else 2);private set + var mode by mutableIntStateOf(vm.debugMode ?: if(quality==StreamQuality.Original)0 else 2);private set private var serverConverting by mutableStateOf(false) private var serverAudioConverting by mutableStateOf(false) val qualityLabel get()=when { - mode==2->"Converting · "+vm.streamQuality.conversion.label + mode==2->"Converting · "+quality.conversion.label serverConverting->if(serverAudioConverting)"Converted video and audio"else "Converted video" serverAudioConverting->"Original video · Converted audio" else->StreamQuality.Original.label @@ -79,7 +85,7 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) { var loading by mutableStateOf(true);private set var error by mutableStateOf<String?>(null);private set var position by mutableLongStateOf(if(vm.startFromZero)0 else item.offset);private set - var duration by mutableLongStateOf(item.duration);private set + var duration by mutableLongStateOf(item.duration.takeIf{it>0} ?: parts.sumOf{it.duration});private set var bufferedPosition by mutableLongStateOf(position);private set var scrubPosition by mutableStateOf<Long?>(null);private set var playbackRate by mutableFloatStateOf(1f);private set @@ -87,8 +93,11 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) { var isPlaying by mutableStateOf(false);private set var ended by mutableStateOf(false);private set var tracks by mutableStateOf(Tracks.EMPTY);private set - var activeSubtitle by mutableStateOf(item.media.first().parts.first().streams.firstOrNull{it.type==3&&it.selected}?.id ?: "0");private set - var activeAudio by mutableStateOf(item.media.first().parts.first().streams.firstOrNull{it.type==2&&it.selected}?.id.orEmpty());private set + var partIndex by mutableIntStateOf(partFor(parts,position));private set + val part get()=parts[partIndex.coerceIn(0,parts.lastIndex)] + private val partOffset get()=partStart(parts,partIndex) + var activeSubtitle by mutableStateOf(parts.first().streams.firstOrNull{it.type==3&&it.selected}?.id ?: "0");private set + var activeAudio by mutableStateOf(parts.first().streams.firstOrNull{it.type==2&&it.selected}?.id.orEmpty());private set private var streamSession=UUID.randomUUID().toString() private var streamStart=0L private var preparing=false @@ -99,8 +108,10 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) { private val reports=Channel<TimelineReport>(Channel.UNLIMITED) private val reportJob=app.scope.launch { val watched=WatchedProgress{api.watched(item,true);withContext(Dispatchers.Main){vm.refreshWatched(item)}} + // Trailers and other extras are not library progress. + val synced=!validation&&item.type!="clip" for(r in reports) { - if(!validation) { + if(synced) { runCatching {api.timeline(item,r.position,r.state,r.duration,streamSession)}.onFailure {Log.w("KaleidoPlayback","Timeline sync unavailable")} runCatching{watched.report(r.position,r.duration,vm.watchedPercent)} .onFailure{Log.w("KaleidoPlayback","Watched status sync unavailable")} @@ -112,7 +123,14 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) { audit?.let{player.addAnalyticsListener(it)} player.addListener(object: Player.Listener { override fun onPlaybackStateChanged(state: Int) { - loading=state==Player.STATE_BUFFERING;ended=state==Player.STATE_ENDED + loading=state==Player.STATE_BUFFERING + // A stacked file continues with its next part; only the last part ends the title. + if(state==Player.STATE_ENDED&&!preparing&&partIndex<parts.lastIndex){ + val next=partStart(parts,partIndex+1) + Log.i("KaleidoPlayback","PART ${partIndex+1} of ${parts.size} ended; continuing at $next") + scope.launch{prepare(mode,next,true)};return + } + ended=state==Player.STATE_ENDED if(state==Player.STATE_READY) {preparing=false;error=null;Log.i("KaleidoPlayback","READY item=${item.id} mode=$mode position=${player.currentPosition} video=${player.videoFormat?.codecs} size=${player.videoSize.width}x${player.videoSize.height}")} if(ended) {position=duration;report("stopped");Log.i("KaleidoPlayback","ENDED")} } @@ -121,7 +139,7 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) { tracks=value Log.i("KaleidoPlayback","TRACKS audio=${value.groups.count{it.type==C.TRACK_TYPE_AUDIO}} text=${value.groups.count{it.type==C.TRACK_TYPE_TEXT}}") // Some extractors expose only audio for an unsupported video codec (e.g. VC-1). - if(value.groups.isNotEmpty()&&item.media.first().videoCodec.isNotBlank()&& + if(value.groups.isNotEmpty()&&media.videoCodec.isNotBlank()&& value.groups.none{it.type==C.TRACK_TYPE_VIDEO&&it.isSupported(true)}) { fallback("unsupportedVideo");return } @@ -138,9 +156,10 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) { }) scope.launch {prepare(mode,position)} if(audit!=null)scope.launch{while(isActive){delay(1000);audit.sample(mode)}} - scope.launch {var ticks=0;while(isActive){delay(250);if(!preparing){position=currentPosition();bufferedPosition=player.bufferedPosition.coerceIn(0,duration);val d=player.duration;if(d>0)duration=if(mode>0)item.duration else d};if(++ticks%40==0&&!preparing&&!ended)report(if(isPlaying)"playing"else "paused")}} + scope.launch {var ticks=0;while(isActive){delay(250);if(!preparing){position=currentPosition();bufferedPosition=(partOffset+player.bufferedPosition).coerceIn(0,duration);val d=player.duration;if(d>0&&parts.size==1)duration=if(mode>0)item.duration else d};if(++ticks%40==0&&!preparing&&!ended)report(if(isPlaying)"playing"else "paused")}} } - private fun currentPosition() = player.currentPosition.coerceIn(0,duration.coerceAtLeast(0)) + /** Position on the title's timeline, across parts. */ + private fun currentPosition() = (partOffset+player.currentPosition).coerceIn(0,duration.coerceAtLeast(0)) private fun report(state: String,final: Boolean=false){reports.trySend(TimelineReport(position,state,duration,final))} private fun fallback(reason:String) { if(closed||mode>=2||localValidationFile!=null||fallbackPending)return @@ -164,17 +183,20 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) { player.stop() try { if(mode>0)runCatching{api.stopTranscode(streamSession)} - mode=newMode;streamSession=UUID.randomUUID().toString();streamStart=if(mode>0)offset else 0L + mode=newMode;streamSession=UUID.randomUUID().toString();streamStart=offset + partIndex=partFor(parts,offset) + val partOffsetMs=(offset-partOffset).coerceAtLeast(0) + position=offset audit?.event("prepare",org.json.JSONObject().put("mode",mode).put("offset",offset)) - val media=item.media.first();val part=media.parts.first() + val part=part val builder=MediaItem.Builder().setMediaId(item.id).setMediaMetadata(MediaMetadata.Builder().setTitle(item.title).setArtist(item.grandparentTitle).build()) if(mode==0) { builder.setUri(if(localValidationFile!=null)android.net.Uri.fromFile(localValidationFile).toString()else api.url(part.key)) builder.setSubtitleConfigurations(part.streams.filter{it.type==3&&it.key.isNotBlank()&&it.codec in listOf("srt","webvtt","vtt","ass","ssa")}.map {s -> - MediaItem.SubtitleConfiguration.Builder(android.net.Uri.parse(api.url(s.key))).setId(s.id).setLabel(s.title).setLanguage(s.language).setMimeType(when(s.codec){"srt"->MimeTypes.APPLICATION_SUBRIP;"ass","ssa"->MimeTypes.TEXT_SSA;else->MimeTypes.TEXT_VTT}).setSelectionFlags(if(s.id==activeSubtitle)C.SELECTION_FLAG_DEFAULT else 0).build() + MediaItem.SubtitleConfiguration.Builder(android.net.Uri.parse(api.url(s.key))).setId(s.id).setLabel(s.title).setLanguage(s.language).setMimeType(when(s.codec){"srt"->MimeTypes.APPLICATION_SUBRIP;"ass","ssa"->MimeTypes.TEXT_SSA;else->MimeTypes.TEXT_VTT}).setSelectionFlags(if(s.id==currentStream(activeSubtitle)?.id)C.SELECTION_FLAG_DEFAULT else 0).build() }) } else { - val p=api.transcodeParams(item,streamSession,mode,offset,vm.streamQuality.conversion) + val p=api.transcodeParams(item,streamSession,mode,partOffsetMs,quality.conversion,mediaIndex,partIndex,local,vm.subtitleSize.plexPercent) val decision=api.container("/video/:/transcode/universal/decision",p) val streams=decision.optJSONArray("Metadata").objects().flatMap{it.optJSONArray("Media").objects()} .flatMap{it.optJSONArray("Part").objects()}.flatMap{it.optJSONArray("Stream").objects()} @@ -183,25 +205,31 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) { audit?.event("decision",org.json.JSONObject().apply{ listOf("generalDecisionCode","generalDecisionText","directPlayDecisionCode","directPlayDecisionText","transcodeDecisionCode","transcodeDecisionText").forEach{k->if(decision.has(k))put(k,decision.get(k))} } - .put("streams",org.json.JSONArray(decision.optJSONArray("Metadata").objects().flatMap{it.optJSONArray("Media").objects()} - .flatMap{it.optJSONArray("Part").objects()}.flatMap{it.optJSONArray("Stream").objects()}.map{s-> + .put("streams",org.json.JSONArray(streams.map{s-> org.json.JSONObject().apply{listOf("streamType","codec","decision","profile","bitDepth","colorTrc","DOVIProfile").forEach{k->if(s.has(k))put(k,s.get(k))}} }))) if(decision.optInt("generalDecisionCode")>=2000)throw PlexException(decision.optString("generalDecisionText","Server cannot convert this media.")) builder.setUri(api.url("/video/:/transcode/universal/start.m3u8",p)).setMimeType(MimeTypes.APPLICATION_M3U8) } - // Plex HLS exposes the original absolute timeline, including a seek-start offset. - player.setMediaItem(builder.build(),offset);player.prepare();player.playWhenReady=resume;player.setPlaybackSpeed(playbackRate) - Log.i("KaleidoPlayback","PREPARE item=${item.id} mode=$mode offset=$offset") + // Plex HLS exposes the part's original timeline, including a seek-start offset: + // never add the requested offset again. + player.setMediaItem(builder.build(),partOffsetMs);player.prepare();player.playWhenReady=resume;player.setPlaybackSpeed(playbackRate) + Log.i("KaleidoPlayback","PREPARE item=${item.id} mode=$mode offset=$offset part=${partIndex+1}/${parts.size} media=${mediaIndex+1}/${item.media.size} local=$local") }catch(e:CancellationException){throw e}catch(e:Exception){ audit?.event("prepareFailure",org.json.JSONObject().put("mode",newMode).put("kind",e.javaClass.simpleName).put("httpStatus",(e as? PlexException)?.status)) if(newMode<2&&localValidationFile==null)prepareInternal(newMode+1,offset,resume)else{preparing=false;loading=false;error=e.message ?: "The server could not start playback."} } } - fun seekTo(target:Long){val clamped=target.coerceIn(0,duration);if(mode>0&&clamped<streamStart){val resume=player.playWhenReady;scope.launch{prepare(mode,clamped,resume)}}else{player.seekTo(clamped);position=clamped;report(if(isPlaying)"playing"else "paused")}} + fun seekTo(target:Long){ + val clamped=target.coerceIn(0,duration) + val resume=player.playWhenReady + // Another part, or a conversion that starts after the target, needs a new stream. + if(partFor(parts,clamped)!=partIndex||mode>0&&clamped<streamStart)scope.launch{prepare(mode,clamped,resume)} + else{player.seekTo(clamped-partOffset);position=clamped;report(if(isPlaying)"playing"else "paused")} + } fun toggle(){if(player.isPlaying)player.pause()else{if(ended)seekTo(0);player.play()}} fun retry(){scope.launch{prepare(mode,position)}} - fun changeQuality(value:StreamQuality){val resume=player.playWhenReady;vm.chooseStreamQuality(value);scope.launch{prepare(if(value==StreamQuality.Original)0 else 2,position,resume)}} + fun changeQuality(value:StreamQuality){val resume=player.playWhenReady;vm.chooseActiveQuality(value);scope.launch{prepare(if(value==StreamQuality.Original)0 else 2,position,resume)}} fun changeSpeed(value:Float){playbackRate=value;player.setPlaybackSpeed(value)} /** Moves the pending seek target; repeated presses accumulate into one seek after [settle] ms. */ fun scrubBy(delta:Long,settle:Long=650){scrubPosition=((scrubPosition ?: position)+delta).coerceIn(0,duration);seekJob?.cancel();seekJob=scope.launch{delay(settle);commitScrub()}} @@ -210,17 +238,28 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) { fun select(type:Int,groupIndex:Int,trackIndex:Int) { val group=tracks.groups[groupIndex];selector.parameters=selector.buildUponParameters().setTrackTypeDisabled(type,false).setOverrideForType(TrackSelectionOverride(group.mediaTrackGroup,listOf(trackIndex))).build() } + /** + * The current part's stream for a selected stream ID. Each part of a stacked file has its own + * stream IDs; Plex applies a selection to all parts, so match by position among that type. + */ + fun currentStream(id:String):Stream? { + part.streams.firstOrNull{it.id==id}?.let{return it} + val source=parts.firstOrNull{p->p.streams.any{it.id==id}} ?: return null + val stream=source.streams.first{it.id==id} + val ordinal=source.streams.filter{it.type==stream.type}.indexOf(stream) + return part.streams.filter{it.type==stream.type}.getOrNull(ordinal) + } private fun nativeTrack(type:Int,stream:Stream):Pair<Int,Int>? { val candidates=tracks.groups.withIndex().filter{it.value.type==type}.flatMap{g->(0 until g.value.length).map{g.index to it}} if(stream.key.isNotBlank())return candidates.firstOrNull{(g,t)->tracks.groups[g].getTrackFormat(t).id==stream.id} - val ordinal=item.media.first().parts.first().streams.filter{it.type==stream.type&&it.key.isBlank()}.indexOfFirst{it.id==stream.id} - return candidates.filter{(g,t)->tracks.groups[g].getTrackFormat(t).id !in item.media.first().parts.first().streams.filter{it.key.isNotBlank()}.map{it.id}}.getOrNull(ordinal) + val ordinal=part.streams.filter{it.type==stream.type&&it.key.isBlank()}.indexOfFirst{it.id==stream.id} + return candidates.filter{(g,t)->tracks.groups[g].getTrackFormat(t).id !in part.streams.filter{it.key.isNotBlank()}.map{it.id}}.getOrNull(ordinal) } private fun applyNativeSelection(type:Int,id:String) { if(type==C.TRACK_TYPE_TEXT&&id=="0") { selector.parameters=selector.buildUponParameters().setTrackTypeDisabled(type,true).build();return } - val stream=item.media.first().parts.first().streams.firstOrNull{it.id==id} ?: return + val stream=currentStream(id) ?: return val match=nativeTrack(type,stream) ?: return if(tracks.groups[match.first].isTrackSupported(match.second,true))select(type,match.first,match.second) else fallback("unsupportedSelectedTrack") @@ -228,14 +267,14 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) { fun selectServerStream(stream:Stream?,type:Int) { scope.launch { try { - val part=item.media.first().parts.first() + val part=part if(type==C.TRACK_TYPE_TEXT){activeSubtitle=stream?.id ?: "0";api.selectStreams(part,subtitle=activeSubtitle)}else{activeAudio=stream?.id.orEmpty();api.selectStreams(part,audio=activeAudio)} if(mode>0){prepare(mode,position,player.playWhenReady);return@launch} if(stream==null){selector.parameters=selector.buildUponParameters().setTrackTypeDisabled(type,true).build();return@launch} val match=nativeTrack(type,stream) if(match!=null&&tracks.groups[match.first].isTrackSupported(match.second,true))select(type,match.first,match.second) else prepare(2,position) // Image subtitles and unsupported embedded tracks are burned by Plex. - }catch(e:Exception){error=e.message ?: "Could not change the selected track."} + }catch(e:CancellationException){throw e}catch(e:Exception){error=e.message ?: "Could not change the selected track."} } } fun close(){if(closed)return;position=currentPosition();closed=true;scope.cancel();audit?.finish(mode);report("stopped",true);reports.close();mediaSession.release();player.release()} @@ -251,3 +290,10 @@ enum class StreamQuality(val label:String,val width:Int,val height:Int,val kbps: val conversion get()=if(this==Original)FullHD else this } fun clockTime(ms:Long):String {val s=(ms.coerceAtLeast(0)/1000);return if(s>=3600)"%d:%02d:%02d".format(s/3600,s/60%60,s%60)else "%d:%02d".format(s/60,s%60)} +/** Subtitle text size; [plexPercent] sizes subtitles Plex burns into converted video. */ +enum class SubtitleSize(val label:String,val scale:Float,val plexPercent:Int) { + Small("Small",.8f,80),Normal("Normal",1f,100),Large("Large",1.25f,125),ExtraLarge("Extra large",1.5f,150) +} +enum class SubtitleStyle(val label:String) { + Box("White on black"),Shadow("White with shadow"),Outline("White with outline"),Yellow("Yellow with outline"),System("Follow TV caption settings") +} diff --git a/app/src/main/java/tv/kaleido/app/PlaybackExtras.kt b/app/src/main/java/tv/kaleido/app/PlaybackExtras.kt index 1650e69..a437187 100644 --- a/app/src/main/java/tv/kaleido/app/PlaybackExtras.kt +++ b/app/src/main/java/tv/kaleido/app/PlaybackExtras.kt @@ -23,21 +23,32 @@ import kotlinx.coroutines.delay @Composable internal fun PlaybackOptions(vm:KaleidoViewModel,controller:PlaybackController,item:Title,menu:Int,open:(Int)->Unit,close:()->Unit) { val speeds=listOf(.5f,.75f,1f,1.25f,1.5f,2f) + // Audio and Subtitles have their own buttons; this menu holds the remaining options. + val entries=listOfNotNull(4 to "Quality · ${vm.activeQuality.label}"+if(vm.localConnection)""else " (remote)",5 to "Speed · ${speedLabel(controller.playbackRate)}", + if(item.chapters.isNotEmpty())7 to "Chapters" else null,8 to "Subtitle size · ${vm.subtitleSize.label}",9 to "Subtitle style · ${vm.subtitleStyle.label}") + // A submenu returns focus to the option that opened it. + var returnTo by remember{mutableIntStateOf(0)} val dismiss={if(menu==3)close()else open(3)} when(menu) { - 3->TrackPanel("Playback options",listOf("Quality · ${vm.streamQuality.label}","Audio language","Subtitles","Speed · ${controller.playbackRate}×","Chapters"),0,dismiss){index->open(when(index){0->4;1->1;2->2;3->5;else->7})} - 4->TrackPanel("Playback quality",StreamQuality.entries.map{it.label},vm.streamQuality.ordinal,dismiss){controller.changeQuality(StreamQuality.entries[it]);close()} - 5->TrackPanel("Playback speed",speeds.map{"${it}×"},speeds.indexOf(controller.playbackRate),dismiss){controller.changeSpeed(speeds[it]);close()} + 3->TrackPanel("Playback options",entries.map{it.second},-1,dismiss,focusIndex=entries.indexOfFirst{it.first==returnTo}.coerceAtLeast(0)){index->returnTo=entries[index].first;open(entries[index].first)} + 4->TrackPanel(if(vm.localConnection)"Playback quality"else "Remote playback quality",StreamQuality.entries.map{it.label},vm.activeQuality.ordinal,dismiss){controller.changeQuality(StreamQuality.entries[it]);close()} + 5->TrackPanel("Playback speed",speeds.map(::speedLabel),speeds.indexOf(controller.playbackRate),dismiss){controller.changeSpeed(speeds[it]);close()} 7->TrackPanel("Chapters",item.chapters.map{"${it.title} · ${clockTime(it.start)}"},item.chapters.indexOfLast{it.start<=controller.position},dismiss){controller.seekTo(item.chapters[it].start);close()} + 8->TrackPanel("Subtitle size",SubtitleSize.entries.map{it.label},vm.subtitleSize.ordinal,dismiss){vm.chooseSubtitleSize(SubtitleSize.entries[it]);close()} + 9->TrackPanel("Subtitle style",SubtitleStyle.entries.map{it.label},vm.subtitleStyle.ordinal,dismiss){vm.chooseSubtitleStyle(SubtitleStyle.entries[it]);close()} } } +internal fun speedLabel(speed:Float)=if(speed==1f)"Normal" else "${speed.toString().removeSuffix(".0")}×" + @Composable internal fun PostPlayScreen(vm:KaleidoViewModel,item:Title,dismiss:()->Unit,next:()->Unit) { val upcoming=vm.followingEpisode(item) - var autoplay by remember{mutableStateOf(true)} - var seconds by remember{mutableIntStateOf(5)} + // Settings › Playback sets the countdown; 0 turns autoplay off. + val countdown=vm.autoplaySeconds + var autoplay by remember{mutableStateOf(countdown>0)} + var seconds by remember{mutableIntStateOf(countdown)} LaunchedEffect(autoplay,upcoming?.id) { - if(autoplay&&upcoming!=null){seconds=5;android.util.Log.i("KaleidoPlayback","AUTOPLAY countdown item=${item.id} next=${upcoming.id}");repeat(5){delay(1000);seconds--};android.util.Log.i("KaleidoPlayback","AUTOPLAY starting next=${upcoming.id}");next()} + if(autoplay&&upcoming!=null&&countdown>0){seconds=countdown;android.util.Log.i("KaleidoPlayback","AUTOPLAY countdown item=${item.id} next=${upcoming.id}");repeat(countdown){delay(1000);seconds--};android.util.Log.i("KaleidoPlayback","AUTOPLAY starting next=${upcoming.id}");next()} } val season=vm.episodeQueue.filter{it.parentId==item.parentId} LazyColumn(Modifier.fillMaxSize().background(Color.Black.copy(alpha=.93f)),contentPadding=PaddingValues(horizontal=Cinema.gutter,vertical=29.dp),verticalArrangement=Arrangement.spacedBy(15.dp)) { @@ -50,7 +61,7 @@ import kotlinx.coroutines.delay Text(upcoming?.let{"S${it.parentIndex} · E${it.index} ${it.title}"} ?: "You've reached the end of this series.",color=Cinema.secondary,fontSize=12.sp,modifier=Modifier.padding(top=5.dp,bottom=15.dp)) Row(horizontalArrangement=Arrangement.spacedBy(10.dp),verticalAlignment=Alignment.CenterVertically) { if(upcoming!=null)ActionButton(if(vm.transitioningEpisode)"Loading…"else if(autoplay)"Play in $seconds"else "Play now",Icons.Filled.PlayArrow,modifier=Modifier.onFocusChanged{if(it.isFocused&&BuildConfig.DEBUG)android.util.Log.i("KaleidoPlayback","POSTPLAY focus=play")},primary=true,initialFocus=true){autoplay=false;next()} - if(upcoming!=null)TvButton(if(autoplay)"Cancel autoplay"else "Autoplay off"){autoplay=!autoplay;android.util.Log.i("KaleidoPlayback","AUTOPLAY ${if(autoplay)"enabled"else "cancelled"} item=${item.id}")} + if(upcoming!=null&&countdown>0)TvButton(if(autoplay)"Cancel autoplay"else "Autoplay off"){autoplay=!autoplay;android.util.Log.i("KaleidoPlayback","AUTOPLAY ${if(autoplay)"enabled"else "cancelled"} item=${item.id}")} TvButton("Back to video"){autoplay=false;dismiss()} } } diff --git a/app/src/main/java/tv/kaleido/app/PlayerControls.kt b/app/src/main/java/tv/kaleido/app/PlayerControls.kt index fd8e5d6..aa5dee5 100644 --- a/app/src/main/java/tv/kaleido/app/PlayerControls.kt +++ b/app/src/main/java/tv/kaleido/app/PlayerControls.kt @@ -11,6 +11,10 @@ import androidx.compose.animation.core.tween import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.ui.platform.LocalContext +import androidx.media3.ui.CaptionStyleCompat +import androidx.media3.ui.SubtitleView import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.* @@ -69,7 +73,25 @@ import kotlinx.coroutines.delay fun interacted(){interaction=System.currentTimeMillis()} fun closeTracks(){restoreMenuFocus=trackMenu;trackMenu=0;interacted()} LaunchedEffect(item.id){vm.loadEpisodeContext(item)} - LaunchedEffect(controller.ended){if(controller.ended&&item.type=="episode"){android.util.Log.i("KaleidoPlayback","POSTPLAY item=${item.id} reason=ended");postPlay=true}} + LaunchedEffect(controller.ended){ + if(!controller.ended)return@LaunchedEffect + if(item.type=="episode"){android.util.Log.i("KaleidoPlayback","POSTPLAY item=${item.id} reason=ended");postPlay=true} + // A finished movie or extra returns to its details instead of resting on the last frame. + else vm.stopPlayback() + } + // Derived: the player only recomposes when a marker starts or ends, not on every position tick. + val marker by remember{derivedStateOf{item.markers.firstOrNull{controller.position>=it.start&&controller.position<it.end&&it.type in listOf("intro","credits")}}} + fun skip(marker:Marker){ + if(marker.type=="credits"&&item.type=="episode"){controller.pause();android.util.Log.i("KaleidoPlayback","POSTPLAY item=${item.id} reason=skip-credits");postPlay=true} + else controller.seekTo(marker.end) + } + // Each marker is skipped automatically once, so seeking back into it plays it. + val autoSkipped=remember{mutableSetOf<Marker>()} + LaunchedEffect(marker,controller.loading) { + val m=marker ?: return@LaunchedEffect + if(controller.loading||postPlay||m in autoSkipped)return@LaunchedEffect + if(m.type=="intro"&&vm.autoSkipIntro||m.type=="credits"&&vm.autoSkipCredits){autoSkipped+=m;android.util.Log.i("KaleidoPlayback","AUTOSKIP ${m.type} item=${item.id}");skip(m)} + } DisposableEffect(controller) { activity.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) val observer=LifecycleEventObserver{_,event->if(event==Lifecycle.Event.ON_STOP)controller.pause()} @@ -95,7 +117,8 @@ import kotlinx.coroutines.delay android.view.KeyEvent.KEYCODE_MEDIA_PAUSE->{controller.pause();controls=true;true} android.view.KeyEvent.KEYCODE_MEDIA_FAST_FORWARD->{controller.seekTo(controller.position+30000);controls=true;seekFocus=true;true} android.view.KeyEvent.KEYCODE_MEDIA_REWIND->{controller.seekTo(controller.position-10000);controls=true;seekFocus=true;true} - android.view.KeyEvent.KEYCODE_DPAD_CENTER,android.view.KeyEvent.KEYCODE_ENTER->{if(!visible){controls=true;true}else false} + // With the controls hidden, OK takes a visible Skip intro/credits; otherwise it reveals them. + android.view.KeyEvent.KEYCODE_DPAD_CENTER,android.view.KeyEvent.KEYCODE_ENTER->{if(!visible){marker?.let(::skip) ?: run{controls=true};true}else false} android.view.KeyEvent.KEYCODE_DPAD_LEFT,android.view.KeyEvent.KEYCODE_DPAD_RIGHT->{ val delta=if(event.nativeKeyEvent.keyCode==android.view.KeyEvent.KEYCODE_DPAD_LEFT)-10000L else 10000L when { @@ -119,14 +142,14 @@ import kotlinx.coroutines.delay descendantFocusability=ViewGroup.FOCUS_BLOCK_DESCENDANTS setShowBuffering(PlayerView.SHOW_BUFFERING_NEVER) setKeepContentOnPlayerReset(true) - }},modifier=Modifier.fillMaxSize(),onRelease={it.player=null}) + }},update={view->view.subtitleView?.let{applySubtitleStyle(it,vm.subtitleSize,vm.subtitleStyle)}},modifier=Modifier.fillMaxSize(),onRelease={it.player=null}) if(controller.loading)CircularProgressIndicator(color=Accent,strokeWidth=2.dp,modifier=Modifier.align(Alignment.Center).size(30.dp)) AnimatedVisibility(visible=visible,enter=fadeIn(tween(190))+slideInVertically(tween(190)){it/8},exit=fadeOut(tween(190))+slideOutVertically(tween(190)){it/10},modifier=Modifier.align(Alignment.BottomCenter)) { Column(Modifier.fillMaxWidth().background(Brush.verticalGradient(0f to Color.Transparent,.42f to Color.Black.copy(alpha=.46f),1f to Color.Black.copy(alpha=.79f))).padding(start=Cinema.gutter,end=Cinema.gutter,top=31.dp,bottom=16.dp)) { Row(Modifier.fillMaxWidth().padding(bottom=7.dp),verticalAlignment=Alignment.Bottom) { Text(item.displayTitle,color=Accent,fontSize=18.sp,lineHeight=23.sp,fontWeight=FontWeight.SemiBold,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f)) Spacer(Modifier.width(18.dp)) - Text(if(item.type=="episode")"S${item.parentIndex} · E${item.index} ${item.title}"else controller.qualityLabel,color=Color.White.copy(alpha=.62f),fontSize=10.sp,lineHeight=15.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.widthIn(max=350.dp)) + Text(if(item.type=="episode")"S${item.parentIndex} · E${item.index} ${item.title}"else controller.qualityLabel,color=Color.White.copy(alpha=.72f),fontSize=12.sp,lineHeight=16.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.widthIn(max=420.dp)) } SeekTimeline(controller,item,Modifier.fillMaxWidth().focusRequester(timelineFocus).focusProperties{down=playFocus},::interacted) Box(Modifier.fillMaxWidth().height(40.dp)) { @@ -140,7 +163,7 @@ import kotlinx.coroutines.delay IconControl(Icons.Outlined.Forward30,"Forward 30 seconds",size=32.dp,iconSize=22.dp,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){controller.seekTo(controller.position+30000);interacted()} } Row(Modifier.align(Alignment.CenterEnd),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(10.dp)) { - Text("−"+clockTime(controller.duration-controller.position),color=Color.White.copy(alpha=.58f),fontSize=10.sp,lineHeight=14.sp,modifier=Modifier.padding(end=8.dp)) + Text("−"+clockTime(controller.duration-controller.position)+" · Ends "+endsAt(controller),color=Color.White.copy(alpha=.58f),fontSize=10.sp,lineHeight=14.sp,modifier=Modifier.padding(end=8.dp)) if(item.type=="episode")IconControl(Icons.Outlined.SkipNext,"Next episode",size=30.dp,iconSize=21.dp,onFocused=::interacted){vm.nextEpisode(item)} IconControl(Icons.AutoMirrored.Outlined.VolumeUp,"Audio tracks",size=30.dp,iconSize=21.dp,requester=audioFocus,selected=trackMenu==1,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){trackMenu=1;interacted()} IconControl(Icons.Outlined.Subtitles,"Subtitles",size=30.dp,iconSize=21.dp,requester=subtitleFocus,selected=trackMenu==2,modifier=Modifier.focusProperties{up=timelineFocus},onFocused=::interacted){trackMenu=2;interacted()} @@ -149,17 +172,17 @@ import kotlinx.coroutines.delay } } } - val marker=item.markers.firstOrNull{controller.position>=it.start&&controller.position<it.end&&it.type in listOf("intro","credits")} - if(marker!=null&&!postPlay)Box(Modifier.align(Alignment.BottomEnd).padding(end=Cinema.gutter,bottom=if(visible)130.dp else 45.dp)) { - ActionButton(if(marker.type=="intro")"Skip intro"else "Skip credits",Icons.Outlined.ChevronRight,modifier=Modifier.background(Color.Black.copy(alpha=.9f),RoundedCornerShape(5.dp)).border(1.dp,Color.White.copy(alpha=.75f),RoundedCornerShape(5.dp))){if(marker.type=="credits"&&item.type=="episode"){controller.pause();android.util.Log.i("KaleidoPlayback","POSTPLAY item=${item.id} reason=skip-credits");postPlay=true}else controller.seekTo(marker.end);interacted()} - } + marker?.let{marker->if(!postPlay)Box(Modifier.align(Alignment.BottomEnd).padding(end=Cinema.gutter,bottom=if(visible)130.dp else 45.dp)) { + ActionButton(if(marker.type=="intro")"Skip intro"else "Skip credits",Icons.Outlined.ChevronRight,modifier=Modifier.background(Color.Black.copy(alpha=.9f),RoundedCornerShape(5.dp)).border(1.dp,Color.White.copy(alpha=.75f),RoundedCornerShape(5.dp))){skip(marker);interacted()} + }} if(postPlay)PostPlayScreen(vm,item,{postPlay=false;controls=true},{vm.nextEpisode(item)}) controller.error?.let{ErrorDialog(it,{vm.stopPlayback()},{controller.retry()})} if(trackMenu in 1..2) { val type=if(trackMenu==1)C.TRACK_TYPE_AUDIO else C.TRACK_TYPE_TEXT - val streams=item.media.firstOrNull()?.parts?.firstOrNull()?.streams.orEmpty().filter{it.type==(if(trackMenu==1)2 else 3)} + val streams=controller.part.streams.filter{it.type==(if(trackMenu==1)2 else 3)} val options=(if(trackMenu==2)listOf("Off")else emptyList())+streams.map{it.title} - val selected=streams.indexOfFirst{it.id==(if(trackMenu==1)controller.activeAudio else controller.activeSubtitle)}+if(trackMenu==2)1 else 0 + val active=controller.currentStream(if(trackMenu==1)controller.activeAudio else controller.activeSubtitle) + val selected=streams.indexOfFirst{it.id==active?.id}+if(trackMenu==2)1 else 0 TrackPanel(if(trackMenu==1)"Audio"else "Subtitles",options,selected,::closeTracks){index-> val stream=if(trackMenu==2)streams.getOrNull(index-1)else streams.getOrNull(index) if(options.isNotEmpty())controller.selectServerStream(stream,type) @@ -170,6 +193,36 @@ import kotlinx.coroutines.delay } } +/** Wall-clock time the title finishes at the current speed, in the TV's 12/24-hour format. */ +@Composable private fun endsAt(controller:PlaybackController):String { + val format=android.text.format.DateFormat.getTimeFormat(LocalContext.current) + val remaining=((controller.duration-controller.position).coerceAtLeast(0)/controller.playbackRate.coerceAtLeast(.25f)).toLong() + return format.format(java.util.Date(System.currentTimeMillis()+remaining)) +} + +@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) +/** [screenHeight]: size text against a full-screen frame, for a preview smaller than the video. */ +internal fun applySubtitleStyle(view:SubtitleView,size:SubtitleSize,style:SubtitleStyle,screenHeight:Int?=null) { + val black=android.graphics.Color.BLACK;val white=android.graphics.Color.WHITE;val clear=android.graphics.Color.TRANSPARENT + var scale=size.scale + val caption=when(style) { + SubtitleStyle.Box->CaptionStyleCompat.DEFAULT + SubtitleStyle.Shadow->CaptionStyleCompat(white,clear,clear,CaptionStyleCompat.EDGE_TYPE_DROP_SHADOW,black,null) + SubtitleStyle.Outline->CaptionStyleCompat(white,clear,clear,CaptionStyleCompat.EDGE_TYPE_OUTLINE,black,null) + SubtitleStyle.Yellow->CaptionStyleCompat(0xFFFFE14D.toInt(),clear,clear,CaptionStyleCompat.EDGE_TYPE_OUTLINE,black,null) + SubtitleStyle.System->{ + val captioning=view.context.getSystemService(android.view.accessibility.CaptioningManager::class.java) + scale*=captioning?.fontScale ?: 1f + captioning?.let{CaptionStyleCompat.createFromCaptionStyle(it.userStyle)} ?: CaptionStyleCompat.DEFAULT + } + } + view.setStyle(caption) + // Embedded ASS/SSA colours and positions still apply; the chosen size always does. + view.setApplyEmbeddedFontSizes(false) + if(screenHeight!=null)view.setFixedTextSize(android.util.TypedValue.COMPLEX_UNIT_PX,screenHeight*SubtitleView.DEFAULT_TEXT_SIZE_FRACTION*scale) + else view.setFractionalTextSize(SubtitleView.DEFAULT_TEXT_SIZE_FRACTION*scale) +} + @Composable private fun SeekTimeline(controller:PlaybackController,item:Title,modifier:Modifier,onInteraction:()->Unit) { var focused by remember{mutableStateOf(false)} val displayed=controller.scrubPosition ?: controller.position @@ -201,15 +254,19 @@ import kotlinx.coroutines.delay } } -@Composable internal fun TrackPanel(title:String,options:List<String>,selected:Int,dismiss:()->Unit,choose:(Int)->Unit) { +/** [selected] shows a checkmark; [focusIndex] only places focus, e.g. in a menu without a selection. */ +@Composable internal fun TrackPanel(title:String,options:List<String>,selected:Int,dismiss:()->Unit,focusIndex:Int=selected,choose:(Int)->Unit) { val density=LocalDensity.current + val initial=(if(focusIndex>=0)focusIndex else 0).coerceIn(0,(options.size-1).coerceAtLeast(0)) + // Start scrolled near the focused row: a lazy row that isn't composed can't take focus. + val list=rememberLazyListState(initialFirstVisibleItemIndex=(initial-2).coerceAtLeast(0)) val offset=with(density){IntOffset(-44.dp.roundToPx(),-108.dp.roundToPx())} Popup(alignment=Alignment.BottomEnd,offset=offset,onDismissRequest=dismiss,properties=PopupProperties(focusable=true)) { Column(Modifier.width(280.dp).heightIn(max=330.dp).clip(RoundedCornerShape(10.dp)).background(Color(0xF5222222)).padding(13.dp).onPreviewKeyEvent{if(it.key==Key.Back){if(it.type==KeyEventType.KeyDown)dismiss();true}else if(it.type==KeyEventType.KeyDown&&it.key==Key.DirectionLeft){dismiss();true}else false}) { Text(title,color=Accent,fontSize=15.sp,lineHeight=20.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(start=9.dp,top=5.dp,bottom=10.dp)) if(options.isEmpty())Text("No tracks available",color=Muted,fontSize=12.sp,modifier=Modifier.padding(10.dp)) - LazyColumn(verticalArrangement=Arrangement.spacedBy(2.dp)) { - items(options.size){index->TrackOption(options[index],index==selected,index==selected||selected<0&&index==0){choose(index)}} + LazyColumn(state=list,verticalArrangement=Arrangement.spacedBy(2.dp)) { + items(options.size){index->TrackOption(options[index],index==selected,index==initial){choose(index)}} } } } diff --git a/app/src/main/java/tv/kaleido/app/PlexApi.kt b/app/src/main/java/tv/kaleido/app/PlexApi.kt index 3d8b4bb..5504b5b 100644 --- a/app/src/main/java/tv/kaleido/app/PlexApi.kt +++ b/app/src/main/java/tv/kaleido/app/PlexApi.kt @@ -66,7 +66,9 @@ class PlexApi(val clientId: String) { suspend fun libraryRevision():String = container("/library/sections").optJSONArray("Directory").objects() .filter{it.optString("type") in listOf("movie","show")}.sortedBy{it.optString("key")} .joinToString("|"){j->listOf("key","title","type","contentChangedAt","scannedAt","updatedAt").joinToString(":"){j.optString(it)}} - suspend fun hubs(section: String? = null): List<Hub> = withContext(Dispatchers.Default){container(if(section==null) "/hubs" else "/hubs/sections/$section", mapOf("count" to "18","includeExternalMetadata" to "1")).optJSONArray("Hub").objects().map { Hub(it.optString("hubIdentifier",it.optString("key",it.optString("title"))),it.optString("title"),it.optJSONArray("Metadata").objects().map(Title::parse)) }.filter { it.items.isNotEmpty() && it.items.first().type in listOf("movie","show","episode","season","collection") }} + suspend fun hubs(section: String? = null): List<Hub> = withContext(Dispatchers.Default){container(if(section==null) "/hubs" else "/hubs/sections/$section", mapOf("count" to "18","includeExternalMetadata" to "1")).optJSONArray("Hub").objects().map { Hub(it.optString("hubIdentifier",it.optString("key",it.optString("title"))),it.optString("title"),it.optJSONArray("Metadata").objects().map(Title::parse),it.optString("key"),it.opt("more").let{v->v==true||v==1||v=="1"||v=="true"}) }.filter { it.items.isNotEmpty() && it.items.first().type in listOf("movie","show","episode","season","collection") }} + /** A hub's complete list, for "View all". Plex keys may already carry query parameters. */ + suspend fun hubItems(key:String):List<Title> = withContext(Dispatchers.Default){container(key,mapOf("X-Plex-Container-Start" to "0","X-Plex-Container-Size" to "500","includeExternalMetadata" to "1")).optJSONArray("Metadata").objects().map(Title::parse)} suspend fun onDeck(): List<Title> = container("/library/onDeck",mapOf("X-Plex-Container-Size" to "30")).optJSONArray("Metadata").objects().map(Title::parse) suspend fun recentSeasons(section:String):List<Title> = withContext(Dispatchers.Default){ // Fetch beyond the display limit so one large series import doesn't fill the row. @@ -97,15 +99,25 @@ class PlexApi(val clientId: String) { 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}" + fun previewPath(item:Title,time:Long,mediaIndex:Int=0):String? { + val parts=item.media.getOrNull(mediaIndex)?.parts.orEmpty() + val partIndex=partFor(parts,time) + val part=parts.getOrNull(partIndex) + val local=time.coerceAtLeast(0)-partStart(parts,partIndex) + if(part!=null&&part.indexes.split(',').contains("sd"))return "/library/parts/${part.id}/indexes/sd/${local.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> = 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 search(query: String): SearchResults = withContext(Dispatchers.Default) { + val hubs=container("/hubs/search",mapOf("query" to query,"limit" to "40","includeCollections" to "1")).optJSONArray("Hub").objects() + val titles=hubs.flatMap{it.optJSONArray("Metadata").objects().map(Title::parse)}.filter{it.type in listOf("movie","show","season","episode","collection")}.distinctBy{it.id} + val people=hubs.filter{it.optString("type")=="actor"}.flatMap{it.optJSONArray("Directory").objects()}.map(CastMember::parse).filter{it.id.isNotBlank()&&it.name.isNotBlank()}.distinctBy{it.id} + SearchResults(titles,people) + } + /** Removes an in-progress title from Continue Watching without changing its watched state. */ + suspend fun removeFromContinueWatching(item:Title){request(url("/actions/removeFromContinueWatching",mapOf("ratingKey" to item.id)),method="PUT")} suspend fun watched(item: Title, watched: Boolean) { container(if(watched) "/:/scrobble" else "/:/unscrobble",mapOf("key" to item.id,"identifier" to "com.plexapp.plugins.library")) } suspend fun timeline(item: Title, position: Long, state: String, duration: Long, sessionId: String) { container("/:/timeline",mapOf("ratingKey" to item.id,"key" to item.key,"state" to state,"time" to position.coerceAtLeast(0).toString(),"duration" to duration.coerceAtLeast(0).toString(),"identifier" to "com.plexapp.plugins.library","session" to sessionId)) @@ -114,13 +126,13 @@ class PlexApi(val clientId: String) { request(url("/library/parts/${part.id}",buildMap { put("allParts","1");audio?.let {put("audioStreamID",it)};subtitle?.let {put("subtitleStreamID",it)} }),method="PUT") } fun image(path: String, width: Int = 600, height: Int = 900): String? = if(path.isBlank() || session==null) null else url("/photo/:/transcode",mapOf("url" to path,"width" to width.toString(),"height" to height.toString(),"minSize" to "1","upscale" to "0")) - fun transcodeParams(item: Title, sessionId: String, mode: Int, offset: Long, quality: StreamQuality): Map<String,String> = buildMap { - put("path",item.key);put("mediaIndex","0");put("partIndex","0");put("protocol","hls");put("session",sessionId);put("offset",(offset/1000.0).toString()) + fun transcodeParams(item: Title, sessionId: String, mode: Int, offset: Long, quality: StreamQuality, mediaIndex:Int=0, partIndex:Int=0, local:Boolean=true, subtitleSize:Int=100): Map<String,String> = buildMap { + put("path",item.key);put("mediaIndex",mediaIndex.toString());put("partIndex",partIndex.toString());put("protocol","hls");put("session",sessionId);put("offset",(offset/1000.0).toString()) put("directPlay","0");put("directStream",if(mode==1) "1" else "0");put("directStreamAudio","1");put("directStreamVideo",if(mode==1) "1" else "0") - val original=item.media.firstOrNull() + val original=item.media.getOrNull(mediaIndex) ?: item.media.firstOrNull() put("maxVideoBitrate",if(mode==1)maxOf(original?.bitrate ?: 0,100000).toString()else quality.kbps.toString()) put("videoResolution",if(mode==1&&original!=null&&original.width>0)"${original.width}x${original.height}"else "${quality.width}x${quality.height}") - put("videoQuality","100");put("audioBoost","100");put("subtitleSize","100");put("location","lan");put("hasMDE","1");put("fastSeek","1") + put("videoQuality","100");put("audioBoost","100");put("subtitleSize",subtitleSize.toString());put("location",if(local)"lan"else "wan");put("hasMDE","1");put("fastSeek","1") put("X-Plex-Client-Identifier",clientId);put("X-Plex-Product","Kaleido");put("X-Plex-Platform","Android");put("X-Plex-Device","Android TV") // Augment the existing target. Separate targets make Plex prefer H.264 conversion even for HEVC it could copy. val hevcAvailable=android.media.MediaCodecList(android.media.MediaCodecList.REGULAR_CODECS).codecInfos.any{!it.isEncoder&&it.supportedTypes.any{type->type.equals("video/hevc",true)}} @@ -128,3 +140,11 @@ class PlexApi(val clientId: String) { } suspend fun stopTranscode(sessionId: String) { container("/video/:/transcode/universal/stop",mapOf("session" to sessionId)) } } + +/** Index of the part containing [time] on the title's combined timeline. */ +internal fun partFor(parts:List<Part>,time:Long):Int { + var start=0L + for((i,p) in parts.withIndex()){if(p.duration<=0||time<start+p.duration||i==parts.lastIndex)return i;start+=p.duration} + return 0 +} +internal fun partStart(parts:List<Part>,index:Int):Long = parts.take(index.coerceAtLeast(0)).sumOf{it.duration.coerceAtLeast(0)} diff --git a/app/src/main/java/tv/kaleido/app/Screens.kt b/app/src/main/java/tv/kaleido/app/Screens.kt index c527764..b6bc6ad 100644 --- a/app/src/main/java/tv/kaleido/app/Screens.kt +++ b/app/src/main/java/tv/kaleido/app/Screens.kt @@ -44,6 +44,9 @@ import kotlinx.coroutines.withTimeoutOrNull import kotlinx.coroutines.flow.first import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.KeyInputModifierNode +import androidx.compose.ui.node.ModifierNodeElement +import androidx.compose.material.icons.automirrored.outlined.ArrowBack import java.io.File @Composable fun Artwork(api: PlexApi,path: String,modifier: Modifier=Modifier,width: Int=600,height: Int=900,animate:Boolean=true,contentScale:ContentScale=ContentScale.Crop) { @@ -97,13 +100,14 @@ 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","actor")) TopBar(vm) + 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) } @@ -114,6 +118,7 @@ import java.io.File } if(vm.busy) LinearProgressIndicator(Modifier.fillMaxWidth().height(2.dp).align(Alignment.TopCenter),color=Accent,trackColor=Color.Transparent) if(vm.error!=null) ErrorDialog(vm.error!!,{vm.dismissError()},{vm.retry()}) + vm.contextItem?.let{item->if(vm.playing==null)TitleActions(vm,item)} vm.playing?.let {item-> androidx.compose.runtime.key(item.id) {PlaybackScreen(vm,item)} } if(startup)StartupSplash({splashExit.value},{!vm.busy}){brandReady=true} } @@ -142,5 +147,86 @@ val sortLabels=listOf("titleSort:asc" to "Title: A–Z","titleSort:desc" to "Tit 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 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)})}}}}} +@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=retry);TvButton("Dismiss",onClick=dismiss)}}}} +/** [heldSelect]: opened by a held OK, so its repeats and release must not choose the first option. */ +@Composable fun ChoiceDialog(title: String,options: List<String>,selected: Int,dismiss: ()->Unit,heldSelect:Boolean=false,choose: (Int)->Unit) { + // Open scrolled to the selection: an uncomposed lazy row cannot take the initial focus. + val list=rememberLazyListState(initialFirstVisibleItemIndex=(selected-2).coerceAtLeast(0)) + val armed=remember{booleanArrayOf(!heldSelect)} + Dialog(onDismissRequest=dismiss){Column(Modifier.onPreviewKeyEvent{event-> + val native=event.nativeKeyEvent + val select=native.keyCode in listOf(android.view.KeyEvent.KEYCODE_DPAD_CENTER,android.view.KeyEvent.KEYCODE_ENTER,android.view.KeyEvent.KEYCODE_NUMPAD_ENTER) + if(armed[0]||!select)false else if(native.action==android.view.KeyEvent.ACTION_DOWN&&native.repeatCount==0){armed[0]=true;false}else true + }.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(state=list,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)})}}}} +} + +/** Long-press OK or Menu on a title: the actions the official app keeps behind its context menu. */ +@Composable fun TitleActions(vm:KaleidoViewModel,item:Title) { + val watched=item.isWatched(vm.watchedPercent) + val actions=buildList<Pair<String,()->Unit>> { + if(item.type=="clip")add("Play" to {vm.play(item)}) + else if(item.type!="collection") { + add((if(item.offset>0)"Resume from ${clockTime(item.offset)}" else if(item.type in listOf("show","season"))"Watch next" else "Play") to {vm.play(item)}) + if(item.offset>0)add("Play from the beginning" to {vm.play(item,true)}) + } + if(item.type!="clip")add("More information" to {vm.open(item)}) + if(item.type in listOf("movie","show","season","episode"))add((if(watched)"Mark unwatched" else "Mark watched") to {vm.mark(item)}) + if(vm.contextFromContinue&&item.type in listOf("movie","episode"))add("Remove from Continue Watching" to {vm.removeFromContinueWatching(item)}) + if(item.type=="episode"&&item.parentId.isNotBlank())add("Go to season ${item.parentIndex}" to {vm.openSeason(item)}) + if(item.type=="episode"&&item.grandparentId.isNotBlank()||item.type=="season"&&item.parentId.isNotBlank())add("Go to show" to {vm.openShow(item)}) + } + ChoiceDialog(item.displayTitle,actions.map{it.first},-1,vm::dismissActions,heldSelect=true){index->vm.dismissActions();actions[index].second()} +} + +/** + * Opens [onLongPress] when OK is held or the remote's Menu key is pressed, without also + * triggering the click that a held OK would send on release. + */ +fun Modifier.titleActions(onLongPress:()->Unit):Modifier = this then TitleActionsElement(onLongPress) + +// A node, not composed{}: every browse card carries this, and a sub-composition per card is costly. +private class TitleActionsElement(val onLongPress:()->Unit):ModifierNodeElement<TitleActionsNode>() { + override fun create()=TitleActionsNode(onLongPress) + override fun update(node:TitleActionsNode){node.onLongPress=onLongPress} + override fun equals(other:Any?)=other is TitleActionsElement&&other.onLongPress===onLongPress + override fun hashCode()=System.identityHashCode(onLongPress) +} +private class TitleActionsNode(var onLongPress:()->Unit):Modifier.Node(),KeyInputModifierNode { + private var held=false + override fun onPreKeyEvent(event:androidx.compose.ui.input.key.KeyEvent):Boolean { + val native=event.nativeKeyEvent + val select=native.keyCode==android.view.KeyEvent.KEYCODE_DPAD_CENTER||native.keyCode==android.view.KeyEvent.KEYCODE_ENTER||native.keyCode==android.view.KeyEvent.KEYCODE_NUMPAD_ENTER + return when { + native.keyCode==android.view.KeyEvent.KEYCODE_MENU->{if(native.action==android.view.KeyEvent.ACTION_UP)onLongPress();true} + !select->false + native.action==android.view.KeyEvent.ACTION_DOWN&&native.repeatCount==0->{held=false;false} + native.action==android.view.KeyEvent.ACTION_DOWN->{if(!held){held=true;onLongPress()};true} + native.action==android.view.KeyEvent.ACTION_UP&&held->{held=false;true} + else->false + } + } + override fun onKeyEvent(event:androidx.compose.ui.input.key.KeyEvent)=false +} + +/** "View all" for a row: every title the Plex hub holds. */ +@Composable fun HubScreen(vm:KaleidoViewModel) { + Column(Modifier.fillMaxSize().background(Ink).padding(top=20.dp)) { + Row(Modifier.fillMaxWidth().padding(start=34.dp,end=Cinema.gutter,bottom=20.dp),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(18.dp)) { + IconControl(androidx.compose.material.icons.Icons.AutoMirrored.Outlined.ArrowBack,"Back"){vm.back()} + Column { + Eyebrow("View all") + Text(vm.page.name,color=Accent,fontSize=29.sp,lineHeight=34.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(vertical=3.dp)) + Text(if(vm.busy)"Loading…"else "${vm.hubTitles.size} titles",color=Muted,fontSize=11.sp) + } + } + if(vm.hubTitles.isEmpty()&&!vm.busy)Text("Nothing to show here right now.",color=Muted,fontSize=14.sp,modifier=Modifier.padding(horizontal=Cinema.gutter)) + // Episode rows read best as landscape stills; everything else as posters. + val landscape=vm.hubTitles.firstOrNull()?.type in listOf("episode","clip") + val columns=if(landscape)4 else 6 + LazyVerticalGrid(GridCells.Fixed(columns),contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,bottom=28.dp),horizontalArrangement=Arrangement.spacedBy(13.dp),verticalArrangement=Arrangement.spacedBy(18.dp)) { + itemsIndexed(vm.hubTitles,key={_,item->item.id}){index,item-> + MediaTile(vm,item,"hub:${item.id}",landscape=landscape,fillWidth=true,initialFocus=index==0&&!vm.focusId.startsWith("hub:"),onMove={anticipateTileMove(vm,vm.hubTitles,index,it,columns)}) + } + } + } +} diff --git a/app/src/main/java/tv/kaleido/app/SettingsScreen.kt b/app/src/main/java/tv/kaleido/app/SettingsScreen.kt index 921a98f..36b925f 100644 --- a/app/src/main/java/tv/kaleido/app/SettingsScreen.kt +++ b/app/src/main/java/tv/kaleido/app/SettingsScreen.kt @@ -37,11 +37,20 @@ 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") } + val categories = remember { listOf("Connection", "Playback", "Subtitles", "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) } + var remoteDialog by remember { mutableStateOf(false) } + var autoplayDialog by remember { mutableStateOf(false) } + var subtitleSizeDialog by remember { mutableStateOf(false) } + var subtitleStyleDialog by remember { mutableStateOf(false) } + val remoteFocus = remember { FocusRequester() } + val autoplayFocus = remember { FocusRequester() } + val introFocus = remember { FocusRequester() } + val creditsFocus = remember { FocusRequester() } + val subtitleStyleFocus = remember { FocusRequester() } val categoryFocus = remember { List(categories.size) { FocusRequester() } } val entryFocus = remember { List(categories.size) { FocusRequester() } } @@ -145,10 +154,21 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { fontSize = 11.sp, lineHeight = 16.sp ) + vm.session?.server?.let { address -> + Text( + (if (vm.localConnection) "Local connection" else "Remote connection") + " · " + + address.removePrefix("https://").removePrefix("http://").substringBefore('/'), + color = Muted, + fontSize = 11.sp, + lineHeight = 16.sp, + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } } Row(horizontalArrangement = Arrangement.spacedBy(9.dp)) { SettingsActionButton( - "Sign in with Plex", + if (vm.accountToken.isBlank()) "Sign in with Plex" else "Switch account", requester = entryFocus[0], leftTarget = categoryFocus[0], rightTarget = if (vm.accountToken.isNotBlank()) serverActionFocus else signOutActionFocus, @@ -176,12 +196,20 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { 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.", + description = "On your home network. 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 = "Remote quality", + description = "Away from home or through Plex Relay, where bandwidth is limited.", + value = vm.remoteQuality.label, + requester = remoteFocus, + leftTarget = categoryFocus[1], + onClick = { remoteDialog = true } + ) SettingsValueRow( title = "Watched status", description = "A resumed title receives its checkmark at this playback percentage.", @@ -190,6 +218,30 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { leftTarget = categoryFocus[1], onClick = { watchedDialog = true } ) + SettingsValueRow( + title = "Autoplay next episode", + description = "Count down to the next episode when one ends.", + value = autoplayLabel(vm.autoplaySeconds), + requester = autoplayFocus, + leftTarget = categoryFocus[1], + onClick = { autoplayDialog = true } + ) + SettingsValueRow( + title = "Skip intros", + description = "Uses intro markers from your Plex server.", + value = if (vm.autoSkipIntro) "Automatically" else "Show button", + requester = introFocus, + leftTarget = categoryFocus[1], + onClick = { vm.chooseAutoSkipIntro(!vm.autoSkipIntro) } + ) + SettingsValueRow( + title = "Skip credits", + description = "Episodes go straight to Up Next; movies skip past the credits.", + value = if (vm.autoSkipCredits) "Automatically" else "Show button", + requester = creditsFocus, + leftTarget = categoryFocus[1], + onClick = { vm.chooseAutoSkipCredits(!vm.autoSkipCredits) } + ) Text( "Completed titles keep their Plex watched status.", color = Cinema.quiet, @@ -200,13 +252,34 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { } 2 -> { + SettingsSectionTitle("Subtitles", "Choose how text subtitles look. Image subtitles keep their own style.") + SettingsValueRow( + title = "Size", + description = "Also sizes subtitles Plex adds to converted video.", + value = vm.subtitleSize.label, + requester = entryFocus[2], + leftTarget = categoryFocus[2], + onClick = { subtitleSizeDialog = true } + ) + SettingsValueRow( + title = "Style", + description = "Text colour, outline and background.", + value = vm.subtitleStyle.label, + requester = subtitleStyleFocus, + leftTarget = categoryFocus[2], + onClick = { subtitleStyleDialog = true } + ) + SubtitlePreview(vm.subtitleSize, vm.subtitleStyle) + } + + 3 -> { 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], + requester = entryFocus[3], + leftTarget = categoryFocus[3], onClick = { vm.chooseNavigationSounds(!vm.navigationSounds) } ) } @@ -237,8 +310,8 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { ) { SettingsActionButton( "Check for updates", - requester = entryFocus[3], - leftTarget = categoryFocus[3], + requester = entryFocus[4], + leftTarget = categoryFocus[4], rightTarget = if (vm.update != null) updateDownloadFocus else null, onClick = { vm.checkUpdate() } ) @@ -251,7 +324,7 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { SettingsActionButton( label, requester = updateDownloadFocus, - leftTarget = categoryFocus[3], + leftTarget = categoryFocus[4], primary = true, onClick = { vm.downloadUpdate() } ) @@ -288,6 +361,31 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { watchedDialog = false } } + if (remoteDialog) { + ChoiceDialog("Remote quality", StreamQuality.entries.map { it.label }, vm.remoteQuality.ordinal, { remoteDialog = false }) { + vm.chooseRemoteQuality(StreamQuality.entries[it]) + remoteDialog = false + } + } + if (autoplayDialog) { + val choices = listOf(0, 5, 10, 15, 30) + ChoiceDialog("Autoplay next episode", choices.map(::autoplayLabel), choices.indexOf(vm.autoplaySeconds), { autoplayDialog = false }) { + vm.chooseAutoplaySeconds(choices[it]) + autoplayDialog = false + } + } + if (subtitleSizeDialog) { + ChoiceDialog("Subtitle size", SubtitleSize.entries.map { it.label }, vm.subtitleSize.ordinal, { subtitleSizeDialog = false }) { + vm.chooseSubtitleSize(SubtitleSize.entries[it]) + subtitleSizeDialog = false + } + } + if (subtitleStyleDialog) { + ChoiceDialog("Subtitle style", SubtitleStyle.entries.map { it.label }, vm.subtitleStyle.ordinal, { subtitleStyleDialog = false }) { + vm.chooseSubtitleStyle(SubtitleStyle.entries[it]) + subtitleStyleDialog = false + } + } if (qualityDialog) { ChoiceDialog("Playback quality", StreamQuality.entries.map { it.label }, vm.streamQuality.ordinal, { qualityDialog = false }) { vm.chooseStreamQuality(StreamQuality.entries[it]) @@ -296,6 +394,28 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { } } +private fun autoplayLabel(seconds: Int) = if (seconds <= 0) "Off" else "After $seconds seconds" + +/** A sample line in the chosen subtitle look, rendered by the player's own subtitle view. */ +@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) +@Composable +private fun SubtitlePreview(size: SubtitleSize, style: SubtitleStyle) { + Box( + Modifier.fillMaxWidth().height(150.dp).clip(RoundedCornerShape(Cinema.radius)) + .background(androidx.compose.ui.graphics.Brush.linearGradient(listOf(Color(0xFF3B4A5A), Color(0xFFB9A27A), Color(0xFF2A2F36)))) + ) { + androidx.compose.ui.viewinterop.AndroidView( + factory = { context -> androidx.media3.ui.SubtitleView(context) }, + update = { view -> + applySubtitleStyle(view, size, style, view.resources.displayMetrics.heightPixels) + view.setBottomPaddingFraction(.12f) + view.setCues(listOf(androidx.media3.common.text.Cue.Builder().setText("Subtitles will look like this.").build())) + }, + modifier = Modifier.fillMaxSize() + ) + } +} + /** 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 { diff --git a/app/src/main/java/tv/kaleido/app/TitleDetails.kt b/app/src/main/java/tv/kaleido/app/TitleDetails.kt index 2264b97..753c766 100644 --- a/app/src/main/java/tv/kaleido/app/TitleDetails.kt +++ b/app/src/main/java/tv/kaleido/app/TitleDetails.kt @@ -44,22 +44,32 @@ import kotlinx.coroutines.launch val item=vm.detail ?: return val actionFocus=remember(item.id){FocusRequester()} val childFocus=remember(item.id){FocusRequester()} + val castFocus=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 restoreRow=remember(item.id){listOf("cast:","children:","related:","extras:").any{restoreFocus.startsWith("$it${item.id}:")}} val list=rememberLazyListState() val backdropFadeDistance=with(LocalDensity.current){180.dp.toPx()} + val season=item.type=="season" + val extras=item.playableExtras 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 + // Lazy items in display order, so a restored row is revealed at its real index. + val rows=buildList { + add("details") + if(vm.children.isNotEmpty()){if(season){add("episodes");vm.children.forEach{add("children:${item.id}:${it.id}")}}else add("children")} + if(item.castMembers.isNotEmpty())add("cast") + if(extras.isNotEmpty())add("extras") + if(vm.detailRelated.isNotEmpty())add("related") } + val target=listOf("children","cast","extras","related").firstOrNull{restoreFocus.startsWith("$it:${item.id}:")}?.let{row-> + if(row=="children"&&season)rows.indexOf(restoreFocus)else rows.indexOf(row) + }?.takeIf{it>0} // 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) } + // Back from playback focuses Play/Resume rather than the first control on the page. + val seenReturn=remember{intArrayOf(vm.playbackReturn)} + LaunchedEffect(vm.playbackReturn){if(vm.playbackReturn!=seenReturn[0]){seenReturn[0]=vm.playbackReturn;withFrameNanos{};list.scrollToItem(0);withFrameNanos{};runCatching{actionFocus.requestFocus()}}} Box(Modifier.fillMaxSize().background(Ink)) { val usesPosterHeader=item.type in listOf("show","movie") if(usesPosterHeader) { @@ -70,26 +80,37 @@ import kotlinx.coroutines.launch // in the layer so scrolling doesn't recompose the details and cast hierarchy. Box(Modifier.fillMaxSize().background(Brush.verticalGradient(0f to Ink.copy(alpha=.4f),.35f to Ink.copy(alpha=.5f),.62f to Ink.copy(alpha=.96f),.8f to Ink))) } + // Actions lead to the first row below them: seasons/episodes, otherwise the first cast member. + val below=if(vm.children.isNotEmpty())childFocus else if(item.castMembers.isNotEmpty())castFocus else null 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().then(if(usesPosterHeader)Modifier.heightIn(min=248.dp)else Modifier.height(if(item.type=="episode")322.dp else 286.dp))) { + Box(Modifier.fillMaxWidth().then(if(usesPosterHeader)Modifier.heightIn(min=248.dp)else Modifier.heightIn(min=if(item.type=="episode")322.dp else 286.dp))) { if(!usesPosterHeader) { - 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)))) + Artwork(vm.api,item.art,Modifier.matchParentSize(),1920,1080) + Box(Modifier.matchParentSize().background(Brush.horizontalGradient(listOf(Ink.copy(alpha=.98f),Ink.copy(alpha=.8f),Color.Transparent)))) + Box(Modifier.matchParentSize().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(usesPosterHeader) { Row(Modifier.fillMaxWidth().padding(start=Cinema.gutter,end=Cinema.gutter,top=56.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,fill=false).widthIn(max=560.dp)) + TitleInformation(vm,item,actionFocus,below,!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)) + }else TitleInformation(vm,item,actionFocus,below,!restoreRow,Modifier.align(Alignment.CenterStart).padding(start=Cinema.gutter,end=Cinema.gutter,top=64.dp,bottom=24.dp).fillMaxWidth()) } } - 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.children.isNotEmpty()) { + if(season) { + item(key="episodes-${item.id}"){Box(Modifier.padding(horizontal=Cinema.gutter)){SectionHeading("Episodes")}} + itemsIndexed(vm.children,key={_,ep->"ep-${ep.id}"}){index,ep->EpisodeRow(vm,ep,"children:${item.id}:${ep.id}",if(index==0)childFocus else null)} + }else item(key="children-${item.id}") { + if(item.type=="episode")MediaRow(vm,"Season ${item.parentIndex}",vm.children,"children:${item.id}",landscape=true,entryFocus=childFocus,episodeTitles=true,initialItem=item.id) + else MediaRow(vm,if(item.type=="show")"Seasons"else "In this collection",vm.children,"children:${item.id}",entryFocus=childFocus) + } + } + if(item.castMembers.isNotEmpty())item(key="cast-${item.id}"){CastRail(vm,item,actionFocus,castFocus)} + if(extras.isNotEmpty())item(key="extras-${item.id}"){MediaRow(vm,"Trailers & extras",extras,"extras:${item.id}",landscape=true,onClick={vm.play(it)})} if(vm.detailRelated.isNotEmpty())item(key="related-${item.id}"){MediaRow(vm,if(item.type=="movie")"Related movies"else "Related shows",vm.detailRelated,"related:${item.id}")} } } @@ -105,32 +126,74 @@ private object DetailsScroll:BringIntoViewSpec { } } -@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} +@Composable private fun TitleInformation(vm:KaleidoViewModel,item:Title,actionFocus:FocusRequester,below:FocusRequester?,initialFocus:Boolean,modifier:Modifier) { + val actionNavigation=Modifier.focusProperties{if(below!=null)down=below} var summaryOverflow by remember(item.id){mutableStateOf(false)} var showSynopsis by remember(item.id){mutableStateOf(false)} + var showVersions by remember(item.id){mutableStateOf(false)} + val media=item.media.getOrNull(vm.mediaIndex(item)) 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)) + // Seasons and episodes name their show above the title. + val show=when(item.type){"episode"->item.grandparentTitle;"season"->item.parentTitle;else->""} + if(show.isNotBlank())Text(show,color=Cinema.secondary,fontSize=12.sp,lineHeight=16.sp,fontWeight=FontWeight.Medium) + Text(item.title,color=Accent,fontSize=32.sp,lineHeight=36.sp,fontWeight=FontWeight.Bold,maxLines=2,overflow=TextOverflow.Ellipsis,modifier=Modifier.widthIn(max=560.dp)) + Row(Modifier.widthIn(max=620.dp).padding(top=9.dp),verticalAlignment=Alignment.CenterVertically) { + Text(listOf(item.subtitle,airDate(item.releaseDate).takeIf{item.type=="episode"}.orEmpty(),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,onTextLayout={summaryOverflow=it.hasVisualOverflow},modifier=Modifier.padding(top=10.dp,bottom=17.dp)) + Text(item.summary,color=Cinema.secondary,fontSize=12.sp,lineHeight=18.sp,maxLines=3,overflow=TextOverflow.Ellipsis,onTextLayout={summaryOverflow=it.hasVisualOverflow},modifier=Modifier.widthIn(max=560.dp).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)} + // Scrolls sideways only if a title has more actions than fit beside its poster. + if(item.type!="collection")Row(Modifier.horizontalScroll(rememberScrollState()).padding(vertical=3.dp),horizontalArrangement=Arrangement.spacedBy(9.dp),verticalAlignment=Alignment.CenterVertically) { + ActionButton(if(item.offset>0)"Resume from ${clockTime(item.offset)}"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)} } + item.trailer?.let{trailer->ActionButton("Trailer",Icons.Outlined.Movie,modifier=actionNavigation){vm.play(trailer)}} + // Name the version by resolution unless several share it, e.g. two 1080p encodes. + if(item.media.size>1)ActionButton(if(item.media.map{it.resolutionLabel}.distinct().size==item.media.size&&media?.resolutionLabel?.isNotBlank()==true)"Version · ${media.resolutionLabel}" + else "Version ${vm.mediaIndex(item)+1} of ${item.media.size}",Icons.Outlined.Layers,modifier=actionNavigation){showVersions=true} + if(item.type in listOf("episode","season")&&(if(item.type=="episode")item.grandparentId else item.parentId).isNotBlank())ActionButton("Go to show",Icons.Outlined.Tv,modifier=actionNavigation){vm.openShow(item)} if(item.type in listOf("show","movie")&&summaryOverflow)ActionButton("Synopsis",Icons.Outlined.Description,modifier=actionNavigation){showSynopsis=true} } - 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))} + if(item.type !in listOf("show","season"))media?.let{Text(it.description(),color=Cinema.quiet,fontSize=9.5.sp,modifier=Modifier.padding(top=12.dp))} } if(showSynopsis)SynopsisDialog(vm.api,item){showSynopsis=false} + if(showVersions)ChoiceDialog("Versions",item.media.map{it.description(includeSize=true)},vm.mediaIndex(item),{showVersions=false}){vm.chooseMedia(item,it);showVersions=false} +} + +/** "Jul 11, 2004" in the TV's locale, from Plex's ISO date. */ +internal fun airDate(iso:String):String = runCatching{ + java.time.LocalDate.parse(iso.take(10)).format(java.time.format.DateTimeFormatter.ofLocalizedDate(java.time.format.FormatStyle.MEDIUM)) +}.getOrDefault("") + +/** A season's episode: still, number and title, runtime, air date and synopsis. */ +@Composable private fun EpisodeRow(vm:KaleidoViewModel,ep:Title,focusKey:String,entry:FocusRequester?) { + var focused by remember{mutableStateOf(false)} + val requester=remember{FocusRequester()} + LaunchedEffect(Unit){if(vm.focusId==focusKey){withFrameNanos{};runCatching{requester.requestFocus()}}} + Row(Modifier.padding(horizontal=Cinema.gutter-8.dp).fillMaxWidth().then(if(entry!=null)Modifier.focusRequester(entry)else Modifier).focusRequester(requester).navigationSound() + .onFocusChanged{focused=it.isFocused;if(it.isFocused)vm.focusId=focusKey}.titleActions{vm.showActions(ep)} + .clip(RoundedCornerShape(Cinema.radius)).background(if(focused)Color.White.copy(alpha=.1f)else Color.Transparent).clickable{vm.open(ep)} + .clearAndSetSemantics{contentDescription=listOf("Episode ${ep.index}",ep.title,ep.watchStatus(vm.watchedPercent)).filter{it.isNotBlank()}.joinToString(". ");this.focused=focused;role=Role.Button;onClick{vm.open(ep);true}} + .padding(8.dp),horizontalArrangement=Arrangement.spacedBy(18.dp),verticalAlignment=Alignment.CenterVertically) { + Box(Modifier.width(160.dp).aspectRatio(16f/9f).clip(RoundedCornerShape(Cinema.radius))) { + Artwork(vm.api,ep.thumb.ifBlank{ep.art},Modifier.fillMaxSize(),480,270,animate=false) + if(ep.offset>0)Box(Modifier.align(Alignment.BottomCenter).fillMaxWidth().padding(start=6.dp,end=6.dp,bottom=5.dp).height(2.dp).background(Color.Black.copy(alpha=.5f))) { + Box(Modifier.fillMaxWidth(ep.progress.coerceAtLeast(.015f)).fillMaxHeight().background(Accent)) + } + WatchBadge(ep,vm.watchedPercent) + if(focused)Box(Modifier.fillMaxSize().border(2.dp,Accent,RoundedCornerShape(Cinema.radius))) + } + Column(Modifier.weight(1f),verticalArrangement=Arrangement.spacedBy(3.dp)) { + Text("${ep.index}. ${ep.title}",color=Accent,fontSize=14.sp,lineHeight=18.sp,fontWeight=if(focused)FontWeight.SemiBold else FontWeight.Medium,maxLines=1,overflow=TextOverflow.Ellipsis) + Text(listOf(if(ep.duration>0)"${ep.duration/60000} min"else "",airDate(ep.releaseDate),if(ep.offset>0)"${((ep.duration-ep.offset)/60000).coerceAtLeast(0)} min left"else ep.watchStatus(vm.watchedPercent)).filter{it.isNotBlank()}.joinToString(" · "),color=Muted,fontSize=10.sp,lineHeight=14.sp,maxLines=1) + if(ep.summary.isNotBlank())Text(ep.summary,color=Cinema.secondary,fontSize=11.sp,lineHeight=16.sp,maxLines=2,overflow=TextOverflow.Ellipsis,modifier=Modifier.widthIn(max=720.dp)) + } + } } @Composable private fun SynopsisDialog(api:PlexApi,item:Title,onDismiss:()->Unit) { @@ -163,18 +226,18 @@ private object DetailsScroll:BringIntoViewSpec { } } -@Composable private fun CastRail(vm:KaleidoViewModel,item:Title,actionFocus:FocusRequester) { +@Composable private fun CastRail(vm:KaleidoViewModel,item:Title,actionFocus:FocusRequester,entry: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-> + LazyRow(state=row,contentPadding=PaddingValues(horizontal=Cinema.gutter),horizontalArrangement=Arrangement.spacedBy(16.dp),modifier=Modifier.focusRestorer(fallback=entry)) { + itemsIndexed(item.castMembers,key={index,actor->actor.id.ifBlank{"${actor.name}-$index"}}){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{ + Column(Modifier.width(108.dp).then(if(index==0)Modifier.focusRequester(entry)else Modifier).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(". ") @@ -190,7 +253,7 @@ private object DetailsScroll:BringIntoViewSpec { } } -@Composable private fun ActorPortrait(api:PlexApi,actor:CastMember,modifier:Modifier) { +@Composable internal 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) { diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..dc16d42 --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,4 @@ +<resources> + <string name="app_name">Kaleido</string> + <string name="search_hint">Movies, shows, episodes, people</string> +</resources> diff --git a/app/src/main/res/xml/searchable.xml b/app/src/main/res/xml/searchable.xml new file mode 100644 index 0000000..500ce53 --- /dev/null +++ b/app/src/main/res/xml/searchable.xml @@ -0,0 +1,5 @@ +<?xml version="1.0" encoding="utf-8"?> +<searchable xmlns:android="http://schemas.android.com/apk/res/android" + android:label="@string/app_name" + android:hint="@string/search_hint" + android:voiceSearchMode="showVoiceSearchButton|launchRecognizer" /> diff --git a/app/src/test/java/tv/kaleido/app/PlaybackModelTest.kt b/app/src/test/java/tv/kaleido/app/PlaybackModelTest.kt new file mode 100644 index 0000000..f53430c --- /dev/null +++ b/app/src/test/java/tv/kaleido/app/PlaybackModelTest.kt @@ -0,0 +1,54 @@ +package tv.kaleido.app +import org.junit.Assert.* +import org.junit.Test +class PlaybackModelTest { + private fun title(type:String,id:String=type)=Title(id,"/library/metadata/$id",type,"Title $id","","","","",0,0,false,"","","","","","",0,0,0,0,emptyList(),emptyList(),emptyList(),emptyList()) + + @Test fun localAddresses() { + assertTrue(isLocalAddress("http://192.168.50.10:32400")) + assertTrue(isLocalAddress("https://192-168-50-10.0123abcd.plex.direct:32400")) + assertTrue(isLocalAddress("https://10-0-0-4.0123abcd.plex.direct:32400")) + assertTrue(isLocalAddress("http://172.20.1.2:32400")) + assertTrue(isLocalAddress("http://tower:32400")) + assertFalse(isLocalAddress("https://73-21-104-9.0123abcd.plex.direct:32400")) + assertFalse(isLocalAddress("http://172.40.1.2:32400")) + assertFalse(isLocalAddress("https://plex.example.com")) + } + + @Test fun stackedPartsShareOneTimeline() { + val parts=listOf(Part("1","/a",emptyList(),duration=1000),Part("2","/b",emptyList(),duration=2000),Part("3","/c",emptyList(),duration=500)) + assertEquals(0,partFor(parts,0));assertEquals(0,partFor(parts,999)) + assertEquals(1,partFor(parts,1000));assertEquals(2,partFor(parts,3200)) + // Past the end, or without durations, stays within the parts. + assertEquals(2,partFor(parts,9000)) + assertEquals(0,partFor(listOf(Part("1","/a",emptyList())),5000)) + assertEquals(0L,partStart(parts,0));assertEquals(3000L,partStart(parts,2)) + } + + @Test fun untitledChaptersAreNumberedFromOne() { + assertEquals("Chapter 1",Title.chapterTitle("",0)) + assertEquals("Opening",Title.chapterTitle("Opening",3)) + } + + @Test fun versionDescriptions() { + val uhd=Media("1","mkv","hevc","eac3","4k",3840,2160,16808,listOf(Part("p","/k",listOf(Stream("a",2,"eac3","English","English (EAC3 7.1 Atmos)",true,"",8,1)),size=12_521_383_389)),"Dolby Vision",8) + assertEquals("4K · Dolby Vision · HEVC · EAC3 7.1 Atmos · 17 Mbps",uhd.description()) + assertTrue(uhd.description(includeSize=true).endsWith("12.5 GB")) + assertEquals("1080p",Media("2","mp4","h264","aac","1080",1920,1080,0,emptyList()).resolutionLabel) + } + + @Test fun searchGroupsFollowBrowsingOrder() { + val groups=searchGroups(listOf(title("episode","e"),title("show","s"),title("movie","m"))) + assertEquals(listOf("Movies","TV shows","Episodes"),groups.map{it.first}) + } + + @Test fun seasonsNameTheirShow() { + val season=title("season").copy(title="Season 1",parentTitle="The 4400") + assertEquals("The 4400 · Season 1",season.displayTitle) + assertEquals("The 4400 · Season 2",season.copy(title="The 4400 · Season 2").displayTitle) + } + + @Test fun speedLabels() { + assertEquals("Normal",speedLabel(1f));assertEquals("1.25×",speedLabel(1.25f));assertEquals("2×",speedLabel(2f)) + } +} diff --git a/distribution/Kaleido.apk b/distribution/Kaleido.apk index 904c126..49b0e46 100644 Binary files a/distribution/Kaleido.apk and b/distribution/Kaleido.apk differ diff --git a/distribution/Kaleido.apk.sha256 b/distribution/Kaleido.apk.sha256 index a260aba..3a6d160 100644 --- a/distribution/Kaleido.apk.sha256 +++ b/distribution/Kaleido.apk.sha256 @@ -1 +1 @@ -ac32fe3f35376c91b7a9dc0876106c0f6f03a849ece6a6796e8a097e7345e897 Kaleido.apk +83592b2954402db222ed3e5e3f533fe3f2f17f8413cff85e77973213b4eb3233 Kaleido.apk diff --git a/distribution/latest.json b/distribution/latest.json index 6cc528e..7157628 100644 --- a/distribution/latest.json +++ b/distribution/latest.json @@ -1,7 +1,7 @@ { - "version": "0.1.11", - "versionCode": 12, - "url": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.1.11/distribution/Kaleido.apk", - "checksumUrl": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.1.11/distribution/Kaleido.apk.sha256", - "notes": "- Give movie information the fitted poster, cinematic backdrop and safe header placement used by TV shows. Add related movies from Plex beneath the cast.\n- Keep open libraries current: check Plex for library changes every 15 seconds and refresh Home and the active movie/TV section silently, with a 60-second fallback. Preserve filters, loaded titles and D-pad focus; pause checks during playback and while the app is in the background." + "version": "0.2.0", + "versionCode": 13, + "url": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.2.0/distribution/Kaleido.apk", + "checksumUrl": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.2.0/distribution/Kaleido.apk.sha256", + "notes": "- Search works fully with the remote: press Down or the keyboard's Search key to reach results, grouped into Movies, TV shows, Episodes and People. Search by voice with the microphone, the remote's search key or the Assistant.\n- Hold OK (or press Menu) on any title for quick actions: play or resume, start over, mark watched, remove from Continue Watching, or go to the season or show.\n- Title pages add a Trailer button and a Trailers & extras row, a version picker for titles with several files, and a fuller media line with HDR/Dolby Vision, audio channels and bitrate. Season pages list episodes with synopses and air dates; episode pages show the rest of their season and link to the show.\n- Rows with more titles end in View all. Back from the rows returns to the top before leaving Kaleido. A second movie or TV library can be chosen from Discover and is remembered.\n- New settings: a separate remote-connection quality (1080p by default), autoplay countdown or off, automatic intro and credit skipping, and subtitle size and style with a preview. OK skips a visible intro or credits.\n- Stacked multi-part movies play through every part. Kaleido finds your server again if its address changes. A finished movie returns to its page, and focus returns to Play after playback.\n- Fix chapter numbering, menus that opened away from the current choice, a misleading checkmark in Playback options, season cards without their show name, faint focus on light posters, and Try again repeating the action that failed." } diff --git a/docs/audit-2026-10-27.md b/docs/audit-2026-10-27.md new file mode 100644 index 0000000..175362d --- /dev/null +++ b/docs/audit-2026-10-27.md @@ -0,0 +1,105 @@ +# Kaleido 0.1.11 polish audit — 2026-10-27 + +> **Status:** the bugs and polish items below, and the missing features marked in section 4, were addressed in **0.2.0**. See [runtime verification](runtime-verification.md) for what was and wasn't verified on a device. + +Scope: a full read of `app/src/main` plus hands-on D-pad testing of the installed **release 0.1.11** on the onn (192.168.50.195). No code was changed and nothing was installed. Screenshots are in the ignored `evidence/private/audit-2026-10-27/` folder; file names are cited as *(shot: name)*. + +Side effect: playing *Hazbin Hotel* S2·E2 for about three minutes moved its Plex resume point from 15 to 18 minutes. The app was left on Home. + +Labels: **Verified** = reproduced on the TV. **Code** = confirmed by reading the source but not exercised on the TV. + +--- + +## 1. Major bugs + +| # | Area | Finding | Evidence | +|---|---|---|---| +| M1 | Search | **You can't reach search results with the D-pad.** Once the search field has focus, Down, Right and the keyboard's Done key all leave focus in the field. Back is the only way out, and it leaves Search for Home. On a remote, Search is effectively unusable. `SearchScreen` has no focus link from the `OutlinedTextField` to the grid, and the field consumes the arrow keys. No UI script covers Search (`verify_ui.py` has no search step). | Verified with `uiautomator` focus dumps after Down/Down/Right *(shots: search4, search5, ime)* | +| M2 | Home | **One Back press from anywhere in the Home rows exits the app.** Pressing Back with focus four rows down went straight to the launcher. Most TV apps first return focus to the top (hero/tabs) and only exit from there. `KaleidoViewModel.back()` returns `false` on Home regardless of scroll position. | Verified *(shots: rows → back1)* | +| M3 | Playback | **Only the first media version and the first part are ever used.** Everything uses `item.media.first()` / `parts.first()` (`Playback.kt`, `PlexApi.transcodeParams` with `mediaIndex=0`/`partIndex=0`). A movie with 4K and 1080p versions can't be switched, and a stacked multi-part movie (CD1/CD2) stops after part 1. | Code | +| M4 | Connection | **The stored server address is never re-discovered.** `initialize()` only validates the saved `session.server` URL. If the server's LAN IP changes, the TV leaves the LAN, or a plex.direct address rotates, startup shows "Cannot load this server" until the user opens Settings → Choose server. The official app retries every connection from `plex.tv/api/v2/resources`. | Code | + +## 2. Functional bugs + +| # | Area | Finding | Evidence | +|---|---|---|---| +| F1 | Player | **Chapter names are off by one.** The first chapter appears as "Chapter 2 · 0:00". `Models.kt` builds the fallback title as `Chapter ${index+1}`, but Plex chapter `index` is already 1-based. | Verified *(shot: chapters)* | +| F2 | Player | **Track lists don't open at the current item.** In the Chapters list at 18:35, focus opened on the first chapter. `TrackOption` gives initial focus only to the selected row, which `LazyColumn` hasn't composed while it's off-screen, so the list never scrolls to it. The same applies to long subtitle lists (this episode has more than 7 languages). | Verified *(shot: chapters)* | +| F3 | Player | **"Playback options" shows a checkmark on its first row** ("✓ Quality · Original quality"), as if it were a selected choice. `PlaybackOptions` passes `selected=0` to `TrackPanel`. | Verified *(shot: opts)* | +| F4 | Player | **"Chapters" is always listed**, even for titles with no chapters. It then opens a panel that says "No tracks available". | Code | +| F5 | Details | **After playback, focus returns to the Back arrow instead of Resume/Play.** | Verified *(shot: afterplay)* | +| F6 | Home | **Season items in "Recently Added TV" are labelled only "Season 1"**, with no show name or subtitle. `BrowseCard` uses `displayTitle`, which equals `title` for seasons. (`recentSeasons` adds the show name for the TV tab, but Home's `/hubs` items don't get it.) | Verified *(shot: rows)* | +| F7 | Movies/TV | **A second movie or TV library is only half supported.** The library switcher appears only in the A–Z view, and Discover always shows the first library. `chooseSection` doesn't reset `unwatched`, doesn't build the "New seasons" row and isn't cached. Changing tabs drops back to the first library. | Code | +| F8 | Player (movies) | **A finished movie sits on its last frame.** Post-play only runs for episodes, and auto-hide requires `isPlaying`, so the player stays open with its controls showing. The official app returns to the details page. | Code | +| F9 | Errors | **"Try again" doesn't retry what failed.** `ErrorDialog` calls `vm.retry()`, which reloads the page. After a failed `play()` or Mark watched, it reloads instead of retrying the action. | Code | +| F10 | Movie details | **Down from Play lands on the second cast member** (Jessica Biel), not the first. Geometric focus search picks the nearest card. | Verified *(shot: mdetail2)* | +| F11 | Details | **Restoring focus to Cast doesn't work on movie pages.** When returning from an actor page to a movie, the scroll target for `cast:` is only computed when `vm.children` is non-empty (shows). | Code | +| F12 | Playback | **Every conversion request says `location=lan`**, and Original quality always tries the source file first. On a remote or relay connection, that means a full-bitrate direct play with no remote-quality limit. | Code | +| F13 | Misc | `selectServerStream` catches `Exception` without rethrowing `CancellationException`, unlike the rest of the codebase. | Code | + +## 3. Polish and UX + +| # | Area | Finding | Evidence | +|---|---|---|---| +| P1 | Browse | **The focus ring is nearly invisible on light posters.** Discover/Home poster cards show focus only as a 2 dp white border and a slight text-colour change, with no scale. On *Toy Story 5*, focus couldn't be seen; a dump confirmed it was there. (`MediaTile` in the A–Z grid does scale; `BrowseCard` doesn't.) | Verified *(shot: s8)* | +| P2 | Home | **Card captions are hard to read over bright backdrops.** Row captions sit directly on the full-bleed backdrop (e.g. "Fire Country S5 · E3"). | Verified *(shot: rows)* | +| P3 | Season page | **The season page doesn't show the show name.** The header says only "Season 1". | Verified *(shot: season)* | +| P4 | Season page | **Season episodes are hard to scan.** Each episode card repeats the show name ("The 4400") as its title and puts the episode name in small subtitle text. There are no synopses, runtimes or air dates, and episodes sit in a horizontal row. | Verified *(shot: season)* | +| P5 | Episode page | **The episode page is a dead end.** It has no link to its show or season and no list of neighbouring episodes. | Verified *(shot: epdetail)* | +| P6 | Search | **Results aren't grouped or ranked by type.** "silo" returned 32 results, mostly Silo episodes in server order. There are no Movies/Shows/Episodes groups and no actor results. | Verified *(shot: search4)* | +| P7 | Skip intro | **Skip intro/credits takes several presses.** OK while it's showing reveals the controls instead of skipping. Reaching the button takes Up→timeline→Up, and there's no auto-skip option. | Code + `repro_runtime.py credits` key path | +| P8 | Settings | **The Connection page says "Sign in with Plex" while already signed in.** "Switch account" would be clearer. It also doesn't show the server address or connection type (local/remote/relay). | Verified *(shot: settings)* | +| P9 | Navigation | **Back from Search or Settings always goes to Home**, not the tab you came from. | Verified | +| P10 | Details | **"Resume · 15 min" reads like "15 minutes left".** "Resume from 15:02" or "13 min left" would be unambiguous. | Verified *(shot: epdetail)* | +| P11 | Details | **The media line is thin.** It shows "4K · AV1 · EAC3", with no HDR/Dolby Vision, channel layout (5.1/Atmos), file size or bitrate. | Verified *(shot: mdetail)* | +| P12 | Player | **The player shows no clock or "Ends at" time.** The episode name is in very small (10 sp) text. | Verified *(shot: play3)* | +| P13 | Player | **The Options menu repeats the Audio and Subtitles buttons**, and speed reads "1.0×". | Verified *(shot: opts)* | +| P14 | Browse | **Partly watched movies show no progress bar on poster cards.** `BrowseCard` draws progress only for landscape cards. | Code | +| P15 | Browse | **Hub rows can't be expanded.** They're capped at 18 items (`count=18`) and have no "View all". | Code | + +## 4. Missing features compared with the official Plex Android TV app + +Music is excluded, since it's deliberately left out. Items marked † may also be intentional omissions; I've listed them so you can decide. + +**Browsing and library** + +- An A–Z jump bar or letter picker. 272 TV titles and the movie library page in 100 at a time with no shortcut. +- Collections and playlists. `PlexApi.collections()` exists but nothing calls it. There are no collection or playlist tabs. +- Richer filters and sorts: year/decade, resolution, content rating, critic rating, last viewed, date added (oldest first). +- *(Added in 0.2.0)* Card context actions (long-press / Menu): Mark watched, Remove from Continue Watching, Go to show/season. +- *(Added in 0.2.0)* Extras and trailers. `details()` requests `includeExtras=1`, but nothing displays them, and there's no Trailer button. +- Director, writer and studio credits on detail pages. +- Theme music on show pages.† +- Photo libraries. `sections()` filters to movie/show only.† +- Watchlist and Plex's online "Discover" content, Live TV/DVR.† + +**Playback** + +- *(Added in 0.2.0)* A version picker for multiple media versions (see M3). +- Choosing audio and subtitles before playback, on the details page. +- Refresh-rate and resolution matching. Nothing sets the frame-rate strategy or display mode; Media3's default only switches when the change is seamless. This onn exposes a single 4K59.94 mode, so it couldn't be tested here. +- *(Size and style added in 0.2.0)* Subtitle appearance (size, colour, background, position) and subtitle sync offset; audio boost and night mode. +- Preferences for default audio/subtitle language and automatic subtitle selection. +- *(Added in 0.2.0)* Autoplay-next on/off and countdown length. The post-play countdown is fixed at 5 seconds and can only be cancelled each time. +- *(Added in 0.2.0)* Auto-skip intros and credits. +- *(Added in 0.2.0)* A separate quality limit for remote connections (see F12). + +**Accounts and the platform** + +- Plex Home / managed-user switching, with PIN entry. +- *(Voice and system search added in 0.2.0)* Android TV home integration: Watch Next / Continue Watching channel, recommendation channels, and voice or global search (`SEARCH` intent). The manifest has only the launcher intent. +- Deep links into titles (from other apps or the system search). + +## 5. Areas that held up well + +- Hero, Continue Watching, Movies/TV Discover and the A–Z grid rendered correctly with stable card bounds, and focus came back correctly from details pages. +- Direct-play H.264/EAC3 started quickly. Resume position, timeline sync, ±10 s taps, and the subtitle, audio, options and chapter panels all opened and closed with Back as expected. +- Mark watched/unwatched, cast → actor pages, related titles, the Synopsis dialog, the update flow, and settings categories behaved as designed. +- The updater checks the host and checksum and compares signing certificates, and the session is encrypted with Android Keystore. + +## 6. Suggested priority + +1. **M1** (Search unreachable), **M2** (Back exits), **F6/P3/P4** (missing show names), **F1–F3** (player menus). +2. **M4** (reconnect), **M3** (versions/parts), **F7** (multiple libraries), **F8** (movie end), **P1** (focus visibility). +3. Missing features, starting with an A–Z jump bar, card context actions, Watch Next integration, collections, and subtitle/autoplay preferences. +4. Add a Search step to `verify_ui.py browse`, since nothing currently exercises it. diff --git a/docs/runtime-verification.md b/docs/runtime-verification.md index 652207a..ec63d81 100644 --- a/docs/runtime-verification.md +++ b/docs/runtime-verification.md @@ -4,6 +4,19 @@ For the 2026-10-26 codec/HDR sweep and its native-versus-converted playback find Target: the authorized onn at `192.168.50.195:5555`, package `tv.kaleido.app`. Other applications and the launcher were not modified. Screenshots, traces, UI dumps and server-specific logs stay in ignored `evidence/private/`. +## 2026-10-27 audit fixes, quick actions, extras, voice search and new settings (0.2.0) + +Addresses the findings in [the 0.1.11 audit](audit-2026-10-27.md). + +- Search had no remote path from the text field to its results and was untested. Down, Right-at-end and the keyboard's Search action now leave the field; results are grouped rows (Movies, TV shows, Seasons, Collections, Episodes, People). `verify_ui.py browse` gained a Search step (type, keyboard Search, open a result, Back restores it, Back returns to the previous tab). The microphone uses Google TV's `com.google.android.katniss` voice input directly; the onn otherwise shows a recognizer chooser. `ACTION_SEARCH` intents open Search with their query. +- Back from Home rows now focuses the hero (Discover on Movies/TV) before exiting. Focus must move before the list scrolls, or the removed card clears it. +- A `focusRestorer()` without a fallback overrode explicit `down` targets and chose the geometrically nearest card (e.g. the second cast member below Play). Rows now pass their entry card as the fallback. +- Long-press OK / Menu actions use a `Modifier.Node`. A `composed {}` modifier and a per-card focus animation on every Home card measurably slowed browsing (median 25 ms / p95 38 ms); with the node and a layer-only lift, five profiled-release runs of `repro_runtime.py browse` measured median 15–17 ms and p95 29, 32, 32, 38 and 46 ms. Four met the <40 ms target; the variance is device noise around the 0.1.11 record (15 ms / 27 ms). The baseline profile now covers `ScreensKt`, the actions node, `Title` and `Media`. +- Moving the skip-marker lookup to the top of the player recomposed the whole player every position tick, re-applying subtitle styling and keeping the window from going idle. It is now `derivedStateOf`. +- `repro_runtime.py episode` and `credits` pressed Pause at a fixed 6–9 s after a cold launch and failed identically on 0.1.11 code; they now wait for the player's READY log like `controls`. +- Verified on the onn: all `verify_ui.py browse` (8) and `player` (7) checks, `verify_settings.py`, `verify_details.py`, `verify_details_layout.py`, `verify_movie_details.py`, `repro_runtime.py sections/controls/episode/postplay/credits/browse`, 25 instrumentation tests and 14 unit tests. Hands-on: actions sheet, season episode list, episode season row, Trailer playback ending back on the movie page, View all, chapter numbering, the Version picker on the server's one two-version episode, voice input and the subtitle preview. +- Not verified on a device: remote-connection quality (no remote connection here; `isLocalAddress` is unit-tested), stacked multi-part playback (no such files on the server), automatic server re-discovery after an address change, and subtitle styles over real subtitles in playback (the Settings preview uses the player's own `SubtitleView`). + ## 2026-10-27 movie details and foreground library sync (0.1.11) - Movies now share TV shows' fitted poster, cinematic backdrop and safe header; related movie cards come from Plex's related metadata endpoint, below Cast. diff --git a/scripts/repro_runtime.py b/scripts/repro_runtime.py index 6162561..bbba668 100644 --- a/scripts/repro_runtime.py +++ b/scripts/repro_runtime.py @@ -16,7 +16,7 @@ def sections(): key(21);wait(lambda r:'Recently released' in labels(r),'Cached Movies must return');focused('Movies') print('PASS startup tab switch, TV loading, and cached section return') -def ready(item,timeout=45): +def await_ready(item,timeout=45): # A pause sent while the player is still preparing is overridden when playback starts. deadline=time.monotonic()+timeout while time.monotonic()<deadline: @@ -27,7 +27,7 @@ def ready(item,timeout=45): def controls(): adb('shell','am','force-stop','tv.kaleido.app');adb('logcat','-c') adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset','90000','--ei','testMode','1','--ez','testValidation','true') - ready(7599);key(127);focused('Play') + await_ready(7599);key(127);focused('Play') screenshot('direct-stream-episode') key(4);wait(lambda r:not labels(r),'One Back must hide controls rather than only clearing focus') key(23);focused('Play');key(126);time.sleep(6) @@ -68,7 +68,7 @@ def episode(): adb('shell','am','force-stop','tv.kaleido.app') adb('logcat','-c') adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId',str(item['ratingKey']),'--el','testOffset','90000','--ei','testMode','2','--ez','testValidation','true') - time.sleep(9);key(127);focused('Play') + await_ready(item["ratingKey"]);key(127);focused('Play') for _ in range(6): if 'Next episode' in focus(snapshot()):break key(22) @@ -105,7 +105,7 @@ def credits(): marker=next(m for m in item['Marker'] if m['type']=='credits') adb('shell','am','force-stop','tv.kaleido.app');adb('logcat','-c') adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset',str(marker['startTimeOffset']+2000),'--ei','testMode','2','--ez','testValidation','true') - time.sleep(6);key(127);focused('Play');key(19);focused('Playback timeline');key(19);focused('Skip credits') + await_ready(7599);key(127);focused('Play');key(19);focused('Playback timeline');key(19);focused('Skip credits') screenshot('skip-credits-contrast');key(23) deadline=time.monotonic()+8 while time.monotonic()<deadline: diff --git a/scripts/verify_details.py b/scripts/verify_details.py index 0755369..8d8736f 100644 --- a/scripts/verify_details.py +++ b/scripts/verify_details.py @@ -57,7 +57,10 @@ def main(): related=get('/library/metadata/'+SHOW+'/related').get('Hub',[]) expected_related={m['ratingKey'] for h in related for m in h.get('Metadata',[]) if m.get('type')=='show' and m['ratingKey']!=SHOW} assert expected_related,'Related-show fixture missing server-generated hubs' - key(21);focused('Watch next');key(20);text('Seasons');key(20);focused(show['Role'][0]['tag']);key(20);text('Related shows') + key(21);focused('Watch next');key(20);text('Seasons');key(20);focused(show['Role'][0]['tag']);key(20) + # Trailers & extras, when Plex has them, sit between Cast and Related shows. + if 'Trailers & extras' in labels(snapshot()):wait(lambda r:'Trailer' in focus(r) or 'Extra' in focus(r) or 'Scene' in focus(r) or 'Behind' in focus(r),'Extras row focus');key(20) + text('Related shows') selected=focus(snapshot());assert selected and selected not in ('Watch next','Mark watched') screenshot('details-related-shows');key(23);focused('Watch next');key(4);focused(selected) results.append('Server-related shows render, open and restore focus');print('PASS '+results[-1],flush=True) diff --git a/scripts/verify_settings.py b/scripts/verify_settings.py index 8a5265a..a76c017 100644 --- a/scripts/verify_settings.py +++ b/scripts/verify_settings.py @@ -2,19 +2,25 @@ from verify_ui import launch,key,text,focused,focus,snapshot from device import screenshot -launch();key(22,4);focused('Settings');key(23);focused('Sign in with Plex') +launch();key(22,4);focused('Settings');key(23);focused('Switch account') key(21);focused('Connection');key(20);focused('Playback');key(22);focused('Playback quality') key(23);focused('Original quality');key(4);focused('Playback quality') +key(20);focused('Remote quality');key(23);focused('1080p');key(4);focused('Remote quality') key(20);focused('Watched status');key(23);focused('80%');key(4);focused('Watched status') -print('PASS quality and watched-threshold dialogs cancel back to their controls',flush=True) +key(20);focused('Autoplay next episode');key(23);focused('After 5 seconds');key(4);focused('Autoplay next episode') +key(20);focused('Skip intros');key(20);focused('Skip credits') +print('PASS playback dialogs cancel back to their controls',flush=True) screenshot('settings-playback-current') -key(21);focused('Playback');key(20);focused('Interface');key(22);focused('Navigation sounds') +key(21);focused('Playback');key(20);focused('Subtitles');key(22);focused('Size');key(23);focused('Normal');key(4);focused('Size') +key(20);focused('Style');key(23);focused('White on black');key(4);focused('Style') +screenshot('settings-subtitles-current') +key(21);focused('Subtitles');key(20);focused('Interface');key(22);focused('Navigation sounds') key(21);focused('Interface');key(20);focused('Updates');key(22);focused('Check for updates');key(23) text('Kaleido is up to date.');focused('Check for updates') screenshot('settings-updates-current') -key(21);focused('Updates');key(19,3);focused('Connection');key(22);focused('Sign in with Plex') +key(21);focused('Updates');key(19,4);focused('Connection');key(22);focused('Switch account') key(22) if 'Choose server' in focus(snapshot()):key(22) focused('Sign out');key(23);focused('Keep watching');key(4);focused('Sign out') -key(4);focused('Home') +key(4);focused('TV Shows');key(4);focused('Home') print('PASS category focus, live update check and safe sign-out cancellation',flush=True) diff --git a/scripts/verify_ui.py b/scripts/verify_ui.py index 9b64a2f..a077d8c 100644 --- a/scripts/verify_ui.py +++ b/scripts/verify_ui.py @@ -54,12 +54,23 @@ def browse(): key(20);focused('Discover');key(20);wait(lambda r:bool(focus(r)) and focus(r)!='Discover','TV next episode focus') capture('tv-next-episodes');key(20);text('New seasons');capture('tv-new-seasons');key(20);text('New episodes');capture('tv-new-episodes') passed('TV prioritizes next episodes, new seasons, and new episodes') + key(4);focused('Discover');passed('Back from TV rows returns to Discover first') key(4);focused('Home');passed('Section Back returns to Home navigation') - key(22,4);focused('Settings');key(23);text('Settings');focused('Sign in with Plex');key(23) + key(22,4);focused('Settings');key(23);text('Settings');focused('Switch account');key(23) text('Sign in to Plex');text('plex.tv/link') wait(lambda r:any(re.fullmatch(r'[A-Z0-9]{4,6}',s) for s in labels(r)),'Live Plex PIN') - capture('plex-sign-in');key(4);text('Settings');key(4);focused('Home') + capture('plex-sign-in');key(4);text('Settings');key(4);focused('TV Shows');key(4);focused('Home') passed('Plex account linking obtains a real PIN and cancellation preserves the session') + # Tabs activate on focus, so Search opens from TV Shows and Back returns there. + key(22,3);focused('Search');key(23);text('Search') + adb('shell','input','text','silo');text('TV shows') + key(66);wait(lambda r:focus(r) not in ('','silo'),'Search results take focus from the field') + root=snapshot() + if 'Silo' not in focus(root):key(20);wait(lambda r:'Silo' in focus(r),'TV shows row below the first result row') + key(23);text('Seasons') + key(4);wait(lambda r:'Silo' in focus(r),'Back restores the search result') + capture('search');key(4);focused('TV Shows');key(4);focused('Home') + passed('Search results are reachable by remote, open details and Back returns to the previous tab') def position(): # Live media-session position: the reported one is as of its last update, so project it to now. @@ -85,7 +96,7 @@ def player(): key(4);focused('Audio tracks');key(22);focused('Subtitles');key(23);text('Off');capture('subtitles') passed('Audio and subtitle panels open, close, and restore focus') key(4);focused('Subtitles');key(22);focused('Playback options');key(23);text('Playback options') - key(20,3);focused('Speed');key(23);text('Playback speed');focused('1.0×');key(20);focused('1.25×');key(23) + key(20);focused('Speed');key(23);text('Playback speed');focused('Normal');key(20);focused('1.25×');key(23) focused('Playback options');key(23);text('Speed · 1.25×');key(4);focused('Playback options') key(23);text('Playback options');key(23);text('Playback quality');focused('Original quality');key(20);focused('4K');key(19);focused('Original quality');key(23) focused('Playback options');time.sleep(5);key(23);text('Quality · Original quality');key(4);focused('Playback options') diff --git a/version.properties b/version.properties index a99ad37..9b827af 100644 --- a/version.properties +++ b/version.properties @@ -1,2 +1,2 @@ -versionName=0.1.11 -versionCode=12 +versionName=0.2.0 +versionCode=13