Release 0.1.5 with a reliable Settings update flow
All checks were successful
Validate and publish Kaleido / android (push) Successful in 2m23s

The update button no longer disappears while downloading, so focus can't
be lost and the remote no longer jumps to Home from Settings. It shows
download progress, offers Install again after a cancelled installer, and
restores focus on return. Settings scrolls only as far as needed, shows
just the new version's notes above the buttons, and focused primary
buttons now stand apart from unfocused ones. Release bodies and the
manifest carry only that version's changelog section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-10-24 14:00:32 -07:00
parent 4ac18c8a45
commit 6a53196748
14 changed files with 140 additions and 24 deletions

View file

@ -14,6 +14,12 @@ import java.security.MessageDigest
import java.util.concurrent.TimeUnit
data class Release(val version: String,val url: String,val checksumUrl: String?,val notes: String)
/** Release bodies may hold the whole changelog; keep only [version]'s section. */
fun releaseNotes(body: String,version: String): String {
val heading=Regex("^## v?"+Regex.escape(version)+"[ \t]*$",RegexOption.MULTILINE).find(body) ?: return body.trim()
val end=Regex("^## ",RegexOption.MULTILINE).find(body,heading.range.last+1)?.range?.first ?: body.length
return body.substring(heading.range.last+1,end).trim()
}
object Versions {
fun newer(candidate: String,current: String): Boolean {
fun parts(v:String)=v.removePrefix("v").split('.').map {it.toIntOrNull() ?: return emptyList<Int>()}
@ -35,12 +41,12 @@ class AppUpdater(private val context: Context) {
if(manifest.isBlank())return@withContext null
val m=JSONObject(manifest)
if(!Versions.newer(m.getString("version"),BuildConfig.VERSION_NAME))return@withContext null
return@withContext Release(m.getString("version"),checkedUrl(m.getString("url")),checkedUrl(m.getString("checksumUrl")),m.optString("notes"))
return@withContext Release(m.getString("version"),checkedUrl(m.getString("url")),checkedUrl(m.getString("checksumUrl")),releaseNotes(m.optString("notes"),m.getString("version")))
}
val j=JSONObject(raw);if(j.optBoolean("draft")||j.optBoolean("prerelease")||!Versions.newer(j.optString("tag_name"),BuildConfig.VERSION_NAME))return@withContext null
val assets=j.optJSONArray("assets").objects();val apk=assets.firstOrNull{it.optString("name")=="Kaleido.apk"} ?: assets.firstOrNull{it.optString("name").endsWith(".apk")} ?: error("This release has no Android APK.")
val sha=assets.firstOrNull{it.optString("name")==apk.optString("name")+".sha256"}
Release(j.getString("tag_name").removePrefix("v"),checkedUrl(apk.getString("browser_download_url")),sha?.getString("browser_download_url")?.let(::checkedUrl),j.optString("body"))
Release(j.getString("tag_name").removePrefix("v"),checkedUrl(apk.getString("browser_download_url")),sha?.getString("browser_download_url")?.let(::checkedUrl),releaseNotes(j.optString("body"),j.getString("tag_name").removePrefix("v")))
}
suspend fun download(release: Release,onProgress: (Int)->Unit): File = withContext(Dispatchers.IO) {
val dir=File(context.cacheDir,"updates").apply{mkdirs()};val part=File(dir,"Kaleido.apk.part");val file=File(dir,"Kaleido.apk");part.delete();file.delete()

View file

@ -6,6 +6,7 @@ import androidx.lifecycle.viewModelScope
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.mutableFloatStateOf
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
@ -59,6 +60,9 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
var updateStatus by mutableStateOf(""); private set
var downloadedApk by mutableStateOf<File?>(null); private set
var downloading by mutableStateOf(false); private set
var downloadProgress by mutableFloatStateOf(0f); private set
/** A verified APK for [update], kept so a cancelled installer can be reopened without downloading again. */
var readyApk by mutableStateOf<File?>(null); private set
var playbackMode by mutableStateOf(preferences.getInt("playbackModeV2",1)); private set
var watchedPercent by mutableStateOf(preferences.getInt("watchedPercent",80).coerceIn(50,100)); private set
var navigationSounds by mutableStateOf(preferences.getBoolean("navigationSounds",true)); private set
@ -264,11 +268,24 @@ class KaleidoViewModel(app: Application): AndroidViewModel(app) {
fun chooseNavigationSounds(value:Boolean){navigationSounds=value;preferences.edit().putBoolean("navigationSounds",value).apply()}
fun chooseQuality(value: Int){quality=value;preferences.edit().putInt("quality",value).apply()}
fun checkUpdate(manual: Boolean=true){viewModelScope.launch {
if(!manual&&System.currentTimeMillis()-preferences.getLong("lastUpdateCheck",0)<6*3600_000L)return@launch
if(downloading||!manual&&System.currentTimeMillis()-preferences.getLong("lastUpdateCheck",0)<6*3600_000L)return@launch
updateStatus="Checking for updates…"
try{update=updater.latest();preferences.edit().putLong("lastUpdateCheck",System.currentTimeMillis()).apply();updateStatus=if(update==null)"Kaleido is up to date." else "Version ${update!!.version} is available."}catch(e:Exception){updateStatus="Update check failed. ${e.message}"}
try{val previous=update?.version;update=updater.latest();if(update?.version!=previous)readyApk=null;preferences.edit().putLong("lastUpdateCheck",System.currentTimeMillis()).apply();updateStatus=if(update==null)"Kaleido is up to date." else "Version ${update!!.version} is available."}catch(e:Exception){updateStatus="Update check failed. ${e.message}"}
}}
fun downloadUpdate(){val release=update ?: return; if(downloading)return;viewModelScope.launch {downloading=true;try {downloadedApk=updater.download(release){progress -> updateStatus="Downloading update · $progress%"};updateStatus="Update verified. Ready to install."}catch(e:Exception){updateStatus=e.message ?: "Download failed."}finally{downloading=false}}}
fun downloadUpdate() {
val release=update ?: return
if(downloading)return
readyApk?.takeIf{it.exists()}?.let{downloadedApk=it;updateStatus="Opening the installer…";return}
viewModelScope.launch {
downloading=true;downloadProgress=0f
try {
val apk=updater.download(release){progress->downloadProgress=progress/100f;updateStatus="Downloading update · $progress%"}
readyApk=apk;downloadedApk=apk;updateStatus="Update verified. Opening the installer…"
}catch(e:Exception){updateStatus=e.message ?: "Download failed."}finally{downloading=false}
}
}
fun clearDownload(){downloadedApk=null}
/** Back from the system installer without updating: the verified APK can be installed again. */
fun installerReturned(){if(readyApk!=null&&!downloading)updateStatus="Update downloaded. Select Install ${update?.version.orEmpty()} to finish."}
fun debugPlay(id: String,offset: Long,mode: Int){if(!BuildConfig.DEBUG)return;launchLoad {playing=null;delay(150);playbackMode=mode;playing=api.details(id).copy(offset=offset);startFromZero=false}}
}

View file

@ -21,14 +21,16 @@ class MainActivity: ComponentActivity() {
if(packageManager.canRequestPackageInstalls()) pendingApk?.let(::installApk)
}
fun installApk(file: File) {
pendingApk=file
// Consume the request first: a denied permission or cancelled installer must not
// reopen on the next visit to Settings. Settings offers Install again instead.
model.clearDownload();pendingApk=file
if(!packageManager.canRequestPackageInstalls()) {
unknownSources.launch(Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,Uri.parse("package:$packageName")));return
}
val uri=FileProvider.getUriForFile(this,"$packageName.files",file)
@Suppress("DEPRECATION")
startActivity(Intent(Intent.ACTION_INSTALL_PACKAGE).setDataAndType(uri,"application/vnd.android.package-archive").addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION))
pendingApk=null;model.clearDownload()
pendingApk=null
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

View file

@ -36,6 +36,9 @@ import androidx.compose.ui.window.Dialog
import coil.compose.AsyncImage
import coil.request.ImageRequest
import coil.size.Precision
import androidx.compose.foundation.gestures.BringIntoViewSpec
import androidx.compose.foundation.gestures.LocalBringIntoViewSpec
import androidx.lifecycle.compose.LifecycleResumeEffect
import kotlinx.coroutines.delay
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.coroutines.flow.first
@ -140,7 +143,21 @@ val sortLabels=listOf("titleSort:asc" to "Title: A–Z","titleSort:desc" to "Tit
@Composable fun SettingsScreen(vm: KaleidoViewModel,install: (File)->Unit) {
var confirmSignOut by remember{mutableStateOf(false)};var modeDialog by remember{mutableStateOf(false)};var qualityDialog by remember{mutableStateOf(false)};var watchedDialog by remember{mutableStateOf(false)}
LaunchedEffect(vm.downloadedApk){vm.downloadedApk?.let(install)}
LazyColumn(contentPadding=PaddingValues(horizontal=Cinema.gutter,vertical=17.dp),verticalArrangement=Arrangement.spacedBy(16.dp)) {
// 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") {Row(horizontalArrangement=Arrangement.spacedBy(12.dp)){TvButton("Mode: "+listOf("Original","Direct stream","Transcode")[vm.playbackMode],onClick={modeDialog=true});TvButton("Transcode quality: "+if(vm.quality>20000)"4K · 80 Mbps"else "1080p · 20 Mbps",onClick={qualityDialog=true})};Text("Direct stream is the default. Playback mode, audio, subtitles, speed, and quality can also be changed in the player.",color=Muted,fontSize=12.sp,modifier=Modifier.padding(top=12.dp))}}
@ -152,7 +169,28 @@ val sortLabels=listOf("titleSort:asc" to "Title: A–Z","titleSort:desc" to "Tit
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);Spacer(Modifier.height(14.dp));Row(horizontalArrangement=Arrangement.spacedBy(10.dp)){TvButton("Check for updates",onClick={vm.checkUpdate()});if(vm.update!=null&&!vm.downloading)TvButton("Download & install ${vm.update!!.version}",primary=true,onClick={vm.downloadUpdate()})};vm.update?.let{if(it.notes.isNotBlank())Text(it.notes.take(1800),color=Muted,fontSize=11.sp,modifier=Modifier.padding(top=12.dp))};Text("git.elijahkuntz.com/Elijah/Kaleido",color=Accent,fontSize=10.sp,modifier=Modifier.padding(top=14.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) {
@ -162,6 +200,18 @@ val sortLabels=listOf("titleSort:asc" to "Title: A–Z","titleSort:desc" to "Tit
if(modeDialog)ChoiceDialog("Playback mode",listOf("Automatic · Original quality","Direct stream · Remux when possible","Transcode · Compatibility mode"),vm.playbackMode,{modeDialog=false}){vm.choosePlaybackMode(it);modeDialog=false}
if(qualityDialog)ChoiceDialog("Transcode quality",listOf("1080p · 20 Mbps","4K · 80 Mbps"),if(vm.quality>20000)1 else 0,{qualityDialog=false}){vm.chooseQuality(if(it==0)20000 else 80000);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)}}}}

View file

@ -54,12 +54,13 @@ object Cinema {
}
@Composable fun TvButton(label: String,modifier: Modifier=Modifier,selected: Boolean=false,primary: Boolean=false,initialFocus: Boolean=false,onClick: ()->Unit) {
var focused by remember { mutableStateOf(false) };val requester=remember {FocusRequester()}
val bg by animateColorAsState(if(focused) Accent else if(primary)Color(0xFFDEDEDE) else if(selected)Color.White.copy(alpha=.16f)else Color.White.copy(alpha=.08f),tween(150),label="buttonBackground")
val fg=if(focused||primary) Ink else Accent
// Only focus is solid white; a primary action is a brighter tint, so focus stays obvious.
val bg by animateColorAsState(if(focused) Accent else if(primary)Color.White.copy(alpha=.24f) else if(selected)Color.White.copy(alpha=.16f)else Color.White.copy(alpha=.08f),tween(150),label="buttonBackground")
val fg=if(focused) Ink else Accent
val scale by animateFloatAsState(if(focused)1.025f else 1f,tween(160),label="buttonScale")
LaunchedEffect(initialFocus){if(initialFocus){withFrameNanos{};runCatching{requester.requestFocus()}}}
Box(modifier.graphicsLayer{scaleX=scale;scaleY=scale}.focusRequester(requester).navigationSound().onFocusChanged{focused=it.isFocused}.clip(RoundedCornerShape(Cinema.radius)).background(bg).clickable(onClick=onClick).padding(horizontal=13.dp,vertical=8.dp)) {
Text(label,color=fg,fontSize=12.sp,lineHeight=16.sp,fontWeight=FontWeight.Medium,maxLines=1)
Text(label,color=fg,fontSize=12.sp,lineHeight=16.sp,fontWeight=if(primary)FontWeight.SemiBold else FontWeight.Medium,maxLines=1)
}
}
@Composable fun SectionHeading(title: String, subtitle: String?=null) {

View file

@ -0,0 +1,17 @@
package tv.kaleido.app
import org.junit.Assert.assertEquals
import org.junit.Test
class ReleaseNotesTest {
private val changelog="# Kaleido releases\n\n## 0.1.4\n\n- Smoother browsing.\n- Library focus.\n\n## 0.1.3\n\n- Aperture splash.\n"
@Test fun keepsOnlyTheReleasedVersionsSection() {
assertEquals("- Smoother browsing.\n- Library focus.",releaseNotes(changelog,"0.1.4"))
assertEquals("- Aperture splash.",releaseNotes(changelog,"0.1.3"))
}
@Test fun leavesNotesWithoutAMatchingHeadingIntact() {
assertEquals("- Only this release.",releaseNotes("\n- Only this release.\n","0.1.5"))
assertEquals(changelog.trim(),releaseNotes(changelog,"0.1.40"))
}
}