youpipe: TV entry, D-pad browse and player UI
- Commit
8adaedc0694bef894f8107d57034b9d2a30fb28b- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-20 07:34 UTC (1 month ago)
- Parents
cd3519f
Diff
youpipe/build.gradle.kts
diff --git a/youpipe/build.gradle.kts b/youpipe/build.gradle.ktsindex 1d39d9cd7d..41b9d3dc41 100644--- a/youpipe/build.gradle.kts+++ b/youpipe/build.gradle.kts@@ -1,5 +1,8 @@ plugins { id("common-conventions-app")+ // androidx.tv, so the TV entry is built on a design system that knows what a D-pad is+ // (the cast:tv precedent).+ id("common-conventions-tv") // Listing screenshots come from Compose previews (src/screenshotTest), not from an // instrumented test on a device. Same `:youpipe:metadata` task name either way. id("common-conventions-preview-metadata")@@ -10,6 +13,11 @@ launcherIcon { symbol = "play_arrow" } +// Google TV hardware runs a 32-bit userspace: an arm64-only APK is rejected at install.+nativeAbis {+ armv7 = true+}+ androidComponents { onVariants { variant -> variant.sources.jniLibs?.addStaticSourceDirectory(@@ -19,7 +27,8 @@ androidComponents { } // YouTube (InnerTube) extractor — a Rust port of PipePipeExtractor. See youpipe/src/main/rust/.-rustNativeLib("youpipe_extractor", "youpipe")+// extraAbis: the .so must also load on 32-bit Google TV.+rustNativeLib("youpipe_extractor", "youpipe", extraAbis = listOf("armeabi-v7a")) android { defaultConfig {
youpipe/src/main/AndroidManifest.xml
diff --git a/youpipe/src/main/AndroidManifest.xml b/youpipe/src/main/AndroidManifest.xmlindex 29f62084ee..e58d300081 100644--- a/youpipe/src/main/AndroidManifest.xml+++ b/youpipe/src/main/AndroidManifest.xml@@ -17,8 +17,18 @@ <package android:name="com.vayunmathur.cast" /> </queries> + <!-- Leanback is supported, not required: one APK serves phones and TVs. Without these,+ a TV launcher never lists the app; with required="true" phones would lose it. -->+ <uses-feature+ android:name="android.software.leanback"+ android:required="false" />+ <uses-feature+ android:name="android.hardware.touchscreen"+ android:required="false" />+ <application android:allowBackup="true"+ android:banner="@drawable/tv_banner" android:dataExtractionRules="@xml/data_extraction_rules" android:icon="@mipmap/ic_launcher" android:label="@string/app_name"@@ -59,6 +69,25 @@ </intent-filter> </activity> + <!--+ TV entry: a separate activity carrying only LEANBACK_LAUNCHER, so the TV row+ opens the D-pad UI instead of the phone pager. Separate activity (not a second+ filter on MainActivity): split filters on one activity build separate resolve+ entries that confuse launcher resolution (the tvlauncher HOME lesson).+ -->+ <activity+ android:name=".tv.TvMainActivity"+ android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"+ android:exported="true"+ android:launchMode="singleTask"+ android:screenOrientation="landscape"+ android:theme="@style/Theme.General">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LEANBACK_LAUNCHER" />+ </intent-filter>+ </activity>+ <activity-alias android:name=".ShareWatchLater" android:targetActivity=".MainActivity"
youpipe/src/main/java/com/vayunmathur/youpipe/platform/CastPlayback.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/platform/CastPlayback.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/platform/CastPlayback.ktindex 255fd93af7..22d838533d 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/platform/CastPlayback.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/platform/CastPlayback.kt@@ -142,6 +142,14 @@ object CastPlayback { */ private var player: Player? = null + /**+ * The currently attached player, for the TV remote map.+ *+ * Read-only: attach/detach stay the only writers, with their identity guard intact.+ * The phone never reads this — only `tv/TvDpadInput` drives the local controller.+ */+ val attachedPlayer: Player? get() = player+ /** * The phone's own media volume, which is the level both ends share. *
youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvAddToPlaylist.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvAddToPlaylist.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvAddToPlaylist.ktnew file mode 100644index 0000000000..35e0214ff3--- /dev/null+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvAddToPlaylist.kt@@ -0,0 +1,183 @@+package com.vayunmathur.youpipe.tv++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import androidx.tv.material3.Button+import androidx.tv.material3.Checkbox+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Surface+import androidx.tv.material3.Text+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.youpipe.R+import com.vayunmathur.youpipe.ui.VideoInfo+import com.vayunmathur.youpipe.util.YouPipeViewModel++/**+ * TV add-to-playlist: staged membership checkboxes as a focusable list.+ *+ * The phone stages membership in an `AddToListDialog` and applies on OK. Same staging here —+ * each playlist row is a focusable `Surface` with a checkbox (CENTER toggles membership), and+ * the OK/Cancel rows at the bottom apply or drop the stage. BACK dismisses without applying,+ * via the overlay-dismiss-first rule. The "new playlist" field only opens its text entry on+ * explicit focus + IME action, never autofocused.+ */+@Composable+fun TvAddToPlaylistPage(+ backStack: NavBackStack<TvRoute>,+ ypvm: YouPipeViewModel,+ videoID: Long,+ includeWatchLater: Boolean = true,+) {+ val allPlaylists by ypvm.playlists.collectAsStateWithLifecycle()+ val playlists = if (includeWatchLater) allPlaylists else allPlaylists.filter { !it.mandatory }+ val allItems by ypvm.allPlaylistItems.collectAsStateWithLifecycle()+ val videoState by ypvm.videoState.collectAsStateWithLifecycle()+ val closeFocus = remember { FocusRequester() }++ val data = videoState.data+ if (data == null) {+ // Same fallback as the phone dialog: the video state went away (rotation, process+ // death) so there is nothing to add — back out instead of staging against nothing.+ TvInitialFocus(closeFocus)+ Column(+ Modifier+ .fillMaxSize()+ .padding(48.dp),+ verticalArrangement = Arrangement.spacedBy(16.dp),+ ) {+ Text(text = stringResource(R.string.add_to_playlist), style = MaterialTheme.typography.headlineSmall)+ Button(onClick = { backStack.pop() }, modifier = Modifier.focusRequester(closeFocus)) {+ Text(stringResource(R.string.action_close))+ }+ }+ return+ }++ val video = VideoInfo(+ data.title, videoID, data.duration, data.views, data.uploadDate, data.thumbnailURL, data.author,+ )+ val membership = remember(allItems, videoID) {+ allItems.filter { it.videoItem.videoID == videoID }.map { it.playlistId }.toSet()+ }+ var staged by remember(membership) { mutableStateOf(membership) }+ var newName by remember { mutableStateOf("") }+ var nameOpen by remember { mutableStateOf(false) }+ val watchLaterLabel = stringResource(R.string.playlist_watch_later)++ fun confirm() {+ val selectedIds = staged+ playlists.forEach { playlist ->+ val wasMember = playlist.id in membership+ val nowMember = playlist.id in selectedIds+ if (nowMember && !wasMember) {+ ypvm.playlistOps.addVideoToPlaylist(playlist.id, video)+ } else if (!nowMember && wasMember) {+ allItems.firstOrNull {+ it.playlistId == playlist.id && it.videoItem.videoID == videoID+ }?.let { ypvm.playlistOps.removeFromPlaylist(it) }+ }+ }+ backStack.pop()+ }++ TvInitialFocus(closeFocus)+ Column(+ Modifier+ .fillMaxSize()+ .padding(horizontal = 48.dp, vertical = 32.dp),+ ) {+ Text(text = stringResource(R.string.add_to_playlist), style = MaterialTheme.typography.headlineSmall)+ LazyColumn(+ modifier = Modifier.weight(1f).padding(top = 16.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ items(playlists, key = { it.id }) { playlist ->+ val checked = playlist.id in staged+ Surface(+ onClick = {+ staged = if (checked) staged - playlist.id else staged + playlist.id+ },+ modifier = Modifier.fillMaxWidth(),+ ) {+ Row(+ Modifier.padding(16.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Checkbox(checked = checked, onCheckedChange = null)+ Text(+ text = if (playlist.mandatory) watchLaterLabel else playlist.name,+ style = MaterialTheme.typography.titleMedium,+ modifier = Modifier.padding(start = 12.dp),+ )+ }+ }+ }+ item(key = "new-playlist") {+ Surface(+ onClick = { nameOpen = true },+ modifier = Modifier.fillMaxWidth(),+ ) {+ Column(Modifier.padding(16.dp)) {+ Text(text = stringResource(R.string.new_playlist), style = MaterialTheme.typography.titleMedium)+ if (nameOpen) {+ androidx.compose.foundation.text.BasicTextField(+ value = newName,+ onValueChange = { newName = it },+ modifier = Modifier+ .fillMaxWidth()+ .padding(top = 8.dp),+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),+ textStyle = MaterialTheme.typography.titleMedium.copy(+ color = MaterialTheme.colorScheme.onSurface,+ ),+ )+ val canCreate = newName.isNotBlank() &&+ allPlaylists.none { it.name == newName.trim() }+ Button(+ onClick = {+ ypvm.playlistOps.createPlaylistAndAddVideo(newName.trim(), video)+ backStack.pop()+ },+ enabled = canCreate,+ modifier = Modifier.padding(top = 8.dp),+ ) {+ Text(stringResource(R.string.new_playlist))+ }+ }+ }+ }+ }+ }+ Row(+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ modifier = Modifier.padding(top = 16.dp),+ ) {+ Button(onClick = ::confirm) {+ Text(stringResource(android.R.string.ok))+ }+ Button(onClick = { backStack.pop() }, modifier = Modifier.focusRequester(closeFocus)) {+ Text(stringResource(android.R.string.cancel))+ }+ }+ }+}
youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvChannel.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvChannel.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvChannel.ktnew file mode 100644index 0000000000..a2c88040f4--- /dev/null+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvChannel.kt@@ -0,0 +1,156 @@+package com.vayunmathur.youpipe.tv++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.grid.GridCells+import androidx.compose.foundation.lazy.grid.items+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid+import androidx.compose.foundation.lazy.grid.rememberLazyGridState+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.remember+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.tv.material3.Button+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.vayunmathur.library.image.compose.AsyncImage+import com.vayunmathur.library.image.ImageRequest+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.youpipe.data.Subscription+import com.vayunmathur.youpipe.R+import com.vayunmathur.youpipe.ui.VideoItem+import com.vayunmathur.youpipe.ui.videoRowState+import com.vayunmathur.youpipe.util.decodeHtml+import com.vayunmathur.youpipe.util.YouPipeViewModel++/**+ * TV channel page: identity header + subscribe toggle + focusable video grid.+ *+ * Mirrors the phone `ChannelPage` binding (`loadChannel`, subscriptions for membership).+ * The header and subscribe button are stacked focus targets — not a scrolling collapse —+ * because a D-pad needs a stable place to land UP from the grid.+ */+@Composable+fun TvChannelPage(+ backStack: NavBackStack<TvRoute>,+ ypvm: YouPipeViewModel,+ channelID: String,+) {+ val channelState by ypvm.channelState.collectAsState()+ val videos = channelState.videos+ val channelInfo = channelState.info+ val subscriptions by ypvm.subscriptions.collectAsState()+ val history by ypvm.historyVideos.collectAsState()+ val deArrowEnabled by ypvm.deArrowEnabled.collectAsState()+ val deArrowCache by ypvm.deArrowCache.collectAsState()+ val progressById = remember(history) { history.associate { it.id to it.progress } }+ val context = LocalContext.current+ val headerFocus = remember { FocusRequester() }++ LaunchedEffect(channelID) {+ ypvm.loadChannel(channelID)+ }++ val rows = remember(videos, deArrowEnabled, deArrowCache, progressById) {+ videos.map { video ->+ val deArrow = if (deArrowEnabled) deArrowCache[video.videoID] else null+ val watched = progressById[video.videoID] ?: 0L+ videoRowState(+ context = context,+ videoInfo = video,+ showAuthor = false,+ percentWatched = if (video.duration > 0) {+ (watched.toDouble() / video.duration).toFloat()+ } else {+ 0f+ },+ deArrowTitle = deArrow?.title,+ deArrowThumbnailURL = deArrow?.thumbnailUrl,+ )+ }+ }++ TvInitialFocus(headerFocus)+ Column(+ Modifier+ .fillMaxSize()+ .padding(horizontal = 48.dp, vertical = 32.dp),+ ) {+ channelInfo?.let { info ->+ androidx.compose.foundation.layout.Row(+ verticalAlignment = androidx.compose.ui.Alignment.CenterVertically,+ ) {+ if (info.avatar.isNotEmpty()) {+ AsyncImage(+ model = ImageRequest.Builder(context)+ .data(info.avatar)+ .memoryCacheKey("channel-avatar-${info.channelID}")+ .build(),+ contentDescription = null,+ modifier = Modifier.padding(end = 16.dp),+ )+ }+ Column(Modifier.weight(1f)) {+ Text(text = info.name.decodeHtml(), style = MaterialTheme.typography.headlineSmall)+ Text(+ text = stringResource(+ R.string.subscribers_count,+ com.vayunmathur.youpipe.ui.countString(context, info.subscribers),+ ),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ }+ val existing = subscriptions.firstOrNull { it.channelID == info.channelID }+ Button(+ onClick = {+ if (existing == null) {+ ypvm.upsertSubscription(+ Subscription(name = info.name, channelID = info.channelID, avatarURL = info.avatar),+ )+ } else {+ ypvm.deleteSubscription(existing)+ }+ },+ modifier = Modifier+ .fillMaxWidth()+ .padding(vertical = 12.dp)+ .focusRequester(headerFocus),+ ) {+ Text(+ if (existing == null) {+ stringResource(R.string.action_subscribe)+ } else {+ stringResource(R.string.action_unsubscribe)+ },+ )+ }+ }+ val gridState = rememberLazyGridState()+ LazyVerticalGrid(+ columns = GridCells.Fixed(3),+ state = gridState,+ modifier = Modifier.fillMaxSize(),+ verticalArrangement = Arrangement.spacedBy(16.dp),+ horizontalArrangement = Arrangement.spacedBy(16.dp),+ ) {+ items(rows, key = { it.videoID }) { row ->+ TvVideoCard(+ row = row,+ onOpen = { backStack.add(TvRoute.Video(row.videoID)) },+ )+ }+ }+ }+}
youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvCreateCategory.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvCreateCategory.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvCreateCategory.ktnew file mode 100644index 0000000000..daee3b1cd3--- /dev/null+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvCreateCategory.kt@@ -0,0 +1,153 @@+package com.vayunmathur.youpipe.tv++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.unit.dp+import androidx.tv.material3.Button+import androidx.tv.material3.Checkbox+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Surface+import androidx.tv.material3.Text+import com.vayunmathur.library.ui.R as UiR+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.youpipe.R+import com.vayunmathur.youpipe.util.decodeHtml+import com.vayunmathur.youpipe.util.YouPipeViewModel+import kotlinx.coroutines.launch++/**+ * TV create/update subscription group: name field + focusable member checklist.+ *+ * Same validation as the phone dialog (non-blank name, non-empty selection, no duplicate on+ * create). Each subscription row is a focusable `Surface` with a checkbox; the confirm row+ * applies `replaceCategory` and pops. BACK dismisses without applying.+ */+@Composable+fun TvCreateCategoryPage(+ backStack: NavBackStack<TvRoute>,+ ypvm: YouPipeViewModel,+ id: String?,+) {+ val subscriptions by ypvm.subscriptions.collectAsState()+ val categories by ypvm.subscriptionCategories.collectAsState()+ val categoryNames = categories.map { it.category }+ var categoryName by remember { mutableStateOf(id ?: "") }+ val subscriptionsAlreadyInCategory by remember(categoryName) {+ ypvm.subscriptionsInCategory(categoryName)+ }.collectAsState(initial = emptyList())+ var selectedSubscriptions by remember(subscriptionsAlreadyInCategory) {+ mutableStateOf(subscriptionsAlreadyInCategory)+ }+ val scope = rememberCoroutineScope()+ val confirmFocus = remember { FocusRequester() }++ val canConfirm = categoryName.isNotBlank() && selectedSubscriptions.isNotEmpty() &&+ (id != null || categoryName !in categoryNames)++ TvInitialFocus(confirmFocus)+ Column(+ Modifier+ .fillMaxSize()+ .padding(horizontal = 48.dp, vertical = 32.dp),+ ) {+ Text(+ text = if (id == null) {+ stringResource(R.string.title_create_subscription_category)+ } else {+ stringResource(R.string.title_update_subscription_category)+ },+ style = MaterialTheme.typography.headlineSmall,+ )+ androidx.compose.foundation.text.BasicTextField(+ value = categoryName,+ onValueChange = { categoryName = it },+ modifier = Modifier+ .fillMaxWidth()+ .padding(vertical = 16.dp),+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),+ textStyle = MaterialTheme.typography.titleMedium.copy(+ color = MaterialTheme.colorScheme.onSurface,+ ),+ )+ Text(+ text = stringResource(R.string.label_select_subscriptions),+ style = MaterialTheme.typography.titleMedium,+ )+ LazyColumn(+ modifier = Modifier.weight(1f).padding(top = 8.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ items(subscriptions, key = { it.id }) { subscription ->+ val checked = subscription in selectedSubscriptions+ Surface(+ onClick = {+ selectedSubscriptions = if (checked) {+ selectedSubscriptions - subscription+ } else {+ selectedSubscriptions + subscription+ }+ },+ modifier = Modifier.fillMaxWidth(),+ ) {+ Row(+ Modifier.padding(16.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Checkbox(checked = checked, onCheckedChange = null)+ Text(+ text = subscription.name.decodeHtml(),+ style = MaterialTheme.typography.titleMedium,+ modifier = Modifier.padding(start = 12.dp),+ )+ }+ }+ }+ }+ Row(+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ modifier = Modifier.padding(top = 16.dp),+ ) {+ Button(+ onClick = {+ scope.launch {+ ypvm.replaceCategory(id, categoryName, selectedSubscriptions.map { it.id })+ backStack.pop()+ }+ },+ enabled = canConfirm,+ modifier = Modifier.focusRequester(confirmFocus),+ ) {+ Text(+ if (id == null) {+ stringResource(UiR.string.create)+ } else {+ stringResource(R.string.action_update)+ },+ )+ }+ Button(onClick = { backStack.pop() }) {+ Text(stringResource(android.R.string.cancel))+ }+ }+ }+}
youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvCreatePlaylist.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvCreatePlaylist.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvCreatePlaylist.ktnew file mode 100644index 0000000000..62e85fa122--- /dev/null+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvCreatePlaylist.kt@@ -0,0 +1,79 @@+package com.vayunmathur.youpipe.tv++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.text.BasicTextField+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import androidx.tv.material3.Button+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.youpipe.R+import com.vayunmathur.youpipe.util.YouPipeViewModel++/**+ * TV create-playlist: name field (explicit IME only) + focused create row.+ *+ * Mirrors the phone `CreatePlaylist` validation: non-blank and no duplicate name.+ */+@Composable+fun TvCreatePlaylistPage(+ backStack: NavBackStack<TvRoute>,+ ypvm: YouPipeViewModel,+) {+ val allPlaylists by ypvm.playlists.collectAsStateWithLifecycle()+ var name by remember { mutableStateOf("") }+ val createFocus = remember { FocusRequester() }++ val canCreate = name.isNotBlank() && allPlaylists.none { it.name == name.trim() }++ TvInitialFocus(createFocus)+ Column(+ Modifier+ .fillMaxSize()+ .padding(horizontal = 48.dp, vertical = 32.dp),+ verticalArrangement = Arrangement.spacedBy(16.dp),+ ) {+ Text(text = stringResource(R.string.title_create_playlist), style = MaterialTheme.typography.headlineSmall)+ BasicTextField(+ value = name,+ onValueChange = { name = it },+ modifier = Modifier.fillMaxWidth(),+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),+ textStyle = MaterialTheme.typography.titleMedium.copy(+ color = MaterialTheme.colorScheme.onSurface,+ ),+ )+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ Button(+ onClick = {+ ypvm.playlistOps.createPlaylist(name.trim())+ backStack.pop()+ },+ enabled = canCreate,+ modifier = Modifier.focusRequester(createFocus),+ ) {+ Text(stringResource(R.string.new_playlist))+ }+ Button(onClick = { backStack.pop() }) {+ Text(stringResource(android.R.string.cancel))+ }+ }+ }+}
youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvDataSettings.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvDataSettings.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvDataSettings.ktnew file mode 100644index 0000000000..e1bf9ebef2--- /dev/null+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvDataSettings.kt@@ -0,0 +1,199 @@+package com.vayunmathur.youpipe.tv++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.tv.material3.Button+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.vayunmathur.library.ui.R as UiR+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.youpipe.R+import com.vayunmathur.youpipe.util.exportSubscriptions+import com.vayunmathur.youpipe.util.importNewPipe+import com.vayunmathur.youpipe.util.importYouTubeTakeout+import com.vayunmathur.youpipe.util.restoreSubscriptions+import com.vayunmathur.youpipe.util.YouPipeViewModel++/**++ * TV data settings: clear-history (with confirm step) + import/export rows.++ *++ * The phone launches SAF pickers via activity-result; on TV the same launchers fire — the++ * system file picker is itself D-pad traversable on Google TV. Import progress shows inline.++ */++@Composable++fun TvDataSettingsPage(++ backStack: NavBackStack<TvRoute>,++ ypvm: YouPipeViewModel,++) {++ val isLoading by ypvm.isImporting.collectAsState()++ val progress by ypvm.importProgress.collectAsState()++ var confirmClear by remember { mutableStateOf(false) }++ val firstFocus = remember { FocusRequester() }++++ val youtubeLauncher = androidx.activity.compose.rememberLauncherForActivityResult(++ androidx.activity.result.contract.ActivityResultContracts.GetContent(),++ ) { uri -> if (uri != null) ypvm.importYouTubeTakeout(uri) }++ val exportLauncher = androidx.activity.compose.rememberLauncherForActivityResult(++ androidx.activity.result.contract.ActivityResultContracts.CreateDocument("application/json"),++ ) { uri -> if (uri != null) ypvm.exportSubscriptions(uri) }++ val restoreLauncher = androidx.activity.compose.rememberLauncherForActivityResult(++ androidx.activity.result.contract.ActivityResultContracts.GetContent(),++ ) { uri -> if (uri != null) ypvm.restoreSubscriptions(uri) }++ val newPipeLauncher = androidx.activity.compose.rememberLauncherForActivityResult(++ androidx.activity.result.contract.ActivityResultContracts.GetContent(),++ ) { uri -> if (uri != null) ypvm.importNewPipe(uri) }++++ TvInitialFocus(firstFocus)++ Column(++ Modifier++ .fillMaxSize()++ .padding(horizontal = 48.dp, vertical = 32.dp)++ .verticalScroll(rememberScrollState()),++ verticalArrangement = Arrangement.spacedBy(8.dp),++ ) {++ Text(text = stringResource(R.string.settings_data), style = MaterialTheme.typography.headlineSmall)++ if (isLoading) {++ com.vayunmathur.library.ui.CircularProgressIndicator(progress = { progress })++ }++ Text(text = stringResource(R.string.title_history), style = MaterialTheme.typography.titleMedium)++ if (confirmClear) {++ Text(++ text = stringResource(R.string.are_you_sure_you_want_to_clear_all_watch),++ style = MaterialTheme.typography.bodyMedium,++ )++ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {++ Button(++ onClick = { ypvm.clearHistory(); confirmClear = false },++ modifier = Modifier.focusRequester(firstFocus),++ ) {++ Text(stringResource(UiR.string.clear))++ }++ Button(onClick = { confirmClear = false }) {++ Text(stringResource(UiR.string.cancel))++ }++ }++ } else {++ TvSettingsRow(++ title = stringResource(R.string.clear_history),++ onClick = { confirmClear = true },++ modifier = Modifier.focusRequester(firstFocus),++ )++ }++ Text(text = stringResource(R.string.label_backup_restore), style = MaterialTheme.typography.titleMedium)++ TvSettingsRow(++ title = stringResource(R.string.label_export_youpipe),++ onClick = { exportLauncher.launch("youpipe_subscriptions.json") },++ )++ TvSettingsRow(++ title = stringResource(R.string.label_restore_youpipe),++ onClick = { restoreLauncher.launch("application/json") },++ )++ TvSettingsRow(++ title = stringResource(R.string.label_import_newpipe),++ onClick = { newPipeLauncher.launch("application/json") },++ )++ TvSettingsRow(++ title = stringResource(R.string.label_import_youtube),++ onClick = { youtubeLauncher.launch("application/zip") },++ )++ }++}
youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvDownloads.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvDownloads.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvDownloads.ktnew file mode 100644index 0000000000..06c9d8b4c2--- /dev/null+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvDownloads.kt@@ -0,0 +1,207 @@+package com.vayunmathur.youpipe.tv++import androidx.activity.compose.BackHandler+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.tv.material3.Button+import androidx.tv.material3.Checkbox+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Surface+import androidx.tv.material3.Text+import com.vayunmathur.library.image.compose.AsyncImage+import com.vayunmathur.library.image.ImageRequest+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.youpipe.R+import com.vayunmathur.youpipe.ui.videoRowState+import com.vayunmathur.youpipe.util.DownloadManager+import com.vayunmathur.youpipe.util.YouPipeViewModel++/**+ * TV downloads: active downloads with cancel + completed downloads with D-pad multiselect.+ *+ * Mirrors the phone `DownloadedVideosPage` binding (activeDownloads + downloadedVideosByRecency)+ * as one focusable list — no expanded-width grid switch, a TV reports one window size.+ * Selection is checkboxes (same pattern as history); BACK clears first.+ */+@Composable+fun TvDownloadsPage(+ backStack: NavBackStack<TvRoute>,+ ypvm: YouPipeViewModel,+) {+ val downloadedVideos by ypvm.downloadedVideos.collectAsState()+ val activeDownloads by DownloadManager.activeDownloads.collectAsState()+ val downloads by ypvm.downloadedVideosByRecency.collectAsState()+ val context = LocalContext.current+ val firstFocus = remember { FocusRequester() }++ var selectedIds by remember { mutableStateOf(setOf<Long>()) }+ var selectedActiveIds by remember { mutableStateOf(setOf<Long>()) }+ val isSelectionMode = selectedIds.isNotEmpty() || selectedActiveIds.isNotEmpty()+ BackHandler(enabled = isSelectionMode) {+ selectedIds = emptySet()+ selectedActiveIds = emptySet()+ }++ TvInitialFocus(firstFocus)+ val listState = rememberLazyListState()+ LazyColumn(+ state = listState,+ modifier = Modifier+ .fillMaxSize()+ .padding(horizontal = 48.dp, vertical = 32.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ item(key = "downloads-title") {+ Text(+ text = if (isSelectionMode) {+ stringResource(R.string.selected_count, selectedIds.size + selectedActiveIds.size)+ } else {+ stringResource(R.string.title_downloads)+ },+ style = MaterialTheme.typography.headlineSmall,+ )+ }+ if (isSelectionMode) {+ item(key = "downloads-actions") {+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ Button(+ onClick = {+ selectedIds.forEach { id ->+ downloadedVideos.find { it.id == id }?.let { ypvm.deleteDownloadedVideo(it) }+ }+ selectedActiveIds.forEach { id ->+ DownloadManager.cancelDownload(context, id)+ }+ selectedIds = emptySet()+ selectedActiveIds = emptySet()+ },+ ) {+ IconDelete()+ }+ Button(+ onClick = {+ selectedIds = emptySet()+ selectedActiveIds = emptySet()+ },+ ) {+ IconClose()+ }+ }+ }+ }+ items(activeDownloads.toList(), key = { (videoID, _) -> "active-$videoID" }) { (videoID, status) ->+ val isSelected = videoID in selectedActiveIds+ Surface(+ onClick = {+ if (isSelectionMode) {+ selectedActiveIds = if (isSelected) selectedActiveIds - videoID else selectedActiveIds + videoID+ }+ },+ modifier = Modifier.fillMaxWidth(),+ ) {+ Row(Modifier.padding(16.dp), verticalAlignment = Alignment.CenterVertically) {+ if (isSelectionMode) {+ Checkbox(+ checked = isSelected,+ onCheckedChange = {+ selectedActiveIds = if (isSelected) {+ selectedActiveIds - videoID+ } else {+ selectedActiveIds + videoID+ }+ },+ )+ }+ if (status.videoInfo.thumbnailURL.isNotEmpty()) {+ AsyncImage(+ model = ImageRequest.Builder(context)+ .data(status.videoInfo.thumbnailURL)+ .memoryCacheKey("dl-thumb-$videoID")+ .build(),+ contentDescription = null,+ modifier = Modifier.padding(end = 12.dp),+ )+ }+ Column(Modifier.weight(1f)) {+ Text(text = status.videoInfo.name, style = MaterialTheme.typography.titleMedium)+ Text(+ text = "${(status.progress * 100).toInt()}%",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ CircularProgressIndicator(+ progress = { status.progress.toFloat() },+ modifier = Modifier.size(24.dp),+ )+ if (!isSelectionMode) {+ Button(onClick = { DownloadManager.cancelDownload(context, videoID) }) {+ IconClose()+ }+ }+ }+ }+ }+ items(downloads, key = { it.id }) { downloadItem ->+ val isSelected = downloadItem.id in selectedIds+ TvVideoCard(+ row = videoRowState(+ context = context,+ videoInfo = downloadItem.videoItem,+ showAuthor = true,+ ),+ onOpen = {+ if (isSelectionMode) {+ selectedIds = if (isSelected) selectedIds - downloadItem.id else selectedIds + downloadItem.id+ } else {+ backStack.add(TvRoute.Video(downloadItem.id))+ }+ },+ modifier = if (activeDownloads.isEmpty() && downloads.indexOf(downloadItem) == 0) {+ Modifier.focusRequester(firstFocus)+ } else {+ Modifier+ },+ trailingContent = {+ if (isSelectionMode) {+ Checkbox(+ checked = isSelected,+ onCheckedChange = {+ selectedIds = if (isSelected) {+ selectedIds - downloadItem.id+ } else {+ selectedIds + downloadItem.id+ }+ },+ modifier = Modifier.padding(top = 8.dp),+ )+ }+ },+ )+ }+ }+}
youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvDpadInput.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvDpadInput.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvDpadInput.ktnew file mode 100644index 0000000000..50d6bf6fe6--- /dev/null+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvDpadInput.kt@@ -0,0 +1,258 @@+package com.vayunmathur.youpipe.tv++import android.app.Activity+import android.media.AudioManager+import android.view.KeyEvent+import androidx.core.content.getSystemService+import com.vayunmathur.youpipe.platform.CastPlayback+import kotlin.math.roundToInt++/**+ * The TV remote map, copied from `cast/tv`'s `MirrorActivity.dispatchKeyEvent` — not imported,+ * because the receiver's commands cross a socket while these drive the local MediaController.+ *+ * Attached by [TvMainActivity] so every TV screen shares one map:+ *+ * - CENTER/ENTER: toggle play/pause (when controls are visible; otherwise reveal them first).+ * - LEFT/RIGHT: ±10s scrub preview while held, committed on release (KEY_UP).+ * - UP/DOWN: nudge the shared `STREAM_MUSIC` volume — the same level the phone owns, so it+ * survives the session and still applies when playback comes back to the phone.+ * - NEXT/PREV: related-video next / back-stack previous, via `CastPlayback.onNavigate`+ * (the player screen installs it; with nothing installed the keys fall through).+ * - BACK: dismiss the overlay first (transport, chapter sheet, dialog), only then navigate.+ * The overlay registers itself via [overlayDismiss]; unregistered means "nothing to dismiss".+ *+ * Like the receiver, a press that wakes hidden controls does not also toggle: with nothing on+ * screen the press reads as "show me the controls", and pausing instead would cost the user+ * their place. Skips and volume are unambiguous and always act.+ */+object TvDpadInput {+ /**+ * Dismiss the topmost overlay if one is showing; true when something was dismissed.+ *+ * The player screen sets this while the transport, chapter sheet or a dialog is up.+ * Last writer wins — only one TV screen is ever composed at a time.+ */+ var overlayDismiss: (() -> Boolean)? = null++ /** A scrub preview the user is composing, or null when no scrub is in progress. */+ var scrubPreviewMs: Long? = null+ private set++ /**+ * Whether the player surface currently holds focus.+ *+ * Set by `TvPlayer`'s surface focus listener. The gesture map (scrub, volume, toggle) only+ * claims D-pad keys while this is true — otherwise UP/DOWN/LEFT/RIGHT belong to focus+ * traversal (related list, option rows, tab strip). Media keys (play/pause/next/prev) act+ * whenever a player is attached, wherever focus sits. This is the one difference from the+ * receiver's map, which has no focusable UI to share the remote with.+ */+ var playerFocused: Boolean = false++ private var attached: android.content.Context? = null++ fun attach(activity: Activity) {+ // Application context, not the activity: volume nudges outlive any composition and a+ // static activity reference would leak the whole window on rotation.+ attached = activity.applicationContext+ }++ fun detach(activity: Activity) {+ attached = null+ }++ /**+ * Handle a key before the focus system sees it. Returns true when claimed.+ *+ * Called from `TvMainActivity.dispatchKeyEvent` — the same seam `MirrorActivity` uses —+ * so volume keys are seen before the system volume UI and BACK is seen before nav.+ * BACK-dismiss runs first, scrub-commit on release second, wake-then-act third.+ */+ fun onKeyEvent(event: KeyEvent): Boolean {+ if (event.keyCode == KeyEvent.KEYCODE_BACK) return handleBack(event)+ if (event.action == KeyEvent.ACTION_UP && isScrubKey(event.keyCode)) {+ // Only a scrub this map started is committed — otherwise the release belongs to+ // whatever (or nothing) handled the press.+ if (scrubPreviewMs == null) return false+ commitScrub()+ return true+ }+ if (event.action != KeyEvent.ACTION_DOWN) return false+ // Media keys act whenever a player is attached, wherever focus sits.+ if (isMediaKey(event.keyCode)) return handleMediaKey(event)+ // The D-pad gesture map only runs while the player surface holds focus; everywhere+ // else the keys belong to focus traversal (lists, option rows, tab strip).+ if (player() == null || !playerFocused) {+ // Still wake the overlay: a press anywhere says "show me the controls".+ if (player() != null) TvTransportState.reveal()+ return false+ }+ if (TvTransportState.controlsHidden) {+ TvTransportState.reveal()+ // A press that wakes the controls does not also toggle — but scrub and volume+ // reveal the very bar they move, so they still act.+ if (isToggleKey(event.keyCode)) return true+ }+ return handleKeyDown(event)+ }++ private fun handleBack(event: KeyEvent): Boolean {+ if (event.action == KeyEvent.ACTION_UP) {+ if (overlayDismiss?.invoke() == true) return true+ }+ return false+ }++ /** Play/pause/next/previous: no focus needed, claimed whenever a player is attached. */+ private fun isMediaKey(keyCode: Int): Boolean = when (keyCode) {+ KeyEvent.KEYCODE_MEDIA_PLAY,+ KeyEvent.KEYCODE_MEDIA_PAUSE,+ KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE,+ KeyEvent.KEYCODE_MEDIA_NEXT,+ KeyEvent.KEYCODE_MEDIA_PREVIOUS,+ KeyEvent.KEYCODE_MEDIA_FAST_FORWARD,+ KeyEvent.KEYCODE_MEDIA_REWIND,+ -> true+ else -> false+ }++ private fun handleMediaKey(event: KeyEvent): Boolean {+ if (player() == null) return false+ when (event.keyCode) {+ KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> toggle()+ KeyEvent.KEYCODE_MEDIA_PLAY -> setPlaying(true)+ KeyEvent.KEYCODE_MEDIA_PAUSE -> setPlaying(false)+ KeyEvent.KEYCODE_MEDIA_NEXT -> navigate(next = true)+ KeyEvent.KEYCODE_MEDIA_PREVIOUS -> navigate(next = false)+ KeyEvent.KEYCODE_MEDIA_FAST_FORWARD -> skip(forward = true)+ KeyEvent.KEYCODE_MEDIA_REWIND -> skip(forward = false)+ }+ return true+ }++ /** One D-pad press while the player surface holds focus: toggle, scrub, or volume. */+ private fun handleKeyDown(event: KeyEvent): Boolean {+ when (event.keyCode) {+ KeyEvent.KEYCODE_DPAD_CENTER,+ KeyEvent.KEYCODE_ENTER,+ KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE,+ -> toggle()++ KeyEvent.KEYCODE_MEDIA_PLAY -> setPlaying(true)+ KeyEvent.KEYCODE_MEDIA_PAUSE -> setPlaying(false)++ KeyEvent.KEYCODE_DPAD_RIGHT -> scrubBy(SCRUB_STEP_MS)+ KeyEvent.KEYCODE_DPAD_LEFT -> scrubBy(-SCRUB_STEP_MS)++ // The remote's dedicated keys, where it has them. Discrete skips, not scrub previews.+ KeyEvent.KEYCODE_MEDIA_FAST_FORWARD -> skip(forward = true)+ KeyEvent.KEYCODE_MEDIA_REWIND -> skip(forward = false)++ KeyEvent.KEYCODE_MEDIA_NEXT -> navigate(next = true)+ KeyEvent.KEYCODE_MEDIA_PREVIOUS -> navigate(next = false)++ KeyEvent.KEYCODE_DPAD_UP,+ KeyEvent.KEYCODE_VOLUME_UP,+ -> nudgeVolume(up = true)++ KeyEvent.KEYCODE_DPAD_DOWN,+ KeyEvent.KEYCODE_VOLUME_DOWN,+ -> nudgeVolume(up = false)++ else -> return false+ }+ return true+ }++ private fun player() = CastPlayback.attachedPlayer++ private fun toggle() {+ val target = player() ?: return+ if (target.isPlaying) target.pause() else target.play()+ }++ private fun setPlaying(playing: Boolean) {+ val target = player() ?: return+ if (playing) target.play() else target.pause()+ }++ /**+ * Move the scrub preview, starting from live playback on the first press.+ *+ * Accumulated locally and committed once on release — one seek per gesture, not one per+ * key-repeat, which is both kinder to ExoPlayer and what holding the key means.+ */+ private fun scrubBy(deltaMs: Long) {+ val transport = CastPlayback.transport.value+ if (transport.durationMs <= 0) return+ val from = scrubPreviewMs ?: transport.positionMs+ scrubPreviewMs = (from + deltaMs).coerceIn(0, transport.durationMs)+ TvTransportState.reveal()+ }++ private fun commitScrub() {+ val target = scrubPreviewMs ?: return+ scrubPreviewMs = null+ player()?.seekTo(target)+ CastPlayback.update { it.copy(positionMs = target) }+ TvTransportState.reveal()+ }++ private fun skip(forward: Boolean) {+ val transport = CastPlayback.transport.value+ val end = transport.durationMs.takeIf { it > 0 } ?: Long.MAX_VALUE+ val target = if (forward) {+ (transport.positionMs + SKIP_MS).coerceAtMost(end)+ } else {+ (transport.positionMs - SKIP_MS).coerceAtLeast(0)+ }+ player()?.seekTo(target)+ CastPlayback.update { it.copy(positionMs = target) }+ TvTransportState.reveal()+ }++ private fun navigate(next: Boolean) {+ CastPlayback.onNavigate?.invoke(next)+ }++ /**+ * Nudge the shared media volume.+ *+ * The same level the phone owns (`STREAM_MUSIC`): the remote moves it and the gain follows+ * on the next snapshot, so the level is still there when playback returns to the phone.+ */+ private fun nudgeVolume(up: Boolean) {+ val activity = attached ?: return+ val audio = activity.getSystemService<AudioManager>() ?: return+ val max = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC)+ if (max <= 0) return+ val current = audio.getStreamVolume(AudioManager.STREAM_MUSIC)+ val step = (max / VOLUME_STEPS).coerceAtLeast(1)+ val next = (current + if (up) step else -step).coerceIn(0, max)+ runCatching { audio.setStreamVolume(AudioManager.STREAM_MUSIC, next, 0) }+ TvTransportState.flashVolume(next.toFloat() / max)+ }++ private fun isScrubKey(keyCode: Int): Boolean =+ keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT++ private fun isToggleKey(keyCode: Int): Boolean =+ keyCode == KeyEvent.KEYCODE_DPAD_CENTER ||+ keyCode == KeyEvent.KEYCODE_ENTER ||+ keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE++ /** How far one D-pad press moves the scrub preview. Matches the receiver's aim-sized step. */+ const val SCRUB_STEP_MS = 10_000L++ /** Discrete skip for the dedicated FF/REW keys — matches the phone's own skip buttons. */+ private const val SKIP_MS = 10_000L++ /** Volume steps across the full range; the TV remote nudges rather than jumps. */+ private const val VOLUME_STEPS = 20++ /** Cancel a scrub without committing (overlay dismissed mid-scrub). */+ fun cancelScrub() {+ scrubPreviewMs = null+ }+}
youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvGeneralSettings.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvGeneralSettings.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvGeneralSettings.ktnew file mode 100644index 0000000000..ffb80ec7f9--- /dev/null+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvGeneralSettings.kt@@ -0,0 +1,220 @@+package com.vayunmathur.youpipe.tv++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.remember+import androidx.compose.ui.Alignment+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Surface+import androidx.tv.material3.Text+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.youpipe.R+import com.vayunmathur.youpipe.util.YouPipeViewModel++/**++ * TV general settings: open-to default, DeArrow, keep-controls, notification bar, language.++ *++ * Same DataStore bindings as the phone `GeneralSettingsPage`; dropdowns become D-pad option++ * lists (one focusable row per choice) because a TV has no dropdown menu convention.++ */++@Composable++fun TvGeneralSettingsPage(++ backStack: NavBackStack<TvRoute>,++ ypvm: YouPipeViewModel,++) {++ val deArrowEnabled by ypvm.deArrowEnabled.collectAsState()++ val youtubeLanguage by ypvm.youtubeLanguage.collectAsState()++ val defaultPage by ypvm.defaultPage.collectAsState()++ val keepControlsVisible by ypvm.keepPlayerControlsVisible.collectAsState()++ val notificationStyleProgress by ypvm.notificationStyleProgressBar.collectAsState()++ val firstFocus = remember { FocusRequester() }++++ // TV pins the transport overlay visible when the accessibility keep-visible is on —++ // same flag the phone player reads, no TV-specific path.++ androidx.compose.runtime.LaunchedEffect(keepControlsVisible) {++ TvTransportState.pinned = keepControlsVisible++ if (keepControlsVisible) TvTransportState.reveal()++ }++++ TvInitialFocus(firstFocus)++ Column(++ Modifier++ .fillMaxSize()++ .padding(horizontal = 48.dp, vertical = 32.dp)++ .verticalScroll(rememberScrollState()),++ verticalArrangement = Arrangement.spacedBy(8.dp),++ ) {++ Text(text = stringResource(R.string.settings_general_content), style = MaterialTheme.typography.headlineSmall)++ Text(text = stringResource(R.string.label_default_page), style = MaterialTheme.typography.titleMedium)++ com.vayunmathur.youpipe.DEFAULT_PAGE_OPTIONS.forEach { (key, labelRes) ->++ TvOptionRow(++ label = stringResource(labelRes),++ selected = defaultPage == key,++ onSelect = { ypvm.setDefaultPage(key) },++ )++ }++ TvSwitchRow(++ title = stringResource(R.string.label_dearrow),++ summary = stringResource(R.string.label_dearrow_description),++ checked = deArrowEnabled,++ onCheckedChange = { ypvm.setDeArrowEnabled(it) },++ )++ TvSwitchRow(++ title = stringResource(R.string.label_keep_controls_visible),++ summary = stringResource(R.string.label_keep_controls_visible_description),++ checked = keepControlsVisible,++ onCheckedChange = { ypvm.setKeepPlayerControlsVisible(it) },++ )++ TvSwitchRow(++ title = stringResource(R.string.label_notification_style_progress),++ summary = stringResource(R.string.label_notification_style_progress_description),++ checked = notificationStyleProgress,++ onCheckedChange = { ypvm.setNotificationStyleProgressBar(it) },++ )++ Text(text = stringResource(R.string.label_youtube_language), style = MaterialTheme.typography.titleMedium)++ TvOptionRow(++ label = stringResource(R.string.label_system_default),++ selected = youtubeLanguage.isBlank(),++ onSelect = { ypvm.setYouTubeLanguage("") },++ )++ YouPipeViewModel.Companion.YOUTUBE_LANGUAGES.forEach { (code, name) ->++ TvOptionRow(++ label = name,++ selected = youtubeLanguage == code,++ onSelect = { ypvm.setYouTubeLanguage(code) },++ )++ }++ }++}++++/** One selectable option row with a checked marker. Shared with recommendations (presets). */+@Composable+internal fun TvOptionRow(++ label: String,++ selected: Boolean,++ onSelect: () -> Unit,++ modifier: Modifier = Modifier,++) {++ Surface(onClick = onSelect, modifier = modifier.fillMaxWidth()) {++ Row(++ Modifier.padding(horizontal = 16.dp, vertical = 12.dp),++ verticalAlignment = Alignment.CenterVertically,++ ) {++ androidx.tv.material3.Checkbox(checked = selected, onCheckedChange = null)++ Text(++ text = label,++ style = MaterialTheme.typography.titleMedium,++ modifier = Modifier.padding(start = 12.dp),++ )++ }++ }++}
youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvHistory.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvHistory.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvHistory.ktnew file mode 100644index 0000000000..68b20486d7--- /dev/null+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvHistory.kt@@ -0,0 +1,160 @@+package com.vayunmathur.youpipe.tv++import androidx.activity.compose.BackHandler+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.lazy.grid.GridCells+import androidx.compose.foundation.lazy.grid.items+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid+import androidx.compose.foundation.lazy.grid.rememberLazyGridState+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.tv.material3.Button+import androidx.tv.material3.Checkbox+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.youpipe.R+import com.vayunmathur.youpipe.ui.videoRowState+import com.vayunmathur.youpipe.util.YouPipeViewModel++/**+ * TV history: focusable grid with D-pad multiselect.+ *+ * The phone uses long-press to enter selection and a FAB to delete. A TV has no long-press+ * convention and no FAB within reach — so selection is a checkbox on each focused card+ * (RIGHT onto the box, CENTER toggles), and delete is a focused action row that appears only+ * while the selection is non-empty. BACK clears the selection first, matching the phone's+ * `BackHandler` and the overlay-dismiss-first rule.+ */+@Composable+fun TvHistoryPage(+ backStack: NavBackStack<TvRoute>,+ ypvm: YouPipeViewModel,+) {+ val history by ypvm.historyVideosByRecency.collectAsState()+ val deArrowEnabled by ypvm.deArrowEnabled.collectAsState()+ val deArrowCache by ypvm.deArrowCache.collectAsState()+ val context = LocalContext.current+ val firstFocus = remember { FocusRequester() }++ var selectedIds by remember { mutableStateOf(emptySet<Long>()) }+ val inSelectionMode = selectedIds.isNotEmpty()+ BackHandler(enabled = inSelectionMode) { selectedIds = emptySet() }++ val rows = remember(history, deArrowEnabled, deArrowCache) {+ history.map { item ->+ val video = item.videoItem+ val deArrow = if (deArrowEnabled) deArrowCache[video.videoID] else null+ item.id to videoRowState(+ context = context,+ videoInfo = video,+ showAuthor = true,+ percentWatched = if (video.duration > 0) {+ (item.progress.toDouble() / video.duration).toFloat()+ } else {+ 0f+ },+ deArrowTitle = deArrow?.title,+ deArrowThumbnailURL = deArrow?.thumbnailUrl,+ )+ }+ }++ TvInitialFocus(firstFocus)+ val gridState = rememberLazyGridState()+ Column(+ Modifier+ .fillMaxSize()+ .padding(horizontal = 48.dp, vertical = 32.dp),+ ) {+ Text(text = stringResource(R.string.title_history), style = MaterialTheme.typography.headlineSmall)+ if (inSelectionMode) {+ Row(+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ modifier = Modifier.padding(vertical = 8.dp),+ ) {+ Text(+ text = stringResource(R.string.selected_count, selectedIds.size),+ style = MaterialTheme.typography.titleMedium,+ )+ Button(+ onClick = {+ ypvm.deleteHistoryVideos(selectedIds.toList())+ selectedIds = emptySet()+ },+ ) {+ IconDelete()+ }+ Button(onClick = { selectedIds = emptySet() }) {+ Text(stringResource(R.string.action_close))+ }+ }+ }+ LazyVerticalGrid(+ columns = GridCells.Fixed(3),+ state = gridState,+ modifier = Modifier.fillMaxSize().padding(top = 8.dp),+ verticalArrangement = Arrangement.spacedBy(16.dp),+ horizontalArrangement = Arrangement.spacedBy(16.dp),+ ) {+ items(rows, key = { it.first }) { (id, row) ->+ val isSelected = id in selectedIds+ Column {+ TvVideoCard(+ row = row,+ onOpen = {+ if (inSelectionMode) {+ selectedIds = if (isSelected) selectedIds - id else selectedIds + id+ } else {+ backStack.add(TvRoute.Video(row.videoID))+ }+ },+ modifier = if (rows.indexOfFirst { it.first == id } == 0) {+ Modifier.focusRequester(firstFocus)+ } else {+ Modifier+ },+ trailingContent = {+ // The selection checkbox: a second focus target on the card, so a+ // focused card offers open (CENTER) and select (RIGHT then CENTER).+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier.padding(top = 8.dp),+ ) {+ Checkbox(+ checked = isSelected,+ onCheckedChange = {+ selectedIds = if (isSelected) selectedIds - id else selectedIds + id+ },+ )+ Text(+ text = stringResource(R.string.selected_count, selectedIds.size),+ style = MaterialTheme.typography.bodySmall,+ modifier = Modifier.padding(start = 8.dp),+ )+ }+ },+ )+ }+ }+ }+ }+}
youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvHomeFeed.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvHomeFeed.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvHomeFeed.ktnew file mode 100644index 0000000000..15535259d8--- /dev/null+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvHomeFeed.kt@@ -0,0 +1,141 @@+package com.vayunmathur.youpipe.tv++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.grid.GridCells+import androidx.compose.foundation.lazy.grid.items+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid+import androidx.compose.foundation.lazy.grid.rememberLazyGridState+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.remember+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.youpipe.R+import com.vayunmathur.youpipe.ui.countString+import com.vayunmathur.youpipe.ui.videoRowState+import com.vayunmathur.youpipe.util.blockChannel+import com.vayunmathur.youpipe.util.boostChannel+import com.vayunmathur.youpipe.util.loadRecommendations+import com.vayunmathur.youpipe.util.pinChannel+import com.vayunmathur.youpipe.util.removeInterest+import com.vayunmathur.youpipe.util.SearchResultRow+import com.vayunmathur.youpipe.util.YouPipeViewModel++/**+ * TV home: the recommendation feed as a focusable grid, with a search entry row on top.+ *+ * Binder mirrors the phone `SearchPage`'s mapping (recommendations + history progress ++ * DeArrow) into plain rows — but there is no search overlay and no autofocus: search is a+ * separate [TvRoute]-less inline panel opened by explicit focus + CENTER, so the TV IME never+ * pops uninvited. Overflow actions (not-interested, pin, block) are per-row D-pad options+ * reached with RIGHT on the focused card.+ */+@Composable+fun TvHomeFeedPage(+ backStack: NavBackStack<TvRoute>,+ ypvm: YouPipeViewModel,+) {+ val recommendations by ypvm.recommendations.collectAsState()+ val recommendationsLoading by ypvm.recommendationsLoading.collectAsState()+ val history by ypvm.historyVideos.collectAsState()+ val deArrowEnabled by ypvm.deArrowEnabled.collectAsState()+ val deArrowCache by ypvm.deArrowCache.collectAsState()+ val progressById = remember(history) { history.associate { it.id to it.progress } }+ val context = LocalContext.current++ LaunchedEffect(Unit) {+ ypvm.loadRecommendations()+ }++ val rows = remember(recommendations, deArrowEnabled, deArrowCache, progressById) {+ recommendations.map { ranked ->+ val video = ranked.video+ val deArrow = if (deArrowEnabled) deArrowCache[video.videoID] else null+ val watched = progressById[video.videoID] ?: 0L+ videoRowState(+ context = context,+ videoInfo = video,+ showAuthor = true,+ reason = ranked.reason,+ percentWatched = if (video.duration > 0) {+ (watched.toDouble() / video.duration).toFloat()+ } else {+ 0f+ },+ deArrowTitle = deArrow?.title,+ deArrowThumbnailURL = deArrow?.thumbnailUrl,+ )+ }+ }++ val gridState = rememberLazyGridState()+ val searchFocus = remember { FocusRequester() }+ TvListScreen(+ title = stringResource(R.string.label_recommendations),+ emptyMessage = if (!recommendationsLoading) {+ stringResource(R.string.empty_recommendations)+ } else {+ null+ },+ itemCount = rows.size,+ ) {+ LazyVerticalGrid(+ columns = GridCells.Fixed(3),+ state = gridState,+ modifier = Modifier+ .fillMaxSize()+ .padding(top = 16.dp),+ verticalArrangement = Arrangement.spacedBy(16.dp),+ horizontalArrangement = Arrangement.spacedBy(16.dp),+ ) {+ item(key = "tv-search-entry") {+ TvSearchEntryRow(+ onOpenSearch = { backStack.add(TvRoute.Search) },+ modifier = Modifier.focusRequester(searchFocus),+ )+ }+ items(rows, key = { it.videoID }) { row ->+ TvVideoCard(+ row = row,+ onOpen = { backStack.add(TvRoute.Video(row.videoID)) },+ )+ }+ }+ }+ TvInitialFocus(searchFocus)+}++/**+ * The search entry row: a focusable card that opens the search panel.+ *+ * Separate from the feed grid items so the IME only ever opens from an explicit CENTER press —+ * never from composition, scroll, or focus passing through.+ */+@Composable+private fun TvSearchEntryRow(+ onOpenSearch: () -> Unit,+ modifier: Modifier = Modifier,+) {+ androidx.tv.material3.Surface(onClick = onOpenSearch, modifier = modifier) {+ androidx.compose.foundation.layout.Row(+ Modifier.padding(16.dp),+ verticalAlignment = androidx.compose.ui.Alignment.CenterVertically,+ ) {+ com.vayunmathur.library.ui.IconSearch()+ androidx.tv.material3.Text(+ text = stringResource(com.vayunmathur.library.ui.R.string.search),+ style = androidx.tv.material3.MaterialTheme.typography.titleMedium,+ modifier = Modifier.padding(start = 12.dp),+ )+ }+ }+}
youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvMainActivity.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvMainActivity.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvMainActivity.ktnew file mode 100644index 0000000000..76fb6e68c0--- /dev/null+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvMainActivity.kt@@ -0,0 +1,64 @@+package com.vayunmathur.youpipe.tv++import android.view.KeyEvent+import androidx.activity.viewModels+import androidx.compose.runtime.Composable+import androidx.tv.material3.darkColorScheme+import androidx.tv.material3.MaterialTheme+import com.vayunmathur.library.ui.MaActivity+import com.vayunmathur.youpipe.data.SubscriptionRepository+import com.vayunmathur.youpipe.util.YouPipeViewModel+import com.vayunmathur.youpipe.util.YouPipeViewModelFactory++/**+ * The TV entry: opened from TV launcher rows (LEANBACK_LAUNCHER). The phone MainActivity+ * stays exactly as it is — this activity hosts the D-pad browse + player UI.+ *+ * Landscape-locked and non-edge-to-edge per the manifest; the activity owns the [TvDpadInput]+ * key map so scrub/volume/BACK work consistently across browse and player.+ */+class TvMainActivity : MaActivity() {+ override val edgeToEdge: Boolean = false++ private val youPipeViewModel: YouPipeViewModel by viewModels {+ YouPipeViewModelFactory(+ application,+ SubscriptionRepository.get(application),+ )+ }++ override fun onCreateBeforeContent() {+ // Same arming the phone does: touch the VM so its hourly subscription task schedules.+ youPipeViewModel+ TvDpadInput.attach(this)+ }++ override fun onDestroy() {+ TvDpadInput.detach(this)+ super.onDestroy()+ }++ /**+ * The remote, in full — copied from `cast/tv`'s `MirrorActivity.dispatchKeyEvent`.+ *+ * Claims a key only while there is something to act on (player attached, overlay up);+ * everything else falls through to the focus system and nav, which is what the browse+ * screens need. BACK is the exception: it dismisses the overlay before it will pop nav.+ */+ override fun dispatchKeyEvent(event: KeyEvent): Boolean {+ if (TvDpadInput.onKeyEvent(event)) return true+ return super.dispatchKeyEvent(event)+ }++ @Composable+ override fun AppTheme(content: @Composable () -> Unit) {+ // Always dark, not dynamic: a TV has no wallpaper to derive a scheme from.+ // Paints nothing itself; screens set their own background.+ MaterialTheme(colorScheme = darkColorScheme(), content = content)+ }++ @Composable+ override fun Content() {+ TvNavigation(youPipeViewModel)+ }+}
youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvManageInterests.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvManageInterests.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvManageInterests.ktnew file mode 100644index 0000000000..a8fdfec893--- /dev/null+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvManageInterests.kt@@ -0,0 +1,343 @@+package com.vayunmathur.youpipe.tv++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.tv.material3.Button+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Surface+import androidx.tv.material3.Text+import com.vayunmathur.library.ui.R as UiR+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.youpipe.R+import com.vayunmathur.youpipe.util.clearChannelPreference+import com.vayunmathur.youpipe.util.decodeHtml+import com.vayunmathur.youpipe.util.pinChannel+import com.vayunmathur.youpipe.util.removeInterest+import com.vayunmathur.youpipe.util.unmuteKeyword+import com.vayunmathur.youpipe.util.YouPipeViewModel++/**++ * TV interests: channels/topics/blocked/muted as focusable rows with pin/remove actions.++ *++ * Same `interestProfile`/`channelPreferences`/`keywordPreferences` bindings as the phone;++ * trailing buttons become stacked focus targets under each row (D-pad DOWN reaches them).++ */++@Composable++fun TvManageInterestsPage(++ backStack: NavBackStack<TvRoute>,++ ypvm: YouPipeViewModel,++) {++ val profile by ypvm.interestProfile.collectAsState()++ val channelPrefs by ypvm.channelPreferences.collectAsState()++ val keywordPrefs by ypvm.keywordPreferences.collectAsState()++ val firstFocus = remember { FocusRequester() }++++ val blockedKeys = channelPrefs.filter { it.blocked }.map { it.channelKey }.toSet()++ val pinnedKeys = channelPrefs.filter { it.pinned }.map { it.channelKey }.toSet()++ val topChannels = remember(profile, blockedKeys) {++ profile.authorWeights.entries++ .filter { it.key.isNotBlank() && it.key !in blockedKeys }++ .sortedByDescending { it.value }++ .take(30)++ .map { it.key }++ }++ val topKeywords = remember(profile) {++ profile.keywordWeights.entries++ .sortedByDescending { it.value }++ .take(30)++ .map { it.key }++ }++ val blockedChannels = remember(channelPrefs) {++ channelPrefs.filter { it.blocked }.map { it.channelKey }++ }++ val mutedKeywords = remember(keywordPrefs) {++ keywordPrefs.filter { it.muted }.map { it.keyword }++ }++++ TvInitialFocus(firstFocus)++ LazyColumn(++ Modifier++ .fillMaxSize()++ .padding(horizontal = 48.dp, vertical = 32.dp),++ verticalArrangement = Arrangement.spacedBy(8.dp),++ ) {++ item(key = "interests-title") {++ Text(text = stringResource(R.string.title_manage_interests), style = MaterialTheme.typography.headlineSmall)++ }++ item(key = "ch-header") { TvSectionHeader(stringResource(R.string.label_your_channels)) }++ if (topChannels.isEmpty()) {++ item(key = "ch-empty") { TvEmptyRow(stringResource(R.string.label_no_channels)) }++ }++ items(topChannels, key = { "ch-$it" }) { channelKey ->++ val pinned = channelKey in pinnedKeys++ TvInterestRow(++ label = channelKey.decodeHtml(),++ badge = if (pinned) stringResource(R.string.label_pinned) else null,++ primaryAction = if (pinned) {++ stringResource(R.string.action_unpin)++ } else {++ stringResource(R.string.action_pin)++ },++ onPrimary = {++ if (pinned) ypvm.clearChannelPreference(channelKey) else ypvm.pinChannel(channelKey)++ },++ secondaryAction = stringResource(UiR.string.remove),++ onSecondary = { ypvm.removeInterest(channelKey = channelKey) },++ )++ }++ item(key = "kw-header") { TvSectionHeader(stringResource(R.string.label_your_topics)) }++ if (topKeywords.isEmpty()) {++ item(key = "kw-empty") { TvEmptyRow(stringResource(R.string.label_no_topics)) }++ }++ items(topKeywords, key = { "kw-$it" }) { keyword ->++ TvInterestRow(++ label = keyword,++ primaryAction = stringResource(UiR.string.remove),++ onPrimary = { ypvm.removeInterest(keyword = keyword) },++ )++ }++ item(key = "bl-header") { TvSectionHeader(stringResource(R.string.label_blocked_channels)) }++ if (blockedChannels.isEmpty()) {++ item(key = "bl-empty") { TvEmptyRow(stringResource(R.string.label_no_blocked_channels)) }++ }++ items(blockedChannels, key = { "bl-$it" }) { channelKey ->++ TvInterestRow(++ label = channelKey.decodeHtml(),++ primaryAction = stringResource(R.string.action_unblock),++ onPrimary = { ypvm.clearChannelPreference(channelKey) },++ )++ }++ item(key = "mk-header") { TvSectionHeader(stringResource(R.string.label_muted_keywords)) }++ if (mutedKeywords.isEmpty()) {++ item(key = "mk-empty") { TvEmptyRow(stringResource(R.string.label_no_muted_keywords)) }++ }++ items(mutedKeywords, key = { "mk-$it" }) { keyword ->++ TvInterestRow(++ label = keyword,++ primaryAction = stringResource(R.string.action_unmute),++ onPrimary = { ypvm.unmuteKeyword(keyword) },++ )++ }++ }++}++++@Composable++private fun TvSectionHeader(text: String) {++ Text(++ text = text,++ style = MaterialTheme.typography.titleSmall,++ color = MaterialTheme.colorScheme.primary,++ )++}++++@Composable++private fun TvEmptyRow(text: String) {++ Text(++ text = text,++ style = MaterialTheme.typography.bodyMedium,++ color = MaterialTheme.colorScheme.onSurfaceVariant,++ )++}++++/**++ * One interest row: label + badge + stacked action buttons, each a focus target.++ * Actions stack under the label (not beside it) so DOWN always reaches them.++ */++@Composable++private fun TvInterestRow(++ label: String,++ primaryAction: String,++ onPrimary: () -> Unit,++ modifier: Modifier = Modifier,++ badge: String? = null,++ secondaryAction: String? = null,++ onSecondary: (() -> Unit)? = null,++) {++ Surface(onClick = onPrimary, modifier = modifier.fillMaxWidth()) {++ Column(Modifier.padding(16.dp)) {++ Text(text = label, style = MaterialTheme.typography.titleMedium)++ if (badge != null) {++ Text(++ text = badge,++ style = MaterialTheme.typography.bodySmall,++ color = MaterialTheme.colorScheme.primary,++ )++ }++ Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(top = 8.dp)) {++ Button(onClick = onPrimary) { Text(primaryAction) }++ if (secondaryAction != null && onSecondary != null) {++ Button(onClick = onSecondary) { Text(secondaryAction) }++ }++ }++ }++ }++}
youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvNavigation.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvNavigation.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvNavigation.ktnew file mode 100644index 0000000000..27cf63b6f3--- /dev/null+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvNavigation.kt@@ -0,0 +1,105 @@+package com.vayunmathur.youpipe.tv++import androidx.activity.compose.BackHandler+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableIntStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Tab+import androidx.tv.material3.TabRow+import com.vayunmathur.library.ui.R as UiR+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.youpipe.R+import com.vayunmathur.youpipe.util.YouPipeViewModel++/**+ * The TV navigation host: [rememberNavBackStack] + [MainNavigation] over [TvRoute], replacing+ * the phone's 5-tab swipe pager.+ *+ * No `HorizontalPager` swipe — a TV has no touch — and no shared-element morphs: the phone's+ * title keys assume single-origin compositions the tab pager already strains, and TV screens+ * compose independently. Tabs are a focusable [TabRow] strip; D-pad LEFT/RIGHT moves between+ * tabs, DOWN drops into content. Each tab keeps its own screen so focus restores per tab.+ */+@Composable+fun TvNavigation(ypvm: YouPipeViewModel) {+ val backStack = rememberNavBackStack<TvRoute>(TvRoute.Main())+ MainNavigation(backStack) {+ entry<TvRoute.Main> { TvMainTabs(backStack, ypvm, it.initialTab) }+ entry<TvRoute.Search> { TvSearchPage(backStack, ypvm) }+ entry<TvRoute.Video> { TvVideoPage(backStack, ypvm, it.videoID) }+ entry<TvRoute.Channel> { TvChannelPage(backStack, ypvm, it.channelID) }+ entry<TvRoute.SubscriptionFeed> { TvSubscriptionFeedPage(backStack, ypvm, it.category) }+ entry<TvRoute.CreateSubscriptionCategory> { TvCreateCategoryPage(backStack, ypvm, it.id) }+ entry<TvRoute.Downloads> { TvDownloadsPage(backStack, ypvm) }+ entry<TvRoute.PlaylistDetail> { TvPlaylistDetailPage(backStack, ypvm, it.playlistId) }+ entry<TvRoute.CreatePlaylist> { TvCreatePlaylistPage(backStack, ypvm) }+ entry<TvRoute.AddToPlaylist> { TvAddToPlaylistPage(backStack, ypvm, it.videoID, it.includeWatchLater) }+ entry<TvRoute.SettingsGeneral> { TvGeneralSettingsPage(backStack, ypvm) }+ entry<TvRoute.SettingsSponsorBlock> { TvSponsorBlockSettingsPage(backStack, ypvm) }+ entry<TvRoute.SettingsRecommendations> { TvRecommendationsSettingsPage(backStack, ypvm) }+ entry<TvRoute.SettingsData> { TvDataSettingsPage(backStack, ypvm) }+ entry<TvRoute.ManageInterests> { TvManageInterestsPage(backStack, ypvm) }+ }+}++/**+ * The five TV tabs as a D-pad strip: Home, Subscriptions, History, Saved, Settings.+ *+ * Unlike the phone's `TabbedPagerScaffold`, tabs are destinations only — selecting one swaps+ * the content below without any swipe gesture. Per-tab focus restores because each tab's+ * screen owns its own list state.+ */+@Composable+private fun TvMainTabs(+ backStack: NavBackStack<TvRoute>,+ ypvm: YouPipeViewModel,+ initialTab: Int,+) {+ var tab by remember { mutableIntStateOf(initialTab.coerceIn(0, 4)) }+ val homeLabel = stringResource(UiR.string.home)+ val subsLabel = stringResource(R.string.title_subscriptions)+ val historyLabel = stringResource(R.string.title_history)+ val savedLabel = stringResource(UiR.string.saved)+ val settingsLabel = stringResource(UiR.string.settings)++ Column(+ Modifier+ .fillMaxSize()+ .background(MaterialTheme.colorScheme.background),+ ) {+ TabRow(selectedTabIndex = tab) {+ for (i in 0..4) {+ Tab(+ selected = tab == i,+ onFocus = { tab = i },+ onClick = { tab = i },+ ) {+ androidx.tv.material3.Text(+ tvLabelForTab(i, homeLabel, subsLabel, historyLabel, savedLabel, settingsLabel),+ )+ }+ }+ }+ when (tab) {+ TV_TAB_HOME -> TvHomeFeedPage(backStack, ypvm)+ TV_TAB_SUBSCRIPTIONS -> TvSubscriptionsPage(backStack, ypvm)+ TV_TAB_HISTORY -> TvHistoryPage(backStack, ypvm)+ TV_TAB_SAVED -> TvSavedPage(backStack, ypvm)+ else -> TvSettingsPage(backStack, ypvm)+ }+ }+ // BACK on a root tab exits the app (the activity finishes); deeper routes pop via nav3.+ BackHandler(enabled = backStack.backStack.size <= 1) {+ // No-op: with nothing to pop, the activity handles BACK as finish.+ }+}
youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvPlayer.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvPlayer.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvPlayer.ktnew file mode 100644index 0000000000..2dd34fe627--- /dev/null+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvPlayer.kt@@ -0,0 +1,681 @@+package com.vayunmathur.youpipe.tv++import android.content.ComponentName+import android.text.format.DateUtils+import androidx.annotation.OptIn+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.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.rememberLazyListState+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.mutableLongStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+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.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.core.net.toUri+import androidx.media3.common.C+import androidx.media3.common.MediaItem+import androidx.media3.common.MediaMetadata+import androidx.media3.common.PlaybackParameters+import androidx.media3.common.Player+import androidx.media3.common.text.Cue+import androidx.media3.common.util.UnstableApi+import androidx.media3.common.VideoSize+import androidx.media3.session.MediaController+import androidx.media3.session.SessionToken+import androidx.media3.ui.compose.PlayerSurface+import androidx.media3.ui.compose.SURFACE_TYPE_SURFACE_VIEW+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Surface+import androidx.tv.material3.Switch+import androidx.tv.material3.Text+import com.google.common.util.concurrent.MoreExecutors+import com.vayunmathur.library.image.compose.AsyncImage+import com.vayunmathur.library.image.ImageRequest+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.FadeVisibility+import com.vayunmathur.library.ui.IconCheck+import com.vayunmathur.library.ui.rememberMessenger+import com.vayunmathur.library.util.AppMessages+import com.vayunmathur.youpipe.platform.CastPlayback+import com.vayunmathur.youpipe.R+import com.vayunmathur.youpipe.ui.AudioStream+import com.vayunmathur.youpipe.ui.selectDefaultVideoStream+import com.vayunmathur.youpipe.ui.SubtitleTrack+import com.vayunmathur.youpipe.ui.VideoChapter+import com.vayunmathur.youpipe.ui.VideoInfo+import com.vayunmathur.youpipe.ui.VideoStream+import com.vayunmathur.youpipe.util.PlaybackService+import com.vayunmathur.youpipe.util.YouPipeViewModel+import kotlin.math.min++/**+ * The TV player: the same media3 `PlayerSurface` + `MediaController`/`PlaybackService` core as+ * the phone, with the touch-only gesture layer replaced.+ *+ * Gone from the phone player: `detectTapGestures` (tap toggle, double-tap ±10s, long-press 2x),+ * the 2s auto-hide timer, hover affordances, and orientation-lock fullscreen (the activity is+ * landscape-locked in the manifest). In their place: [TvTransportOverlay] (non-focusable+ * readout + focusable controls), the [TvDpadInput] key map (scrub commit on UP, volume nudge,+ * BACK dismisses overlay first), and [TvPlaybackClock] (one per-frame ticker).+ *+ * PiP is left alone — the manifest flag is harmless on TV and the phone owns the behavior.+ */+@OptIn(UnstableApi::class)+@Composable+fun TvPlayer(+ ypvm: YouPipeViewModel,+ videoInfo: VideoInfo,+ videoStreams: List<VideoStream>,+ audioStreams: List<AudioStream>,+ subtitles: List<SubtitleTrack>,+ segments: List<VideoChapter>,+) {+ if (videoStreams.isEmpty()) return+ val context = LocalContext.current+ val messenger = rememberMessenger()++ var controller by remember { mutableStateOf<MediaController?>(null) }+ var cues by remember { mutableStateOf<List<Cue>>(emptyList()) }+ var showChapters by remember { mutableStateOf(false) }+ var showQuality by remember { mutableStateOf(false) }+ var showCaptions by remember { mutableStateOf(false) }+ var showSpeed by remember { mutableStateOf(false) }+ val overlayVisible by TvTransportState.visible.collectAsState()++ val deviceHeightPx = remember(context) {+ context.resources.displayMetrics.let { min(it.widthPixels, it.heightPixels) }+ }+ var currentVideoStream by remember(videoStreams) {+ mutableStateOf(selectDefaultVideoStream(videoStreams, deviceHeightPx) ?: videoStreams.first())+ }+ // TV keeps the phone's audio rule: highest-quality opus for the selected language.+ val language = remember(audioStreams) {+ val codes = audioStreams.map { it.language }.distinct()+ if ("en" in codes) "en" else codes.firstOrNull().orEmpty()+ }+ val currentAudioStream = remember(audioStreams, language) {+ audioStreams.filter { it.language == language }.maxByOrNull { it.bitrate }+ }+ var selectedSubtitle by remember { mutableStateOf<SubtitleTrack?>(null) }+ val transport by CastPlayback.transport.collectAsState()+ val playbackErrorMessage = stringResource(R.string.playback_error)++ // Controller lifecycle: same SessionToken → PlaybackService connect as the phone.+ DisposableEffect(Unit) {+ val sessionToken = SessionToken(context, ComponentName(context, PlaybackService::class.java))+ val future = MediaController.Builder(context, sessionToken).buildAsync()+ var disposed = false+ future.addListener({+ val c = try {+ future.get()+ } catch (_: java.util.concurrent.CancellationException) {+ null+ } catch (_: Exception) {+ AppMessages.show(playbackErrorMessage)+ null+ }+ if (c == null) return@addListener+ if (disposed) {+ c.stop()+ c.release()+ } else {+ controller = c+ }+ }, MoreExecutors.directExecutor())+ onDispose {+ disposed = true+ controller?.let { it.stop(); it.release() }+ MediaController.releaseFuture(future)+ }+ }++ // Media item: same extras contract (audio URI + itag) the SABR source resolves in-process.+ LaunchedEffect(controller, currentVideoStream, currentAudioStream, videoInfo.name, subtitles) {+ val player = controller ?: return@LaunchedEffect+ val metadata = MediaMetadata.Builder()+ .setTitle(videoInfo.name)+ .setArtist(videoInfo.author)+ .build()+ val item = MediaItem.Builder()+ .setUri(currentVideoStream.url)+ .setMediaMetadata(metadata)+ .setSubtitleConfigurations(+ subtitles.map { sub ->+ MediaItem.SubtitleConfiguration.Builder(sub.url.toUri())+ .setMimeType(sub.mimeType)+ .setLanguage(sub.languageTag)+ .build()+ },+ )+ .build()+ player.setMediaItem(item)+ player.prepare()+ player.play()+ }++ // Transport observer: aspect, cues, playing/buffering into the shared transport.+ DisposableEffect(controller) {+ val player = controller ?: return@DisposableEffect onDispose {}+ CastPlayback.update { it.copy(playing = player.isPlaying) }+ CastPlayback.attachPlayer(player)+ val listener = object : Player.Listener {+ override fun onEvents(player: Player, events: Player.Events) {+ if (events.contains(Player.EVENT_TIMELINE_CHANGED) ||+ events.contains(Player.EVENT_PLAYBACK_STATE_CHANGED)+ ) {+ CastPlayback.update {+ it.copy(+ durationMs = player.duration.coerceAtLeast(0L),+ buffering = player.playbackState == Player.STATE_BUFFERING,+ playing = player.isPlaying,+ )+ }+ }+ }+ override fun onIsPlayingChanged(isPlaying: Boolean) {+ CastPlayback.update { it.copy(playing = isPlaying) }+ }+ override fun onCues(cueGroup: androidx.media3.common.text.CueGroup) {+ cues = cueGroup.cues+ }+ }+ player.addListener(listener)+ onDispose {+ player.removeListener(listener)+ CastPlayback.detachPlayer(player)+ }+ }++ // Position loop + history: same 300ms poll the phone runs (sponsor-block included).+ TvPlayerPositionLoop(ypvm, videoInfo, controller)++ // Subtitle + tempo application.+ LaunchedEffect(controller, selectedSubtitle) {+ val player = controller ?: return@LaunchedEffect+ player.trackSelectionParameters = player.trackSelectionParameters.buildUpon().apply {+ if (selectedSubtitle == null) {+ setTrackTypeDisabled(C.TRACK_TYPE_TEXT, true)+ } else {+ setTrackTypeDisabled(C.TRACK_TYPE_TEXT, false)+ setPreferredTextLanguage(selectedSubtitle!!.languageTag)+ }+ }.build()+ }+ LaunchedEffect(controller, transport.speed) {+ val pitch = transport.speed+ controller?.playbackParameters = PlaybackParameters(transport.speed, pitch)+ }++ // BACK dismisses the topmost overlay first: chapter sheet, then menus, then transport.+ DisposableEffect(showChapters, showQuality, showCaptions, showSpeed, overlayVisible) {+ TvDpadInput.overlayDismiss = {+ when {+ showChapters -> { showChapters = false; true }+ showQuality -> { showQuality = false; true }+ showCaptions -> { showCaptions = false; true }+ showSpeed -> { showSpeed = false; true }+ overlayVisible -> { TvTransportState.hide(); true }+ else -> false+ }+ }+ onDispose {+ if (TvDpadInput.overlayDismiss != null) TvDpadInput.overlayDismiss = null+ }+ }+ DisposableEffect(Unit) {+ TvTransportState.reveal()+ onDispose { TvTransportState.hide() }+ }++ val focusRequester = remember { FocusRequester() }+ TvInitialFocus(focusRequester)++ Box(+ Modifier+ .fillMaxSize()+ .background(Color.Black),+ ) {+ controller?.let { player ->+ PlayerSurface(+ player = player,+ modifier = Modifier+ .fillMaxSize()+ .focusRequester(focusRequester)+ .onFocusChanged { TvDpadInput.playerFocused = it.isFocused },+ surfaceType = SURFACE_TYPE_SURFACE_VIEW,+ )+ } ?: Box(Modifier.fillMaxSize().background(Color.Black))++ if (cues.isNotEmpty()) {+ Column(+ Modifier+ .align(Alignment.BottomCenter)+ .padding(bottom = 120.dp, start = 48.dp, end = 48.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ cues.forEach { cue ->+ cue.text?.let { text ->+ Text(+ text = text.toString(),+ color = Color.White,+ style = MaterialTheme.typography.bodyLarge,+ modifier = Modifier+ .background(Color.Black.copy(alpha = 0.6f))+ .padding(horizontal = 8.dp, vertical = 2.dp),+ )+ }+ }+ }+ }++ if (transport.buffering) {+ CircularProgressIndicator(+ modifier = Modifier.align(Alignment.Center),+ color = Color.White,+ )+ }++ FadeVisibility(visible = overlayVisible) {+ Box(Modifier.fillMaxSize()) {+ TvTransportOverlay(+ title = videoInfo.name,+ author = videoInfo.author,+ hasNext = transport.hasNext,+ hasPrevious = transport.hasPrevious,+ speed = transport.speed,+ modifier = Modifier.align(Alignment.BottomCenter),+ )+ // Focusable option rows above the transport: chapters, quality, captions, speed.+ TvPlayerOptionsRow(+ onChapters = { showChapters = true },+ onQuality = { showQuality = true },+ onCaptions = { showCaptions = true },+ onSpeed = { showSpeed = true },+ hasChapters = segments.isNotEmpty(),+ hasCaptions = subtitles.isNotEmpty(),+ modifier = Modifier.align(Alignment.TopCenter).padding(top = 32.dp),+ )+ }+ }++ if (showChapters) {+ TvChapterSheet(+ segments = segments,+ onSeekTo = { controller?.seekTo(it) },+ onDismiss = { showChapters = false },+ )+ }+ if (showQuality) {+ TvQualitySheet(+ streams = videoStreams,+ current = currentVideoStream,+ onSelect = { currentVideoStream = it; showQuality = false },+ onDismiss = { showQuality = false },+ )+ }+ if (showCaptions) {+ TvCaptionSheet(+ tracks = subtitles,+ selected = selectedSubtitle,+ onSelect = { selectedSubtitle = it; showCaptions = false },+ onDismiss = { showCaptions = false },+ )+ }+ if (showSpeed) {+ TvSpeedSheet(+ current = transport.speed,+ onSelect = { speed ->+ CastPlayback.update { it.copy(speed = speed) }+ showSpeed = false+ },+ onDismiss = { showSpeed = false },+ )+ }++ val volumeFlash by TvTransportState.volumeFlash.collectAsState()+ volumeFlash?.let { level ->+ Box(+ Modifier+ .align(Alignment.TopEnd)+ .padding(32.dp)+ .background(Color.Black.copy(alpha = 0.7f))+ .padding(horizontal = 16.dp, vertical = 8.dp),+ ) {+ Text(+ text = "${(level * 100).toInt()}%",+ color = Color.White,+ style = MaterialTheme.typography.titleMedium,+ )+ }+ }+ }+}++/** The focusable option row: chapters / quality / captions / speed. */+@Composable+private fun TvPlayerOptionsRow(+ onChapters: () -> Unit,+ onQuality: () -> Unit,+ onCaptions: () -> Unit,+ onSpeed: () -> Unit,+ hasChapters: Boolean,+ hasCaptions: Boolean,+ modifier: Modifier = Modifier,+) {+ Row(+ modifier = modifier,+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ ) {+ if (hasChapters) {+ androidx.tv.material3.Button(onClick = onChapters) {+ Text(stringResource(R.string.chapter))+ }+ }+ androidx.tv.material3.Button(onClick = onQuality) {+ Text(stringResource(R.string.label_quality))+ }+ if (hasCaptions) {+ androidx.tv.material3.Button(onClick = onCaptions) {+ Text(stringResource(R.string.label_captions))+ }+ }+ androidx.tv.material3.Button(onClick = onSpeed) {+ Text(stringResource(R.string.label_speed))+ }+ }+}++/** D-pad chapter list: focus a chapter, CENTER/ENTER seeks. Replaces the phone bottom sheet. */+@Composable+internal fun TvChapterSheet(+ segments: List<VideoChapter>,+ onSeekTo: (Long) -> Unit,+ onDismiss: () -> Unit,+ modifier: Modifier = Modifier,+) {+ val context = LocalContext.current+ val transport by CastPlayback.transport.collectAsState()+ val listState = rememberLazyListState()+ val focusRequester = remember { FocusRequester() }+ TvInitialFocus(focusRequester)+ Box(+ modifier+ .fillMaxSize()+ .background(Color.Black.copy(alpha = 0.9f)),+ ) {+ Column(Modifier.fillMaxSize().padding(48.dp)) {+ Row(+ Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(text = stringResource(R.string.chapter), style = MaterialTheme.typography.headlineSmall)+ androidx.tv.material3.Button(onClick = onDismiss, modifier = Modifier.focusRequester(focusRequester)) {+ Text(stringResource(R.string.action_close))+ }+ }+ LazyColumn(state = listState, modifier = Modifier.padding(top = 16.dp)) {+ items(segments, key = { it.time }) { chapter ->+ val index = segments.indexOf(chapter)+ val isCurrent = transport.positionMs >= chapter.time &&+ (segments.getOrNull(index + 1)?.time?.let { transport.positionMs < it } ?: true)+ Surface(+ onClick = { onSeekTo(chapter.time.toLong()); onDismiss() },+ modifier = Modifier+ .fillMaxWidth()+ .padding(vertical = 4.dp),+ ) {+ Row(+ Modifier.padding(12.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ if (!chapter.previewURL.isNullOrEmpty()) {+ AsyncImage(+ model = ImageRequest.Builder(context)+ .data(chapter.previewURL)+ .memoryCacheKey("chapter-${chapter.time}")+ .build(),+ contentDescription = null,+ modifier = Modifier.fillMaxWidth(0.2f),+ )+ }+ Column(Modifier.weight(1f).padding(start = 16.dp)) {+ Text(+ text = chapter.title,+ style = MaterialTheme.typography.titleMedium,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis,+ )+ Text(+ text = DateUtils.formatElapsedTime(chapter.time.toLong() / 1000),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ if (isCurrent) IconCheck()+ }+ }+ }+ }+ }+ }+}++/** D-pad quality list: one focusable row per stream. Replaces the phone dropdown. */+@Composable+internal fun TvQualitySheet(+ streams: List<VideoStream>,+ current: VideoStream,+ onSelect: (VideoStream) -> Unit,+ onDismiss: () -> Unit,+ modifier: Modifier = Modifier,+) {+ TvOptionSheet(title = stringResource(R.string.label_quality), onDismiss = onDismiss, modifier = modifier) {+ items(streams, key = { it.quality + it.height }) { stream ->+ Surface(onClick = { onSelect(stream) }, modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) {+ Row(+ Modifier.padding(12.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(text = stream.quality, style = MaterialTheme.typography.titleMedium)+ if (stream == current) IconCheck()+ }+ }+ }+ }+}++/** D-pad caption list: off + one row per track. Replaces the phone dropdown. */+@Composable+internal fun TvCaptionSheet(+ tracks: List<SubtitleTrack>,+ selected: SubtitleTrack?,+ onSelect: (SubtitleTrack?) -> Unit,+ onDismiss: () -> Unit,+ modifier: Modifier = Modifier,+) {+ TvOptionSheet(title = stringResource(R.string.label_captions), onDismiss = onDismiss, modifier = modifier) {+ item {+ Surface(onClick = { onSelect(null) }, modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) {+ Row(+ Modifier.padding(12.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(text = stringResource(R.string.label_captions_off), style = MaterialTheme.typography.titleMedium)+ if (selected == null) IconCheck()+ }+ }+ }+ items(tracks, key = { it.languageTag + it.url }) { track ->+ Surface(onClick = { onSelect(track) }, modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) {+ Row(+ Modifier.padding(12.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(text = track.displayName, style = MaterialTheme.typography.titleMedium)+ if (track == selected) IconCheck()+ }+ }+ }+ }+}++/** D-pad speed list: the same range the phone offers, nothing the phone cannot do. */+@Composable+internal fun TvSpeedSheet(+ current: Float,+ onSelect: (Float) -> Unit,+ onDismiss: () -> Unit,+ modifier: Modifier = Modifier,+) {+ TvOptionSheet(title = stringResource(R.string.label_speed), onDismiss = onDismiss, modifier = modifier) {+ items(TV_SPEEDS, key = { it }) { speed ->+ Surface(onClick = { onSelect(speed) }, modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) {+ Row(+ Modifier.padding(12.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(text = formatTvSpeedLabel(speed), style = MaterialTheme.typography.titleMedium)+ if (speed == current) IconCheck()+ }+ }+ }+ }+}++/** Shared sheet frame: title + close, focus starts on close, BACK dismisses. */+@Composable+private fun TvOptionSheet(+ title: String,+ onDismiss: () -> Unit,+ modifier: Modifier = Modifier,+ content: androidx.compose.foundation.lazy.LazyListScope.() -> Unit,+) {+ val focusRequester = remember { FocusRequester() }+ TvInitialFocus(focusRequester)+ Box(+ modifier+ .fillMaxSize()+ .background(Color.Black.copy(alpha = 0.9f)),+ ) {+ Column(Modifier.fillMaxSize().padding(48.dp)) {+ Row(+ Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(text = title, style = MaterialTheme.typography.headlineSmall)+ androidx.tv.material3.Button(onClick = onDismiss, modifier = Modifier.focusRequester(focusRequester)) {+ Text(stringResource(R.string.action_close))+ }+ }+ LazyColumn(Modifier.padding(top = 16.dp), content = content)+ }+ }+}++private val TV_SPEEDS = listOf(0.25f, 0.5f, 0.75f, 1f, 1.25f, 1.5f, 1.75f, 2f)++private fun formatTvSpeedLabel(speed: Float): String =+ if (speed % 1f == 0f) "${speed.toInt()}x" else "${speed}x"++/**+ * The 300ms poll loop: transport position, sponsor-block skips, periodic history writes.+ *+ * Mirrors the phone `VideoPlayerPositionLoop` exactly (same interval, same skip-while-sponsor+ * rule, same 5s history cadence) — the only reader difference is that the transport here is+ * also what the TV overlay draws, so the loop is the single writer of `positionMs`.+ */+@Composable+private fun TvPlayerPositionLoop(+ ypvm: YouPipeViewModel,+ videoInfo: VideoInfo,+ controller: MediaController?,+) {+ val sponsorSegments by ypvm.videoState.collectAsState()+ val sponsorBlockEnabled by ypvm.sponsorBlockEnabled.collectAsState()+ val categories by ypvm.sponsorBlockCategories.collectAsState()+ val segments = remember(sponsorSegments.sponsorSegments, categories) {+ sponsorSegments.sponsorSegments.filter { it.category in categories }+ }+ // Persist the final position on dispose — the phone's HistoryPersist equivalent.+ var lastPosition by remember(videoInfo.videoID) { mutableLongStateOf(0L) }+ var lastDuration by remember(videoInfo.videoID) { mutableLongStateOf(0L) }+ DisposableEffect(videoInfo.videoID) {+ onDispose {+ ypvm.upsertHistoryVideo(+ com.vayunmathur.youpipe.data.HistoryVideo.fromVideoData(+ videoInfo.copy(duration = lastDuration),+ lastPosition,+ ),+ )+ }+ }+ androidx.compose.runtime.LaunchedEffect(controller) {+ val player = controller ?: return@LaunchedEffect+ var lastHistoryUpsert = 0L+ while (true) {+ var position = player.currentPosition.coerceAtLeast(0L)+ if (sponsorBlockEnabled) {+ val current = segments.find { position in it.start until it.end }+ if (current != null) {+ player.seekTo(current.end)+ position = current.end+ }+ }+ // A TV scrub preview freezes the loop's write so the bar does not fight the D-pad,+ // the same guard the phone's `dragging` provides against its own seek bar.+ if (TvDpadInput.scrubPreviewMs == null) {+ CastPlayback.update {+ it.copy(+ positionMs = position,+ bufferedMs = player.bufferedPosition.coerceAtLeast(0L),+ )+ }+ }+ lastPosition = position+ lastDuration = player.duration.coerceAtLeast(0L)+ if (player.isPlaying) {+ val now = System.currentTimeMillis()+ if (now - lastHistoryUpsert >= TV_HISTORY_UPSERT_INTERVAL_MS) {+ ypvm.upsertHistoryVideo(+ com.vayunmathur.youpipe.data.HistoryVideo.fromVideoData(+ videoInfo.copy(duration = lastDuration),+ position,+ ),+ )+ lastHistoryUpsert = now+ }+ }+ kotlinx.coroutines.delay(300)+ }+ }+}++private const val TV_HISTORY_UPSERT_INTERVAL_MS = 5_000L
youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvPlaylistDetail.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvPlaylistDetail.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvPlaylistDetail.ktnew file mode 100644index 0000000000..ad86caa8fa--- /dev/null+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvPlaylistDetail.kt@@ -0,0 +1,221 @@+package com.vayunmathur.youpipe.tv++import androidx.activity.compose.BackHandler+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.lazy.grid.GridCells+import androidx.compose.foundation.lazy.grid.items+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid+import androidx.compose.foundation.lazy.grid.rememberLazyGridState+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.derivedStateOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import androidx.tv.material3.Button+import androidx.tv.material3.Checkbox+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.youpipe.R+import com.vayunmathur.youpipe.ui.videoRowState+import com.vayunmathur.youpipe.util.YouPipeViewModel++/**+ * TV playlist detail: videos as a focusable grid with D-pad multiselect + move-mode reorder.+ *+ * The phone combines long-press selection with drag-handle reorder. Neither exists on a TV:+ * selection is a checkbox on each card (same pattern as [TvHistoryPage]), and reorder is the+ * same move-mode as [TvSavedPage] — arm on one row, commit onto another, midpoint positions.+ * The whole playlist deletes from a focused action row (Watch later excluded, as on phone).+ */+@Composable+fun TvPlaylistDetailPage(+ backStack: NavBackStack<TvRoute>,+ ypvm: YouPipeViewModel,+ playlistId: Long,+) {+ val playlist by remember(playlistId) { ypvm.playlistById(playlistId) }+ .collectAsStateWithLifecycle(initialValue = null)+ val itemsFlow = remember(playlistId) { ypvm.playlistItemsFor(playlistId) }+ val playlistItems by itemsFlow.collectAsStateWithLifecycle(initialValue = emptyList())+ val context = LocalContext.current+ val firstFocus = remember { FocusRequester() }++ val mandatory = playlist?.mandatory == true+ val title = when {+ mandatory -> stringResource(R.string.playlist_watch_later)+ else -> playlist?.name.orEmpty()+ }++ val selectedIds = remember { mutableStateListOf<Long>() }+ val isSelectionMode by remember { derivedStateOf { selectedIds.isNotEmpty() } }+ BackHandler(enabled = isSelectionMode) { selectedIds.clear() }++ var movingId by remember { mutableStateOf<Long?>(null) }++ TvInitialFocus(firstFocus)+ val gridState = rememberLazyGridState()+ Column(+ Modifier+ .fillMaxSize()+ .padding(horizontal = 48.dp, vertical = 32.dp),+ ) {+ Text(+ text = if (isSelectionMode) {+ stringResource(R.string.selected_count, selectedIds.size)+ } else {+ title+ },+ style = MaterialTheme.typography.headlineSmall,+ )+ Row(+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier.padding(vertical = 8.dp),+ ) {+ if (isSelectionMode) {+ Button(+ onClick = {+ playlistItems.filter { it.id in selectedIds }+ .forEach { ypvm.playlistOps.removeFromPlaylist(it) }+ selectedIds.clear()+ },+ ) {+ IconDelete()+ }+ Button(onClick = { selectedIds.clear() }) {+ IconClose()+ }+ } else if (!mandatory) {+ Button(+ onClick = {+ playlist?.let { ypvm.playlistOps.deletePlaylist(it) }+ backStack.pop()+ },+ ) {+ IconDelete()+ }+ }+ }+ LazyVerticalGrid(+ columns = GridCells.Fixed(3),+ state = gridState,+ modifier = Modifier.fillMaxSize(),+ verticalArrangement = Arrangement.spacedBy(16.dp),+ horizontalArrangement = Arrangement.spacedBy(16.dp),+ ) {+ items(playlistItems, key = { it.id }) { item ->+ val isSelected = item.id in selectedIds+ val isMoving = movingId == item.id+ Column {+ TvVideoCard(+ row = videoRowState(+ context = context,+ videoInfo = item.videoItem,+ showAuthor = true,+ ),+ onOpen = {+ val moveFrom = movingId+ when {+ moveFrom != null && moveFrom != item.id -> {+ commitTvPlaylistItemMove(ypvm, playlistItems, moveFrom, item.id)+ movingId = null+ }+ isSelectionMode -> {+ if (isSelected) selectedIds.remove(item.id)+ else selectedIds.add(item.id)+ }+ else -> backStack.add(TvRoute.Video(item.videoItem.videoID))+ }+ },+ modifier = if (playlistItems.indexOf(item) == 0) {+ Modifier.focusRequester(firstFocus)+ } else {+ Modifier+ },+ trailingContent = {+ Row(+ verticalAlignment = Alignment.CenterVertically,+ modifier = Modifier.padding(top = 8.dp),+ ) {+ Checkbox(+ checked = isSelected,+ onCheckedChange = {+ if (isSelected) selectedIds.remove(item.id)+ else selectedIds.add(item.id)+ },+ )+ if (playlistItems.size > 1) {+ Button(+ onClick = {+ movingId = if (isMoving) null else item.id+ },+ modifier = Modifier.padding(start = 8.dp),+ ) {+ Text(+ if (isMoving) {+ stringResource(R.string.action_close)+ } else {+ stringResource(R.string.tv_action_move)+ },+ )+ }+ }+ }+ if (isMoving) {+ Text(+ text = stringResource(R.string.tv_move_mode_hint),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.primary,+ )+ }+ },+ )+ }+ }+ }+ }+}++/** Midpoint-position move commit for playlist items — same scheme as the phone's drag onMove. */+private fun commitTvPlaylistItemMove(+ ypvm: YouPipeViewModel,+ ordered: List<com.vayunmathur.youpipe.data.PlaylistItem>,+ fromId: Long,+ toId: Long,+) {+ val fromIdx = ordered.indexOfFirst { it.id == fromId }+ val toIdx = ordered.indexOfFirst { it.id == toId }+ if (fromIdx !in ordered.indices || toIdx !in ordered.indices || fromIdx == toIdx) return+ val mutable = ordered.toMutableList()+ val moved = mutable.removeAt(fromIdx)+ mutable.add(toIdx, moved)+ val prevPos = mutable.getOrNull(toIdx - 1)?.position+ val nextPos = mutable.getOrNull(toIdx + 1)?.position+ val resultPosition = when {+ prevPos == null -> (nextPos ?: 0.0) - 50.0+ nextPos == null -> prevPos + 50.0+ else -> (prevPos + nextPos) / 2.0+ }+ val repositioned = mutable.toMutableList()+ repositioned[toIdx] = moved.copy(position = resultPosition)+ ypvm.playlistOps.reorderPlaylistItems(repositioned)+}diff --git
Diff truncated.