Release Kaleido 0.1.8 with cast browsing and refreshed title pages
All checks were successful
Validate and publish Kaleido / android (push) Successful in 2m8s

This commit is contained in:
Elijah 2026-10-25 21:49:24 -07:00
parent 119f1ae5a9
commit 5199bb0928
28 changed files with 982 additions and 187 deletions

View file

@ -53,6 +53,9 @@ Use `& $KaleidoPython` before the Python commands below. Run only checks relevan
| `scripts/trace_transition.py <label> <setup> <keys>` | atrace one transition and list slow UI frames with their nested work |
| `scripts/profile_home.py <label>` | Hero → Continue Watching frame timing; profiled **release**; `--cold --cycles 1` checks the first transition |
| `scripts/verify_navigation_sounds.py` | Sound toggle and cold-start persistence; leaves sounds On |
| `scripts/verify_details.py` | Cast/actor navigation, related shows and watched sync; temporarily marks validated unwatched movie/show fixtures, then restores them |
| `scripts/verify_details_layout.py` | Fresh TV show header bounds and Seasons before Cast; debug or release |
| `scripts/verify_settings.py` | Category navigation, preference-dialog cancellation and live update check; expects Original quality / 80% test preferences |
Live Android integration tests (currently six) cover secure persistence, library APIs, episodes, PIN, preview JPEGs/new seasons and supported HEVC remux negotiation:

View file

@ -1,5 +1,14 @@
# Kaleido releases
## 0.1.8
- Add cast portraits with character names to title information. Select an actor to browse their movies and shows across your Plex libraries.
- Add Mark watched / Mark unwatched buttons that synchronize movies, series and episodes with Plex.
- Put Seasons first on TV show pages, followed by Cast and related shows supplied by Plex.
- Redesign TV show information with a full backdrop, fitted poster and stable header placement. Add text shadows and stronger contrast for readable descriptions and ratings.
- Redesign Settings with a category rail and consistent controls for Connection, Playback, Interface and Updates.
- Refresh the screenshots and rewrite the README around the app's features and installation.
## 0.1.7
- Give the launcher banner and app icon a soft colored background: deep sea-glass light from the top right fading to a warm glow at the bottom left, behind the unchanged six-facet mark.

View file

