diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d6aa49..8098db5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Kaleido releases +## 0.4.0 + +- Frame TV show, season and episode background artwork against the full page, preserving the top of the scene instead of cropping it into a short season header, with no gap above the artwork. +- Redesign Movie and TV Categories with large artwork cards drawn from titles in each Plex genre, with clear remote focus and category return navigation. +- Show a brief animated direction and seconds cue when tapping Left or Right during playback. Repeated taps accumulate and holding still opens the timeline. +- Remove the broken in-app voice search button. Android TV keyboard voice input remains available. Add a Clear button that empties the query and results and returns focus to the search field. + ## 0.3.1 - Fix episode pages getting stuck on Resume after scrolling the season row away from the original episode, returning Home, and reopening it from Continue Watching. diff --git a/app/src/main/java/tv/kaleido/app/BrowseBackdrop.kt b/app/src/main/java/tv/kaleido/app/BrowseBackdrop.kt index bd753f3..7e8e8bc 100644 --- a/app/src/main/java/tv/kaleido/app/BrowseBackdrop.kt +++ b/app/src/main/java/tv/kaleido/app/BrowseBackdrop.kt @@ -13,6 +13,7 @@ import androidx.compose.foundation.Image import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.* import androidx.compose.ui.Modifier +import androidx.compose.ui.Alignment import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.graphics.asImageBitmap @@ -46,7 +47,7 @@ internal fun browseBackdropRequest(context:Context,api:PlexApi,path:String,cinem .transformations(BrowseContrast(cinematic)).crossfade(false).build() } -@Composable internal fun BrowseBackdrop(api:PlexApi,path:String,modifier:Modifier,cinematic:Boolean=false,animate:Boolean=false) { +@Composable internal fun BrowseBackdrop(api:PlexApi,path:String,modifier:Modifier,cinematic:Boolean=false,animate:Boolean=false,alignment:Alignment=Alignment.Center,contentScale:ContentScale=ContentScale.Crop) { val context=LocalContext.current var previous by remember{mutableStateOf(null)} val request=remember(path,api.session?.server,cinematic,animate){browseBackdropRequest(context,api,path,cinematic)?.newBuilder()?.placeholderMemoryCacheKey(previous)?.build()} @@ -56,7 +57,7 @@ internal fun browseBackdropRequest(context:Context,api:PlexApi,path:String,cinem if(request!=null){val result=context.imageLoader.execute(request);if(result is SuccessResult){previous=result.memoryCacheKey;value=(result.drawable as? BitmapDrawable)?.bitmap}} } Crossfade(bitmap,modifier=modifier,animationSpec=tween(220),label="heroArtwork"){loaded-> - loaded?.let{Image(it.asImageBitmap(),null,contentScale=ContentScale.Crop,modifier=Modifier.fillMaxSize())} + loaded?.let{Image(it.asImageBitmap(),null,contentScale=contentScale,alignment=alignment,modifier=Modifier.fillMaxSize())} } - }else AsyncImage(request,contentDescription=null,modifier=modifier,contentScale=ContentScale.Crop,onSuccess={previous=it.result.memoryCacheKey}) + }else AsyncImage(request,contentDescription=null,modifier=modifier,contentScale=contentScale,alignment=alignment,onSuccess={previous=it.result.memoryCacheKey}) } diff --git a/app/src/main/java/tv/kaleido/app/BrowseScreens.kt b/app/src/main/java/tv/kaleido/app/BrowseScreens.kt index 4d59c8f..45340e4 100644 --- a/app/src/main/java/tv/kaleido/app/BrowseScreens.kt +++ b/app/src/main/java/tv/kaleido/app/BrowseScreens.kt @@ -34,8 +34,6 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlinx.coroutines.delay import kotlinx.coroutines.flow.first -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 @@ -155,6 +153,7 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List,index:Int, @Composable fun LibraryScreen(vm:KaleidoViewModel,navigation:DiscoveryNavigation) { if(!vm.allTitles){DiscoveryScreen(vm,home=false,navigation=navigation);return} val name=if(vm.page.kind=="movies")"Movies"else "TV Shows" + LaunchedEffect(vm.categories,vm.section?.id,vm.genres){vm.loadCategoryArtworks()} var sortMenu by remember{mutableStateOf(false)} var genreMenu by remember{mutableStateOf(false)} var sectionMenu by remember{mutableStateOf(false)} @@ -176,13 +175,30 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int, else if(vm.genres.isEmpty()&&vm.busy)Text("Loading categories…",color=Muted,fontSize=13.sp,modifier=Modifier.padding(start=Cinema.gutter,top=24.dp)) else if(vm.genres.isEmpty())EmptyState("No categories available","This Plex library has no genre categories.") else { - val categoryRequesters=remember(vm.section?.id,vm.genres){vm.genres.associate{it.first to FocusRequester()}.toMutableMap()} - LazyVerticalGrid(GridCells.Fixed(5),contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=18.dp,bottom=30.dp),horizontalArrangement=Arrangement.spacedBy(13.dp),verticalArrangement=Arrangement.spacedBy(12.dp),modifier=Modifier.fillMaxSize()) { + val categoryRequesters=remember(vm.section?.id,vm.genres,categoryEntryFocus){vm.genres.mapIndexed{i,entry->entry.first to if(i==0)categoryEntryFocus else FocusRequester()}.toMap()} + LazyVerticalGrid(GridCells.Fixed(3),contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=18.dp,bottom=30.dp),horizontalArrangement=Arrangement.spacedBy(13.dp),verticalArrangement=Arrangement.spacedBy(12.dp),modifier=Modifier.fillMaxSize()) { itemsIndexed(vm.genres,key={_,it->it.first}){index,entry-> - val requester=if(index==0)categoryEntryFocus else categoryRequesters.getValue(entry.first) - val selected=vm.focusId=="category:${entry.first}" - Box(Modifier.fillMaxWidth().height(54.dp).focusRequester(requester).onFocusChanged{if(it.isFocused)vm.focusId="category:${entry.first}"}.navigationSound().clip(RoundedCornerShape(Cinema.radius)).background(Color.White.copy(alpha=if(selected) .13f else .07f)).border(1.dp,Color.White.copy(alpha=if(selected) .38f else .08f),RoundedCornerShape(Cinema.radius)).clickable{vm.selectCategory(entry.first)}.padding(horizontal=14.dp),contentAlignment=Alignment.CenterStart) { - Text(entry.second,color=if(selected)Accent else Cinema.secondary,fontSize=13.sp,fontWeight=if(selected)FontWeight.SemiBold else FontWeight.Medium,maxLines=1,overflow=TextOverflow.Ellipsis) + val requester=categoryRequesters.getValue(entry.first) + val sample=vm.categoryArtwork[entry.first] + val artworkPath=sample?.let{it.art.ifBlank{it.thumb}}.orEmpty() + var focused by remember(entry.first,vm.section?.id){mutableStateOf(false)} + val shape=RoundedCornerShape(Cinema.radius) + Box(Modifier.fillMaxWidth().aspectRatio(16f/9f).focusRequester(requester).focusProperties { + left=if(index%3==0)FocusRequester.Cancel else categoryRequesters.getValue(vm.genres[index-1].first) + right=if(index%3==2||index==vm.genres.lastIndex)FocusRequester.Cancel else categoryRequesters.getValue(vm.genres[index+1].first) + up=if(index<3)categoriesFocus else categoryRequesters.getValue(vm.genres[index-3].first) + down=if(index+3>=vm.genres.size)FocusRequester.Cancel else categoryRequesters.getValue(vm.genres[index+3].first) + }.onFocusChanged{focused=it.isFocused;if(it.isFocused)vm.focusId="category:${entry.first}"}.navigationSound().clip(shape).background(Color(0xFF171717)).border(1.dp,Color.White.copy(alpha=if(focused).9f else .09f),shape).clickable{vm.selectCategory(entry.first)}) { + if(artworkPath.isNotBlank())Artwork(vm.api,artworkPath,Modifier.fillMaxSize(),540,304) + Box(Modifier.fillMaxSize().background(Brush.verticalGradient(listOf(Color.Black.copy(alpha=.08f),Color.Black.copy(alpha=.12f),Color.Black.copy(alpha=.9f))))) + Box(Modifier.align(Alignment.TopStart).padding(9.dp).background(Color.Black.copy(alpha=.6f),RoundedCornerShape(3.dp)).padding(horizontal=7.dp,vertical=4.dp)) { + Text(if(vm.section?.type=="movie")"FILM"else"SERIES",color=Color.White.copy(alpha=.88f),fontSize=8.sp,lineHeight=10.sp,fontWeight=FontWeight.SemiBold,letterSpacing=1.sp,maxLines=1) + } + Column(Modifier.align(Alignment.BottomStart).fillMaxWidth().padding(horizontal=17.dp,vertical=15.dp)) { + if(sample!=null)Text(sample.title,color=Color.White.copy(alpha=.78f),fontSize=11.sp,lineHeight=12.sp,fontWeight=FontWeight.Medium,maxLines=1,overflow=TextOverflow.Ellipsis) + Text(entry.second,color=Color.White,fontSize=16.sp,lineHeight=19.sp,fontWeight=FontWeight.SemiBold,maxLines=1,overflow=TextOverflow.Ellipsis) + } + if(focused)Box(Modifier.fillMaxSize().padding(3.dp).border(1.dp,Color.White.copy(alpha=.85f),shape)) } LaunchedEffect(vm.focusId,index){if((vm.focusId=="categories-entry"&&index==0)||vm.focusId=="category:${entry.first}"){withFrameNanos{};runCatching{requester.requestFocus()}}} } @@ -248,27 +264,10 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int, } @Composable fun SearchScreen(vm:KaleidoViewModel) { - val field=remember{FocusRequester()};val resultsFocus=remember{FocusRequester()};val micFocus=remember{FocusRequester()} + val field=remember{FocusRequester()};val resultsFocus=remember{FocusRequester()};val clearFocus=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,vm.query){searchGroups(vm.searchResults.titles,vm.query)} val people=vm.searchResults.people @@ -281,18 +280,20 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int, 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. + // Down enters results; Right at the end reaches Clear without deleting character by character. 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 if(it.key==Key.DirectionDown){if(hasResults)enterResults()else if(value.text.isNotEmpty()){keyboard?.hide();runCatching{clearFocus.requestFocus()}};true} + else if(it.key==Key.DirectionRight&&value.text.isNotEmpty()&&value.selection.collapsed&&value.selection.end==value.text.length){keyboard?.hide();runCatching{clearFocus.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(value.text.isNotEmpty())ActionButton("Clear",Icons.Outlined.Close,modifier=Modifier.focusRequester(clearFocus).focusProperties{left=field;if(hasResults)down=resultsFocus}){ + // Move focus before removing this button from the composition. + runCatching{field.requestFocus()};query("") + } + if(vm.query.isNotBlank())Text((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(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)) + if(vm.query.isNotBlank()&&!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-> diff --git a/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt b/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt index 2be7d2a..2b93995 100644 --- a/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt +++ b/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt @@ -22,10 +22,18 @@ import coil.request.Disposable import java.util.concurrent.Executors import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.isActive +import kotlinx.coroutines.sync.Semaphore +import kotlinx.coroutines.sync.withPermit data class Page(val kind: String="home",val id: String="",val name: String="",val returnFocus: String="",val actor:CastMember?=null) private data class SectionContent(val hubs:List<Hub>,val genres:List<Pair<String,String>>,val library:LibraryPage) private data class HomeContent(val hubs:List<Hub>,val features:List<HomeFeature>) +private fun Title.artworkPath():String=art.ifBlank{thumb} +private fun categoryArtworkHint(section:Section,genre:String):String?=when { + section.type=="show"&&genre.equals("Animation",ignoreCase=true)->"Hazbin" + section.type=="movie"&&genre.equals("Action",ignoreCase=true)->"Batman" + else->null +} class KaleidoViewModel(app: Application): AndroidViewModel(app) { val application = app as KaleidoApplication val api = application.api @@ -43,6 +51,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { var library by mutableStateOf(emptyList<Title>()); private set var total by mutableStateOf(0); private set var genres by mutableStateOf(emptyList<Pair<String,String>>()); private set + var categoryArtwork by mutableStateOf<Map<String,Title>>(emptyMap()); private set var section by mutableStateOf<Section?>(null); private set var sort by mutableStateOf("titleSort:asc"); private set var genre by mutableStateOf(""); private set @@ -59,8 +68,6 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { var actorTitles by mutableStateOf(emptyList<Title>()); private set var markingId by mutableStateOf<String?>(null); 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 @@ -116,6 +123,9 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { private var loadGeneration=0 private var authJob: Job? = null private var searchJob: Job? = null + private var categoryArtworkJob: Job? = null + private var categoryArtworkSectionId = "" + private var categoryArtworkGeneration = 0 private val detailsCache = mutableMapOf<String,Title>() private val sectionCache=mutableMapOf<String,SectionContent>() private val characterOffsetCache=mutableMapOf<LibraryCharacterQuery,Map<String,Int>>() @@ -257,6 +267,12 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { } } private fun cancelAnticipation(){previews.cancelPrediction();predictedArtwork?.dispose();predictedArtwork=null;predictedArtworkKey=""} + private fun resetCategoryArtwork(sectionId:String?) { + categoryArtworkGeneration++ + categoryArtworkJob?.cancel();categoryArtworkJob=null + categoryArtworkSectionId=sectionId.orEmpty() + categoryArtwork=emptyMap() + } override fun onCleared(){cancelAnticipation();artworkPrefetchDispatcher.close();super.onCleared()} fun linkAccount() { authJob?.cancel();error=null;pin=null @@ -300,8 +316,6 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { /** "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){ @@ -380,7 +394,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { } /** 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 + loadJob?.cancel();resetCategoryArtwork(s?.id);section=s;sort="titleSort:asc";genre="";unwatched=false categories=false;libraryJumpIndex=-1;libraryJumpLetter=null if(s==null){discoverHubs=emptyList();library=emptyList();total=0;genres=emptyList();return} val cached=sectionCache[s.id] @@ -404,6 +418,43 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { } fun setAll(value: Boolean){focusId=if(value)"library-entry"else "discovery-entry";allTitles=value;categories=false;libraryJumpIndex=-1;libraryJumpLetter=null} fun openCategories(){val hadGenre=genre.isNotBlank();allTitles=true;categories=true;genre="";focusId="categories-entry";libraryJumpIndex=-1;libraryJumpLetter=null;if(hadGenre)refreshLibrary()} + fun loadCategoryArtworks() { + val selectedSection=section ?: return + if(!categories||genre.isNotBlank()||genres.isEmpty())return + if(categoryArtworkSectionId!=selectedSection.id)resetCategoryArtwork(selectedSection.id) + val localSamples=genres.mapNotNull{entry-> + val hint=categoryArtworkHint(selectedSection,entry.second) + val sample=library.firstOrNull{item-> + item.type==selectedSection.type&&item.genres.any{it.equals(entry.second,ignoreCase=true)}&& + item.artworkPath().isNotBlank()&&(hint==null||item.title.contains(hint,ignoreCase=true)) + } + sample?.let{entry.first to it} + }.toMap() + if(localSamples.isNotEmpty())categoryArtwork=categoryArtwork+localSamples + val missing=genres.filter{entry->entry.first !in categoryArtwork} + if(missing.isEmpty()||categoryArtworkJob?.isActive==true)return + val sectionId=selectedSection.id + val sectionType=selectedSection.type + val generation=categoryArtworkGeneration + categoryArtworkJob=viewModelScope.launch { + val requestGate=Semaphore(3) + coroutineScope { + missing.map{entry->async { + requestGate.withPermit { + val hint=categoryArtworkHint(selectedSection,entry.second) + val results=try { + api.library(sectionId,sort="titleSort:asc",genre=entry.first,size=if(hint!=null)80 else 12,type=plexLibraryType(sectionType)).items + }catch(e:CancellationException){throw e}catch(_:Exception){emptyList()} + val matching=results.filter{it.type==sectionType} + val sample=matching.firstOrNull{hint!=null&&it.title.contains(hint,ignoreCase=true)&&it.artworkPath().isNotBlank()} + ?:matching.firstOrNull{it.artworkPath().isNotBlank()} + if(sample!=null&&generation==categoryArtworkGeneration&&categoryArtworkSectionId==sectionId&§ion?.id==sectionId) + categoryArtwork=categoryArtwork+(entry.first to sample) + } + }}.awaitAll() + } + } + } fun selectCategory(value:String){if(value.isBlank())return;categories=true;allTitles=true;genre=value;sort="titleSort:asc";focusId="category-grid";libraryJumpIndex=-1;libraryJumpLetter=null;refreshLibrary()} fun filter(sortValue: String=sort,genreValue: String=genre,unwatchedValue: Boolean=unwatched){sort=sortValue;genre=genreValue;unwatched=unwatchedValue;libraryJumpIndex=-1;libraryJumpLetter=null;refreshLibrary()} private fun refreshLibrary() { @@ -450,7 +501,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { } } fun onLibraryGridFocused(){libraryJumpIndex=-1} - 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 search(text: String){query=text;searchJob?.cancel();if(text.isBlank()){searchResults=SearchResults();busy=false;return};searchJob=viewModelScope.launch {delay(350);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 diff --git a/app/src/main/java/tv/kaleido/app/MainActivity.kt b/app/src/main/java/tv/kaleido/app/MainActivity.kt index 9b32dff..5e9f375 100644 --- a/app/src/main/java/tv/kaleido/app/MainActivity.kt +++ b/app/src/main/java/tv/kaleido/app/MainActivity.kt @@ -49,14 +49,14 @@ class MainActivity: ComponentActivity() { 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. */ + /** Open the native text field; voice input belongs to the Android TV keyboard. */ 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} + if(keyCode==android.view.KeyEvent.KEYCODE_SEARCH&&model.session!=null&&model.playing==null){if(event.repeatCount==0)model.openSearch();return true} return super.onKeyDown(keyCode,event) } override fun onSearchRequested(): Boolean { if(model.session==null||model.playing!=null)return false - model.requestVoiceSearch();return true + model.openSearch();return true } private fun debugPlayback(intent: Intent) {if(BuildConfig.DEBUG){ intent.getStringExtra("testFixture")?.let{model.debugPlayFixture(it);return} diff --git a/app/src/main/java/tv/kaleido/app/PlayerControls.kt b/app/src/main/java/tv/kaleido/app/PlayerControls.kt index aa5dee5..86a499f 100644 --- a/app/src/main/java/tv/kaleido/app/PlayerControls.kt +++ b/app/src/main/java/tv/kaleido/app/PlayerControls.kt @@ -5,6 +5,8 @@ import androidx.activity.compose.LocalActivity import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut +import androidx.compose.animation.scaleIn +import androidx.compose.animation.scaleOut import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutVertically import androidx.compose.animation.core.tween @@ -30,6 +32,7 @@ import androidx.compose.ui.focus.* import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.input.key.* import androidx.compose.ui.platform.LocalDensity @@ -64,6 +67,18 @@ import kotlinx.coroutines.delay // Set once the timeline takes focus for this reveal, so Play's initial focus can't take it back. var timelineReveal by remember{mutableStateOf(false)} var restoreMenuFocus by remember{mutableIntStateOf(0)} + var skipSeconds by remember(item.id){mutableIntStateOf(0)} + var skipPulse by remember(item.id){mutableIntStateOf(0)} + var skipForward by remember(item.id){mutableStateOf(true)} + LaunchedEffect(skipPulse){if(skipPulse>0){delay(1000);skipSeconds=0}} + fun quickSkip(delta:Long){ + val before=controller.scrubPosition ?: controller.position + controller.scrubBy(delta,settle=350) + val actual=((controller.scrubPosition ?: before)-before).toInt()/1000 + skipSeconds=if(skipSeconds*actual>0)skipSeconds+actual else actual + skipForward=delta>0 + skipPulse++ + } val rootFocus=remember{FocusRequester()} val timelineFocus=remember{FocusRequester()} val playFocus=remember{FocusRequester()} @@ -122,8 +137,8 @@ import kotlinx.coroutines.delay 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 { - // A tap skips without revealing anything; quick taps add up into one seek. - !visible&&event.nativeKeyEvent.repeatCount==0->{controller.scrubBy(delta,settle=350);true} + // Quick taps accumulate a seek and show a brief directional cue. + !visible&&event.nativeKeyEvent.repeatCount==0->{quickSkip(delta);true} // Holding reveals the timeline and keeps scrubbing until it takes focus. !visible||seekFocus->{controller.scrubBy(delta);controls=true;seekFocus=true;true} else->false @@ -144,6 +159,7 @@ import kotlinx.coroutines.delay setKeepContentOnPlayerReset(true) }},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)) + QuickSkipFeedback(skipSeconds,skipPulse,!visible&&!postPlay,Modifier.align(if(skipForward)Alignment.CenterEnd else Alignment.CenterStart).padding(horizontal=32.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) { @@ -193,6 +209,25 @@ import kotlinx.coroutines.delay } } +/** A short, non-focusable cue leaves the picture and remote focus undisturbed. */ +@Composable private fun QuickSkipFeedback(seconds:Int,pulse:Int,allowed:Boolean,modifier:Modifier) { + // Keep the final label while the cue fades out. + var last by remember{mutableIntStateOf(10)} + if(seconds!=0)last=seconds + AnimatedVisibility(visible=seconds!=0&&allowed,enter=fadeIn(tween(100))+scaleIn(tween(150),initialScale=.88f),exit=fadeOut(tween(180))+scaleOut(tween(180),targetScale=.96f),modifier=modifier) { + Column(Modifier.size(width=56.dp,height=64.dp).background(Brush.radialGradient(listOf(Color.Black.copy(alpha=.4f),Color.Transparent))) + .semantics(mergeDescendants=true){contentDescription=if(last<0)"Back ${-last} seconds"else "Forward $last seconds"},horizontalAlignment=Alignment.CenterHorizontally) { + Spacer(Modifier.height(9.dp)) + key(pulse){ + val opacity=remember{androidx.compose.animation.core.Animatable(.6f)} + LaunchedEffect(Unit){opacity.animateTo(1f,tween(180))} + Icon(if(last<0)Icons.Filled.FastRewind else Icons.Filled.FastForward,null,tint=Color.White,modifier=Modifier.size(22.dp).graphicsLayer{alpha=opacity.value}) + } + Text((if(last>0)"+"else "−")+kotlin.math.abs(last)+" s",color=Color.White,fontSize=12.sp,lineHeight=16.sp,fontWeight=FontWeight.Medium,style=LocalTextStyle.current.copy(shadow=androidx.compose.ui.graphics.Shadow(Color.Black,Offset(0f,1f),4f)),modifier=Modifier.padding(top=3.dp)) + } + } +} + /** 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) diff --git a/app/src/main/java/tv/kaleido/app/TitleDetails.kt b/app/src/main/java/tv/kaleido/app/TitleDetails.kt index f72e5f7..db01d96 100644 --- a/app/src/main/java/tv/kaleido/app/TitleDetails.kt +++ b/app/src/main/java/tv/kaleido/app/TitleDetails.kt @@ -82,10 +82,13 @@ import kotlinx.coroutines.launch LaunchedEffect(vm.playbackReturn){if(vm.playbackReturn!=seenReturn[0]){seenReturn[0]=vm.playbackReturn;if(vm.focusId.startsWith("children:${item.id}:"))return@LaunchedEffect;withFrameNanos{};list.scrollToItem(0);withFrameNanos{};runCatching{actionFocus.requestFocus()}}} Box(Modifier.fillMaxSize().background(Ink)) { val usesPosterHeader=item.type in listOf("show","movie") - if(usesPosterHeader) { + if(usesPosterHeader||episodic) { + // Season headers are shorter than 16:9: cropping into that box cut off heads. + // Frame TV artwork against the full page, with its top edge flush to movies. + val showArtwork=item.type=="show"||episodic BrowseBackdrop(vm.api,item.art.ifBlank{item.thumb},Modifier.fillMaxSize().graphicsLayer { alpha=if(list.firstVisibleItemIndex>0)0f else (1f-list.firstVisibleItemScrollOffset/backdropFadeDistance).coerceIn(0f,1f) - },cinematic=true) + },cinematic=true,alignment=if(showArtwork)Alignment.TopCenter else Alignment.Center,contentScale=if(showArtwork)ContentScale.FillWidth else ContentScale.Crop) // Keep the scene in the header; rows and captions sit on near-black. Read scroll // 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))) @@ -97,7 +100,7 @@ import kotlinx.coroutines.launch item(key="details-${item.id}") { // A fixed episode header, so moving along the season row never shifts the page. Box(Modifier.fillMaxWidth().then(if(usesPosterHeader)Modifier.heightIn(min=248.dp)else if(episodic)Modifier.height(322.dp)else Modifier.heightIn(min=286.dp))) { - if(!usesPosterHeader) { + if(!usesPosterHeader&&!episodic) { 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)))) diff --git a/distribution/Kaleido.apk b/distribution/Kaleido.apk index 84afadb..b9f58dc 100644 Binary files a/distribution/Kaleido.apk and b/distribution/Kaleido.apk differ diff --git a/distribution/Kaleido.apk.sha256 b/distribution/Kaleido.apk.sha256 index 88788d9..ad022fa 100644 --- a/distribution/Kaleido.apk.sha256 +++ b/distribution/Kaleido.apk.sha256 @@ -1 +1 @@ -0270206e1a3cf1574f58cd8f5f8bcef828277012bf2a56cf082a556656c6f3a1 Kaleido.apk +ed81fd04d09650c9ff43aae39d8638f5015048d608d10fd67e939124e8b1548e Kaleido.apk diff --git a/distribution/latest.json b/distribution/latest.json index 419011b..9acc770 100644 --- a/distribution/latest.json +++ b/distribution/latest.json @@ -1,7 +1,7 @@ { - "version": "0.3.1", - "versionCode": 16, - "url": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.3.1/distribution/Kaleido.apk", - "checksumUrl": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.3.1/distribution/Kaleido.apk.sha256", - "notes": "- Fix episode pages getting stuck on Resume after scrolling the season row away from the original episode, returning Home, and reopening it from Continue Watching." + "version": "0.4.0", + "versionCode": 17, + "url": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.4.0/distribution/Kaleido.apk", + "checksumUrl": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.4.0/distribution/Kaleido.apk.sha256", + "notes": "- Frame TV show, season and episode background artwork against the full page, preserving the top of the scene instead of cropping it into a short season header, with no gap above the artwork.\n- Redesign Movie and TV Categories with large artwork cards drawn from titles in each Plex genre, with clear remote focus and category return navigation.\n- Show a brief animated direction and seconds cue when tapping Left or Right during playback. Repeated taps accumulate and holding still opens the timeline.\n- Remove the broken in-app voice search button. Android TV keyboard voice input remains available. Add a Clear button that empties the query and results and returns focus to the search field." } diff --git a/docs/runtime-verification.md b/docs/runtime-verification.md index f0930d0..6ec3d74 100644 --- a/docs/runtime-verification.md +++ b/docs/runtime-verification.md @@ -4,6 +4,15 @@ For the 2026-10-26 codec/HDR sweep and its native-versus-converted playback find Target: the authorized onn at `192.168.50.195:5555`, package `tv.kaleido.app`. Other applications and the launcher were not modified. Screenshots, traces, UI dumps and server-specific logs stay in ignored `evidence/private/`. +## 2026-10-28 artwork, category cards, quick skips and search (0.4.0) + +- Started from the latest published 0.3.1 history, retaining its episode-row reentry fix and regression script. +- Reproduced the Hazbin Hotel season artwork cutting off the character's head. Season/episode artwork now uses the full-page background rather than a cropped 322 dp header. A temporary top inset was removed after visual review: TV art fills the top edge like movies. Compared final signed-release screenshots of the show, season and 2 Fast 2 Furious; retained episode selection and season Back focus. +- Movie and TV category cards display real Plex artwork from matching genres. Both pages passed horizontal/vertical navigation, scoped-category entry and selected-card restoration on Back; TV navigation also traversed six lower rows. Screenshots include The Batman for movie Action and Hazbin Hotel for TV Animation. +- Verified actual hidden-controls skips of +10 s, -10 s and repeated +20 s on real playback. The final compact cue sits near either edge, with a centered arrow above its time, a short fade and no bordered panel. Screenshots cover both directions and accumulation; normal controls/timeline still work. Debug validation suppressed timeline/scrobble writes, and the harness confirmed the Plex fixture's progress and watched state stayed unchanged. +- Verified Clear empties the query/results and returns typing focus for a new search. The Android TV keyboard must be closed before D-pad navigation to app controls. The in-app microphone is absent; final signed-release empty Search has neither "Your collection" nor "Find something worth watching." +- `scripts/verify_040.py` contains focused feature checks. Debug/release builds and lint passed; the broad device suites were not run. Restored the signed release, installed its ART profile, compiled only Kaleido with `speed-profile`, and returned to Home. + ## 2026-10-27 categories, search, themes and volume boost (0.3.0) - Removed repeated Settings category headings. Exact normalized title matches now lead search rows instead of fixed Movies-first ordering; own-title matches outrank inherited episode/show names. The Silo case was reproduced by a failing grouping regression and verified against the live server and remote UI. diff --git a/scripts/verify_040.py b/scripts/verify_040.py new file mode 100644 index 0000000..067db0e --- /dev/null +++ b/scripts/verify_040.py @@ -0,0 +1,119 @@ +"""Only 0.4.0 UI changes: TV artwork, category cards, Clear, and quick skip cues.""" +import argparse, json, time, urllib.parse, urllib.request +from contextlib import contextmanager +from device import ROOT, adb, screenshot +from verify_ui import launch, key, focused, wait, focus, labels, snapshot, text, passed, position + + +def search_title(query, expected): + launch(); key(22, 3); focused('Search'); key(23) + focused('Movies, shows, episodes, people') + adb('shell', 'input', 'text', query) + wait(lambda r: expected in labels(r), 'Search fixture '+expected) + key(66); focused(expected) + + +def search_check(): + search_title('hazbin', 'Hazbin Hotel') + key(23); text('Seasons'); key(4); focused('Hazbin Hotel') + # Return to the field, then Right at the end reaches Clear. + key(19) + wait(lambda r: focus(r)=='hazbin', 'Search field above results') + key(4) # Close the Android TV keyboard before navigating app buttons. + key(22); focused('Clear'); screenshot('040-search-clear') + key(23) + root=wait(lambda r:'Movies, shows, episodes, people' in labels(r), 'Clear resets results') + assert 'Hazbin Hotel' not in labels(root) + assert 'Your collection' not in labels(root) and 'Find something worth watching.' not in labels(root) + assert all('Voice search' not in n.get('content-desc','') for n in root.iter('node')) + assert not any(n.get('text')=='Clear' for n in root.iter('node')) + adb('shell', 'input', 'text', 'silo'); text('TV shows'); key(66); focused('Silo') + screenshot('040-search-new-query') + passed('Clear removes query/results, restores typing, and microphone is absent') + + +def details_check(): + search_title('hazbin', 'Hazbin Hotel'); key(23); text('Seasons') + screenshot('040-show-artwork') + # Initial show entry may have its first season focused already. + if 'Season 1' not in focus(snapshot()):key(20) + focused('Season 1'); key(23) + wait(lambda r:'Hazbin Hotel' in labels(r) and 'Season 1' in labels(r), 'Season details') + screenshot('040-season-artwork') + root=snapshot() + assert any(n.get('content-desc')=='Back' for n in root.iter('node')) + # Moving across episode cards retains the fixed header and useful focus. + if not any(x in focus(root) for x in ['Dad Beat Dad','Hello Rosie','Overture']):key(20) + before=focus(snapshot()); key(22); after=focus(snapshot()) + assert before!=after and after, 'Episode selection must move' + screenshot('040-season-next-episode') + key(4); focused('Season 1') + passed('Hazbin show/season art captured; episode movement and Back focus preserved') + + +def categories_check(): + for moves, name in [(1, 'Movies'), (2, 'TV Shows')]: + launch(); key(22, moves); focused(name); key(20); focused('Discover') + key(22, 2); focused('Categories'); key(23) + wait(lambda r:focus(r) not in ('','Categories'), 'Category entry') + # Artwork metadata labels prove a matching Plex sample has loaded. + wait(lambda r:any(x in labels(r) for x in ['FILM','SERIES']), 'Artwork cards loaded') + time.sleep(2); screenshot('040-'+name.lower().replace(' ','-')+'-categories') + first=focus(snapshot()); key(22); second=focus(snapshot()) + assert first!=second + key(20); below=focus(snapshot()); assert below!=second + key(19); focused(second); key(21); focused(first) + key(23) + wait(lambda r:any('titles' in s for s in labels(r)), 'Scoped category results') + key(4); focused(first) + passed(name+' artwork cards: horizontal/vertical navigation, open and Back restoration') + + +@contextmanager +def preserve_movie_progress(): + cfg=dict(l.split('=',1) for l in (ROOT/'.env').read_text().splitlines() if '=' in l and not l.startswith('#')) + server=cfg['PLEX_SERVER_URL'].strip('"\'').rstrip('/') + headers={'X-Plex-Token':cfg['PLEX_TOKEN'].strip('"\''),'Accept':'application/json'} + def request(path, params=None): + url=server+path+('?' + urllib.parse.urlencode(params) if params else '') + with urllib.request.urlopen(urllib.request.Request(url,headers=headers),timeout=30) as response:return response.read() + original=json.loads(request('/library/metadata/9776'))['MediaContainer']['Metadata'][0] + try:yield + finally: + adb('shell','am','force-stop','tv.kaleido.app');time.sleep(.4) + # testValidation suppresses Plex timeline/scrobble writes. Verify that contract. + restored=json.loads(request('/library/metadata/9776'))['MediaContainer']['Metadata'][0] + assert restored.get('viewOffset',0)==original.get('viewOffset',0), 'Preserve fixture progress' + assert restored.get('viewCount',0)==original.get('viewCount',0), 'Preserve watched state' + + +def skip_check(): + with preserve_movie_progress():quick_skip_check() + + +def quick_skip_check(): + adb('shell','am','force-stop','tv.kaleido.app'); adb('logcat','-c') + adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','9776','--el','testOffset','90000','--ei','testMode','2','--ez','testValidation','true') + deadline=time.monotonic()+45 + while 'READY item=9776' not in adb('logcat','-d','-s','KaleidoPlayback:I').decode(errors='replace'): + assert time.monotonic()<deadline, 'Playback ready'; time.sleep(.5) + key(127); focused('Play'); key(4); time.sleep(.4) + before=position() + adb('shell','input','keyevent','22'); time.sleep(.16); screenshot('040-skip-forward') + time.sleep(1.3); after=position() + assert 8500<=after-before<=11500, (before,after) + adb('shell','input','keyevent','21'); time.sleep(.16); screenshot('040-skip-back') + time.sleep(1.3); back=position(); assert abs(back-before)<1600, (before,back) + adb('shell','input','keyevent','22'); adb('shell','input','keyevent','22') + time.sleep(.12); screenshot('040-skip-repeated'); time.sleep(1.4) + assert 18500<=position()-back<=21500, 'Repeated taps must accumulate' + root=snapshot(); assert '2 Fast 2 Furious' not in labels(root), 'Cue must leave controls hidden' + key(23); focused('Play'); key(19); focused('Playback timeline') + key(22); key(20); focused('Play') + key(4); key(4) + passed('Actual +/-10s and repeated +20s seeks; cue screenshots; timeout and timeline coexist') + + +if __name__=='__main__': + parser=argparse.ArgumentParser();parser.add_argument('check',choices=['search','details','categories','skip']) + globals()[parser.parse_args().check+'_check']() diff --git a/version.properties b/version.properties index 48722fc..daf6acf 100644 --- a/version.properties +++ b/version.properties @@ -1,2 +1,2 @@ -versionName=0.3.1 -versionCode=16 +versionName=0.4.0 +versionCode=17