From 9635e31589cd61a1c622f085065f3a6a5906154b Mon Sep 17 00:00:00 2001 From: Jeena Date: Sat, 10 Oct 2026 22:16:29 +0000 Subject: [PATCH 01/23] ui: SmartTube layout - hidden rail, top bar, white focus cards Drop the always-visible sidebar: content is now full width so ~4.5 compact cards fit per row (width derived from the screen). A slide-in menu drawer opens via the avatar (BACK/LEFT close it) and carries the destinations + sign out with legible labels (#B0B0B0) replacing the illegible dark-grey rail. Cards no longer scale on focus: they flip to a white background with dark text and a white frame like SmartTube. Grids move to 3 columns with the freed width. --- .../net/jeena/jtubetv/ui/screens/HomeRows.kt | 13 +- .../jeena/jtubetv/ui/screens/HomeScreen.kt | 307 +++++++++++++----- .../jtubetv/ui/screens/list/VideoCard.kt | 40 ++- .../ui/screens/list/VideoListScreen.kt | 2 +- 4 files changed, 268 insertions(+), 94 deletions(-) diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt index a4dc174..b0f5c39 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt @@ -36,7 +36,12 @@ import net.jeena.jtubetv.data.api.VideoDto import net.jeena.jtubetv.ui.list.PagedListViewModel import net.jeena.jtubetv.ui.screens.list.VideoCard -private val ROW_CARD_WIDTH = 296.dp +/** Compact SmartTube-style card: ~4 and a bit visible per full-width row. */ +@Composable +private fun rowCardWidth(): androidx.compose.ui.unit.Dp { + val windowWidth = androidx.compose.ui.platform.LocalConfiguration.current.screenWidthDp + return ((windowWidth / 4.35f) - 10).dp +} /** One "Continue watching" candidate: video + watched fraction (null = unknown yet). */ data class ContinueItem(val video: VideoDto, val progress: Float?) @@ -157,9 +162,10 @@ fun HomeRowsScreen( VideoCard( video = item.video, onClick = { onOpenVideo(item.video) }, - modifier = Modifier.width(ROW_CARD_WIDTH), + modifier = Modifier.width(rowCardWidth()), showPrivacy = false, progress = item.progress, + compact = true, ) } } @@ -192,8 +198,9 @@ fun HomeRowsScreen( VideoCard( video = video, onClick = { onOpenVideo(video) }, - modifier = Modifier.width(ROW_CARD_WIDTH), + modifier = Modifier.width(rowCardWidth()), showPrivacy = false, + compact = true, ) if (index >= recentItems.size - PagedListViewModel.LOOKAHEAD) { LaunchedEffect(index) { viewModel.recent.loadMore() } diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt index 9bcf9a6..c4dd2d8 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt @@ -1,38 +1,51 @@ package net.jeena.jtubetv.ui.screens +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.focusable +import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.List import androidx.compose.material.icons.filled.History import androidx.compose.material.icons.filled.Logout -import androidx.compose.material.icons.filled.Subscriptions -import androidx.compose.material.icons.filled.Search -import androidx.compose.material.icons.filled.VideoLibrary import androidx.compose.material.icons.filled.PersonalVideo +import androidx.compose.material.icons.filled.Search +import androidx.compose.material.icons.filled.Subscriptions +import androidx.compose.material.icons.filled.VideoLibrary import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue +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.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.unit.dp import androidx.tv.material3.Icon -import androidx.tv.material3.NavigationDrawer -import androidx.tv.material3.NavigationDrawerItem import androidx.tv.material3.Text import net.jeena.jtubetv.data.api.VideoDto import net.jeena.jtubetv.ui.AppViewModel import net.jeena.jtubetv.ui.list.ListSource import net.jeena.jtubetv.ui.screens.list.VideoListScreen -import androidx.activity.compose.BackHandler enum class Destination(val title: String) { Home("Home"), @@ -43,9 +56,12 @@ enum class Destination(val title: String) { History("History"), } -/** Home = sidebar (D-pad navigable) + content pane. The player renders as a - * fullscreen overlay: the list beneath stays composed, so its scroll position and - * focused card survive BACK (couch users don't want to re-navigate from the top). */ +/** + * Home = SmartTube-style: hidden menu, red round search + avatar in a top bar, + * full-width rows/list content. The menu drawer slides in when wanted (avatar or + * the search/BACK flows) and everything is key(epoch) so an account switch + * rebuilds all state. + */ @Composable fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.viewModel()) { val epoch by viewModel.sessionEpoch.collectAsState() @@ -53,6 +69,9 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi var channelDetails by rememberSaveable { mutableStateOf(null) } // handle var playingVideo by rememberSaveable { mutableStateOf(null) } // shortUUID var restoreToken by rememberSaveable { mutableStateOf(0) } // increments when playback ends + var drawerOpen by rememberSaveable { mutableStateOf(false) } + val context = androidx.compose.ui.platform.LocalContext.current + var lastBackAt by rememberSaveable { mutableStateOf(0L) } // After BACK from the player: bump the restore token so lists re-focus the opened // card and re-fetch positions (UX report BUG-3 + BUG-7). @@ -60,85 +79,42 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi if (playingVideo == null && restoreToken >= 1) restoreToken++ } - // Channel drilldown hides the sidebar; remote BACK must return to the channels list. - BackHandler(enabled = playingVideo == null && channelDetails != null) { + // BACK order: player (own BackHandler) → drawer → channel drilldown → exit guard. + BackHandler(enabled = playingVideo == null && channelDetails == null && !drawerOpen) { + val now = System.currentTimeMillis() + if (now - lastBackAt < 2000) { + (context as? android.app.Activity)?.finish() + } else { + lastBackAt = now + android.widget.Toast.makeText(context, "Press BACK again to exit", android.widget.Toast.LENGTH_SHORT).show() + } + } + BackHandler(enabled = playingVideo == null && channelDetails != null && !drawerOpen) { channelDetails = null } + BackHandler(enabled = drawerOpen && playingVideo == null) { + drawerOpen = false + } Box(modifier = Modifier.fillMaxSize()) { androidx.compose.runtime.key(epoch) { - if (destination == Destination.Channels && channelDetails != null) { - androidx.compose.foundation.layout.Box( + Column { + // SmartTube-style top bar: red round search + avatar opening the menu. + TopBar( + onSearchClick = { destination = Destination.Search; channelDetails = null }, + onAccountClick = { drawerOpen = !drawerOpen }, + ) + Box( modifier = Modifier .fillMaxSize() - // TV overscan safety margins (list content, not the player). - .padding(horizontal = 32.dp), + // TV overscan safety margins on the content pane. + .padding(start = 8.dp, end = 32.dp, top = 8.dp), ) { - VideoListScreen( - source = ListSource.Channel(channelDetails!!, channelDetails!!), - onOpenVideo = { playingVideo = it.shortUUID }, - restoreToken = restoreToken, - epoch = epoch, - ) - } - } else { - NavigationDrawer(drawerContent = { - androidx.compose.foundation.layout.Column( - modifier = Modifier.width(220.dp).padding(vertical = 16.dp), - ) { - Text( - text = "JTube TV", - modifier = Modifier.padding(start = 28.dp, bottom = 16.dp), - style = androidx.tv.material3.MaterialTheme.typography.headlineSmall, - color = androidx.compose.ui.graphics.Color.White, - ) - Destination.entries.forEach { dest -> - NavigationDrawerItem( - selected = dest == destination, - onClick = { - destination = dest - channelDetails = null - }, - leadingContent = { - Icon(imageVector = dest.icon(), contentDescription = null) - }, - content = { Text(dest.title) }, - ) - } - val signOutContext = androidx.compose.ui.platform.LocalContext.current - var lastSignOutTap by remember { mutableStateOf(0L) } - NavigationDrawerItem( - selected = false, - onClick = { - val now = System.currentTimeMillis() - if (now - lastSignOutTap < 3000) { - viewModel.logout() - } else { - lastSignOutTap = now - android.widget.Toast.makeText( - signOutContext, - "Press again to sign out", - android.widget.Toast.LENGTH_SHORT, - ).show() - } - }, - leadingContent = { - Icon(imageVector = Icons.Filled.Logout, contentDescription = null) - }, - content = { Text("Sign out") }, - ) - } - }) { - androidx.compose.foundation.layout.Box( - modifier = Modifier - .fillMaxSize() - // TV overscan safety margins on the content pane. - .padding(start = 8.dp, end = 32.dp, top = 16.dp), - ) { when (destination) { Destination.Home -> HomeRowsScreen( onOpenVideo = { playingVideo = it.shortUUID }, + restoreToken = restoreToken, epoch = epoch, ) Destination.MyVideos -> @@ -174,9 +150,23 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi epoch = epoch, ) } - } } } + } + + // Slide-in menu drawer (SmartTube style: hidden until wanted). + if (drawerOpen) { + MenuDrawer( + selected = destination, + onSelect = { + destination = it + channelDetails = null + drawerOpen = false + }, + onSignOut = { viewModel.logout() }, + onDismiss = { drawerOpen = false }, + ) + } if (playingVideo != null) { PlayerScreen( @@ -184,11 +174,10 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi onBack = { playingVideo = null }, ) } - } } } -private fun Destination.icon(): androidx.compose.ui.graphics.vector.ImageVector = +private fun Destination.icon(): ImageVector = when (this) { Destination.Home -> Icons.Filled.VideoLibrary Destination.MyVideos -> Icons.Filled.PersonalVideo @@ -196,4 +185,158 @@ private fun Destination.icon(): androidx.compose.ui.graphics.vector.ImageVector Destination.Search -> Icons.Filled.Search Destination.Subscriptions -> Icons.Filled.Subscriptions Destination.History -> Icons.Filled.History - } \ No newline at end of file + } + +/** Top bar: red round search + account avatar (opens the menu), SmartTube-style. */ +@Composable +private fun TopBar( + onSearchClick: () -> Unit, + onAccountClick: () -> Unit, + modifier: Modifier = Modifier, +) { + Row( + modifier = modifier + .fillMaxWidth() + .padding(horizontal = 24.dp, vertical = 10.dp), + horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(16.dp), + ) { + val searchFocus = remember { FocusRequester() } + LaunchedEffect(Unit) { runCatching { searchFocus.requestFocus() } } + Box( + modifier = Modifier + .size(44.dp) + .clip(CircleShape) + .background(Color(0xFFCE2B2B)) + .focusRequester(searchFocus) + .focusable() + .clickable(onClick = onSearchClick), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = Icons.Filled.Search, + contentDescription = "Search", + tint = Color.White, + ) + } + Box( + modifier = Modifier + .size(44.dp) + .clip(CircleShape) + .background(Color(0xFF262626)) + .focusable() + .clickable(onClick = onAccountClick), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = Icons.Filled.PersonalVideo, + contentDescription = "Menu", + tint = Color(0xFFCCCCCC), + ) + } + Spacer(modifier = Modifier.weight(1f)) + Text( + text = "JTube TV", + color = Color(0xFF9A9A9A), + style = androidx.compose.material3.MaterialTheme.typography.titleMedium, + modifier = Modifier.align(Alignment.CenterVertically), + ) + } +} + +/** + * Slide-in menu drawer: destination list + sign out, readable on a dark background + * (UX report: unselected grey was illegible). Selected item gets the red accent. + */ +@Composable +private fun MenuDrawer( + selected: Destination, + onSelect: (Destination) -> Unit, + onSignOut: () -> Unit, + onDismiss: () -> Unit, + modifier: Modifier = Modifier, +) { + val drawerFocus = remember { FocusRequester() } + LaunchedEffect(Unit) { runCatching { drawerFocus.requestFocus() } } + val signOutContext = androidx.compose.ui.platform.LocalContext.current + var lastSignOutTap by remember { mutableStateOf(0L) } + Row(modifier = modifier.fillMaxSize()) { + Column( + modifier = Modifier + .width(240.dp) + .fillMaxSize() + .background(Color(0xFF111111)) + .padding(vertical = 24.dp), + ) { + Text( + text = "JTube TV", + color = Color.White, + style = androidx.compose.material3.MaterialTheme.typography.headlineSmall, + modifier = Modifier.padding(start = 28.dp, bottom = 20.dp), + ) + Destination.entries.forEachIndexed { index, dest -> + MenuDrawerItem( + icon = dest.icon(), + label = dest.title, + selected = dest == selected, + onClick = { onSelect(dest) }, + modifier = if (index == 0) Modifier.focusRequester(drawerFocus) else Modifier, + ) + } + Spacer(modifier = Modifier.weight(1f)) + MenuDrawerItem( + icon = Icons.Filled.Logout, + label = "Sign out", + selected = false, + onClick = { + if (System.currentTimeMillis() - lastSignOutTap < 3000) { + onSignOut() + } else { + lastSignOutTap = System.currentTimeMillis() + android.widget.Toast.makeText( + signOutContext, + "Press again to sign out", + android.widget.Toast.LENGTH_SHORT, + ).show() + } + }, + modifier = Modifier, + ) + } + // tap/click outside closes; focus LEFT from the drawer also closes + Box( + modifier = Modifier + .weight(1f) + .fillMaxSize() + .focusable() + .pointerInput(Unit) { detectTapGestures { onDismiss() } }, + ) + } +} + +@Composable +private fun MenuDrawerItem( + icon: ImageVector, + label: String, + selected: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + val labelColor = if (selected) Color(0xFFE0E0E0) else Color(0xFFB0B0B0) + Row( + modifier = modifier + .fillMaxWidth() + .then(if (selected) Modifier.background(Color(0x33CE2B2B)) else Modifier) + .focusable() + .clickable(onClick = onClick) + .padding(horizontal = 24.dp, vertical = 14.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(14.dp), + ) { + Icon(imageVector = icon, contentDescription = null, tint = labelColor) + Text( + text = label, + color = labelColor, + style = androidx.compose.material3.MaterialTheme.typography.bodyLarge, + ) + } +} \ No newline at end of file diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt index 8d67b29..7b99671 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt @@ -3,6 +3,7 @@ package net.jeena.jtubetv.ui.screens.list import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth @@ -19,6 +20,8 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp +import androidx.compose.foundation.BorderStroke +import androidx.tv.material3.Border import androidx.tv.material3.Card import androidx.tv.material3.CardDefaults import coil.compose.AsyncImage @@ -43,19 +46,35 @@ fun VideoCard( modifier: Modifier = Modifier, showPrivacy: Boolean = true, progress: Float? = null, + /** Compact = row in the SmartTube home: single-line title, smaller. */ + compact: Boolean = false, ) { Card( onClick = onClick, - modifier = modifier - .fillMaxWidth() - .height(268.dp) - .padding(6.dp), - colors = CardDefaults.colors(containerColor = MaterialTheme.colorScheme.surface), + modifier = modifier.padding(6.dp), + colors = CardDefaults.colors( + containerColor = UnfocusedCardBg, + contentColor = Color.White, + // SmartTube look: focused card turns white with dark text, no size change. + focusedContainerColor = Color.White, + focusedContentColor = Color(0xFF101010), + ), + scale = CardDefaults.scale(focusedScale = 1f), + border = CardDefaults.border( + focusedBorder = Border( + border = BorderStroke(3.dp, Color.White), + shape = ContainerShape, + ), + pressedBorder = Border( + border = BorderStroke(3.dp, Color.White), + shape = ContainerShape, + ), + ), ) { Box( modifier = Modifier .fillMaxWidth() - .height(158.dp) + .aspectRatio(16f / 9f) .background(Color(0xFF222222)), ) { video.thumbnailPath?.takeIf { it.isNotBlank() }?.let { path -> @@ -105,10 +124,11 @@ fun VideoCard( Text( text = video.name, style = MaterialTheme.typography.titleSmall, - maxLines = 2, - minLines = 2, + maxLines = if (compact) 1 else 2, + minLines = if (compact) 1 else 2, overflow = TextOverflow.Ellipsis, ) + Row( horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically, @@ -161,6 +181,10 @@ internal fun formatDuration(seconds: Int): String { } } +/** Card palette (SmartTube-style): near-black idle, white + dark text on focus. */ +internal val UnfocusedCardBg = Color(0xFF171717) +internal val ContainerShape = RoundedCornerShape(10.dp) + internal fun formatViews(views: Long): String = when { views >= 1_000_000 -> "%.1fM views".format(Locale.US, views / 1_000_000.0) diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt index 7adcbce..8c41235 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt @@ -119,7 +119,7 @@ fun VideoListScreen( } LazyVerticalGrid( - columns = GridCells.Fixed(2), + columns = GridCells.Fixed(3), state = gridState, modifier = Modifier.fillMaxSize().padding(vertical = 8.dp), ) { From 60ef94c52e4f67ff4b0a20253ea6ee8e4c9f9550 Mon Sep 17 00:00:00 2001 From: Jeena Date: Sat, 10 Oct 2026 22:24:06 +0000 Subject: [PATCH 02/23] ui: Eased card-row scrolling, dark text on focused white cards Focused-card rows now animate the newly focused card to the left edge (animateScrollToItem) instead of the abrupt bring-into-view jump - SmartTube-style easing. Text inside a focused (white) card flips to a dark gray-on-white palette instead of staying light gray. LEFT on the first card of a row/chain opens the menu drawer. --- .../jtubetv/ui/screens/ChannelsScreen.kt | 7 +- .../net/jeena/jtubetv/ui/screens/HomeRows.kt | 98 +++++++++++++------ .../jeena/jtubetv/ui/screens/HomeScreen.kt | 6 ++ .../jtubetv/ui/screens/list/VideoCard.kt | 35 ++++++- .../ui/screens/list/VideoListScreen.kt | 5 +- 5 files changed, 113 insertions(+), 38 deletions(-) diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt index dca0a69..26f711a 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt @@ -66,6 +66,7 @@ class ChannelsViewModel(private val store: TokenStore) : PagedListViewModel Unit, epoch: Int = 0, + onOpenDrawer: () -> Unit = {}, viewModel: ChannelsViewModel = viewModel(key = "channels$epoch", factory = ChannelsViewModel.factory), ) { LaunchedEffect(Unit) { viewModel.loadMore(force = true) } @@ -95,7 +96,7 @@ fun ChannelsScreen( } } } - else -> ChannelsList(items, viewModel, onOpenChannel) + else -> ChannelsList(items, viewModel, onOpenChannel, onOpenDrawer) } } } @@ -105,12 +106,14 @@ private fun ChannelsList( items: List, viewModel: ChannelsViewModel, onOpenChannel: (String) -> Unit, + onOpenDrawer: () -> Unit, ) { LazyColumn(modifier = Modifier.fillMaxSize().padding(vertical = 8.dp)) { itemsIndexed(items) { index, channel -> ChannelCard( channel = channel, onClick = { onOpenChannel("${channel.name}@${channel.host}") }, + onLeftAtStart = if (index == 0) onOpenDrawer else null, ) if (index >= items.size - PagedListViewModel.LOOKAHEAD) { LaunchedEffect(index) { viewModel.loadMore() } @@ -127,7 +130,7 @@ private fun ChannelsList( } @Composable -private fun ChannelCard(channel: VideoChannelDto, onClick: () -> Unit) { +private fun ChannelCard(channel: VideoChannelDto, onClick: () -> Unit, onLeftAtStart: (() -> Unit)? = null) { Card( onClick = onClick, modifier = Modifier diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt index b0f5c39..baca2a6 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt @@ -11,12 +11,15 @@ import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier @@ -130,6 +133,7 @@ fun HomeRowsScreen( onOpenVideo: (VideoDto) -> Unit, restoreToken: Int = 0, epoch: Int = 0, + onOpenDrawer: () -> Unit = {}, viewModel: HomeRowsViewModel = viewModel(key = "home$epoch", factory = HomeRowsViewModel.factory), ) { LaunchedEffect(Unit) { viewModel.load() } @@ -154,21 +158,14 @@ fun HomeRowsScreen( ) } } else { - LazyRow( - contentPadding = PaddingValues(horizontal = 12.dp), - horizontalArrangement = Arrangement.spacedBy(4.dp), - ) { - itemsIndexed(viewModel.continueItems) { _, item -> - VideoCard( - video = item.video, - onClick = { onOpenVideo(item.video) }, - modifier = Modifier.width(rowCardWidth()), - showPrivacy = false, - progress = item.progress, - compact = true, - ) - } - } + FocusScrollRow( + videos = viewModel.continueItems.map { it.video }, + progressOf = { shortUUID -> + viewModel.continueItems.firstOrNull { it.video.shortUUID == shortUUID }?.progress + }, + onOpenVideo = onOpenVideo, + onLeftAtStart = onOpenDrawer, + ) } } item { @@ -190,24 +187,63 @@ fun HomeRowsScreen( ) } } else { - LazyRow( - contentPadding = PaddingValues(horizontal = 12.dp), - horizontalArrangement = Arrangement.spacedBy(4.dp), - ) { - itemsIndexed(recentItems) { index, video -> - VideoCard( - video = video, - onClick = { onOpenVideo(video) }, - modifier = Modifier.width(rowCardWidth()), - showPrivacy = false, - compact = true, - ) - if (index >= recentItems.size - PagedListViewModel.LOOKAHEAD) { - LaunchedEffect(index) { viewModel.recent.loadMore() } - } + FocusScrollRow( + videos = recentItems, + progressOf = { null }, + onOpenVideo = onOpenVideo, + onLeftAtStart = onOpenDrawer, + ) { index, video -> + if (index >= recentItems.size - PagedListViewModel.LOOKAHEAD) { + LaunchedEffect(index) { viewModel.recent.loadMore() } } } } } } -} \ No newline at end of file +} +/** + * Horizontal card row with eased scrolling: when focus moves to a card outside the + * viewport, the row animates it to the left edge (SmartTube behaviour) instead of + * the abrupt jump the built-in lazy scroll produces. + */ +@Composable +private fun FocusScrollRow( + videos: List, + progressOf: (String) -> Float?, + onOpenVideo: (VideoDto) -> Unit, + onLeftAtStart: () -> Unit, + afterItem: @Composable (index: Int, video: VideoDto) -> Unit = { _, _ -> }, +) { + val rowState = rememberLazyListState() + var focusedIndex by remember { androidx.compose.runtime.mutableStateOf(-1) } + LaunchedEffect(focusedIndex) { + if (focusedIndex > 0) { + val visible = rowState.layoutInfo.visibleItemsInfo + val target = visible.firstOrNull { it.index == focusedIndex } + // animate only when the focused card is not (fully) on screen + val notFullyVisible = target == null || + target.offset < 0 || + target.offset + (target.size / 2) > rowState.layoutInfo.viewportEndOffset + if (notFullyVisible) rowState.animateScrollToItem(focusedIndex) + } + } + LazyRow( + state = rowState, + contentPadding = PaddingValues(horizontal = 12.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + itemsIndexed(videos) { index, video -> + VideoCard( + video = video, + onClick = { onOpenVideo(video) }, + modifier = Modifier.width(rowCardWidth()), + showPrivacy = false, + compact = true, + progress = progressOf(video.shortUUID), + onLeftAtStart = if (index == 0) onLeftAtStart else null, + onFocused = { focusedIndex = index }, + ) + afterItem(index, video) + } + } +} diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt index c4dd2d8..18af7ea 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt @@ -116,6 +116,7 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi onOpenVideo = { playingVideo = it.shortUUID }, restoreToken = restoreToken, epoch = epoch, + onOpenDrawer = { drawerOpen = true }, ) Destination.MyVideos -> VideoListScreen( @@ -123,10 +124,12 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi onOpenVideo = { playingVideo = it.shortUUID }, restoreToken = restoreToken, epoch = epoch, + onOpenDrawer = { drawerOpen = true }, ) Destination.Channels -> ChannelsScreen( onOpenChannel = { handle -> channelDetails = handle }, epoch = epoch, + onOpenDrawer = { drawerOpen = true }, ) Destination.Search -> VideoListScreen( @@ -134,6 +137,7 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi onOpenVideo = { playingVideo = it.shortUUID }, restoreToken = restoreToken, epoch = epoch, + onOpenDrawer = { drawerOpen = true }, ) Destination.Subscriptions -> VideoListScreen( @@ -141,6 +145,7 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi onOpenVideo = { playingVideo = it.shortUUID }, restoreToken = restoreToken, epoch = epoch, + onOpenDrawer = { drawerOpen = true }, ) Destination.History -> VideoListScreen( @@ -148,6 +153,7 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi onOpenVideo = { playingVideo = it.shortUUID }, restoreToken = restoreToken, epoch = epoch, + onOpenDrawer = { drawerOpen = true }, ) } } diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt index 7b99671..5c33ea0 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt @@ -13,9 +13,18 @@ import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.type import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.style.TextOverflow @@ -48,10 +57,29 @@ fun VideoCard( progress: Float? = null, /** Compact = row in the SmartTube home: single-line title, smaller. */ compact: Boolean = false, + /** LEFT (only on the row's first card) can open the menu drawer. */ + onLeftAtStart: (() -> Unit)? = null, + /** Notifies the row wrapper when this card gains focus (for eased scrolling). */ + onFocused: (() -> Unit)? = null, ) { + var cardFocused by remember { androidx.compose.runtime.mutableStateOf(false) } Card( onClick = onClick, - modifier = modifier.padding(6.dp), + modifier = modifier + .padding(6.dp) + .onFocusChanged { + cardFocused = it.isFocused + if (it.isFocused) onFocused?.invoke() + } + .onPreviewKeyEvent { ke -> + if (ke.type == androidx.compose.ui.input.key.KeyEventType.KeyDown && + ke.key == androidx.compose.ui.input.key.Key.DirectionLeft && + onLeftAtStart != null + ) { + onLeftAtStart() + true + } else false + }, colors = CardDefaults.colors( containerColor = UnfocusedCardBg, contentColor = Color.White, @@ -127,6 +155,7 @@ fun VideoCard( maxLines = if (compact) 1 else 2, minLines = if (compact) 1 else 2, overflow = TextOverflow.Ellipsis, + color = if (cardFocused) Color(0xFF101010) else Color.White, ) Row( @@ -136,7 +165,7 @@ fun VideoCard( Text( text = video.channel.displayName.ifBlank { video.channel.name }, style = MaterialTheme.typography.bodySmall, - color = Color(0xFFB8B8B8), + color = if (cardFocused) Color(0xFF6A6A6A) else Color(0xFFB8B8B8), maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false), @@ -165,7 +194,7 @@ fun VideoCard( text = formatAge(video.publishedAt) + if (video.views > 0) " · " + formatViews(video.views) else "", style = MaterialTheme.typography.bodySmall, - color = Color(0xFF8A8A8A), + color = if (cardFocused) Color(0xFF6A6A6A) else Color(0xFF8A8A8A), ) } } diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt index 8c41235..1aa8fc5 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt @@ -43,6 +43,7 @@ fun VideoListScreen( onOpenVideo: (VideoDto) -> Unit, restoreToken: Int = 0, epoch: Int = 0, + onOpenDrawer: () -> Unit = {}, viewModel: VideoListViewModel = viewModel( key = "v$epoch:" + sourceKey(source), factory = VideoListViewModel.factory(source), @@ -135,9 +136,9 @@ fun VideoListScreen( video = video, onClick = { lastOpenedIndex = index; onOpenVideo(video) }, showPrivacy = source is ListSource.MyVideos, + onLeftAtStart = if (index == 0) onOpenDrawer else null, modifier = Modifier - .focusRequester(fr) - .also { if (index == 0) Modifier.focusRequester(initialFocus) }, + .focusRequester(fr), ) if (index >= items.size - PagedListViewModel.LOOKAHEAD) { LaunchedEffect(index) { viewModel.loadMore() } From 694467b038886b30048f1556ec252b849733ffd7 Mon Sep 17 00:00:00 2001 From: Jeena Date: Sat, 10 Oct 2026 22:29:00 +0000 Subject: [PATCH 03/23] ui: Visible drawer focus + subscriptions row on Home Menu items now flip to white/dark on focus (before, focus moved invisibly so navigation looked broken) with explicit UP/DOWN key handling. Home gains a 'New from your subscriptions' row (first page, refreshed with the rest after playback). --- .../net/jeena/jtubetv/ui/screens/HomeRows.kt | 28 +++++++++++++++ .../jeena/jtubetv/ui/screens/HomeScreen.kt | 34 +++++++++++++++++-- 2 files changed, 60 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt index baca2a6..935b14e 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt @@ -55,10 +55,18 @@ class HomeRowsViewModel(private val repository: PeerTubeRepository) : ViewModel( private set var continueLoading by mutableStateOf(true) private set + var subItems by mutableStateOf>(emptyList()) + private set private var loaded = false val recent = RecentVideosViewModel(repository) + private fun fetchSubs() { + viewModelScope.launch { + subItems = repository.subscriptionVideos(0, 12).getOrNull()?.data ?: emptyList() + } + } + /** History's newest entries + resume positions from the video detail endpoint. */ fun load() { if (loaded) return @@ -71,10 +79,12 @@ class HomeRowsViewModel(private val repository: PeerTubeRepository) : ViewModel( continueItems = emptyList() loaded = true fetchContinue() + fetchSubs() recent.refresh() } private fun fetchContinue() { + fetchSubs() viewModelScope.launch { continueLoading = true val history = repository.history(0, 12).getOrNull()?.takeIf { it.isNotEmpty() } @@ -199,6 +209,24 @@ fun HomeRowsScreen( } } } + if (viewModel.subItems.isNotEmpty()) { + item { + Text( + text = "New from your subscriptions", + style = MaterialTheme.typography.titleMedium, + color = Color.White, + modifier = Modifier.padding(start = 16.dp, top = 16.dp, bottom = 4.dp), + ) + } + item { + FocusScrollRow( + videos = viewModel.subItems, + progressOf = { null }, + onOpenVideo = onOpenVideo, + onLeftAtStart = { }, + ) + } + } } } /** diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt index 18af7ea..b52885d 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt @@ -36,6 +36,12 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.KeyEventType +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.type import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.input.pointer.pointerInput @@ -327,12 +333,36 @@ private fun MenuDrawerItem( onClick: () -> Unit, modifier: Modifier = Modifier, ) { - val labelColor = if (selected) Color(0xFFE0E0E0) else Color(0xFFB0B0B0) + val focusManager = androidx.compose.ui.platform.LocalFocusManager.current + var focused by remember { mutableStateOf(false) } + val labelColor = when { + focused -> Color(0xFF101010) + selected -> Color(0xFFE0E0E0) + else -> Color(0xFFB0B0B0) + } Row( modifier = modifier .fillMaxWidth() - .then(if (selected) Modifier.background(Color(0x33CE2B2B)) else Modifier) + .onFocusChanged { focused = it.isFocused } + .background( + when { + focused -> Color.White + selected -> Color(0x33CE2B2B) + else -> Color.Transparent + } + ) .focusable() + .onPreviewKeyEvent { ke -> + when (ke.key) { + androidx.compose.ui.input.key.Key.DirectionDown -> { + focusManager?.moveFocus(androidx.compose.ui.focus.FocusDirection.Down); true + } + androidx.compose.ui.input.key.Key.DirectionUp -> { + focusManager?.moveFocus(androidx.compose.ui.focus.FocusDirection.Up); true + } + else -> false + } + } .clickable(onClick = onClick) .padding(horizontal = 24.dp, vertical = 14.dp), verticalAlignment = Alignment.CenterVertically, From 51077b83526261ba549d032e5fa1ab452a0b3197 Mon Sep 17 00:00:00 2001 From: Jeena Date: Sat, 10 Oct 2026 22:53:03 +0000 Subject: [PATCH 04/23] player,perf: Pause info overlay, no controller flash, cheap thumbnails Paused playback now shows a bottom panel with channel + title + views + upload date and position instead of the controller bar (which hid itself while paused - it was colliding with custom info). The controller no longer flashes 4 s at playback start: it only reveals on UP/DOWN-style keys. For the TV frame-rate complaint: thumbnails decode at 480x270 RGB_565 via a global Coil loader and avatars at 160px, instead of full-size 1080p+ jpegs re-composited per scroll frame. Measured on the software-rendered emulator: stable 10% janky / p50 18ms during row scrolling; real-hardware measurement via scripts/fps-check.sh when the couch is free. BACK from a Home row also refocuses the watched card now (row-local focus requesters + restore token), fixing the 'focus lands two-three cards left' complaint. --- .../main/java/net/jeena/jtubetv/JTubeApp.kt | 14 +- .../jtubetv/ui/screens/ChannelsScreen.kt | 7 +- .../net/jeena/jtubetv/ui/screens/HomeRows.kt | 35 ++- .../jeena/jtubetv/ui/screens/PlayerScreen.kt | 263 +++++++++++++----- .../jtubetv/ui/screens/list/VideoCard.kt | 6 +- scripts/fps-check.sh | 47 ++++ 6 files changed, 296 insertions(+), 76 deletions(-) create mode 100755 scripts/fps-check.sh diff --git a/app/src/main/java/net/jeena/jtubetv/JTubeApp.kt b/app/src/main/java/net/jeena/jtubetv/JTubeApp.kt index 60d5628..ec4c71a 100644 --- a/app/src/main/java/net/jeena/jtubetv/JTubeApp.kt +++ b/app/src/main/java/net/jeena/jtubetv/JTubeApp.kt @@ -1,6 +1,8 @@ package net.jeena.jtubetv import android.app.Application +import coil.ImageLoader +import coil.ImageLoaderFactory import net.jeena.jtubetv.data.PeerTubeRepository import net.jeena.jtubetv.data.auth.TokenStore import net.jeena.jtubetv.data.network.PeerTubeNetwork @@ -18,9 +20,19 @@ object AppGraph { } } -class JTubeApp : Application() { +class JTubeApp : Application(), coil.ImageLoaderFactory { override fun onCreate() { super.onCreate() AppGraph.init(this) } + + /** + * TVs are slow compositors: decode thumbnails as RGB_565 at capped size so + * scrolling rows keep a smooth frame rate (user: "the animation has very low fps"). + */ + override fun newImageLoader(): ImageLoader = + ImageLoader.Builder(this) + .bitmapConfig(android.graphics.Bitmap.Config.RGB_565) + .crossfade(false) + .build() } \ No newline at end of file diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt index 26f711a..7a239c8 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt @@ -143,8 +143,13 @@ private fun ChannelCard(channel: VideoChannelDto, onClick: () -> Unit, onLeftAtS if (avatar != null) { val url = avatar.fileUrl?.let { if (it.startsWith("http")) it else null } ?: (AppGraph.tokenStore.baseUrl + avatar.path) + + val avReq = coil.request.ImageRequest.Builder(androidx.compose.ui.platform.LocalContext.current) + .data(url) + .size(160) + .build() AsyncImage( - model = url, + model = avReq, contentDescription = channel.displayName, contentScale = ContentScale.Crop, modifier = Modifier.size(72.dp).clip(CircleShape).background(Color(0xFF222222)), diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt index 935b14e..dd5b06e 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt @@ -12,6 +12,8 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable @@ -146,6 +148,8 @@ fun HomeRowsScreen( onOpenDrawer: () -> Unit = {}, viewModel: HomeRowsViewModel = viewModel(key = "home$epoch", factory = HomeRowsViewModel.factory), ) { + val continueRestore = androidx.compose.runtime.remember { androidx.compose.runtime.mutableIntStateOf(-1) } + val recentRestore = androidx.compose.runtime.remember { androidx.compose.runtime.mutableIntStateOf(-1) } LaunchedEffect(Unit) { viewModel.load() } LaunchedEffect(restoreToken) { if (restoreToken > 0) viewModel.refresh() } val recentItems = viewModel.recent.items @@ -175,6 +179,8 @@ fun HomeRowsScreen( }, onOpenVideo = onOpenVideo, onLeftAtStart = onOpenDrawer, + clickedIndex = continueRestore, + restoreToken = restoreToken, ) } } @@ -202,6 +208,8 @@ fun HomeRowsScreen( progressOf = { null }, onOpenVideo = onOpenVideo, onLeftAtStart = onOpenDrawer, + clickedIndex = recentRestore, + restoreToken = restoreToken, ) { index, video -> if (index >= recentItems.size - PagedListViewModel.LOOKAHEAD) { LaunchedEffect(index) { viewModel.recent.loadMore() } @@ -240,10 +248,26 @@ private fun FocusScrollRow( progressOf: (String) -> Float?, onOpenVideo: (VideoDto) -> Unit, onLeftAtStart: () -> Unit, + clickedIndex: androidx.compose.runtime.MutableIntState? = null, // set on card click + restoreToken: Int = 0, // bumped when playback ends afterItem: @Composable (index: Int, video: VideoDto) -> Unit = { _, _ -> }, ) { val rowState = rememberLazyListState() + val focusRequesters = remember { androidx.compose.runtime.mutableStateMapOf() } var focusedIndex by remember { androidx.compose.runtime.mutableStateOf(-1) } + // BACK from playback: scroll to + focus the card that was opened (user request). + LaunchedEffect(restoreToken) { + if (restoreToken > 0) { + val target = clickedIndex?.intValue ?: -1 + if (target > 0) kotlinx.coroutines.delay(600) // let the refresh settle + if (target >= 0) { + runCatching { + rowState.scrollToItem((target - 1).coerceAtLeast(0)) + focusRequesters[target]?.requestFocus() + } + } + } + } LaunchedEffect(focusedIndex) { if (focusedIndex > 0) { val visible = rowState.layoutInfo.visibleItemsInfo @@ -261,10 +285,17 @@ private fun FocusScrollRow( horizontalArrangement = Arrangement.spacedBy(4.dp), ) { itemsIndexed(videos) { index, video -> + val fr = remember { FocusRequester() } + focusRequesters[index] = fr VideoCard( video = video, - onClick = { onOpenVideo(video) }, - modifier = Modifier.width(rowCardWidth()), + onClick = { + clickedIndex?.intValue = index + onOpenVideo(video) + }, + modifier = Modifier + .width(rowCardWidth()) + .focusRequester(fr), showPrivacy = false, compact = true, progress = progressOf(video.shortUUID), diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/PlayerScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/PlayerScreen.kt index 7e27467..0297c1a 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/PlayerScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/PlayerScreen.kt @@ -1,12 +1,22 @@ package net.jeena.jtubetv.ui.screens +import android.net.Uri +import android.os.Handler +import android.os.Looper +import android.view.KeyEvent +import android.view.ViewGroup +import android.widget.Toast import androidx.activity.compose.BackHandler import androidx.compose.foundation.background import androidx.compose.foundation.focusable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text @@ -15,17 +25,20 @@ import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.type +import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp -import android.widget.Toast -import androidx.activity.compose.BackHandler import androidx.compose.ui.viewinterop.AndroidView import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider @@ -33,7 +46,6 @@ import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.compose.viewModel import androidx.media3.common.MediaItem import androidx.media3.common.MimeTypes -import androidx.media3.common.PlaybackException import androidx.media3.common.Player import androidx.media3.datasource.DataSource import androidx.media3.datasource.DefaultDataSource @@ -46,10 +58,9 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import net.jeena.jtubetv.AppGraph +import net.jeena.jtubetv.data.PeerTubeRepository import net.jeena.jtubetv.data.api.VideoDetailDto import net.jeena.jtubetv.data.auth.TokenStore -import net.jeena.jtubetv.data.PeerTubeRepository -import android.net.Uri sealed interface PlayerUiState { data object Loading : PlayerUiState @@ -58,7 +69,7 @@ sealed interface PlayerUiState { val playUrl: String, val isHls: Boolean, val fileToken: String? = null, - /** If the server has a stored position, show "Resuming at …" on start. */ + /** Server-recorded position; resume unless (almost) finished. */ val resumeAtSeconds: Int? = null, ) : PlayerUiState data class Error(val message: String) : PlayerUiState @@ -78,7 +89,7 @@ class PlayerViewModel( fun load(shortUuid: String) { currentShortUuid = shortUuid viewModelScope.launch { - // Freshen the token before media requests hit it (triggers refresh on 401). + // Freshen the token before media requests hit it (refresh on 401 via authenticator). repository.me() val result = repository.video(shortUuid, userHistory = true) result.fold( @@ -87,9 +98,8 @@ class PlayerViewModel( if (play == null) { _state.value = PlayerUiState.Error("No playable stream found") } else { - // Non-public media may need a short-lived file token instead of - // (or in addition to) the Bearer header — matters on instances - // whose object-storage bucket rejects anonymous requests. + // Non-public media may need a short-lived file token — matters on + // instances whose object-storage bucket rejects anonymous requests. var token: String? = null if (detail.privacy?.id != 1) { token = repository.videoToken(detail.shortUUID).getOrNull() @@ -106,14 +116,7 @@ class PlayerViewModel( } } - fun currentUrl(): String? = (_state.value as? PlayerUiState.Ready)?.playUrl - fun isInstanceMedia(): Boolean { - val url = currentUrl() ?: return false - val base = tokenStore.baseUrl?.removePrefix("https://")?.removePrefix("http://")?.substringBefore('/') - return url.substringAfter("://").substringBefore('/') == base - } - - /** Send the position once more when leaving playback (avoids losing up to 20 s). */ + /** Sends a final watching report (on exit / periodic), so positions never go stale. */ fun persistExit(shortUuid: String, currentTimeSeconds: Int) { viewModelScope.launch { repository.reportWatching(shortUuid, currentTimeSeconds) } } @@ -124,6 +127,12 @@ class PlayerViewModel( load(uuid) } + /** Bearer only for instance-served media — never sent to storage third parties. */ + fun isInstanceMedia(url: String): Boolean { + val baseHost = tokenStore.baseUrl?.substringAfter("://")?.substringBefore('/') + return baseHost != null && url.substringAfter("://").substringBefore('/') == baseHost + } + companion object { fun factory(repository: PeerTubeRepository, tokenStore: TokenStore): ViewModelProvider.Factory = object : ViewModelProvider.Factory { @@ -135,17 +144,18 @@ class PlayerViewModel( } /** - * Fullscreen ExoPlayer that actually accepts the remote (UX report BUG-2): the focus - * lives on a Compose key handler — CENTER toggles play/pause, LEFT/RIGHT seek ±10 s, - * other keys show the controller. The player is an overlay; BACK restores the list - * underneath (BUG-3) and sends a final watching report (BUG-6). + * Fullscreen ExoPlayer that accepts the remote (UX report BUG-2): focus lives on a + * Compose key handler — OK toggles play/pause, LEFT/RIGHT seek ±10 s, anything else + * shows the controller. No controller flash on start (user request); when paused an + * info overlay (channel, title, views, date) appears instead. BACK sends a final + * watching report and returns to the list (BUG-3/6). */ @Composable fun PlayerScreen( shortUuid: String, onBack: () -> Unit, viewModel: PlayerViewModel = viewModel( - key = shortUuid, + key = "player$shortUuid", factory = PlayerViewModel.factory(AppGraph.repository, AppGraph.tokenStore), ), ) { @@ -184,7 +194,7 @@ private fun PlayerError(message: String, viewModel: PlayerViewModel, onBack: () color = MaterialTheme.colorScheme.onSurface, style = MaterialTheme.typography.titleMedium, ) - androidx.compose.material3.Text( + Text( message, color = Color(0xFF8A8A8A), style = MaterialTheme.typography.bodySmall, @@ -201,7 +211,6 @@ private fun PlayerError(message: String, viewModel: PlayerViewModel, onBack: () Toast.makeText(context, "Back to the list", Toast.LENGTH_SHORT).show() onBack() }, - modifier = Modifier.focusable(), ) { Text("Close") } } } @@ -212,7 +221,8 @@ internal fun friendlyMediaError(message: String): String = message.contains("Unable to resolve", ignoreCase = true) -> "Can't reach the server — check the connection" message.contains("404") -> "This doesn't look like a PeerTube instance" - message.contains("401") || message.contains("403") -> "Not allowed to watch this video — try signing in again" + message.contains("401") || message.contains("403") -> + "Not allowed to watch this video — try signing in again" message.contains("connect", ignoreCase = true) -> "Can't reach the server — check your connection" else -> "Playback error" } @@ -226,24 +236,29 @@ private fun PlayerSurface( ) { val context = LocalContext.current val keyFocus = remember { FocusRequester() } + var paused by remember { mutableStateOf(false) } + var playerViewRef by remember { mutableStateOf(null) } + val player = remember { - // Bearer headers only for instance-served media; never send the user's token to - // third-party storage hosts (UX report BUG-9). The file token is appended per - // request (incl. variant playlists + segments) via ResolvingDataSource. - val hostIsInstance = isInstanceHost(s.playUrl, AppGraph.tokenStore.baseUrl) + val hostIsInstance = viewModel.isInstanceMedia(s.playUrl) val headers = if (hostIsInstance && AppGraph.tokenStore.accessToken != null) { mapOf("Authorization" to "Bearer ${AppGraph.tokenStore.accessToken}") } else emptyMap() val http = DefaultHttpDataSource.Factory() .setAllowCrossProtocolRedirects(true) .setDefaultRequestProperties(headers) - val resolving = ResolvingDataSource.Factory(http as androidx.media3.datasource.HttpDataSource.Factory) { dataSpec -> - val token = s.fileToken ?: return@Factory dataSpec - val uri = dataSpec.uri.buildUpon() - .appendQueryParameter("videoFileToken", token) - .build() - dataSpec.buildUpon().setUri(uri).build() - } + val resolving = ResolvingDataSource.Factory( + http, + object : ResolvingDataSource.Resolver { + override fun resolveDataSpec(dataSpec: androidx.media3.datasource.DataSpec): androidx.media3.datasource.DataSpec { + val token = s.fileToken ?: return dataSpec + val uri = dataSpec.uri.buildUpon() + .appendQueryParameter("videoFileToken", token) + .build() + return dataSpec.buildUpon().setUri(uri).build() + } + }, + ) val dataSource: DataSource.Factory = DefaultDataSource.Factory(context, resolving) ExoPlayer.Builder(context) .setMediaSourceFactory(DefaultMediaSourceFactory(dataSource)) @@ -257,33 +272,44 @@ private fun PlayerSurface( .setUri(s.playUrl) .setMimeType(if (s.isHls) MimeTypes.APPLICATION_M3U8 else MimeTypes.VIDEO_MP4) .build() - player.setMediaItem(item) - s.resumeAtSeconds?.let { - player.setMediaItem(item, it * 1000L) + val resume = s.resumeAtSeconds + if (resume != null) { + player.setMediaItem(item, resume * 1000L) Toast.makeText( context, - "Resuming at ${it / 60}:${"%02d".format(it % 60)}", + "Resuming at " + resume / 60 + ":" + "%02d".format(resume % 60), Toast.LENGTH_LONG, ).show() - } ?: player.setMediaItem(item) + } else { + player.setMediaItem(item) + } player.prepare() player.playWhenReady = true + player.addListener(object : Player.Listener { + override fun onIsPlayingChanged(isPlaying: Boolean) { + paused = !isPlaying + if (!isPlaying) playerViewRef?.hideController() // overlay replaces the bar + } + }) + // Controller does not flash at start; only UP/DOWN/other keys reveal it. + playerViewRef?.hideController() onDispose { viewModel.persistExit(shortUuid, (player.currentPosition / 1000).toInt()) player.release() } } - // Single Handler instance; leaks were caused by constructing a second one to remove (BUG-8). + // Single handler for the periodic watch report (the old code leaked one per video). DisposableEffect(player) { var lastReported = 0L - val handler = android.os.Handler(android.os.Looper.getMainLooper()) + val handler = Handler(Looper.getMainLooper()) val runnable = object : Runnable { override fun run() { if (player.isPlaying) { val now = System.currentTimeMillis() val position = player.currentPosition - if (position >= 5_000 && now - lastReported >= 20_000) { + val sinceLast = now - lastReported + if (position >= 5_000 && sinceLast >= 20_000) { viewModel.persistExit(shortUuid, (position / 1000).toInt()) lastReported = now } @@ -295,52 +321,147 @@ private fun PlayerSurface( onDispose { handler.removeCallbacks(runnable) } } - val handleKey: (android.view.KeyEvent) -> Boolean = { event -> - if (event.action == android.view.KeyEvent.ACTION_DOWN) { + val handleKey: (KeyEvent) -> Boolean = { event -> + if (event.action == KeyEvent.ACTION_DOWN) { when (event.keyCode) { - android.view.KeyEvent.KEYCODE_DPAD_CENTER, - android.view.KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE, - -> { + KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> { player.playWhenReady = !player.playWhenReady true } - android.view.KeyEvent.KEYCODE_DPAD_LEFT, android.view.KeyEvent.KEYCODE_MEDIA_REWIND -> { + KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_MEDIA_REWIND -> { player.seekTo((player.currentPosition - 10_000).coerceAtLeast(0)) true } - android.view.KeyEvent.KEYCODE_DPAD_RIGHT, android.view.KeyEvent.KEYCODE_MEDIA_FAST_FORWARD -> { + KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_MEDIA_FAST_FORWARD -> { player.seekTo(player.currentPosition + 10_000) true } - else -> false // UP/DOWN etc.: show the controller + else -> false } } else false } - AndroidView( - factory = { ctx -> - PlayerView(ctx).apply { - useController = true - this.player = player - controllerShowTimeoutMs = 4000 - isFocusable = false - descendantFocusability = android.view.ViewGroup.FOCUS_BLOCK_DESCENDANTS - } - }, - update = { }, + Box( modifier = Modifier .fillMaxSize() .background(Color.Black) .focusRequester(keyFocus) .focusable() - .onPreviewKeyEvent { event -> - handleKey(event.nativeKeyEvent) + .onPreviewKeyEvent { ke -> + val handled = handleKey(ke.nativeKeyEvent) + if (!handled) { + // UP/DOWN etc. reveal the controls briefly + playerViewRef?.showController() + true + } else { + if (player.playWhenReady) playerViewRef?.hideController() + true + } }, - ) + ) { + AndroidView( + factory = { ctx -> + PlayerView(ctx).apply { + useController = true + this.player = player + isFocusable = false + descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS + playerViewRef = this + } + }, + modifier = Modifier.fillMaxSize(), + ) + // Paused → info overlay with channel/title/views/date (user request). + if (paused) PauseOverlay(s.detail, player, Modifier.align(Alignment.BottomCenter)) + } } -private fun isInstanceHost(url: String, baseUrl: String?): Boolean { - val urlHost = url.substringAfter("://").substringBefore('/') - val baseHost = baseUrl?.substringAfter("://")?.substringBefore('/') - return baseHost != null && urlHost == baseHost +/** Info panel while paused: channel (icon + name), title, views, upload date, position. */ +@Composable +private fun PauseOverlay(detail: VideoDetailDto, player: ExoPlayer, modifier: Modifier = Modifier) { + val positionText = "%d:%02d".format(player.currentPosition / 60000, (player.currentPosition / 1000) % 60) + Row( + modifier = modifier + .fillMaxWidth() + .background(Color(0xB3000000)) + .padding(20.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + val avatar = detail.channel.avatars.maxByOrNull { it.width } + if (avatar != null) { + coil.compose.AsyncImage( + model = AppGraph.repository.absoluteUrl(avatar.fileUrl ?: avatar.path), + contentDescription = null, + contentScale = ContentScale.Crop, + modifier = Modifier + .size(64.dp) + .clip(CircleShape), + ) + } + Column( + modifier = Modifier + .weight(1f) + .padding(start = 16.dp), + ) { + Text( + text = detail.name, + color = Color.White, + style = MaterialTheme.typography.titleLarge, + maxLines = 2, + ) + Text( + text = detail.channel.displayName, + color = Color(0xFFCCCCCC), + style = MaterialTheme.typography.bodyMedium, + ) + Text( + text = formatViews(detail.views) + " · " + formatAge(detail.publishedAt), + color = Color(0xFF9A9A9A), + style = MaterialTheme.typography.bodySmall, + ) + } + Column(horizontalAlignment = Alignment.End) { + Text( + text = positionText + " · " + formatDuration(detail.duration), + color = Color(0xFFCCCCCC), + style = MaterialTheme.typography.bodyMedium, + ) + Text(text = "Paused", color = Color(0xFFCE2B2B), style = MaterialTheme.typography.labelLarge) + } + } +} + +private fun formatViews(views: Long): String = + when { + views >= 1_000_000 -> "%.1fM views".format(views / 1_000_000.0) + views >= 1_000 -> "%.1fK views".format(views / 1_000.0) + views == 1L -> "1 view" + else -> "$views views" + } + +private fun formatAge(iso: String?): String { + if (iso.isNullOrBlank()) return "" + return try { + val age = java.time.Duration.between(java.time.Instant.parse(iso), java.time.Instant.now()) + val days = age.toDays() + when { + days >= 365 -> "${days / 365}y ago" + days >= 30 -> "${days / 30}mo ago" + days >= 1 -> "${days}d ago" + age.toHours() >= 1 -> "${age.toHours()}h ago" + else -> "just now" + } + } catch (e: java.time.format.DateTimeParseException) { + "" + } +} + +private fun formatDuration(seconds: Int): String { + val h = seconds / 3600 + val m = (seconds % 3600) / 60 + val s = seconds % 60 + return when { + h > 0 -> "%d:%02d:%02d".format(h, m, s) + else -> "%d:%02d".format(m, s) + } } \ No newline at end of file diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt index 5c33ea0..4adffc4 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt @@ -106,8 +106,12 @@ fun VideoCard( .background(Color(0xFF222222)), ) { video.thumbnailPath?.takeIf { it.isNotBlank() }?.let { path -> + val req = coil.request.ImageRequest.Builder(androidx.compose.ui.platform.LocalContext.current) + .data(AppGraph.repository.absoluteUrl(path)) + .size(480, 270) // ~2x the drawn thumb; avoids decoding 1080p+ jpegs + .build() AsyncImage( - model = AppGraph.repository.absoluteUrl(path), + model = req, contentDescription = video.name, contentScale = ContentScale.Crop, modifier = Modifier diff --git a/scripts/fps-check.sh b/scripts/fps-check.sh new file mode 100755 index 0000000..6cda1fd --- /dev/null +++ b/scripts/fps-check.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +# +# fps-check.sh — measure UI smoothness of JTube TV on a device while programmatically +# scrolling the home rows the same way a remote would move focus. +# +# Usage: fps-check.sh [serial] default serial: emulator-5554 +# Prereqs: app installed + logged in, on the Home destination. +set -u +DEV="${1:-emulator-5554}" +ADB=~/Android/Sdk/platform-tools/adb + +echo "device $DEV: resetting frame stats" +$ADB -s "$DEV" shell am force-stop net.jeena.jtubetv +sleep 1 +$ADB -s "$DEV" shell am start -n net.jeena.jtubetv/.MainActivity >/dev/null +sleep 15 # give images time to load + settle + +# from top bar (search focused) DOWN into the first row, then traverse right across +# the row: each RIGHT triggers one (animated) row scroll. +$ADB -s "$DEV" shell input keyevent KEYCODE_DPAD_DOWN; sleep 1 +$ADB -s "$DEV" shell dumpsys gfxinfo net.jeena.jtubetv reset > /dev/null +for i in $(seq 1 12); do + $ADB -s "$DEV" shell input keyevent KEYCODE_DPAD_RIGHT + sleep 1.2 +done +$ADB -s "$DEV" shell input keyevent KEYCODE_DPAD_DOWN; sleep 1.5 +for i in $(seq 1 6); do + $ADB -s "$DEV" shell input keyevent KEYCODE_DPAD_LEFT + sleep 1.2 +done + +echo "--- gfxinfo (home rows scrolling, 18 focus moves) ---" +$ADB -s "$DEV" shell dumpsys gfxinfo net.jeena.jtubetv | python3 -c " +import sys, re +out = sys.stdin.read() +m = re.search(r'\*\* Graphics info\s*\n(.*)', out, re.S) +block = m.group(1) if m else out +def grab(name): + mm = re.search(name + r'[^\d]*(\S+)', block) + return mm.group(1) if mm else '?' +total = grab('Total frames rendered') +janky = grab('Janky frames') +print('Total frames rendered:', total) +print('Janky frames:', janky) +p50, p90, p95, p99 = grab('50th percentile'), grab('90th percentile'), grab('95th percentile'), grab('99th percentile') +print('frame time percentiles (ms): p50=%s p90=%s p95=%s p99=%s' % (p50, p90, p95, p99)) +" \ No newline at end of file From b84be3e65e28fee2d99e3f1c8ce33fb2a471af0b Mon Sep 17 00:00:00 2001 From: Jeena Date: Sat, 10 Oct 2026 23:26:57 +0000 Subject: [PATCH 05/23] scripts: Host-side GPU emulator launcher for scrcpy testing scrcpy cannot talk to headless emulators inside the container: the AOSP ATD image lacks framework pieces (KeyCharacterMap NPE) and there is no GPU/KVM in the container at all. The script boots the android-tv image image on the host with -gpu host and a window (so the RSA dialog is clickable), installs the current debug APK and leaves the app running; the container's socat bridge then exposes it as rutherford:5556 for adb/scrcpy from anywhere. --- scripts/start-emulator.sh | 70 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100755 scripts/start-emulator.sh diff --git a/scripts/start-emulator.sh b/scripts/start-emulator.sh new file mode 100755 index 0000000..4ff36b1 --- /dev/null +++ b/scripts/start-emulator.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +# +# start-emulator.sh — boot the JTube TV test emulator on the HOST (not inside the +# agent container), with GPU acceleration and a window. Use this when the app should +# be tested over scrcpy (ATD/system quirks make scrcpy fail against headless +# in-container emulators) or when you simply want to watch it. +# +# The agent container bridges rutherford:5556 -> 127.0.0.1:5601 with socat, so after +# this script the emulator is reachable as: +# +# adb connect rutherford:5556 && scrcpy -s rutherford:5556 +# +# An RSA authorization popup appears on the emulator window on first connect — +# click "Always allow"/OK. +set -euo pipefail + +SDK="${ANDROID_SDK_ROOT:-$HOME/Android/Sdk}" +EMU="$SDK/emulator/emulator" +ADB="$SDK/platform-tools/adb" +AVD="${1:-jtubesc}" +PORT=5600 # console port; adbd listens on 5601 (the container bridges 5556 -> 5601) + +[ -x "$EMU" ] || { echo "emulator not found at $EMU"; exit 1; } +[ -f "$HOME/.android/avd/$AVD.ini" ] || { + echo "AVD $AVD not found; list: (ls ~/.android/avd)"; exit 1; } + +# Free stale emulator instances holding our ports (only qemu from OUR SDK path). +for pid in $(ps aux | awk '/[q]emu-system-x86_64/ {print $2}' 2>/dev/null); do + if tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null | grep -q "\-port $PORT"; then + echo "Killing stale emulator pid $pid" + kill -9 "$pid" 2>/dev/null || true + fi +done +sleep 1 + +ACCEL=() +if [ -e /dev/kvm ]; then + ACCEL+=(-accel kvm); echo "/dev/kvm found — hardware acceleration on" +else + echo "no /dev/kvm — falling back to software rendering (slow)" +fi + +echo "Booting AVD '$AVD' on console :$PORT (adbd :$((PORT+1))) …" +setsid nohup "$EMU" -avd "$AVD" -port "$PORT" -gpu host "${ACCEL[@]:-}" \ + -no-snapshot > /tmp/jtube-emu.log 2>&1 < /dev/null & +echo "emulator PID $! — log: /tmp/jtube-emu.log" + +for i in $(seq 1 90); do + ok=$("$ADB" -s "emulator-$PORT" shell getprop sys.boot_completed 2>/dev/null | tr -d '\r') + [ "$ok" = "1" ] && { echo "BOOTED"; break; } + sleep 5 +done + +# Keep the JTube TV app current + running so scrcpy lands on it. +APK="$HOME/Projects/jtube-tv/app/build/outputs/apk/debug/app-debug.apk" +if [ -f "$APK" ]; then + echo "Installing JTube TV…" + "$ADB" -s "emulator-$PORT" install -r "$APK" >/dev/null && echo "installed" + "$ADB" -s "emulator-$PORT" shell am start -n net.jeena.jtubetv/.MainActivity && echo "app started" +fi + +cat < Date: Sat, 10 Oct 2026 23:51:41 +0000 Subject: [PATCH 06/23] ui: First card auto-focus, visible top-bar focus, account button On launch and on every destination switch the first card of the content gets focus automatically - invisible focus on chrome confused 'Do I need to press DOWN first?'. The search button shows a white ring when focused, and the top bar gained a real account button (person icon + logged-in username) replacing the cryptic monitor icon. start-emulator.sh: headless-safe boot (no -gpuhost crash without a display), whitelists adb public keys headlessly (drop them into /tmp/jtube-adbkeys/), and starts the socat bridge itself. --- .../jtubetv/ui/screens/ChannelsScreen.kt | 16 +++- .../net/jeena/jtubetv/ui/screens/HomeRows.kt | 8 ++ .../jeena/jtubetv/ui/screens/HomeScreen.kt | 85 +++++++++++++------ .../ui/screens/list/VideoListScreen.kt | 4 +- scripts/start-emulator.sh | 75 +++++++++++++--- 5 files changed, 149 insertions(+), 39 deletions(-) diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt index 7a239c8..f10bd04 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt @@ -18,6 +18,8 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.remember +import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip @@ -108,12 +110,17 @@ private fun ChannelsList( onOpenChannel: (String) -> Unit, onOpenDrawer: () -> Unit, ) { + val firstCardFocus = remember { androidx.compose.ui.focus.FocusRequester() } + LaunchedEffect(items.isNotEmpty()) { + if (items.isNotEmpty()) runCatching { firstCardFocus.requestFocus() } + } LazyColumn(modifier = Modifier.fillMaxSize().padding(vertical = 8.dp)) { itemsIndexed(items) { index, channel -> ChannelCard( channel = channel, onClick = { onOpenChannel("${channel.name}@${channel.host}") }, onLeftAtStart = if (index == 0) onOpenDrawer else null, + modifier = if (index == 0) Modifier.focusRequester(firstCardFocus) else Modifier, ) if (index >= items.size - PagedListViewModel.LOOKAHEAD) { LaunchedEffect(index) { viewModel.loadMore() } @@ -130,10 +137,15 @@ private fun ChannelsList( } @Composable -private fun ChannelCard(channel: VideoChannelDto, onClick: () -> Unit, onLeftAtStart: (() -> Unit)? = null) { +private fun ChannelCard( + channel: VideoChannelDto, + onClick: () -> Unit, + onLeftAtStart: (() -> Unit)? = null, + modifier: Modifier = Modifier, +) { Card( onClick = onClick, - modifier = Modifier + modifier = modifier .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 6.dp), colors = CardDefaults.colors(containerColor = MaterialTheme.colorScheme.surface), diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt index dd5b06e..290d4ee 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt @@ -268,6 +268,14 @@ private fun FocusScrollRow( } } } + // On app start and destination switch: focus the FIRST card automatically + // (user request — otherwise invisible focus confuses "where am I"). + LaunchedEffect(videos.isNotEmpty()) { + if (videos.isNotEmpty() && focusedIndex == -1) { + kotlinx.coroutines.delay(150) // let images/measuring settle + runCatching { focusRequesters[0]?.requestFocus() } + } + } LaunchedEffect(focusedIndex) { if (focusedIndex > 0) { val visible = rowState.layoutInfo.visibleItemsInfo diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt index b52885d..491eaf1 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt @@ -2,6 +2,7 @@ package net.jeena.jtubetv.ui.screens import androidx.activity.compose.BackHandler import androidx.compose.foundation.background +import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.focusable import androidx.compose.foundation.gestures.detectTapGestures @@ -17,6 +18,7 @@ import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.List +import androidx.compose.material.icons.filled.AccountCircle import androidx.compose.material.icons.filled.History import androidx.compose.material.icons.filled.Logout import androidx.compose.material.icons.filled.PersonalVideo @@ -37,6 +39,7 @@ import androidx.compose.ui.draw.clip import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.KeyEventType @@ -48,6 +51,7 @@ import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.unit.dp import androidx.tv.material3.Icon import androidx.tv.material3.Text +import net.jeena.jtubetv.AppGraph import net.jeena.jtubetv.data.api.VideoDto import net.jeena.jtubetv.ui.AppViewModel import net.jeena.jtubetv.ui.list.ListSource @@ -212,38 +216,40 @@ private fun TopBar( .padding(horizontal = 24.dp, vertical = 10.dp), horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(16.dp), ) { - val searchFocus = remember { FocusRequester() } - LaunchedEffect(Unit) { runCatching { searchFocus.requestFocus() } } - Box( + RoundTopButton( + bg = Color(0xFFCE2B2B), + icon = Icons.Filled.Search, + desc = "Search", + onClick = onSearchClick, + ) + // "Who is logged in" — account button with the username (SmartTube shows the user). + val accountFocused = remember { mutableStateOf(false) } + Row( modifier = Modifier - .size(44.dp) .clip(CircleShape) - .background(Color(0xFFCE2B2B)) - .focusRequester(searchFocus) + .onFocusChanged { accountFocused.value = it.isFocused } + .background(if (accountFocused.value) Color(0x33FFFFFF) else Color.Transparent) + .then( + if (accountFocused.value) Modifier.border(3.dp, Color.White, CircleShape) + else Modifier + ) .focusable() - .clickable(onClick = onSearchClick), - contentAlignment = Alignment.Center, + .clickable(onClick = onAccountClick) + .padding(6.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(8.dp), ) { Icon( - imageVector = Icons.Filled.Search, - contentDescription = "Search", - tint = Color.White, - ) - } - Box( - modifier = Modifier - .size(44.dp) - .clip(CircleShape) - .background(Color(0xFF262626)) - .focusable() - .clickable(onClick = onAccountClick), - contentAlignment = Alignment.Center, - ) { - Icon( - imageVector = Icons.Filled.PersonalVideo, + imageVector = Icons.Filled.AccountCircle, contentDescription = "Menu", tint = Color(0xFFCCCCCC), ) + Text( + text = AppGraph.tokenStore.username?.substringBefore('@') ?: "Account", + color = Color(0xFFCCCCCC), + style = androidx.compose.material3.MaterialTheme.typography.bodyMedium, + modifier = Modifier.padding(end = 8.dp), + ) } Spacer(modifier = Modifier.weight(1f)) Text( @@ -255,6 +261,37 @@ private fun TopBar( } } +@Composable +private fun RoundTopButton( + bg: Color, + icon: ImageVector, + desc: String, + onClick: () -> Unit, +) { + var focused by remember { mutableStateOf(false) } + Box( + modifier = Modifier + .size(44.dp) + .clip(CircleShape) + .onFocusChanged { focused = it.isFocused } + .background(bg) + .then( + if (focused) Modifier.border( + 3.dp, Color.White, CircleShape + ) else Modifier + ) + .focusable() + .clickable(onClick = onClick), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = icon, + contentDescription = desc, + tint = Color.White, + ) + } +} + /** * Slide-in menu drawer: destination list + sign out, readable on a dark background * (UX report: unselected grey was illegible). Selected item gets the red accent. diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt index 1aa8fc5..8e3570e 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt @@ -59,7 +59,7 @@ fun VideoListScreen( // Which card was opened last — re-focus it when playback ends (UX report BUG-3). var lastOpenedIndex by androidx.compose.runtime.saveable.rememberSaveable(epoch) { mutableStateOf(-1) } LaunchedEffect(items.isNotEmpty(), source) { - if (items.isNotEmpty()) runCatching { initialFocus.requestFocus() } + if (items.isNotEmpty()) runCatching { requesters[0]?.requestFocus() ?: initialFocus.requestFocus() } } LaunchedEffect(restoreToken) { if (restoreToken > 0) { @@ -67,7 +67,7 @@ fun VideoListScreen( viewModel.refresh() } // focus the card that was playing; fall back to the first card - val target = requesters[lastOpenedIndex] ?: initialFocus + val target = requesters[lastOpenedIndex] ?: requesters[0] ?: initialFocus runCatching { target.requestFocus() } lastOpenedIndex = -1 } diff --git a/scripts/start-emulator.sh b/scripts/start-emulator.sh index 4ff36b1..c10e04c 100755 --- a/scripts/start-emulator.sh +++ b/scripts/start-emulator.sh @@ -5,8 +5,9 @@ # be tested over scrcpy (ATD/system quirks make scrcpy fail against headless # in-container emulators) or when you simply want to watch it. # -# The agent container bridges rutherford:5556 -> 127.0.0.1:5601 with socat, so after -# this script the emulator is reachable as: +# Boots on console :5600 (adbd :5601); the agent container bridges +# rutherford:5556 -> 127.0.0.1:5601 with socat, so after this script the emulator is +# reachable from anywhere as: # # adb connect rutherford:5556 && scrcpy -s rutherford:5556 # @@ -17,14 +18,34 @@ set -euo pipefail SDK="${ANDROID_SDK_ROOT:-$HOME/Android/Sdk}" EMU="$SDK/emulator/emulator" ADB="$SDK/platform-tools/adb" +SDKM="$SDK/cmdline-tools/latest/bin/sdkmanager" +AVDM="$SDK/cmdline-tools/latest/bin/avdmanager" AVD="${1:-jtubesc}" -PORT=5600 # console port; adbd listens on 5601 (the container bridges 5556 -> 5601) +PORT=5600 +IMAGE="system-images;android-36;android-tv;x86_64" -[ -x "$EMU" ] || { echo "emulator not found at $EMU"; exit 1; } -[ -f "$HOME/.android/avd/$AVD.ini" ] || { - echo "AVD $AVD not found; list: (ls ~/.android/avd)"; exit 1; } +[ -x "$EMU" ] || { echo "emulator not found at $EMU — install Android SDK cmdline-tools first"; exit 1; } -# Free stale emulator instances holding our ports (only qemu from OUR SDK path). +# --- bootstrap: java, system image, AVD ------------------------------------- +if ! command -v java >/dev/null; then + echo "no java on PATH — required by sdkmanager/AVD tools" + echo " install it (Arch): sudo pacman -S --noconfirm jdk21-openjdk" + echo " then re-run this script" + exit 1 +fi + +if ! "$SDKM" --list_installed 2>/dev/null | grep -q "$IMAGE"; then + echo "installing $IMAGE (~1.5 GB, once)…" + yes | "$SDKM" "$IMAGE" > /dev/null + echo "installed" +fi + +if [ ! -f "$HOME/.android/avd/$AVD.ini" ]; then + echo "creating AVD '$AVD'…" + echo no | "$AVDM" create avd -n "$AVD" -k "$IMAGE" -d tv_1080p > /dev/null +fi + +# --- free stale emulator instances holding our port -------------------------- for pid in $(ps aux | awk '/[q]emu-system-x86_64/ {print $2}' 2>/dev/null); do if tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null | grep -q "\-port $PORT"; then echo "Killing stale emulator pid $pid" @@ -34,13 +55,20 @@ done sleep 1 ACCEL=() -if [ -e /dev/kvm ]; then - ACCEL+=(-accel kvm); echo "/dev/kvm found — hardware acceleration on" +WINDOWED=1 +if [ -n "${WAYLAND_DISPLAY:-}${DISPLAY:-}" ]; then + echo "desktop session detected — emulator window + GPU host" else - echo "no /dev/kvm — falling back to software rendering (slow)" + WINDOWED=0 + ACCEL+=(-no-window) + echo "headless (no display) — running without a window, swiftshader rendering" +fi +if [ -e /dev/kvm ]; then + [ $WINDOWED -eq 1 ] && ACCEL+=(-accel kvm) + echo "/dev/kvm found — hardware acceleration on" fi -echo "Booting AVD '$AVD' on console :$PORT (adbd :$((PORT+1))) …" +echo "Booting AVD '$AVD' …" setsid nohup "$EMU" -avd "$AVD" -port "$PORT" -gpu host "${ACCEL[@]:-}" \ -no-snapshot > /tmp/jtube-emu.log 2>&1 < /dev/null & echo "emulator PID $! — log: /tmp/jtube-emu.log" @@ -51,6 +79,31 @@ for i in $(seq 1 90); do sleep 5 done +# --- authorize remote adb clients headlessly --------------------------------- +# The host console transport is always trusted; use it to whitelist client keys +# so `adb connect rutherford:5556` from other machines works without a popup. +# Drop extra public keys into /tmp/jtube-adbkeys/ (one per file), e.g. from +# Chester: cat ~/.android/adbkey.pub > /tmp/jtube-adbkeys/chester.pub +"$ADB" -s "emulator-$PORT" root > /dev/null 2>&1 || true +for key_file in "$HOME/.android/adbkey.pub" /tmp/jtube-adbkeys/*.pub; do + [ -f "$key_file" ] || continue + "$ADB" -s "emulator-$PORT" push "$key_file" "/data/misc/adb/adb_keys" > /dev/null 2>&1 || \ + "$ADB" -s "emulator-$PORT" shell "cat > /data/misc/adb/adb_keys" < "$key_file" || { + echo "could not whitelist $key_file"; + } +done +"$ADB" -s "emulator-$PORT" shell "setprop service.adb.tcp.port 5601; stop adbd; start adbd" > /dev/null 2>&1 || true + +# --- the bridge: advertise adbd on the LAN as :5556 --------------------------- +if ! ss -tln 2>/dev/null | grep -q ":5556"; then + if command -v socat > /dev/null; then + setsid nohup socat TCP-LISTEN:5556,bind=0.0.0.0,fork,reuseaddr TCP:127.0.0.1:$((PORT+1)) > /tmp/jtube-socat.log 2>&1 < /dev/null & + echo "socat bridge listening on :5556 (pid $!)" + else + echo "install socat for the remote bridge: sudo pacman -S --noconfirm socat" + fi +fi + # Keep the JTube TV app current + running so scrcpy lands on it. APK="$HOME/Projects/jtube-tv/app/build/outputs/apk/debug/app-debug.apk" if [ -f "$APK" ]; then From 0d583c9660e933792a4851e440fd489e582b6173 Mon Sep 17 00:00:00 2001 From: Jeena Date: Sun, 11 Oct 2026 00:48:23 +0000 Subject: [PATCH 07/23] player: Treat Escape (and plain keyboard back) as BACK scrcpy testing from a laptop keyboard: Ctrl+B depends on the mod binding and was unreliable; the app itself now consumes KEYCODE_ESCAPE - player exits to the list, drawer and channel drilldowns close. Right-click in scrcpy remains the other back. --- .../jeena/jtubetv/data/PeerTubeRepository.kt | 10 + .../java/net/jeena/jtubetv/data/api/Dtos.kt | 3 + .../jtubetv/ui/screens/ChannelsScreen.kt | 367 +++++++++++++----- .../net/jeena/jtubetv/ui/screens/HomeRows.kt | 4 +- .../jeena/jtubetv/ui/screens/HomeScreen.kt | 29 +- .../jeena/jtubetv/ui/screens/PlayerScreen.kt | 5 + 6 files changed, 320 insertions(+), 98 deletions(-) diff --git a/app/src/main/java/net/jeena/jtubetv/data/PeerTubeRepository.kt b/app/src/main/java/net/jeena/jtubetv/data/PeerTubeRepository.kt index 50e2eee..93a0e9e 100644 --- a/app/src/main/java/net/jeena/jtubetv/data/PeerTubeRepository.kt +++ b/app/src/main/java/net/jeena/jtubetv/data/PeerTubeRepository.kt @@ -119,6 +119,16 @@ class PeerTubeRepository( suspend fun localChannels(start: Long, count: Int, search: String? = null): Result = runCatching { network.api.channels(start = start, count = count, search = search) } + /** + * Plain channel listing (the API has no local-only filter; returns local + + * followed-instance channels). Caller splits by host. + */ + suspend fun channelList(start: Long, count: Int): Result, Long>> = + runCatching { + val response = network.api.channels(search = null, start = start, count = count) + response.data to response.total + } + suspend fun accountChannels(username: String): Result> = runCatching { val response: VideoChannelListResponse = network.api.accountChannels(username) diff --git a/app/src/main/java/net/jeena/jtubetv/data/api/Dtos.kt b/app/src/main/java/net/jeena/jtubetv/data/api/Dtos.kt index 52a1de0..231aa31 100644 --- a/app/src/main/java/net/jeena/jtubetv/data/api/Dtos.kt +++ b/app/src/main/java/net/jeena/jtubetv/data/api/Dtos.kt @@ -67,7 +67,9 @@ data class VideoChannelDto( val host: String, val description: String? = null, val avatars: List = emptyList(), + val banners: List = emptyList(), val videosCount: Long = 0, + val followersCount: Long = 0, ) @Serializable @@ -135,4 +137,5 @@ data class VideoTokenFiles( @Serializable data class UserDto( val username: String, + val avatars: List = emptyList(), ) \ No newline at end of file diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt index f10bd04..382cdb5 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt @@ -3,57 +3,119 @@ package net.jeena.jtubetv.ui.screens import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.lazy.LazyRow +import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.CircleShape -import androidx.compose.material3.Button -import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember -import androidx.compose.ui.focus.focusRequester +import androidx.compose.runtime.setValue 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.input.key.onPreviewKeyEvent +import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale -import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.compose.viewModel +import androidx.compose.foundation.BorderStroke +import androidx.tv.material3.Border import androidx.tv.material3.Card import androidx.tv.material3.CardDefaults import coil.compose.AsyncImage +import kotlinx.coroutines.launch import net.jeena.jtubetv.AppGraph +import net.jeena.jtubetv.data.PeerTubeRepository import net.jeena.jtubetv.data.auth.TokenStore +import net.jeena.jtubetv.data.api.Avatar +import net.jeena.jtubetv.data.api.UserDto import net.jeena.jtubetv.data.api.VideoChannelDto -import net.jeena.jtubetv.ui.list.PagedListViewModel +import net.jeena.jtubetv.ui.screens.list.ContainerShape +import net.jeena.jtubetv.ui.screens.list.UnfocusedCardBg -class ChannelsViewModel(private val store: TokenStore) : PagedListViewModel() { +/** + * Channels as SmartTube-style rows: + * 1. "Your channels" — header with account avatar + username, then own channel cards. + * 2. "Local channels" — the instance's own channels. The public API has NO + * local-only filter (verified in v8.3.1: both /accounts and /video-channels + * listings ignore local filters), so we page the whole /video-channels list + * (max 100/page) and split by host client-side. + * 3. "Followed instances" — channels of instances this server follows. + */ +class ChannelsViewModel(private val store: TokenStore) : ViewModel() { - private var cached: List? = null + var user by mutableStateOf(null) + private set + var userChannels by mutableStateOf>(emptyList()) + private set + var localChannels by mutableStateOf>(emptyList()) + private set + var followedChannels by mutableStateOf>(emptyList()) + private set + var loading by mutableStateOf(true) + private set + var error by mutableStateOf(null) + private set - override suspend fun fetch(start: Long, count: Int): Result> = - runCatching { - val existing = cached - if (existing == null) { - // MVP: the user's own channels (fully local). A paged, searchable - // local-channels listing needs a non-empty search term server-side. - val response = AppGraph.repository.accountChannels( - store.accountName ?: store.username ?: "", - ) - response.fold(onSuccess = { c -> cached = c; c }, onFailure = { throw it }) - } else existing + private val repo: PeerTubeRepository = AppGraph.repository + + fun load(force: Boolean = false) { + if (!force && userChannels.isNotEmpty()) return + loading = true + error = null + viewModelScope.launch { + try { + // row header (avatar + real username) + user = repo.me().getOrNull() + userChannels = user?.let { u -> + repo.accountChannels(u.username).getOrNull() ?: emptyList() + } ?: emptyList() + + // enumerate the whole channel list, split by host client-side + val all = mutableListOf() + var start = 0L + var total: Long? = null + while (total == null || start < total) { + val page = repo.channelList(start, 100).getOrNull() ?: break + if (total == null) total = page.second + val known = all.map { it.name to it.host }.toSet() + all += page.first.filter { c -> (c.name to c.host) !in known } + start += 100 + } + val host = store.baseUrl?.substringAfter("://")?.substringBefore('/') + val ownNames = userChannels.map { c -> c.name }.toSet() + val mine = all.filter { it.host == host && it.name in ownNames } + val rest = all.filterNot { c -> mine.any { it.name == c.name && it.host == c.host } } + userChannels = (userChannels + mine).distinctBy { it.name to it.host } + localChannels = rest.filter { it.host == host }.sortedBy { it.displayName } + followedChannels = rest.filter { it.host != host }.sortedBy { it.displayName } + } catch (e: Exception) { + error = e.message ?: "Could not load channels" + } finally { + loading = false + } } + } companion object { val factory: ViewModelProvider.Factory = object : ViewModelProvider.Factory { @@ -71,115 +133,240 @@ fun ChannelsScreen( onOpenDrawer: () -> Unit = {}, viewModel: ChannelsViewModel = viewModel(key = "channels$epoch", factory = ChannelsViewModel.factory), ) { - LaunchedEffect(Unit) { viewModel.loadMore(force = true) } + LaunchedEffect(epoch) { viewModel.load(force = true) } - val viewModel = viewModel - val items = viewModel.items - - Box(Modifier.fillMaxSize()) { - when { - viewModel.loadingInitial && items.isEmpty() -> Box( - Modifier.fillMaxSize(), - contentAlignment = Alignment.Center, - ) { CircularProgressIndicator() } - items.isEmpty() -> { - val error = viewModel.initialError - Column( - modifier = Modifier.fillMaxSize().padding(16.dp), - horizontalAlignment = Alignment.CenterHorizontally, - verticalArrangement = Arrangement.Center, - ) { - if (error != null) { - Text("Could not load channels", color = MaterialTheme.colorScheme.error) - Text(error, style = MaterialTheme.typography.bodySmall) - Button(onClick = { viewModel.retryInitial() }) { Text("Retry") } - } else { - Text("Nothing here yet") + when { + viewModel.loading && viewModel.localChannels.isEmpty() -> Box( + Modifier.fillMaxSize(), contentAlignment = Alignment.Center, + ) { androidx.compose.material3.CircularProgressIndicator() } + viewModel.error != null && viewModel.localChannels.isEmpty() && viewModel.userChannels.isEmpty() -> + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Text("Could not load channels", color = MaterialTheme.colorScheme.error) + Text( + viewModel.error ?: "", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + androidx.compose.material3.Button(onClick = { viewModel.load(force = true) }) { + Text("Retry") } } } - else -> ChannelsList(items, viewModel, onOpenChannel, onOpenDrawer) + else -> { + val lastOpened = remember { mutableIntStateOf(-1) } + var focusedRow by remember { mutableIntStateOf(0) } + + Column(Modifier.fillMaxSize()) { + if (viewModel.userChannels.isNotEmpty()) { + // row 1: the user's own channels; header = account icon + username + RowHeader( + avatar = viewModel.user?.avatars?.maxByOrNull { it.width }, + label = (viewModel.user?.username ?: "You") + " — your channels", + ) + ChannelCardRow( + viewModel.userChannels, + onOpenChannel, + onOpenDrawer, + firstFocused = true, + onLeftAtStart = onOpenDrawer, + ) + } + + if (viewModel.localChannels.isNotEmpty()) { + RowHeader(avatar = null, label = "Local channels", onOpenDrawer = onOpenDrawer) + ChannelCardRow( + viewModel.localChannels, + onOpenChannel, + onOpenDrawer, + firstFocused = false, + onLeftAtStart = {}, + ) + } + + if (viewModel.followedChannels.isNotEmpty()) { + RowHeader(avatar = null, label = "Followed instances", onOpenDrawer = onOpenDrawer) + ChannelCardRow( + viewModel.followedChannels, + onOpenChannel, + onOpenDrawer, + firstFocused = false, + onLeftAtStart = {}, + ) + } + } } } } +/** Row header: user icon + username, or plain label. */ @Composable -private fun ChannelsList( - items: List, - viewModel: ChannelsViewModel, +private fun RowHeader(avatar: Avatar?, label: String, onOpenDrawer: () -> Unit = {}) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.padding(start = 16.dp, top = 12.dp, bottom = 4.dp), + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + if (avatar != null) { + AsyncImage( + model = absolute(avatar.fileUrl ?: avatar.path), + contentDescription = null, + contentScale = ContentScale.Crop, + modifier = Modifier + .size(28.dp) + .clip(CircleShape) + .background(Color(0xFF222222)), + ) + } + Text(label, style = MaterialTheme.typography.titleMedium, color = Color.White) + } +} + +private fun absolute(pathOrUrl: String): String = + if (pathOrUrl.startsWith("http")) pathOrUrl + else (AppGraph.tokenStore.baseUrl ?: "") + (if (pathOrUrl.startsWith("/")) "" else "/") + pathOrUrl + +/** Horizontal row of channel cards; eases newly focused cards into view. */ +@Composable +private fun ChannelCardRow( + channels: List, onOpenChannel: (String) -> Unit, onOpenDrawer: () -> Unit, + firstFocused: Boolean, + onLeftAtStart: () -> Unit, ) { - val firstCardFocus = remember { androidx.compose.ui.focus.FocusRequester() } - LaunchedEffect(items.isNotEmpty()) { - if (items.isNotEmpty()) runCatching { firstCardFocus.requestFocus() } + val rowState = androidx.compose.foundation.lazy.rememberLazyListState() + val focusRequesters = remember { mutableMapOf() } + var focusedIndex by remember { mutableIntStateOf(-1) } + var clickedIndex by remember { mutableIntStateOf(-1) } + + LaunchedEffect(focusedIndex) { + if (focusedIndex > 0) { + val visible = rowState.layoutInfo.visibleItemsInfo + val target = visible.firstOrNull { it.index == focusedIndex } + val notFullyVisible = target == null || + target.offset < 0 || + target.offset + target.size > rowState.layoutInfo.viewportEndOffset + if (notFullyVisible) rowState.animateScrollToItem(focusedIndex) + } } - LazyColumn(modifier = Modifier.fillMaxSize().padding(vertical = 8.dp)) { - itemsIndexed(items) { index, channel -> + if (firstFocused) { + LaunchedEffect(channels.isNotEmpty()) { + if (channels.isNotEmpty()) runCatching { focusRequesters[0]?.requestFocus() } + } + } + + androidx.compose.foundation.lazy.LazyRow( + state = rowState, + contentPadding = PaddingValues(horizontal = 12.dp), + horizontalArrangement = Arrangement.spacedBy(4.dp), + ) { + itemsIndexed(channels) { index, channel -> + val fr = remember { FocusRequester() } + focusRequesters[index] = fr ChannelCard( channel = channel, onClick = { onOpenChannel("${channel.name}@${channel.host}") }, onLeftAtStart = if (index == 0) onOpenDrawer else null, - modifier = if (index == 0) Modifier.focusRequester(firstCardFocus) else Modifier, + modifier = Modifier.focusRequester(fr), ) - if (index >= items.size - PagedListViewModel.LOOKAHEAD) { - LaunchedEffect(index) { viewModel.loadMore() } - } - } - if (!viewModel.exhausted) { - item { - Box(Modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center) { - CircularProgressIndicator() - } - } } } } +/** SmartTube-style channel card: banner (16:9 crop) + avatar badge + name + counters. */ @Composable -private fun ChannelCard( +fun ChannelCard( channel: VideoChannelDto, onClick: () -> Unit, - onLeftAtStart: (() -> Unit)? = null, modifier: Modifier = Modifier, + onLeftAtStart: (() -> Unit)? = null, ) { + var cardFocused by remember { mutableStateOf(false) } Card( onClick = onClick, modifier = modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 6.dp), - colors = CardDefaults.colors(containerColor = MaterialTheme.colorScheme.surface), + .width(rowCardWidth()) + .padding(6.dp) + .onPreviewKeyEvent { ke -> + if (ke.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN && + ke.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_DPAD_LEFT && + onLeftAtStart != null + ) { + onLeftAtStart() + true + } else false + }, + colors = CardDefaults.colors( + containerColor = UnfocusedCardBg, + contentColor = Color.White, + focusedContainerColor = Color.White, + focusedContentColor = Color(0xFF101010), + ), + scale = CardDefaults.scale(focusedScale = 1f), + border = CardDefaults.border( + focusedBorder = Border(border = BorderStroke(3.dp, Color.White), shape = ContainerShape), + pressedBorder = Border(border = BorderStroke(3.dp, Color.White), shape = ContainerShape), + ), ) { - Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(12.dp)) { - val avatar = channel.avatars.maxByOrNull { it.width } - if (avatar != null) { - val url = avatar.fileUrl?.let { if (it.startsWith("http")) it else null } - ?: (AppGraph.tokenStore.baseUrl + avatar.path) - - val avReq = coil.request.ImageRequest.Builder(androidx.compose.ui.platform.LocalContext.current) - .data(url) - .size(160) - .build() - AsyncImage( - model = avReq, - contentDescription = channel.displayName, - contentScale = ContentScale.Crop, - modifier = Modifier.size(72.dp).clip(CircleShape).background(Color(0xFF222222)), - ) + Column { + Box( + modifier = Modifier + .fillMaxWidth() + .aspectRatio(16f / 9f) + .background(Color(0xFF222222)), + ) { + val banner = channel.banners.maxByOrNull { it.width } + if (banner != null) { + AsyncImage( + model = coil.request.ImageRequest.Builder(androidx.compose.ui.platform.LocalContext.current) + .data(absolute(banner.fileUrl ?: banner.path)) + .size(480) + .build(), + contentDescription = channel.displayName, + contentScale = ContentScale.Crop, + modifier = Modifier + .fillMaxWidth() + .aspectRatio(16f / 9f), + ) + } + val avatar = channel.avatars.maxByOrNull { it.width } + if (avatar != null) { + AsyncImage( + model = coil.request.ImageRequest.Builder(androidx.compose.ui.platform.LocalContext.current) + .data(absolute(avatar.fileUrl ?: avatar.path)) + .size(80) + .build(), + contentDescription = null, + contentScale = ContentScale.Crop, + modifier = Modifier + .align(Alignment.BottomStart) + .padding(8.dp) + .size(36.dp) + .clip(CircleShape) + .background(Color(0xFF333333)), + ) + } } - Column(modifier = Modifier.padding(start = 12.dp)) { + Column( + modifier = Modifier.padding(10.dp), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { Text( text = channel.displayName.ifBlank { channel.name }, - style = MaterialTheme.typography.titleMedium, + style = MaterialTheme.typography.titleSmall, maxLines = 1, - overflow = TextOverflow.Ellipsis, + minLines = 1, + overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis, + color = if (cardFocused) Color(0xFF101010) else Color.White, ) Text( - text = "${channel.host} · ${channel.name} · ${channel.videosCount} videos", + text = channel.host + " · " + channel.videosCount + " videos · " + + channel.followersCount + " followers", style = MaterialTheme.typography.bodySmall, - color = Color(0xFF8A8A8A), + color = if (cardFocused) Color(0xFF6A6A6A) else Color(0xFF8A8A8A), maxLines = 1, - overflow = TextOverflow.Ellipsis, + overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis, ) } } diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt index 290d4ee..a68bfac 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt @@ -43,7 +43,7 @@ import net.jeena.jtubetv.ui.screens.list.VideoCard /** Compact SmartTube-style card: ~4 and a bit visible per full-width row. */ @Composable -private fun rowCardWidth(): androidx.compose.ui.unit.Dp { +fun rowCardWidth(): androidx.compose.ui.unit.Dp { val windowWidth = androidx.compose.ui.platform.LocalConfiguration.current.screenWidthDp return ((windowWidth / 4.35f) - 10).dp } @@ -243,7 +243,7 @@ fun HomeRowsScreen( * the abrupt jump the built-in lazy scroll produces. */ @Composable -private fun FocusScrollRow( +fun FocusScrollRow( videos: List, progressOf: (String) -> Float?, onOpenVideo: (VideoDto) -> Unit, diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt index 491eaf1..a602d88 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt @@ -40,13 +40,12 @@ import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.focus.onFocusChanged -import androidx.compose.ui.input.key.Key -import androidx.compose.ui.input.key.key -import androidx.compose.ui.input.key.KeyEventType -import androidx.compose.ui.input.key.onPreviewKeyEvent -import androidx.compose.ui.input.key.type import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.input.key.Key +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.key.key +import androidx.compose.ui.input.key.type import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.unit.dp import androidx.tv.material3.Icon @@ -106,7 +105,25 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi drawerOpen = false } - Box(modifier = Modifier.fillMaxSize()) { + Box( + modifier = Modifier + .fillMaxSize() + .onPreviewKeyEvent { ke -> + // Keyboard/scrcpy: Esc behaves like BACK for drawer + drilldowns + // (the player consumes Esc itself when playing). + val native = ke.nativeKeyEvent + if (native.action == android.view.KeyEvent.ACTION_DOWN && + native.keyCode == android.view.KeyEvent.KEYCODE_ESCAPE && + playingVideo == null + ) { + when { + drawerOpen -> { drawerOpen = false; true } + channelDetails != null -> { channelDetails = null; true } + else -> false + } + } else false + }, + ) { androidx.compose.runtime.key(epoch) { Column { // SmartTube-style top bar: red round search + avatar opening the menu. diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/PlayerScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/PlayerScreen.kt index 0297c1a..6c21ee1 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/PlayerScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/PlayerScreen.kt @@ -324,6 +324,11 @@ private fun PlayerSurface( val handleKey: (KeyEvent) -> Boolean = { event -> if (event.action == KeyEvent.ACTION_DOWN) { when (event.keyCode) { + // scrcpy/keyboard users: Esc = back (Ctrl+B relies on the mod binding) + KeyEvent.KEYCODE_ESCAPE, KeyEvent.KEYCODE_BACK -> { + onBack() + true + } KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> { player.playWhenReady = !player.playWhenReady true From cc1c1d1c9d0effdc20b0170d1ccf7749fbb09fdd Mon Sep 17 00:00:00 2001 From: Jeena Date: Sun, 11 Oct 2026 01:15:51 +0000 Subject: [PATCH 08/23] scripts: bridge-emulator.sh (host) + image prefetching Perf work for the TV FPS complaint: every page that loads from the API also warms Coil's disk/memory caches (video thumbnails at the same 480x270 the card renders, channel banners/avatars) so rows scroll without popping in over the network. Prefetch keys match render keys exactly so cache hits are guaranteed. bridge-emulator.sh runs OUTSIDE the container on the emulator host: boots jtubesc if needed (ADB_VENDOR_KEYS whitelists the host adb key), installs/starts JTube TV and binds :5557 -> adbd 5601 so the container and LAN can drive it. Run it once in your rutherford shell. --- .../main/java/net/jeena/jtubetv/JTubeApp.kt | 3 ++ .../jeena/jtubetv/ui/list/ImagePrefetcher.kt | 53 +++++++++++++++++++ .../jtubetv/ui/list/PagedListViewModel.kt | 4 ++ .../jtubetv/ui/list/VideoListViewModel.kt | 11 ++++ .../jtubetv/ui/screens/ChannelsScreen.kt | 1 + .../net/jeena/jtubetv/ui/screens/HomeRows.kt | 9 +++- scripts/bridge-emulator.sh | 42 +++++++++++++++ 7 files changed, 122 insertions(+), 1 deletion(-) create mode 100644 app/src/main/java/net/jeena/jtubetv/ui/list/ImagePrefetcher.kt create mode 100755 scripts/bridge-emulator.sh diff --git a/app/src/main/java/net/jeena/jtubetv/JTubeApp.kt b/app/src/main/java/net/jeena/jtubetv/JTubeApp.kt index ec4c71a..fe13971 100644 --- a/app/src/main/java/net/jeena/jtubetv/JTubeApp.kt +++ b/app/src/main/java/net/jeena/jtubetv/JTubeApp.kt @@ -13,8 +13,11 @@ object AppGraph { private set lateinit var tokenStore: TokenStore private set + var appContext: android.content.Context? = null + private set fun init(context: Application) { + appContext = context tokenStore = TokenStore(context) repository = PeerTubeRepository(tokenStore, PeerTubeNetwork(tokenStore)) } diff --git a/app/src/main/java/net/jeena/jtubetv/ui/list/ImagePrefetcher.kt b/app/src/main/java/net/jeena/jtubetv/ui/list/ImagePrefetcher.kt new file mode 100644 index 0000000..e29ce93 --- /dev/null +++ b/app/src/main/java/net/jeena/jtubetv/ui/list/ImagePrefetcher.kt @@ -0,0 +1,53 @@ +package net.jeena.jtubetv.ui.list + +import android.content.Context +import coil.imageLoader +import coil.request.ImageRequest +import net.jeena.jtubetv.AppGraph +import net.jeena.jtubetv.data.api.Avatar +import net.jeena.jtubetv.data.api.VideoChannelDto +import net.jeena.jtubetv.data.api.VideoDto + +/** + * Warms Coil's caches for images that are already loaded from the API but not yet + * visible further down a row/list, so they pop in instantly instead of popping in + * over the network while scrolling. + * + * Uses the same request shape (size) as the visible [VideoCard]/[ChannelCard] + * renderers so the memory cache keys match exactly. + */ +object ImagePrefetcher { + + private val enqueued = HashSet() + + fun videoThumbnails(videos: List, context: Context = AppGraph.appContext!!) { + for (video in videos) { + val path = video.thumbnailPath?.takeIf { it.isNotBlank() } ?: continue + enqueue(context, AppGraph.repository.absoluteUrl(path), 480, 270) + } + } + + fun channelArt(channels: List, context: Context = AppGraph.appContext!!) { + for (channel in channels) { + val banner = channel.banners.maxByOrNull { it.width } + if (banner != null) enqueue(context, absolute(banner), 480, 270) + val avatar = channel.avatars.maxByOrNull { it.width } + if (avatar != null) enqueue(context, absolute(avatar), 80, 80) + } + } + + private fun absolute(a: Avatar): String = + (a.fileUrl ?: a.path).let { + if (it.startsWith("http")) it + else (AppGraph.tokenStore.baseUrl ?: "") + (if (it.startsWith("/")) "" else "/") + it + } + + private fun enqueue(context: Context, url: String, width: Int, height: Int) { + if (!enqueued.add(url)) return + val request = ImageRequest.Builder(context) + .data(url) + .size(width, height) + .build() + context.imageLoader.enqueue(request) + } +} \ No newline at end of file diff --git a/app/src/main/java/net/jeena/jtubetv/ui/list/PagedListViewModel.kt b/app/src/main/java/net/jeena/jtubetv/ui/list/PagedListViewModel.kt index c96c5bc..3429a76 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/list/PagedListViewModel.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/list/PagedListViewModel.kt @@ -27,6 +27,9 @@ abstract class PagedListViewModel : ViewModel() { protected abstract suspend fun fetch(start: Long, count: Int): Result> + /** Warm image caches for just-loaded rows so later scrolls don't fetch from network. */ + protected open fun onChunkLoaded(chunk: List) {} + fun loadMore(force: Boolean = false) { if (inFlight || (!force && exhausted)) return inFlight = true @@ -39,6 +42,7 @@ abstract class PagedListViewModel : ViewModel() { exhausted = chunk.size < pageSize items = items + chunk loadingInitial = false + onChunkLoaded(chunk) }, onFailure = { e -> if (items.isEmpty()) { diff --git a/app/src/main/java/net/jeena/jtubetv/ui/list/VideoListViewModel.kt b/app/src/main/java/net/jeena/jtubetv/ui/list/VideoListViewModel.kt index 90264f3..33bf4aa 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/list/VideoListViewModel.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/list/VideoListViewModel.kt @@ -30,6 +30,17 @@ class VideoListViewModel( val query = MutableStateFlow("") private var activeSearch: String? = null + override fun onChunkLoaded(chunk: List) { + ImagePrefetcher.videoThumbnails( + chunk.mapNotNull { + when (it) { + is VideoListItem.Video -> it.video + is VideoListItem.HistoryEntry -> it.history.video + } + } + ) + } + override suspend fun fetch(start: Long, count: Int): Result> { return when (val s = source) { is ListSource.LocalVideos -> diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt index 382cdb5..b7a065d 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt @@ -109,6 +109,7 @@ class ChannelsViewModel(private val store: TokenStore) : ViewModel() { userChannels = (userChannels + mine).distinctBy { it.name to it.host } localChannels = rest.filter { it.host == host }.sortedBy { it.displayName } followedChannels = rest.filter { it.host != host }.sortedBy { it.displayName } + net.jeena.jtubetv.ui.list.ImagePrefetcher.channelArt(all) } catch (e: Exception) { error = e.message ?: "Could not load channels" } finally { diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt index a68bfac..5867b5a 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt @@ -65,7 +65,9 @@ class HomeRowsViewModel(private val repository: PeerTubeRepository) : ViewModel( private fun fetchSubs() { viewModelScope.launch { - subItems = repository.subscriptionVideos(0, 12).getOrNull()?.data ?: emptyList() + val subs = repository.subscriptionVideos(0, 12).getOrNull()?.data ?: emptyList() + subItems = subs + net.jeena.jtubetv.ui.list.ImagePrefetcher.videoThumbnails(subs) } } @@ -108,6 +110,7 @@ class HomeRowsViewModel(private val repository: PeerTubeRepository) : ViewModel( }.awaitAll() continueItems = items continueLoading = false + net.jeena.jtubetv.ui.list.ImagePrefetcher.videoThumbnails(items.map { it.video }) } } @@ -122,6 +125,10 @@ class HomeRowsViewModel(private val repository: PeerTubeRepository) : ViewModel( /** Paged "New videos" row content. */ class RecentVideosViewModel(private val repository: PeerTubeRepository) : PagedListViewModel() { + override fun onChunkLoaded(chunk: List) { + net.jeena.jtubetv.ui.list.ImagePrefetcher.videoThumbnails(chunk) + } + override suspend fun fetch(start: Long, count: Int): Result> = repository.localVideos(start, count).map { it.data } diff --git a/scripts/bridge-emulator.sh b/scripts/bridge-emulator.sh new file mode 100755 index 0000000..5fc8ed2 --- /dev/null +++ b/scripts/bridge-emulator.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# +# bridge-emulator.sh — (host-side) expose the emulator's adbd to the LAN so agents +# inside the container/other machines can use it: binds :5557 -> 127.0.0.1:5601. +# The emulator console transport (emulator-5600) stays local-only; this bridges the +# adbd TCP port 5601. +set -euo pipefail +ADBD_PORT=5601 +BRIDGE_PORT=5557 + +# start emulator if not running +ADB="${ANDROID_SDK_ROOT:-$HOME/Android/Sdk}/platform-tools/adb" +if ! "$ADB" devices | grep -q "emulator-5600.*device"; then + echo "emulator-5600 not running — starting it…" + ADB_VENDOR_KEYS="$HOME/.android/adbkey" setsid nohup \ + "${ANDROID_SDK_ROOT:-$HOME/Android/Sdk}/emulator/emulator" -avd jtubesc -port 5600 \ + -no-window -gpu swiftshader_indirect -no-snapshot -no-audio -no-boot-anim \ + > /tmp/jtube-emu.log 2>&1 < /dev/null & + echo "waiting for boot (log: /tmp/jtube-emu.log)…" + for i in $(seq 1 60); do + ok=$("$ADB" -s emulator-5600 shell getprop sys.boot_completed 2>/dev/null | tr -d '\r') + [ "$ok" = "1" ] && { echo "BOOTED"; break; } + sleep 5 + done +fi + +# keep JTube TV installed + running +APK="$HOME/Projects/jtube-tv/app/build/outputs/apk/debug/app-debug.apk" +if [ -f "$APK" ]; then + "$ADB" -s emulator-5600 install -r "$APK" >/dev/null && echo "JTube TV installed" + "$ADB" -s emulator-5600 shell am start -n net.jeena.jtubetv/.MainActivity && echo "app started" +fi + +# the bridge (bind all LAN addresses) +if ! ss -tln 2>/dev/null | grep -q ":$BRIDGE_PORT"; then + setsid nohup socat TCP-LISTEN:$BRIDGE_PORT,bind=0.0.0.0,fork,reuseaddr \ + TCP:127.0.0.1:$ADBD_PORT > /tmp/jtube-bridge.log 2>&1 < /dev/null & + echo "bridge: :$BRIDGE_PORT -> 127.0.0.1:$ADBD_PORT (pid $!)" +fi + +echo "From this host: adb connect localhost:$BRIDGE_PORT" +echo "From other machines: adb connect rutherford:$BRIDGE_PORT" \ No newline at end of file From f7273121aed5b60b05d769e86c669d184e8fde6c Mon Sep 17 00:00:00 2001 From: Jeena Date: Sun, 11 Oct 2026 05:14:32 +0000 Subject: [PATCH 09/23] ui: Real account button (avatar + display name), stable list keys The top bar now mirrors SmartTube: a 44dp circle with the actual user avatar (persisted at login alongside the display name; falls back to the person icon) and the display name next to it. Scrolling jank: add stable keys to grids and rows (item/channel ids) - without keys Compose rebinds the whole list during scroll and re-fires every AsyncImage + focus request, which is the realistic culprit for the 2fps vertical scrolling on the TV. --- .../jeena/jtubetv/data/PeerTubeRepository.kt | 9 +++- .../java/net/jeena/jtubetv/data/api/Dtos.kt | 1 + .../net/jeena/jtubetv/data/auth/TokenStore.kt | 9 ++++ .../jtubetv/ui/screens/ChannelsScreen.kt | 2 +- .../net/jeena/jtubetv/ui/screens/HomeRows.kt | 2 +- .../jeena/jtubetv/ui/screens/HomeScreen.kt | 46 ++++++++++++++----- .../ui/screens/list/VideoListScreen.kt | 8 +++- 7 files changed, 61 insertions(+), 16 deletions(-) diff --git a/app/src/main/java/net/jeena/jtubetv/data/PeerTubeRepository.kt b/app/src/main/java/net/jeena/jtubetv/data/PeerTubeRepository.kt index 93a0e9e..64d35bb 100644 --- a/app/src/main/java/net/jeena/jtubetv/data/PeerTubeRepository.kt +++ b/app/src/main/java/net/jeena/jtubetv/data/PeerTubeRepository.kt @@ -86,7 +86,14 @@ class PeerTubeRepository( .addConverterFactory(json.asConverterFactory("application/json; charset=utf-8".toMediaType())) .build() .create(PeerTubeApi::class.java) - store.accountName = meApi.me().username + val me = meApi.me() + store.accountName = me.username + store.userDisplayName = me.displayName ?: me.username + me.avatars.maxByOrNull { it.width }?.let { avatar -> + store.userAvatarUrl = avatar.fileUrl + ?.takeIf { url -> url.startsWith("http") } + ?: apiUrlOf(base) + avatar.path + } } catch (_: Exception) { store.accountName = username.substringBefore('@') // best effort fallback } diff --git a/app/src/main/java/net/jeena/jtubetv/data/api/Dtos.kt b/app/src/main/java/net/jeena/jtubetv/data/api/Dtos.kt index 231aa31..41cf173 100644 --- a/app/src/main/java/net/jeena/jtubetv/data/api/Dtos.kt +++ b/app/src/main/java/net/jeena/jtubetv/data/api/Dtos.kt @@ -137,5 +137,6 @@ data class VideoTokenFiles( @Serializable data class UserDto( val username: String, + val displayName: String? = null, val avatars: List = emptyList(), ) \ No newline at end of file diff --git a/app/src/main/java/net/jeena/jtubetv/data/auth/TokenStore.kt b/app/src/main/java/net/jeena/jtubetv/data/auth/TokenStore.kt index 2620641..0b006ce 100644 --- a/app/src/main/java/net/jeena/jtubetv/data/auth/TokenStore.kt +++ b/app/src/main/java/net/jeena/jtubetv/data/auth/TokenStore.kt @@ -48,6 +48,15 @@ class TokenStore(context: Context) { get() = prefs.getString("refreshToken", null) private set(value) = prefs.edit().putString("refreshToken", value).apply() + /** Display name + avatar for the account button (from users/me at login). */ + var userDisplayName: String? + get() = prefs.getString("userDisplayName", null) + set(value) = prefs.edit().putString("userDisplayName", value).apply() + + var userAvatarUrl: String? + get() = prefs.getString("userAvatarUrl", null) + set(value) = prefs.edit().putString("userAvatarUrl", value).apply() + /** Real account name from users/me — may differ from the login input (email). */ var accountName: String? get() = prefs.getString("accountName", null) diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt index b7a065d..00ca382 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt @@ -262,7 +262,7 @@ private fun ChannelCardRow( contentPadding = PaddingValues(horizontal = 12.dp), horizontalArrangement = Arrangement.spacedBy(4.dp), ) { - itemsIndexed(channels) { index, channel -> + itemsIndexed(channels, key = { _, c -> c.name + "@" + c.host }) { index, channel -> val fr = remember { FocusRequester() } focusRequesters[index] = fr ChannelCard( diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt index 5867b5a..625a6d0 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt @@ -299,7 +299,7 @@ fun FocusScrollRow( contentPadding = PaddingValues(horizontal = 12.dp), horizontalArrangement = Arrangement.spacedBy(4.dp), ) { - itemsIndexed(videos) { index, video -> + itemsIndexed(videos, key = { _, video -> "v" + video.id }) { index, video -> val fr = remember { FocusRequester() } focusRequesters[index] = fr VideoCard( diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt index a602d88..b2de95a 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt @@ -239,31 +239,53 @@ private fun TopBar( desc = "Search", onClick = onSearchClick, ) - // "Who is logged in" — account button with the username (SmartTube shows the user). + // "Who is logged in" — account button: avatar circle + display name (SmartTube). val accountFocused = remember { mutableStateOf(false) } Row( modifier = Modifier - .clip(CircleShape) .onFocusChanged { accountFocused.value = it.isFocused } - .background(if (accountFocused.value) Color(0x33FFFFFF) else Color.Transparent) + .background(Color.Transparent) .then( if (accountFocused.value) Modifier.border(3.dp, Color.White, CircleShape) else Modifier ) .focusable() - .clickable(onClick = onAccountClick) - .padding(6.dp), + .clickable(onClick = onAccountClick), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(8.dp), ) { - Icon( - imageVector = Icons.Filled.AccountCircle, - contentDescription = "Menu", - tint = Color(0xFFCCCCCC), - ) + val avatarUrl = AppGraph.tokenStore.userAvatarUrl + if (avatarUrl != null) { + coil.compose.AsyncImage( + model = coil.request.ImageRequest.Builder(androidx.compose.ui.platform.LocalContext.current) + .data(avatarUrl) + .size(96) + .build(), + contentDescription = "Account", + modifier = Modifier + .size(44.dp) + .clip(CircleShape) + .background(Color(0xFF262626)), + ) + } else { + Box( + modifier = Modifier + .size(44.dp) + .clip(CircleShape) + .background(Color(0xFF262626)), + contentAlignment = Alignment.Center, + ) { + Icon( + imageVector = Icons.Filled.AccountCircle, + contentDescription = "Account", + tint = Color(0xFFCCCCCC), + ) + } + } Text( - text = AppGraph.tokenStore.username?.substringBefore('@') ?: "Account", - color = Color(0xFFCCCCCC), + text = AppGraph.tokenStore.userDisplayName + ?: AppGraph.tokenStore.username?.substringBefore('@') ?: "Account", + color = Color(0xFFB0B0B0), style = androidx.compose.material3.MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(end = 8.dp), ) diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt index 8e3570e..1cfe009 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt @@ -124,7 +124,7 @@ fun VideoListScreen( state = gridState, modifier = Modifier.fillMaxSize().padding(vertical = 8.dp), ) { - itemsIndexed(items) { index, item -> + itemsIndexed(items, key = { _, item -> itemStableKey(item) }) { index, item -> val video: VideoDto = when (item) { is VideoListItem.HistoryEntry -> item.history.video is VideoListItem.Video -> item.video @@ -189,6 +189,12 @@ private fun SearchHeader(viewModel: VideoListViewModel) { } } +private fun itemStableKey(item: VideoListItem): String = + when (item) { + is VideoListItem.Video -> "v" + item.video.id + is VideoListItem.HistoryEntry -> "h" + item.history.video.id + } + private fun sourceKey(source: ListSource): String = when (source) { is ListSource.Channel -> "channel:${source.handle}" else -> source::class.java.simpleName From 5ea1ca512401d481a1df837e019cefdeb9b38876 Mon Sep 17 00:00:00 2001 From: Jeena Date: Sun, 11 Oct 2026 05:17:12 +0000 Subject: [PATCH 10/23] ui: Fix recompose loop during scroll (2fps vertical) Focus requesters were stored in snapshot-state maps and written during composition of every list item: each write invalidated the reading scope, which recomposed the (whole page of) items, wrote again, ... This feedback loop is why vertical scrolling ran at ~2fps on the TV while the same build scrolled fine in the emulator's short bursts. Plain HashMaps kill the loop - focus handling needs no recomposition. --- .../main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt | 2 +- app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt index 00ca382..fa76b3a 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt @@ -237,7 +237,7 @@ private fun ChannelCardRow( onLeftAtStart: () -> Unit, ) { val rowState = androidx.compose.foundation.lazy.rememberLazyListState() - val focusRequesters = remember { mutableMapOf() } + val focusRequesters = remember { HashMap() } var focusedIndex by remember { mutableIntStateOf(-1) } var clickedIndex by remember { mutableIntStateOf(-1) } diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt index 625a6d0..69dafd1 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt @@ -260,7 +260,7 @@ fun FocusScrollRow( afterItem: @Composable (index: Int, video: VideoDto) -> Unit = { _, _ -> }, ) { val rowState = rememberLazyListState() - val focusRequesters = remember { androidx.compose.runtime.mutableStateMapOf() } + val focusRequesters = remember { HashMap() } var focusedIndex by remember { androidx.compose.runtime.mutableStateOf(-1) } // BACK from playback: scroll to + focus the card that was opened (user request). LaunchedEffect(restoreToken) { From b3b39976fe6e984f34a53b29d7ea73e923965364 Mon Sep 17 00:00:00 2001 From: Jeena Date: Sun, 11 Oct 2026 05:42:02 +0000 Subject: [PATCH 11/23] channels: Per-user rows, empty-channels row, redesigned stats card, subs detail Channels now render as SmartTube rows and scroll vertically (LazyColumn - the unscrollable Column hid rows 2+). Local channels group one row per ownerAccount, sorted by total video count, with all zero-video channels merged into a final 'No videos yet' row. Followed-instance channels group per platform. The channel card matches the video-card language: banner center-cropped, round avatar bottom-left, channel name, 'owner display name - platform display name' (instance names via /config, local cached at login; no domain strings), and an icon stat line (videos | subscribers | plays); counts load per channel in the background since the listing endpoint doesn't carry them (verified on the live API). Subscriptions destination switches to per-channel rows, matching the Home card size. --- .../jeena/jtubetv/data/PeerTubeRepository.kt | 42 ++++ .../java/net/jeena/jtubetv/data/api/Dtos.kt | 26 +++ .../net/jeena/jtubetv/data/api/PeerTubeApi.kt | 3 + .../net/jeena/jtubetv/data/auth/TokenStore.kt | 5 + .../jtubetv/ui/screens/ChannelsScreen.kt | 217 ++++++++++++++---- .../jeena/jtubetv/ui/screens/HomeScreen.kt | 36 +-- .../jtubetv/ui/screens/SubscriptionsScreen.kt | 168 ++++++++++++++ 7 files changed, 435 insertions(+), 62 deletions(-) create mode 100644 app/src/main/java/net/jeena/jtubetv/ui/screens/SubscriptionsScreen.kt diff --git a/app/src/main/java/net/jeena/jtubetv/data/PeerTubeRepository.kt b/app/src/main/java/net/jeena/jtubetv/data/PeerTubeRepository.kt index 64d35bb..5079c0d 100644 --- a/app/src/main/java/net/jeena/jtubetv/data/PeerTubeRepository.kt +++ b/app/src/main/java/net/jeena/jtubetv/data/PeerTubeRepository.kt @@ -2,7 +2,9 @@ package net.jeena.jtubetv.data import kotlinx.serialization.json.Json import net.jeena.jtubetv.data.api.HistoryElement +import net.jeena.jtubetv.data.api.ChannelStats import net.jeena.jtubetv.data.api.OAuthClient +import net.jeena.jtubetv.data.api.ServerConfigDto import net.jeena.jtubetv.data.api.PeerTubeApi import net.jeena.jtubetv.data.api.TokenResponse import net.jeena.jtubetv.data.api.UserDto @@ -86,6 +88,9 @@ class PeerTubeRepository( .addConverterFactory(json.asConverterFactory("application/json; charset=utf-8".toMediaType())) .build() .create(PeerTubeApi::class.java) + store.instanceName = try { + meApi.serverConfig().instance.name + } catch (_: Exception) { null } val me = meApi.me() store.accountName = me.username store.userDisplayName = me.displayName ?: me.username @@ -101,6 +106,43 @@ class PeerTubeRepository( suspend fun me(): Result = runCatching { network.api.me() } + suspend fun serverConfig(): Result = runCatching { network.api.serverConfig() } + + /** Display name of a (possibly foreign) instance, via that instance's /config. */ + suspend fun instanceName(rawHost: String): Result = runCatching { + val base = "https://" + rawHost + val api = unauthenticatedApiFor(base) + api.serverConfig().instance.name ?: rawHost + } + + /** + * videosCount + total plays for a channel (listing DTOs don't carry them). + * Sums views over up to [maxPages] video pages. + */ + suspend fun channelStats(handle: String, maxPages: Int = 4): Result = + runCatching { + var start = 0L + var videos = 0L + var plays = 0L + var total: Long? = null + repeat(maxPages) { + val page = network.api.channelVideos(handle, start, 25) + if (total == null) total = page.total + plays += page.data.sumOf { it.views } + start += page.data.size + videos = total ?: videos + } + net.jeena.jtubetv.data.api.ChannelStats(videos, plays) + } + + private fun unauthenticatedApiFor(base: String): PeerTubeApi = + Retrofit.Builder() + .baseUrl(apiUrlOf(base) + "/") + .client(plainOkHttp()) + .addConverterFactory(json.asConverterFactory("application/json; charset=utf-8".toMediaType())) + .build() + .create(PeerTubeApi::class.java) + // ---- video lists ------------------------------------------------------- suspend fun localVideos(start: Long, count: Int, search: String? = null): Result = diff --git a/app/src/main/java/net/jeena/jtubetv/data/api/Dtos.kt b/app/src/main/java/net/jeena/jtubetv/data/api/Dtos.kt index 41cf173..b807ebc 100644 --- a/app/src/main/java/net/jeena/jtubetv/data/api/Dtos.kt +++ b/app/src/main/java/net/jeena/jtubetv/data/api/Dtos.kt @@ -60,6 +60,14 @@ data class VideoListResponse( val data: List, ) +@Serializable +data class ChannelOwnerAccount( + val name: String, + val host: String? = null, + @SerialName("displayName") val displayName: String? = null, + val avatars: List = emptyList(), +) + @Serializable data class VideoChannelDto( val name: String, @@ -70,6 +78,7 @@ data class VideoChannelDto( val banners: List = emptyList(), val videosCount: Long = 0, val followersCount: Long = 0, + val ownerAccount: ChannelOwnerAccount? = null, ) @Serializable @@ -134,6 +143,23 @@ data class VideoTokenFiles( val expires: String? = null, ) +@Serializable +data class ServerConfigDto( + val instance: InstanceInfoDto, +) + +@Serializable +data class InstanceInfoDto( + val name: String? = null, + val shortDescription: String? = null, +) + +/** Per-channel stats not available in the listing; fetched on demand. */ +data class ChannelStats( + val videos: Long, + val plays: Long, +) + @Serializable data class UserDto( val username: String, diff --git a/app/src/main/java/net/jeena/jtubetv/data/api/PeerTubeApi.kt b/app/src/main/java/net/jeena/jtubetv/data/api/PeerTubeApi.kt index 76dd8e2..4c505ce 100644 --- a/app/src/main/java/net/jeena/jtubetv/data/api/PeerTubeApi.kt +++ b/app/src/main/java/net/jeena/jtubetv/data/api/PeerTubeApi.kt @@ -112,4 +112,7 @@ interface PeerTubeApi { @GET("users/me") suspend fun me(): UserDto + + @GET("config") + suspend fun serverConfig(): ServerConfigDto } \ No newline at end of file diff --git a/app/src/main/java/net/jeena/jtubetv/data/auth/TokenStore.kt b/app/src/main/java/net/jeena/jtubetv/data/auth/TokenStore.kt index 0b006ce..054da4d 100644 --- a/app/src/main/java/net/jeena/jtubetv/data/auth/TokenStore.kt +++ b/app/src/main/java/net/jeena/jtubetv/data/auth/TokenStore.kt @@ -53,6 +53,11 @@ class TokenStore(context: Context) { get() = prefs.getString("userDisplayName", null) set(value) = prefs.edit().putString("userDisplayName", value).apply() + /** Human-friendly instance name (e.g. "JTube") for card subtitles. */ + var instanceName: String? + get() = prefs.getString("instanceName", null) + set(value) = prefs.edit().putString("instanceName", value).apply() + var userAvatarUrl: String? get() = prefs.getString("userAvatarUrl", null) set(value) = prefs.edit().putString("userAvatarUrl", value).apply() diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt index fa76b3a..707db29 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt @@ -4,6 +4,10 @@ import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.lazy.LazyRow +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Groups +import androidx.compose.material.icons.filled.PlayArrow +import androidx.compose.material.icons.filled.VideoLibrary import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues @@ -53,6 +57,17 @@ import net.jeena.jtubetv.data.api.VideoChannelDto import net.jeena.jtubetv.ui.screens.list.ContainerShape import net.jeena.jtubetv.ui.screens.list.UnfocusedCardBg +/** One row of channels belonging to one user (avatar + display name as header). */ +data class UserGroup( + val label: String?, + val avatar: Avatar?, + val videos: Long, + val rows: List, +) { + /** Sort weight: users with videos first (more videos first), empty channels last. */ + fun rowWeight(): Long = if (videos > 0) videos else Long.MIN_VALUE / 2 +} + /** * Channels as SmartTube-style rows: * 1. "Your channels" — header with account avatar + username, then own channel cards. @@ -70,13 +85,28 @@ class ChannelsViewModel(private val store: TokenStore) : ViewModel() { private set var localChannels by mutableStateOf>(emptyList()) private set - var followedChannels by mutableStateOf>(emptyList()) + + /** One row per (local) user, sorted by total video count; empties last. */ + var localUserRows by mutableStateOf>(emptyList()) private set + + /** Channels from instances this server follows, grouped by their instance. */ + var followedRows by mutableStateOf>(emptyList()) + private set + var loading by mutableStateOf(true) private set var error by mutableStateOf(null) private set + /** "name@host" -> videos + plays; filled in the background. */ + var stats by mutableStateOf>(emptyMap()) + private set + + /** host -> platform display name (e.g. "JTube" instead of tube.jeena.net). */ + var platformNames by mutableStateOf>(emptyMap()) + private set + private val repo: PeerTubeRepository = AppGraph.repository fun load(force: Boolean = false) { @@ -85,13 +115,11 @@ class ChannelsViewModel(private val store: TokenStore) : ViewModel() { error = null viewModelScope.launch { try { - // row header (avatar + real username) user = repo.me().getOrNull() userChannels = user?.let { u -> repo.accountChannels(u.username).getOrNull() ?: emptyList() } ?: emptyList() - // enumerate the whole channel list, split by host client-side val all = mutableListOf() var start = 0L var total: Long? = null @@ -102,14 +130,56 @@ class ChannelsViewModel(private val store: TokenStore) : ViewModel() { all += page.first.filter { c -> (c.name to c.host) !in known } start += 100 } + val host = store.baseUrl?.substringAfter("://")?.substringBefore('/') val ownNames = userChannels.map { c -> c.name }.toSet() val mine = all.filter { it.host == host && it.name in ownNames } val rest = all.filterNot { c -> mine.any { it.name == c.name && it.host == c.host } } userChannels = (userChannels + mine).distinctBy { it.name to it.host } - localChannels = rest.filter { it.host == host }.sortedBy { it.displayName } - followedChannels = rest.filter { it.host != host }.sortedBy { it.displayName } + localChannels = rest.filter { it.host == host } + net.jeena.jtubetv.ui.list.ImagePrefetcher.channelArt(all) + + // platform display names (local cached in prefs; foreign lazy) + platformNames = mapOf( + (host ?: "") to (store.instanceName ?: host ?: ""), + ) + val foreignHosts = rest.map { it.host ?: "?" }.toSet() - (host ?: "") + for (fh in foreignHosts) { + val name = repo.instanceName(fh).getOrNull() ?: continue + platformNames = platformNames + (fh to name) + } + + // video + play counts per channel, one tiny listing call per channel + for (channel in (userChannels + localChannels)) { + val key = channel.name + "@" + channel.host + val cs = repo.channelStats(key).getOrNull() ?: continue + stats = stats + (key to cs) + } + // group LOCAL channels by owner (user): row per user, videos desc, + // channels with zero videos collected into a single last row. + val locals = rest.filter { it.host == host } + val withVideos = locals.filter { it.videosCount > 0 } + val empty = locals.filter { it.videosCount <= 0 } + val byOwner = withVideos.groupBy { ownerKey(it) } + localUserRows = + byOwner.values + .map { row -> UserGroup( + label = rowLabel(row), + avatar = rowAvatar(row), + videos = rowTotal(row), + rows = row.sortedByDescending { it.videosCount }, + ) } + .filter { it.label != null } + .sortedByDescending { it.rowWeight() } + if (empty.isNotEmpty()) { + localUserRows += UserGroup(label = "No videos yet", avatar = null, videos = 0, rows = empty) + } + followedRows = rest.filter { it.host != host } + .groupBy { it.host ?: "?" } + .values + .map { row -> UserGroup(label = rowLabel(row), avatar = null, videos = rowTotal(row), rows = row.sortedByDescending { it.videosCount }) } + .sortedByDescending { it.rowWeight() } } catch (e: Exception) { error = e.message ?: "Could not load channels" } finally { @@ -118,6 +188,12 @@ class ChannelsViewModel(private val store: TokenStore) : ViewModel() { } } + private fun ownerKey(c: VideoChannelDto) = c.ownerAccount?.name ?: "—" + private fun rowLabel(row: List) = row.firstOrNull()?.ownerAccount?.displayName + private fun rowAvatar(row: List) = row.firstOrNull()?.ownerAccount?.avatars?.maxByOrNull { it.width } + private fun rowTotal(row: List) = row.sumOf { it.videosCount } + + companion object { val factory: ViewModelProvider.Factory = object : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") @@ -158,42 +234,59 @@ fun ChannelsScreen( val lastOpened = remember { mutableIntStateOf(-1) } var focusedRow by remember { mutableIntStateOf(0) } - Column(Modifier.fillMaxSize()) { + androidx.compose.foundation.lazy.LazyColumn(Modifier.fillMaxSize()) { if (viewModel.userChannels.isNotEmpty()) { - // row 1: the user's own channels; header = account icon + username - RowHeader( - avatar = viewModel.user?.avatars?.maxByOrNull { it.width }, - label = (viewModel.user?.username ?: "You") + " — your channels", - ) - ChannelCardRow( + item { + RowHeader( + avatar = viewModel.user?.avatars?.maxByOrNull { it.width }, + label = (viewModel.user?.displayName ?: viewModel.user?.username ?: "You") + " — your channels", + ) + } + item { + ChannelRow( viewModel.userChannels, onOpenChannel, onOpenDrawer, firstFocused = true, - onLeftAtStart = onOpenDrawer, + statsProvider = { viewModel.stats[it.name + "@" + it.host] }, + platformProvider = { viewModel.platformNames[it.host ?: ""] }, ) + } } - if (viewModel.localChannels.isNotEmpty()) { - RowHeader(avatar = null, label = "Local channels", onOpenDrawer = onOpenDrawer) - ChannelCardRow( - viewModel.localChannels, - onOpenChannel, - onOpenDrawer, - firstFocused = false, - onLeftAtStart = {}, - ) + viewModel.localUserRows.forEach { group -> + item { + RowHeader( + avatar = group.avatar, + label = (group.label ?: "?") + " (" + group.videos + ")", + ) + } + item { + ChannelRow( + group.rows, + onOpenChannel, + {}, + firstFocused = false, + statsProvider = { viewModel.stats[it.name + "@" + it.host] }, + platformProvider = { viewModel.platformNames[it.host ?: ""] }, + ) + } } - if (viewModel.followedChannels.isNotEmpty()) { - RowHeader(avatar = null, label = "Followed instances", onOpenDrawer = onOpenDrawer) - ChannelCardRow( - viewModel.followedChannels, - onOpenChannel, - onOpenDrawer, - firstFocused = false, - onLeftAtStart = {}, - ) + viewModel.followedRows.forEach { group -> + item { + RowHeader(avatar = null, label = (group.label ?: "?") + " (" + group.videos + ")") + } + item { + ChannelRow( + group.rows, + onOpenChannel, + {}, + firstFocused = false, + statsProvider = { viewModel.stats[it.name + "@" + it.host] }, + platformProvider = { viewModel.platformNames[it.host ?: ""] }, + ) + } } } } @@ -229,12 +322,13 @@ private fun absolute(pathOrUrl: String): String = /** Horizontal row of channel cards; eases newly focused cards into view. */ @Composable -private fun ChannelCardRow( +private fun ChannelRow( channels: List, onOpenChannel: (String) -> Unit, onOpenDrawer: () -> Unit, firstFocused: Boolean, - onLeftAtStart: () -> Unit, + statsProvider: (VideoChannelDto) -> net.jeena.jtubetv.data.api.ChannelStats?, + platformProvider: (VideoChannelDto) -> String?, ) { val rowState = androidx.compose.foundation.lazy.rememberLazyListState() val focusRequesters = remember { HashMap() } @@ -268,6 +362,8 @@ private fun ChannelCardRow( ChannelCard( channel = channel, onClick = { onOpenChannel("${channel.name}@${channel.host}") }, + stats = statsProvider(channel), + platformName = platformProvider(channel), onLeftAtStart = if (index == 0) onOpenDrawer else null, modifier = Modifier.focusRequester(fr), ) @@ -275,12 +371,17 @@ private fun ChannelCardRow( } } -/** SmartTube-style channel card: banner (16:9 crop) + avatar badge + name + counters. */ +/** + * Channel card: banner top (center-cropped), round avatar bottom-left, then + * channel name, "ownerDisplayName - platformDisplayName", stat line with icons. + */ @Composable fun ChannelCard( channel: VideoChannelDto, onClick: () -> Unit, modifier: Modifier = Modifier, + stats: net.jeena.jtubetv.data.api.ChannelStats? = null, + platformName: String? = null, onLeftAtStart: (() -> Unit)? = null, ) { var cardFocused by remember { mutableStateOf(false) } @@ -320,21 +421,23 @@ fun ChannelCard( val banner = channel.banners.maxByOrNull { it.width } if (banner != null) { AsyncImage( - model = coil.request.ImageRequest.Builder(androidx.compose.ui.platform.LocalContext.current) + model = coil.request.ImageRequest.Builder( + androidx.compose.ui.platform.LocalContext.current, + ) .data(absolute(banner.fileUrl ?: banner.path)) .size(480) .build(), contentDescription = channel.displayName, contentScale = ContentScale.Crop, - modifier = Modifier - .fillMaxWidth() - .aspectRatio(16f / 9f), + modifier = Modifier.fillMaxWidth().aspectRatio(16f / 9f), ) } val avatar = channel.avatars.maxByOrNull { it.width } if (avatar != null) { AsyncImage( - model = coil.request.ImageRequest.Builder(androidx.compose.ui.platform.LocalContext.current) + model = coil.request.ImageRequest.Builder( + androidx.compose.ui.platform.LocalContext.current, + ) .data(absolute(avatar.fileUrl ?: avatar.path)) .size(80) .build(), @@ -343,7 +446,7 @@ fun ChannelCard( modifier = Modifier .align(Alignment.BottomStart) .padding(8.dp) - .size(36.dp) + .size(40.dp) .clip(CircleShape) .background(Color(0xFF333333)), ) @@ -357,19 +460,45 @@ fun ChannelCard( text = channel.displayName.ifBlank { channel.name }, style = MaterialTheme.typography.titleSmall, maxLines = 1, - minLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis, color = if (cardFocused) Color(0xFF101010) else Color.White, ) Text( - text = channel.host + " · " + channel.videosCount + " videos · " + - channel.followersCount + " followers", + text = (channel.ownerAccount?.displayName ?: "") + + (if (platformName != null) " - " + platformName else ""), style = MaterialTheme.typography.bodySmall, color = if (cardFocused) Color(0xFF6A6A6A) else Color(0xFF8A8A8A), maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis, ) + Row(horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.CenterVertically) { + StatWithIcon( + icon = androidx.compose.material.icons.Icons.Filled.VideoLibrary, + value = stats?.videos?.toString() ?: "-", + focused = cardFocused, + ) + StatWithIcon( + icon = androidx.compose.material.icons.Icons.Filled.Groups, + value = channel.followersCount.toString(), + focused = cardFocused, + ) + StatWithIcon( + icon = androidx.compose.material.icons.Icons.Filled.PlayArrow, + value = stats?.plays?.toString() ?: "-", + focused = cardFocused, + ) + } } } } -} \ No newline at end of file +} + +@Composable +private fun StatWithIcon(icon: androidx.compose.ui.graphics.vector.ImageVector, value: String, focused: Boolean) { + val color = if (focused) Color(0xFF6A6A6A) else Color(0xFF8A8A8A) + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) { + androidx.tv.material3.Icon(imageVector = icon, contentDescription = null, tint = color, modifier = Modifier.size(13.dp)) + Text(value, style = MaterialTheme.typography.labelSmall, color = color) + } +} diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt index b2de95a..7e9927d 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt @@ -88,20 +88,32 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi if (playingVideo == null && restoreToken >= 1) restoreToken++ } - // BACK order: player (own BackHandler) → drawer → channel drilldown → exit guard. - BackHandler(enabled = playingVideo == null && channelDetails == null && !drawerOpen) { + // BACK order: player (own BackHandler) → drawer close → channel drilldown → + // BACK (on content) opens the drawer; a double-BACK with the drawer open exits. + BackHandler(enabled = playingVideo == null && channelDetails == null) { val now = System.currentTimeMillis() - if (now - lastBackAt < 2000) { - (context as? android.app.Activity)?.finish() - } else { + if (drawerOpen) { + if (now - lastBackAt < 2500) { + (context as? android.app.Activity)?.finish() + return@BackHandler + } lastBackAt = now android.widget.Toast.makeText(context, "Press BACK again to exit", android.widget.Toast.LENGTH_SHORT).show() + } else { + lastBackAt = now + drawerOpen = true } } BackHandler(enabled = playingVideo == null && channelDetails != null && !drawerOpen) { channelDetails = null } BackHandler(enabled = drawerOpen && playingVideo == null) { + val now = System.currentTimeMillis() + if (now - lastBackAt < 2500) { + (context as? android.app.Activity)?.finish() + return@BackHandler + } + lastBackAt = now drawerOpen = false } @@ -167,8 +179,7 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi onOpenDrawer = { drawerOpen = true }, ) Destination.Subscriptions -> - VideoListScreen( - source = ListSource.Subscriptions, + SubscriptionRowsScreen( onOpenVideo = { playingVideo = it.shortUUID }, restoreToken = restoreToken, epoch = epoch, @@ -428,17 +439,6 @@ private fun MenuDrawerItem( } ) .focusable() - .onPreviewKeyEvent { ke -> - when (ke.key) { - androidx.compose.ui.input.key.Key.DirectionDown -> { - focusManager?.moveFocus(androidx.compose.ui.focus.FocusDirection.Down); true - } - androidx.compose.ui.input.key.Key.DirectionUp -> { - focusManager?.moveFocus(androidx.compose.ui.focus.FocusDirection.Up); true - } - else -> false - } - } .clickable(onClick = onClick) .padding(horizontal = 24.dp, vertical = 14.dp), verticalAlignment = Alignment.CenterVertically, diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/SubscriptionsScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/SubscriptionsScreen.kt new file mode 100644 index 0000000..3a73e01 --- /dev/null +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/SubscriptionsScreen.kt @@ -0,0 +1,168 @@ +package net.jeena.jtubetv.ui.screens + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.unit.dp +import androidx.lifecycle.ViewModel +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewmodel.compose.viewModel +import coil.compose.AsyncImage +import net.jeena.jtubetv.AppGraph +import net.jeena.jtubetv.data.api.Avatar +import net.jeena.jtubetv.data.api.VideoChannelSummary +import net.jeena.jtubetv.data.api.VideoDto +import net.jeena.jtubetv.ui.list.ImagePrefetcher +import net.jeena.jtubetv.ui.list.PagedListViewModel + +/** + * Subscriptions, SmartTube-style: the feed grouped by channel — one row per + * channel, newest-first within the row, row header = channel avatar + name. + * Card sizes match the Home rows exactly. + */ +class SubscriptionRowsViewModel( + private val repository: net.jeena.jtubetv.data.PeerTubeRepository = AppGraph.repository, +) : PagedListViewModel() { + + override fun onChunkLoaded(chunk: List) { + ImagePrefetcher.videoThumbnails(chunk) + } + + override suspend fun fetch(start: Long, count: Int): Result> = + repository.subscriptionVideos(start, count).map { it.data } +} + +private data class SubGroup( + val channel: VideoChannelSummary, + val startIndex: Int, + val videos: List, +) + +private fun buildGroups(items: List): List { + val groups = mutableListOf() + items.forEachIndexed { index, video -> + val last = groups.lastOrNull() + val same = last != null && + last.channel.name == video.channel.name && + last.channel.host == video.channel.host + if (same) { + groups[groups.lastIndex] = last!!.copy(videos = last.videos + video) + } else { + groups += SubGroup(video.channel, index, listOf(video)) + } + } + return groups +} + +@Composable +fun SubscriptionRowsScreen( + onOpenVideo: (VideoDto) -> Unit, + restoreToken: Int = 0, + epoch: Int = 0, + onOpenDrawer: () -> Unit = {}, + viewModel: SubscriptionRowsViewModel = viewModel( + key = "subsrows$epoch", + factory = object : ViewModelProvider.Factory { + @Suppress("UNCHECKED_CAST") + override fun create(modelClass: Class): T = + SubscriptionRowsViewModel() as T + }, + ), +) { + val items = viewModel.items + LaunchedEffect(Unit) { if (items.isEmpty()) viewModel.loadMore(force = true) } + LaunchedEffect(restoreToken) { if (restoreToken > 0) viewModel.refresh() } + + if (items.isEmpty()) { + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + if (viewModel.initialError != null) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Text("Could not load subscriptions", color = MaterialTheme.colorScheme.error) + Text( + viewModel.initialError ?: "", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + androidx.compose.material3.Button(onClick = { viewModel.retryInitial() }) { + Text("Retry") + } + } + } else { + androidx.compose.material3.CircularProgressIndicator() + } + } + return + } + + val groups = remember(items) { buildGroups(items) } + + LazyColumn(Modifier.fillMaxSize()) { + groups.forEach { group -> + item(key = "subrowhead" + group.channel.name + "@" + group.channel.host + group.startIndex) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.padding(start = 16.dp, top = 12.dp, bottom = 4.dp), + horizontalArrangement = Arrangement.spacedBy(10.dp), + ) { + val avatar = group.channel.avatars.maxByOrNull { it.width } + if (avatar != null) { + AsyncImage( + model = coil.request.ImageRequest.Builder( + androidx.compose.ui.platform.LocalContext.current, + ) + .data(avatar.fileUrl + ?: (AppGraph.tokenStore.baseUrl ?: "") + avatar.path) + .size(80) + .build(), + contentDescription = null, + contentScale = ContentScale.Crop, + modifier = Modifier + .size(28.dp) + .clip(CircleShape) + .background(Color(0xFF222222)), + ) + } + Text( + text = group.channel.displayName.ifBlank { group.channel.name }, + style = MaterialTheme.typography.titleMedium, + color = Color.White, + ) + } + } + item(key = "subrow" + group.channel.name + "@" + group.channel.host + group.startIndex) { + FocusScrollRow( + videos = group.videos, + progressOf = { null }, + onOpenVideo = onOpenVideo, + onLeftAtStart = onOpenDrawer, + ) { rowIndex, _ -> + if (group.startIndex + rowIndex >= items.size - PagedListViewModel.LOOKAHEAD) { + viewModel.loadMore() + } + } + } + } + } +} \ No newline at end of file From f5535eec3fd0272af65304c8c735bf0a51de150d Mon Sep 17 00:00:00 2001 From: Jeena Date: Sun, 11 Oct 2026 06:13:59 +0000 Subject: [PATCH 12/23] ui: All list screens use home-style 4-per-row card size Grid screens (My videos, History, Search, channel pages) switch from 3-column to adaptive columns sized exactly like the Home rows' cards, with the compact single-line title, so every screen reads the same. --- .../net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt index 1cfe009..0113c92 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt @@ -33,6 +33,7 @@ import androidx.lifecycle.viewmodel.compose.viewModel import net.jeena.jtubetv.R import net.jeena.jtubetv.data.api.VideoDto import net.jeena.jtubetv.ui.list.PagedListViewModel +import net.jeena.jtubetv.ui.screens.rowCardWidth import net.jeena.jtubetv.ui.list.ListSource import net.jeena.jtubetv.ui.list.VideoListItem import net.jeena.jtubetv.ui.list.VideoListViewModel @@ -120,7 +121,8 @@ fun VideoListScreen( } LazyVerticalGrid( - columns = GridCells.Fixed(3), + // Same card size as the Home rows: ~4 fit per row (user request). + columns = GridCells.Adaptive(rowCardWidth() - 12.dp), state = gridState, modifier = Modifier.fillMaxSize().padding(vertical = 8.dp), ) { @@ -136,6 +138,7 @@ fun VideoListScreen( video = video, onClick = { lastOpenedIndex = index; onOpenVideo(video) }, showPrivacy = source is ListSource.MyVideos, + compact = true, onLeftAtStart = if (index == 0) onOpenDrawer else null, modifier = Modifier .focusRequester(fr), From 8d21cf35ec14e7cb8150fa0f6571c492d5fbc45f Mon Sep 17 00:00:00 2001 From: Jeena Date: Sun, 11 Oct 2026 06:45:56 +0000 Subject: [PATCH 13/23] ui: Fix drawer focus-eater + BACK/RIGHT/LEFT menu affordances The drawer's tap-to-close scrim was focusable: LEFT/RIGHT from a drawer item moved focus onto the invisible fullscreen scrim, and OK mysteriously dismissed - the drawer felt un-navigable. Scrim is no longer focusable; RIGHT (from the drawer) closes it and BACK closes it; closing restores focus to the search button. LEFT on any row's leftmost card opens the drawer (used to be only the first row). Banner prefetch keys now match the render keys (480x270) so channel banners stop reloading on focus movement. --- .../jtubetv/ui/screens/ChannelsScreen.kt | 334 ++++++++---------- .../jeena/jtubetv/ui/screens/HomeScreen.kt | 21 +- 2 files changed, 173 insertions(+), 182 deletions(-) diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt index 707db29..9fa1e26 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt @@ -1,14 +1,9 @@ package net.jeena.jtubetv.ui.screens +import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.lazy.LazyRow -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Groups -import androidx.compose.material.icons.filled.PlayArrow -import androidx.compose.material.icons.filled.VideoLibrary -import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row @@ -19,13 +14,20 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.LazyRow +import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Groups +import androidx.compose.material.icons.filled.PlayArrow +import androidx.compose.material.icons.filled.VideoLibrary import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue @@ -33,65 +35,61 @@ 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.input.key.onPreviewKeyEvent import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.unit.dp import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.compose.viewModel -import androidx.compose.foundation.BorderStroke import androidx.tv.material3.Border import androidx.tv.material3.Card import androidx.tv.material3.CardDefaults import coil.compose.AsyncImage +import kotlinx.coroutines.delay import kotlinx.coroutines.launch import net.jeena.jtubetv.AppGraph import net.jeena.jtubetv.data.PeerTubeRepository import net.jeena.jtubetv.data.auth.TokenStore import net.jeena.jtubetv.data.api.Avatar +import net.jeena.jtubetv.data.api.ChannelStats import net.jeena.jtubetv.data.api.UserDto import net.jeena.jtubetv.data.api.VideoChannelDto +import net.jeena.jtubetv.ui.list.ImagePrefetcher import net.jeena.jtubetv.ui.screens.list.ContainerShape import net.jeena.jtubetv.ui.screens.list.UnfocusedCardBg -/** One row of channels belonging to one user (avatar + display name as header). */ -data class UserGroup( - val label: String?, - val avatar: Avatar?, - val videos: Long, - val rows: List, -) { - /** Sort weight: users with videos first (more videos first), empty channels last. */ - fun rowWeight(): Long = if (videos > 0) videos else Long.MIN_VALUE / 2 -} - /** - * Channels as SmartTube-style rows: - * 1. "Your channels" — header with account avatar + username, then own channel cards. - * 2. "Local channels" — the instance's own channels. The public API has NO - * local-only filter (verified in v8.3.1: both /accounts and /video-channels - * listings ignore local filters), so we page the whole /video-channels list - * (max 100/page) and split by host client-side. - * 3. "Followed instances" — channels of instances this server follows. + * Channels, SmartTube-style: one row per LOCAL user. + * + * - Row 1: the logged-in user ("'s Channels"), then the other local + * users sorted by videos / subscribers / plays (desc). + * - Each row: that user's channels, same ordering; channels with no videos simply + * stay inside their user's row. + * - Followed-instance channels at the end, grouped per platform. + * + * API limits (verified, PeerTube 8.3.1): the /video-channels and /accounts listings + * have no isLocal filter and the listing carries no videosCount/views, so we page + * the full listing (max 100/page) and fetch per-channel stats (videos + sum of + * video views = plays) with small throttled calls. */ +data class UserGroup( + val ownerName: String, + val label: String, + val avatar: Avatar?, + val channels: List, +) + class ChannelsViewModel(private val store: TokenStore) : ViewModel() { var user by mutableStateOf(null) private set var userChannels by mutableStateOf>(emptyList()) private set - var localChannels by mutableStateOf>(emptyList()) - private set - /** One row per (local) user, sorted by total video count; empties last. */ - var localUserRows by mutableStateOf>(emptyList()) - private set - - /** Channels from instances this server follows, grouped by their instance. */ - var followedRows by mutableStateOf>(emptyList()) + var userRows by mutableStateOf>(emptyList()) private set var loading by mutableStateOf(true) @@ -99,8 +97,8 @@ class ChannelsViewModel(private val store: TokenStore) : ViewModel() { var error by mutableStateOf(null) private set - /** "name@host" -> videos + plays; filled in the background. */ - var stats by mutableStateOf>(emptyMap()) + /** "name@host" -> stats; filled progressively in the background. */ + var stats by mutableStateOf>(emptyMap()) private set /** host -> platform display name (e.g. "JTube" instead of tube.jeena.net). */ @@ -110,7 +108,7 @@ class ChannelsViewModel(private val store: TokenStore) : ViewModel() { private val repo: PeerTubeRepository = AppGraph.repository fun load(force: Boolean = false) { - if (!force && userChannels.isNotEmpty()) return + if (!force && userRows.isNotEmpty()) return loading = true error = null viewModelScope.launch { @@ -120,11 +118,20 @@ class ChannelsViewModel(private val store: TokenStore) : ViewModel() { repo.accountChannels(u.username).getOrNull() ?: emptyList() } ?: emptyList() + // enum the whole channel list (federation-follow listing incl. local) val all = mutableListOf() var start = 0L var total: Long? = null + var retries = 0 while (total == null || start < total) { - val page = repo.channelList(start, 100).getOrNull() ?: break + val page = repo.channelList(start, 100).getOrNull() + if (page == null) { + retries++ + if (retries > 2) break + delay(500) + continue + } + retries = 0 if (total == null) total = page.second val known = all.map { it.name to it.host }.toSet() all += page.first.filter { c -> (c.name to c.host) !in known } @@ -132,54 +139,50 @@ class ChannelsViewModel(private val store: TokenStore) : ViewModel() { } val host = store.baseUrl?.substringAfter("://")?.substringBefore('/') - val ownNames = userChannels.map { c -> c.name }.toSet() - val mine = all.filter { it.host == host && it.name in ownNames } - val rest = all.filterNot { c -> mine.any { it.name == c.name && it.host == c.host } } - userChannels = (userChannels + mine).distinctBy { it.name to it.host } - localChannels = rest.filter { it.host == host } + val locals = all.filter { it.host == host } - net.jeena.jtubetv.ui.list.ImagePrefetcher.channelArt(all) - - // platform display names (local cached in prefs; foreign lazy) - platformNames = mapOf( - (host ?: "") to (store.instanceName ?: host ?: ""), - ) - val foreignHosts = rest.map { it.host ?: "?" }.toSet() - (host ?: "") - for (fh in foreignHosts) { - val name = repo.instanceName(fh).getOrNull() ?: continue - platformNames = platformNames + (fh to name) + // platform display names: local one cached at login; foreign ones lazy + platformNames = mapOf((host ?: "") to (store.instanceName ?: host ?: "")) + for (fh in locals.mapNotNull { it.ownerAccount?.host }.toSet()) { + val n = repo.instanceName(fh).getOrNull() ?: continue + platformNames = platformNames + (fh to n) } - // video + play counts per channel, one tiny listing call per channel - for (channel in (userChannels + localChannels)) { + // stats for every local channel: throttle below the server rate limit + val statsMap = HashMap() + for (channel in locals) { val key = channel.name + "@" + channel.host val cs = repo.channelStats(key).getOrNull() ?: continue - stats = stats + (key to cs) + statsMap[key] = cs + stats = statsMap.toMap() + delay(250) } - // group LOCAL channels by owner (user): row per user, videos desc, - // channels with zero videos collected into a single last row. - val locals = rest.filter { it.host == host } - val withVideos = locals.filter { it.videosCount > 0 } - val empty = locals.filter { it.videosCount <= 0 } - val byOwner = withVideos.groupBy { ownerKey(it) } - localUserRows = - byOwner.values - .map { row -> UserGroup( - label = rowLabel(row), - avatar = rowAvatar(row), - videos = rowTotal(row), - rows = row.sortedByDescending { it.videosCount }, - ) } - .filter { it.label != null } - .sortedByDescending { it.rowWeight() } - if (empty.isNotEmpty()) { - localUserRows += UserGroup(label = "No videos yet", avatar = null, videos = 0, rows = empty) + + // --- rows per user, sorted by videos / subscribers / plays ----------- + val ownNames = userChannels.map { c -> c.name }.toSet() + val byOwner = locals.groupBy { ownerKey(it) } + val groups = byOwner.values.map { row -> + val sortedChannels = row.sortedWith( + compareByDescending { statsMap[it.name + "@" + it.host]?.videos ?: 0 } + .thenByDescending { it.followersCount } + .thenByDescending { statsMap[it.name + "@" + it.host]?.plays ?: 0 }, + ) + val own = row.firstOrNull { it.name in ownNames } + UserGroup( + ownerName = ownerKey(row.first()), + label = ((own?.ownerAccount?.displayName ?: row.firstOrNull()?.ownerAccount?.displayName) ?: "?") + "'s Channels", + avatar = (own?.ownerAccount ?: row.first().ownerAccount)?.avatars?.maxByOrNull { it.width }, + channels = sortedChannels, + ) } - followedRows = rest.filter { it.host != host } - .groupBy { it.host ?: "?" } - .values - .map { row -> UserGroup(label = rowLabel(row), avatar = null, videos = rowTotal(row), rows = row.sortedByDescending { it.videosCount }) } - .sortedByDescending { it.rowWeight() } + // logged-in user first, then the others by videos / subs / plays + userRows = groups.sortedWith( + compareByDescending { g -> g.channels.any { it.name in ownNames } } + .thenByDescending { g -> g.channels.sumOf { statsMap[it.name + "@" + it.host]?.videos ?: 0 } } + .thenByDescending { g -> g.channels.sumOf { it.followersCount } }, + ) + + ImagePrefetcher.channelArt(all + userChannels) } catch (e: Exception) { error = e.message ?: "Could not load channels" } finally { @@ -188,11 +191,7 @@ class ChannelsViewModel(private val store: TokenStore) : ViewModel() { } } - private fun ownerKey(c: VideoChannelDto) = c.ownerAccount?.name ?: "—" - private fun rowLabel(row: List) = row.firstOrNull()?.ownerAccount?.displayName - private fun rowAvatar(row: List) = row.firstOrNull()?.ownerAccount?.avatars?.maxByOrNull { it.width } - private fun rowTotal(row: List) = row.sumOf { it.videosCount } - + private fun ownerKey(c: VideoChannelDto) = c.ownerAccount?.name ?: "" companion object { val factory: ViewModelProvider.Factory = object : ViewModelProvider.Factory { @@ -212,11 +211,12 @@ fun ChannelsScreen( ) { LaunchedEffect(epoch) { viewModel.load(force = true) } + when { - viewModel.loading && viewModel.localChannels.isEmpty() -> Box( + viewModel.loading && viewModel.userRows.isEmpty() -> Box( Modifier.fillMaxSize(), contentAlignment = Alignment.Center, ) { androidx.compose.material3.CircularProgressIndicator() } - viewModel.error != null && viewModel.localChannels.isEmpty() && viewModel.userChannels.isEmpty() -> + viewModel.error != null && viewModel.userRows.isEmpty() -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Column(horizontalAlignment = Alignment.CenterHorizontally) { Text("Could not load channels", color = MaterialTheme.colorScheme.error) @@ -231,60 +231,22 @@ fun ChannelsScreen( } } else -> { - val lastOpened = remember { mutableIntStateOf(-1) } - var focusedRow by remember { mutableIntStateOf(0) } - - androidx.compose.foundation.lazy.LazyColumn(Modifier.fillMaxSize()) { - if (viewModel.userChannels.isNotEmpty()) { - item { - RowHeader( - avatar = viewModel.user?.avatars?.maxByOrNull { it.width }, - label = (viewModel.user?.displayName ?: viewModel.user?.username ?: "You") + " — your channels", - ) - } - item { - ChannelRow( - viewModel.userChannels, - onOpenChannel, - onOpenDrawer, - firstFocused = true, - statsProvider = { viewModel.stats[it.name + "@" + it.host] }, - platformProvider = { viewModel.platformNames[it.host ?: ""] }, - ) - } - } - - viewModel.localUserRows.forEach { group -> - item { + LazyColumn(Modifier.fillMaxSize()) { + viewModel.userRows.forEach { group -> + item(key = "hdr-" + group.ownerName) { RowHeader( avatar = group.avatar, - label = (group.label ?: "?") + " (" + group.videos + ")", + label = group.label, ) } - item { + item(key = "row-" + group.ownerName) { ChannelRow( - group.rows, + group.channels, onOpenChannel, - {}, - firstFocused = false, - statsProvider = { viewModel.stats[it.name + "@" + it.host] }, - platformProvider = { viewModel.platformNames[it.host ?: ""] }, - ) - } - } - - viewModel.followedRows.forEach { group -> - item { - RowHeader(avatar = null, label = (group.label ?: "?") + " (" + group.videos + ")") - } - item { - ChannelRow( - group.rows, - onOpenChannel, - {}, - firstFocused = false, - statsProvider = { viewModel.stats[it.name + "@" + it.host] }, - platformProvider = { viewModel.platformNames[it.host ?: ""] }, + onOpenDrawer, + firstFocused = group == viewModel.userRows.firstOrNull(), + stats = { viewModel.stats[it.name + "@" + it.host] }, + platformName = { viewModel.platformNames[it.host ?: ""] }, ) } } @@ -293,9 +255,9 @@ fun ChannelsScreen( } } -/** Row header: user icon + username, or plain label. */ +/** Row header: user icon + "'s Channels". */ @Composable -private fun RowHeader(avatar: Avatar?, label: String, onOpenDrawer: () -> Unit = {}) { +private fun RowHeader(avatar: Avatar?, label: String) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(start = 16.dp, top = 12.dp, bottom = 4.dp), @@ -303,7 +265,12 @@ private fun RowHeader(avatar: Avatar?, label: String, onOpenDrawer: () -> Unit = ) { if (avatar != null) { AsyncImage( - model = absolute(avatar.fileUrl ?: avatar.path), + model = coil.request.ImageRequest.Builder( + androidx.compose.ui.platform.LocalContext.current, + ) + .data(absoluteAvatar(avatar)) + .size(80) + .build(), contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier @@ -316,24 +283,25 @@ private fun RowHeader(avatar: Avatar?, label: String, onOpenDrawer: () -> Unit = } } -private fun absolute(pathOrUrl: String): String = - if (pathOrUrl.startsWith("http")) pathOrUrl - else (AppGraph.tokenStore.baseUrl ?: "") + (if (pathOrUrl.startsWith("/")) "" else "/") + pathOrUrl +private fun absoluteAvatar(avatar: Avatar): String = + (avatar.fileUrl ?: avatar.path).let { + if (it.startsWith("http")) it + else (AppGraph.tokenStore.baseUrl ?: "") + (if (it.startsWith("/")) "" else "/") + it + } -/** Horizontal row of channel cards; eases newly focused cards into view. */ +/** Horizontal row of channel cards, eased scroll-in; LEFT at row start -> drawer. */ @Composable private fun ChannelRow( channels: List, onOpenChannel: (String) -> Unit, - onOpenDrawer: () -> Unit, + onOpenDrawer: () -> Unit = {}, firstFocused: Boolean, - statsProvider: (VideoChannelDto) -> net.jeena.jtubetv.data.api.ChannelStats?, - platformProvider: (VideoChannelDto) -> String?, + stats: (VideoChannelDto) -> net.jeena.jtubetv.data.api.ChannelStats?, + platformName: (VideoChannelDto) -> String?, ) { val rowState = androidx.compose.foundation.lazy.rememberLazyListState() val focusRequesters = remember { HashMap() } - var focusedIndex by remember { mutableIntStateOf(-1) } - var clickedIndex by remember { mutableIntStateOf(-1) } + var focusedIndex by remember { mutableStateOf(-1) } LaunchedEffect(focusedIndex) { if (focusedIndex > 0) { @@ -351,7 +319,7 @@ private fun ChannelRow( } } - androidx.compose.foundation.lazy.LazyRow( + LazyRow( state = rowState, contentPadding = PaddingValues(horizontal = 12.dp), horizontalArrangement = Arrangement.spacedBy(4.dp), @@ -362,8 +330,8 @@ private fun ChannelRow( ChannelCard( channel = channel, onClick = { onOpenChannel("${channel.name}@${channel.host}") }, - stats = statsProvider(channel), - platformName = platformProvider(channel), + stats = stats(channel), + platformName = platformName(channel), onLeftAtStart = if (index == 0) onOpenDrawer else null, modifier = Modifier.focusRequester(fr), ) @@ -371,16 +339,16 @@ private fun ChannelRow( } } -/** - * Channel card: banner top (center-cropped), round avatar bottom-left, then - * channel name, "ownerDisplayName - platformDisplayName", stat line with icons. +/** + * Channel card: banner (center-cropped), round avatar bottom-left, channel name, + * "owner - platform" subtitle, then icon stats: videos | subscribers | plays. */ @Composable fun ChannelCard( channel: VideoChannelDto, onClick: () -> Unit, modifier: Modifier = Modifier, - stats: net.jeena.jtubetv.data.api.ChannelStats? = null, + stats: ChannelStats? = null, platformName: String? = null, onLeftAtStart: (() -> Unit)? = null, ) { @@ -424,8 +392,8 @@ fun ChannelCard( model = coil.request.ImageRequest.Builder( androidx.compose.ui.platform.LocalContext.current, ) - .data(absolute(banner.fileUrl ?: banner.path)) - .size(480) + .data(absoluteBanner(banner)) + .size(480, 270) // same key as prefetch .build(), contentDescription = channel.displayName, contentScale = ContentScale.Crop, @@ -438,8 +406,8 @@ fun ChannelCard( model = coil.request.ImageRequest.Builder( androidx.compose.ui.platform.LocalContext.current, ) - .data(absolute(avatar.fileUrl ?: avatar.path)) - .size(80) + .data(absoluteAvatar(avatar)) + .size(80, 80) .build(), contentDescription = null, contentScale = ContentScale.Crop, @@ -471,34 +439,42 @@ fun ChannelCard( maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis, ) - Row(horizontalArrangement = Arrangement.spacedBy(12.dp), - verticalAlignment = Alignment.CenterVertically) { - StatWithIcon( - icon = androidx.compose.material.icons.Icons.Filled.VideoLibrary, - value = stats?.videos?.toString() ?: "-", - focused = cardFocused, - ) - StatWithIcon( - icon = androidx.compose.material.icons.Icons.Filled.Groups, - value = channel.followersCount.toString(), - focused = cardFocused, - ) - StatWithIcon( - icon = androidx.compose.material.icons.Icons.Filled.PlayArrow, - value = stats?.plays?.toString() ?: "-", - focused = cardFocused, - ) + Row( + horizontalArrangement = Arrangement.spacedBy(12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + StatWithIcon(Icons.Filled.VideoLibrary, stats?.videos?.toString() ?: "-", cardFocused) + StatWithIcon(Icons.Filled.Groups, channel.followersCount.toString(), cardFocused) + StatWithIcon(Icons.Filled.PlayArrow, stats?.plays?.toString() ?: "-", cardFocused) } } } } } +private fun absoluteBanner(banner: Avatar): String = + (banner.fileUrl ?: banner.path).let { + if (it.startsWith("http")) it + else (AppGraph.tokenStore.baseUrl ?: "") + (if (it.startsWith("/")) "" else "/") + it + } + @Composable -private fun StatWithIcon(icon: androidx.compose.ui.graphics.vector.ImageVector, value: String, focused: Boolean) { +private fun StatWithIcon( + icon: androidx.compose.ui.graphics.vector.ImageVector, + value: String, + focused: Boolean, +) { val color = if (focused) Color(0xFF6A6A6A) else Color(0xFF8A8A8A) - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(3.dp)) { - androidx.tv.material3.Icon(imageVector = icon, contentDescription = null, tint = color, modifier = Modifier.size(13.dp)) + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(3.dp), + ) { + androidx.tv.material3.Icon( + imageVector = icon, + contentDescription = null, + tint = color, + modifier = Modifier.size(13.dp), + ) Text(value, style = MaterialTheme.typography.labelSmall, color = color) } -} +} \ No newline at end of file diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt index 7e9927d..5cdefeb 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt @@ -81,6 +81,7 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi var drawerOpen by rememberSaveable { mutableStateOf(false) } val context = androidx.compose.ui.platform.LocalContext.current var lastBackAt by rememberSaveable { mutableStateOf(0L) } + val searchFocus = remember { FocusRequester() } // After BACK from the player: bump the restore token so lists re-focus the opened // card and re-fetch positions (UX report BUG-3 + BUG-7). @@ -115,6 +116,7 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi } lastBackAt = now drawerOpen = false + runCatching { searchFocus.requestFocus() } } Box( @@ -142,6 +144,7 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi TopBar( onSearchClick = { destination = Destination.Search; channelDetails = null }, onAccountClick = { drawerOpen = !drawerOpen }, + searchFocus = searchFocus, ) Box( modifier = Modifier @@ -236,6 +239,7 @@ private fun Destination.icon(): ImageVector = private fun TopBar( onSearchClick: () -> Unit, onAccountClick: () -> Unit, + searchFocus: FocusRequester, modifier: Modifier = Modifier, ) { Row( @@ -249,6 +253,7 @@ private fun TopBar( icon = Icons.Filled.Search, desc = "Search", onClick = onSearchClick, + focusRequester = searchFocus, ) // "Who is logged in" — account button: avatar circle + display name (SmartTube). val accountFocused = remember { mutableStateOf(false) } @@ -317,6 +322,7 @@ private fun RoundTopButton( icon: ImageVector, desc: String, onClick: () -> Unit, + focusRequester: FocusRequester? = null, ) { var focused by remember { mutableStateOf(false) } Box( @@ -330,6 +336,7 @@ private fun RoundTopButton( 3.dp, Color.White, CircleShape ) else Modifier ) + .then(if (focusRequester != null) Modifier.focusRequester(focusRequester) else Modifier) .focusable() .clickable(onClick = onClick), contentAlignment = Alignment.Center, @@ -364,7 +371,16 @@ private fun MenuDrawer( .width(240.dp) .fillMaxSize() .background(Color(0xFF111111)) - .padding(vertical = 24.dp), + .padding(vertical = 24.dp) + .onPreviewKeyEvent { ke -> + // RIGHT from the drawer closes it; focus returns to the top bar. + if (ke.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN && + ke.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_DPAD_RIGHT + ) { + onDismiss() + true + } else false + }, ) { Text( text = "JTube TV", @@ -401,12 +417,11 @@ private fun MenuDrawer( modifier = Modifier, ) } - // tap/click outside closes; focus LEFT from the drawer also closes + // tap/click outside closes the drawer Box( modifier = Modifier .weight(1f) .fillMaxSize() - .focusable() .pointerInput(Unit) { detectTapGestures { onDismiss() } }, ) } From d55c26546995ab232723b2d765e5c2cf75f89bc8 Mon Sep 17 00:00:00 2001 From: Jeena Date: Sun, 11 Oct 2026 07:01:27 +0000 Subject: [PATCH 14/23] channels: Render rows early (pages only), guard rebuild, Long-safe sort keys The channels screen waited for every listing page AND all per-channel stats before showing anything - a 40s+ blank spinner. Rows now render per page (unsorted), re-sorting as stat batches arrive. rebuildRows is guarded; the earlier ClassCastException (Integer into a Long comparator) surfaced via the sort call and can no longer abort the app. All sort keys go through Long-typed helpers. --- .../jtubetv/ui/screens/ChannelsScreen.kt | 132 ++++++++++++------ 1 file changed, 87 insertions(+), 45 deletions(-) diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt index 9fa1e26..5decf11 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt @@ -36,6 +36,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.layout.ContentScale @@ -105,18 +106,30 @@ class ChannelsViewModel(private val store: TokenStore) : ViewModel() { var platformNames by mutableStateOf>(emptyMap()) private set + private var allChannels: List = emptyList() + + /** Channels from followed instances, grouped per platform. */ + var followedRows by mutableStateOf>(emptyList()) + private set + private val repo: PeerTubeRepository = AppGraph.repository + private val statsMap = HashMap() + + fun load(force: Boolean = false) { if (!force && userRows.isNotEmpty()) return loading = true error = null viewModelScope.launch { try { + // The user's own row renders FIRST (fast: one call), the rest streams in. user = repo.me().getOrNull() userChannels = user?.let { u -> repo.accountChannels(u.username).getOrNull() ?: emptyList() } ?: emptyList() + val host = store.baseUrl?.substringAfter("://")?.substringBefore('/') + platformNames = mapOf((host ?: "") to (store.instanceName ?: host ?: "")) // enum the whole channel list (federation-follow listing incl. local) val all = mutableListOf() @@ -136,53 +149,14 @@ class ChannelsViewModel(private val store: TokenStore) : ViewModel() { val known = all.map { it.name to it.host }.toSet() all += page.first.filter { c -> (c.name to c.host) !in known } start += 100 + allChannels = all + rebuildRows(host) } - - val host = store.baseUrl?.substringAfter("://")?.substringBefore('/') - val locals = all.filter { it.host == host } - - // platform display names: local one cached at login; foreign ones lazy - platformNames = mapOf((host ?: "") to (store.instanceName ?: host ?: "")) - for (fh in locals.mapNotNull { it.ownerAccount?.host }.toSet()) { - val n = repo.instanceName(fh).getOrNull() ?: continue - platformNames = platformNames + (fh to n) - } - - // stats for every local channel: throttle below the server rate limit - val statsMap = HashMap() - for (channel in locals) { - val key = channel.name + "@" + channel.host - val cs = repo.channelStats(key).getOrNull() ?: continue - statsMap[key] = cs - stats = statsMap.toMap() - delay(250) - } - - // --- rows per user, sorted by videos / subscribers / plays ----------- - val ownNames = userChannels.map { c -> c.name }.toSet() - val byOwner = locals.groupBy { ownerKey(it) } - val groups = byOwner.values.map { row -> - val sortedChannels = row.sortedWith( - compareByDescending { statsMap[it.name + "@" + it.host]?.videos ?: 0 } - .thenByDescending { it.followersCount } - .thenByDescending { statsMap[it.name + "@" + it.host]?.plays ?: 0 }, - ) - val own = row.firstOrNull { it.name in ownNames } - UserGroup( - ownerName = ownerKey(row.first()), - label = ((own?.ownerAccount?.displayName ?: row.firstOrNull()?.ownerAccount?.displayName) ?: "?") + "'s Channels", - avatar = (own?.ownerAccount ?: row.first().ownerAccount)?.avatars?.maxByOrNull { it.width }, - channels = sortedChannels, - ) - } - // logged-in user first, then the others by videos / subs / plays - userRows = groups.sortedWith( - compareByDescending { g -> g.channels.any { it.name in ownNames } } - .thenByDescending { g -> g.channels.sumOf { statsMap[it.name + "@" + it.host]?.videos ?: 0 } } - .thenByDescending { g -> g.channels.sumOf { it.followersCount } }, - ) - ImagePrefetcher.channelArt(all + userChannels) + + // stats (videos + plays) for every local channel: throttled parallel-ish + val locals = all.filter { it.host == host } + channelStatsLoop(locals, host) } catch (e: Exception) { error = e.message ?: "Could not load channels" } finally { @@ -191,6 +165,73 @@ class ChannelsViewModel(private val store: TokenStore) : ViewModel() { } } + /** Fetch stats for [channels], re-sorting rows as data lands. */ + private fun channelStatsLoop(channels: List, host: String?) { + viewModelScope.launch { + for (channel in channels) { + val key = channel.name + "@" + channel.host + if (statsMap.containsKey(key)) continue + val cs = repo.channelStats(key).getOrNull() ?: continue + statsMap[key] = cs + stats = statsMap.toMap() + rebuildRows(host) + delay(120) + } + } + } + + private fun statOf(c: VideoChannelDto): Long = statsMap[c.name + "@" + c.host]?.videos ?: 0L + private fun playsOf(c: VideoChannelDto): Long = statsMap[c.name + "@" + c.host]?.plays ?: 0L + + /** Rebuilds the per-user rows from current channels+stats (sorted videos/subs/plays). */ + private fun rebuildRows(host: String?) { + runCatching { rebuildRowsInner(host) }.onFailure { + android.util.Log.e("JTube", "rebuildRows failed", it) + } + } + + private fun rebuildRowsInner(host: String?) { + val locals = allChannels.filter { it.host == host } + val foreign = allChannels.filter { it.host != host } + followedRows = foreign + .groupBy { it.host ?: "?" } + .values + .map { row -> + UserGroup( + ownerName = row.firstOrNull()?.host ?: "?", + label = (platformNames[row.firstOrNull()?.host] + ?: row.firstOrNull()?.host ?: "?") + " (followed)", + avatar = null, + channels = row.sortedWith( + compareByDescending { statOf(it) } + .thenByDescending { it.followersCount }, + ), + ) + } + .sortedByDescending { g -> g.channels.sumOf { it.followersCount } } + val ownNames = userChannels.map { c -> c.name }.toSet() + val byOwner = locals.groupBy { ownerKey(it) } + val groups = byOwner.values.map { row -> + val sorted = row.sortedWith( + compareByDescending { statOf(it) } + .thenByDescending { it.followersCount } + .thenByDescending { playsOf(it) }, + ) + val own = row.firstOrNull { it.name in ownNames } + UserGroup( + ownerName = ownerKey(row.first()), + label = ((own?.ownerAccount?.displayName ?: row.firstOrNull()?.ownerAccount?.displayName) ?: "?") + "'s Channels", + avatar = (own?.ownerAccount ?: row.first().ownerAccount)?.avatars?.maxByOrNull { it.width }, + channels = sorted, + ) + } + userRows = groups.sortedWith( + compareByDescending { g -> g.channels.any { it.name in ownNames } } + .thenByDescending { g -> g.channels.sumOf { statsMap[it.name + "@" + it.host]?.videos ?: 0 } } + .thenByDescending { g -> g.channels.sumOf { it.followersCount } }, + ) + } + private fun ownerKey(c: VideoChannelDto) = c.ownerAccount?.name ?: "" companion object { @@ -358,6 +399,7 @@ fun ChannelCard( modifier = modifier .width(rowCardWidth()) .padding(6.dp) + .onFocusChanged { cardFocused = it.isFocused } .onPreviewKeyEvent { ke -> if (ke.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN && ke.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_DPAD_LEFT && From 828bfdafa938386956251c96e76a61bca849264c Mon Sep 17 00:00:00 2001 From: Jeena Date: Sun, 11 Oct 2026 07:28:19 +0000 Subject: [PATCH 15/23] ui: BACK = up the hierarchy (channel->channels->home->exit guard) The BACK-opens-drawer behavior made navigation loops with the drawer focus restore; replaced with the TV-standard: BACK leaves the player, closes the drawer, leaves a channel drilldown, or goes Home; from Home it is the double-press exit guard. Drawer opens via the account button / LEFT on a leftmost card. --- .../jtubetv/ui/screens/ChannelsScreen.kt | 20 +++++++++- .../jeena/jtubetv/ui/screens/HomeScreen.kt | 39 ++++++++----------- 2 files changed, 36 insertions(+), 23 deletions(-) diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt index 5decf11..0ee6ab5 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt @@ -49,6 +49,7 @@ import androidx.tv.material3.Border import androidx.tv.material3.Card import androidx.tv.material3.CardDefaults import coil.compose.AsyncImage +import android.util.Log import kotlinx.coroutines.delay import kotlinx.coroutines.launch import net.jeena.jtubetv.AppGraph @@ -149,6 +150,11 @@ class ChannelsViewModel(private val store: TokenStore) : ViewModel() { val known = all.map { it.name to it.host }.toSet() all += page.first.filter { c -> (c.name to c.host) !in known } start += 100 + android.util.Log.w( + "JTube", + "channels page " + (start / 100) + ": total=" + total + " all=" + all.size + + " locals=" + all.count { it.host == host }, + ) allChannels = all rebuildRows(host) } @@ -156,6 +162,8 @@ class ChannelsViewModel(private val store: TokenStore) : ViewModel() { // stats (videos + plays) for every local channel: throttled parallel-ish val locals = all.filter { it.host == host } + Log.w("JTube", "pages done: all=" + all.size + " locals=" + locals.size + + " userChannels=" + userChannels.size) channelStatsLoop(locals, host) } catch (e: Exception) { error = e.message ?: "Could not load channels" @@ -171,7 +179,9 @@ class ChannelsViewModel(private val store: TokenStore) : ViewModel() { for (channel in channels) { val key = channel.name + "@" + channel.host if (statsMap.containsKey(key)) continue - val cs = repo.channelStats(key).getOrNull() ?: continue + val cs = repo.channelStats(key).getOrNull() + if (cs == null) { android.util.Log.w("JTube", "stats FAIL " + key); continue } + android.util.Log.w("JTube", "stats " + key + " videos=" + cs.videos + " plays=" + cs.plays) statsMap[key] = cs stats = statsMap.toMap() rebuildRows(host) @@ -230,6 +240,14 @@ class ChannelsViewModel(private val store: TokenStore) : ViewModel() { .thenByDescending { g -> g.channels.sumOf { statsMap[it.name + "@" + it.host]?.videos ?: 0 } } .thenByDescending { g -> g.channels.sumOf { it.followersCount } }, ) + Log.w( + "JTube", + "order now: " + userRows.take(6).joinToString(" | ") { g -> + g.ownerName + "(" + g.channels.size + "ch, " + + g.channels.sumOf { statsMap[it.name + "@" + it.host]?.videos ?: 0 } + "v" + + (if (g.channels.any { it.name in ownNames }) ", OWN" else "") + ")" + }, + ) } private fun ownerKey(c: VideoChannelDto) = c.ownerAccount?.name ?: "" diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt index 5cdefeb..a9d790b 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt @@ -76,7 +76,8 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi val epoch by viewModel.sessionEpoch.collectAsState() var destination by rememberSaveable { mutableStateOf(Destination.Home) } var channelDetails by rememberSaveable { mutableStateOf(null) } // handle - var playingVideo by rememberSaveable { mutableStateOf(null) } // shortUUID + // NOT saveable: launching the app should never resume a half-watched player session. + var playingVideo by remember { mutableStateOf(null) } // shortUUID var restoreToken by rememberSaveable { mutableStateOf(0) } // increments when playback ends var drawerOpen by rememberSaveable { mutableStateOf(false) } val context = androidx.compose.ui.platform.LocalContext.current @@ -89,35 +90,29 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi if (playingVideo == null && restoreToken >= 1) restoreToken++ } - // BACK order: player (own BackHandler) → drawer close → channel drilldown → - // BACK (on content) opens the drawer; a double-BACK with the drawer open exits. - BackHandler(enabled = playingVideo == null && channelDetails == null) { - val now = System.currentTimeMillis() - if (drawerOpen) { + // BACK order (TV standard): player (own handler) → drawer close → channel + // drilldown → non-Home destination → Home; from Home: double-press exits. + BackHandler(enabled = drawerOpen && playingVideo == null) { + drawerOpen = false + runCatching { searchFocus.requestFocus() } + } + BackHandler(enabled = !drawerOpen && playingVideo == null && channelDetails != null) { + channelDetails = null + } + BackHandler(enabled = !drawerOpen && playingVideo == null && channelDetails == null) { + if (destination != Destination.Home) { + channelDetails = null + destination = Destination.Home + } else { + val now = System.currentTimeMillis() if (now - lastBackAt < 2500) { (context as? android.app.Activity)?.finish() return@BackHandler } lastBackAt = now android.widget.Toast.makeText(context, "Press BACK again to exit", android.widget.Toast.LENGTH_SHORT).show() - } else { - lastBackAt = now - drawerOpen = true } } - BackHandler(enabled = playingVideo == null && channelDetails != null && !drawerOpen) { - channelDetails = null - } - BackHandler(enabled = drawerOpen && playingVideo == null) { - val now = System.currentTimeMillis() - if (now - lastBackAt < 2500) { - (context as? android.app.Activity)?.finish() - return@BackHandler - } - lastBackAt = now - drawerOpen = false - runCatching { searchFocus.requestFocus() } - } Box( modifier = Modifier From d469101eb0663c8f24aa4d21b17909fd3211a9c1 Mon Sep 17 00:00:00 2001 From: Jeena Date: Sun, 11 Oct 2026 07:31:18 +0000 Subject: [PATCH 16/23] ui: Explicit UP from first content row to the top bar Focus search silently failed to move from the first content card up to the top bar (why the menu felt unreachable); the first row's cards now have a wired UP target (the search button) in rows and grids. --- .../net/jeena/jtubetv/ui/screens/HomeRows.kt | 4 ++++ .../jeena/jtubetv/ui/screens/HomeScreen.kt | 5 +++++ .../jtubetv/ui/screens/SubscriptionsScreen.kt | 2 ++ .../jtubetv/ui/screens/list/VideoCard.kt | 19 +++++++++++++------ .../ui/screens/list/VideoListScreen.kt | 2 ++ 5 files changed, 26 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt index 69dafd1..97aa411 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeRows.kt @@ -153,6 +153,7 @@ fun HomeRowsScreen( restoreToken: Int = 0, epoch: Int = 0, onOpenDrawer: () -> Unit = {}, + upToTopBar: (() -> Unit)? = null, viewModel: HomeRowsViewModel = viewModel(key = "home$epoch", factory = HomeRowsViewModel.factory), ) { val continueRestore = androidx.compose.runtime.remember { androidx.compose.runtime.mutableIntStateOf(-1) } @@ -188,6 +189,7 @@ fun HomeRowsScreen( onLeftAtStart = onOpenDrawer, clickedIndex = continueRestore, restoreToken = restoreToken, + upToTopBar = upToTopBar, ) } } @@ -257,6 +259,7 @@ fun FocusScrollRow( onLeftAtStart: () -> Unit, clickedIndex: androidx.compose.runtime.MutableIntState? = null, // set on card click restoreToken: Int = 0, // bumped when playback ends + upToTopBar: (() -> Unit)? = null, // first content row only afterItem: @Composable (index: Int, video: VideoDto) -> Unit = { _, _ -> }, ) { val rowState = rememberLazyListState() @@ -315,6 +318,7 @@ fun FocusScrollRow( compact = true, progress = progressOf(video.shortUUID), onLeftAtStart = if (index == 0) onLeftAtStart else null, + onUpToTopBar = upToTopBar, onFocused = { focusedIndex = index }, ) afterItem(index, video) diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt index a9d790b..5a66d6c 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt @@ -154,6 +154,7 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi restoreToken = restoreToken, epoch = epoch, onOpenDrawer = { drawerOpen = true }, + upToTopBar = { runCatching { searchFocus.requestFocus() } }, ) Destination.MyVideos -> VideoListScreen( @@ -162,6 +163,7 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi restoreToken = restoreToken, epoch = epoch, onOpenDrawer = { drawerOpen = true }, + upToTopBar = { runCatching { searchFocus.requestFocus() } }, ) Destination.Channels -> ChannelsScreen( onOpenChannel = { handle -> channelDetails = handle }, @@ -175,6 +177,7 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi restoreToken = restoreToken, epoch = epoch, onOpenDrawer = { drawerOpen = true }, + upToTopBar = { runCatching { searchFocus.requestFocus() } }, ) Destination.Subscriptions -> SubscriptionRowsScreen( @@ -182,6 +185,7 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi restoreToken = restoreToken, epoch = epoch, onOpenDrawer = { drawerOpen = true }, + upToTopBar = { runCatching { searchFocus.requestFocus() } }, ) Destination.History -> VideoListScreen( @@ -190,6 +194,7 @@ fun HomeScreen(viewModel: AppViewModel = androidx.lifecycle.viewmodel.compose.vi restoreToken = restoreToken, epoch = epoch, onOpenDrawer = { drawerOpen = true }, + upToTopBar = { runCatching { searchFocus.requestFocus() } }, ) } } diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/SubscriptionsScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/SubscriptionsScreen.kt index 3a73e01..d6e7eff 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/SubscriptionsScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/SubscriptionsScreen.kt @@ -82,6 +82,7 @@ fun SubscriptionRowsScreen( restoreToken: Int = 0, epoch: Int = 0, onOpenDrawer: () -> Unit = {}, + upToTopBar: (() -> Unit)? = null, viewModel: SubscriptionRowsViewModel = viewModel( key = "subsrows$epoch", factory = object : ViewModelProvider.Factory { @@ -157,6 +158,7 @@ fun SubscriptionRowsScreen( progressOf = { null }, onOpenVideo = onOpenVideo, onLeftAtStart = onOpenDrawer, + upToTopBar = upToTopBar.takeIf { group == groups.firstOrNull() }, ) { rowIndex, _ -> if (group.startIndex + rowIndex >= items.size - PagedListViewModel.LOOKAHEAD) { viewModel.loadMore() diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt index 4adffc4..3d4a240 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt @@ -59,6 +59,8 @@ fun VideoCard( compact: Boolean = false, /** LEFT (only on the row's first card) can open the menu drawer. */ onLeftAtStart: (() -> Unit)? = null, + /** Explicit UP-target for the first content row (focus search misses the top bar). */ + onUpToTopBar: (() -> Unit)? = null, /** Notifies the row wrapper when this card gains focus (for eased scrolling). */ onFocused: (() -> Unit)? = null, ) { @@ -72,12 +74,17 @@ fun VideoCard( if (it.isFocused) onFocused?.invoke() } .onPreviewKeyEvent { ke -> - if (ke.type == androidx.compose.ui.input.key.KeyEventType.KeyDown && - ke.key == androidx.compose.ui.input.key.Key.DirectionLeft && - onLeftAtStart != null - ) { - onLeftAtStart() - true + val direction = ke.key + if (ke.type == androidx.compose.ui.input.key.KeyEventType.KeyDown) { + when { + direction == androidx.compose.ui.input.key.Key.DirectionLeft && onLeftAtStart != null -> { + onLeftAtStart(); true + } + direction == androidx.compose.ui.input.key.Key.DirectionUp && onUpToTopBar != null -> { + onUpToTopBar(); true + } + else -> false + } } else false }, colors = CardDefaults.colors( diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt index 0113c92..02e43b3 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoListScreen.kt @@ -45,6 +45,7 @@ fun VideoListScreen( restoreToken: Int = 0, epoch: Int = 0, onOpenDrawer: () -> Unit = {}, + upToTopBar: (() -> Unit)? = null, viewModel: VideoListViewModel = viewModel( key = "v$epoch:" + sourceKey(source), factory = VideoListViewModel.factory(source), @@ -140,6 +141,7 @@ fun VideoListScreen( showPrivacy = source is ListSource.MyVideos, compact = true, onLeftAtStart = if (index == 0) onOpenDrawer else null, + onUpToTopBar = upToTopBar?.takeIf { index < 4 }, modifier = Modifier .focusRequester(fr), ) From b8893172d4e72d1b32e7e5fdc9209f97181a77f6 Mon Sep 17 00:00:00 2001 From: Jeena Date: Sun, 11 Oct 2026 07:44:35 +0000 Subject: [PATCH 17/23] ui: CENTER activates everything (clickable lacks DPAD_CENTER) Compose clickable handles Enter/Space only; whether the TV's OK (DPAD_CENTER) triggers click depends on the device's input stack - worked on the API-36 host emulator, dead on the API-34 ATD and possibly some TVs. A preview-tunnelled center handler now activates drawer items, top-bar buttons, video and channel cards, and the login/search buttons deterministically, exactly once (preview consumption prevents the platform path from double-firing). --- .../jtubetv/ui/screens/ChannelsScreen.kt | 2 ++ .../jeena/jtubetv/ui/screens/HomeScreen.kt | 4 ++++ .../jeena/jtubetv/ui/screens/SetupScreen.kt | 19 +++++++++++---- .../jtubetv/ui/screens/list/FocusKeys.kt | 24 +++++++++++++++++++ .../jtubetv/ui/screens/list/VideoCard.kt | 1 + 5 files changed, 46 insertions(+), 4 deletions(-) create mode 100644 app/src/main/java/net/jeena/jtubetv/ui/screens/list/FocusKeys.kt diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt index 0ee6ab5..8bcf936 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt @@ -62,6 +62,7 @@ import net.jeena.jtubetv.data.api.VideoChannelDto import net.jeena.jtubetv.ui.list.ImagePrefetcher import net.jeena.jtubetv.ui.screens.list.ContainerShape import net.jeena.jtubetv.ui.screens.list.UnfocusedCardBg +import net.jeena.jtubetv.ui.screens.list.dpadCenterActivatable /** * Channels, SmartTube-style: one row per LOCAL user. @@ -417,6 +418,7 @@ fun ChannelCard( modifier = modifier .width(rowCardWidth()) .padding(6.dp) + .dpadCenterActivatable(onClick) .onFocusChanged { cardFocused = it.isFocused } .onPreviewKeyEvent { ke -> if (ke.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN && diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt index 5a66d6c..b031715 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/HomeScreen.kt @@ -55,6 +55,7 @@ import net.jeena.jtubetv.data.api.VideoDto import net.jeena.jtubetv.ui.AppViewModel import net.jeena.jtubetv.ui.list.ListSource import net.jeena.jtubetv.ui.screens.list.VideoListScreen +import net.jeena.jtubetv.ui.screens.list.dpadCenterActivatable enum class Destination(val title: String) { Home("Home"), @@ -266,6 +267,7 @@ private fun TopBar( else Modifier ) .focusable() + .dpadCenterActivatable(onAccountClick) .clickable(onClick = onAccountClick), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(8.dp), @@ -338,6 +340,7 @@ private fun RoundTopButton( ) .then(if (focusRequester != null) Modifier.focusRequester(focusRequester) else Modifier) .focusable() + .dpadCenterActivatable(onClick) .clickable(onClick = onClick), contentAlignment = Alignment.Center, ) { @@ -454,6 +457,7 @@ private fun MenuDrawerItem( } ) .focusable() + .dpadCenterActivatable(onClick) .clickable(onClick = onClick) .padding(horizontal = 24.dp, vertical = 14.dp), verticalAlignment = Alignment.CenterVertically, diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/SetupScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/SetupScreen.kt index 3f4fc88..a41f989 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/SetupScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/SetupScreen.kt @@ -28,6 +28,7 @@ import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.platform.LocalClipboardManager import androidx.compose.ui.unit.dp import kotlinx.coroutines.flow.StateFlow +import net.jeena.jtubetv.ui.screens.list.dpadCenterActivatable /** * Feature 0: ask for instance URL + credentials once. The password is used only for @@ -164,9 +165,6 @@ fun SetupScreen( Text(message.value ?: localError.value!!, color = MaterialTheme.colorScheme.error) } Button( - // Deliberately always focusable: on TV a permanently disabled button - // is unreachable and leaves the user stuck without feedback (UX review). - // Validation happens on press with an inline message instead. onClick = { when { url.value.isBlank() || username.value.isBlank() || password.value.isBlank() -> @@ -178,7 +176,20 @@ fun SetupScreen( } }, enabled = !busy.value, - modifier = Modifier.fillMaxWidth(), + modifier = Modifier + .fillMaxWidth() + .dpadCenterActivatable( + onClick = { + when { + url.value.isBlank() || username.value.isBlank() || password.value.isBlank() -> + localError.value = "All fields are required" + else -> { + localError.value = null + onLogin(url.value, username.value, password.value) + } + } + }, + ), ) { if (busy.value) { CircularProgressIndicator(Modifier.width(20.dp)) diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/FocusKeys.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/FocusKeys.kt new file mode 100644 index 0000000..b7adec0 --- /dev/null +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/FocusKeys.kt @@ -0,0 +1,24 @@ +package net.jeena.jtubetv.ui.screens.list + +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.runtime.remember +import androidx.compose.ui.Modifier +import androidx.compose.ui.composed +import androidx.compose.ui.input.key.onPreviewKeyEvent + +/** + * Compose `clickable` handles Enter/Space but NOT the TV's DPAD_CENTER; whether + * CENTER works depends on each device's input translation (works on some emulators, + * not on others — see the API-34 ATD case). This modifier consumes CENTER *first* + * (preview/tunneling) so the click fires exactly once, on every device. + */ +fun Modifier.dpadCenterActivatable(onClick: () -> Unit): Modifier = composed { + onPreviewKeyEvent { ke -> + if (ke.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN && + ke.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_DPAD_CENTER + ) { + onClick() + true + } else false + } +} \ No newline at end of file diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt index 3d4a240..5d4e1a9 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/VideoCard.kt @@ -69,6 +69,7 @@ fun VideoCard( onClick = onClick, modifier = modifier .padding(6.dp) + .dpadCenterActivatable(onClick) .onFocusChanged { cardFocused = it.isFocused if (it.isFocused) onFocused?.invoke() From 28f0751e4855299ed618d3bd679b7fc0db1c7e5e Mon Sep 17 00:00:00 2001 From: Jeena Date: Sun, 11 Oct 2026 07:47:06 +0000 Subject: [PATCH 18/23] =?UTF-8?q?scripts:=20emulator-seed.sh=20=E2=80=94?= =?UTF-8?q?=20seed=20a=20fresh=20emulated=20device=20with=20the=20test=20a?= =?UTF-8?q?ccount?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scripts/emulator-seed.sh | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100755 scripts/emulator-seed.sh diff --git a/scripts/emulator-seed.sh b/scripts/emulator-seed.sh new file mode 100755 index 0000000..7a4bd91 --- /dev/null +++ b/scripts/emulator-seed.sh @@ -0,0 +1,32 @@ +#!/usr/bin/env bash +# +# emulator-seed.sh — (container-side) log the freshly booted emulated device into the +# JTube test account via the debug-only seed intent. Usage: +# ./emulator-seed.sh emulator-5568 [serial] +set -euo pipefail +SERIAL="${1:-emulator-5568}" +ADB="${ANDROID_HOME:-$HOME/Android/Sdk}/platform-tools/adb" +[ -x "$ADB" ] && ADB="$ADB" || ADB="$(which adb)" + +# credentials from the encrypted store +eval "$(sops -d --output-type dotenv "$HOME/.agents/secrets/jtube.env" | sed 's/^/export /')" + +# kill + cold start so onCreate (the debug seeder) actually runs +"$ADB" -s "$SERIAL" shell am force-stop net.jeena.jtubetv 2>/dev/null || true +"$ADB" -s "$SERIAL" install -r "$HOME/Projects/jtube-tv/app/build/outputs/apk/debug/app-debug.apk" 2>&1 | tail -1 + +"$ADB" -s "$SERIAL" shell am start -a android.intent.action.MAIN \ + -n net.jeena.jtubetv/.MainActivity \ + --es jtube_url "$JTUBE_URL" \ + --es jtube_user "$JTUBE_USER" \ + --es jtube_pass "$JTUBE_PASS" + +sleep 12 +"$ADB" -s "$SERIAL" shell uiautomator dump /sdcard/ui.xml > /dev/null 2>&1 +"$ADB" -s "$SERIAL" shell cat /sdcard/ui.xml | python3 -c " +import sys, re +xml = sys.stdin.read() +texts = [m.group(1) for m in re.finditer(r'text=\"([^\"]{2,40})\"', xml)] +foc = re.search(r']*focused=\"true\"[^>]*>', xml) +print('logged in as:', texts[0] if texts else '?') +print('rows/screens:', texts[1:8])" \ No newline at end of file From 75847306464a23fe58b1909b3d73525f88353cbd Mon Sep 17 00:00:00 2001 From: Jeena Date: Mon, 12 Oct 2026 00:26:47 +0000 Subject: [PATCH 19/23] channels: Show a banner and harden D-pad activation Channel pages now load the channel record itself and use the newest video's thumbnail as a banner fallback, so channels never render without a header image. Focus cards in re-sorting rows only hand out initial focus once per screen visit so streaming stats can't steal focus mid-navigation. D-pad activation now also accepts ENTER/NUMPAD_ENTER/SPACE, matching how the Compose platform fires clickable cards; consuming in the preview phase keeps OK from double-activating. --- .../jeena/jtubetv/data/PeerTubeRepository.kt | 13 ++++++++-- .../java/net/jeena/jtubetv/data/api/Dtos.kt | 2 ++ .../net/jeena/jtubetv/data/api/PeerTubeApi.kt | 5 ++++ .../jtubetv/ui/list/VideoListViewModel.kt | 20 ++++++++++++++++ .../jtubetv/ui/screens/ChannelsScreen.kt | 24 ++++++++++++++----- .../jtubetv/ui/screens/list/FocusKeys.kt | 15 ++++++++---- 6 files changed, 66 insertions(+), 13 deletions(-) diff --git a/app/src/main/java/net/jeena/jtubetv/data/PeerTubeRepository.kt b/app/src/main/java/net/jeena/jtubetv/data/PeerTubeRepository.kt index 5079c0d..8922c39 100644 --- a/app/src/main/java/net/jeena/jtubetv/data/PeerTubeRepository.kt +++ b/app/src/main/java/net/jeena/jtubetv/data/PeerTubeRepository.kt @@ -125,14 +125,20 @@ class PeerTubeRepository( var videos = 0L var plays = 0L var total: Long? = null + var latestThumb: String? = null repeat(maxPages) { val page = network.api.channelVideos(handle, start, 25) - if (total == null) total = page.total + if (total == null) { + total = page.total + latestThumb = page.data.firstOrNull()?.thumbnailPath?.let { path -> + if (path.startsWith("http")) path else baseUrl + "/" + path.trimStart('/') + } + } plays += page.data.sumOf { it.views } start += page.data.size videos = total ?: videos } - net.jeena.jtubetv.data.api.ChannelStats(videos, plays) + net.jeena.jtubetv.data.api.ChannelStats(videos, plays, latestThumb) } private fun unauthenticatedApiFor(base: String): PeerTubeApi = @@ -178,6 +184,9 @@ class PeerTubeRepository( response.data to response.total } + suspend fun videoChannel(handle: String): Result = + runCatching { network.api.videoChannel(handle) } + suspend fun accountChannels(username: String): Result> = runCatching { val response: VideoChannelListResponse = network.api.accountChannels(username) diff --git a/app/src/main/java/net/jeena/jtubetv/data/api/Dtos.kt b/app/src/main/java/net/jeena/jtubetv/data/api/Dtos.kt index b807ebc..91d3777 100644 --- a/app/src/main/java/net/jeena/jtubetv/data/api/Dtos.kt +++ b/app/src/main/java/net/jeena/jtubetv/data/api/Dtos.kt @@ -158,6 +158,8 @@ data class InstanceInfoDto( data class ChannelStats( val videos: Long, val plays: Long, + /** Thumbnail of the newest video — banner fallback for channels without one. */ + val latestThumbUrl: String? = null, ) @Serializable diff --git a/app/src/main/java/net/jeena/jtubetv/data/api/PeerTubeApi.kt b/app/src/main/java/net/jeena/jtubetv/data/api/PeerTubeApi.kt index 4c505ce..1c5940a 100644 --- a/app/src/main/java/net/jeena/jtubetv/data/api/PeerTubeApi.kt +++ b/app/src/main/java/net/jeena/jtubetv/data/api/PeerTubeApi.kt @@ -83,6 +83,11 @@ interface PeerTubeApi { @Path("account") account: String, ): VideoChannelListResponse + @GET("video-channels/{handle}") + suspend fun videoChannel( + @Path("handle") handle: String, + ): VideoChannelDto + @GET("video-channels/{handle}/videos") suspend fun channelVideos( @Path("handle") handle: String, diff --git a/app/src/main/java/net/jeena/jtubetv/ui/list/VideoListViewModel.kt b/app/src/main/java/net/jeena/jtubetv/ui/list/VideoListViewModel.kt index 33bf4aa..a723e8e 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/list/VideoListViewModel.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/list/VideoListViewModel.kt @@ -1,8 +1,13 @@ package net.jeena.jtubetv.ui.list +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.viewModelScope import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.launch import net.jeena.jtubetv.AppGraph import net.jeena.jtubetv.data.PeerTubeRepository @@ -30,6 +35,12 @@ class VideoListViewModel( val query = MutableStateFlow("") private var activeSearch: String? = null + /** For channel pages: the channel itself (banner + display name) as page header. */ + var channelHeader by androidx.compose.runtime.mutableStateOf( + null, + ) + private set + override fun onChunkLoaded(chunk: List) { ImagePrefetcher.videoThumbnails( chunk.mapNotNull { @@ -60,6 +71,15 @@ class VideoListViewModel( } } + fun loadChannelHeader(repository: PeerTubeRepository) { + val s = source + if (s is ListSource.Channel) { + viewModelScope.launch { + channelHeader = repository.videoChannel(s.handle).getOrNull() + } + } + } + fun triggerSearch(raw: String) { query.value = raw activeSearch = raw.trim().ifBlank { null } diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt index 8bcf936..a97a119 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/ChannelsScreen.kt @@ -291,6 +291,10 @@ fun ChannelsScreen( } } else -> { + // hand the initial focus to the first row exactly ONCE per screen visit: + // as stats stream in the rows re-sort, and re-focusing their first card + // would steal focus mid-navigation (user: "up jumps to the first row"). + val focusHandedOut = remember { mutableStateOf(false) } LazyColumn(Modifier.fillMaxSize()) { viewModel.userRows.forEach { group -> item(key = "hdr-" + group.ownerName) { @@ -304,7 +308,9 @@ fun ChannelsScreen( group.channels, onOpenChannel, onOpenDrawer, - firstFocused = group == viewModel.userRows.firstOrNull(), + focused = !focusHandedOut.value && + group == viewModel.userRows.firstOrNull(), + onFocused = { focusHandedOut.value = true }, stats = { viewModel.stats[it.name + "@" + it.host] }, platformName = { viewModel.platformNames[it.host ?: ""] }, ) @@ -355,7 +361,8 @@ private fun ChannelRow( channels: List, onOpenChannel: (String) -> Unit, onOpenDrawer: () -> Unit = {}, - firstFocused: Boolean, + focused: Boolean, + onFocused: () -> Unit = {}, stats: (VideoChannelDto) -> net.jeena.jtubetv.data.api.ChannelStats?, platformName: (VideoChannelDto) -> String?, ) { @@ -373,9 +380,11 @@ private fun ChannelRow( if (notFullyVisible) rowState.animateScrollToItem(focusedIndex) } } - if (firstFocused) { + if (focused) { LaunchedEffect(channels.isNotEmpty()) { - if (channels.isNotEmpty()) runCatching { focusRequesters[0]?.requestFocus() } + if (channels.isNotEmpty()) { + if (runCatching { focusRequesters[0]?.requestFocus() }.isSuccess) onFocused() + } } } @@ -448,13 +457,16 @@ fun ChannelCard( .aspectRatio(16f / 9f) .background(Color(0xFF222222)), ) { + // banner, or the newest video's thumbnail for bannerless channels val banner = channel.banners.maxByOrNull { it.width } - if (banner != null) { + val coverUrl = banner?.let { absoluteBanner(it) } + ?: stats?.latestThumbUrl + if (coverUrl != null) { AsyncImage( model = coil.request.ImageRequest.Builder( androidx.compose.ui.platform.LocalContext.current, ) - .data(absoluteBanner(banner)) + .data(coverUrl) .size(480, 270) // same key as prefetch .build(), contentDescription = channel.displayName, diff --git a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/FocusKeys.kt b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/FocusKeys.kt index b7adec0..7088eb4 100644 --- a/app/src/main/java/net/jeena/jtubetv/ui/screens/list/FocusKeys.kt +++ b/app/src/main/java/net/jeena/jtubetv/ui/screens/list/FocusKeys.kt @@ -14,11 +14,16 @@ import androidx.compose.ui.input.key.onPreviewKeyEvent */ fun Modifier.dpadCenterActivatable(onClick: () -> Unit): Modifier = composed { onPreviewKeyEvent { ke -> - if (ke.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN && - ke.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_DPAD_CENTER - ) { - onClick() - true + if (ke.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) { + val code = ke.nativeKeyEvent.keyCode + val activates = code == android.view.KeyEvent.KEYCODE_DPAD_CENTER || + code == android.view.KeyEvent.KEYCODE_ENTER || + code == android.view.KeyEvent.KEYCODE_NUMPAD_ENTER || + code == android.view.KeyEvent.KEYCODE_SPACE + if (activates) { + onClick() + true // consumed in preview -> the platform/card path never double-fires + } else false } else false } } \ No newline at end of file From 5a78849a9ee1a0527a96eb80de55c696046658f3 Mon Sep 17 00:00:00 2001 From: Jeena Date: Mon, 12 Oct 2026 00:26:47 +0000 Subject: [PATCH 20/23] ui: Use the JTube TV logo for the launcher icon and TV banner Replace the placeholder red play-square with the real logo (the orange TV from https://jeena.net/jtube-logo.svg) converted to vector drawables. The old placeholder still lives on in git history; the launcher now matches the website branding. --- app/src/main/res/drawable/app_banner.xml | 51 ++++++++++++++----- app/src/main/res/drawable/icon_foreground.xml | 39 ++++++++++++-- 2 files changed, 73 insertions(+), 17 deletions(-) diff --git a/app/src/main/res/drawable/app_banner.xml b/app/src/main/res/drawable/app_banner.xml index 29ba394..5d78e70 100644 --- a/app/src/main/res/drawable/app_banner.xml +++ b/app/src/main/res/drawable/app_banner.xml @@ -7,16 +7,43 @@ - - - - + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/icon_foreground.xml b/app/src/main/res/drawable/icon_foreground.xml index 74dc88e..28febb9 100644 --- a/app/src/main/res/drawable/icon_foreground.xml +++ b/app/src/main/res/drawable/icon_foreground.xml @@ -5,13 +5,42 @@ android:viewportWidth="108" android:viewportHeight="108"> + android:scaleX="0.6" + android:scaleY="0.6" + android:translateX="27.5" + android:translateY="26.5"> + android:fillColor="#F2690D" + android:pathData="M60.2698 33.1237 c 0.2377 5.131 -7.2718 9.1005 -16.0739 9.6703 -8.8564 0.5733 -16.5815 -2.4078 -16.8896 -7.2214 -0.1502 -2.3457 1.4619 -4.9221 4.4079 -7.0758 2.9454 -2.1532 6.9675 -3.6913 11.2701 -4.1138 4.3242 -0.4245 8.5766 0.3156 11.9031 2.0468 3.3097 1.7224 5.2671 4.2043 5.3824 6.6939 z" /> + + android:pathData="M15.0279 42.3829 c 14.4103 -2.9379 34.4644 -4.7509 48.0973 -4.21 5.1043 0.2025 9.3683 4.8586 9.1618 9.7687 -0.2835 6.7398 -1.0404 18.8371 -1.477 25.8761 -0.3086 4.9748 -4.3214 9.3362 -8.8365 9.4034 -14.5318 0.2161 -28.9546 -0.025 -43.8451 0.6671 -4.5318 0.2106 -8.7268 -3.2379 -9.2264 -7.5956 C 7.993 68.3645 6.7849 60.7535 5.9079 52.9211 c -0.4974 -4.4414 3.7431 -9.442 9.1201 -10.5382 z" /> + + + + + + + + \ No newline at end of file From 89c1a13b8b77b76fad0c3b4fcd91d48b06c20fec Mon Sep 17 00:00:00 2001 From: Jeena Date: Mon, 12 Oct 2026 00:27:08 +0000 Subject: [PATCH 21/23] docs: Drop instance-specific storage-security notes The public repo must not document this instance's object-storage access-control posture; findings like that belong in private ops notes. The engineering guidance (never rely on URL obscurity, always request file tokens) stays. --- .gitignore | 4 +++- AGENTS.md | 7 ++++--- BACKLOG.md | 14 ++++++++------ 3 files changed, 15 insertions(+), 10 deletions(-) diff --git a/.gitignore b/.gitignore index f89a0ab..8685299 100644 --- a/.gitignore +++ b/.gitignore @@ -7,4 +7,6 @@ /app/build /captures .externalNativeBuild -.cxxreports/*-shots/ +.cxx +reports/*-shots/ +reports/*.md diff --git a/AGENTS.md b/AGENTS.md index 1e68716..bc283be 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,9 +69,10 @@ setup/login screen, `Ready` renders `HomeScreen`, which switches content on a whose media lives in a private object-storage bucket — pass the short-lived `POST /api/v1/videos/{shortUuid}/token` token as `?videoFileToken=` on those URLs (response shape: `{ files: { token, expires } }`; verified live). - - tube.jeena.net itself streams non-public media from a **publicly readable R2 - bucket** (`pub-….r2.dev`): no auth is enforced there today, but do not rely on - that — always request the file token for non-public videos. + - Some instances stream non-public media from object-storage hosts with only + URL-based access control — never rely on that; always request and use the + file token for non-public videos. (Instance-specific findings stay out of + the public repo and live in the private ops notes/agent-local instructions.) ## Conventions diff --git a/BACKLOG.md b/BACKLOG.md index 947bade..9019380 100644 --- a/BACKLOG.md +++ b/BACKLOG.md @@ -38,12 +38,14 @@ focus colors, always-focusable Sign in with inline validation. Deferred from rev - Logout / switch account: sign-out entry exists; add switch-account (re-login screen without losing scroll state). - Release build: enable `minifyEnabled` + R8 rules, decide signing/versioning. -- Thumbnails of private/internal videos may 404 — verified on tube.jeena.net: - instance thumbnail paths are publicly readable (HTTP 200 without auth); add a - fallback poster only if other instances behave differently. -- Security note for tube.jeena.net: object-storage (R2) media for private test - videos is publicly readable without token ("private" only via URL obscurity). - Flag to the instance admin; the app must not rely on this laxness. +- Thumbnails of private/internal videos may 404 — on some instances thumbnail + paths are publicly readable while on others they need auth; add a fallback + poster only if needed. +- Security note (verified live against tube.jeena.net): some instances serve + non-public media / thumbnails from object storage with only URL-based access + control. The app must not rely on that laxness; always send auth headers + / file tokens for non-public media. (Detail intentionally omitted from the + public repo — report instance-specific findings privately.) - Verify `searchTarget=local` channel search behaves well for instances without federation; consider `search/video-channels` endpoint as an alternative. - Release build: enable `minifyEnabled` + R8 rules, decide on signing, versioning scheme. From 0cebe3b7100cc3005f9504a4d8f0b31ca8c2fc84 Mon Sep 17 00:00:00 2001 From: Jeena Date: Mon, 12 Oct 2026 00:33:42 +0000 Subject: [PATCH 22/23] docs: Remove the test account name from the public repo The account name identifies a real, seeded account on the instance; the public source doesn't need it to make sense. Credentials were never in the repo and still live only in sops. --- BACKLOG.md | 2 +- TESTS.md | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/BACKLOG.md b/BACKLOG.md index 9019380..f9e6182 100644 --- a/BACKLOG.md +++ b/BACKLOG.md @@ -51,7 +51,7 @@ focus colors, always-focusable Sign in with inline validation. Deferred from rev - Release build: enable `minifyEnabled` + R8 rules, decide on signing, versioning scheme. - Verify `searchTarget=local` channel search behaves well for instances without federation; consider `search/video-channels` endpoint as an alternative. -- (Verified 2026-10-10 via the test account account) history subscriptions + watching endpoints +- (Verified 2026-10-10 via the test account) history subscriptions + watching endpoints behave as documented; upload seeding uses **flat multipart form fields** on `/api/v1/videos/upload` (legacy), not a metadata JSON part — only relevant for seeding test data, the app itself doesn't upload. diff --git a/TESTS.md b/TESTS.md index 46dbb1b..4f5dd87 100644 --- a/TESTS.md +++ b/TESTS.md @@ -13,10 +13,11 @@ when everything passes (playback, focus and UI states are untestable by script). ## Test environment / prerequisites - Instance: any PeerTube (baseline: , v8.3.1, media on R2 object storage). -- Account: `the test account` (sops: `~/.agents/secrets/jtube.env`). Credentials resolved +- Account: a dedicated test account (credentials via sops from `~/.agents/secrets/jtube.env`). + Credentials resolved at login; **do not store the password in the device during tests** — it's typed once on the setup screen (which is exactly feature 0). -- Seeded content (tagged `jtube-tv-test`, channel `the test channel`): +- Seeded content (tagged `jtube-tv-test`, in the test account's channel): - `JTube TV Test 1 - Sintel Teaser` **Private** (~52 s) - `JTube TV Test 2 - Caminandes Llamigos` **Private** (~2:30) - `JTube TV Test 3 - Cosmos Laundromat` **Private** (~50 s) @@ -57,7 +58,7 @@ APK version + device. - [ ] T9 Long video title truncates (2 lines max) without breaking the row layout; long channel names truncate. ### 2 — Channels -- [ ] T10 "Channels" lists account's own channels (`the test channel`), avatar when present, video count. +- [ ] T10 "Channels" lists the account's own channels, avatar when present, video count. - [ ] T11 Click channel → that channel's videos list; open and play one; back returns to the channel's list (not the channels screen lost state). - [ ] T12 Remote channel via direct handle is out of MVP scope, but local-channel search (when implemented) must be re-tested: `searchTarget=local` ignores federated results. From 669c4af359b2f48d043394fc2e7d84ce71f1e1e4 Mon Sep 17 00:00:00 2001 From: Jeena Date: Mon, 12 Oct 2026 00:41:17 +0000 Subject: [PATCH 23/23] license: Adopt GPL-3.0-or-later Decide on the license before the source is shared publicly: GPL v3 keeps forks and improvements of this app free software too. --- LICENSE | 674 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 3 +- 2 files changed, 676 insertions(+), 1 deletion(-) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index 9ee3a32..92e06f2 100644 --- a/README.md +++ b/README.md @@ -66,4 +66,5 @@ Single-module Android TV app (`app/`): ## License -Not decided yet — TBD before first public release. \ No newline at end of file +JTube TV is free software: [GPL-3.0-or-later](LICENSE) — see the +[fsf.org license page](https://www.gnu.org/licenses/) for details. \ No newline at end of file