@ -1,59 +1,70 @@
# Kaleido
A native client for personal Plex movie and television libraries on Android TV 9 and newer. Built for a remote, with cinematic artwork, movie and TV discovery, next-episode rows, and filterable libraries. Powered by Kotlin, Jetpack Compose, and Media3.
A Plex client for Android TV, designed for browsing from the couch. Kaleido puts your movies, shows and next episodes up front, with large artwork and controls that work with a remote.
**[Download the latest release](https://git.elijahkuntz.com/Elijah/Kaleido/releases/latest)** · Android TV 9 or newer · Requires a Plex Media Server
## What's in the app
### Find something to watch
- **Home** brings together featured titles, Plex recommendations and Continue Watching. Resume a movie or get back to your current series without digging through your library.
- **Movies** starts with recent releases and recommendations. **TV Shows** leads with your next episodes, new seasons and newly added episodes.
- **Library** gives you an A–Z poster grid with genre, watched-status and sorting controls. Search finds movies, shows and episodes across your libraries.
- **Title pages** include ratings, a synopsis and cast portraits with character names. Select an actor to see their available movies and shows. Series pages put seasons first, with cast and related shows below.
### Watch the way you want
Original quality plays the source video where your TV supports it. You can also ask Plex to convert to 4K, 1080p, 720p or 480p for a slower connection or a different device.
Choose audio tracks, subtitles, playback speed and chapters from the player. Tap Left or Right to skip ten seconds, or hold to scrub through the timeline with thumbnail previews. Skip intros and credits, and let the next episode start after a short, cancellable countdown. Previews and skip markers appear when Plex supplies them; HDR and format support depend on your TV and server.
### Keep your place
Playback progress and watched status sync with Plex, so your place carries across clients. Mark a movie, season or whole show watched or unwatched from its information page. You can set the playback percentage that counts as watched, too.
Settings groups connection, playback, interface and updates in one place. Navigation tap sounds can be turned on or off. The built-in updater checks for releases and downloads new versions without another manual sideload.
## Install
1. Download **Kaleido.apk** from the [latest release](https://git.elijahkuntz.com/Elijah/Kaleido/releases/latest) and install it on your Android TV.
2. Open Kaleido and enter the code at [plex.tv/link](https://plex.tv/link).
3. Choose your Plex server and start browsing.
A manual server URL and token connection is also available. For future updates, use **Settings → Updates**. Android will ask you to confirm the installation.
## Screenshots
Captured from Kaleido **0.1.7** running on Android TV with a live Plex library. Select a screenshot to view it at full resolution.
Captured from Kaleido **0.1.8** running on Android TV with a live Plex library. Select a screenshot to view it at full resolution.
**Home** — a cinematic feature with playback actions and integrated Continue Watching.
[![Kaleido Home with a cinematic Parasite feature and Continue Watching row](docs/screenshots/home.webp)](docs/screenshots/home.webp)
[![Kaleido Home with cinematic featured artwork and a Continue Watching row](docs/screenshots/home.webp)](docs/screenshots/home.webp)
| Movie discovery | TV discovery |
| --- | --- |
| [![Movies with focused backdrop artwork, audience ratings, and recently released posters](docs/screenshots/movies.webp)](docs/screenshots/movies.webp) | [![TV shows with next-episode thumbnails and newly added seasons](docs/screenshots/tv.webp)](docs/screenshots/tv.webp) |
| A–Z library | Title details |
| Movie information and cast | TV show information and seasons |
| --- | --- |
| [![Movie library with a six-column poster grid, genre filters, and sorting](docs/screenshots/library.webp)](docs/screenshots/library.webp) | [![Title details with synopsis, audience ratings, cast, and playback action](docs/screenshots/details.webp)](docs/screenshots/details.webp) |
| [![Movie information with synopsis, ratings, watched controls and actor portraits](docs/screenshots/details.webp)](docs/screenshots/details.webp) | [![TV show information with a fitted poster, readable synopsis and Seasons first](docs/screenshots/show.webp)](docs/screenshots/show.webp) |
## Build on Windows
| Actor filmography | Settings |
| --- | --- |
| [![Actor page showing available movies and television series across Plex libraries](docs/screenshots/actors.webp)](docs/screenshots/actors.webp) | [![Settings category rail with playback quality and watched preferences](docs/screenshots/settings.webp)](docs/screenshots/settings.webp) |
1. Run `scripts/bootstrap.py` with Python 3 to download an isolated JDK 17, Gradle 8.13, and Android command-line tools under `.tools/`.
2. Set `JAVA_HOME` to the extracted JDK directory and run `.tools/sdk/cmdline-tools/latest/bin/sdkmanager.bat --sdk_root=<absolute .tools/sdk path> "platforms;android-36" "build-tools;35.0.0"`. Accept the SDK license when prompted.
3. Run `./Build.ps1 -Test` for the debug APK, unit tests, and lint. Run `./Build.ps1 -Release` for the optimized release APK.
| A–Z library | Cast and related shows |
| --- | --- |
| [![Movie library with a six-column poster grid, genre filters, and sorting](docs/screenshots/library.webp)](docs/screenshots/library.webp) | [![Show information with actor portraits and related series from Plex](docs/screenshots/related.webp)](docs/screenshots/related.webp) |
Open the project root in Android Studio to use an existing local Android SDK instead. Set `ANDROID_HOME` and use the bundled Gradle distribution or the wrapper.
## Build from source
The first local build creates `.tools/kaleido-signing.jks`. **Keep a private backup of this file and its credentials. Every app update must use the same signing key.** Debug and release builds share this local key so the test installation can receive the release through the updater. CI uses an ephemeral validation key and publishes only the locally signed distribution APK. For alternate signing, set `KALEIDO_KEYSTORE`, `KALEIDO_STORE_PASSWORD`, `KALEIDO_KEY_ALIAS`, and `KALEIDO_KEY_PASSWORD`.
Kaleido is written in Kotlin with Jetpack Compose and Media3. On Windows, the local toolchain can be set up with `scripts/bootstrap.py`, then built with:
## Connect
```powershell
.\Build.ps1 -Release -Test
```
Open Kaleido and enter its code at [plex.tv/link](https://plex.tv/link). Settings → Sign in with Plex can link an account while keeping the current connection until successful server selection; Back cancels linking. Choose a server if more than one is available. The client tests the discovered server connections and prefers TLS. A manual server URL / token connection is also available. The credentials are AES-GCM encrypted with an Android Keystore key, never backed up, and removed on sign-out. Local HTTP servers remain supported. Account tokens are sent only to Plex account endpoints; server tokens are sent to the selected Plex server.
See the [development guide](docs/development.md) for setup and releases, the [design notes](docs/design-system.md), and [device testing](docs/runtime-verification.md).
`.env` and signing keys are ignored by Git. No test credentials are included in source code, BuildConfig, resources, or APKs. `scripts/device.py seed` is an optional debug-only provisioning helper: it sends `.env` credentials to private app data over the already-authorized ADB connection. Kaleido immediately encrypts them and deletes the staging file. Release builds never read this staging file.
## Remote and playback
D-pad moves focus, OK activates, and Back returns through details and seasons. In the player, OK shows controls; Left/Right while controls are hidden seeks; dedicated media keys control playback. The on-screen controls provide pause, seeking, audio, subtitles, next episode, and exit. Back first hides controls, then exits playback. Stopping or leaving the app reports the latest position to Plex.
Direct stream is the default, requesting original resolution and remuxing where supported, with transcoding fallback. The player gear also exposes original-file playback, transcoding, audio, subtitles, speed, quality, and chapters. Media3's SurfaceView preserves supported HDR. Actual HDR, Dolby Vision, codecs, and audio passthrough depend on the device, connected display/receiver, source profile, and server. Plex owns transcoding capability and any account entitlements. Unsupported subtitle formats use server conversion. Intro and credit buttons appear when the server supplies markers. Scrubbing displays server-generated video previews or chapter thumbnails when available; the timeline also shows buffered progress. Episode endings and Skip credits show a cancellable five-second next-episode countdown, season episodes, and related shows.
## Updates and releases
Kaleido checks [the public repository releases](https://git.elijahkuntz.com/Elijah/Kaleido/releases) on launch and foreground entry, at most once per six hours. Settings offers an immediate check. It downloads the release APK over HTTPS, checks its supplied SHA-256 when available, and verifies the package name, increasing Android version code, and installed signing certificate before opening Android's package installer. Android requires a one-time “allow from this source” permission and confirmation for each installation.
To publish a version:
1. Increment **both** fields in `version.properties` and update `CHANGELOG.md`.
2. Run `./Build.ps1 -Release -Test`, then `python scripts/package_release.py`.
3. Commit the source and `distribution/`, push `main`, and push the matching `v<versionName>` tag.
The Forgejo workflow builds, tests, and lints the source, verifies the prebuilt signed distribution, then publishes its APK and checksum using Forgejo's repository-scoped token. The private production signing key never leaves the developer machine. The checked-in APK also provides a repository-file update channel, with an immutable tag URL in `distribution/latest.json`, for installations before the first Forgejo release is ready.
## Structure and references
`PlexApi.kt` owns Plex transport and server-relative API calls; `SecureSession.kt` owns credential encryption; `KaleidoViewModel.kt` owns navigation and async screen data; `Screens.kt` and `Theme.kt` implement the TV UI; `Playback.kt` owns Media3, stream negotiation, track selection, lifecycle, and timeline reporting; `AppUpdater.kt` verifies updates. Artwork has bounded memory and disk caches. Library data is paged in batches of 100.
Implementation follows the [official Plex Media Server API](https://developer.plex.tv/pms/), [Android Compose guidance](https://developer.android.com/compose), and [Media3 documentation](https://developer.android.com/media/media3). This is an independent client, unaffiliated with Plex. No existing Plex client source is copied.
Kaleido is in active development. It is an independent project and is not affiliated with Plex.

View file

@ -6,3 +6,5 @@ HPLtv/kaleido/app/DiscoveryScreensKt**->**(**)**
HPLtv/kaleido/app/ThemeKt**->**(**)**
HPLtv/kaleido/app/NavigationSoundsKt**->**(**)**
HPLtv/kaleido/app/NavigationSoundController;->**(**)**
HPLtv/kaleido/app/TitleDetailsKt**->**(**)**
HPLtv/kaleido/app/SettingsScreenKt**->**(**)**

View file

@ -72,16 +72,16 @@ import kotlinx.coroutines.delay
}
}
@Composable fun MediaRow(vm:KaleidoViewModel,title:String,items:List<Title>,rowId:String,landscape:Boolean=false,subtitle:String?=null) {
@Composable fun MediaRow(vm:KaleidoViewModel,title:String,items:List<Title>,rowId:String,landscape:Boolean=false,subtitle:String?=null,entryFocus:FocusRequester?=null) {
Column {
Box(Modifier.padding(horizontal=Cinema.gutter)){SectionHeading(title,subtitle)}
LazyRow(contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,top=5.dp,bottom=5.dp),horizontalArrangement=Arrangement.spacedBy(if(landscape)13.dp else 12.dp),modifier=Modifier.focusRestorer()) {
itemsIndexed(items,key={_,it->it.id}){index,item->MediaTile(vm,item,"$rowId:${item.id}",landscape,onMove={anticipateTileMove(vm,items,index,it,0)})}
itemsIndexed(items,key={_,it->it.id}){index,item->MediaTile(vm,item,"$rowId:${item.id}",landscape,modifier=if(index==0&&entryFocus!=null)Modifier.focusRequester(entryFocus)else Modifier,onMove={anticipateTileMove(vm,items,index,it,0)})}
}
}
}
private fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,direction:Key,columns:Int) {
internal fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,direction:Key,columns:Int) {
val target=when(direction){
Key.DirectionLeft->if(columns==0||index%columns>0)index-1 else -1
Key.DirectionRight->if(columns==0||index%columns<columns-1)index+1 else -1
@ -92,12 +92,12 @@ private fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,d
items.getOrNull(target)?.let{vm.anticipate(it,backdrop=false)}
}
@Composable fun MediaTile(vm:KaleidoViewModel,item:Title,focusKey:String,landscape:Boolean=false,fillWidth:Boolean=false,onMove:(Key)->Unit={}) {
@Composable fun MediaTile(vm:KaleidoViewModel,item:Title,focusKey:String,landscape:Boolean=false,fillWidth:Boolean=false,initialFocus:Boolean=false,modifier:Modifier=Modifier,onMove:(Key)->Unit={}) {
var focused by remember{mutableStateOf(false)}
val requester=remember{FocusRequester()}
val scale by animateFloatAsState(if(focused)1.035f else 1f,tween(180),label="artworkFocus")
LaunchedEffect(Unit){if(vm.focusId==focusKey){delay(220);runCatching{requester.requestFocus()}}}
Column((if(fillWidth)Modifier.fillMaxWidth()else Modifier.width(if(landscape)216.dp else 132.dp)).onPreviewKeyEvent{if(it.type==KeyEventType.KeyDown)onMove(it.key);false}.graphicsLayer{scaleX=scale;scaleY=scale}.focusRequester(requester).navigationSound().onFocusChanged{focused=it.isFocused;if(it.isFocused)vm.focusId=focusKey}.clickable{vm.open(item)}) {
LaunchedEffect(Unit){if(vm.focusId==focusKey||initialFocus){delay(220);runCatching{requester.requestFocus()}}}
Column(modifier.then(if(fillWidth)Modifier.fillMaxWidth()else Modifier.width(if(landscape)216.dp else 132.dp)).onPreviewKeyEvent{if(it.type==KeyEventType.KeyDown)onMove(it.key);false}.graphicsLayer{scaleX=scale;scaleY=scale}.focusRequester(requester).navigationSound().onFocusChanged{focused=it.isFocused;if(it.isFocused)vm.focusId=focusKey}.clickable{vm.open(item)}) {
Box(Modifier.fillMaxWidth().aspectRatio(if(landscape)16f/9f else 2f/3f).graphicsLayer{shadowElevation=if(focused)12.dp.toPx()else 0f;shape=RoundedCornerShape(Cinema.radius)}.clip(RoundedCornerShape(Cinema.radius))) {
val artwork=if(landscape&&item.type=="episode")item.thumb.ifBlank{item.art}else if(landscape)item.art.ifBlank{item.thumb}else item.thumb
Artwork(vm.api,artwork,Modifier.fillMaxSize(),if(landscape)720 else 450,if(landscape)405 else 675)
@ -154,37 +154,6 @@ private fun anticipateTileMove(vm:KaleidoViewModel,items:List<Title>,index:Int,d
if(sectionMenu){val options=vm.sections.filter{it.type==vm.section?.type};ChoiceDialog("Libraries",options.map{it.title},options.indexOf(vm.section),{sectionMenu=false}){vm.chooseSection(options[it]);sectionMenu=false}}
}
@Composable fun DetailsScreen(vm:KaleidoViewModel) {
val item=vm.detail ?: return
LazyColumn(contentPadding=PaddingValues(bottom=32.dp),verticalArrangement=Arrangement.spacedBy(15.dp),modifier=Modifier.fillMaxSize()) {
item(key="details") {
Box(Modifier.fillMaxWidth().height(if(item.type in listOf("movie","episode"))432.dp else 304.dp)) {
Artwork(vm.api,item.art,Modifier.fillMaxSize(),1920,1080)
Box(Modifier.fillMaxSize().background(Brush.horizontalGradient(listOf(Ink.copy(alpha=.98f),Ink.copy(alpha=.83f),Ink.copy(alpha=.05f)))))
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(0f to Color.Black.copy(alpha=.12f),.5f to Color.Transparent,1f to Ink)))
IconControl(Icons.AutoMirrored.Outlined.ArrowBack,"Back",modifier=Modifier.padding(start=36.dp,top=18.dp)){vm.back()}
Column(Modifier.align(Alignment.CenterStart).padding(start=Cinema.gutter,top=30.dp).width(490.dp)) {
if(item.type=="episode")Text(item.grandparentTitle,color=Cinema.secondary,fontSize=12.sp,lineHeight=17.sp,fontWeight=FontWeight.Medium)
Text(item.title,color=Accent,fontSize=34.sp,lineHeight=37.sp,fontWeight=FontWeight.Bold,letterSpacing=(-1).sp,maxLines=2,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(bottom=9.dp))
Row(Modifier.fillMaxWidth(),verticalAlignment=Alignment.CenterVertically) {
Text(listOf(item.subtitle,item.contentRating).filter{it.isNotBlank()}.joinToString(" · "),color=Muted,fontSize=10.5.sp,lineHeight=16.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f,fill=false))
AudienceRatings(item,Modifier.padding(start=12.dp))
}
Text(item.summary,color=Cinema.secondary,fontSize=12.5.sp,lineHeight=19.sp,maxLines=if(item.type in listOf("movie","episode"))4 else 3,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=11.dp,bottom=18.dp))
if(item.type!="collection")Row(horizontalArrangement=Arrangement.spacedBy(8.dp)) {
ActionButton(if(item.offset>0)"Resume · ${item.offset/60000} min"else if(item.type=="show")"Watch next"else "Play",Icons.Filled.PlayArrow,primary=true,initialFocus=true){vm.play(item)}
if(item.offset>0)ActionButton("Start over",Icons.Outlined.Replay){vm.play(item,true)}
if(item.type in listOf("movie","episode"))IconControl(if(item.isWatched(vm.watchedPercent))Icons.Outlined.CheckCircle else Icons.Outlined.Check,"Mark ${if(item.isWatched(vm.watchedPercent))"unwatched"else "watched"}",selected=item.isWatched(vm.watchedPercent)){vm.mark(item)}
}
if(item.media.isNotEmpty())Text(item.media.first().let{m->listOf(m.resolution.uppercase(),m.videoCodec.uppercase(),m.audioCodec.uppercase()).joinToString(" · ")},color=Muted,fontSize=9.sp,lineHeight=13.sp,modifier=Modifier.padding(top=16.dp))
if(item.cast.isNotEmpty())Text(item.cast.take(5).joinToString(" · "),color=Cinema.quiet,fontSize=10.sp,lineHeight=15.sp,maxLines=2,modifier=Modifier.padding(top=8.dp))
}
}
}
if(vm.children.isNotEmpty())item{MediaRow(vm,if(item.type=="show")"Seasons"else if(item.type=="season")"Episodes"else "In this collection",vm.children,"children:${item.id}",landscape=item.type=="season")}
}
}
@Composable fun SearchScreen(vm:KaleidoViewModel) {
Column(Modifier.fillMaxSize().padding(horizontal=Cinema.gutter)) {
Row(Modifier.fillMaxWidth().padding(top=12.dp,bottom=18.dp),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(25.dp)) {

View file

@ -21,7 +21,7 @@ import coil.request.Disposable
import java.util.concurrent.Executors
import kotlinx.coroutines.asCoroutineDispatcher
data class Page(val kind: String="home",val id: String="",val name: String="",val returnFocus: String="")
data class Page(val kind: String="home",val id: String="",val name: String="",val returnFocus: String="",val actor:CastMember?=null)
private data class SectionContent(val hubs:List<Hub>,val genres:List<Pair<String,String>>,val library:LibraryPage)
class KaleidoViewModel(app: Application): AndroidViewModel(app) {
val application = app as KaleidoApplication
@ -47,6 +47,9 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
var allTitles by mutableStateOf(false); 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
var actorTitles by mutableStateOf(emptyList<Title>()); private set
var markingId by mutableStateOf<String?>(null); private set
var searchResults by mutableStateOf(emptyList<Title>()); private set
var query by mutableStateOf(""); private set
var pin by mutableStateOf<Pin?>(null); private set
@ -174,6 +177,10 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
fun switchServer()=launchLoad { require(accountToken.isNotBlank()){ "This connection uses a server token. Sign out to link a Plex account." };servers=api.servers(accountToken) }
fun tab(kind: String){if(pages.size==1&&page.kind==kind)return;cancelAnticipation();loadJob?.cancel();busy=false;focusId="";if(kind in listOf("movies","tv"))allTitles=false;pages=listOf(Page(kind));loadPage(true)}
fun open(item: Title){detailsCache[item.id]=item;pages=pages+Page(if(item.type in listOf("collection","season")) "group" else "details",item.id,item.title,focusId);loadPage()}
fun openActor(actor:CastMember){
if(actor.id.isBlank())return
pages=pages+Page("actor",actor.id,actor.name,focusId,actor);focusId="";loadPage()
}
fun back(): Boolean {
if(playing!=null){stopPlayback();return true}
if(pages.size>1){focusId=page.returnFocus;pages=pages.dropLast(1);loadPage();return true}
@ -202,7 +209,23 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
discoverHubs=rows;genres=genreList;library=p.items;total=p.total
}}
}
"details","group" -> { detail=detailsCache[page.id];children=emptyList();launchLoad { val id=page.id;val d=detailsCache[id]?.let{previews.details(it)} ?: api.details(id);detail=d;detailsCache[id]=d;previews.remember(d);if(d.type in listOf("show","season","collection"))children=api.children(id) } }
"details","group" -> {
detail=detailsCache[page.id];children=emptyList();detailRelated=emptyList()
launchLoad {
val id=page.id;val d=detailsCache[id]?.let{previews.details(it)} ?: api.details(id)
detail=d;detailsCache[id]=d;previews.remember(d)
coroutineScope {
val groups=async{if(d.type in listOf("show","season","collection"))api.children(id)else emptyList()}
val related=async{if(d.type=="show")try{api.relatedShows(id).filter{it.id!=id}}catch(e:CancellationException){throw e}catch(_:Exception){emptyList()}else emptyList()}
children=groups.await();detailRelated=related.await()
}
}
}
"actor" -> {
val actor=page.actor ?: return
actorTitles=emptyList()
launchLoad {actorTitles=api.actorTitles(actor,sections)}
}
"search" -> {busy=false;error=null}
"settings" -> {busy=false;error=null}
}
@ -213,22 +236,44 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
private fun refreshLibrary()=launchLoad { val p=api.library(section?.id ?: return@launchLoad,0,sort,genre,unwatched);library=p.items;total=p.total }
fun more(){if(busy||library.size>=total)return;launchLoad {val p=api.library(section?.id ?: return@launchLoad,library.size,sort,genre,unwatched);library=(library+p.items).distinctBy {it.id};total=p.total}}
fun search(text: String){query=text;searchJob?.cancel();searchJob=viewModelScope.launch {delay(350);if(text.isBlank()){searchResults=emptyList();return@launch};busy=true;error=null;try{searchResults=api.search(text)}catch(e:CancellationException){throw e}catch(e:Exception){error=e.message}finally{busy=false}}}
fun mark(item: Title)=launchLoad {
api.watched(item,!item.isWatched(watchedPercent));refreshWatchedItems(item)
fun mark(item: Title) {
if(markingId!=null)return
markingId=item.id
// A navigation request must not cancel an already submitted Plex watched write.
viewModelScope.launch {
try {
api.watched(item,!item.isWatched(watchedPercent));refreshWatchedItems(item)
homeHubs=loadHome()
}catch(e:CancellationException){throw e}catch(e:Exception){error=e.message ?: "Plex could not update this title."}finally{markingId=null}
}
}
fun refreshWatched(item:Title){viewModelScope.launch{try{refreshWatchedItems(item)}catch(e:CancellationException){throw e}catch(_:Exception){sectionCache.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)
if(d.type in listOf("show","season")) {
api.children(d.id).forEach{updated[it.id]=it}
api.allEpisodes(d.id).forEach{updated[it.id]=it}
}
if(d.type=="episode")for(id in listOf(d.parentId,d.grandparentId).filter{it.isNotBlank()}) {
try{updated[id]=api.details(id)}catch(e:CancellationException){throw e}catch(_:Exception){detailsCache.remove(id)}
}
previews.clear();updated.values.forEach{previews.remember(it)};detailsCache.putAll(updated);detail=detail?.let{updated[it.id] ?: it}
fun refreshed(hubs:List<Hub>)=hubs.map{h->h.copy(items=h.items.map{updated[it.id] ?: it})}
// Only /metadata details are complete; children/allLeaves are summary records.
// Merge their watched fields without poisoning full metadata/cast caches.
val fullIds=if(d.type=="episode")setOf(d.id,d.parentId,d.grandparentId)else setOf(d.id)
fun refreshedTitle(existing:Title):Title {
val fresh=updated[existing.id] ?: return existing
return if(existing.id in fullIds)fresh else existing.copy(watched=fresh.watched,offset=fresh.offset,leafCount=fresh.leafCount,viewedLeafCount=fresh.viewedLeafCount)
}
previews.clear();updated.keys.forEach{detailsCache.remove(it)}
updated.filterKeys{it in fullIds}.values.forEach{previews.remember(it);detailsCache[it.id]=it}
detail=detail?.let(::refreshedTitle)
fun refreshed(hubs:List<Hub>)=hubs.map{h->h.copy(items=h.items.map(::refreshedTitle))}
homeHubs=refreshed(homeHubs);discoverHubs=refreshed(discoverHubs)
library=library.map{updated[it.id] ?: it};children=children.map{updated[it.id] ?: it}
searchResults=searchResults.map{updated[it.id] ?: it}
homeFeatures=homeFeatures.map{it.copy(item=updated[it.item.id] ?: it.item)}.filterNot{it.item.fullyWatched}
library=library.map(::refreshedTitle);children=children.map(::refreshedTitle)
searchResults=searchResults.map(::refreshedTitle)
actorTitles=actorTitles.map(::refreshedTitle);detailRelated=detailRelated.map(::refreshedTitle)
homeFeatures=homeFeatures.map{it.copy(item=refreshedTitle(it.item))}.filterNot{it.item.fullyWatched}
sectionCache.clear()
}
fun play(item: Title,fromStart: Boolean=false)=launchLoad {

View file

@ -10,6 +10,11 @@ data class Part(val id: String, val key: String, val streams: List<Stream>,val i
data class Media(val id: String, val container: String, val videoCodec: String, val audioCodec: String, val resolution: String, val width: Int, val height: Int, val bitrate: Int, val parts: List<Part>)
data class Marker(val type: String, val start: Long, val end: Long)
data class Chapter(val index:Int,val title:String,val start:Long,val end:Long,val thumb:String)
data class CastMember(val id:String,val name:String,val role:String,val thumb:String) {
companion object {
fun parse(j:JSONObject)=CastMember(j.optString("id").ifBlank{j.optString("filter").removePrefix("actor=")}.takeIf{it.all(Char::isDigit)}.orEmpty(),j.optString("tag"),j.optString("role"),j.optString("thumb"))
}
}
data class Title(
val id: String, val key: String, val type: String, val title: String, val summary: String,
val thumb: String, val art: String, val year: String, val duration: Long, val offset: Long,
@ -18,7 +23,8 @@ data class Title(
val index: Int, val parentIndex: Int, val leafCount: Int, val viewedLeafCount: Int,
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 audienceScore: AudienceScore? = null, val releaseDate: String = "",val audienceScores:List<AudienceScore> = emptyList(),
val castMembers:List<CastMember> = emptyList()
) {
val remainingEpisodes get() = (leafCount-viewedLeafCount).coerceAtLeast(0)
val fullyWatched get() = isWatched()
@ -45,7 +51,8 @@ data class Title(
j.optJSONArray("Image").objects().firstOrNull{it.optString("type")=="coverPoster"}?.optString("url").orEmpty(),
j.optJSONArray("Image").objects().firstOrNull{it.optString("type")=="snapshot"}?.optString("url").orEmpty(),
j.optJSONArray("Chapter").objects().map{Chapter(it.optInt("index"),it.optString("title","Chapter ${it.optInt("index")+1}"),it.optLong("startTimeOffset"),it.optLong("endTimeOffset"),it.optString("thumb"))},
AudienceScore.parse(j),j.optString("originallyAvailableAt"),AudienceScore.parseAll(j)
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}}
)
}
}

View file

@ -77,15 +77,28 @@ class PlexApi(val clientId: String) {
LibraryPage(d.optJSONArray("Metadata").objects().map(Title::parse),d.optInt("totalSize",d.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 = 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> = container("/library/metadata/$id/related").optJSONArray("Hub").objects().flatMap{it.optJSONArray("Metadata").objects()}.map(Title::parse).filter{it.type=="show"}.distinctBy{it.id}
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}}
/** Actor tags are server-local. Query each accessible movie/show library, with pagination. */
suspend fun actorTitles(actor:CastMember,sections:List<Section>):List<Title> = coroutineScope {
require(actor.id.isNotBlank()){"This cast member has no Plex library identifier."}
sections.filter{it.type in listOf("movie","show")}.map { section->async {
val found=mutableListOf<Title>();var start=0
do {
val data=container("/library/sections/${section.id}/all",mapOf("actor" to actor.id,"sort" to "titleSort:asc","X-Plex-Container-Start" to start.toString(),"X-Plex-Container-Size" to "100"))
val batch=withContext(Dispatchers.Default){data.optJSONArray("Metadata").objects().map(Title::parse)}
found.addAll(batch.filter{it.type in listOf("movie","show")});start+=batch.size
}while(batch.isNotEmpty()&&start<data.optInt("totalSize",start))
found
}}.awaitAll().flatten().distinctBy{it.id}.sortedBy{it.title.lowercase(java.util.Locale.ROOT)}
}
fun previewPath(item:Title,time:Long):String? {
val part=item.media.firstOrNull()?.parts?.firstOrNull()
if(part!=null&&part.indexes.split(',').contains("sd"))return "/library/parts/${part.id}/indexes/sd/${time.coerceAtLeast(0)/5000*5000}"
return item.chapters.lastOrNull{it.start<=time}?.thumb?.takeIf{it.isNotBlank()}
}
suspend fun children(id: String): List<Title> = container("/library/metadata/$id/children").optJSONArray("Metadata").objects().map(Title::parse)
suspend fun allEpisodes(id: String): List<Title> = container("/library/metadata/$id/allLeaves").optJSONArray("Metadata").objects().map(Title::parse)
suspend fun allEpisodes(id: String): List<Title> = withContext(Dispatchers.Default){container("/library/metadata/$id/allLeaves").optJSONArray("Metadata").objects().map(Title::parse)}
suspend fun collections(section: String): List<Title> = container("/library/sections/$section/collections").optJSONArray("Metadata").objects().map(Title::parse)
suspend fun search(query: String): List<Title> = container("/hubs/search",mapOf("query" to query,"limit" to "60","includeCollections" to "1")).optJSONArray("Hub").objects().flatMap { it.optJSONArray("Metadata").objects().map(Title::parse) }.filter { it.type in listOf("movie","show","episode","collection") }.distinctBy { it.id }
suspend fun watched(item: Title, watched: Boolean) { container(if(watched) "/:/scrobble" else "/:/unscrobble",mapOf("key" to item.id,"identifier" to "com.plexapp.plugins.library")) }

View file

@ -46,12 +46,12 @@ import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.input.key.onPreviewKeyEvent
import java.io.File
@Composable fun Artwork(api: PlexApi,path: String,modifier: Modifier=Modifier,width: Int=600,height: Int=900,animate:Boolean=true) {
@Composable fun Artwork(api: PlexApi,path: String,modifier: Modifier=Modifier,width: Int=600,height: Int=900,animate:Boolean=true,contentScale:ContentScale=ContentScale.Crop) {
val context=LocalContext.current
// The server already scales to width × height. Stating that size lets Coil resolve cache
// hits while composing, instead of each painter waiting for layout to measure it.
val model=remember(path,api.session?.server,width,height,animate){api.image(path,width,height)?.let {u -> ImageRequest.Builder(context).data(u).apply {api.headers().forEach{(k,v)->addHeader(k,v)}}.size(width,height).precision(Precision.INEXACT).crossfade(if(animate)180 else 0).build()}}
AsyncImage(model=model,contentDescription=null,contentScale=ContentScale.Crop,modifier=modifier.background(Panel))
AsyncImage(model=model,contentDescription=null,contentScale=contentScale,modifier=modifier.background(Panel))
}
@Composable fun KaleidoApp(vm: KaleidoViewModel,install: (File)->Unit) {
KaleidoTheme {
@ -97,14 +97,15 @@ import java.io.File
alpha=.18f+.82f*entrance.value
translationX=with(density){28.dp.toPx()}*direction*(1f-entrance.value)
}) {
if(!immersive&&vm.page.kind !in listOf("details","group")) TopBar(vm)
if(!immersive&&vm.page.kind !in listOf("details","group","actor")) TopBar(vm)
stateHolder.SaveableStateProvider(screenKey) {
when(vm.page.kind){
"home"->HomeScreen(vm,discoveryFocus)
"movies","tv"->LibraryScreen(vm,discoveryFocus)
"details","group"->DetailsScreen(vm)
"actor"->ActorScreen(vm)
"search"->SearchScreen(vm)
"settings"->SettingsScreen(vm,install)
"settings"->CohesiveSettingsScreen(vm,install)
}
}
}
@ -140,81 +141,6 @@ val sortLabels=listOf("titleSort:asc" to "Title: A–Z","titleSort:desc" to "Tit
@Composable fun ServerPicker(vm: KaleidoViewModel) {
Column(Modifier.fillMaxSize().padding(60.dp),verticalArrangement=Arrangement.spacedBy(18.dp)){Brand();Spacer(Modifier.height(20.dp));Text("Choose your Plex server",color=Color.White,fontSize=32.sp,fontWeight=FontWeight.Bold);vm.servers.forEachIndexed{i,s->TvButton(s.name,initialFocus=i==0,onClick={vm.chooseServer(s)})}}
}
@Composable fun SettingsScreen(vm: KaleidoViewModel,install: (File)->Unit) {
var confirmSignOut by remember{mutableStateOf(false)};var qualityDialog by remember{mutableStateOf(false)};var watchedDialog by remember{mutableStateOf(false)}
LaunchedEffect(vm.downloadedApk){vm.downloadedApk?.let(install)}
// Returning from the package installer can leave nothing focused; the next D-pad press
// would then search from the top bar and open Home. Put focus back on the update actions.
var settingsFocused by remember{mutableStateOf(false)}
val updateFocus=remember{FocusRequester()}
val paused=remember{booleanArrayOf(false)}
LifecycleResumeEffect(Unit){
if(paused[0]){vm.installerReturned();if(!settingsFocused)runCatching{updateFocus.requestFocus()}}
onPauseOrDispose{paused[0]=true}
}
// TV's default scrolling pins focus a third of the way down, so even sideways moves
// shifted this page. Scroll only as far as needed to keep the focused control visible.
val density=LocalDensity.current
val scroll=remember(density){MinimalScroll(with(density){56.dp.toPx()})}
CompositionLocalProvider(LocalBringIntoViewSpec provides scroll) {
LazyColumn(Modifier.onFocusChanged{settingsFocused=it.hasFocus},contentPadding=PaddingValues(horizontal=Cinema.gutter,vertical=17.dp),verticalArrangement=Arrangement.spacedBy(16.dp)) {
item {Text("Settings",color=Accent,fontSize=29.sp,lineHeight=34.sp,fontWeight=FontWeight.SemiBold,letterSpacing=(-.8).sp)}
item{SettingsPanel("Plex connection") {Text(vm.session?.serverName.orEmpty(),color=Color.White,fontSize=20.sp,fontWeight=FontWeight.Bold);Text(if(vm.accountToken.isBlank())"Server connection · Link your Plex account to discover your servers"else "Plex account linked · Session encrypted with Android Keystore",color=Muted,fontSize=12.sp);Spacer(Modifier.height(14.dp));Row(horizontalArrangement=Arrangement.spacedBy(10.dp)){TvButton("Sign in with Plex",initialFocus=true,onClick={vm.beginAccountLink()});if(vm.accountToken.isNotBlank())TvButton("Choose server",onClick={vm.switchServer()});TvButton("Sign out",onClick={confirmSignOut=true})}}}
item{SettingsPanel("Playback") {
TvButton("Quality: "+vm.streamQuality.label,onClick={qualityDialog=true})
Text("Original quality plays the source video without conversion and is the default. A resolution asks Plex to convert, which helps on slower connections. Quality, audio, subtitles and speed can also be changed in the player.",color=Muted,fontSize=12.sp,lineHeight=18.sp,modifier=Modifier.padding(top=10.dp))
}}
item{SettingsPanel("Watched status") {
TvButton("Mark watched at ${vm.watchedPercent}%",onClick={watchedDialog=true})
Text("A resumed title gets its checkmark at this playback percentage. Completed titles keep their Plex watched status.",color=Muted,fontSize=12.sp,lineHeight=18.sp,modifier=Modifier.padding(top=10.dp))
}}
item{SettingsPanel("Interface") {
TvButton("Navigation sounds: "+if(vm.navigationSounds)"On"else "Off",onClick={vm.chooseNavigationSounds(!vm.navigationSounds)})
Text("Play the TV's system tap when focus moves. Follows your TV's sound-effects setting.",color=Muted,fontSize=12.sp,lineHeight=18.sp,modifier=Modifier.padding(top=10.dp))
}}
item{SettingsPanel("Software updates") {
Text("Kaleido ${BuildConfig.VERSION_NAME}",color=Color.White,fontSize=20.sp,fontWeight=FontWeight.Bold)
Text(vm.updateStatus,color=Muted,fontSize=12.sp,modifier=Modifier.padding(vertical=8.dp))
Text("Updates are checked automatically every six hours while Kaleido is in use.",color=Muted,fontSize=12.sp)
// Notes sit above the actions, so scrolling to the buttons always reveals them.
vm.update?.let{if(it.notes.isNotBlank()){
Spacer(Modifier.height(16.dp));Eyebrow("What's new in ${it.version}")
Text(it.notes.take(1800),color=Cinema.secondary,fontSize=11.sp,lineHeight=17.sp,modifier=Modifier.padding(top=7.dp))
}}
Spacer(Modifier.height(16.dp))
Row(Modifier.focusRequester(updateFocus).focusRestorer(),horizontalArrangement=Arrangement.spacedBy(10.dp)) {
TvButton("Check for updates",onClick={vm.checkUpdate()})
// The update action never leaves while focused; it reports progress in place.
vm.update?.let{release->
val label=when{vm.downloading->"Downloading… ${(vm.downloadProgress*100).toInt()}%";vm.readyApk!=null->"Install ${release.version}";else->"Download & install ${release.version}"}
TvButton(label,primary=true,onClick={vm.downloadUpdate()})
}
}
if(vm.downloading)LinearProgressIndicator(progress={vm.downloadProgress},modifier=Modifier.padding(top=14.dp).width(340.dp).height(3.dp),color=Accent,trackColor=Color.White.copy(alpha=.14f),gapSize=0.dp,drawStopIndicator={})
Text("git.elijahkuntz.com/Elijah/Kaleido",color=Accent,fontSize=10.sp,modifier=Modifier.padding(top=14.dp))
}}
}
}
if(confirmSignOut)ChoiceDialog("Sign out of Plex?",listOf("Keep watching","Sign out"),0,{confirmSignOut=false}){if(it==1)vm.signOut();confirmSignOut=false}
if(watchedDialog) {
val thresholds=listOf(50,60,70,75,80,85,90,95,100)
ChoiceDialog("Mark watched after",thresholds.map{"$it%"},thresholds.indexOf(vm.watchedPercent),{watchedDialog=false}){vm.chooseWatchedPercent(thresholds[it]);watchedDialog=false}
}
if(qualityDialog)ChoiceDialog("Playback quality",StreamQuality.entries.map{it.label},vm.streamQuality.ordinal,{qualityDialog=false}){vm.chooseStreamQuality(StreamQuality.entries[it]);qualityDialog=false}
}
/** Scroll only as far as needed to reveal the focused control, keeping [margin] px clear of the edges. */
private class MinimalScroll(private val margin:Float):BringIntoViewSpec {
override fun calculateScrollDistance(offset:Float,size:Float,containerSize:Float):Float {
val leading=offset-margin;val trailing=offset+size+margin
return when {
leading>=0f&&trailing<=containerSize->0f
leading<0f&&trailing>containerSize->0f
kotlin.math.abs(leading)<kotlin.math.abs(trailing-containerSize)->leading
else->trailing-containerSize
}
}
}
@Composable fun SettingsPanel(title: String,content: @Composable ColumnScope.()->Unit) {Column(Modifier.fillMaxWidth().clip(RoundedCornerShape(9.dp)).background(Panel.copy(alpha=.65f)).padding(18.dp)){Eyebrow(title);Spacer(Modifier.height(11.dp));content()}}
@Composable fun EmptyState(title: String,message: String){Column(Modifier.padding(52.dp),verticalArrangement=Arrangement.spacedBy(12.dp)){Text(title,color=Color.White,fontSize=26.sp,fontWeight=FontWeight.Bold);Text(message,color=Muted,fontSize=14.sp)}}
@Composable fun ErrorDialog(message: String,dismiss: ()->Unit,retry: ()->Unit) {Dialog(onDismissRequest=dismiss){Column(Modifier.width(390.dp).clip(RoundedCornerShape(12.dp)).background(Panel).padding(23.dp)){Text("Something needs attention",color=Accent,fontSize=20.sp,lineHeight=26.sp,fontWeight=FontWeight.SemiBold);Text(message,color=Muted,fontSize=12.sp,lineHeight=19.sp,modifier=Modifier.padding(vertical=17.dp));Row(horizontalArrangement=Arrangement.spacedBy(9.dp)){TvButton("Try again",primary=true,initialFocus=true,onClick={dismiss();retry()});TvButton("Dismiss",onClick=dismiss)}}}}
@Composable fun ChoiceDialog(title: String,options: List<String>,selected: Int,dismiss: ()->Unit,choose: (Int)->Unit) {Dialog(onDismissRequest=dismiss){Column(Modifier.width(360.dp).heightIn(max=390.dp).clip(RoundedCornerShape(12.dp)).background(Panel).padding(21.dp)){Text(title,color=Accent,fontSize=20.sp,lineHeight=26.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(bottom=14.dp));LazyColumn(verticalArrangement=Arrangement.spacedBy(4.dp)){items(options.size){i->TvButton(options[i],Modifier.fillMaxWidth(),selected=i==selected,initialFocus=i==selected||selected<0&&i==0,onClick={choose(i)})}}}}}

View file

@ -0,0 +1,464 @@
@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
package tv.kaleido.app
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.focusGroup
import androidx.compose.foundation.gestures.BringIntoViewSpec
import androidx.compose.foundation.gestures.LocalBringIntoViewSpec
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusProperties
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.focusRestorer
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.LifecycleResumeEffect
import kotlinx.coroutines.delay
import java.io.File
/** Compact TV settings with a stable category rail and explicit left/right focus routing. */
@Composable
fun CohesiveSettingsScreen(vm: KaleidoViewModel, install: (File) -> Unit) {
val categories = remember { listOf("Connection", "Playback", "Interface", "Updates") }
var selectedCategory by rememberSaveable { mutableIntStateOf(0) }
var confirmSignOut by remember { mutableStateOf(false) }
var qualityDialog by remember { mutableStateOf(false) }
var watchedDialog by remember { mutableStateOf(false) }
val categoryFocus = remember { List(categories.size) { FocusRequester() } }
val entryFocus = remember { List(categories.size) { FocusRequester() } }
val watchedFocus = remember { FocusRequester() }
val serverActionFocus = remember { FocusRequester() }
val signOutActionFocus = remember { FocusRequester() }
val updateFocus = remember { FocusRequester() }
val updateDownloadFocus = remember { FocusRequester() }
var settingsFocused by remember { mutableStateOf(false) }
val paused = remember { booleanArrayOf(false) }
LaunchedEffect(vm.downloadedApk) { vm.downloadedApk?.let(install) }
LaunchedEffect(Unit) {
delay(140)
runCatching { entryFocus[selectedCategory].requestFocus() }
}
LifecycleResumeEffect(Unit) {
if (paused[0]) {
vm.installerReturned()
if (!settingsFocused) runCatching { updateFocus.requestFocus() }
}
onPauseOrDispose { paused[0] = true }
}
Column(
Modifier.fillMaxSize()
.background(Ink)
.onFocusChanged { settingsFocused = it.hasFocus }
.padding(horizontal = Cinema.gutter, vertical = 22.dp)
) {
Row(verticalAlignment = Alignment.Bottom) {
Column(Modifier.weight(1f)) {
Text(
"Settings",
color = Accent,
fontSize = 29.sp,
lineHeight = 34.sp,
fontWeight = FontWeight.SemiBold,
letterSpacing = (-.8).sp
)
Text(
"Playback, preferences and software updates",
color = Muted,
fontSize = 11.sp,
lineHeight = 15.sp,
modifier = Modifier.padding(top = 3.dp)
)
}
Eyebrow(categories[selectedCategory])
}
Spacer(Modifier.height(25.dp))
Row(Modifier.weight(1f).fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(28.dp)) {
Column(
Modifier.width(205.dp).fillMaxHeight().focusGroup(),
verticalArrangement = Arrangement.spacedBy(5.dp)
) {
Eyebrow("Categories")
Spacer(Modifier.height(7.dp))
categories.forEachIndexed { index, category ->
SettingsCategoryItem(
label = category,
selected = selectedCategory == index,
requester = categoryFocus[index],
upTarget = categoryFocus[(index - 1).coerceAtLeast(0)],
downTarget = categoryFocus[(index + 1).coerceAtMost(categories.lastIndex)],
rightTarget = entryFocus[index],
onFocused = { selectedCategory = index },
onClick = { selectedCategory = index }
)
}
}
Box(Modifier.width(1.dp).fillMaxHeight().background(Color.White.copy(alpha = .10f)))
CompositionLocalProvider(LocalBringIntoViewSpec provides SettingsScroll) {
Column(
Modifier.weight(1f).fillMaxHeight()
.verticalScroll(remember(selectedCategory) { ScrollState(0) })
.focusGroup(),
verticalArrangement = Arrangement.spacedBy(20.dp)
) {
when (selectedCategory) {
0 -> {
SettingsSectionTitle("Plex account", "Manage the server and account used by Kaleido.")
Column(verticalArrangement = Arrangement.spacedBy(5.dp)) {
Text(
vm.session?.serverName.orEmpty().ifBlank { "Plex connection" },
color = Accent,
fontSize = 19.sp,
lineHeight = 24.sp,
fontWeight = FontWeight.SemiBold
)
Text(
if (vm.accountToken.isBlank()) {
"Server connection · Link your Plex account to discover your servers"
} else {
"Plex account linked · Session encrypted with Android Keystore"
},
color = Muted,
fontSize = 11.sp,
lineHeight = 16.sp
)
}
Row(horizontalArrangement = Arrangement.spacedBy(9.dp)) {
SettingsActionButton(
"Sign in with Plex",
requester = entryFocus[0],
leftTarget = categoryFocus[0],
rightTarget = if (vm.accountToken.isNotBlank()) serverActionFocus else signOutActionFocus,
onClick = { vm.beginAccountLink() }
)
if (vm.accountToken.isNotBlank()) {
SettingsActionButton(
"Choose server",
requester = serverActionFocus,
leftTarget = categoryFocus[0],
rightTarget = signOutActionFocus,
onClick = { vm.switchServer() }
)
}
SettingsActionButton(
"Sign out",
requester = signOutActionFocus,
leftTarget = categoryFocus[0],
onClick = { confirmSignOut = true }
)
}
}
1 -> {
SettingsSectionTitle("Playback", "Choose how Plex delivers video and when a title counts as watched.")
SettingsValueRow(
title = "Playback quality",
description = "Original plays the source; a resolution asks Plex to convert.",
value = vm.streamQuality.label,
requester = entryFocus[1],
leftTarget = categoryFocus[1],
onClick = { qualityDialog = true }
)
SettingsValueRow(
title = "Watched status",
description = "A resumed title receives its checkmark at this playback percentage.",
value = "${vm.watchedPercent}%",
requester = watchedFocus,
leftTarget = categoryFocus[1],
onClick = { watchedDialog = true }
)
Text(
"Completed titles keep their Plex watched status.",
color = Cinema.quiet,
fontSize = 10.sp,
lineHeight = 14.sp,
modifier = Modifier.padding(start = 1.dp, top = 1.dp)
)
}
2 -> {
SettingsSectionTitle("Interface", "Control the small cues Kaleido plays as you browse.")
SettingsValueRow(
title = "Navigation sounds",
description = "Play the TV's system tap when focus moves. Follows the TV sound-effects setting.",
value = if (vm.navigationSounds) "On" else "Off",
requester = entryFocus[2],
leftTarget = categoryFocus[2],
onClick = { vm.chooseNavigationSounds(!vm.navigationSounds) }
)
}
else -> {
SettingsSectionTitle("Software updates", "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)
Text("Updates are checked automatically every six hours while Kaleido is in use.", color = Muted, fontSize = 10.sp, lineHeight = 15.sp)
}
vm.update?.let { release ->
if (release.notes.isNotBlank()) {
Column(verticalArrangement = Arrangement.spacedBy(5.dp)) {
Eyebrow("What's new in ${release.version}")
Text(
release.notes.take(1800),
color = Cinema.secondary,
fontSize = 10.sp,
lineHeight = 15.sp
)
}
}
}
Row(
Modifier.focusRequester(updateFocus).focusRestorer(),
horizontalArrangement = Arrangement.spacedBy(9.dp)
) {
SettingsActionButton(
"Check for updates",
requester = entryFocus[3],
leftTarget = categoryFocus[3],
rightTarget = if (vm.update != null) updateDownloadFocus else null,
onClick = { vm.checkUpdate() }
)
vm.update?.let { release ->
val label = when {
vm.downloading -> "Downloading… ${(vm.downloadProgress * 100).toInt()}%"
vm.readyApk != null -> "Install ${release.version}"
else -> "Download & install ${release.version}"
}
SettingsActionButton(
label,
requester = updateDownloadFocus,
leftTarget = categoryFocus[3],
primary = true,
onClick = { vm.downloadUpdate() }
)
}
}
if (vm.downloading) {
androidx.compose.material3.LinearProgressIndicator(
progress = { vm.downloadProgress },
modifier = Modifier.width(340.dp).height(3.dp),
color = Accent,
trackColor = Color.White.copy(alpha = .14f),
gapSize = 0.dp,
drawStopIndicator = {}
)
}
Text("git.elijahkuntz.com/Elijah/Kaleido", color = Accent, fontSize = 10.sp)
}
}
}
}
}
}
if (confirmSignOut) {
ChoiceDialog("Sign out of Plex?", listOf("Keep watching", "Sign out"), 0, { confirmSignOut = false }) {
if (it == 1) vm.signOut()
confirmSignOut = false
}
}
if (watchedDialog) {
val thresholds = listOf(50, 60, 70, 75, 80, 85, 90, 95, 100)
ChoiceDialog("Mark watched after", thresholds.map { "$it%" }, thresholds.indexOf(vm.watchedPercent), { watchedDialog = false }) {
vm.chooseWatchedPercent(thresholds[it])
watchedDialog = false
}
}
if (qualityDialog) {
ChoiceDialog("Playback quality", StreamQuality.entries.map { it.label }, vm.streamQuality.ordinal, { qualityDialog = false }) {
vm.chooseStreamQuality(StreamQuality.entries[it])
qualityDialog = false
}
}
}
/** Keep sideways moves still, scrolling only when a control is outside the pane. */
private object SettingsScroll:BringIntoViewSpec {
override fun calculateScrollDistance(offset:Float,size:Float,containerSize:Float):Float = when {
offset<0f->offset
offset+size>containerSize->offset+size-containerSize
else->0f
}
}
@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)
}
}
@Composable
private fun SettingsCategoryItem(
label: String,
selected: Boolean,
requester: FocusRequester,
upTarget: FocusRequester,
downTarget: FocusRequester,
rightTarget: FocusRequester,
onFocused: () -> Unit,
onClick: () -> Unit
) {
var focused by remember { mutableStateOf(false) }
val background by animateColorAsState(
if (focused) Accent else if (selected) Color.White.copy(alpha = .09f) else Color.Transparent,
tween(150),
label = "settingsCategoryBackground"
)
val scale by animateFloatAsState(if (focused) 1.025f else 1f, tween(160), label = "settingsCategoryScale")
Row(
Modifier.fillMaxWidth().height(40.dp)
.graphicsLayer { scaleX = scale; scaleY = scale }
.focusRequester(requester)
.focusProperties {
left = FocusRequester.Cancel
right = rightTarget
up = upTarget
down = downTarget
}
.navigationSound()
.onFocusChanged {
focused = it.isFocused
if (it.isFocused) onFocused()
}
.clip(RoundedCornerShape(Cinema.radius))
.background(background)
.clickable(onClick = onClick)
.padding(horizontal = 11.dp),
verticalAlignment = Alignment.CenterVertically
) {
Box(
Modifier.width(2.dp).height(17.dp)
.background(if (selected) (if (focused) Ink else Accent.copy(alpha = .72f)) else Color.Transparent, RoundedCornerShape(2.dp))
)
Text(
label,
color = if (focused) Ink else if (selected) Accent else Muted,
fontSize = 12.sp,
lineHeight = 16.sp,
fontWeight = if (focused || selected) FontWeight.SemiBold else FontWeight.Medium,
modifier = Modifier.padding(start = 10.dp)
)
}
}
@Composable
private fun SettingsValueRow(
title: String,
description: String,
value: String,
requester: FocusRequester,
leftTarget: FocusRequester,
rightTarget: FocusRequester? = null,
onClick: () -> Unit
) {
var focused by remember { mutableStateOf(false) }
val background by animateColorAsState(if (focused) Accent else Color.White.copy(alpha = .045f), tween(150), label = "settingsValueBackground")
val foreground = if (focused) Ink else Accent
Row(
Modifier.fillMaxWidth().heightIn(min = 58.dp)
.focusRequester(requester)
.focusProperties {
left = leftTarget
right = rightTarget ?: FocusRequester.Cancel
}
.navigationSound()
.onFocusChanged { focused = it.isFocused }
.clip(RoundedCornerShape(Cinema.radius))
.background(background)
.clickable(onClick = onClick)
.padding(horizontal = 14.dp, vertical = 9.dp),
verticalAlignment = Alignment.CenterVertically
) {
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(title, color = foreground, fontSize = 12.sp, lineHeight = 16.sp, fontWeight = FontWeight.SemiBold)
Text(
description,
color = if (focused) Ink.copy(alpha = .72f) else Muted,
fontSize = 10.sp,
lineHeight = 14.sp,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
}
Spacer(Modifier.width(15.dp))
Text(
value,
color = if (focused) Ink else Accent,
fontSize = 11.sp,
lineHeight = 15.sp,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.widthIn(max = 190.dp).padding(start = 5.dp)
)
}
}
@Composable
private fun SettingsActionButton(
label: String,
requester: FocusRequester,
leftTarget: FocusRequester,
rightTarget: FocusRequester? = null,
primary: Boolean = false,
onClick: () -> Unit
) {
var focused by remember { mutableStateOf(false) }
val background by animateColorAsState(
if (focused) Accent else if (primary) Color.White.copy(alpha = .21f) else Color.White.copy(alpha = .09f),
tween(150),
label = "settingsActionBackground"
)
val scale by animateFloatAsState(if (focused) 1.025f else 1f, tween(160), label = "settingsActionScale")
Box(
Modifier.height(36.dp).graphicsLayer { scaleX = scale; scaleY = scale }
.focusRequester(requester)
.focusProperties {
left = leftTarget
right = rightTarget ?: FocusRequester.Cancel
}
.navigationSound()
.onFocusChanged { focused = it.isFocused }
.clip(RoundedCornerShape(Cinema.radius))
.background(background)
.clickable(onClick = onClick)
.padding(horizontal = 13.dp),
contentAlignment = Alignment.Center
) {
Text(
label,
color = if (focused) Ink else Accent,
fontSize = 11.sp,
lineHeight = 15.sp,
fontWeight = FontWeight.SemiBold,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
}

View file

@ -0,0 +1,174 @@
@file:OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
package tv.kaleido.app
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.*
import androidx.compose.foundation.gestures.BringIntoViewSpec
import androidx.compose.foundation.gestures.LocalBringIntoViewSpec
import androidx.compose.foundation.lazy.grid.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.outlined.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.*
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shadow
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.semantics.*
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import coil.request.ImageRequest
@Composable fun DetailsScreen(vm:KaleidoViewModel) {
val item=vm.detail ?: return
val actionFocus=remember(item.id){FocusRequester()}
val childFocus=remember(item.id){FocusRequester()}
val restoreFocus=remember(item.id){vm.focusId}
val restoreRow=remember(item.id){listOf("cast:","children:","related:").any{restoreFocus.startsWith("$it${item.id}:")}}
val list=rememberLazyListState()
LaunchedEffect(item.id,vm.children.isNotEmpty(),vm.detailRelated.isNotEmpty()) {
val castCount=if(item.castMembers.isNotEmpty())1 else 0
val target=when {
restoreFocus.startsWith("related:${item.id}:")&&vm.detailRelated.isNotEmpty()->1+castCount+if(vm.children.isNotEmpty())1 else 0
restoreFocus.startsWith("children:${item.id}:")&&vm.children.isNotEmpty()->1
restoreFocus.startsWith("cast:${item.id}:")&&vm.children.isNotEmpty()->2
else->null
}
// Async rows may not exist during the first restored layout. Reveal the
// requested row after it loads, then its card restores the exact focus.
if(target!=null)list.scrollToItem(target)
}
Box(Modifier.fillMaxSize().background(Ink)) {
if(item.type=="show") {
BrowseBackdrop(vm.api,item.art.ifBlank{item.thumb},Modifier.fillMaxSize(),cinematic=true)
// Keep long descriptions and provider badges legible across bright artwork.
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(0f to Ink.copy(alpha=.4f),.48f to Ink.copy(alpha=.4f),.75f to Color.Transparent)))
}
CompositionLocalProvider(LocalBringIntoViewSpec provides DetailsScroll) {
LazyColumn(state=list,contentPadding=PaddingValues(bottom=30.dp),verticalArrangement=Arrangement.spacedBy(18.dp),modifier=Modifier.fillMaxSize()) {
item(key="details-${item.id}") {
Box(Modifier.fillMaxWidth().height(if(item.type in listOf("movie","episode"))322.dp else 286.dp)) {
if(item.type!="show") {
Artwork(vm.api,item.art,Modifier.fillMaxSize(),1920,1080)
Box(Modifier.fillMaxSize().background(Brush.horizontalGradient(listOf(Ink.copy(alpha=.98f),Ink.copy(alpha=.8f),Color.Transparent))))
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(listOf(Color.Black.copy(alpha=.12f),Color.Transparent,Ink))))
}
IconControl(Icons.AutoMirrored.Outlined.ArrowBack,"Back",modifier=Modifier.padding(start=36.dp,top=14.dp)){vm.back()}
if(item.type=="show") {
Row(Modifier.fillMaxWidth().padding(start=Cinema.gutter,end=Cinema.gutter,top=68.dp),horizontalArrangement=Arrangement.spacedBy(24.dp),verticalAlignment=Alignment.Top) {
Artwork(vm.api,item.poster.ifBlank{item.thumb},Modifier.width(128.dp).height(192.dp).clip(androidx.compose.foundation.shape.RoundedCornerShape(6.dp)),384,576,animate=false,contentScale=ContentScale.Fit)
TitleInformation(vm,item,actionFocus,childFocus,!restoreRow,Modifier.weight(1f))
}
}else TitleInformation(vm,item,actionFocus,childFocus,!restoreRow,Modifier.align(Alignment.CenterStart).padding(start=Cinema.gutter,top=30.dp).width(560.dp))
}
}
if(vm.children.isNotEmpty())item(key="children-${item.id}"){MediaRow(vm,if(item.type=="show")"Seasons"else if(item.type=="season")"Episodes"else "In this collection",vm.children,"children:${item.id}",landscape=item.type=="season",entryFocus=childFocus)}
if(item.castMembers.isNotEmpty())item(key="cast-${item.id}"){CastRail(vm,item,actionFocus)}
if(vm.detailRelated.isNotEmpty())item(key="related-${item.id}"){MediaRow(vm,"Related shows",vm.detailRelated,"related:${item.id}")}
}
}
}
}
/** Do not pin an already visible action a third of the way down the screen. */
private object DetailsScroll:BringIntoViewSpec {
override fun calculateScrollDistance(offset:Float,size:Float,containerSize:Float):Float = when {
offset<12f->offset-12f
offset+size>containerSize-12f->offset+size-containerSize+12f
else->0f
}
}
@Composable private fun TitleInformation(vm:KaleidoViewModel,item:Title,actionFocus:FocusRequester,childFocus:FocusRequester,initialFocus:Boolean,modifier:Modifier) {
val actionNavigation=Modifier.focusProperties{if(vm.children.isNotEmpty())down=childFocus}
Column(modifier) {
CompositionLocalProvider(LocalTextStyle provides LocalTextStyle.current.copy(shadow=Shadow(Color.Black.copy(alpha=.95f),Offset(0f,2f),6f))) {
if(item.type=="episode")Text(item.grandparentTitle,color=Cinema.secondary,fontSize=11.sp)
Text(item.title,color=Accent,fontSize=32.sp,lineHeight=36.sp,fontWeight=FontWeight.Bold,maxLines=2,overflow=TextOverflow.Ellipsis)
Row(Modifier.fillMaxWidth().padding(top=9.dp),verticalAlignment=Alignment.CenterVertically) {
Text(listOf(item.subtitle,item.contentRating).filter{it.isNotBlank()}.joinToString(" · "),color=Muted,fontSize=10.5.sp,lineHeight=16.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.weight(1f,fill=false))
AudienceRatings(item,Modifier.padding(start=12.dp))
}
Text(item.summary,color=Cinema.secondary,fontSize=12.sp,lineHeight=18.sp,maxLines=3,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=10.dp,bottom=17.dp))
}
if(item.type!="collection")Row(horizontalArrangement=Arrangement.spacedBy(9.dp),verticalAlignment=Alignment.CenterVertically) {
ActionButton(if(item.offset>0)"Resume · ${item.offset/60000} min"else if(item.type=="show")"Watch next"else "Play",Icons.Filled.PlayArrow,modifier=actionNavigation.focusRequester(actionFocus),primary=true,initialFocus=initialFocus){vm.play(item)}
if(item.offset>0)ActionButton("Start over",Icons.Outlined.Replay,modifier=actionNavigation){vm.play(item,true)}
if(item.type in listOf("movie","show","season","episode")) {
val watched=item.isWatched(vm.watchedPercent)
ActionButton(if(vm.markingId==item.id)"Updating…"else if(watched)"Mark unwatched"else "Mark watched",if(watched)Icons.Outlined.CheckCircle else Icons.Outlined.Check,modifier=actionNavigation){vm.mark(item)}
}
}
if(item.type!="show")item.media.firstOrNull()?.let{media->Text(listOf(media.resolution.uppercase(),media.videoCodec.uppercase(),media.audioCodec.uppercase()).filter{it.isNotBlank()}.joinToString(" · "),color=Cinema.quiet,fontSize=9.sp,modifier=Modifier.padding(top=12.dp))}
}
}
@Composable private fun CastRail(vm:KaleidoViewModel,item:Title,actionFocus:FocusRequester) {
val initial=remember(item.id){item.castMembers.indexOfFirst{"cast:${item.id}:${it.id.ifBlank{it.name}}"==vm.focusId}.coerceAtLeast(0)}
val row=rememberLazyListState(initialFirstVisibleItemIndex=initial)
Column {
Text("Cast",color=Accent,fontSize=17.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(start=Cinema.gutter,bottom=10.dp))
LazyRow(state=row,contentPadding=PaddingValues(horizontal=Cinema.gutter),horizontalArrangement=Arrangement.spacedBy(16.dp),modifier=Modifier.focusRestorer()) {
itemsIndexed(item.castMembers,key={index,actor->actor.id.ifBlank{"${actor.name}-$index"}}){_,actor->
val key="cast:${item.id}:${actor.id.ifBlank{actor.name}}"
var focused by remember{mutableStateOf(false)}
val requester=remember{FocusRequester()}
LaunchedEffect(Unit){if(vm.focusId==key){withFrameNanos{};runCatching{requester.requestFocus()}}}
Column(Modifier.width(108.dp).focusRequester(requester).focusProperties{if(item.type!="collection"&&vm.children.isEmpty())up=actionFocus}.navigationSound().onFocusChanged{
focused=it.isFocused;if(it.isFocused)vm.focusId=key
}.clickable(enabled=actor.id.isNotBlank()){vm.openActor(actor)}.clearAndSetSemantics{
contentDescription=listOf(actor.name,actor.role).filter{it.isNotBlank()}.joinToString(". ")
this.focused=focused;role=Role.Button
if(actor.id.isNotBlank())onClick{vm.openActor(actor);true}
},horizontalAlignment=Alignment.CenterHorizontally) {
ActorPortrait(vm.api,actor,Modifier.size(86.dp).then(if(focused)Modifier.border(2.dp,Accent,CircleShape)else Modifier))
Text(actor.name,color=if(focused)Accent else Cinema.secondary,fontSize=11.sp,lineHeight=14.sp,maxLines=2,overflow=TextOverflow.Ellipsis,modifier=Modifier.padding(top=7.dp).height(28.dp))
Text(actor.role,color=Muted,fontSize=9.sp,lineHeight=12.sp,maxLines=1,overflow=TextOverflow.Ellipsis,modifier=Modifier.height(12.dp))
}
}
}
}
}
@Composable private fun ActorPortrait(api:PlexApi,actor:CastMember,modifier:Modifier) {
val context=LocalContext.current
val request=remember(actor.thumb,api.session?.server){api.image(actor.thumb,256,256)?.let{url->ImageRequest.Builder(context).data(url).apply{api.headers().forEach{(k,v)->addHeader(k,v)}}.crossfade(false).build()}}
Box(modifier.clip(CircleShape).background(Panel),contentAlignment=Alignment.Center) {
Icon(Icons.Outlined.Person,null,tint=Muted,modifier=Modifier.fillMaxSize(.5f))
AsyncImage(request,null,modifier=Modifier.fillMaxSize(),contentScale=ContentScale.Crop)
}
}
@Composable fun ActorScreen(vm:KaleidoViewModel) {
val actor=vm.page.actor ?: return
Column(Modifier.fillMaxSize().background(Ink).padding(top=20.dp)) {
Row(Modifier.fillMaxWidth().padding(start=34.dp,end=Cinema.gutter,bottom=22.dp),verticalAlignment=Alignment.CenterVertically,horizontalArrangement=Arrangement.spacedBy(18.dp)) {
IconControl(Icons.AutoMirrored.Outlined.ArrowBack,"Back"){vm.back()}
ActorPortrait(vm.api,actor,Modifier.size(65.dp))
Column {
Eyebrow("In your libraries")
Text(actor.name,color=Accent,fontSize=29.sp,lineHeight=34.sp,fontWeight=FontWeight.SemiBold,modifier=Modifier.padding(vertical=3.dp))
Text(if(vm.busy)"Finding movies and shows…"else "${vm.actorTitles.size} titles",color=Muted,fontSize=11.sp)
}
}
if(vm.actorTitles.isEmpty()&&!vm.busy)Text("No titles with this actor in your libraries.",color=Muted,fontSize=14.sp,modifier=Modifier.padding(horizontal=Cinema.gutter))
LazyVerticalGrid(GridCells.Fixed(6),contentPadding=PaddingValues(start=Cinema.gutter,end=Cinema.gutter,bottom=28.dp),horizontalArrangement=Arrangement.spacedBy(13.dp),verticalArrangement=Arrangement.spacedBy(18.dp)) {
itemsIndexed(vm.actorTitles,key={_,item->item.id}){index,item->
MediaTile(vm,item,"actor:${actor.id}:${item.id}",fillWidth=true,initialFocus=index==0&&!vm.focusId.startsWith("actor:${actor.id}:"),onMove={anticipateTileMove(vm,vm.actorTitles,index,it,6)})
}
}
}
}

Binary file not shown.

View file

@ -1 +1 @@
5ed19959904a8497fcef312dd0ee2e33008e9f551c732d520c4888486c09db28 Kaleido.apk
894a949b7aa290b6f1f90d692a22ac4043c709182b77b65cfa7704841d4a7ffa Kaleido.apk

View file

@ -1,7 +1,7 @@
{
"version": "0.1.7",
"versionCode": 8,
"url": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.1.7/distribution/Kaleido.apk",
"checksumUrl": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.1.7/distribution/Kaleido.apk.sha256",
"notes": "- Give the launcher banner and app icon a soft colored background: deep sea-glass light from the top right fading to a warm glow at the bottom left, behind the unchanged six-facet mark."
"version": "0.1.8",
"versionCode": 9,
"url": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.1.8/distribution/Kaleido.apk",
"checksumUrl": "https://git.elijahkuntz.com/Elijah/Kaleido/raw/tag/v0.1.8/distribution/Kaleido.apk.sha256",
"notes": "- Add cast portraits with character names to title information. Select an actor to browse their movies and shows across your Plex libraries.\n- Add Mark watched / Mark unwatched buttons that synchronize movies, series and episodes with Plex.\n- Put Seasons first on TV show pages, followed by Cast and related shows supplied by Plex.\n- Redesign TV show information with a full backdrop, fitted poster and stable header placement. Add text shadows and stronger contrast for readable descriptions and ratings.\n- Redesign Settings with a category rail and consistent controls for Connection, Playback, Interface and Updates.\n- Refresh the screenshots and rewrite the README around the app's features and installation."
}

View file

@ -10,7 +10,11 @@ The interface gives artwork priority. App chrome uses neutral near-black, charco
- Library: title and discovery/full-library navigation share a 64 dp header. A 43 dp filter row sits immediately above the six-column poster grid.
- Browsing card widths: landscape 214 dp, TV episodes 264 dp, posters 120 dp. Landscape artwork uses 16:9; posters use 2:3. The full grid scales six columns to available width. Captions reserve a fixed height.
- Search uses three columns of landscape results. Episodes use their actual stills, preserving their native proportions instead of cropping them into posters.
- Features use original Plex clear-logo artwork within 264 × 80 dp, falling back to title text. Detail title: 34/37 sp. Library title: 29/34 sp. Discovery rail heading: 17/22 sp. Supporting information: 10/14 sp.
- Movie and episode information pages place a horizontal Cast row beneath the description and actions, using Plex portraits, names and character roles. TV show pages place Seasons first, then Cast, then server-provided Related shows; season pages likewise keep Episodes ahead of Cast. Missing portraits use a neutral person placeholder. Actor cards open a six-column filmography of available movies and shows across the connected server's libraries, using Plex actor identifiers and pagination.
- TV show information uses a full-screen backdrop behind a fitted 128 × 192 dp poster and a top-aligned text block. The Back control stays in the safe area; focus only scrolls controls that are out of view. A dark backdrop fade and soft text shadows preserve contrast for descriptions, metadata and audience ratings.
- Movie, episode, show and season information pages expose labelled Mark watched / Mark unwatched actions. Changes are sent to Plex and reflected in the title, descendant episodes/seasons, library cards, actor results and recommendations. An in-flight write survives navigation and prevents duplicate submissions. Partial episode-list records update watch fields without replacing full cast/detail metadata.
- Settings uses a fixed category rail (Connection, Playback, Interface, Updates) beside compact value/action rows. Focus selects categories; Right enters their controls and Left returns to the rail. Neutral surfaces, white focus, existing typography and restrained motion match the browsing destinations. Existing account, quality, watched-threshold, navigation-sound and updater preferences keep their behavior.
- Features use original Plex clear-logo artwork within 264 × 80 dp, falling back to title text. Detail title: 32/36 sp. Library title: 29/34 sp. Discovery rail heading: 17/22 sp. Supporting information: 10/14 sp.
- Poster and thumbnail corners: 6 dp. Compact action corners: 5 dp. Cards have no idle border; a compact bottom-right check marks watched titles, or a number shows remaining episodes for a show/season when Plex provides counts. Unwatched movies have no badge. Resumed movies/episodes only show a check after the configured playback threshold (80 percent by default), even if Plex retains a historical watched flag. Completed titles with no resume position retain Plex's watched state. Progress uses a two-dp inset line.
- The abstract six-facet aperture mark is shared by the header, sign-in, app icon, TV banner, and the cold-start aperture sequence. It uses muted sea-glass and warm ivory facets around a dark center, with no letterform or sparkle. The launcher banner and app icon place it on a diagonal light, deep sea-glass at the top right through near-black to a warm tan glow at the bottom left, with a soft vignette and nothing over the aperture; `scripts/generate_brand_tiles.py` regenerates both from `brand_mark.xml`.
- Audience ratings display Rotten Tomatoes as a percentage beside its official Popcornmeter artwork, and IMDb on its native ten-point scale beside the gold IMDb logo. Both appear when Plex exposes both; TVDB is retained as a fallback when neither is available. Critic scores and unsupported providers are omitted. Stable preview focus hydrates detail metadata, where Plex exposes the full provider list. The official red Hot mark appears at 60 percent or above and the green Stale mark below 60 percent; each fits a stable, font-scaled square without recoloring or distortion. Verified Hot is not inferred from a percentage. Asset provenance is in [brand-assets.md](brand-assets.md). The IMDb vector uses the official gold primary mark and supplied clear space from the [IMDb brand toolkit](https://brand.imdb.com/imdb).

43
docs/development.md Normal file
View file

@ -0,0 +1,43 @@
# Kaleido development
Build setup, release packaging and implementation notes. For app features and installation, see the [README](../README.md).
## Build on Windows
1. Run `scripts/bootstrap.py` with Python 3 to download an isolated JDK 17, Gradle 8.13, and Android command-line tools under `.tools/`.
2. Set `JAVA_HOME` to the extracted JDK directory and run `.tools/sdk/cmdline-tools/latest/bin/sdkmanager.bat --sdk_root=<absolute .tools/sdk path> "platforms;android-36" "build-tools;35.0.0"`. Accept the SDK license when prompted.
3. Run `./Build.ps1 -Test` for the debug APK, unit tests, and lint. Run `./Build.ps1 -Release` for the optimized release APK.
Open the project root in Android Studio to use an existing local Android SDK instead. Set `ANDROID_HOME` and use the bundled Gradle distribution or the wrapper.
The first local build creates `.tools/kaleido-signing.jks`. **Keep a private backup of this file and its credentials. Every app update must use the same signing key.** Debug and release builds share this local key so the test installation can receive the release through the updater. CI uses an ephemeral validation key and publishes only the locally signed distribution APK. For alternate signing, set `KALEIDO_KEYSTORE`, `KALEIDO_STORE_PASSWORD`, `KALEIDO_KEY_ALIAS`, and `KALEIDO_KEY_PASSWORD`.
## Connect
Open Kaleido and enter its code at [plex.tv/link](https://plex.tv/link). Settings → Sign in with Plex can link an account while keeping the current connection until successful server selection; Back cancels linking. Choose a server if more than one is available. The client tests the discovered server connections and prefers TLS. A manual server URL / token connection is also available. The credentials are AES-GCM encrypted with an Android Keystore key, never backed up, and removed on sign-out. Local HTTP servers remain supported. Account tokens are sent only to Plex account endpoints; server tokens are sent to the selected Plex server.
`.env` and signing keys are ignored by Git. No test credentials are included in source code, BuildConfig, resources, or APKs. `scripts/device.py seed` is an optional debug-only provisioning helper: it sends `.env` credentials to private app data over the already-authorized ADB connection. Kaleido immediately encrypts them and deletes the staging file. Release builds never read this staging file.
## Remote and playback
D-pad moves focus, OK activates, and Back returns through details and seasons. In the player, OK shows controls; Left/Right while controls are hidden seeks; dedicated media keys control playback. The on-screen controls provide pause, seeking, audio, subtitles, next episode, and exit. Back first hides controls, then exits playback. Stopping or leaving the app reports the latest position to Plex.
Original quality is the default, requesting the source video and remuxing where supported, with a 1080p conversion fallback. The player gear exposes the same quality preference as Settings, along with audio, subtitles, speed and chapters. Media3's SurfaceView preserves supported HDR. Actual HDR, Dolby Vision, codecs, and audio passthrough depend on the device, connected display/receiver, source profile, and server. Plex owns transcoding capability and any account entitlements. Unsupported subtitle formats use server conversion. Intro and credit buttons appear when the server supplies markers. Scrubbing displays server-generated video previews or chapter thumbnails when available; the timeline also shows buffered progress. Episode endings and Skip credits show a cancellable five-second next-episode countdown, season episodes, and related shows.
## Updates and releases
Kaleido checks [the public repository releases](https://git.elijahkuntz.com/Elijah/Kaleido/releases) on launch and foreground entry, at most once per six hours. Settings offers an immediate check. It downloads the release APK over HTTPS, checks its supplied SHA-256 when available, and verifies the package name, increasing Android version code, and installed signing certificate before opening Android's package installer. Android requires a one-time “allow from this source” permission and confirmation for each installation.
To publish a version:
1. Increment **both** fields in `version.properties` and update `CHANGELOG.md`.
2. Run `./Build.ps1 -Release -Test`, then `python scripts/package_release.py`.
3. Commit the source and `distribution/`, push `main`, and push the matching `v<versionName>` tag.
The Forgejo workflow builds, tests, and lints the source, verifies the prebuilt signed distribution, then publishes its APK and checksum using Forgejo's repository-scoped token. The private production signing key never leaves the developer machine. The checked-in APK also provides a repository-file update channel, with an immutable tag URL in `distribution/latest.json`, for installations before the first Forgejo release is ready.
## Structure and references
`PlexApi.kt` owns Plex transport and server-relative API calls; `SecureSession.kt` owns credential encryption; `KaleidoViewModel.kt` owns navigation and async screen data; `Screens.kt` and `Theme.kt` implement the TV UI; `Playback.kt` owns Media3, stream negotiation, track selection, lifecycle, and timeline reporting; `AppUpdater.kt` verifies updates. Artwork has bounded memory and disk caches. Library data is paged in batches of 100.
Implementation follows the [official Plex Media Server API](https://developer.plex.tv/pms/), [Android Compose guidance](https://developer.android.com/compose), and [Media3 documentation](https://developer.android.com/media/media3). This is an independent client, unaffiliated with Plex. No existing Plex client source is copied.

View file

@ -118,3 +118,15 @@ Verified on the Fire Stick with a build labelled 0.1.3 against published 0.1.4:
Playback mode and transcode quality are now one `StreamQuality` preference: Original quality (direct stream of the source video, falling back to a 1080p conversion) and 4K/1080p/720p/480p conversions, in Settings and the player gear. Earlier `playbackModeV2`/`quality` preferences migrate on first read. With the controls hidden, a Left/Right tap now only moves a pending seek (350 ms settle, so quick taps add up); a key repeat reveals the controls with the timeline focused. Play's initial focus no longer takes focus back after a timeline reveal.
On the onn, `verify_ui.py player` passed all seven checks, including two new ones: a Right tap skipped at least 9 s (projected from the Android media-session position) with no controls, and `input keyevent --longpress 22` revealed the focused timeline. `repro_runtime.py controls` passed. While video plays with controls visible, their clock updates keep `uiautomator` from dumping and it silently returns the previous hierarchy; the player checks now wait for the `READY` log line before pausing and inspect the screen while paused. A focus-loss theory based on those stale dumps was ruled out with a temporary focus log.
## Title information, cast and Settings - 2026-10-25
Cast cards use real Plex Role portraits, names, roles and server-local actor identifiers. Selecting an actor queries every accessible movie/show section with pagination. Series information keeps Seasons ahead of Cast and Plex's related-show hubs. The labelled watched actions use Plex scrobble/unscrobble, refresh descendants and preserve full metadata when merging summary records. Writes survive navigation and repeated submissions are ignored until the refresh completes.
`verify_details.py` passed on the optimized release on the onn: movie watched/unwatched persisted in Plex; John Cena's 13 titles matched results from both libraries; actor/title/cast return focus restored; marking the eight-episode series updated every episode; related shows opened and returned to the selected card. The harness validated initially unwatched, zero-resume fixtures (Matchbox `36486`, 3 Body Problem `16413`), then restored and rechecked both. It did not play content or alter existing resume points.
The TV show header initially moved its title to y=21 px when Compose's default TV bring-into-view pinned the focused action higher on screen. `verify_details_layout.py` reproduced that failure. The revised header uses a full-screen backdrop, fitted poster and top-aligned information; scrolling only reveals controls outside the viewport. The regression check passed with title bounds `[392,136,849,212]`, Back visible and Seasons first. Text shadows and a dark fade improve description/rating contrast; filled action buttons retain crisp text without that shadow.
Settings now uses Connection / Playback / Interface / Updates categories. The underlying account, preferences and signed-updater behavior are preserved. Raw captures and server-specific verification results remain in ignored `evidence/private/`; the README gallery contains reviewed screenshots from the release build.
Final 0.1.8 verification: `Build.ps1 -Release -Test` passed; `verify_settings.py` passed category focus, Original quality / 80% dialog cancellation, live update checking and sign-out cancellation. `verify_navigation_sounds.py` passed Off and On persistence across cold starts, leaving sounds On. All six `verify_ui.py browse` checks passed, including real Plex PIN cancellation. The final signed APK (version code 9) was installed in place and profile compiled; the encrypted session and playback preferences were retained. The app was returned to Home. The release gallery includes nine new 1920 × 1080 captures, encoded as lossless WebP and checked for pixel equality with their source PNGs.

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 MiB

After

Width:  |  Height:  |  Size: 1 MiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

After

Width:  |  Height:  |  Size: 1.1 MiB

Before After
Before After

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

BIN
docs/screenshots/show.webp Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

73
scripts/verify_details.py Normal file
View file

@ -0,0 +1,73 @@
"""Live details/cast/related checks on the onn. Temporarily toggles unwatched fixtures.
The movie and every episode of the show must start unwatched with no resume point.
Both are restored, including on failure. Do not run beside another device/UI test.
"""
import json,time,urllib.parse,urllib.request
from device import adb,OUT,screenshot
from inspect_server import get,base,token
from verify_ui import launch,key,text,focused,wait,focus,labels,snapshot
MOVIE='36486' # Matchbox: first recent-release movie on the private test server.
SHOW='16413' # 3 Body Problem: first A-Z show, eight initially unwatched episodes.
def metadata(ident):return get('/library/metadata/'+ident)['Metadata'][0]
def leaves(ident):return get('/library/metadata/'+ident+'/allLeaves').get('Metadata',[])
def clean(item):return not item.get('viewCount',0) and not item.get('viewOffset',0)
def reset(ident):
# Cleanup uses Plex's same endpoint if a failing UI cannot restore the fixture.
path='/:/unscrobble?'+urllib.parse.urlencode({'key':ident,'identifier':'com.plexapp.plugins.library'})
request=urllib.request.Request(base+path,headers={'X-Plex-Token':token,'Accept':'application/json'})
with urllib.request.urlopen(request,timeout=20) as response:assert response.status==200
def main():
movie=metadata(MOVIE);show=metadata(SHOW);episodes=leaves(SHOW)
assert clean(movie),'Movie fixture has existing watched/resume state; choose another fixture'
assert episodes and all(clean(e) for e in episodes),'Show fixture has existing watched/resume state; choose another fixture'
results=[];touched=set()
try:
launch();key(22);focused('Movies');text('Recently released');key(20);focused('Discover');key(20);key(23)
text(movie['title']);text('Cast');focused('Play');text('Mark watched')
key(22);focused('Mark watched');touched.add(MOVIE);key(23);focused('Mark unwatched')
assert metadata(MOVIE).get('viewCount',0)>0
screenshot('details-movie-watched');key(23);focused('Mark watched');assert clean(metadata(MOVIE))
results.append('Movie watched/unwatched persisted in Plex');print('PASS '+results[-1],flush=True)
key(21);focused('Play');key(20)
actor=movie['Role'][0];focused(actor['tag']);key(23)
expected=[]
for section in get('/library/sections').get('Directory',[]):
if section['type'] in ('movie','show'):
expected.extend(get('/library/sections/'+section['key']+'/all?actor='+str(actor['id'])).get('Metadata',[]))
expected={j['ratingKey']:j for j in expected};text(actor['tag']);text(str(len(expected))+' titles')
wait(lambda r:focus(r) not in ('','Back'),'Actor title grid focus');first=focus(snapshot());key(22);second=focus(snapshot());key(23)
wait(lambda r:'Cast' in labels(r),'Selected actor title details');key(4);focused(second);key(4);focused(actor['tag'])
screenshot('details-cast-restored')
results.append('Actor titles match both Plex libraries; title and cast focus restore');print('PASS '+results[-1],flush=True)
key(4);key(4);focused('Home');key(22,2);focused('TV Shows');key(20);focused('Discover');key(22);focused('Library');key(23)
wait(lambda r:any(x.startswith('All genres') for x in labels(r)),'Show library filters loaded');focused('Library');key(20)
if show['title'] not in focus(snapshot()):key(21)
focused(show['title']);key(23)
text('Seasons');focused('Watch next');text('Mark watched');key(22);focused('Mark watched');touched.add(SHOW);key(23);focused('Mark unwatched')
assert metadata(SHOW).get('viewedLeafCount')==len(episodes)
assert all(e.get('viewCount',0)>0 for e in leaves(SHOW))
screenshot('details-show-watched');key(23);focused('Mark watched')
assert metadata(SHOW).get('viewedLeafCount',0)==0 and all(clean(e) for e in leaves(SHOW))
results.append('Series watched/unwatched updates every episode in Plex');print('PASS '+results[-1],flush=True)
related=get('/library/metadata/'+SHOW+'/related').get('Hub',[])
expected_related={m['ratingKey'] for h in related for m in h.get('Metadata',[]) if m.get('type')=='show' and m['ratingKey']!=SHOW}
assert expected_related,'Related-show fixture missing server-generated hubs'
key(21);focused('Watch next');key(20);text('Seasons');key(20);focused(show['Role'][0]['tag']);key(20);text('Related shows')
selected=focus(snapshot());assert selected and selected not in ('Watch next','Mark watched')
screenshot('details-related-shows');key(23);focused('Watch next');key(4);focused(selected)
results.append('Server-related shows render, open and restore focus');print('PASS '+results[-1],flush=True)
key(4,3);focused('Home')
finally:
for ident in touched:
changed=not clean(metadata(ident)) if ident==MOVIE else any(not clean(e) for e in leaves(ident))
if changed:reset(ident)
assert clean(metadata(MOVIE)) and all(clean(e) for e in leaves(SHOW)),'Fixture restoration failed'
(OUT/'details-feature-results.json').write_text(json.dumps(results,indent=2)+'\n')
print('PASS original unwatched/resume state restored for both fixtures',flush=True)
if __name__=='__main__':main()

View file

@ -0,0 +1,20 @@
"""Check a fresh show page keeps its Back control and description in the safe area."""
import re
from device import screenshot
from verify_ui import launch,key,focused,wait,focus,labels,snapshot
launch();key(22,2);focused('TV Shows');key(20);focused('Discover');key(22);focused('Library');key(23)
wait(lambda r:any(x.startswith('All genres') for x in labels(r)),'Show library loaded');focused('Library');key(20)
if '3 Body Problem' not in focus(snapshot()):key(21)
focused('3 Body Problem');key(23);focused('Watch next')
root=snapshot();screenshot('show-layout-current')
title=next(n for n in root.iter('node') if n.get('text')=='3 Body Problem')
bounds=list(map(int,re.findall(r'\d+',title.get('bounds'))))
back=next((n for n in root.iter('node') if n.get('content-desc')=='Back'),None)
print('Title bounds:',bounds,'Back visible:',back is not None,flush=True)
assert bounds[1]>=88,'Show title was scrolled above the safe header area on initial focus'
assert back is not None,'Back control must remain visible on initial show entry'
back_bounds=list(map(int,re.findall(r'\d+',back.get('bounds'))))
assert back_bounds[1]>=0 and back_bounds[3]>back_bounds[1],'Back control must stay inside the visible header'
assert 'Seasons' in labels(root),'Seasons must lead the rows beneath show information'
print('PASS safe show header and Seasons first on initial entry')

View file

@ -9,15 +9,15 @@ from device import adb,OUT,screenshot
def setting():
launch();key(22,4);focused('Settings');key(23);focused('Sign in with Plex')
key(20);focused('Mode: Direct stream');key(20);focused('Mark watched at 80%');key(20)
key(21);focused('Connection');key(20,2);focused('Interface');key(22);focused('Navigation sounds')
def persistence():
setting();focused('Navigation sounds: On');key(23);focused('Navigation sounds: Off')
setting();focused('Navigation sounds');text('On');key(23);focused('Navigation sounds');text('Off')
screenshot('navigation-sounds-off')
setting();focused('Navigation sounds: Off')
setting();focused('Navigation sounds');text('Off')
print('PASS disabling navigation sounds persists across process restart',flush=True)
key(23);focused('Navigation sounds: On')
setting();focused('Navigation sounds: On')
key(23);focused('Navigation sounds');text('On')
setting();focused('Navigation sounds');text('On')
print('PASS enabling navigation sounds persists across process restart',flush=True)
screenshot('navigation-sounds-on');key(4);focused('Home');text('Continue Watching')
@ -28,16 +28,16 @@ def audio():
adb('shell','atrace','--async_start','-b','16384','audio')
try:
for _ in range(3):
adb('shell','input','keyevent','20');time.sleep(.3)
adb('shell','input','keyevent','19');time.sleep(.3)
adb('shell','input','keyevent','21');time.sleep(.3)
adb('shell','input','keyevent','22');time.sleep(.3)
time.sleep(.4)
finally:raw=adb('shell','atrace','--async_stop','audio').decode(errors='replace')
(OUT/f'navigation-audio-{label}-atrace.txt').write_text(raw)
focused('Navigation sounds: '+label.capitalize())
focused('Navigation sounds');text(label.capitalize())
return sum('tracing_mark_write: B|' in line and line.endswith('|write') for line in raw.splitlines())
setting();focused('Navigation sounds: On');key(23);focused('Navigation sounds: Off')
setting();focused('Navigation sounds');text('On');key(23);focused('Navigation sounds');text('Off')
muted=probe('off')
key(23);focused('Navigation sounds: On');enabled=probe('on')
key(23);focused('Navigation sounds');text('On');enabled=probe('on')
result={'mutedMixerWrites':muted,'enabledMixerWrites':enabled}
(OUT/'navigation-audio-results.json').write_text(json.dumps(result,indent=2)+'\n')
print('Native audio activity:',result,flush=True)

View file

@ -0,0 +1,20 @@
"""D-pad checks for the category settings page; dialogs are cancelled without changes."""
from verify_ui import launch,key,text,focused,focus,snapshot
from device import screenshot
launch();key(22,4);focused('Settings');key(23);focused('Sign in with Plex')
key(21);focused('Connection');key(20);focused('Playback');key(22);focused('Playback quality')
key(23);focused('Original quality');key(4);focused('Playback quality')
key(20);focused('Watched status');key(23);focused('80%');key(4);focused('Watched status')
print('PASS quality and watched-threshold dialogs cancel back to their controls',flush=True)
screenshot('settings-playback-current')
key(21);focused('Playback');key(20);focused('Interface');key(22);focused('Navigation sounds')
key(21);focused('Interface');key(20);focused('Updates');key(22);focused('Check for updates');key(23)
text('Kaleido is up to date.');focused('Check for updates')
screenshot('settings-updates-current')
key(21);focused('Updates');key(19,3);focused('Connection');key(22);focused('Sign in with Plex')
key(22)
if 'Choose server' in focus(snapshot()):key(22)
focused('Sign out');key(23);focused('Keep watching');key(4);focused('Sign out')
key(4);focused('Home')
print('PASS category focus, live update check and safe sign-out cancellation',flush=True)

View file

@ -1,2 +1,2 @@
versionName=0.1.7
versionCode=8
versionName=0.1.8
versionCode=9