diff --git a/AGENTS.md b/AGENTS.md index 69eb215..e0e974d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -57,6 +57,8 @@ Use `& $KaleidoPython` before the Python commands below. Run only checks relevan | `scripts/verify_details_layout.py` | Fresh TV show header bounds and Seasons before Cast; debug or release | | `scripts/verify_movie_details.py` | Movie safe header, related movies and Back focus restoration; debug or release | | `scripts/verify_settings.py` | Category navigation, preference-dialog cancellation and live update check; expects Original quality / 80% test preferences | +| `scripts/verify_library_jump.py` | Scoped Movie/TV categories, A–Z jumps beyond the first page, details/Back focus and exact Silo search | +| `scripts/verify_audio_preferences.py` | Theme/boost persistence and actual boosted playback; **debug**; restores prior audio preferences | Live Android integration tests (currently six) cover secure persistence, library APIs, episodes, PIN, preview JPEGs/new seasons and supported HEVC remux negotiation: @@ -81,6 +83,7 @@ These require the private test session. Playback test intents (`testTitleId`, `t - Playback has one quality preference (`StreamQuality`): **Original quality** (the default) tries the original file, then Plex HLS, then a 1080p conversion if needed; 4K/1080p/720p/480p ask Plex to convert. A nonempty audio-only track list for a declared video must trigger fallback. Earlier preferences migrate on first read. Debug `testMode` still forces a delivery mode. Augment Plex's existing HEVC target; competing targets previously forced unnecessary conversion. A server copy decision does not prove rendering. Preserve the selected Plex tracks and check actual delivered formats. - **ADB screenshots can omit HEVC video on this onn while the actual TV displays it. The user confirmed this.** Do not force transcoding based solely on a blank capture. `scripts/check_video.py` has a pixel assertion that can falsely fail for this reason; use playback logs/rendered-frame evidence and physical TV confirmation as appropriate. Never infer universal HDR/codec support from one test. - Preview thumbnails and intro/credit markers depend on server-generated data. Do not fabricate them. +- Theme tracks come from Plex metadata and inherit from the show for seasons/episodes. Stop music on video playback/background. Volume boost processes decoded PCM; Off must preserve passthrough and the normal audio path. ### Performance testing @@ -96,6 +99,8 @@ The harness requires horizontal Y drift ≤3 px and frame-time p95 <40 ms. On 20 ## Releases and further detail +Use Semantic Versioning (`major.minor.patch`) for release names. + Updates come from `https://git.elijahkuntz.com/Elijah/Kaleido`. Keep the private `.tools/kaleido-signing.jks`; replacing it breaks in-place updates. `version.properties` is the version source. Before a requested release, increment version name/code, update `CHANGELOG.md`, build/test, and use `scripts/package_release.py`; the Forgejo workflow publishes matching version tags. Do not claim publication or updater installation was tested without verifying it. See `docs/design-system.md` for the visual system and `docs/runtime-verification.md` for device evidence and limitations. Keep this file concise; put detailed investigation history there. diff --git a/CHANGELOG.md b/CHANGELOG.md index 6236a1d..2270307 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Kaleido releases +## 0.3.0 + +- Add Categories alongside Discover and Library in Movies and TV Shows. Browse the genres from the selected Plex library, with movies and shows kept separate. +- Add a light grey A–Z jump bar on the right of libraries and category results. Jump to letters with the remote, including titles beyond the first loaded page, and press Left to enter the titles. +- Put exact title matches first in Search, including the Silo series ahead of unrelated movie matches. Order result rows by relevance instead of always placing movies first. +- Add optional Plex theme music on movie, series, season and episode pages, with a separate volume setting. Music stops for playback and when Kaleido leaves the foreground; titles without theme tracks stay silent. +- Add an optional app-wide volume boost from +3 to +12 dB for all video playback. Boost uses decoded audio instead of compressed passthrough; Off preserves the original audio path. +- Remove repeated category headings in Settings and restore focus to preference controls after closing their dialogs. + ## 0.2.1 - Season and episode pages are one horizontal layout again. Moving along the season row shows that episode at the top, and selecting it or Play plays it, instead of opening another page with the same information. Back from playback returns to the episode you played. diff --git a/app/src/androidTest/java/tv/kaleido/app/BrowseAudioIntegrationTest.kt b/app/src/androidTest/java/tv/kaleido/app/BrowseAudioIntegrationTest.kt new file mode 100644 index 0000000..778dee2 --- /dev/null +++ b/app/src/androidTest/java/tv/kaleido/app/BrowseAudioIntegrationTest.kt @@ -0,0 +1,62 @@ +package tv.kaleido.app + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import kotlinx.coroutines.runBlocking +import org.json.JSONObject +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith + +/** Read-only checks against the private server, including the same filters used by category jumps. */ +@RunWith(AndroidJUnit4::class) +class BrowseAudioIntegrationTest { + private val app get()=InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as KaleidoApplication + private val api get()=app.api.apply { session=app.secure.load() } + + @Test fun exactShowRanksAheadOfMetadataMovieMatch()=runBlocking { + val results=api.search("Silo") + assertEquals("Silo",searchGroups(results.titles,"Silo").first().second.first().title) + assertEquals("show",searchGroups(results.titles,"Silo").first().second.first().type) + } + + @Test fun plexThemesAreInheritedAndPlayable()=runBlocking { + val show=api.details("6115") + val episode=api.details("7599") + assertTrue(show.theme.startsWith("/library/")) + assertEquals(show.theme,episode.theme) + val season=api.details(episode.parentId) + val inherited=season.theme.ifBlank { api.details(season.parentId).theme } + assertEquals(show.theme,inherited) + val request=okhttp3.Request.Builder().url(api.url(show.theme)).apply { + api.headers().filterKeys { it!="Accept" }.forEach { (k,v)->header(k,v) } + header("Range","bytes=0-1023") + }.build() + api.http.newCall(request).execute().use { response-> + assertTrue(response.isSuccessful) + assertTrue(response.body!!.source().readByteArray(32).isNotEmpty()) + } + val movie=Title.parse(JSONObject().put("type","movie").put("theme","/library/metadata/1/theme/2")) + assertEquals("/library/metadata/1/theme/2",movie.theme) + } + + @Test fun letterCountsRespectCategoriesAndMediaType()=runBlocking { + for(section in api.sections().filter { it.type in listOf("movie","show") }) { + val type=plexLibraryType(section.type) + val genres=api.genres(section.id) + val genre=genres.firstOrNull { it.second=="Animation" } ?: genres.first() + for(unwatched in listOf(false,true)) { + val page=api.library(section.id,genre=genre.first,unwatched=unwatched,type=type) + val characters=api.firstCharacters(section.id,genre.first,unwatched,type) + assertEquals(page.total,characters.sumOf { it.size }) + assertTrue(page.items.all { it.type==section.type }) + val offsets=libraryCharacterOffsets(characters) + assertTrue(offsets.values.all { it in 0 until page.total }) + val last=characters.lastOrNull { it.size>0 } ?: continue + val offset=offsets[last.title] ?: continue + val tail=api.library(section.id,start=offset,genre=genre.first,unwatched=unwatched,type=type) + assertEquals(last.size,tail.items.size) + } + } + } +} diff --git a/app/src/main/baseline-prof.txt b/app/src/main/baseline-prof.txt index fcc221c..b57d4cd 100644 --- a/app/src/main/baseline-prof.txt +++ b/app/src/main/baseline-prof.txt @@ -8,6 +8,7 @@ HPLtv/kaleido/app/NavigationSoundsKt**->**(**)** HPLtv/kaleido/app/NavigationSoundController;->**(**)** HPLtv/kaleido/app/TitleDetailsKt**->**(**)** HPLtv/kaleido/app/SettingsScreenKt**->**(**)** +HPLtv/kaleido/app/LibraryNavigationKt**->**(**)** HPLtv/kaleido/app/ScreensKt**->**(**)** HPLtv/kaleido/app/TitleActionsNode;->**(**)** HPLtv/kaleido/app/TitleActionsElement;->**(**)** diff --git a/app/src/main/java/tv/kaleido/app/BrowseScreens.kt b/app/src/main/java/tv/kaleido/app/BrowseScreens.kt index b4f2bb2..ee3962a 100644 --- a/app/src/main/java/tv/kaleido/app/BrowseScreens.kt +++ b/app/src/main/java/tv/kaleido/app/BrowseScreens.kt @@ -33,6 +33,7 @@ import androidx.compose.ui.text.style.TextOverflow 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 @@ -154,34 +155,87 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List,index:Int, var sortMenu by remember{mutableStateOf(false)} var genreMenu by remember{mutableStateOf(false)} var sectionMenu by remember{mutableStateOf(false)} - // Without explicit links, Right from Library searches upward and lands on (and opens) Home. - val libraryFocus=remember{FocusRequester()};val filterFocus=remember{FocusRequester()} + val discoverFocus=remember{FocusRequester()};val libraryFocus=remember{FocusRequester()};val categoriesFocus=remember{FocusRequester()} + val filterFocus=remember{FocusRequester()};val categoryEntryFocus=remember{FocusRequester()};val railFocus=remember{FocusRequester()};val sectionFocus=remember{FocusRequester()} val filters=vm.section!=null||vm.busy Column(Modifier.fillMaxSize()) { Row(Modifier.fillMaxWidth().height(64.dp).padding(horizontal=Cinema.gutter),verticalAlignment=Alignment.CenterVertically) { Text(name,color=Accent,fontSize=29.sp,lineHeight=34.sp,fontWeight=FontWeight.SemiBold,letterSpacing=(-.8).sp) Spacer(Modifier.width(21.dp)) - NavigationLabel("Discover",!vm.allTitles){vm.setAll(false)} - NavigationLabel("Library",vm.allTitles,modifier=Modifier.focusRequester(libraryFocus).focusProperties{right=if(filters)filterFocus else FocusRequester.Cancel},initialFocus=vm.focusId=="library-entry"){vm.setAll(true)} + NavigationLabel("Discover",!vm.allTitles,modifier=Modifier.focusRequester(discoverFocus).focusProperties{right=libraryFocus},onClick={vm.setAll(false)}) + NavigationLabel("Library",!vm.categories,modifier=Modifier.focusRequester(libraryFocus).focusProperties{right=categoriesFocus;down=if(filters)filterFocus else FocusRequester.Cancel},initialFocus=vm.focusId=="library-entry"){vm.setAll(true)} + NavigationLabel("Categories",vm.categories,modifier=Modifier.focusRequester(categoriesFocus).focusProperties{right=if(vm.sections.count{it.type==vm.section?.type}>1)sectionFocus else FocusRequester.Cancel;down=if(vm.categories&&vm.genre.isBlank())categoryEntryFocus else if(filters)filterFocus else FocusRequester.Cancel}){vm.openCategories()} Spacer(Modifier.weight(1f)) - if(vm.sections.count{it.type==vm.section?.type}>1)TvButton(vm.section?.title ?: "Library"){sectionMenu=true} - else if(!vm.allTitles)Text("${vm.total} titles",color=Muted,fontSize=11.sp,lineHeight=16.sp) + if(vm.sections.count{it.type==vm.section?.type}>1)TvButton(vm.section?.title ?: "Library",Modifier.focusRequester(sectionFocus).focusProperties{left=categoriesFocus}){sectionMenu=true} } - if(!filters)EmptyState("No $name library","This server has no matching library.") + if(vm.categories&&vm.genre.isBlank()) { + if(vm.section==null)EmptyState("No $name library","This server has no matching library.") + 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()) { + 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) + } + LaunchedEffect(vm.focusId,index){if((vm.focusId=="categories-entry"&&index==0)||vm.focusId=="category:${entry.first}"){withFrameNanos{};runCatching{requester.requestFocus()}}} + } + } + } + } else if(!filters)EmptyState("No $name library","This server has no matching library.") else { Row(Modifier.fillMaxWidth().height(43.dp).padding(horizontal=Cinema.gutter),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(8.dp)) { Text("${vm.total} titles",color=Muted,fontSize=11.sp,lineHeight=16.sp) Spacer(Modifier.weight(1f)) - TvButton((if(vm.genre.isBlank())"All genres"else vm.genres.firstOrNull{it.first==vm.genre}?.second ?: "Genre")+" ⌄",Modifier.focusRequester(filterFocus).focusProperties{left=libraryFocus}){genreMenu=true} + TvButton((if(vm.genre.isBlank())"All genres"else vm.genres.firstOrNull{it.first==vm.genre}?.second ?: "Genre")+" ⌄",Modifier.focusRequester(filterFocus).focusProperties{left=categoriesFocus}){genreMenu=true} TvButton(if(vm.unwatched)"Unwatched ✓"else "Unwatched",selected=vm.unwatched){vm.filter(unwatchedValue=!vm.unwatched)} TvButton((sortLabels.firstOrNull{it.first==vm.sort}?.second ?: "Title: A–Z")+" ⌄",Modifier.focusProperties{right=FocusRequester.Cancel}){sortMenu=true} } val grid=rememberLazyGridState() + val tileRequesters=remember{mutableMapOf<String,FocusRequester>()} + val scope=rememberCoroutineScope() + val enabledLetters=remember{LibraryJumpLetters.toSet()} LaunchedEffect(grid,vm.library.size,vm.total){snapshotFlow{grid.layoutInfo.visibleItemsInfo.lastOrNull()?.index ?: 0}.collect{if(it>=vm.library.size-18&&vm.library.isNotEmpty())vm.more()}} - LazyVerticalGrid(GridCells.Fixed(6),state=grid,contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=10.dp,bottom=30.dp),horizontalArrangement=Arrangement.spacedBy(13.dp),verticalArrangement=Arrangement.spacedBy(18.dp),modifier=Modifier.fillMaxSize()) { - itemsIndexed(vm.library,key={_,it->it.id}){index,item->MediaTile(vm,item,"library:${item.id}",fillWidth=true,onMove={anticipateTileMove(vm,vm.library,index,it,6)})} - if(vm.library.isEmpty()&&!vm.busy)item(span={GridItemSpan(6)}){EmptyState("No matching titles","Try another genre or watch filter.")} - if(vm.library.size<vm.total)item(span={GridItemSpan(6)}){TvButton(if(vm.busy)"Loading…"else "Load more titles"){vm.more()}} + LaunchedEffect(vm.libraryJumpRequest){ + val index=vm.libraryJumpIndex.takeIf{it>=0&&it<vm.library.size} ?: return@LaunchedEffect + grid.scrollToItem(index) + } + LaunchedEffect(vm.libraryFocusRequest){ + val itemId=vm.focusId.removePrefix("library:").takeIf{vm.focusId.startsWith("library:")} + val index=itemId?.let{id->vm.library.indexOfFirst{it.id==id}}?.takeIf{it>=0} + ?: if(vm.focusId=="category-grid"&&!vm.busy&&vm.library.isNotEmpty())0 else -1 + if(index>=0){ + grid.scrollToItem(index) + snapshotFlow{grid.layoutInfo.visibleItemsInfo.any{it.index==index}}.first{it} + withFrameNanos{} + tileRequesters[vm.library[index].id]?.requestFocus() + } + } + suspend fun returnFocusToGrid(){ + val itemId=vm.focusId.removePrefix("library:").takeIf{vm.focusId.startsWith("library:")} + val index=vm.libraryJumpIndex.takeIf{it>=0&&it<vm.library.size} + ?: itemId?.let{id->vm.library.indexOfFirst{it.id==id}}?.takeIf{it>=0} ?: 0 + if(vm.library.isNotEmpty()){ + grid.scrollToItem(index) + snapshotFlow{grid.layoutInfo.visibleItemsInfo.any{it.index==index}}.first{it} + withFrameNanos{} + tileRequesters[vm.library[index].id]?.requestFocus() + } + } + Row(Modifier.fillMaxWidth().weight(1f),horizontalArrangement=Arrangement.spacedBy(7.dp),verticalAlignment=Alignment.Top) { + LazyVerticalGrid(GridCells.Fixed(6),state=grid,contentPadding=PaddingValues(start=Cinema.gutter,end=5.dp,top=10.dp,bottom=30.dp),horizontalArrangement=Arrangement.spacedBy(13.dp),verticalArrangement=Arrangement.spacedBy(18.dp),modifier=Modifier.weight(1f)) { + itemsIndexed(vm.library,key={_,it->it.id}){index,item-> + val requester=tileRequesters.getOrPut(item.id){FocusRequester()} + val lastColumn=index%6==5||index==vm.library.lastIndex + MediaTile(vm,item,"library:${item.id}",fillWidth=true,modifier=Modifier.focusRequester(requester).then(if(lastColumn)Modifier.focusProperties{right=railFocus}else Modifier),onMove={anticipateTileMove(vm,vm.library,index,it,6)},onFocused={vm.onLibraryGridFocused()}) + } + if(vm.library.isEmpty()&&!vm.busy)item(span={GridItemSpan(6)}){EmptyState("No matching titles","Try another genre or watch filter.")} + if(vm.library.size<vm.total)item(span={GridItemSpan(6)}){TvButton(if(vm.busy)"Loading…"else "Load more titles"){vm.more()}} + } + LibraryJumpRail(enabledLetters,vm.libraryJumpLetter,railFocus,{scope.launch{runCatching{ returnFocusToGrid() }}},{vm.jumpToLibraryLetter(it)}) } } } @@ -213,7 +267,7 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int, 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 groups=remember(vm.searchResults,vm.query){searchGroups(vm.searchResults.titles,vm.query)} val people=vm.searchResults.people val hasResults=groups.isNotEmpty()||people.isNotEmpty() fun enterResults(){keyboard?.hide();runCatching{resultsFocus.requestFocus()}} @@ -246,9 +300,9 @@ internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int, } } -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()} +internal fun searchGroups(titles:List<Title>,query:String=""):List<Pair<String,List<Title>>> = rankSearchGroups( + titles,query,Title::type +){title->listOf(title.title,title.parentTitle,title.grandparentTitle)} @Composable private fun PeopleRow(vm:KaleidoViewModel,people:List<CastMember>,entryFocus:FocusRequester?) { Column { diff --git a/app/src/main/java/tv/kaleido/app/CompatibleAudioSink.kt b/app/src/main/java/tv/kaleido/app/CompatibleAudioSink.kt index 51a537a..93be599 100644 --- a/app/src/main/java/tv/kaleido/app/CompatibleAudioSink.kt +++ b/app/src/main/java/tv/kaleido/app/CompatibleAudioSink.kt @@ -9,7 +9,13 @@ import androidx.media3.exoplayer.audio.ForwardingAudioSink /** Android rejects a center-only PCM mask; one-channel audio uses its standard mono output. */ @androidx.annotation.OptIn(UnstableApi::class) -internal class CompatibleAudioSink(sink:AudioSink):ForwardingAudioSink(sink) { +internal class CompatibleAudioSink(sink:AudioSink,private val decodedOnly:Boolean=false):ForwardingAudioSink(sink) { + override fun supportsFormat(format:Format):Boolean = + if(decodedOnly&&format.sampleMimeType!=MimeTypes.AUDIO_RAW)false else super.supportsFormat(format) + override fun getFormatSupport(format:Format):Int = + if(decodedOnly&&format.sampleMimeType!=MimeTypes.AUDIO_RAW)AudioSink.SINK_FORMAT_UNSUPPORTED else super.getFormatSupport(format) + override fun getFormatOffloadSupport(format:Format):androidx.media3.exoplayer.audio.AudioOffloadSupport = + if(decodedOnly)androidx.media3.exoplayer.audio.AudioOffloadSupport.DEFAULT_UNSUPPORTED else super.getFormatOffloadSupport(format) @Suppress("DEPRECATION") override fun configure(config:AudioSink.AudioSinkConfig) { val format=compatiblePcmFormat(config.format) diff --git a/app/src/main/java/tv/kaleido/app/FocusedBrowse.kt b/app/src/main/java/tv/kaleido/app/FocusedBrowse.kt index 7d94b5e..4466745 100644 --- a/app/src/main/java/tv/kaleido/app/FocusedBrowse.kt +++ b/app/src/main/java/tv/kaleido/app/FocusedBrowse.kt @@ -240,7 +240,7 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) { } var sectionMenu by remember{mutableStateOf(false)} val sectionChoices=vm.sections.filter{it.type==vm.section?.type} - val sectionFocus=remember{FocusRequester()} + val sectionFocus=remember{FocusRequester()};val categoriesFocus=remember{FocusRequester()} val title=when(destination){"movies"->"Movies";"tv"->"TV Shows";else->"Home"} BoxWithConstraints(Modifier.fillMaxSize()) { val heroHeight=maxHeight*.80f-62.dp @@ -257,8 +257,12 @@ private suspend fun LazyListState.animateBrowseTo(index:Int) { navigationJob[0]?.cancel();navigationJob[0]=scope.launch{hubs.firstOrNull()?.let{hub->hub.items.firstOrNull()?.let{moveToRow(hub.id,it.id)}}};true }else false },initialFocus=sectionEntry){} - // 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=if(sectionChoices.size>1)sectionFocus else FocusRequester.Cancel}){vm.setAll(true)} + NavigationLabel("Library",false,modifier=Modifier.focusProperties{up=navigation.top;down=navigation.entry;right=categoriesFocus}){vm.setAll(true)} + NavigationLabel("Categories",false,modifier=Modifier.focusRequester(categoriesFocus).focusProperties{up=navigation.top;down=navigation.entry;right=if(sectionChoices.size>1)sectionFocus else FocusRequester.Cancel}.onPreviewKeyEvent{ + 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 + }){vm.openCategories()} 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{ diff --git a/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt b/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt index c8e915a..2be7d2a 100644 --- a/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt +++ b/app/src/main/java/tv/kaleido/app/KaleidoViewModel.kt @@ -48,6 +48,11 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { var genre by mutableStateOf(""); private set var unwatched by mutableStateOf(false); private set var allTitles by mutableStateOf(false); private set + var categories by mutableStateOf(false); private set + var libraryJumpIndex by mutableIntStateOf(-1); private set + var libraryJumpRequest by mutableIntStateOf(0); private set + var libraryFocusRequest by mutableIntStateOf(0); private set + var libraryJumpLetter by mutableStateOf<String?>(null); private set var detail by mutableStateOf<Title?>(null); private set var children by mutableStateOf(emptyList<Title>()); private set var detailRelated by mutableStateOf(emptyList<Title>()); private set @@ -96,6 +101,9 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { var debugValidationFile:File?=null; private set var watchedPercent by mutableStateOf(preferences.getInt("watchedPercent",80).coerceIn(50,100)); private set var navigationSounds by mutableStateOf(preferences.getBoolean("navigationSounds",true)); private set + var themeMusic by mutableStateOf(preferences.getBoolean("themeMusic",false)); private set + var themeVolume by mutableIntStateOf(preferences.getInt("themeVolume",30).coerceIn(10,100)); private set + var volumeBoostDb by mutableIntStateOf(preferences.getInt("volumeBoostDb",0).coerceIn(0,12)); private set var episodeQueue by mutableStateOf(emptyList<Title>());private set var relatedShows by mutableStateOf(emptyList<Title>());private set var transitioningEpisode by mutableStateOf(false);private set @@ -110,6 +118,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { private var searchJob: Job? = null private val detailsCache = mutableMapOf<String,Title>() private val sectionCache=mutableMapOf<String,SectionContent>() + private val characterOffsetCache=mutableMapOf<LibraryCharacterQuery,Map<String,Int>>() private var sectionStale=false private val featureSeed=kotlin.random.Random.nextInt() private val previews=PreviewMetadata(viewModelScope){api.details(it.id)} @@ -203,7 +212,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { private suspend fun syncLibrary():Boolean { val expectedSession=session ?: return false val expectedPage=page;val generation=loadGeneration - val expectedSection=section;val expectedSort=sort;val expectedGenre=genre;val expectedUnwatched=unwatched + val expectedSection=section;val expectedSort=sort;val expectedGenre=genre;val expectedUnwatched=unwatched;val expectedCategories=categories;val expectedAllTitles=allTitles val freshSections=api.sections() val freshHome=fetchHome(freshSections) val sectionPage=expectedPage.kind in listOf("movies","tv") @@ -215,7 +224,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { // Preserve the loaded range and selected filters, instead of resetting the A-Z grid. val freshSection=active?.let{s-> val raw=api.hubs(s.id);val newGenres=api.genres(s.id) - val p=api.library(s.id,sort=expectedSort,genre=expectedGenre,unwatched=expectedUnwatched,size=library.size.coerceAtLeast(100)) + val p=api.library(s.id,sort=expectedSort,genre=expectedGenre,unwatched=expectedUnwatched,size=library.size.coerceAtLeast(100),type=plexLibraryType(s.type)) val seasons=if(s.type=="show")api.recentSeasons(s.id)else emptyList() val rows=(if(raw.isEmpty()&&p.items.isNotEmpty())listOf(Hub("library-${s.id}","From your library",p.items.take(18)))else raw)+ if(seasons.isNotEmpty())listOf(Hub("tv.newseasons.${s.id}","New seasons",seasons))else emptyList() @@ -225,10 +234,10 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { val freshChildren=detailSnapshot?.let{api.children(it.id)} // All loads above are staged. A tab/filter/session change must win over this snapshot. if(!foreground||session!=expectedSession||page!=expectedPage||generation!=loadGeneration|| - section!=expectedSection||sort!=expectedSort||genre!=expectedGenre||unwatched!=expectedUnwatched|| + section!=expectedSection||sort!=expectedSort||genre!=expectedGenre||unwatched!=expectedUnwatched||categories!=expectedCategories||allTitles!=expectedAllTitles|| playing!=null||busy||markingId!=null)return false sections=freshSections;homeHubs=freshHome.hubs;homeFeatures=freshHome.features - sectionCache.clear();detailsCache.clear();previews.clear() + sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear() sectionStale=freshSection==null if(freshSection!=null){section=active;discoverHubs=freshSection.hubs;genres=freshSection.genres;library=freshSection.library.items;total=freshSection.library.total} else if(sectionPage){section=null;discoverHubs=emptyList();genres=emptyList();library=emptyList();total=0} @@ -266,23 +275,23 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { fun beginAccountLink(){linkingAccount=true;linkAccount()} fun cancelAccountLink(){authJob?.cancel();pin=null;servers=emptyList();accountToken=session?.accountToken.orEmpty();linkingAccount=false} fun chooseServer(server: Server) = launchLoad { - sectionCache.clear();detailsCache.clear();previews.clear();cancelAnticipation() + sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation() val s=api.connect(server,accountToken); application.secure.save(s);api.session=s;session=s;servers=emptyList();linkingAccount=false;pages=listOf(Page());sections=api.sections();homeHubs=loadHome() } fun manualConnect(address: String, token: String) = launchLoad { - sectionCache.clear();detailsCache.clear();previews.clear();cancelAnticipation() + sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation() require(address.startsWith("https://")||address.startsWith("http://")){"Enter a complete http:// or https:// server address."} require(token.isNotBlank()){ "Enter an access token." } val s=api.validate(Session("",token.trim(),address.trim().trimEnd('/'),"Plex","")) authJob?.cancel();application.secure.save(s);api.session=s;session=s;linkingAccount=false;pages=listOf(Page());sections=api.sections();homeHubs=loadHome() } - fun signOut(){loadJob?.cancel();initializeJob?.cancel();application.secure.clear();api.session=null;session=null;homeHubs=emptyList();discoverHubs=emptyList();sections=emptyList();library=emptyList();sectionCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();pages=listOf(Page());servers=emptyList();accountToken="";linkAccount()} + fun signOut(){loadJob?.cancel();initializeJob?.cancel();application.secure.clear();api.session=null;session=null;homeHubs=emptyList();discoverHubs=emptyList();sections=emptyList();library=emptyList();sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation();pages=listOf(Page());servers=emptyList();accountToken="";linkAccount()} fun switchServer()=launchLoad { require(accountToken.isNotBlank()){ "This connection uses a server token. Sign out to link a Plex account." };servers=api.servers(accountToken) } fun tab(kind: String){ if(pages.size==1&&page.kind==kind)return // 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) + cancelAnticipation();loadJob?.cancel();busy=false;focusId="";if(kind in listOf("movies","tv")){allTitles=false;categories=false;genre="";libraryJumpIndex=-1;libraryJumpLetter=null};pages=listOf(Page(kind));loadPage(true) } fun open(item: Title){detailsCache[item.id]=item;episodeSelections.remove(item.id);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. */ @@ -297,7 +306,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { fun dismissActions(){contextItem=null;contextFromContinue=false} fun removeFromContinueWatching(item:Title){ viewModelScope.launch { - try{api.removeFromContinueWatching(item);homeHubs=loadHome();sectionCache.clear()} + try{api.removeFromContinueWatching(item);homeHubs=loadHome();sectionCache.clear();characterOffsetCache.clear()} catch(e:CancellationException){throw e}catch(e:Exception){fail(e.message ?: "Plex could not update Continue Watching."){removeFromContinueWatching(item)}} } } @@ -310,7 +319,20 @@ 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(pages.size>1){focusId=page.returnFocus;pages=pages.dropLast(1);if(pages.last().kind in listOf("movies","tv")&&focusId.startsWith("library:"))libraryFocusRequest++;loadPage();return true} + if(page.kind in listOf("movies","tv")&&allTitles){ + if(categories&&genre.isNotBlank()){ + val selected=genre + genre="" + focusId="category:$selected" + libraryJumpIndex=-1;libraryJumpLetter=null + refreshLibrary() + return true + } + if(categories){categories=false;allTitles=false;genre="";focusId="discovery-entry";libraryJumpIndex=-1;libraryJumpLetter=null;return true} + setAll(false) + return true + } if(page.kind in listOf("search","settings")){tab(previousTab);return true} if(page.kind!="home"){tab("home");return true} return false @@ -359,12 +381,13 @@ 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 + categories=false;libraryJumpIndex=-1;libraryJumpLetter=null 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 + discoverHubs=emptyList();library=emptyList();total=0;genres=emptyList() launchLoad({loadSection(s)}) {coroutineScope { - val g=async{api.genres(s.id)};val h=async{api.hubs(s.id)};val l=async{api.library(s.id)} + val g=async{api.genres(s.id)};val h=async{api.hubs(s.id)};val l=async{api.library(s.id,type=plexLibraryType(s.type))} val seasons:kotlinx.coroutines.Deferred<List<Title>>?=if(s.type=="show")async{runCatching{api.recentSeasons(s.id)}.getOrDefault(emptyList())}else null val raw=h.await();val genreList=g.await();val p=l.await();val newSeasons=seasons?.await().orEmpty() val rows=(if(raw.isEmpty()&&p.items.isNotEmpty())listOf(Hub("library-${s.id}","From your library",p.items.take(18)))else raw)+if(newSeasons.isNotEmpty())listOf(Hub("tv.newseasons.${s.id}","New seasons",newSeasons))else emptyList() @@ -374,13 +397,59 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { } fun chooseSection(s: Section){ if(s.id==section?.id)return + val keepCategories=categories preferences.edit().putString("section.${s.type}",s.id).apply() cancelAnticipation();focusId=if(allTitles)"library-entry"else "discovery-entry";loadSection(s) + if(keepCategories){allTitles=true;categories=true;focusId="categories-entry"} } - 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 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 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() { + val selectedSection=section ?: return + val requestedSort=sort;val requestedGenre=genre;val requestedUnwatched=unwatched + launchLoad { + val p=api.library(selectedSection.id,0,requestedSort,requestedGenre,requestedUnwatched,type=plexLibraryType(selectedSection.type)) + if(section?.id!=selectedSection.id||sort!=requestedSort||genre!=requestedGenre||unwatched!=requestedUnwatched)return@launchLoad + library=p.items;total=p.total + if(categories&&requestedGenre.isNotBlank()){ + focusId=p.items.firstOrNull()?.let{"library:${it.id}"} ?: "category-grid" + libraryFocusRequest++ + } + } + } + fun more(){ + if(busy||library.size>=total)return + val selectedSection=section ?: return;val start=library.size + val requestedSort=sort;val requestedGenre=genre;val requestedUnwatched=unwatched + launchLoad { + val p=api.library(selectedSection.id,start,requestedSort,requestedGenre,requestedUnwatched,type=plexLibraryType(selectedSection.type)) + if(section?.id!=selectedSection.id||sort!=requestedSort||genre!=requestedGenre||unwatched!=requestedUnwatched)return@launchLoad + library=(library+p.items).distinctBy{it.id};total=p.total + } + } + fun jumpToLibraryLetter(letter:String){ + if(busy||letter !in LibraryJumpLetters)return + val selectedSection=section ?: return + val requestedGenre=genre;val requestedUnwatched=unwatched;val requestedSort=sort;val requestedType=plexLibraryType(selectedSection.type) + val cacheKey=LibraryCharacterQuery(selectedSection.id,requestedGenre,requestedUnwatched,requestedType) + launchLoad({jumpToLibraryLetter(letter)}) { + val offsets=characterOffsetCache[cacheKey] ?: libraryCharacterOffsets(api.firstCharacters(selectedSection.id,requestedGenre,requestedUnwatched,requestedType)).also{characterOffsetCache[cacheKey]=it} + val offset=offsets[letter] ?: return@launchLoad + val loaded=if(requestedSort=="titleSort:asc"&&library.size>offset)null else api.library( + selectedSection.id,0,"titleSort:asc",requestedGenre,requestedUnwatched, + size=(offset+100).coerceAtLeast(100),type=requestedType, + ) + if(section?.id!=selectedSection.id||genre!=requestedGenre||unwatched!=requestedUnwatched)return@launchLoad + if(loaded!=null){library=loaded.items;total=loaded.total} + sort="titleSort:asc" + if(offset !in library.indices)return@launchLoad + focusId="library-rail" + libraryJumpIndex=offset;libraryJumpLetter=letter;libraryJumpRequest++ + } + } + 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 mark(item: Title) { if(markingId!=null)return @@ -393,7 +462,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { }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()}}} + fun refreshWatched(item:Title){viewModelScope.launch{try{refreshWatchedItems(item)}catch(e:CancellationException){throw e}catch(_:Exception){sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation()}}} private suspend fun refreshWatchedItems(item:Title) { val d=api.details(item.id) val updated=mutableMapOf(d.id to d) @@ -421,7 +490,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { 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() + sectionCache.clear();characterOffsetCache.clear() } fun play(item: Title,fromStart: Boolean=false):Unit=launchLoad({play(item,fromStart)}) { debugMode=null;debugValidation=false;debugValidationFile=null @@ -458,7 +527,7 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { } fun stopPlayback(){ val finished=playing - if(finished!=null)playbackReturn++;playing=null;sectionCache.clear();detailsCache.clear();previews.clear();cancelAnticipation() + if(finished!=null)playbackReturn++;playing=null;sectionCache.clear();characterOffsetCache.clear();detailsCache.clear();previews.clear();cancelAnticipation() // A season or episode page shows the last episode played, with fresh progress in its row. detail?.let{if(finished?.type=="episode"&&it.type in listOf("season","episode"))episodeSelections[it.id]=finished.id} launchLoad { @@ -484,6 +553,9 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) { 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 chooseThemeMusic(value:Boolean){themeMusic=value;preferences.edit().putBoolean("themeMusic",value).apply()} + fun chooseThemeVolume(value:Int){themeVolume=value.coerceIn(10,100);preferences.edit().putInt("themeVolume",themeVolume).apply()} + fun chooseVolumeBoostDb(value:Int){volumeBoostDb=value.coerceIn(0,12);preferences.edit().putInt("volumeBoostDb",volumeBoostDb).apply()} fun checkUpdate(manual: Boolean=true){viewModelScope.launch { if(downloading||!manual&&System.currentTimeMillis()-preferences.getLong("lastUpdateCheck",0)<6*3600_000L)return@launch updateStatus="Checking for updates…" diff --git a/app/src/main/java/tv/kaleido/app/LibraryNavigation.kt b/app/src/main/java/tv/kaleido/app/LibraryNavigation.kt new file mode 100644 index 0000000..4ce3a68 --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/LibraryNavigation.kt @@ -0,0 +1,134 @@ +package tv.kaleido.app + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusProperties +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.platform.LocalViewConfiguration +import androidx.compose.ui.platform.ViewConfiguration +import androidx.compose.ui.unit.DpSize +import androidx.compose.material3.Text + +internal data class PlexCharacterCount(val key: String, val title: String, val size: Int) +internal data class LibraryCharacterQuery(val section: String, val genre: String, val unwatched: Boolean, val type: String) + +internal fun libraryFilterParameters(genre: String, unwatched: Boolean, type: String): Map<String, String> = buildMap { + if (genre.isNotBlank()) put("genre", genre) + if (unwatched) put("unwatched", "1") + if (type.isNotBlank()) put("type", type) +} + +internal val LibraryJumpLetters = listOf("#") + ('A'..'Z').map(Char::toString) + +/** Plex returns one ordered Directory per initial; summing its sizes yields each absolute grid index. */ +internal fun libraryCharacterOffsets(characters: List<PlexCharacterCount>): Map<String, Int> { + val offsets = linkedMapOf<String, Int>() + var index = 0 + characters.forEach { character -> + val label = when { + character.key.equals("%23", ignoreCase = true) || character.key == "#" || character.title == "#" -> "#" + else -> character.title.firstOrNull()?.uppercaseChar()?.toString() + ?: character.key.firstOrNull()?.uppercaseChar()?.toString() + } + if (character.size > 0 && label != null && label in LibraryJumpLetters) offsets.putIfAbsent(label, index) + index += character.size.coerceAtLeast(0) + } + return offsets +} + +internal fun plexLibraryType(type: String): String = when (type) { + "movie" -> "1" + "show" -> "2" + else -> "" +} + +@Composable +@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class) +internal fun LibraryJumpRail( + enabledLetters: Set<String>, + selectedLetter: String?, + entryFocus: FocusRequester, + returnToGrid: () -> Unit, + onLetter: (String) -> Unit, +) { + // This remote-operated alphabet is denser than touch controls. Expanded touch targets + // overlap adjacent letters and hide their accessibility labels on Android TV. + val configuration=LocalViewConfiguration.current + val compactTargets=remember(configuration){object:ViewConfiguration by configuration { + override val minimumTouchTargetSize=DpSize.Zero + }} + CompositionLocalProvider(LocalViewConfiguration provides compactTargets) { + Column(modifier = Modifier.width(34.dp).height(350.dp)) { + LibraryJumpLetters.forEach { letter -> + var focused by remember { mutableStateOf(false) } + val active = letter in enabledLetters + val selected = letter == selectedLetter + Box( + Modifier + .weight(1f) + .width(34.dp) + .semantics { contentDescription = letter } + .then(if (letter == "#") Modifier.focusRequester(entryFocus) else Modifier) + .focusProperties { right = FocusRequester.Cancel } + .onPreviewKeyEvent { + if (it.type == KeyEventType.KeyDown && it.key == Key.DirectionLeft) { + returnToGrid() + true + } else false + } + .onFocusChanged { focused = it.isFocused } + .navigationSound() + .background( + when { + focused -> Accent + selected -> Color.White.copy(alpha = .14f) + else -> Color.Transparent + }, + RoundedCornerShape(3.dp), + ) + .clickable { if (active) onLetter(letter) }, + contentAlignment = Alignment.Center, + ) { + Text( + letter, + color = when { + focused -> Ink + selected -> Color(0xFFBBBBBB) + active -> Color(0xFF999999) + else -> Muted.copy(alpha = .46f) + }, + fontSize = 10.sp, + lineHeight = 12.sp, + fontWeight = if (focused || selected) FontWeight.SemiBold else FontWeight.Normal, + ) + } + } + } + } +} diff --git a/app/src/main/java/tv/kaleido/app/Models.kt b/app/src/main/java/tv/kaleido/app/Models.kt index 141f986..4248349 100644 --- a/app/src/main/java/tv/kaleido/app/Models.kt +++ b/app/src/main/java/tv/kaleido/app/Models.kt @@ -36,7 +36,8 @@ 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 subtype:String="",val extras:List<Title> = emptyList() + val castMembers:List<CastMember> = emptyList(),val subtype:String="",val extras:List<Title> = emptyList(), + val theme:String="" ) { val remainingEpisodes get() = (leafCount-viewedLeafCount).coerceAtLeast(0) val fullyWatched get() = isWatched() @@ -77,7 +78,8 @@ data class Title( 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.optString("subtype"),j.optJSONObject("Extras")?.optJSONArray("Metadata").objects().map(::parse) + j.optString("subtype"),j.optJSONObject("Extras")?.optJSONArray("Metadata").objects().map(::parse), + j.optString("theme").ifBlank{j.optString("parentTheme")}.ifBlank{j.optString("grandparentTheme")} ) 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")) } diff --git a/app/src/main/java/tv/kaleido/app/Playback.kt b/app/src/main/java/tv/kaleido/app/Playback.kt index 6b4b05c..5ce50c1 100644 --- a/app/src/main/java/tv/kaleido/app/Playback.kt +++ b/app/src/main/java/tv/kaleido/app/Playback.kt @@ -54,9 +54,10 @@ class PlaybackController(private val vm: KaleidoViewModel,val item: Title) { private val renderers=object:DefaultRenderersFactory(app) { override fun buildAudioSink(context:android.content.Context,enableFloatOutput:Boolean,enableAudioOutputPlaybackParams:Boolean):androidx.media3.exoplayer.audio.AudioSink = CompatibleAudioSink(androidx.media3.exoplayer.audio.DefaultAudioSink.Builder(context) - .setEnableFloatOutput(enableFloatOutput) + .setAudioProcessors(if(vm.volumeBoostDb>0)arrayOf(VolumeBoostProcessor(vm.volumeBoostDb){Log.i("KaleidoPlayback","BOOST processing PCM db=${vm.volumeBoostDb}")})else emptyArray()) + .setEnableFloatOutput(enableFloatOutput&&vm.volumeBoostDb==0) .setEnableAudioOutputPlaybackParameters(enableAudioOutputPlaybackParams) - .build()) + .build(),decodedOnly=vm.volumeBoostDb>0) }.setEnableDecoderFallback(true).forceDisableMediaCodecAsynchronousQueueing() val player=ExoPlayer.Builder(app,renderers).setTrackSelector(selector).setMediaSourceFactory(sourceFactory).build().apply { setAudioAttributes(AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MOVIE).build(),true) diff --git a/app/src/main/java/tv/kaleido/app/PlexApi.kt b/app/src/main/java/tv/kaleido/app/PlexApi.kt index 5504b5b..d3c4d19 100644 --- a/app/src/main/java/tv/kaleido/app/PlexApi.kt +++ b/app/src/main/java/tv/kaleido/app/PlexApi.kt @@ -75,13 +75,17 @@ class PlexApi(val clientId: String) { val seasons=container("/library/sections/$section/all",mapOf("type" to "3","sort" to "addedAt:desc","X-Plex-Container-Size" to "100")).optJSONArray("Metadata").objects().map(Title::parse) groupRecentSeasons(seasons,::details) } - suspend fun library(section: String, start: Int = 0, sort: String = "titleSort:asc", genre: String = "", unwatched: Boolean = false, size:Int=100): LibraryPage = withContext(Dispatchers.Default){ + suspend fun library(section: String, start: Int = 0, sort: String = "titleSort:asc", genre: String = "", unwatched: Boolean = false, size:Int=100, type:String=""): LibraryPage = withContext(Dispatchers.Default){ val p=mutableMapOf("X-Plex-Container-Start" to start.toString(),"X-Plex-Container-Size" to size.coerceAtLeast(1).toString(),"sort" to sort) - if(genre.isNotBlank())p["genre"]=genre - if(unwatched)p["unwatched"]="1" + p.putAll(libraryFilterParameters(genre,unwatched,type)) val d=container("/library/sections/$section/all",p) LibraryPage(d.optJSONArray("Metadata").objects().map(Title::parse),d.optInt("totalSize",d.optInt("size"))) } + internal suspend fun firstCharacters(section:String,genre:String="",unwatched:Boolean=false,type:String=""):List<PlexCharacterCount> = withContext(Dispatchers.Default){ + container("/library/sections/$section/firstCharacter",libraryFilterParameters(genre,unwatched,type)).optJSONArray("Directory").objects().map { + PlexCharacterCount(it.optString("key"),it.optString("title"),it.optInt("size")) + } + } suspend fun genres(section: String): List<Pair<String,String>> = container("/library/sections/$section/genre").optJSONArray("Directory").objects().map { it.optString("key") to it.optString("title") } suspend fun details(id: String): Title = withContext(Dispatchers.Default){container("/library/metadata/$id",mapOf("includeMarkers" to "1","includeChapters" to "1","includeExtras" to "1")).optJSONArray("Metadata").objects().firstOrNull()?.let(Title::parse) ?: throw PlexException("This title is unavailable.")} suspend fun relatedShows(id:String):List<Title> = withContext(Dispatchers.Default){container("/library/metadata/$id/related").optJSONArray("Hub").objects().flatMap{it.optJSONArray("Metadata").objects()}.map(Title::parse).filter{it.type=="show"}.distinctBy{it.id}} diff --git a/app/src/main/java/tv/kaleido/app/Screens.kt b/app/src/main/java/tv/kaleido/app/Screens.kt index b6bc6ad..53663f0 100644 --- a/app/src/main/java/tv/kaleido/app/Screens.kt +++ b/app/src/main/java/tv/kaleido/app/Screens.kt @@ -58,10 +58,11 @@ import java.io.File } @Composable fun KaleidoApp(vm: KaleidoViewModel,install: (File)->Unit) { KaleidoTheme { + ThemeMusic(vm) val stateHolder=rememberSaveableStateHolder() val discoveryFocus=remember{DiscoveryNavigation()} val immersive=vm.page.kind=="home"||(vm.page.kind in listOf("movies","tv")&&!vm.allTitles) - val screenKey=vm.page.kind+":"+vm.page.id+if(vm.page.kind in listOf("movies","tv")) ":${vm.allTitles}"else "" + val screenKey=vm.page.kind+":"+vm.page.id+if(vm.page.kind in listOf("movies","tv")) ":${vm.allTitles}:${vm.categories}:${vm.genre}"else "" val entrance=remember{Animatable(1f)} val density=LocalDensity.current var previousDestination by remember{mutableStateOf(vm.page.kind)} @@ -87,7 +88,7 @@ import java.io.File } } BackHandler(enabled=vm.linkingAccount||vm.playing!=null||vm.pages.size>1||vm.page.kind!="home"){ - if(vm.linkingAccount)vm.cancelAccountLink()else if(vm.playing==null&&vm.pages.size==1&&vm.page.kind in listOf("movies","tv")&&vm.allTitles)vm.setAll(false)else vm.back() + if(vm.linkingAccount)vm.cancelAccountLink()else vm.back() } NavigationSounds(vm.navigationSounds&&!startup) { Box(Modifier.fillMaxSize().background(Ink).onPreviewKeyEvent{startup}) { diff --git a/app/src/main/java/tv/kaleido/app/SearchRanking.kt b/app/src/main/java/tv/kaleido/app/SearchRanking.kt new file mode 100644 index 0000000..b14e4f5 --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/SearchRanking.kt @@ -0,0 +1,82 @@ +package tv.kaleido.app + +import java.text.Normalizer +import java.util.Locale + +private val searchGroupSpecs = listOf( + "movie" to "Movies", + "show" to "TV shows", + "season" to "Seasons", + "collection" to "Collections", + "episode" to "Episodes" +) + +private val combiningMarks = Regex("\\p{M}+") +private val nonLettersOrDigits = Regex("[^\\p{L}\\p{N}]+") +private val whitespace = Regex("\\s+") + +private data class RankedSearchResult<T>(val value: T, val index: Int, val score: Int) +private data class RankedSearchGroup<T>( + val label: String, + val results: List<T>, + val bestScore: Int, + val firstBestResult: Int +) + +internal fun <T> rankSearchGroups( + titles: List<T>, + query: String, + typeOf: (T) -> String, + searchableTitles: (T) -> List<String> +): List<Pair<String, List<T>>> { + val normalizedQuery = normalizeSearchText(query) + if (normalizedQuery.isBlank()) { + return searchGroupSpecs + .map { (type, label) -> label to titles.filter { typeOf(it) == type } } + .filter { it.second.isNotEmpty() } + } + + val ranked = titles.mapIndexed { index, title -> + RankedSearchResult(title, index, titleRelevance(normalizedQuery, searchableTitles(title))) + } + + return searchGroupSpecs.mapNotNull { (type, label) -> + val matching = ranked.filter { typeOf(it.value) == type } + if (matching.isEmpty()) return@mapNotNull null + + val bestScore = matching.maxOf { it.score } + val ordered = matching.sortedWith(compareByDescending<RankedSearchResult<T>> { it.score }.thenBy { it.index }) + RankedSearchGroup( + label = label, + results = ordered.map { it.value }, + bestScore = bestScore, + firstBestResult = matching.first { it.score == bestScore }.index + ) + } + .sortedWith(compareByDescending<RankedSearchGroup<T>> { it.bestScore }.thenBy { it.firstBestResult }) + .map { it.label to it.results } +} + +private fun titleRelevance(query: String, titles: List<String>): Int { + if (query.isBlank()) return 0 + val queryTokens = query.split(' ') + return titles.mapIndexedNotNull { index, title -> + val candidate = normalizeSearchText(title) + val matchScore = when { + candidate.isBlank() -> 0 + candidate == query -> 4 + candidate.startsWith(query) -> 3 + candidate.split(' ').windowed(queryTokens.size).any { it == queryTokens } -> 2 + candidate.contains(query) -> 1 + else -> 0 + } + if (matchScore == 0) null else matchScore * 10 - index + }.maxOrNull() ?: 0 +} + +private fun normalizeSearchText(value: String): String = Normalizer.normalize(value, Normalizer.Form.NFKD) + .replace(combiningMarks, "") + .lowercase(Locale.ROOT) + .replace(nonLettersOrDigits, " ") + .replace(whitespace, " ") + .trim() diff --git a/app/src/main/java/tv/kaleido/app/SettingsScreen.kt b/app/src/main/java/tv/kaleido/app/SettingsScreen.kt index 36b925f..187e4fd 100644 --- a/app/src/main/java/tv/kaleido/app/SettingsScreen.kt +++ b/app/src/main/java/tv/kaleido/app/SettingsScreen.kt @@ -46,11 +46,16 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { var autoplayDialog by remember { mutableStateOf(false) } var subtitleSizeDialog by remember { mutableStateOf(false) } var subtitleStyleDialog by remember { mutableStateOf(false) } + var themeVolumeDialog by remember { mutableStateOf(false) } + var volumeBoostDialog 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 themeMusicFocus = remember { FocusRequester() } + val themeVolumeFocus = remember { FocusRequester() } + val volumeBoostFocus = remember { FocusRequester() } val categoryFocus = remember { List(categories.size) { FocusRequester() } } val entryFocus = remember { List(categories.size) { FocusRequester() } } @@ -59,6 +64,7 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { val signOutActionFocus = remember { FocusRequester() } val updateFocus = remember { FocusRequester() } val updateDownloadFocus = remember { FocusRequester() } + var dialogRestoreFocus by remember { mutableStateOf<FocusRequester?>(null) } var settingsFocused by remember { mutableStateOf(false) } val paused = remember { booleanArrayOf(false) } @@ -67,6 +73,16 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { delay(140) runCatching { entryFocus[selectedCategory].requestFocus() } } + val anyDialogOpen = confirmSignOut || qualityDialog || watchedDialog || remoteDialog || autoplayDialog || + subtitleSizeDialog || subtitleStyleDialog || themeVolumeDialog || volumeBoostDialog + LaunchedEffect(anyDialogOpen, dialogRestoreFocus) { + if (!anyDialogOpen) { + dialogRestoreFocus?.let { requester -> + runCatching { requester.requestFocus() } + dialogRestoreFocus = null + } + } + } LifecycleResumeEffect(Unit) { if (paused[0]) { vm.installerReturned() @@ -99,7 +115,6 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { modifier = Modifier.padding(top = 3.dp) ) } - Eyebrow(categories[selectedCategory]) } Spacer(Modifier.height(25.dp)) @@ -135,7 +150,7 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { ) { when (selectedCategory) { 0 -> { - SettingsSectionTitle("Plex account", "Manage the server and account used by Kaleido.") + SettingsSectionDescription("Manage the server and account used by Kaleido.") Column(verticalArrangement = Arrangement.spacedBy(5.dp)) { Text( vm.session?.serverName.orEmpty().ifBlank { "Plex connection" }, @@ -187,20 +202,20 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { "Sign out", requester = signOutActionFocus, leftTarget = categoryFocus[0], - onClick = { confirmSignOut = true } + onClick = { dialogRestoreFocus = signOutActionFocus; confirmSignOut = true } ) } } 1 -> { - SettingsSectionTitle("Playback", "Choose how Plex delivers video and when a title counts as watched.") + SettingsSectionDescription("Choose how Plex delivers video and when a title counts as watched.") SettingsValueRow( title = "Playback quality", 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 } + onClick = { dialogRestoreFocus = entryFocus[1]; qualityDialog = true } ) SettingsValueRow( title = "Remote quality", @@ -208,7 +223,7 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { value = vm.remoteQuality.label, requester = remoteFocus, leftTarget = categoryFocus[1], - onClick = { remoteDialog = true } + onClick = { dialogRestoreFocus = remoteFocus; remoteDialog = true } ) SettingsValueRow( title = "Watched status", @@ -216,7 +231,7 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { value = "${vm.watchedPercent}%", requester = watchedFocus, leftTarget = categoryFocus[1], - onClick = { watchedDialog = true } + onClick = { dialogRestoreFocus = watchedFocus; watchedDialog = true } ) SettingsValueRow( title = "Autoplay next episode", @@ -224,7 +239,7 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { value = autoplayLabel(vm.autoplaySeconds), requester = autoplayFocus, leftTarget = categoryFocus[1], - onClick = { autoplayDialog = true } + onClick = { dialogRestoreFocus = autoplayFocus; autoplayDialog = true } ) SettingsValueRow( title = "Skip intros", @@ -242,6 +257,14 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { leftTarget = categoryFocus[1], onClick = { vm.chooseAutoSkipCredits(!vm.autoSkipCredits) } ) + SettingsValueRow( + title = "Volume boost", + description = "Raise quiet titles. Higher boosts can distort loud peaks. Uses decoded audio instead of passthrough.", + value = volumeBoostLabel(vm.volumeBoostDb), + requester = volumeBoostFocus, + leftTarget = categoryFocus[1], + onClick = { dialogRestoreFocus = volumeBoostFocus; volumeBoostDialog = true } + ) Text( "Completed titles keep their Plex watched status.", color = Cinema.quiet, @@ -252,14 +275,14 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { } 2 -> { - SettingsSectionTitle("Subtitles", "Choose how text subtitles look. Image subtitles keep their own style.") + SettingsSectionDescription("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 } + onClick = { dialogRestoreFocus = entryFocus[2]; subtitleSizeDialog = true } ) SettingsValueRow( title = "Style", @@ -267,13 +290,13 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { value = vm.subtitleStyle.label, requester = subtitleStyleFocus, leftTarget = categoryFocus[2], - onClick = { subtitleStyleDialog = true } + onClick = { dialogRestoreFocus = subtitleStyleFocus; subtitleStyleDialog = true } ) SubtitlePreview(vm.subtitleSize, vm.subtitleStyle) } 3 -> { - SettingsSectionTitle("Interface", "Control the small cues Kaleido plays as you browse.") + SettingsSectionDescription("Choose the sounds Kaleido plays while you browse.") SettingsValueRow( title = "Navigation sounds", description = "Play the TV's system tap when focus moves. Follows the TV sound-effects setting.", @@ -282,10 +305,26 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { leftTarget = categoryFocus[3], onClick = { vm.chooseNavigationSounds(!vm.navigationSounds) } ) + SettingsValueRow( + title = "Theme music", + description = "Play Plex theme tracks on movie, series, season and episode pages when available.", + value = if (vm.themeMusic) "On" else "Off", + requester = themeMusicFocus, + leftTarget = categoryFocus[3], + onClick = { vm.chooseThemeMusic(!vm.themeMusic) } + ) + SettingsValueRow( + title = "Theme music volume", + description = "Set the browsing music volume.", + value = "${vm.themeVolume}%", + requester = themeVolumeFocus, + leftTarget = categoryFocus[3], + onClick = { dialogRestoreFocus = themeVolumeFocus; themeVolumeDialog = true } + ) } else -> { - SettingsSectionTitle("Software updates", "Install the latest updates published for Kaleido.") + SettingsSectionDescription("Install the latest updates published for Kaleido.") Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { Text("Kaleido ${BuildConfig.VERSION_NAME}", color = Accent, fontSize = 18.sp, lineHeight = 23.sp, fontWeight = FontWeight.SemiBold) Text(vm.updateStatus, color = Muted, fontSize = 11.sp, lineHeight = 16.sp) @@ -392,9 +431,24 @@ fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) { qualityDialog = false } } + if (themeVolumeDialog) { + val choices = (10..100 step 10).toList() + ChoiceDialog("Theme music volume", choices.map { "$it%" }, choices.indexOf(vm.themeVolume).coerceAtLeast(0), { themeVolumeDialog = false }) { + vm.chooseThemeVolume(choices[it]) + themeVolumeDialog = false + } + } + if (volumeBoostDialog) { + val choices = listOf(0, 3, 6, 9, 12) + ChoiceDialog("Volume boost", choices.map(::volumeBoostLabel), choices.indexOf(vm.volumeBoostDb).coerceAtLeast(0), { volumeBoostDialog = false }) { + vm.chooseVolumeBoostDb(choices[it]) + volumeBoostDialog = false + } + } } private fun autoplayLabel(seconds: Int) = if (seconds <= 0) "Off" else "After $seconds seconds" +private fun volumeBoostLabel(db: Int) = if (db == 0) "Off (+0 dB)" else "+$db dB" /** 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) @@ -426,11 +480,8 @@ private object SettingsScroll:BringIntoViewSpec { } @Composable -private fun SettingsSectionTitle(title: String, subtitle: String) { - Column(verticalArrangement = Arrangement.spacedBy(4.dp)) { - Text(title, color = Accent, fontSize = 21.sp, lineHeight = 27.sp, fontWeight = FontWeight.SemiBold, letterSpacing = (-.3).sp) - Text(subtitle, color = Muted, fontSize = 11.sp, lineHeight = 16.sp) - } +private fun SettingsSectionDescription(description: String) { + Text(description, color = Muted, fontSize = 11.sp, lineHeight = 16.sp) } @Composable diff --git a/app/src/main/java/tv/kaleido/app/ThemeMusic.kt b/app/src/main/java/tv/kaleido/app/ThemeMusic.kt new file mode 100644 index 0000000..d6d52d0 --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/ThemeMusic.kt @@ -0,0 +1,81 @@ +package tv.kaleido.app + +import androidx.compose.runtime.* +import androidx.lifecycle.compose.LifecycleResumeEffect +import androidx.lifecycle.compose.LocalLifecycleOwner +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import androidx.media3.common.AudioAttributes +import androidx.media3.common.C +import androidx.media3.common.MediaItem +import androidx.media3.common.Player +import androidx.media3.datasource.DefaultDataSource +import androidx.media3.datasource.okhttp.OkHttpDataSource +import androidx.media3.exoplayer.ExoPlayer +import androidx.media3.exoplayer.source.DefaultMediaSourceFactory +import kotlinx.coroutines.CancellationException + +/** Themes belong to title pages, never the foreground video or a background Activity. */ +@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) +@Composable internal fun ThemeMusic(vm:KaleidoViewModel) { + val lifecycle=LocalLifecycleOwner.current.lifecycle + var resumed by remember { mutableStateOf(false) } + LifecycleResumeEffect(Unit) { + resumed=true + onPauseOrDispose { resumed=false } + } + val title=vm.detail?.takeIf { it.id==vm.page.id && vm.page.kind in listOf("details","group") } + val eligible=resumed && vm.themeMusic && vm.playing==null && !vm.linkingAccount && vm.servers.isEmpty() && vm.session!=null + val server=vm.session?.server + val parents=remember(server) { mutableMapOf<String,String>() } + val path by produceState("",eligible,title?.id,title?.theme,server) { + value="" + if(!eligible || title==null)return@produceState + val direct=title.theme + if(direct.isNotBlank()) { value=safeThemePath(direct);return@produceState } + val parent=when(title.type) { "season"->title.parentId; "episode"->title.grandparentId; else->"" } + if(parent.isBlank())return@produceState + try { + val theme=parents[parent] ?: vm.api.details(parent).theme.also { parents[parent]=it } + value=safeThemePath(theme) + } catch(e:CancellationException) { throw e } catch(_:Exception) { /* Missing themes stay silent. */ } + } + val source=path.takeIf { eligible && it.isNotBlank() } + val player=remember(source,server) { + source?.let { + val data=OkHttpDataSource.Factory(vm.api.http).setDefaultRequestProperties(vm.api.headers().filterKeys { key->key!="Accept" }) + ExoPlayer.Builder(vm.application).setMediaSourceFactory(DefaultMediaSourceFactory(DefaultDataSource.Factory(vm.application,data))).build().apply { + setAudioAttributes(AudioAttributes.Builder().setUsage(C.USAGE_MEDIA).setContentType(C.AUDIO_CONTENT_TYPE_MUSIC).build(),true) + setHandleAudioBecomingNoisy(true) + repeatMode=Player.REPEAT_MODE_ONE + volume=vm.themeVolume/100f + addListener(object:Player.Listener { + override fun onPlaybackStateChanged(state:Int) { + if(state==Player.STATE_READY)android.util.Log.i("KaleidoTheme","READY volume=${vm.themeVolume}%") + } + override fun onIsPlayingChanged(isPlaying:Boolean) { + if(isPlaying)android.util.Log.i("KaleidoTheme","PLAYING") + } + }) + setMediaItem(MediaItem.fromUri(vm.api.url(it))) + prepare();playWhenReady=true + } + } + } + SideEffect { player?.volume=vm.themeVolume/100f } + DisposableEffect(player,lifecycle) { + // Pause synchronously: backgrounding must not depend on a later Compose frame. + val observer=LifecycleEventObserver { _,event-> + if(event==Lifecycle.Event.ON_PAUSE)player?.pause() + else if(event==Lifecycle.Event.ON_RESUME && vm.themeMusic && vm.playing==null && + vm.page.id==title?.id && vm.page.kind in listOf("details","group") && !vm.linkingAccount)player?.play() + } + lifecycle.addObserver(observer) + onDispose { + lifecycle.removeObserver(observer) + if(player!=null){player.release();android.util.Log.i("KaleidoTheme","STOP")} + } + } +} + +internal fun safeThemePath(path:String):String = path.takeIf { it.startsWith('/') && !it.startsWith("//") }.orEmpty() diff --git a/app/src/main/java/tv/kaleido/app/VolumeBoost.kt b/app/src/main/java/tv/kaleido/app/VolumeBoost.kt new file mode 100644 index 0000000..e058028 --- /dev/null +++ b/app/src/main/java/tv/kaleido/app/VolumeBoost.kt @@ -0,0 +1,29 @@ +package tv.kaleido.app + +import androidx.media3.common.C +import androidx.media3.common.audio.AudioProcessor.AudioFormat +import androidx.media3.common.audio.AudioProcessor.UnhandledAudioFormatException +import androidx.media3.common.audio.BaseAudioProcessor +import java.nio.ByteBuffer +import kotlin.math.pow +import kotlin.math.roundToInt + +/** Applied after decoding, for every channel and delivery mode; passthrough is disabled when on. */ +@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) +internal class VolumeBoostProcessor(db:Int,private val onProcessing:(()->Unit)?=null):BaseAudioProcessor() { + private val gain=boostGain(db) + private var reported=false + override fun onConfigure(inputAudioFormat:AudioFormat):AudioFormat { + if(inputAudioFormat.encoding!=C.ENCODING_PCM_16BIT)throw UnhandledAudioFormatException(inputAudioFormat) + return if(gain>1.0)inputAudioFormat else AudioFormat.NOT_SET + } + override fun queueInput(inputBuffer:ByteBuffer) { + if(!reported&&inputBuffer.hasRemaining()) { reported=true;onProcessing?.invoke() } + val output=replaceOutputBuffer(inputBuffer.remaining()) + while(inputBuffer.remaining()>=2)output.putShort(boostSample(inputBuffer.short,gain)) + output.flip() + } +} + +internal fun boostGain(db:Int):Double=10.0.pow(db.coerceIn(0,12)/20.0) +internal fun boostSample(sample:Short,gain:Double):Short=(sample*gain).roundToInt().coerceIn(Short.MIN_VALUE.toInt(),Short.MAX_VALUE.toInt()).toShort() diff --git a/app/src/test/java/tv/kaleido/app/AudioPreferencesTest.kt b/app/src/test/java/tv/kaleido/app/AudioPreferencesTest.kt new file mode 100644 index 0000000..fcbf68c --- /dev/null +++ b/app/src/test/java/tv/kaleido/app/AudioPreferencesTest.kt @@ -0,0 +1,36 @@ +package tv.kaleido.app + +import org.junit.Assert.* +import org.junit.Test +import java.nio.ByteBuffer +import java.nio.ByteOrder +import androidx.media3.common.C +import androidx.media3.common.audio.AudioProcessor.AudioFormat + +@androidx.annotation.OptIn(androidx.media3.common.util.UnstableApi::class) +class AudioPreferencesTest { + @Test fun boostProcessesEveryChannelAndSaturatesWithoutWrapping() { + val processor=VolumeBoostProcessor(6) + processor.configure(AudioFormat(48000,2,C.ENCODING_PCM_16BIT)) + val input=ByteBuffer.allocateDirect(12).order(ByteOrder.nativeOrder()) + listOf(1000,-1000,30000,-30000,0,Short.MIN_VALUE.toInt()).forEach { input.putShort(it.toShort()) } + input.flip();processor.queueInput(input) + val output=processor.output.order(ByteOrder.nativeOrder()) + val samples=generateSequence { if(output.remaining()>=2)output.short.toInt()else null }.toList() + assertEquals(listOf(1995,-1995,32767,-32768,0,-32768),samples) + assertFalse(input.hasRemaining()) + } + @Test fun boostOffPreservesSamplesAndBoundsGain() { + assertEquals(1.0,boostGain(0),0.0) + assertEquals(1.0,boostGain(-30),0.0) + assertEquals(boostGain(12),boostGain(99),0.0) + assertEquals(1234.toShort(),boostSample(1234,boostGain(0))) + assertEquals((-1234).toShort(),boostSample(-1234,boostGain(0))) + } + @Test fun themesUseOnlyServerRelativePaths() { + assertEquals("/library/metadata/6115/theme/1",safeThemePath("/library/metadata/6115/theme/1")) + assertEquals("",safeThemePath("https://elsewhere.example/theme.mp3")) + assertEquals("",safeThemePath("//elsewhere.example/theme.mp3")) + assertEquals("",safeThemePath("")) + } +} diff --git a/app/src/test/java/tv/kaleido/app/LibraryNavigationTest.kt b/app/src/test/java/tv/kaleido/app/LibraryNavigationTest.kt new file mode 100644 index 0000000..6796636 --- /dev/null +++ b/app/src/test/java/tv/kaleido/app/LibraryNavigationTest.kt @@ -0,0 +1,33 @@ +package tv.kaleido.app + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Test + +class LibraryNavigationTest { + @Test fun firstCharacterCountsProduceAbsoluteTitleOffsets() { + val counts = listOf( + PlexCharacterCount("%23", "#", 3), + PlexCharacterCount("A", "A", 12), + PlexCharacterCount("B", "B", 0), + PlexCharacterCount("C", "C", 4), + ) + + assertEquals(mapOf("#" to 0, "A" to 3, "C" to 15), libraryCharacterOffsets(counts)) + assertEquals(false, libraryCharacterOffsets(counts).containsKey("B")) + } + + @Test fun genreUnwatchedAndMediaTypeArePartOfTheCharacterQuery() { + val all = LibraryCharacterQuery("1", "", false, plexLibraryType("movie")) + val action = LibraryCharacterQuery("1", "12", false, plexLibraryType("movie")) + val unwatched = LibraryCharacterQuery("1", "12", true, plexLibraryType("movie")) + val shows = LibraryCharacterQuery("2", "12", true, plexLibraryType("show")) + + assertNotEquals(all, action) + assertNotEquals(action, unwatched) + assertNotEquals(unwatched, shows) + assertEquals(mapOf("genre" to "12", "unwatched" to "1", "type" to "2"), libraryFilterParameters("12", true, "2")) + assertEquals("1", plexLibraryType("movie")) + assertEquals("2", plexLibraryType("show")) + } +} diff --git a/app/src/test/java/tv/kaleido/app/PlaybackModelTest.kt b/app/src/test/java/tv/kaleido/app/PlaybackModelTest.kt index 6f91867..7a11181 100644 --- a/app/src/test/java/tv/kaleido/app/PlaybackModelTest.kt +++ b/app/src/test/java/tv/kaleido/app/PlaybackModelTest.kt @@ -38,7 +38,7 @@ class PlaybackModelTest { } @Test fun searchGroupsFollowBrowsingOrder() { - val groups=searchGroups(listOf(title("episode","e"),title("show","s"),title("movie","m"))) + val groups=searchGroups(listOf(title("episode","e"),title("show","s"),title("movie","m")),query="") assertEquals(listOf("Movies","TV shows","Episodes"),groups.map{it.first}) } diff --git a/app/src/test/java/tv/kaleido/app/SearchRankingTest.kt b/app/src/test/java/tv/kaleido/app/SearchRankingTest.kt new file mode 100644 index 0000000..a384f25 --- /dev/null +++ b/app/src/test/java/tv/kaleido/app/SearchRankingTest.kt @@ -0,0 +1,70 @@ +package tv.kaleido.app + +import org.junit.Assert.assertEquals +import org.junit.Test + +class SearchRankingTest { + private data class Result(val type: String, val title: String, val inheritedTitles: List<String> = emptyList()) + + @Test fun exactShowRanksAheadOfLooseMovieResult() { + val groups = rankSearchGroups(listOf( + Result("movie", "The SpongeBob Movie: Sponge on the Run"), + Result("show", "Silo") + ), "Silo", { it.type }) { listOf(it.title) } + + assertEquals("TV shows", groups.first().first) + } + + @Test fun exactMovieRanksAheadOfLooselyMatchingShow() { + val groups = rankSearchGroups( + listOf(Result("show", "The Silo Series"), Result("movie", "Silo")), + "Silo", + { it.type } + ) { listOf(it.title) } + + assertEquals("Movies", groups.first().first) + } + + @Test fun titlePrefixRanksAheadOfLaterTokenMatch() { + val groups = rankSearchGroups( + listOf(Result("show", "The Silo Series"), Result("movie", "Silo: Lost in Space")), + "Silo", + { it.type } + ) { listOf(it.title) } + + assertEquals("Movies", groups.first().first) + } + + @Test fun normalizedExactTitleOutranksPrefix() { + val groups = rankSearchGroups( + listOf(Result("movie", "Silo: The Movie"), Result("show", "Sílo")), + "Silo", + { it.type } + ) { listOf(it.title) } + + assertEquals("TV shows", groups.first().first) + } + + @Test fun ownExactTitleOutranksAnInheritedShowTitle() { + val groups = rankSearchGroups( + listOf( + Result("episode", "The Long Day", listOf("Silo")), + Result("show", "Silo") + ), + "Silo", + { it.type } + ) { listOf(it.title) + it.inheritedTitles } + + assertEquals("TV shows", groups.first().first) + } + + @Test fun tiedGroupsKeepPlexResultOrder() { + val groups = rankSearchGroups( + listOf(Result("show", "Silo"), Result("movie", "Silo")), + "Silo", + { it.type } + ) { listOf(it.title) } + + assertEquals(listOf("TV shows", "Movies"), groups.map { it.first }) + } +} diff --git a/distribution/Kaleido.apk b/distribution/Kaleido.apk index 9acb2ae..817ea24 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 090566a..19017d2 100644 --- a/distribution/Kaleido.apk.sha256 +++ b/distribution/Kaleido.apk.sha256 @@ -1 +1 @@ -aaf650185f6854837afae9f69aee40e64060e5b22d8783aa1850a31196bf075a Kaleido.apk +38c998fbd09f410828deb30882196e722d209e411d6ddb10067265668d740d55 Kaleido.apk diff --git a/distribution/latest.json b/distribution/latest.json index 0955a38..d07389f 100644 --- a/distribution/latest.json +++ b/distribution/latest.json @@ -1,7 +1,7 @@ { - "version": "0.2.1", - "versionCode": 14, - "url": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.2.1/distribution/Kaleido.apk", - "checksumUrl": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.2.1/distribution/Kaleido.apk.sha256", - "notes": "- Season and episode pages are one horizontal layout again. Moving along the season row shows that episode at the top, and selecting it or Play plays it, instead of opening another page with the same information. Back from playback returns to the episode you played.\n- Remove the Go to show button from season and episode pages; Back returns to the show, and quick actions still offer Go to show.\n- Play buttons are solid white only when focused, so an unfocused Play no longer looks selected." + "version": "0.3.0", + "versionCode": 15, + "url": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.3.0/distribution/Kaleido.apk", + "checksumUrl": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.3.0/distribution/Kaleido.apk.sha256", + "notes": "- Add Categories alongside Discover and Library in Movies and TV Shows. Browse the genres from the selected Plex library, with movies and shows kept separate.\n- Add a light grey A\u2013Z jump bar on the right of libraries and category results. Jump to letters with the remote, including titles beyond the first loaded page, and press Left to enter the titles.\n- Put exact title matches first in Search, including the Silo series ahead of unrelated movie matches. Order result rows by relevance instead of always placing movies first.\n- Add optional Plex theme music on movie, series, season and episode pages, with a separate volume setting. Music stops for playback and when Kaleido leaves the foreground; titles without theme tracks stay silent.\n- Add an optional app-wide volume boost from +3 to +12 dB for all video playback. Boost uses decoded audio instead of compressed passthrough; Off preserves the original audio path.\n- Remove repeated category headings in Settings and restore focus to preference controls after closing their dialogs." } diff --git a/docs/performance-2026-10-27.md b/docs/performance-2026-10-27.md new file mode 100644 index 0000000..1fc67bb --- /dev/null +++ b/docs/performance-2026-10-27.md @@ -0,0 +1,37 @@ +# Navigation performance comparison - 2026-10-27 + +The onn shows measurable navigation hitches in all three releases. This comparison does not establish a broad regression from the 0.2.1 bugfixes: optimized horizontal browse p95 was 32 ms in both 0.1.11 and 0.2.1, and 34 ms in 0.3.0. Some first-entry transitions are slower in the newer releases, while warm results overlap. No individual change or author can be identified as the cause from these measurements. + +## Method + +- Same onn 4K Plus Streaming at 192.168.50.195:5555, Android 14, armeabi-v7a; existing 1920x1080 display override and density 320 retained. Launcher, accessibility services and system settings were unchanged. +- Original signed 0.1.11/code 12 and 0.2.1/code 14 APKs were extracted from their tags and checksum-verified. The final signed 0.3.0/code 15 APK was tested. In-place installs retained the encrypted session and app preferences. Theme music and boost were Off. +- Each fresh install began in ART status=verify. Ran the horizontal browse harness, installed the bundled baseline profile, forced speed-profile compilation, confirmed ART status=speed-profile, then ran three cycles of all 14 Home/Movies transitions and another horizontal browse check. Thermal status was 0 throughout the version-start snapshots; corresponding reported sensor temperatures were essentially unchanged. +- Commands: scripts/repro_runtime.py browse and scripts/profile_transitions.py <label> --cycles 3. No competing device/UI tests ran. Raw framestats, compilation states and thermal snapshots remain in ignored evidence/private/. + +## Results + +| Release | Fresh-install browse median / p95 | Profiled browse median / p95 | Missed intervals across 42 transitions | +| --- | --- | --- | --- | +| 0.1.11 | 27 / 48 ms | 14 / 32 ms | 47 | +| 0.2.1 | 30 / 61 ms | 16 / 32 ms | 50 | +| 0.3.0 | 30 / 53 ms | 16 / 34 ms | 54 | + + +Fresh-install browse exceeded the 40 ms harness threshold in every release. All profiled browse runs passed, with stable horizontal Y geometry and zero gfxinfo Missed Vsync in that specific horizontal sample. That does not mean every frame met the 16.7 ms budget or every navigation transition was smooth. + +Missed intervals below are inferred display stalls from adjacent framestats, not a count of dropped video frames. Each array is cycles 1, 2 and 3; the first cycle is the first pass after launch. + +| Transition | 0.1.11 | 0.2.1 | 0.3.0 | +| --- | --- | --- | --- | +| home: hero -> row | 1 / 0 / 0 | 2 / 0 / 0 | 1 / 0 / 0 | +| home: hero <- row | 0 / 0 / 0 | 1 / 1 / 0 | 1 / 2 / 1 | +| tabs: home -> movies | 7 / 6 / 7 | 10 / 6 / 5 | 8 / 6 / 5 | +| tabs: home <- movies | 6 / 4 / 3 | 6 / 3 / 3 | 4 / 6 / 4 | +| movies: row -> row | 2 / 1 / 0 | 2 / 1 / 1 | 1 / 2 / 1 | +| movies: row <- row | 2 / 2 / 2 | 2 / 2 / 2 | 2 / 2 / 2 | + + +First Home hero-to-row p95 was 28.4 / 42.0 / 43.0 ms respectively; later cycles were 26.5-27.6 / 25.9 / 23.9-27.5 ms. First-pass work is a visible source of occasional stutter. Repeated tab switches also missed display intervals in every version. + +This is a small on-device comparison, not a statistical attribution study. It cannot reconstruct the original compilation state when the user noticed the issue. Fresh-install optimization has a large effect here, but it is not proven to explain that earlier observation. The final 0.3.0 release was reinstalled, baseline-profile compiled and returned to Home afterward. diff --git a/docs/runtime-verification.md b/docs/runtime-verification.md index 056c9fb..f0930d0 100644 --- a/docs/runtime-verification.md +++ b/docs/runtime-verification.md @@ -4,6 +4,16 @@ For the 2026-10-26 codec/HDR sweep and its native-versus-converted playback find Target: the authorized onn at `192.168.50.195:5555`, package `tv.kaleido.app`. Other applications and the launcher were not modified. Screenshots, traces, UI dumps and server-specific logs stay in ignored `evidence/private/`. +## 2026-10-27 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. +- Added scoped Plex genre categories and a light grey A–Z rail to movie/show libraries and category results. Plex first-character counts use the same media type, genre and watched filters as the grid; a jump loads the required prefix without fetching its artwork. Movie S reached absolute index 772 and TV S index 200. Both Animation categories, details Back, selected-category Back and grid focus restoration passed. Dense rail controls require compact touch targets, otherwise Android TV accessibility hides overlapping letters despite correct visual focus. +- Theme music defaults Off, with independent 10–100% volume. Plex themes inherit from show metadata on season/episode pages. Real Silo theme playback, season/episode pages, background stop and video stop were checked. The server currently supplies no movie theme fixtures; movie theme parsing is tested and uses the same playback path. Returning through a launcher can reopen Home, where music correctly remains silent; reopening a supported title starts its theme. +- Boost defaults Off and supports +3/+6/+9/+12 dB. It processes decoded 16-bit PCM across all channels and disables encoded passthrough/offload only while enabled; Off preserves the normal audio path. Unit tests cover gain, clipping without integer wrap and unchanged samples at zero gain. Real +6 dB playback of HEVC/EAC3 episode 7599 and converted movie 9776 confirmed PCM processing, advancing audio and rendered video. No acoustic loudness measurement was made. Validation mode avoided Plex progress changes. +- Checks: 26 unit tests, debug/release compilation and lint, three new live integration tests, existing Settings remote/dialog tests, the scoped library/jump checks and `verify_audio_preferences.py --playback-only`. The full audio UI batch separately verified setting changes, dialog focus and cold-start persistence; its fixture assertions now accept labels such as `Resume from 2:01`. Prior audio preferences were restored exactly. Private screenshots and audio/video validation logs remain ignored. + +See [the navigation comparison](performance-2026-10-27.md) for matched release/profile benchmarks against 0.1.11 and 0.2.1. The final 0.3.0 release was restored on Home with ART speed-profile compilation. Publication and ADB installation do not constitute an in-app updater installation test. + ## 2026-10-27 one season layout (0.2.1) - 0.2.0 gave seasons a vertical episode list whose items opened an episode page with a horizontal season row, so the same season appeared in two layouts and selecting an episode never played it. Season and episode pages now share the episode header and horizontal season row: focusing a card shows that episode (summary row data at once, full metadata after 250 ms, keeping the row's progress), and OK on the card or Play plays it. The header has a fixed height so moving along the row never shifts the page. Up from the row returns to Play; Down from Play enters the shown episode. diff --git a/scripts/package_release.py b/scripts/package_release.py index b4a22ff..1915294 100644 --- a/scripts/package_release.py +++ b/scripts/package_release.py @@ -1,7 +1,7 @@ """Stage a locally signed APK for Git distribution and tag-triggered Forgejo releases.""" import hashlib, json, pathlib, re, shutil, subprocess ROOT=pathlib.Path(__file__).resolve().parents[1] -version=dict(l.split('=',1) for l in (ROOT/'version.properties').read_text().splitlines() if '=' in l) +version=dict(l.split('=',1) for l in (ROOT/'version.properties').read_text(encoding='utf-8').splitlines() if '=' in l) apk=ROOT/'app/build/outputs/apk/release/app-release.apk' if not apk.exists():raise SystemExit('Run Build.ps1 -Release first.') out=ROOT/'distribution';out.mkdir(exist_ok=True) @@ -11,8 +11,8 @@ digest=hashlib.sha256(apk.read_bytes()).hexdigest() repo='https://git.elijahkuntz.com/Elijah/Kaleido' tag='v'+version['versionName'] # Only this version's section, matching the release body the app shows as notes. -changelog=(ROOT/'CHANGELOG.md').read_text() if (ROOT/'CHANGELOG.md').exists() else '' +changelog=(ROOT/'CHANGELOG.md').read_text(encoding='utf-8') if (ROOT/'CHANGELOG.md').exists() else '' section=re.search(r'^## v?'+re.escape(version['versionName'])+r'[ \t]*$(.*?)(?=^## |\Z)',changelog,re.M|re.S) manifest={'version':version['versionName'],'versionCode':int(version['versionCode']),'url':repo+'/raw/tag/'+tag+'/distribution/Kaleido.apk','checksumUrl':repo+'/raw/tag/'+tag+'/distribution/Kaleido.apk.sha256','notes':section.group(1).strip() if section else ''} -(out/'latest.json').write_text(json.dumps(manifest,indent=2)+'\n') +(out/'latest.json').write_text(json.dumps(manifest,indent=2)+'\n',encoding='utf-8') print('Packaged',tag,'SHA-256',digest) diff --git a/scripts/publish_release.py b/scripts/publish_release.py index e159a90..bb71aa1 100644 --- a/scripts/publish_release.py +++ b/scripts/publish_release.py @@ -3,14 +3,14 @@ import hashlib, json, os, pathlib, re, urllib.request, uuid ROOT=pathlib.Path(__file__).resolve().parents[1] API='https://git.elijahkuntz.com/api/v1/repos/Elijah/Kaleido' token=os.environ['KALEIDO_RELEASE_TOKEN'] -version=dict(l.split('=',1) for l in (ROOT/'version.properties').read_text().splitlines() if '=' in l) +version=dict(l.split('=',1) for l in (ROOT/'version.properties').read_text(encoding='utf-8').splitlines() if '=' in l) tag='v'+version['versionName'] ref=os.environ.get('RELEASE_REF','') assert ref=='refs/tags/'+tag,'Tag must match version.properties exactly' out=ROOT/'distribution' def notes(): """Only this version's changelog section; the app shows the body as release notes.""" - text=(ROOT/'CHANGELOG.md').read_text() + text=(ROOT/'CHANGELOG.md').read_text(encoding='utf-8') m=re.search(r'^## v?'+re.escape(version['versionName'])+r'[ \t]*$(.*?)(?=^## |\Z)',text,re.M|re.S) return m.group(1).strip() if m else '' assert hashlib.sha256((out/'Kaleido.apk').read_bytes()).hexdigest()==(out/'Kaleido.apk.sha256').read_text().split()[0] diff --git a/scripts/verify_audio_preferences.py b/scripts/verify_audio_preferences.py new file mode 100644 index 0000000..f59ec3b --- /dev/null +++ b/scripts/verify_audio_preferences.py @@ -0,0 +1,111 @@ +"""Validate optional themes and PCM boost on the authorized onn; restore the prior audio preferences.""" +import re,time,sys,xml.etree.ElementTree as ET +from device import adb,OUT,screenshot +from verify_ui import launch,key,text,focused,focus,snapshot,labels,wait,passed + +def settings(category): + launch();key(22,4);focused('Settings');key(23);focused('Switch account') + key(21);focused('Connection');key(20,category);key(22) + +def choose(options,value): + key(23) + current=focus(snapshot()) + assert current in options,(current,options) + delta=options.index(value)-options.index(current) + key(20 if delta>=0 else 19,abs(delta));focused(value);key(23) + +def logs():return adb('logcat','-d','-s','KaleidoTheme:I','KaleidoPlayback:I','*:S').decode(errors='replace') + +def wait_log(fragment,timeout=40): + deadline=time.monotonic()+timeout + while time.monotonic()<deadline: + value=logs() + if fragment in value:return value + time.sleep(.5) + raise AssertionError('Missing log '+fragment) + +def open_silo(): + launch();key(22,3);focused('Search');key(23);text('Search') + adb('shell','input','text','silo') + text('TV shows');key(66);focused('Silo');key(23);text('Seasons') + +if __name__=='__main__': + playback_only='--playback-only' in sys.argv + original_xml=None + if playback_only: + # UI preferences and persistence are checked separately; isolate the playback batch + # using only this debug app's private preferences, with byte-for-byte restoration. + original_xml=adb('shell','run-as','tv.kaleido.app','cat','shared_prefs/preferences.xml') + (OUT/'030-audio-original-preferences.xml').write_bytes(original_xml) + tree=ET.fromstring(original_xml) + for name,kind,value in [('themeMusic','boolean','true'),('themeVolume','int','20'),('volumeBoostDb','int','6')]: + node=next((n for n in tree if n.get('name')==name),None) + if node is None:node=ET.SubElement(tree,kind,{'name':name}) + node.set('value',value) + adb('shell','am','force-stop','tv.kaleido.app') + adb('shell','run-as','tv.kaleido.app','sh','-c','"cat > shared_prefs/preferences.xml"',data=ET.tostring(tree,encoding='utf-8',xml_declaration=True)) + else: + settings(3);focused('Navigation sounds');key(20);focused('Theme music') + original_on=focus(snapshot()).endswith('On') + if not original_on:key(23) + key(20);focused('Theme music volume') + original_volume=re.search(r'(\d+)%$',focus(snapshot())).group(1)+'%' + choose([str(n)+'%' for n in range(10,101,10)],'20%');focused('Theme music volume') + settings(1);focused('Playback quality');key(20,6);focused('Volume boost') + current=focus(snapshot());original_boost='Off (+0 dB)' if current.endswith('Off (+0 dB)') else re.search(r'\+\d+ dB$',current).group() + choose(['Off (+0 dB)','+3 dB','+6 dB','+9 dB','+12 dB'],'+6 dB');focused('Volume boost') + screenshot('030-volume-boost') + settings(3);key(20);focused('Theme music');assert focus(snapshot()).endswith('On') + key(20);focused('Theme music volume');assert focus(snapshot()).endswith('20%') + screenshot('030-theme-settings') + passed('Theme toggle, theme volume and boost persist through cold starts; dialogs restore focus') + try: + adb('logcat','-c');open_silo();wait_log('KaleidoTheme: READY volume=20%') + screenshot('030-silo-theme') + adb('logcat','-c');key(3);wait_log('STOP') + # Launchers may reopen Home rather than restore the previous Activity task. + # Enter the title through the normal remote flow before expecting music again. + open_silo();wait_log('PLAYING') + passed('Theme stops in the background and plays again on a title page') + # Show -> season -> neighbouring episode selection all retain a supported theme. + key(20) + wait(lambda r:'Season' in focus(r),'Season receives focus');key(23) + wait(lambda r:any(t=='Episodes' or t.startswith(('Play','Resume')) for t in labels(r)),'Season episode header') + wait_log('KaleidoTheme: READY volume=20%') + passed('Series and season/episode detail pages play the real inherited Plex theme') + # Actual video uses validation mode, which avoids changing Plex progress. + adb('logcat','-c') + adb('shell','am','start','-n','tv.kaleido.app/.MainActivity','--es','testTitleId','7599','--el','testOffset','90000','--ei','testMode','0','--ez','testValidation','true') + wait_log('STOP');wait_log('BOOST processing PCM db=6');wait_log('READY item=7599') + time.sleep(4) + audit=adb('shell','run-as','tv.kaleido.app','cat','files/playback-validation.jsonl') + (OUT/'030-boost-validation.jsonl').write_bytes(audit) + import json + events=[json.loads(line) for line in audit.decode().splitlines()] + assert any(e.get('event')=='audioAdvancing' for e in events),'Decoded audio must advance' + assert any(e.get('event')=='firstFrame' for e in events),'Video must render' + passed('Theme stops for actual video; +6 dB processor receives decoded PCM and audio/video advance') + 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') + wait_log('BOOST processing PCM db=6');wait_log('READY item=9776');time.sleep(4) + movie_audit=adb('shell','run-as','tv.kaleido.app','cat','files/playback-validation.jsonl') + (OUT/'030-boost-movie-validation.jsonl').write_bytes(movie_audit) + movie_events=[json.loads(line) for line in movie_audit.decode().splitlines()] + assert any(e.get('event')=='audioAdvancing' for e in movie_events) + assert any(e.get('event')=='firstFrame' for e in movie_events) + passed('Volume boost also processes a real Plex-converted movie with rendered audio/video') + adb('shell','am','force-stop','tv.kaleido.app') + finally: + if playback_only: + adb('shell','am','force-stop','tv.kaleido.app') + adb('shell','run-as','tv.kaleido.app','sh','-c','"cat > shared_prefs/preferences.xml"',data=original_xml) + assert adb('shell','run-as','tv.kaleido.app','cat','shared_prefs/preferences.xml')==original_xml + else: + settings(1);key(20,6);focused('Volume boost') + choose(['Off (+0 dB)','+3 dB','+6 dB','+9 dB','+12 dB'],original_boost) + settings(3);key(20);focused('Theme music') + if focus(snapshot()).endswith('On')!=original_on:key(23) + key(20);focused('Theme music volume');choose([str(n)+'%' for n in range(10,101,10)],original_volume) + launch() + (OUT/'030-audio.log').write_text(logs()) + passed('Prior theme and boost preferences restored; device returned to Home') diff --git a/scripts/verify_library_jump.py b/scripts/verify_library_jump.py new file mode 100644 index 0000000..6b539b0 --- /dev/null +++ b/scripts/verify_library_jump.py @@ -0,0 +1,76 @@ +"""Read-only D-pad checks for exact search, scoped genres and jumps beyond the first catalog page.""" +import json,time,urllib.parse,urllib.request +from device import ROOT,adb,screenshot +from verify_ui import launch,key,text,focused,focus,snapshot,labels,wait,passed + +LETTERS=['#']+list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') + +def first_at_letter(section,media_type,letter,genre=''): + cfg=dict(l.split('=',1) for l in (ROOT/'.env').read_text().splitlines() if '=' in l and not l.startswith('#')) + base=cfg['PLEX_SERVER_URL'].strip('"\'').rstrip('/') + headers={'X-Plex-Token':cfg['PLEX_TOKEN'].strip('"\''),'Accept':'application/json'} + def get(path,params): + request=urllib.request.Request(base+path+'?'+urllib.parse.urlencode(params),headers=headers) + with urllib.request.urlopen(request,timeout=30) as response:return json.load(response)['MediaContainer'] + sections=get('/library/sections',{})['Directory'] + section=next(s['key'] for s in sections if s['type']==media_type) + params={'type':'1' if media_type=='movie' else '2'} + if genre: + genres=get('/library/sections/'+section+'/genre',{})['Directory'] + params['genre']=next(g['key'] for g in genres if g['title']==genre) + chars=get('/library/sections/'+section+'/firstCharacter',params)['Directory'] + offset=0 + for item in chars: + if item['title']==letter:break + offset+=item['size'] + params.update({'sort':'titleSort:asc','X-Plex-Container-Start':offset,'X-Plex-Container-Size':1}) + return get('/library/sections/'+section+'/all',params)['Metadata'][0]['title'],offset + +def enter_rail(): + for _ in range(10): + value=focus(snapshot()) + if value in LETTERS:return value + key(22) + raise AssertionError('Right edge must enter letter bar; focus='+focus(snapshot())) + +def jump(letter,expected): + current=enter_rail() + delta=LETTERS.index(letter)-LETTERS.index(current) + key(20 if delta>=0 else 19,abs(delta));focused(letter) + key(23) + # OK keeps the letter selected; Left explicitly enters the target title. + time.sleep(2);focused(letter);key(21);focused(expected) + key(23);wait(lambda r:any(s in labels(r) for s in ['Play','Resume','Seasons','Synopsis']),'Title details open') + key(4);focused(expected) + +def section_check(tab,media_type): + launch();key(22,1 if tab=='Movies' else 2);focused(tab) + key(20);focused('Discover');key(22);focused('Library');key(23);focused('Library') + text('Z');screenshot('030-'+media_type+'-library') + key(20);key(20) + expected,offset=first_at_letter('',media_type,'S') + jump('S',expected) + passed(f'{tab} A-Z reaches S at absolute index {offset}, enters title and restores focus') + key(4);focused('Discover');key(22,2);focused('Categories');key(23) + # Genres are server-supplied and alphabetically ordered; move within the first row. + wait(lambda r:focus(r) not in ('','Categories'),'Category tile receives focus') + for _ in range(8): + if focus(snapshot())=='Animation':break + key(22) + focused('Animation');key(23);text('Animation ⌄');text('Z') + expected,offset=first_at_letter('',media_type,'S','Animation') + jump('S',expected) + screenshot('030-'+media_type+'-animation-jump') + key(4);focused('Animation');key(4);focused('Discover') + passed(f'{tab} Animation stays scoped and supports letter jump, details Back and category Back') + +if __name__=='__main__': + for tab,kind in [('Movies','movie'),('TV Shows','show')]:section_check(tab,kind) + launch() + key(22,3);focused('Search');key(23);text('Search') + adb('shell','input','text','silo') + text('TV shows');key(66);focused('Silo') + # The first reachable result must be the exact series, never the unrelated movie row. + key(23);text('Seasons');screenshot('030-exact-silo-search') + key(4);focused('Silo');key(4);key(4) + passed('Silo search enters the exact series first and restores the result on Back') diff --git a/version.properties b/version.properties index 529144c..77a2edf 100644 --- a/version.properties +++ b/version.properties @@ -1,2 +1,2 @@ -versionName=0.2.1 -versionCode=14 +versionName=0.3.0 +versionCode=15