Release Kaleido 0.2.0 with remote-ready search, quick actions, extras and playback settings
All checks were successful
Validate and publish Kaleido / android (push) Successful in 2m44s
All checks were successful
Validate and publish Kaleido / android (push) Successful in 2m44s
Fix the 0.1.11 audit findings: Search results were unreachable from the text field, Back exited from Home rows, only the first version/part played, a moved server was never re-discovered, chapter names were off by one, menus opened away from the current choice, and focus restoration misfired. Add long-press/Menu title actions, trailers and extras, voice and system search, View all rows, a per-destination library choice, autoplay and auto-skip settings, a separate remote quality, and subtitle size/style. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
5230692b8d
commit
64ad7b55cd
31 changed files with 1184 additions and 253 deletions
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -4,9 +4,15 @@
|
|||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
<uses-feature android:name="android.software.leanback" android:required="true" />
|
||||
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
|
||||
<uses-feature android:name="android.hardware.microphone" android:required="false" />
|
||||
<!-- Voice search uses the TV's speech recognizer when it has one. -->
|
||||
<queries><intent><action android:name="android.speech.action.RECOGNIZE_SPEECH" /></intent></queries>
|
||||
<application android:name=".KaleidoApplication" android:label="Kaleido" android:icon="@drawable/icon" android:banner="@drawable/banner" android:theme="@style/Theme.Kaleido" android:allowBackup="false" android:usesCleartextTraffic="true" android:supportsRtl="true">
|
||||
<activity android:name=".MainActivity" android:exported="true" android:screenOrientation="landscape" android:configChanges="keyboard|keyboardHidden|navigation|orientation|screenSize|screenLayout|uiMode" android:launchMode="singleTop">
|
||||
<intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LEANBACK_LAUNCHER" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter>
|
||||
<intent-filter><action android:name="android.intent.action.SEARCH" /></intent-filter>
|
||||
<intent-filter><action android:name="com.google.android.gms.actions.SEARCH_ACTION" /><category android:name="android.intent.category.DEFAULT" /></intent-filter>
|
||||
<meta-data android:name="android.app.searchable" android:resource="@xml/searchable" />
|
||||
</activity>
|
||||
<provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.files" android:exported="false" android:grantUriPermissions="true"><meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /></provider>
|
||||
</application>
|
||||
|
|
|
|||
|
|
@ -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;->**(**)**
|
||||
|
|
|
|||
|
|
@ -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<Title>,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))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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))
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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))}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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()}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)}}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)}
|
||||
|
|
|
|||
|
|
@ -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)})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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) {
|
||||
|
|
|
|||
4
app/src/main/res/values/strings.xml
Normal file
4
app/src/main/res/values/strings.xml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
<resources>
|
||||
<string name="app_name">Kaleido</string>
|
||||
<string name="search_hint">Movies, shows, episodes, people</string>
|
||||
</resources>
|
||||
5
app/src/main/res/xml/searchable.xml
Normal file
5
app/src/main/res/xml/searchable.xml
Normal file
|
|
@ -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" />
|
||||
54
app/src/test/java/tv/kaleido/app/PlaybackModelTest.kt
Normal file
54
app/src/test/java/tv/kaleido/app/PlaybackModelTest.kt
Normal file
|
|
@ -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))
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue