Modern Apps git

← Modern-Apps.git

youpipe: detekt clean (367 tests)

Commit
a4743234c81b13005905cb112053ea1c405f0b03
Author
Vayun Mathur <[email protected]>
When
2026-11-15 01:11 UTC (21 days ago)
Parents
4e103b1
Fix all detekt findings in youpipe by fixing code, not config
(detekt.yml untouched, no baselines added):
- UndocumentedPublicClass: KDoc for the module
  types.
- SubscriptionRepository finished its store split:
  new SubscriptionStore/HistoryStore, by-id flows
  on the stores, repository delegates removed and
  call sites use repository.<store> / ViewModel
  store accessors (TooManyFunctions).
- TV pages decomposed into per-section private
  composables (LongMethod/complexity); unused
  backStack/params removed at call sites;
  TvDpadInput guards restructured; SABR open
  throws via failOpen; recommendation loaders
  share candidatesOrEmpty (narrow @Suppress for
  unchecked extractor failures).
- Tests: fake-player answers split by return
  kind; generic RuntimeException ->
  IllegalStateException; fixture suppressions.
Verified: ./gradlew :youpipe:detekt :youpipe:testDevUnitTest :youpipe:lint
--max-workers=32 all pass (367 unit tests).

Diff

youpipe/src/main/java/com/vayunmathur/youpipe/MainActivity.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/MainActivity.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/MainActivity.ktindex 804de09538..cabfeeb731 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/MainActivity.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/MainActivity.kt@@ -87,6 +87,7 @@ fun rememberIsInPipMode(): Boolean {   +/** Main Activity: a ma activity implementation for main activity. */ class MainActivity : MaActivity() {     private val youPipeViewModel: YouPipeViewModel by viewModels {         YouPipeViewModelFactory(@@ -216,50 +217,66 @@ fun defaultBackStack(key: String?): List<Route> = when (key) {     else -> listOf(Route.Main(TAB_HOME)) // home / unset / unknown } +/** Contract for route. */ @Serializable sealed interface Route: NavKey {+    /** Immutable value describing main; carries initialTab. */     @Serializable     data class Main(val initialTab: Int = 0) : Route +    /** Immutable value describing video page; carries videoID. */     @Serializable     data class VideoPage(val videoID: Long) : Route +    /** Immutable value describing channel page; carries channelID. */     @Serializable     data class ChannelPage(val channelID: String): Route +    /** Immutable value describing subscription videos page; carries category. */     @Serializable     data class SubscriptionVideosPage(val category: String?): Route +    /** Immutable value describing create subscription category; carries id. */     @Serializable     data class CreateSubscriptionCategory(val id: String?): Route +    /** Singleton holding downloads state and operations. */     @Serializable     data object Downloads: Route +    /** Immutable value describing playlist detail; carries playlistId. */     @Serializable     data class PlaylistDetail(val playlistId: Long): Route +    /** Singleton holding create playlist state and operations. */     @Serializable     data object CreatePlaylist: Route +    /** Immutable value describing add to playlist; carries videoID, includeWatchLater. */     @Serializable     data class AddToPlaylist(val videoID: Long, val includeWatchLater: Boolean = true): Route +    /** Immutable value describing add to watch later; carries videoID. */     @Serializable     data class AddToWatchLater(val videoID: Long): Route +    /** Singleton holding settings general state and operations. */     @Serializable     data object SettingsGeneral: Route +    /** Singleton holding settings sponsor block state and operations. */     @Serializable     data object SettingsSponsorBlock: Route +    /** Singleton holding settings recommendations state and operations. */     @Serializable     data object SettingsRecommendations: Route +    /** Singleton holding settings data state and operations. */     @Serializable     data object SettingsData: Route +    /** Singleton holding manage interests state and operations. */     @Serializable     data object ManageInterests: Route }
youpipe/src/main/java/com/vayunmathur/youpipe/YouPipeApplication.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/YouPipeApplication.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/YouPipeApplication.ktindex 59cd66cc2f..fde3dfb559 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/YouPipeApplication.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/YouPipeApplication.kt@@ -12,7 +12,9 @@ import com.vayunmathur.youpipe.util.sabr.LocalDomPoTokenProvider import com.vayunmathur.youpipe.util.youtubeLocalization import org.schabi.newpipe.extractor.NewPipe +/** You Pipe Application: a application implementation for you pipe application. */ class YouPipeApplication : Application() {+    /** Shared constants and helpers for YouPipeApplication. */     companion object {         @JvmStatic         lateinit var appContext: android.content.Context
youpipe/src/main/java/com/vayunmathur/youpipe/data/CachedRelatedVideo.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/CachedRelatedVideo.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/CachedRelatedVideo.ktindex d312e7681c..bf4e412d19 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/CachedRelatedVideo.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/CachedRelatedVideo.kt@@ -10,6 +10,7 @@ import com.vayunmathur.youpipe.ui.VideoInfo import kotlinx.coroutines.flow.Flow import kotlin.time.Instant +/** Immutable value describing cached related video. */ @Entity data class CachedRelatedVideo(     @PrimaryKey(autoGenerate = true) val id: Long = 0,@@ -18,6 +19,7 @@ data class CachedRelatedVideo(     val cachedAt: Instant ) +/** Contract for cached related video dao. */ @Dao interface CachedRelatedVideoDao {     @Upsert
youpipe/src/main/java/com/vayunmathur/youpipe/data/ChannelPreference.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/ChannelPreference.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/ChannelPreference.ktindex 507e5e80c9..7501f5eb48 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/ChannelPreference.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/ChannelPreference.kt@@ -21,6 +21,7 @@ data class ChannelPreference(     val pinned: Boolean = false, ) +/** Contract for channel preference dao. */ @Dao interface ChannelPreferenceDao {     @Query("SELECT * FROM ChannelPreference")
youpipe/src/main/java/com/vayunmathur/youpipe/data/DownloadedVideo.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/DownloadedVideo.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/DownloadedVideo.ktindex 1bd86f70f3..73a82ab45f 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/DownloadedVideo.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/DownloadedVideo.kt@@ -12,6 +12,7 @@ import com.vayunmathur.youpipe.ui.VideoInfo import kotlinx.coroutines.flow.Flow import kotlin.time.Instant +/** Immutable value describing downloaded video. */ @Entity data class DownloadedVideo(     @PrimaryKey override val id: Long, // video id@@ -21,6 +22,7 @@ data class DownloadedVideo(     val timestamp: Instant ): DatabaseItem +/** Contract for downloaded video dao. */ @Dao interface DownloadedVideoDao {     @Query("SELECT * FROM DownloadedVideo")
youpipe/src/main/java/com/vayunmathur/youpipe/data/HistoryStore.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/HistoryStore.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/HistoryStore.ktnew file mode 100644index 0000000000..e0e617f22e--- /dev/null+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/HistoryStore.kt@@ -0,0 +1,39 @@+package com.vayunmathur.youpipe.data++import kotlinx.coroutines.flow.Flow++/** Watch-history and downloaded-video persistence, split out of [SubscriptionRepository]. */+class HistoryStore(+    private val historyVideoDao: HistoryVideoDao,+    private val downloadedVideoDao: DownloadedVideoDao,+) {+    /** The history entry with [id] as a flow. */+    fun historyById(id: Long): Flow<HistoryVideo?> = historyVideoDao.getByIdFlow(id)++    /** The downloaded video with [id] as a flow. */+    fun downloadedById(id: Long): Flow<DownloadedVideo?> = downloadedVideoDao.getByIdFlow(id)++    /** All history entries. */+    suspend fun getAllHistoryVideos(): List<HistoryVideo> = historyVideoDao.getAll()++    /** Inserts or replaces one history entry. */+    suspend fun upsertHistoryVideo(value: HistoryVideo): Long = historyVideoDao.upsert(value)++    /** Inserts or replaces history entries. */+    suspend fun upsertHistoryVideos(values: List<HistoryVideo>) = historyVideoDao.upsertAll(values)++    /** Deletes history entries by id. */+    suspend fun deleteHistoryVideosByIds(ids: List<Long>) = historyVideoDao.deleteByIds(ids)++    /** Deletes one history entry. */+    suspend fun deleteHistoryVideo(value: HistoryVideo) = historyVideoDao.delete(value)++    /** Clears all history. */+    suspend fun clearAllHistory() = historyVideoDao.clearAll()++    /** Inserts or replaces one downloaded video. */+    suspend fun upsertDownloadedVideo(value: DownloadedVideo): Long = downloadedVideoDao.upsert(value)++    /** Deletes one downloaded video. */+    suspend fun deleteDownloadedVideo(value: DownloadedVideo): Int = downloadedVideoDao.delete(value)+}
youpipe/src/main/java/com/vayunmathur/youpipe/data/HistoryVideo.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/HistoryVideo.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/HistoryVideo.ktindex 7dad562e9e..082a0dd566 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/HistoryVideo.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/HistoryVideo.kt@@ -8,6 +8,7 @@ import com.vayunmathur.youpipe.ui.VideoInfo import kotlin.time.Clock import kotlin.time.Instant +/** Immutable value describing history video. */ @Entity data class HistoryVideo(     @PrimaryKey(autoGenerate = true) override val id: Long = 0, // video id@@ -15,6 +16,7 @@ data class HistoryVideo(     @Embedded val videoItem: VideoInfo,     val timestamp: Instant ): DatabaseItem {+    /** Shared constants and helpers for HistoryVideo. */     companion object {         fun fromVideoData(videoInfo: VideoInfo, progress: Long) =             HistoryVideo(videoInfo.videoID, progress, videoInfo, Clock.System.now())
youpipe/src/main/java/com/vayunmathur/youpipe/data/KeywordPreference.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/KeywordPreference.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/KeywordPreference.ktindex d81e031496..60308113e9 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/KeywordPreference.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/KeywordPreference.kt@@ -18,6 +18,7 @@ data class KeywordPreference(     val muted: Boolean = true, ) +/** Contract for keyword preference dao. */ @Dao interface KeywordPreferenceDao {     @Query("SELECT * FROM KeywordPreference")
youpipe/src/main/java/com/vayunmathur/youpipe/data/Playlist.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/Playlist.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/Playlist.ktindex aff258cf4b..5ef2ae9398 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/Playlist.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/Playlist.kt@@ -52,6 +52,7 @@ data class PlaylistItem(     override fun withPosition(position: Double) = copy(position = position) } +/** Contract for playlist dao. */ @Dao interface PlaylistDao {     @Query("SELECT * FROM Playlist")@@ -73,6 +74,7 @@ interface PlaylistDao {     suspend fun delete(value: Playlist): Int } +/** Contract for playlist item dao. */ @Dao interface PlaylistItemDao {     @Query("SELECT * FROM PlaylistItem")
youpipe/src/main/java/com/vayunmathur/youpipe/data/PlaylistStore.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/PlaylistStore.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/PlaylistStore.ktindex 1e727ead04..7a8ba01e3a 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/PlaylistStore.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/PlaylistStore.kt@@ -1,15 +1,24 @@ package com.vayunmathur.youpipe.data +import kotlinx.coroutines.flow.Flow+ /**  * Playlist and playlist-item writes, split from [SubscriptionRepository] (TooManyFunctions cap).  *  * Same package and module; behavior identical. Access via  * [SubscriptionRepository.playlistStore].  */-internal class PlaylistStore(+class PlaylistStore(     private val playlistDao: PlaylistDao,     private val playlistItemDao: PlaylistItemDao, ) {+    /** The playlist with [id] as a flow. */+    fun playlistById(id: Long): Flow<Playlist?> = playlistDao.getByIdFlow(id)++    /** Items of a playlist as a flow. */+    fun playlistItemsFor(playlistId: Long): Flow<List<PlaylistItem>> =+        playlistItemDao.getForPlaylistFlow(playlistId)+     suspend fun getAllPlaylists(): List<Playlist> = playlistDao.getAll()      suspend fun upsertPlaylist(value: Playlist): Long = playlistDao.upsert(value)
youpipe/src/main/java/com/vayunmathur/youpipe/data/RecommendationImpression.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/RecommendationImpression.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/RecommendationImpression.ktindex 1dcb222cd6..d2d2c14496 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/RecommendationImpression.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/RecommendationImpression.kt@@ -24,6 +24,7 @@ data class RecommendationImpression(     val lastShownAt: Instant, ) +/** Contract for recommendation impression dao. */ @Dao interface RecommendationImpressionDao {     @Query("SELECT * FROM RecommendationImpression")
youpipe/src/main/java/com/vayunmathur/youpipe/data/RecommendationPreferences.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/RecommendationPreferences.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/RecommendationPreferences.ktindex a3d3250dfc..fea0eaf84b 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/RecommendationPreferences.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/RecommendationPreferences.kt@@ -36,6 +36,7 @@ data class RecommendationPreferences(     val maxDurationSec: Long = 0, ) +/** Contract for recommendation preferences dao. */ @Dao interface RecommendationPreferencesDao {     @Query("SELECT * FROM RecommendationPreferences WHERE id = 0")
youpipe/src/main/java/com/vayunmathur/youpipe/data/RecommendationStore.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/RecommendationStore.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/RecommendationStore.ktindex fbf5ea448d..d0d1c502b4 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/RecommendationStore.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/RecommendationStore.kt@@ -9,7 +9,7 @@ import kotlin.time.Instant  * Same package and module; behavior identical. Access via  * [SubscriptionRepository.recommendationStore].  */-internal class RecommendationStore(+class RecommendationStore(     private val cachedRelatedVideoDao: CachedRelatedVideoDao,     private val recommendationImpressionDao: RecommendationImpressionDao,     private val recommendationPreferencesDao: RecommendationPreferencesDao,
youpipe/src/main/java/com/vayunmathur/youpipe/data/Subscription.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/Subscription.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/Subscription.ktindex 0b35e9f73a..521b574798 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/Subscription.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/Subscription.kt@@ -5,6 +5,7 @@ import androidx.room3.PrimaryKey import com.vayunmathur.library.util.DatabaseItem import kotlinx.serialization.Serializable +/** Immutable value describing subscription. */ @Serializable @Entity data class Subscription(
youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionCategory.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionCategory.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionCategory.ktindex 162e181f55..8f13c41290 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionCategory.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionCategory.kt@@ -23,6 +23,7 @@ import kotlinx.serialization.Serializable         ),     ], )+/** Immutable value describing subscription category. */ data class SubscriptionCategory(     @ColumnInfo(index = true)     val subscriptionID: Long,@@ -30,6 +31,7 @@ data class SubscriptionCategory(     @PrimaryKey(autoGenerate = true) override val id: Long = 0 ): DatabaseItem +/** Contract for subscription category dao. */ @Dao interface SubscriptionCategoryDao {     @Query("SELECT * FROM SubscriptionCategory")
youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionCategoryStore.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionCategoryStore.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionCategoryStore.ktindex 5e54280a55..6f2ede81a5 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionCategoryStore.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionCategoryStore.kt@@ -1,14 +1,20 @@ package com.vayunmathur.youpipe.data +import kotlinx.coroutines.flow.Flow+ /**  * Subscription-category writes, split from [SubscriptionRepository] (TooManyFunctions cap).  *  * Same package and module; behavior identical. Access via  * [SubscriptionRepository.categoryStore].  */-internal class SubscriptionCategoryStore(+class SubscriptionCategoryStore(     private val subscriptionCategoryDao: SubscriptionCategoryDao, ) {+    /** The subscription category with [id] as a flow. */+    fun subscriptionCategoryById(id: Long): Flow<SubscriptionCategory?> =+        subscriptionCategoryDao.getByIdFlow(id)+     suspend fun replaceCategory(originalCategoryName: String?, categoryName: String, ids: List<Long>) =         subscriptionCategoryDao.replaceCategory(originalCategoryName, categoryName, ids) 
youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionDatabase.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionDatabase.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionDatabase.ktindex 1d8ff586b9..1923141d01 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionDatabase.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionDatabase.kt@@ -136,6 +136,7 @@ val MIGRATION_6_7 = Migration(6, 7) {     it.execSQL("ALTER TABLE `PlaylistItem` ADD COLUMN `isPaid` INTEGER NOT NULL DEFAULT 0") } +/** Contract for history video dao. */ @Dao interface HistoryVideoDao {     @Query("SELECT * FROM HistoryVideo")@@ -163,6 +164,7 @@ interface HistoryVideoDao {     suspend fun clearAll() } +/** Contract for subscription dao. */ @Dao interface SubscriptionDao {     @Query("SELECT * FROM Subscription")@@ -187,6 +189,7 @@ interface SubscriptionDao {     suspend fun delete(value: Subscription): Int } +/** Contract for subscription video dao. */ @Dao interface SubscriptionVideoDao {     @Query("SELECT * FROM SubscriptionVideo")@@ -221,6 +224,7 @@ interface SubscriptionVideoDao {     version = 7,     exportSchema = false, )+/** Subscription Database: a room database implementation for subscription database. */ abstract class SubscriptionDatabase : RoomDatabase() {     abstract fun subscriptionDao(): SubscriptionDao     abstract fun subscriptionVideoDao(): SubscriptionVideoDao@@ -235,6 +239,7 @@ abstract class SubscriptionDatabase : RoomDatabase() {     abstract fun playlistDao(): PlaylistDao     abstract fun playlistItemDao(): PlaylistItemDao +    /** Shared constants and helpers for SubscriptionDatabase. */     companion object : com.vayunmathur.library.util.DatabaseMigrations {         override val migrations: List<Migration> = listOf(             MIGRATION_1_2,
youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionRepository.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionRepository.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionRepository.ktindex eb66f0aee0..66f4d22733 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionRepository.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionRepository.kt@@ -41,23 +41,30 @@ class SubscriptionRepository internal constructor(     private val downloadedVideoDao: DownloadedVideoDao get() = database.downloadedVideoDao()     private val cachedRelatedVideoDao: CachedRelatedVideoDao get() = database.cachedRelatedVideoDao()     private val recommendationImpressionDao: RecommendationImpressionDao get() = database.recommendationImpressionDao()-    private val recommendationPreferencesDao: RecommendationPreferencesDao get() = database.recommendationPreferencesDao()+    private val recommendationPreferencesDao: RecommendationPreferencesDao+        get() = database.recommendationPreferencesDao()     private val channelPreferenceDao: ChannelPreferenceDao get() = database.channelPreferenceDao()     private val keywordPreferenceDao: KeywordPreferenceDao get() = database.keywordPreferenceDao()     private val playlistDao: PlaylistDao get() = database.playlistDao()     private val playlistItemDao: PlaylistItemDao get() = database.playlistItemDao()      /** Category writes (split out: TooManyFunctions cap). Same module; behavior identical. */-    internal val categoryStore by lazy { SubscriptionCategoryStore(subscriptionCategoryDao) }+    val categoryStore by lazy { SubscriptionCategoryStore(subscriptionCategoryDao) }++    /** Subscription reads/writes (split out: TooManyFunctions cap). */+    val subscriptionStore by lazy { SubscriptionStore(subscriptionDao, subscriptionVideoDao) }++    /** History and download reads/writes (split out: TooManyFunctions cap). */+    val historyStore by lazy { HistoryStore(historyVideoDao, downloadedVideoDao) }      /** Playlist writes (split out: TooManyFunctions cap). Same module; behavior identical. */-    internal val playlistStore by lazy { PlaylistStore(playlistDao, playlistItemDao) }+    val playlistStore by lazy { PlaylistStore(playlistDao, playlistItemDao) }      /**      * Recommendation reads/writes (split out: TooManyFunctions cap).      * Same module; behavior identical.      */-    internal val recommendationStore by lazy {+    val recommendationStore by lazy {         RecommendationStore(             cachedRelatedVideoDao,             recommendationImpressionDao,@@ -84,127 +91,10 @@ class SubscriptionRepository internal constructor(     val channelPreferences: Flow<List<ChannelPreference>> get() = channelPreferenceDao.getAllFlow()     val keywordPreferences: Flow<List<KeywordPreference>> get() = keywordPreferenceDao.getAllFlow() -    // By-id flows-    fun historyById(id: Long): Flow<HistoryVideo?> = historyVideoDao.getByIdFlow(id)-    fun downloadedById(id: Long): Flow<DownloadedVideo?> = downloadedVideoDao.getByIdFlow(id)-    fun playlistById(id: Long): Flow<Playlist?> = playlistDao.getByIdFlow(id)-    fun subscriptionById(id: Long): Flow<Subscription?> = subscriptionDao.getByIdFlow(id)-    fun subscriptionVideoById(id: Long): Flow<SubscriptionVideo?> = subscriptionVideoDao.getByIdFlow(id)-    fun subscriptionCategoryById(id: Long): Flow<SubscriptionCategory?> = subscriptionCategoryDao.getByIdFlow(id)-    fun playlistItemsFor(playlistId: Long): Flow<List<PlaylistItem>> = playlistItemDao.getForPlaylistFlow(playlistId)--    // -------------------------------------------------------------------    // Subscription-    // --------------------------------------------------------------------    suspend fun getAllSubscriptions(): List<Subscription> = subscriptionDao.getAll()-    suspend fun upsertSubscription(value: Subscription): Long = subscriptionDao.upsert(value)-    suspend fun upsertSubscriptions(values: List<Subscription>) = subscriptionDao.upsertAll(values)-    suspend fun deleteSubscription(value: Subscription): Int = subscriptionDao.delete(value)-    suspend fun clearAllSubscriptions() = subscriptionDao.clearAll()--    // Category writes live on [categoryStore]; recommendation reads/writes on-    // [recommendationStore]; playlist writes on [playlistStore] (TooManyFunctions cap).-    // Call sites use `repository.<store>.<fn>` directly; behavior is identical.--    // -------------------------------------------------------------------    // SubscriptionVideo-    // --------------------------------------------------------------------    suspend fun getAllSubscriptionVideos(): List<SubscriptionVideo> = subscriptionVideoDao.getAll()-    suspend fun upsertSubscriptionVideos(values: List<SubscriptionVideo>) = subscriptionVideoDao.upsertAll(values)--    // -------------------------------------------------------------------    // Category (delegates to SubscriptionCategoryStore; kept here so existing-    // call sites using `repository.*` keep compiling)-    // --------------------------------------------------------------------    suspend fun replaceCategory(originalCategoryName: String?, categoryName: String, ids: List<Long>) =-        categoryStore.replaceCategory(originalCategoryName, categoryName, ids)--    suspend fun deleteCategory(categoryName: String) = categoryStore.deleteCategory(categoryName)--    suspend fun upsertSubscriptionCategories(items: List<SubscriptionCategory>) =-        categoryStore.upsertSubscriptionCategories(items)--    // -------------------------------------------------------------------    // Playlist (delegates to PlaylistStore)-    // --------------------------------------------------------------------    suspend fun getAllPlaylists(): List<Playlist> = playlistStore.getAllPlaylists()-    suspend fun upsertPlaylist(value: Playlist): Long = playlistStore.upsertPlaylist(value)-    suspend fun upsertPlaylists(values: List<Playlist>) = playlistStore.upsertPlaylists(values)-    suspend fun deletePlaylist(value: Playlist): Int = playlistStore.deletePlaylist(value)-    suspend fun getPlaylistItemsForPlaylist(playlistId: Long): List<PlaylistItem> =-        playlistStore.getPlaylistItemsForPlaylist(playlistId)-    suspend fun upsertPlaylistItem(value: PlaylistItem): Long = playlistStore.upsertPlaylistItem(value)-    suspend fun upsertPlaylistItems(values: List<PlaylistItem>) = playlistStore.upsertPlaylistItems(values)-    suspend fun deletePlaylistItem(value: PlaylistItem): Int = playlistStore.deletePlaylistItem(value)--    // -------------------------------------------------------------------    // Recommendation (delegates to RecommendationStore)-    // --------------------------------------------------------------------    suspend fun getAllCachedRelatedVideos(): List<CachedRelatedVideo> =-        recommendationStore.getAllCachedRelatedVideos()-    suspend fun upsertCachedRelatedVideos(values: List<CachedRelatedVideo>) =-        recommendationStore.upsertCachedRelatedVideos(values)-    suspend fun deleteCachedRelatedOlderThan(cutoff: kotlin.time.Instant) =-        recommendationStore.deleteCachedRelatedOlderThan(cutoff)-    suspend fun getAllRecommendationImpressions(): List<RecommendationImpression> =-        recommendationStore.getAllRecommendationImpressions()-    suspend fun recordRecommendationImpression(-        videoID: Long,-        channelKey: String,-        source: String,-        now: kotlin.time.Instant,-    ) = recommendationStore.recordRecommendationImpression(videoID, channelKey, source, now)-    suspend fun deleteRecommendationImpressionsOlderThan(cutoff: kotlin.time.Instant) =-        recommendationStore.deleteRecommendationImpressionsOlderThan(cutoff)-    suspend fun clearAllRecommendationImpressions() = recommendationStore.clearAllRecommendationImpressions()-    suspend fun getRecommendationPreferences(): RecommendationPreferences? =-        recommendationStore.getRecommendationPreferences()-    suspend fun upsertRecommendationPreferences(value: RecommendationPreferences) =-        recommendationStore.upsertRecommendationPreferences(value)-    suspend fun clearAllRecommendationPreferences() = recommendationStore.clearAllRecommendationPreferences()-    suspend fun getAllChannelPreferences(): List<ChannelPreference> =-        recommendationStore.getAllChannelPreferences()-    suspend fun getChannelPreference(channelKey: String): ChannelPreference? =-        recommendationStore.getChannelPreference(channelKey)-    suspend fun upsertChannelPreference(value: ChannelPreference) =-        recommendationStore.upsertChannelPreference(value)-    suspend fun deleteChannelPreference(channelKey: String) =-        recommendationStore.deleteChannelPreference(channelKey)-    suspend fun clearAllChannelPreferences() = recommendationStore.clearAllChannelPreferences()-    suspend fun getAllKeywordPreferences(): List<KeywordPreference> =-        recommendationStore.getAllKeywordPreferences()-    suspend fun upsertKeywordPreference(value: KeywordPreference) =-        recommendationStore.upsertKeywordPreference(value)-    suspend fun deleteKeywordPreference(keyword: String) =-        recommendationStore.deleteKeywordPreference(keyword)-    suspend fun clearAllKeywordPreferences() = recommendationStore.clearAllKeywordPreferences()--    // -------------------------------------------------------------------    // HistoryVideo-    // --------------------------------------------------------------------    suspend fun getAllHistoryVideos(): List<HistoryVideo> = historyVideoDao.getAll()-    suspend fun upsertHistoryVideo(value: HistoryVideo): Long = historyVideoDao.upsert(value)-    suspend fun upsertHistoryVideos(values: List<HistoryVideo>) = historyVideoDao.upsertAll(values)-    suspend fun deleteHistoryVideosByIds(ids: List<Long>) = historyVideoDao.deleteByIds(ids)-    suspend fun deleteHistoryVideo(value: HistoryVideo) = historyVideoDao.delete(value)-    suspend fun clearAllHistory() = historyVideoDao.clearAll()--    // -------------------------------------------------------------------    // DownloadedVideo-    // --------------------------------------------------------------------    suspend fun upsertDownloadedVideo(value: DownloadedVideo): Long = downloadedVideoDao.upsert(value)-    suspend fun deleteDownloadedVideo(value: DownloadedVideo): Int = downloadedVideoDao.delete(value)--    // (CachedRelatedVideo / RecommendationImpression / RecommendationPreferences /-    // ChannelPreference / KeywordPreference / Playlist / PlaylistItem live on the stores above.)+    // All writes live on the stores above (TooManyFunctions cap); call sites+    // use `repository.<store>.<fn>` directly. Behavior is identical. +    /** Shared constants and helpers for SubscriptionRepository. */     companion object {         @Volatile         private var instance: SubscriptionRepository? = null
youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionStore.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionStore.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionStore.ktnew file mode 100644index 0000000000..949e5eee7d--- /dev/null+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionStore.kt@@ -0,0 +1,37 @@+package com.vayunmathur.youpipe.data++import kotlinx.coroutines.flow.Flow++/** Subscription and subscription-video persistence, split out of [SubscriptionRepository]. */+class SubscriptionStore(+    private val subscriptionDao: SubscriptionDao,+    private val subscriptionVideoDao: SubscriptionVideoDao,+) {+    /** The subscription with [id] as a flow. */+    fun subscriptionById(id: Long): Flow<Subscription?> = subscriptionDao.getByIdFlow(id)++    /** The subscription video with [id] as a flow. */+    fun subscriptionVideoById(id: Long): Flow<SubscriptionVideo?> = subscriptionVideoDao.getByIdFlow(id)++    /** All subscriptions. */+    suspend fun getAllSubscriptions(): List<Subscription> = subscriptionDao.getAll()++    /** Inserts or replaces one subscription. */+    suspend fun upsertSubscription(value: Subscription): Long = subscriptionDao.upsert(value)++    /** Inserts or replaces subscriptions. */+    suspend fun upsertSubscriptions(values: List<Subscription>) = subscriptionDao.upsertAll(values)++    /** Deletes one subscription. */+    suspend fun deleteSubscription(value: Subscription): Int = subscriptionDao.delete(value)++    /** Deletes every subscription. */+    suspend fun clearAllSubscriptions() = subscriptionDao.clearAll()++    /** All subscription videos. */+    suspend fun getAllSubscriptionVideos(): List<SubscriptionVideo> = subscriptionVideoDao.getAll()++    /** Inserts or replaces subscription videos. */+    suspend fun upsertSubscriptionVideos(values: List<SubscriptionVideo>) =+        subscriptionVideoDao.upsertAll(values)+}
youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionVideo.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionVideo.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionVideo.ktindex da5807f575..8854a3ab3a 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionVideo.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/data/SubscriptionVideo.kt@@ -19,6 +19,7 @@ import kotlin.time.Instant         ),     ], )+/** Immutable value describing subscription video. */ data class SubscriptionVideo(     @PrimaryKey(autoGenerate = true) override val id: Long = 0, // video id     val name: String,
youpipe/src/main/java/com/vayunmathur/youpipe/nativeext/NativeExtractor.kt
diff --git a/youpipe/src/main/java/com/vayunmathur/youpipe/nativeext/NativeExtractor.kt b/youpipe/src/main/java/com/vayunmathur/youpipe/nativeext/NativeExtractor.ktindex 0f3845317f..1dd4d2c711 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/nativeext/NativeExtractor.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/nativeext/NativeExtractor.kt@@ -92,6 +92,7 @@ object NativeExtractor {     private const val DEFAULT_GL = "GB" } +/** Native Extractor Exception: a string implementation for native extractor exception. */ class NativeExtractorException(message: String) : Exception(message)  /** Value used wherever YouTube reported no count. */@@ -101,6 +102,7 @@ const val UNKNOWN_COUNT: Long = -1 // Lists // --------------------------------------------------------------------------- +/** Immutable value describing search result. */ @Serializable data class SearchResult(     val items: List<SearchItem> = emptyList(),@@ -111,6 +113,7 @@ data class SearchResult(     val errors: List<String> = emptyList(), ) +/** Immutable value describing items page. */ @Serializable data class ItemsPage(     val items: List<SearchItem> = emptyList(),@@ -118,11 +121,13 @@ data class ItemsPage(     val errors: List<String> = emptyList(), ) +/** Contract for search item. */ @Serializable sealed interface SearchItem {     val url: String     val name: String +    /** Immutable value describing stream. */     @Serializable     @SerialName("STREAM")     data class Stream(@@ -139,6 +144,7 @@ sealed interface SearchItem {         @SerialName("is_short") val isShort: Boolean = false,     ) : SearchItem +    /** Immutable value describing channel. */     @Serializable     @SerialName("CHANNEL")     data class Channel(@@ -151,6 +157,7 @@ sealed interface SearchItem {         val thumbnails: List<Thumbnail> = emptyList(),     ) : SearchItem +    /** Immutable value describing playlist. */     @Serializable     @SerialName("PLAYLIST")     data class Playlist(@@ -162,6 +169,7 @@ sealed interface SearchItem {     ) : SearchItem } +/** Immutable value describing thumbnail; carries url, width, height. */ @Serializable data class Thumbnail(val url: String, val width: Long = 0, val height: Long = 0) @@ -169,6 +177,7 @@ data class Thumbnail(val url: String, val width: Long = 0, val height: Long = 0) // Video playback // --------------------------------------------------------------------------- +/** Kinds of stream kind. */ @Serializable enum class StreamKind {     @SerialName("VIDEO") VIDEO,@@ -177,6 +186,7 @@ enum class StreamKind {     @SerialName("POST_LIVE") POST_LIVE, } +/** Immutable value describing stream info. */ @Serializable data class StreamInfo(     val id: String,@@ -210,6 +220,7 @@ data class StreamInfo(     val errors: List<String> = emptyList(), ) +/** Immutable value describing video stream. */ @Serializable data class VideoStream(     val url: String,@@ -229,6 +240,7 @@ data class VideoStream(     @SerialName("video_only") val videoOnly: Boolean = false, ) +/** Immutable value describing audio stream. */ @Serializable data class AudioStream(     val url: String,@@ -254,6 +266,7 @@ data class AudioStream( // Channel / playlist / comments // --------------------------------------------------------------------------- +/** Immutable value describing channel info. */ @Serializable data class ChannelInfo(     val id: String,@@ -269,6 +282,7 @@ data class ChannelInfo(     val errors: List<String> = emptyList(), ) +/** Immutable value describing playlist info. */ @Serializable data class PlaylistInfo(     val id: String,@@ -284,6 +298,7 @@ data class PlaylistInfo(     val errors: List<String> = emptyList(), ) +/** Immutable value describing comment. */ @Serializable data class Comment(     val id: String = "",@@ -299,6 +314,7 @@ data class Comment(     @SerialName("is_hearted") val isHearted: Boolean = false, ) +/** Immutable value describing comments page. */ @Serializable data class CommentsPage(     val comments: List<Comment> = emptyList(),
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.ktindex ef8241bfa2..f05249344a 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvAddToPlaylist.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvAddToPlaylist.kt@@ -30,6 +30,8 @@ import com.vayunmathur.library.ui.IconCheck import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.youpipe.R+import com.vayunmathur.youpipe.data.Playlist+import com.vayunmathur.youpipe.data.PlaylistItem import com.vayunmathur.youpipe.ui.VideoInfo import com.vayunmathur.youpipe.util.YouPipeViewModel @@ -58,16 +60,7 @@ fun TvAddToPlaylistPage(     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)-        TvScreenHeader(-            title = stringResource(R.string.add_to_playlist),-            actions = {-                TvButton(-                    text = stringResource(R.string.action_close),-                    onClick = { backStack.pop() },-                )-            },-        )+        TvAddToPlaylistCloseHeader(closeFocus = closeFocus, onClose = { backStack.pop() })         return     } @@ -81,94 +74,158 @@ fun TvAddToPlaylistPage(     var newName by remember { mutableStateOf("") }     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)     TvSettingsBody {         Column(Modifier.fillMaxSize()) {-            TvScreenHeader(-                title = stringResource(R.string.add_to_playlist),-                actions = {-                    TvButton(-                        text = stringResource(UiR.string.ok),-                        onClick = ::confirm,-                        primary = true,-                    )-                    TvButton(-                        text = stringResource(UiR.string.cancel),-                        onClick = { backStack.pop() },-                    )+            TvAddToPlaylistHeader(+                onConfirm = {+                    applyStagedMembership(playlists, membership, staged, allItems, video, videoID, ypvm)+                    backStack.pop()+                },+                onCancel = { backStack.pop() },+            )+            TvAddToPlaylistList(+                playlists = playlists, allPlaylists = allPlaylists, staged = staged,+                watchLaterLabel = watchLaterLabel, newName = newName,+                onNewNameChange = { newName = it },+                onToggle = { playlist, checked ->+                    staged = if (checked) staged - playlist.id else staged + playlist.id+                },+                onCreate = {+                    ypvm.playlistOps.createPlaylistAndAddVideo(newName.trim(), video)+                    backStack.pop()                 },             )-            LazyColumn(-                state = rememberLazyListState(),-                modifier = Modifier.fillMaxSize(),-                contentPadding = tvContentPadding(top = 14.dp),-                verticalArrangement = Arrangement.spacedBy(8.dp),-            ) {-            items(playlists, key = { it.id }) { playlist ->-                val checked = playlist.id in staged-                TvListRow(-                    headline = if (playlist.mandatory) watchLaterLabel else playlist.name,-                    trailing = if (checked) {-                        { IconCheck() }-                    } else {-                        null-                    },-                    selected = checked,-                    onClick = {-                        staged = if (checked) staged - playlist.id else staged + playlist.id-                    },-                )-            }-            item(key = "new-playlist") {-                var nameOpen by remember { mutableStateOf(false) }-                if (!nameOpen) {-                    TvListRow(-                        headline = stringResource(R.string.new_playlist),-                        onClick = { nameOpen = true },-                    )+        }+    }+}++private fun applyStagedMembership(+    playlists: List<Playlist>,+    membership: Set<Long>,+    staged: Set<Long>,+    allItems: List<PlaylistItem>,+    video: VideoInfo,+    videoID: Long,+    ypvm: YouPipeViewModel,+) {+    playlists.forEach { playlist ->+        val wasMember = playlist.id in membership+        val nowMember = playlist.id in staged+        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) }+        }+    }+}++@Composable+private fun TvAddToPlaylistCloseHeader(closeFocus: FocusRequester, onClose: () -> Unit) {+    TvInitialFocus(closeFocus)+    TvScreenHeader(+        title = stringResource(R.string.add_to_playlist),+        actions = {+            TvButton(+                text = stringResource(R.string.action_close),+                onClick = onClose,+            )+        },+    )+}++@Composable+private fun TvAddToPlaylistHeader(onConfirm: () -> Unit, onCancel: () -> Unit) {+    TvScreenHeader(+        title = stringResource(R.string.add_to_playlist),+        actions = {+            TvButton(+                text = stringResource(UiR.string.ok),+                onClick = onConfirm,+                primary = true,+            )+            TvButton(+                text = stringResource(UiR.string.cancel),+                onClick = onCancel,+            )+        },+    )+}++@Composable+private fun TvAddToPlaylistList(+    playlists: List<Playlist>,+    allPlaylists: List<Playlist>,+    staged: Set<Long>,+    watchLaterLabel: String,+    newName: String,+    onNewNameChange: (String) -> Unit,+    onToggle: (Playlist, Boolean) -> Unit,+    onCreate: () -> Unit,+) {+    LazyColumn(+        state = rememberLazyListState(),+        modifier = Modifier.fillMaxSize(),+        contentPadding = tvContentPadding(top = 14.dp),+        verticalArrangement = Arrangement.spacedBy(8.dp),+    ) {+        items(playlists, key = { it.id }) { playlist ->+            val checked = playlist.id in staged+            TvListRow(+                headline = if (playlist.mandatory) watchLaterLabel else playlist.name,+                trailing = if (checked) {+                    { IconCheck() }                 } else {-                    val canCreate = newName.isNotBlank() &&-                        allPlaylists.none { it.name == newName.trim() }-                    TvTextField(-                        value = newName,-                        onValueChange = { newName = it },-                        placeholder = stringResource(R.string.label_playlist_name),-                        onSubmit = {-                            if (canCreate) {-                                ypvm.playlistOps.createPlaylistAndAddVideo(newName.trim(), video)-                                backStack.pop()-                            }-                        },-                        modifier = Modifier.fillMaxWidth(),-                    )-                    TvButton(-                        text = stringResource(R.string.new_playlist),-                        onClick = {-                            ypvm.playlistOps.createPlaylistAndAddVideo(newName.trim(), video)-                            backStack.pop()-                        },-                        enabled = canCreate,-                        modifier = Modifier.padding(top = 8.dp),-                    )-                }-            }-            }+                    null+                },+                selected = checked,+                onClick = { onToggle(playlist, checked) },+            )         }+        item(key = "new-playlist") {+            TvNewPlaylistRow(+                newName = newName,+                canCreate = newName.isNotBlank() &&+                    allPlaylists.none { it.name == newName.trim() },+                onNewNameChange = onNewNameChange,+                onCreate = onCreate,+            )+        }+    }+}++@Composable+private fun TvNewPlaylistRow(+    newName: String,+    canCreate: Boolean,+    onNewNameChange: (String) -> Unit,+    onCreate: () -> Unit,+) {+    var nameOpen by remember { mutableStateOf(false) }+    if (!nameOpen) {+        TvListRow(+            headline = stringResource(R.string.new_playlist),+            onClick = { nameOpen = true },+        )+    } else {+        TvTextField(+            value = newName,+            onValueChange = onNewNameChange,+            placeholder = stringResource(R.string.label_playlist_name),+            onSubmit = {+                if (canCreate) {+                    onCreate()+                }+            },+            modifier = Modifier.fillMaxWidth(),+        )+        TvButton(+            text = stringResource(R.string.new_playlist),+            onClick = onCreate,+            enabled = canCreate,+            modifier = Modifier.padding(top = 8.dp),+        )     } }
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.ktindex d4d3c2b2b9..a3f7d9f779 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvChannel.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvChannel.kt@@ -1,5 +1,6 @@ package com.vayunmathur.youpipe.tv +import android.content.Context import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize@@ -28,6 +29,7 @@ import com.vayunmathur.library.tv.TvScreenHeader import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.youpipe.R import com.vayunmathur.youpipe.data.Subscription+import com.vayunmathur.youpipe.ui.ChannelInfo import com.vayunmathur.youpipe.ui.countString import com.vayunmathur.youpipe.util.YouPipeViewModel import com.vayunmathur.youpipe.util.decodeHtml@@ -63,65 +65,100 @@ fun TvChannelPage(     TvInitialFocus(subscribeFocus, channelID)     Column(Modifier.fillMaxSize()) {         channelInfo?.let { info ->-            TvScreenHeader(-                title = info.name.decodeHtml(),-                subtitle = stringResource(-                    R.string.subscribers_count,-                    countString(context, info.subscribers),+            TvChannelHeader(+                info = info,+                subscriptions = subscriptions,+                subscribeFocus = subscribeFocus,+                context = context,+                ypvm = ypvm,+            )+        }+        TvChannelBody(+            channelInfo = channelInfo,+            rows = rows,+            onOpen = { backStack.playVideo(it) },+        )+    }+}++@Composable+private fun TvChannelHeader(+    info: ChannelInfo,+    subscriptions: List<Subscription>,+    subscribeFocus: FocusRequester,+    context: Context,+    ypvm: YouPipeViewModel,+) {+    TvScreenHeader(+        title = info.name.decodeHtml(),+        subtitle = stringResource(+            R.string.subscribers_count,+            countString(context, info.subscribers),+        ),+        actions = {+            val existing = subscriptions.firstOrNull { it.channelID == info.channelID }+            TvButton(+                text = stringResource(+                    if (existing == null) R.string.action_subscribe+                    else R.string.action_unsubscribe,                 ),-                actions = {-                    val existing = subscriptions.firstOrNull { it.channelID == info.channelID }-                    TvButton(-                        text = stringResource(-                            if (existing == null) R.string.action_subscribe-                            else R.string.action_unsubscribe,-                        ),-                        onClick = {-                            if (existing == null) {-                                ypvm.upsertSubscription(-                                    Subscription(-                                        name = info.name,-                                        channelID = info.channelID,-                                        avatarURL = info.avatar,-                                    ),-                                )-                            } else {-                                ypvm.deleteSubscription(existing)-                            }-                        },-                        primary = existing == null,-                        modifier = Modifier.focusRequester(subscribeFocus),-                    )+                onClick = {+                    if (existing == null) {+                        ypvm.upsertSubscription(+                            Subscription(+                                name = info.name,+                                channelID = info.channelID,+                                avatarURL = info.avatar,+                            ),+                        )+                    } else {+                        ypvm.deleteSubscription(existing)+                    }                 },+                primary = existing == null,+                modifier = Modifier.focusRequester(subscribeFocus),+            )+        },+    )+    TvChannelAvatar(info = info, context = context)+}++@Composable+private fun TvChannelAvatar(info: ChannelInfo, context: Context) {+    if (info.avatar.isNotEmpty()) {+        Row(+            Modifier.padding(start = 48.dp, bottom = 8.dp),+            verticalAlignment = Alignment.CenterVertically,+        ) {+            AsyncImage(+                model = ImageRequest.Builder(context)+                    .data(info.avatar)+                    .memoryCacheKey("channel-avatar-${info.channelID}")+                    .build(),+                contentDescription = null,+                modifier = Modifier.tvCircularAvatar(),+                contentScale = ContentScale.Crop,             )-            if (info.avatar.isNotEmpty()) {-                Row(-                    Modifier.padding(start = 48.dp, bottom = 8.dp),-                    verticalAlignment = Alignment.CenterVertically,-                ) {-                    AsyncImage(-                        model = ImageRequest.Builder(context)-                            .data(info.avatar)-                            .memoryCacheKey("channel-avatar-${info.channelID}")-                            .build(),-                        contentDescription = null,-                        modifier = Modifier.tvCircularAvatar(),-                        contentScale = ContentScale.Crop,-                    )-                }-            }         }-        when {-            channelInfo == null -> TvLoading()-            rows.isEmpty() -> TvEmptyState(title = stringResource(R.string.empty_recommendations))-            else -> TvGrid(columns = TV_GRID_COLUMNS, modifier = Modifier.fillMaxSize()) {-                items(rows.size, key = { rows[it].row.videoID }) { index ->-                    val item = rows[index]-                    TvVideoCard(-                        item = item,-                        onOpen = { backStack.playVideo(item.row.videoID) },-                    )-                }+    }+}++@Composable+private fun TvChannelBody(+    channelInfo: ChannelInfo?,+    rows: List<TvVideoRow>,+    onOpen: (Long) -> Unit,+) {+    when {+        channelInfo == null -> TvLoading()+        rows.isEmpty() -> TvEmptyState(title = stringResource(R.string.empty_recommendations))+        else -> TvGrid(columns = TV_GRID_COLUMNS, modifier = Modifier.fillMaxSize()) {+            items(rows.size, key = { rows[it].row.videoID }) { index ->+                val item = rows[index]+                TvVideoCard(+                    item = item,+                    onOpen = { onOpen(item.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.ktindex f07d89a1d5..5725a92409 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvCreateCategory.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvCreateCategory.kt@@ -32,6 +32,7 @@ import com.vayunmathur.library.ui.IconCheck import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.youpipe.R+import com.vayunmathur.youpipe.data.Subscription import com.vayunmathur.youpipe.util.YouPipeViewModel import com.vayunmathur.youpipe.util.decodeHtml import kotlinx.coroutines.launch@@ -69,28 +70,16 @@ fun TvCreateCategoryPage(     TvInitialFocus(nameFocus)     TvSettingsBody {         Column(Modifier.fillMaxSize()) {-            TvScreenHeader(-                title = if (id == null) {-                    stringResource(R.string.title_create_subscription_category)-                } else {-                    stringResource(R.string.title_update_subscription_category)-                },-                actions = {-                    TvButton(-                        text = if (id == null) {-                            stringResource(UiR.string.create)-                        } else {-                            stringResource(R.string.action_update)-                        },-                        onClick = {-                            scope.launch {-                                ypvm.replaceCategory(id, categoryName, selectedSubscriptions.map { it.id })-                                backStack.pop()-                            }-                        },-                        enabled = canConfirm,-                        primary = true,-                    )+            TvCreateCategoryHeader(+                isCreate = id == null,+                canConfirm = canConfirm,+                onConfirm = {+                    scope.launch {+                        ypvm.replaceCategory(+                            id, categoryName, selectedSubscriptions.map { it.id },+                        )+                        backStack.pop()+                    }                 },             )             TvTextField(@@ -100,38 +89,73 @@ fun TvCreateCategoryPage(                 focusRequester = nameFocus,                 modifier = Modifier.fillMaxWidth().padding(start = 48.dp, end = 48.dp, bottom = 8.dp),             )-            LazyColumn(-                state = rememberLazyListState(),-                modifier = Modifier.fillMaxSize(),-                contentPadding = tvContentPadding(),-                verticalArrangement = Arrangement.spacedBy(8.dp),-            ) {-                item(key = "select-label") {-                    androidx.tv.material3.Text(-                        text = stringResource(R.string.label_select_subscriptions),-                        style = androidx.tv.material3.MaterialTheme.typography.titleMedium,-                    )-                }-                items(subscriptions, key = { it.id }) { subscription ->-                    val checked = subscription in selectedSubscriptions-                    TvListRow(-                        headline = subscription.name.decodeHtml(),-                        trailing = if (checked) {-                            { IconCheck() }-                        } else {-                            null-                        },-                        selected = checked,-                        onClick = {-                            selectedSubscriptions = if (checked) {-                                selectedSubscriptions - subscription-                            } else {-                                selectedSubscriptions + subscription-                            }-                        },-                    )-                }-            }+            TvCreateCategoryList(+                subscriptions = subscriptions, selectedSubscriptions = selectedSubscriptions,+                onToggle = { subscription, checked ->+                    selectedSubscriptions = if (checked) {+                        selectedSubscriptions - subscription+                    } else {+                        selectedSubscriptions + subscription+                    }+                },+            )+        }+    }+}++@Composable+private fun TvCreateCategoryHeader(isCreate: Boolean, canConfirm: Boolean, onConfirm: () -> Unit) {+    TvScreenHeader(+        title = if (isCreate) {+            stringResource(R.string.title_create_subscription_category)+        } else {+            stringResource(R.string.title_update_subscription_category)+        },+        actions = {+            TvButton(+                text = if (isCreate) {+                    stringResource(UiR.string.create)+                } else {+                    stringResource(R.string.action_update)+                },+                onClick = onConfirm,+                enabled = canConfirm,+                primary = true,+            )+        },+    )+}++@Composable+private fun TvCreateCategoryList(+    subscriptions: List<Subscription>,+    selectedSubscriptions: List<Subscription>,+    onToggle: (Subscription, Boolean) -> Unit,+) {+    LazyColumn(+        state = rememberLazyListState(),+        modifier = Modifier.fillMaxSize(),+        contentPadding = tvContentPadding(),+        verticalArrangement = Arrangement.spacedBy(8.dp),+    ) {+        item(key = "select-label") {+            androidx.tv.material3.Text(+                text = stringResource(R.string.label_select_subscriptions),+                style = androidx.tv.material3.MaterialTheme.typography.titleMedium,+            )+        }+        items(subscriptions, key = { it.id }) { subscription ->+            val checked = subscription in selectedSubscriptions+            TvListRow(+                headline = subscription.name.decodeHtml(),+                trailing = if (checked) {+                    { IconCheck() }+                } else {+                    null+                },+                selected = checked,+                onClick = { onToggle(subscription, checked) },+            )         }     } }
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.ktindex 240f47fb94..6dda40c493 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvDataSettings.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvDataSettings.kt@@ -26,7 +26,6 @@ import com.vayunmathur.library.tv.TvListRow import com.vayunmathur.library.tv.TvScreenHeader import com.vayunmathur.library.ui.CircularProgressIndicator import com.vayunmathur.library.ui.R as UiR-import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.youpipe.R import com.vayunmathur.youpipe.util.YouPipeViewModel import com.vayunmathur.youpipe.util.exportSubscriptions@@ -42,7 +41,6 @@ import com.vayunmathur.youpipe.util.restoreSubscriptions  */ @Composable fun TvDataSettingsPage(-    backStack: NavBackStack<TvRoute>,     ypvm: YouPipeViewModel, ) {     val isLoading by ypvm.isImporting.collectAsState()@@ -66,65 +64,96 @@ fun TvDataSettingsPage(     Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {         TvScreenHeader(title = stringResource(R.string.settings_data))         TvSettingsBody {-            Column(-                Modifier.padding(start = 48.dp, end = 48.dp, bottom = 44.dp),-                verticalArrangement = Arrangement.spacedBy(8.dp),-            ) {-            if (isLoading) {-                CircularProgressIndicator(progress = { progress })-            }-            Text(-                text = stringResource(R.string.title_history),-                style = MaterialTheme.typography.titleMedium,+            TvDataSettingsRows(+                isLoading = isLoading,+                progress = progress,+                firstFocus = firstFocus,+                onClearClick = { confirmClear = true },+                onExport = { exportLauncher.launch("youpipe_subscriptions.json") },+                onRestore = { restoreLauncher.launch("application/json") },+                onImportNewPipe = { newPipeLauncher.launch("application/json") },+                onImportYouTube = { youtubeLauncher.launch("application/zip") },             )-            TvListRow(-                headline = stringResource(R.string.clear_history),-                onClick = { confirmClear = true },-                modifier = Modifier.focusRequester(firstFocus),-            )-            Text(-                text = stringResource(R.string.label_backup_restore),-                style = MaterialTheme.typography.titleMedium,-            )-            TvListRow(-                headline = stringResource(R.string.label_export_youpipe),-                onClick = { exportLauncher.launch("youpipe_subscriptions.json") },-            )-            TvListRow(-                headline = stringResource(R.string.label_restore_youpipe),-                onClick = { restoreLauncher.launch("application/json") },-            )-            TvListRow(-                headline = stringResource(R.string.label_import_newpipe),-                onClick = { newPipeLauncher.launch("application/json") },-            )-            TvListRow(-                headline = stringResource(R.string.label_import_youtube),-                onClick = { youtubeLauncher.launch("application/zip") },-            )-            }         }     }     if (confirmClear) {-        TvDialog(-            title = stringResource(R.string.clear_history),-            onDismissRequest = { confirmClear = false },-            body = stringResource(R.string.are_you_sure_you_want_to_clear_all_watch),-            buttons = {-                TvButton(-                    text = stringResource(UiR.string.clear),-                    onClick = {-                        ypvm.clearHistory()-                        confirmClear = false-                    },-                    primary = true,-                )-                TvButton(-                    text = stringResource(UiR.string.cancel),-                    onClick = { confirmClear = false },-                )+        TvClearHistoryDialog(+            onDismiss = { confirmClear = false },+            onClear = {+                ypvm.clearHistory()+                confirmClear = false             },-            content = {},         )     } }++@Composable+private fun TvDataSettingsRows(+    isLoading: Boolean,+    progress: Float,+    firstFocus: FocusRequester,+    onClearClick: () -> Unit,+    onExport: () -> Unit,+    onRestore: () -> Unit,+    onImportNewPipe: () -> Unit,+    onImportYouTube: () -> Unit,+) {+    Column(+        Modifier.padding(start = 48.dp, end = 48.dp, bottom = 44.dp),+        verticalArrangement = Arrangement.spacedBy(8.dp),+    ) {+        if (isLoading) {+            CircularProgressIndicator(progress = { progress })+        }+        Text(+            text = stringResource(R.string.title_history),+            style = MaterialTheme.typography.titleMedium,+        )+        TvListRow(+            headline = stringResource(R.string.clear_history),+            onClick = onClearClick,+            modifier = Modifier.focusRequester(firstFocus),+        )+        Text(+            text = stringResource(R.string.label_backup_restore),+            style = MaterialTheme.typography.titleMedium,+        )+        TvListRow(+            headline = stringResource(R.string.label_export_youpipe),+            onClick = onExport,+        )+        TvListRow(+            headline = stringResource(R.string.label_restore_youpipe),+            onClick = onRestore,+        )+        TvListRow(+            headline = stringResource(R.string.label_import_newpipe),+            onClick = onImportNewPipe,+        )+        TvListRow(+            headline = stringResource(R.string.label_import_youtube),+            onClick = onImportYouTube,+        )+    }+}++@Composable+private fun TvClearHistoryDialog(onDismiss: () -> Unit, onClear: () -> Unit) {+    TvDialog(+        title = stringResource(R.string.clear_history),+        onDismissRequest = onDismiss,+        body = stringResource(R.string.are_you_sure_you_want_to_clear_all_watch),+        buttons = {+            TvButton(+                text = stringResource(UiR.string.clear),+                onClick = onClear,+                primary = true,+            )+            TvButton(+                text = stringResource(UiR.string.cancel),+                onClick = onDismiss,+            )+        },+        content = {},+    )+}
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.ktindex 824ab170e2..2563b531b6 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvDownloads.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvDownloads.kt@@ -1,5 +1,6 @@ package com.vayunmathur.youpipe.tv +import android.content.Context import androidx.activity.compose.BackHandler import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize@@ -30,7 +31,9 @@ import com.vayunmathur.library.ui.IconDelete import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.youpipe.R+import com.vayunmathur.youpipe.data.DownloadedVideo import com.vayunmathur.youpipe.util.DownloadManager+import com.vayunmathur.youpipe.util.DownloadStatus import com.vayunmathur.youpipe.util.YouPipeViewModel  /**@@ -69,106 +72,191 @@ fun TvDownloadsPage(      TvInitialFocus(firstFocus)     Column(Modifier.fillMaxSize()) {-        TvScreenHeader(-            title = if (isSelectionMode) {-                stringResource(R.string.selected_count, (selectedIds.size + selectedActiveIds.size).toString())-            } else {-                stringResource(R.string.title_downloads)+        TvDownloadsContent(+            modifier = Modifier.weight(1f),+            activeDownloads = activeDownloads, rows = rows,+            activeTitle = activeTitle, doneTitle = doneTitle,+            selectedIds = selectedIds, selectedActiveIds = selectedActiveIds,+            isSelectionMode = isSelectionMode,+            onDelete = {+                deleteSelectedDownloads(downloadedVideos, selectedIds, selectedActiveIds, context, ypvm)+                selectedIds = emptySet()+                selectedActiveIds = emptySet()             },-            actions = {-                if (isSelectionMode) {-                    TvButton(-                        text = stringResource(UiR.string.delete),-                        onClick = {-                            selectedIds.forEach { id ->-                                downloadedVideos.find { it.id == id }?.let { ypvm.deleteDownloadedVideo(it) }-                            }-                            selectedActiveIds.forEach { id ->-                                DownloadManager.cancelDownload(context, id)-                            }-                            selectedIds = emptySet()-                            selectedActiveIds = emptySet()-                        },-                        icon = { IconDelete() },-                    )-                    TvButton(-                        text = stringResource(UiR.string.cancel),-                        onClick = {-                            selectedIds = emptySet()-                            selectedActiveIds = emptySet()-                        },-                        icon = { IconClose() },-                    )-                }+            onCancelSelection = { selectedIds = emptySet(); selectedActiveIds = emptySet() },+            onToggleActive = { videoID, isSelected ->+                selectedActiveIds = if (isSelected) selectedActiveIds - videoID else selectedActiveIds + videoID             },+            onToggleDone = { id, isSelected ->+                selectedIds = if (isSelected) selectedIds - id else selectedIds + id+            },+            onOpen = { backStack.playVideo(it) },         )-        val activeList = remember(activeDownloads) { activeDownloads.toList() }-        if (rows.isEmpty() && activeList.isEmpty()) {-            TvEmptyState(title = stringResource(R.string.playlist_empty))-            return@Column-        }-        TvGrid(columns = TV_GRID_COLUMNS, modifier = Modifier.fillMaxSize().weight(1f)) {-            if (activeList.isNotEmpty()) {-                tvGridHeader(-                    key = "active-header",-                    title = activeTitle,-                    first = true,+    }+}++private fun deleteSelectedDownloads(+    downloadedVideos: List<DownloadedVideo>,+    selectedIds: Set<Long>,+    selectedActiveIds: Set<Long>,+    context: Context,+    ypvm: YouPipeViewModel,+) {+    selectedIds.forEach { id ->+        downloadedVideos.find { it.id == id }?.let { ypvm.deleteDownloadedVideo(it) }+    }+    selectedActiveIds.forEach { id -> DownloadManager.cancelDownload(context, id) }+}++@Composable+private fun TvDownloadsContent(+    modifier: Modifier = Modifier,+    activeDownloads: Map<Long, DownloadStatus>,+    rows: List<TvVideoRow>,+    activeTitle: String,+    doneTitle: String,+    selectedIds: Set<Long>,+    selectedActiveIds: Set<Long>,+    isSelectionMode: Boolean,+    onDelete: () -> Unit,+    onCancelSelection: () -> Unit,+    onToggleActive: (Long, Boolean) -> Unit,+    onToggleDone: (Long, Boolean) -> Unit,+    onOpen: (Long) -> Unit,+) {+    TvDownloadsHeader(+        isSelectionMode = isSelectionMode,+        selectedCount = selectedIds.size + selectedActiveIds.size,+        onDelete = onDelete,+        onCancelSelection = onCancelSelection,+    )+    val activeList = remember(activeDownloads) { activeDownloads.toList() }+    if (rows.isEmpty() && activeList.isEmpty()) {+        TvEmptyState(title = stringResource(R.string.playlist_empty))+        return+    }+    TvDownloadsGrid(+        modifier = modifier, activeList = activeList, rows = rows,+        activeTitle = activeTitle, doneTitle = doneTitle,+        selectedIds = selectedIds, selectedActiveIds = selectedActiveIds,+        isSelectionMode = isSelectionMode, onToggleActive = onToggleActive,+        onToggleDone = onToggleDone, onOpen = onOpen,+    )+}++@Composable+private fun TvDownloadsHeader(+    isSelectionMode: Boolean,+    selectedCount: Int,+    onDelete: () -> Unit,+    onCancelSelection: () -> Unit,+) {+    TvScreenHeader(+        title = if (isSelectionMode) {+            stringResource(R.string.selected_count, selectedCount.toString())+        } else {+            stringResource(R.string.title_downloads)+        },+        actions = {+            if (isSelectionMode) {+                TvButton(+                    text = stringResource(UiR.string.delete),+                    onClick = onDelete,+                    icon = { IconDelete() },+                )+                TvButton(+                    text = stringResource(UiR.string.cancel),+                    onClick = onCancelSelection,+                    icon = { IconClose() },+                )+            }+        },+    )+}++@Composable+private fun TvDownloadsGrid(+    modifier: Modifier = Modifier,+    activeList: List<Pair<Long, DownloadStatus>>,+    rows: List<TvVideoRow>,+    activeTitle: String,+    doneTitle: String,+    selectedIds: Set<Long>,+    selectedActiveIds: Set<Long>,+    isSelectionMode: Boolean,+    onToggleActive: (Long, Boolean) -> Unit,+    onToggleDone: (Long, Boolean) -> Unit,+    onOpen: (Long) -> Unit,+) {+    TvGrid(columns = TV_GRID_COLUMNS, modifier = Modifier.fillMaxSize().then(modifier)) {+        if (activeList.isNotEmpty()) {+            tvGridHeader(+                key = "active-header",+                title = activeTitle,+                first = true,+            )+            items(activeList.size, key = { index -> "active-${activeList[index].first}" }) { index ->+                val (videoID, status) = activeList[index]+                val isSelected = videoID in selectedActiveIds+                TvActiveDownloadCard(+                    videoID = videoID,+                    status = status,+                    isSelected = isSelected,+                    isSelectionMode = isSelectionMode,+                    onToggle = { onToggleActive(videoID, isSelected) },                 )-                items(activeList.size, key = { index -> "active-${activeList[index].first}" }) { index ->-                    val (videoID, status) = activeList[index]-                    val isSelected = videoID in selectedActiveIds-                    fun toggle() {-                        selectedActiveIds = if (isSelected) {-                            selectedActiveIds - videoID-                        } else {-                            selectedActiveIds + videoID-                        }-                    }-                    TvInfoCard(-                        title = status.videoInfo.name,-                        onClick = { if (isSelectionMode) toggle() },-                        subtitle = "${(status.progress * 100).toInt()}%" +-                            if (isSelected) "  •  ✓" else "",-                        leading = {-                            if (status.videoInfo.thumbnailURL.isNotEmpty()) {-                                AsyncImage(-                                    model = ImageRequest.Builder(context)-                                        .data(status.videoInfo.thumbnailURL)-                                        .memoryCacheKey("dl-thumb-$videoID")-                                        .build(),-                                    contentDescription = null,-                                    modifier = Modifier.fillMaxSize(),-                                    contentScale = ContentScale.Crop,-                                )-                            }-                        },-                        leadingSize = 96.dp,-                        progress = status.progress.toFloat(),-                        onLongClick = ::toggle,-                    )-                }             }-            if (rows.isNotEmpty()) {-                tvGridHeader(-                    key = "done-header",-                    title = doneTitle,-                    first = activeList.isEmpty(),+        }+        if (rows.isNotEmpty()) {+            tvGridHeader(+                key = "done-header",+                title = doneTitle,+                first = activeList.isEmpty(),+            )+            items(rows.size, key = { rows[it].row.videoID }) { index ->+                val item = rows[index]+                val isSelected = item.info.videoID in selectedIds+                TvSelectableCard(+                    item = item,+                    selected = isSelected,+                    inSelectionMode = isSelectionMode,+                    onOpen = { onOpen(item.row.videoID) },+                    onToggleSelect = { onToggleDone(item.info.videoID, isSelected) },                 )-                items(rows.size, key = { rows[it].row.videoID }) { index ->-                    val item = rows[index]-                    val isSelected = item.info.videoID in selectedIds-                    TvSelectableCard(-                        item = item,-                        selected = isSelected,-                        inSelectionMode = isSelectionMode,-                        onOpen = { backStack.playVideo(item.row.videoID) },-                        onToggleSelect = {-                            val id = item.info.videoID-                            selectedIds = if (isSelected) selectedIds - id else selectedIds + id-                        },-                    )-                }             }         }     } }++@Composable+private fun TvActiveDownloadCard(+    videoID: Long,+    status: DownloadStatus,+    isSelected: Boolean,+    isSelectionMode: Boolean,+    onToggle: () -> Unit,+) {+    val context = LocalContext.current+    TvInfoCard(+        title = status.videoInfo.name,+        onClick = { if (isSelectionMode) onToggle() },+        subtitle = "${(status.progress * 100).toInt()}%" ++            if (isSelected) "  •  ✓" else "",+        leading = {+            if (status.videoInfo.thumbnailURL.isNotEmpty()) {+                AsyncImage(+                    model = ImageRequest.Builder(context)+                        .data(status.videoInfo.thumbnailURL)+                        .memoryCacheKey("dl-thumb-$videoID")+                        .build(),+                    contentDescription = null,+                    modifier = Modifier.fillMaxSize(),+                    contentScale = ContentScale.Crop,+                )+            }+        },+        leadingSize = 96.dp,+        progress = status.progress.toFloat(),+        onLongClick = onToggle,+    )+}
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.ktindex eeb9c45c70..b0cf498e6b 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvDpadInput.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvDpadInput.kt@@ -36,24 +36,29 @@ object TvDpadInput {     var sheetOpen: Boolean = false      /** Handle a key before the focus system sees it. Returns true when claimed. */-    fun onKeyEvent(event: KeyEvent): Boolean {-        if (event.keyCode == KeyEvent.KEYCODE_BACK) return handleBack(event)-        if (player() == null) return false-        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-        if (isMediaKey(event.keyCode)) return handleMediaKey(event.keyCode)-        if (sheetOpen) return false-        if (TvTransportState.controlsHidden) return handleWhileHidden(event.keyCode)+    fun onKeyEvent(event: KeyEvent): Boolean = when {+        event.keyCode == KeyEvent.KEYCODE_BACK -> handleBack(event)+        player() == null -> false+        event.action == KeyEvent.ACTION_UP && isScrubKey(event.keyCode) -> handleScrubRelease()+        event.action != KeyEvent.ACTION_DOWN -> false+        isMediaKey(event.keyCode) -> handleMediaKey(event.keyCode)+        sheetOpen -> false+        TvTransportState.controlsHidden -> handleWhileHidden(event.keyCode)+        else -> handleWhileVisible(event.keyCode)+    }++    /** Only a scrub this map started is committed; otherwise the release is not ours. */+    private fun handleScrubRelease(): Boolean {+        if (scrubPreviewMs == null) return false+        commitScrub()+        return true+    }++    private fun handleWhileVisible(keyCode: Int): Boolean {         TvTransportState.reveal()         // A scrub in progress keeps scrubbing even before focus has landed on the seek bar.-        if ((seekFocused || scrubPreviewMs != null) && isScrubKey(event.keyCode)) {-            scrubBy(if (event.keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) SCRUB_STEP_MS else -SCRUB_STEP_MS)+        if ((seekFocused || scrubPreviewMs != null) && isScrubKey(keyCode)) {+            scrubBy(if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) SCRUB_STEP_MS else -SCRUB_STEP_MS)             return true         }         return false
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.ktindex a4ef99593e..9e6dd2e8b0 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvGeneralSettings.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvGeneralSettings.kt@@ -23,7 +23,6 @@ import com.vayunmathur.library.tv.TvListRow import com.vayunmathur.library.tv.TvScreenHeader import com.vayunmathur.library.tv.TvSwitchRow import com.vayunmathur.library.ui.IconCheck-import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.youpipe.R import com.vayunmathur.youpipe.util.YouPipeViewModel @@ -36,7 +35,6 @@ import com.vayunmathur.youpipe.util.YouPipeViewModel  */ @Composable fun TvGeneralSettingsPage(-    backStack: NavBackStack<TvRoute>,     ypvm: YouPipeViewModel, ) {     val deArrowEnabled by ypvm.deArrowEnabled.collectAsState()@@ -61,65 +59,104 @@ fun TvGeneralSettingsPage(                 Modifier.padding(start = 48.dp, end = 48.dp, bottom = 44.dp),                 verticalArrangement = Arrangement.spacedBy(8.dp),             ) {-                Text(-                    text = stringResource(R.string.label_default_page),-                    style = MaterialTheme.typography.titleMedium,+                TvDefaultPageOptions(+                    defaultPage = defaultPage,+                    firstFocus = firstFocus,+                    onSelect = { ypvm.setDefaultPage(it) },                 )-                com.vayunmathur.youpipe.DEFAULT_PAGE_OPTIONS.forEachIndexed { index, (key, labelRes) ->-                    TvListRow(-                        headline = stringResource(labelRes),-                        trailing = if (defaultPage == key) {-                            { IconCheck() }-                        } else {-                            null-                        },-                        onClick = { ypvm.setDefaultPage(key) },-                        modifier = if (index == 0) Modifier.focusRequester(firstFocus) else Modifier,-                    )-                }-                TvSwitchRow(-                    headline = stringResource(R.string.label_dearrow),-                    supporting = stringResource(R.string.label_dearrow_description),-                    checked = deArrowEnabled,-                    onCheckedChange = { ypvm.setDeArrowEnabled(it) },+                TvGeneralSwitches(+                    deArrowEnabled = deArrowEnabled, keepControlsVisible = keepControlsVisible,+                    notificationStyleProgress = notificationStyleProgress,+                    onDeArrowChange = { ypvm.setDeArrowEnabled(it) },+                    onKeepControlsChange = { ypvm.setKeepPlayerControlsVisible(it) },+                    onNotificationStyleChange = { ypvm.setNotificationStyleProgressBar(it) },                 )-                TvSwitchRow(-                    headline = stringResource(R.string.label_keep_controls_visible),-                    supporting = stringResource(R.string.label_keep_controls_visible_description),-                    checked = keepControlsVisible,-                    onCheckedChange = { ypvm.setKeepPlayerControlsVisible(it) },+                TvLanguageOptions(+                    youtubeLanguage = youtubeLanguage,+                    onSelect = { ypvm.setYouTubeLanguage(it) },                 )-                TvSwitchRow(-                    headline = stringResource(R.string.label_notification_style_progress),-                    supporting = 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,-                )-                TvListRow(-                    headline = stringResource(R.string.label_system_default),-                    trailing = if (youtubeLanguage.isBlank()) {-                        { IconCheck() }-                    } else {-                        null-                    },-                    onClick = { ypvm.setYouTubeLanguage("") },-                )-                YouPipeViewModel.Companion.YOUTUBE_LANGUAGES.forEach { (code, name) ->-                    TvListRow(-                        headline = name,-                        trailing = if (youtubeLanguage == code) {-                            { IconCheck() }-                        } else {-                            null-                        },-                        onClick = { ypvm.setYouTubeLanguage(code) },-                    )-                }             }         }     } }++@Composable+private fun TvDefaultPageOptions(+    defaultPage: String,+    firstFocus: FocusRequester,+    onSelect: (String) -> Unit,+) {+    Text(+        text = stringResource(R.string.label_default_page),+        style = MaterialTheme.typography.titleMedium,+    )+    com.vayunmathur.youpipe.DEFAULT_PAGE_OPTIONS.forEachIndexed { index, (key, labelRes) ->+        TvListRow(+            headline = stringResource(labelRes),+            trailing = if (defaultPage == key) {+                { IconCheck() }+            } else {+                null+            },+            onClick = { onSelect(key) },+            modifier = if (index == 0) Modifier.focusRequester(firstFocus) else Modifier,+        )+    }+}++@Composable+private fun TvGeneralSwitches(+    deArrowEnabled: Boolean,+    keepControlsVisible: Boolean,+    notificationStyleProgress: Boolean,+    onDeArrowChange: (Boolean) -> Unit,+    onKeepControlsChange: (Boolean) -> Unit,+    onNotificationStyleChange: (Boolean) -> Unit,+) {+    TvSwitchRow(+        headline = stringResource(R.string.label_dearrow),+        supporting = stringResource(R.string.label_dearrow_description),+        checked = deArrowEnabled,+        onCheckedChange = onDeArrowChange,+    )+    TvSwitchRow(+        headline = stringResource(R.string.label_keep_controls_visible),+        supporting = stringResource(R.string.label_keep_controls_visible_description),+        checked = keepControlsVisible,+        onCheckedChange = onKeepControlsChange,+    )+    TvSwitchRow(+        headline = stringResource(R.string.label_notification_style_progress),+        supporting = stringResource(R.string.label_notification_style_progress_description),+        checked = notificationStyleProgress,+        onCheckedChange = onNotificationStyleChange,+    )+}++@Composable+private fun TvLanguageOptions(youtubeLanguage: String, onSelect: (String) -> Unit) {+    Text(+        text = stringResource(R.string.label_youtube_language),+        style = MaterialTheme.typography.titleMedium,+    )+    TvListRow(+        headline = stringResource(R.string.label_system_default),+        trailing = if (youtubeLanguage.isBlank()) {+            { IconCheck() }+        } else {+            null+        },+        onClick = { onSelect("") },+    )+    YouPipeViewModel.Companion.YOUTUBE_LANGUAGES.forEach { (code, name) ->+        TvListRow(+            headline = name,+            trailing = if (youtubeLanguage == code) {+                { IconCheck() }+            } else {+                null+            },+            onClick = { onSelect(code) },+        )+    }+}
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.ktindex 25b708ddc4..9178658d5e 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvHistory.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvHistory.kt@@ -52,79 +52,123 @@ fun TvHistoryPage(     val firstFocus = remember { FocusRequester() }     TvInitialFocus(firstFocus)     Column(Modifier.fillMaxSize()) {-        TvScreenHeader(-            title = if (inSelectionMode) {-                stringResource(R.string.selected_count, selectedIds.size.toString())-            } else {-                stringResource(R.string.title_history)-            },-            actions = {-                if (inSelectionMode) {-                    TvButton(-                        text = stringResource(UiR.string.delete),-                        onClick = {-                            ypvm.deleteHistoryVideos(selectedIds.toList())-                            selectedIds = emptySet()-                        },-                        icon = { IconDelete() },-                    )-                    TvButton(-                        text = stringResource(UiR.string.cancel),-                        onClick = { selectedIds = emptySet() },-                    )-                } else if (rows.isNotEmpty()) {-                    TvButton(-                        text = stringResource(R.string.clear_history),-                        onClick = { confirmClear = true },-                        icon = { IconDelete() },-                    )-                }+        TvHistoryHeader(+            inSelectionMode = inSelectionMode, selectedCount = selectedIds.size,+            hasRows = rows.isNotEmpty(),+            onDelete = {+                ypvm.deleteHistoryVideos(selectedIds.toList())+                selectedIds = emptySet()             },+            onCancelSelection = { selectedIds = emptySet() },+            onClearClick = { confirmClear = true },         )         if (rows.isEmpty()) {             TvEmptyState(title = stringResource(R.string.empty_recommendations))             return@Column         }-        TvGrid(columns = TV_GRID_COLUMNS, modifier = Modifier.fillMaxSize().weight(1f)) {-            items(rows.size, key = { rows[it].row.videoID }) { index ->-                val item = rows[index]-                val isSelected = item.row.videoID in selectedIds-                TvSelectableCard(-                    item = item,-                    selected = isSelected,-                    inSelectionMode = inSelectionMode,-                    onOpen = { backStack.playVideo(item.row.videoID) },-                    onToggleSelect = {-                        selectedIds = if (isSelected) {-                            selectedIds - item.row.videoID-                        } else {-                            selectedIds + item.row.videoID-                        }-                    },-                    modifier = if (index == 0) Modifier.focusRequester(firstFocus) else Modifier,-                )-            }-        }+        TvHistoryGrid(+            modifier = Modifier.weight(1f), rows = rows, selectedIds = selectedIds,+            inSelectionMode = inSelectionMode, firstFocus = firstFocus,+            onOpen = { backStack.playVideo(it) },+            onToggle = { id, isSelected ->+                selectedIds = if (isSelected) {+                    selectedIds - id+                } else {+                    selectedIds + id+                }+            },+        )     }     if (confirmClear) {-        TvDialog(-            title = stringResource(R.string.clear_history),-            onDismissRequest = { confirmClear = false },-            body = stringResource(R.string.are_you_sure_you_want_to_clear_all_watch),-            buttons = {+        TvClearHistoryDialog(+            onDismiss = { confirmClear = false },+            onClear = {+                ypvm.clearHistory()+                confirmClear = false+            },+        )+    }+}++@Composable+private fun TvHistoryHeader(+    inSelectionMode: Boolean,+    selectedCount: Int,+    hasRows: Boolean,+    onDelete: () -> Unit,+    onCancelSelection: () -> Unit,+    onClearClick: () -> Unit,+) {+    TvScreenHeader(+        title = if (inSelectionMode) {+            stringResource(R.string.selected_count, selectedCount.toString())+        } else {+            stringResource(R.string.title_history)+        },+        actions = {+            if (inSelectionMode) {                 TvButton(-                    text = stringResource(UiR.string.clear),-                    onClick = {-                        ypvm.clearHistory()-                        confirmClear = false-                    },-                    primary = true,+                    text = stringResource(UiR.string.delete),+                    onClick = onDelete,+                    icon = { IconDelete() },                 )                 TvButton(                     text = stringResource(UiR.string.cancel),-                    onClick = { confirmClear = false },+                    onClick = onCancelSelection,                 )-            },-        )+            } else if (hasRows) {+                TvButton(+                    text = stringResource(R.string.clear_history),+                    onClick = onClearClick,+                    icon = { IconDelete() },+                )+            }+        },+    )+}++@Composable+private fun TvHistoryGrid(+    modifier: Modifier = Modifier,+    rows: List<TvVideoRow>,+    selectedIds: Set<Long>,+    inSelectionMode: Boolean,+    firstFocus: FocusRequester,+    onOpen: (Long) -> Unit,+    onToggle: (Long, Boolean) -> Unit,+) {+    TvGrid(columns = TV_GRID_COLUMNS, modifier = Modifier.fillMaxSize().then(modifier)) {+        items(rows.size, key = { rows[it].row.videoID }) { index ->+            val item = rows[index]+            val isSelected = item.row.videoID in selectedIds+            TvSelectableCard(+                item = item,+                selected = isSelected,+                inSelectionMode = inSelectionMode,+                onOpen = { onOpen(item.row.videoID) },+                onToggleSelect = { onToggle(item.row.videoID, isSelected) },+                modifier = if (index == 0) Modifier.focusRequester(firstFocus) else Modifier,+            )+        }     } }++@Composable+private fun TvClearHistoryDialog(onDismiss: () -> Unit, onClear: () -> Unit) {+    TvDialog(+        title = stringResource(R.string.clear_history),+        onDismissRequest = onDismiss,+        body = stringResource(R.string.are_you_sure_you_want_to_clear_all_watch),+        buttons = {+            TvButton(+                text = stringResource(UiR.string.clear),+                onClick = onClear,+                primary = true,+            )+            TvButton(+                text = stringResource(UiR.string.cancel),+                onClick = onDismiss,+            )+        },+    )+}
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.ktindex 405244160c..f30abdbfec 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvHomeFeed.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvHomeFeed.kt@@ -1,6 +1,7 @@ package com.vayunmathur.youpipe.tv  import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.lazy.grid.LazyGridScope import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState@@ -39,16 +40,13 @@ fun TvHomeFeedPage(     val recommendations by ypvm.recommendations.collectAsState()     val recommendationsLoading by ypvm.recommendationsLoading.collectAsState()     val history by ypvm.historyVideos.collectAsState()-     LaunchedEffect(Unit) { ypvm.loadRecommendations() }-     val historyById = remember(history) { history.associate { it.id to it.progress } }     val videos = remember(recommendations) { recommendations.map { it.video } }     val reasons = remember(recommendations) {         recommendations.associate { it.video.videoID to it.reason }     }     val rows = rememberTvVideoRows(videos, ypvm, historyById, reasonsById = reasons)-     val continueRows = rememberTvVideoRows(         videos = remember(history) {             history.sortedByDescending { it.timestamp }.take(TV_CONTINUE_COUNT).map { it.videoItem }@@ -56,76 +54,120 @@ fun TvHomeFeedPage(         ypvm = ypvm,         historyProgressMsById = historyById,     )-     var optionsFor by remember { mutableStateOf<TvVideoRow?>(null) }     val firstFocus = remember { FocusRequester() }-    val continueTitle = stringResource(R.string.tv_shelf_continue)-    val forYouTitle = stringResource(R.string.tv_shelf_for_you)-     if (rows.isEmpty() && !recommendationsLoading) {-        TvEmptyState(-            title = stringResource(R.string.empty_recommendations),-            action = {-                TvButton(-                    text = stringResource(UiR.string.retry),-                    onClick = { ypvm.loadRecommendations() },-                )-            },-        )+        TvHomeEmptyState(onRetry = { ypvm.loadRecommendations() })         return     }     if (rows.isEmpty()) {         TvLoading()         return     }-     TvInitialFocus(firstFocus)-    TvGrid(columns = TV_GRID_COLUMNS, modifier = Modifier.fillMaxSize()) {-        if (continueRows.isNotEmpty()) {-            tvGridHeader(-                key = "continue-header",-                title = continueTitle,-                first = true,+    TvHomeFeedGrid(+        backStack = backStack,+        rows = rows,+        continueRows = continueRows,+        firstFocus = firstFocus,+        onOptions = { optionsFor = it },+    )+    TvHomeOptionsDialog(+        item = optionsFor,+        backStack = backStack,+        ypvm = ypvm,+        onDismiss = { optionsFor = null },+    )+}++@Composable+private fun TvHomeEmptyState(onRetry: () -> Unit) {+    TvEmptyState(+        title = stringResource(R.string.empty_recommendations),+        action = {+            TvButton(+                text = stringResource(UiR.string.retry),+                onClick = onRetry,             )-            items(continueRows.size, key = { continueRows[it].row.videoID }) { index ->-                val item = continueRows[index]-                TvVideoCard(-                    item = item,-                    onOpen = { backStack.playVideo(item.row.videoID) },-                    onLongClick = { optionsFor = item },-                    modifier = if (index == 0) {-                        Modifier.focusRequester(firstFocus)-                    } else {-                        Modifier-                    },-                )-            }-        }+        },+    )+}++@Composable+private fun TvHomeFeedGrid(+    backStack: NavBackStack<TvRoute>,+    rows: List<TvVideoRow>,+    continueRows: List<TvVideoRow>,+    firstFocus: FocusRequester,+    onOptions: (TvVideoRow) -> Unit,+) {+    val continueTitle = stringResource(R.string.tv_shelf_continue)+    val forYouTitle = stringResource(R.string.tv_shelf_for_you)+    TvGrid(columns = TV_GRID_COLUMNS, modifier = Modifier.fillMaxSize()) {+        tvHomeContinueSection(backStack, continueRows, firstFocus, continueTitle, onOptions)         tvGridHeader(             key = "for-you-header",             title = forYouTitle,             first = continueRows.isEmpty(),         )-        items(rows.size, key = { rows[it].row.videoID }) { index ->-            val item = rows[index]-            TvVideoCard(-                item = item,-                onOpen = { backStack.playVideo(item.row.videoID) },-                onLongClick = { optionsFor = item },-                modifier = if (continueRows.isEmpty() && index == 0) {-                    Modifier.focusRequester(firstFocus)-                } else {-                    Modifier-                },-            )-        }+        tvHomeForYouSection(backStack, rows, continueRows, firstFocus, onOptions)     }+} -    optionsFor?.let { item ->-        TvVideoOptionsDialog(+private fun LazyGridScope.tvHomeContinueSection(+    backStack: NavBackStack<TvRoute>,+    continueRows: List<TvVideoRow>,+    firstFocus: FocusRequester,+    continueTitle: String,+    onOptions: (TvVideoRow) -> Unit,+) {+    if (continueRows.isEmpty()) return+    tvGridHeader(key = "continue-header", title = continueTitle, first = true)+    items(continueRows.size, key = { continueRows[it].row.videoID }) { index ->+        val item = continueRows[index]+        TvVideoCard(             item = item,-            onDismiss = { optionsFor = null },             onOpen = { backStack.playVideo(item.row.videoID) },+            onLongClick = { onOptions(item) },+            modifier = if (index == 0) Modifier.focusRequester(firstFocus) else Modifier,+        )+    }+}++private fun LazyGridScope.tvHomeForYouSection(+    backStack: NavBackStack<TvRoute>,+    rows: List<TvVideoRow>,+    continueRows: List<TvVideoRow>,+    firstFocus: FocusRequester,+    onOptions: (TvVideoRow) -> Unit,+) {+    items(rows.size, key = { rows[it].row.videoID }) { index ->+        val item = rows[index]+        TvVideoCard(+            item = item,+            onOpen = { backStack.playVideo(item.row.videoID) },+            onLongClick = { onOptions(item) },+            modifier = if (continueRows.isEmpty() && index == 0) {+                Modifier.focusRequester(firstFocus)+            } else {+                Modifier+            },+        )+    }+}++@Composable+private fun TvHomeOptionsDialog(+    item: TvVideoRow?,+    backStack: NavBackStack<TvRoute>,+    ypvm: YouPipeViewModel,+    onDismiss: () -> Unit,+) {+    item?.let { row ->+        TvVideoOptionsDialog(+            item = row,+            onDismiss = onDismiss,+            onOpen = { backStack.playVideo(row.row.videoID) },             ypvm = ypvm,         )     }
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.ktindex bc30a79a41..00fd7f1074 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvManageInterests.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvManageInterests.kt@@ -6,6 +6,7 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.runtime.Composable@@ -23,7 +24,6 @@ import com.vayunmathur.library.tv.TvInitialFocus import com.vayunmathur.library.tv.TvListRow import com.vayunmathur.library.tv.tvContentPadding import com.vayunmathur.library.ui.R as UiR-import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.youpipe.R import com.vayunmathur.youpipe.util.YouPipeViewModel import com.vayunmathur.youpipe.util.clearChannelPreference@@ -42,14 +42,12 @@ import com.vayunmathur.youpipe.util.unmuteKeyword  */ @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) {@@ -71,8 +69,26 @@ fun TvManageInterestsPage(     val mutedKeywords = remember(keywordPrefs) {         keywordPrefs.filter { it.muted }.map { it.keyword }     }-     TvInitialFocus(firstFocus)+    TvManageInterestsList(+        ypvm = ypvm,+        topChannels = topChannels,+        pinnedKeys = pinnedKeys,+        topKeywords = topKeywords,+        blockedChannels = blockedChannels,+        mutedKeywords = mutedKeywords,+    )+}++@Composable+private fun TvManageInterestsList(+    ypvm: YouPipeViewModel,+    topChannels: List<String>,+    pinnedKeys: Set<String>,+    topKeywords: List<String>,+    blockedChannels: List<String>,+    mutedKeywords: List<String>,+) {     TvSettingsBody {         LazyColumn(             state = rememberLazyListState(),@@ -80,85 +96,110 @@ fun TvManageInterestsPage(             contentPadding = tvContentPadding(top = 28.dp),             verticalArrangement = Arrangement.spacedBy(8.dp),         ) {-        item(key = "interests-title") {-            Text(-                text = stringResource(R.string.title_manage_interests),-                style = MaterialTheme.typography.headlineLarge,-                color = MaterialTheme.colorScheme.onSurface,-            )-        }-        item(key = "ch-header") {-            TvInterestSectionHeader(stringResource(R.string.label_your_channels))-        }-        if (topChannels.isEmpty()) {-            item(key = "ch-empty") {-                TvInterestEmpty(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") {-            TvInterestSectionHeader(stringResource(R.string.label_your_topics))-        }-        if (topKeywords.isEmpty()) {-            item(key = "kw-empty") {-                TvInterestEmpty(stringResource(R.string.label_no_topics))-            }+            tvInterestsTitle()+            tvChannelsSection(ypvm, topChannels, pinnedKeys)+            tvKeywordsSection(ypvm, topKeywords)+            tvBlockedSection(ypvm, blockedChannels)+            tvMutedSection(ypvm, mutedKeywords)         }-        items(topKeywords, key = { "kw-$it" }) { keyword ->-            TvInterestRow(-                label = keyword,-                primaryAction = stringResource(UiR.string.remove),-                onPrimary = { ypvm.removeInterest(keyword = keyword) },-            )-        }-        item(key = "bl-header") {-            TvInterestSectionHeader(stringResource(R.string.label_blocked_channels))-        }-        if (blockedChannels.isEmpty()) {-            item(key = "bl-empty") {-                TvInterestEmpty(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") {-            TvInterestSectionHeader(stringResource(R.string.label_muted_keywords))+    }+}++private fun LazyListScope.tvInterestsTitle() {+    item(key = "interests-title") {+        Text(+            text = stringResource(R.string.title_manage_interests),+            style = MaterialTheme.typography.headlineLarge,+            color = MaterialTheme.colorScheme.onSurface,+        )+    }+}++private fun LazyListScope.tvChannelsSection(+    ypvm: YouPipeViewModel,+    topChannels: List<String>,+    pinnedKeys: Set<String>,+) {+    item(key = "ch-header") {+        TvInterestSectionHeader(stringResource(R.string.label_your_channels))+    }+    if (topChannels.isEmpty()) {+        item(key = "ch-empty") {+            TvInterestEmpty(stringResource(R.string.label_no_channels))         }-        if (mutedKeywords.isEmpty()) {-            item(key = "mk-empty") {-                TvInterestEmpty(stringResource(R.string.label_no_muted_keywords))-            }+    }+    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,+            onPrimary = {+                if (pinned) ypvm.clearChannelPreference(channelKey) else ypvm.pinChannel(channelKey)+            },+            secondaryAction = stringResource(UiR.string.remove),+            onSecondary = { ypvm.removeInterest(channelKey = channelKey) },+        )+    }+}++private fun LazyListScope.tvKeywordsSection(+    ypvm: YouPipeViewModel,+    topKeywords: List<String>,+) {+    item(key = "kw-header") {+        TvInterestSectionHeader(stringResource(R.string.label_your_topics))+    }+    if (topKeywords.isEmpty()) {+        item(key = "kw-empty") {+            TvInterestEmpty(stringResource(R.string.label_no_topics))         }-        items(mutedKeywords, key = { "mk-$it" }) { keyword ->-            TvInterestRow(-                label = keyword,-                primaryAction = stringResource(R.string.action_unmute),-                onPrimary = { ypvm.unmuteKeyword(keyword) },-            )+    }+    items(topKeywords, key = { "kw-$it" }) { keyword ->+        TvInterestRow(+            label = keyword,+            onPrimary = { ypvm.removeInterest(keyword = keyword) },+        )+    }+}++private fun LazyListScope.tvBlockedSection(+    ypvm: YouPipeViewModel,+    blockedChannels: List<String>,+) {+    item(key = "bl-header") {+        TvInterestSectionHeader(stringResource(R.string.label_blocked_channels))+    }+    if (blockedChannels.isEmpty()) {+        item(key = "bl-empty") {+            TvInterestEmpty(stringResource(R.string.label_no_blocked_channels))         }+    }+    items(blockedChannels, key = { "bl-$it" }) { channelKey ->+        TvInterestRow(+            label = channelKey.decodeHtml(),+            onPrimary = { ypvm.clearChannelPreference(channelKey) },+        )+    }+}++private fun LazyListScope.tvMutedSection(+    ypvm: YouPipeViewModel,+    mutedKeywords: List<String>,+) {+    item(key = "mk-header") {+        TvInterestSectionHeader(stringResource(R.string.label_muted_keywords))+    }+    if (mutedKeywords.isEmpty()) {+        item(key = "mk-empty") {+            TvInterestEmpty(stringResource(R.string.label_no_muted_keywords))         }     }+    items(mutedKeywords, key = { "mk-$it" }) { keyword ->+        TvInterestRow(+            label = keyword,+            onPrimary = { ypvm.unmuteKeyword(keyword) },+        )+    } }  @Composable@@ -187,7 +228,6 @@ private fun TvInterestEmpty(text: String) { @Composable private fun TvInterestRow(     label: String,-    primaryAction: String,     onPrimary: () -> Unit,     modifier: Modifier = Modifier,     badge: String? = null,
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.ktindex 63be0855a2..07210d376e 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvNavigation.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvNavigation.kt@@ -53,11 +53,11 @@ fun TvNavigation(ypvm: YouPipeViewModel, initialBackStack: List<TvRoute> = listO         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.SettingsGeneral> { TvGeneralSettingsPage(ypvm) }+        entry<TvRoute.SettingsSponsorBlock> { TvSponsorBlockSettingsPage(ypvm) }         entry<TvRoute.SettingsRecommendations> { TvRecommendationsSettingsPage(backStack, ypvm) }-        entry<TvRoute.SettingsData> { TvDataSettingsPage(backStack, ypvm) }-        entry<TvRoute.ManageInterests> { TvManageInterestsPage(backStack, ypvm) }+        entry<TvRoute.SettingsData> { TvDataSettingsPage(ypvm) }+        entry<TvRoute.ManageInterests> { TvManageInterestsPage(ypvm) }     } } 
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.ktindex f3c56c325f..3bf26091b0 100644--- a/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvPlayer.kt+++ b/youpipe/src/main/java/com/vayunmathur/youpipe/tv/TvPlayer.kt@@ -1,6 +1,7 @@ package com.vayunmathur.youpipe.tv  import android.content.ComponentName+import android.content.Context import android.text.format.DateUtils import android.view.WindowManager import androidx.annotation.OptIn@@ -21,6 +22,7 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableLongStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember@@ -90,19 +92,54 @@ import kotlin.math.min @OptIn(UnstableApi::class) @Composable internal fun TvPlayer(-    ypvm: YouPipeViewModel,-    videoInfo: VideoInfo,-    videoStreams: List<VideoStream>,-    audioStreams: List<AudioStream>,-    subtitles: List<SubtitleTrack>,-    segments: List<VideoChapter>,-    startPositionMs: Long,-    chrome: TvPlayerChrome,+    ypvm: YouPipeViewModel, videoInfo: VideoInfo, videoStreams: List<VideoStream>,+    audioStreams: List<AudioStream>, subtitles: List<SubtitleTrack>, segments: List<VideoChapter>,+    startPositionMs: Long, chrome: TvPlayerChrome, ) {     if (videoStreams.isEmpty()) return     val context = LocalContext.current     val messenger = rememberMessenger()+    TvPlayerKeepScreenOn(context)+    val controllerState = remember { mutableStateOf<MediaController?>(null) }+    var controller by controllerState+    var cues by remember { mutableStateOf<List<Cue>>(emptyList()) }+    var showChapters by remember { mutableStateOf(false) }+    var showQuality by remember { mutableStateOf(false) }+    var showLanguage by remember { mutableStateOf(false) }+    var showCaptions by remember { mutableStateOf(false) }+    var showSpeed by remember { mutableStateOf(false) }+    val overlayVisible by TvTransportState.visible.collectAsState()+    val videoStreamState = rememberTvPlayerVideoStream(videoStreams, context)+    val audioState = rememberTvPlayerAudioState(audioStreams)+    var selectedSubtitle by remember { mutableStateOf<SubtitleTrack?>(null) }+    val transport by CastPlayback.transport.collectAsState()+    val playbackErrorMessage = stringResource(R.string.playback_error)+    val startedState = remember(videoInfo.videoID) { mutableStateOf(false) }+    TvPlayerControllerEffect(controllerState, context, playbackErrorMessage)+    val mediaArgs = TvPlayerMediaArgs(+        controller, videoStreamState.current, audioState.current, videoInfo, subtitles, startPositionMs,+    )+    TvPlayerMediaItemEffect(mediaArgs, startedState)+    TvPlayerTransportObserverEffect(controller) { cues = it }+    TvPlayerPositionLoop(ypvm, videoInfo, controller)+    TvPlayerTrackAndSpeedEffects(controller, selectedSubtitle, transport.speed)+    val sheets = TvPlayerSheetState(+        showChapters, { showChapters = it }, showQuality, { showQuality = it }, showLanguage,+        { showLanguage = it }, showCaptions, { showCaptions = it }, showSpeed, { showSpeed = it },+    )+    TvPlayerOverlayDismissEffects(sheets, overlayVisible)+    val focusRequester = remember { FocusRequester() }+    TvInitialFocus(focusRequester)+    val overlayArgs = TvPlayerOverlayArgs(+        ypvm, videoInfo, videoStreams, subtitles, segments, transport, cues, overlayVisible, controller,+        audioState.entries, audioState.language, audioState.onLanguage, selectedSubtitle,+        { selectedSubtitle = it }, videoStreamState.current, videoStreamState.onCurrent, sheets, chrome,+    )+    TvPlayerContent(controller, focusRequester, overlayArgs)+} +@Composable+private fun TvPlayerKeepScreenOn(context: Context) {     // Keep the screen on while the player is composed — same DisposableEffect pattern     // as the phone's VideoPlayerViewState.     DisposableEffect(Unit) {@@ -112,22 +149,36 @@ internal fun TvPlayer(             activity.window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)         }     }+} -    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 showLanguage by remember { mutableStateOf(false) }-    var showCaptions by remember { mutableStateOf(false) }-    var showSpeed by remember { mutableStateOf(false) }-    val overlayVisible by TvTransportState.visible.collectAsState()+private data class TvPlayerVideoStreamState(+    val current: VideoStream,+    val onCurrent: (VideoStream) -> Unit,+) +@Composable+private fun rememberTvPlayerVideoStream(+    videoStreams: List<VideoStream>,+    context: Context,+): TvPlayerVideoStreamState {     val deviceHeightPx = remember(context) {         context.resources.displayMetrics.let { min(it.widthPixels, it.heightPixels) }     }     var currentVideoStream by remember(videoStreams) {         mutableStateOf(selectDefaultVideoStream(videoStreams, deviceHeightPx) ?: videoStreams.first())     }+    return TvPlayerVideoStreamState(currentVideoStream) { currentVideoStream = it }+}++private data class TvPlayerAudioState(+    val entries: List<Pair<String, String>>,+    val language: String,+    val onLanguage: (String) -> Unit,+    val current: AudioStream?,+)++@Composable+private fun rememberTvPlayerAudioState(audioStreams: List<AudioStream>): TvPlayerAudioState {     // TV keeps the phone's audio rule: highest-quality opus for the selected language.     // Use displayName for language UI when available, fallback to language code (same as phone).     val languageEntries = remember(audioStreams) {@@ -150,10 +201,15 @@ internal fun TvPlayer(     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)+    return TvPlayerAudioState(languageEntries, language, { language = it }, currentAudioStream)+} +@Composable+private fun TvPlayerControllerEffect(+    controllerState: MutableState<MediaController?>,+    context: Context,+    playbackErrorMessage: String,+) {     // Controller lifecycle: same SessionToken → PlaybackService connect as the phone.     DisposableEffect(Unit) {         val sessionToken = SessionToken(context, ComponentName(context, PlaybackService::class.java))@@ -173,31 +229,42 @@ internal fun TvPlayer(                 c.stop()                 c.release()             } else {-                controller = c+                controllerState.value = c             }         }, MoreExecutors.directExecutor())         onDispose {             disposed = true-            controller?.let { it.stop(); it.release() }+            controllerState.value?.let { it.stop(); it.release() }             MediaController.releaseFuture(future)         }     }+}++private data class TvPlayerMediaArgs(+    val controller: MediaController?,+    val videoStream: VideoStream,+    val audioStream: AudioStream?,+    val videoInfo: VideoInfo,+    val subtitles: List<SubtitleTrack>,+    val startPositionMs: Long,+) +@Composable+private fun TvPlayerMediaItemEffect(args: TvPlayerMediaArgs, startedState: MutableState<Boolean>) {     // Media item: same extras contract (audio URI + itag) the SABR source resolves in-process.     // The first load starts at the resume point; a later reload (quality, language, captions)     // keeps the current position instead of restarting the video.-    var started by remember(videoInfo.videoID) { mutableStateOf(false) }-    LaunchedEffect(controller, currentVideoStream, currentAudioStream, videoInfo.name, subtitles) {-        val player = controller ?: return@LaunchedEffect+    LaunchedEffect(args.controller, args.videoStream, args.audioStream, args.videoInfo.name, args.subtitles) {+        val player = args.controller ?: return@LaunchedEffect         val metadata = MediaMetadata.Builder()-            .setTitle(videoInfo.name)-            .setArtist(videoInfo.author)+            .setTitle(args.videoInfo.name)+            .setArtist(args.videoInfo.author)             .build()         val item = MediaItem.Builder()-            .setUri(currentVideoStream.url)+            .setUri(args.videoStream.url)             .setMediaMetadata(metadata)             .setSubtitleConfigurations(-                subtitles.map { sub ->+                args.subtitles.map { sub ->                     MediaItem.SubtitleConfiguration.Builder(sub.url.toUri())                         .setMimeType(sub.mimeType)                         .setLanguage(sub.languageTag)@@ -205,13 +272,16 @@ internal fun TvPlayer(                 },             )             .build()-        val startAt = if (started) player.currentPosition.coerceAtLeast(0L) else startPositionMs-        started = true+        val startAt = if (startedState.value) player.currentPosition.coerceAtLeast(0L) else args.startPositionMs+        startedState.value = true         player.setMediaItem(item, startAt)         player.prepare()         player.play()     }+} +@Composable+private fun TvPlayerTransportObserverEffect(controller: MediaController?, onCues: (List<Cue>) -> Unit) {     // Transport observer: aspect, cues, playing/buffering into the shared transport.     DisposableEffect(controller) {         val player = controller ?: return@DisposableEffect onDispose {}@@ -231,11 +301,13 @@ internal fun TvPlayer(                     }                 }             }+             override fun onIsPlayingChanged(isPlaying: Boolean) {                 CastPlayback.update { it.copy(playing = isPlaying) }             }+             override fun onCues(cueGroup: androidx.media3.common.text.CueGroup) {-                cues = cueGroup.cues+                onCues(cueGroup.cues)             }         }         player.addListener(listener)@@ -244,10 +316,14 @@ internal fun TvPlayer(             CastPlayback.detachPlayer(player)         }     }+} -    // Position loop + history: same 300ms poll the phone runs (sponsor-block included).-    TvPlayerPositionLoop(ypvm, videoInfo, controller)-+@Composable+private fun TvPlayerTrackAndSpeedEffects(+    controller: MediaController?,+    selectedSubtitle: SubtitleTrack?,+    speed: Float,+) {     // Subtitle + tempo application.     LaunchedEffect(controller, selectedSubtitle) {         val player = controller ?: return@LaunchedEffect@@ -260,25 +336,45 @@ internal fun TvPlayer(             }         }.build()     }-    LaunchedEffect(controller, transport.speed) {-        val pitch = transport.speed-        controller?.playbackParameters = PlaybackParameters(transport.speed, pitch)+    LaunchedEffect(controller, speed) {+        val pitch = speed+        controller?.playbackParameters = PlaybackParameters(speed, pitch)     }+} +private data class TvPlayerSheetState(+    val showChapters: Boolean,+    val onShowChapters: (Boolean) -> Unit,+    val showQuality: Boolean,+    val onShowQuality: (Boolean) -> Unit,+    val showLanguage: Boolean,+    val onShowLanguage: (Boolean) -> Unit,+    val showCaptions: Boolean,+    val onShowCaptions: (Boolean) -> Unit,+    val showSpeed: Boolean,+    val onShowSpeed: (Boolean) -> Unit,+)++@Composable+private fun TvPlayerOverlayDismissEffects(sheets: TvPlayerSheetState, overlayVisible: Boolean) {     // BACK dismisses the topmost overlay first: option sheets, then the controls.-    val anySheet = showChapters || showQuality || showLanguage || showCaptions || showSpeed+    val anySheet = sheets.showChapters || sheets.showQuality || sheets.showLanguage ||+        sheets.showCaptions || sheets.showSpeed     DisposableEffect(anySheet) {         TvDpadInput.sheetOpen = anySheet         onDispose { TvDpadInput.sheetOpen = false }     }-    DisposableEffect(showChapters, showQuality, showLanguage, showCaptions, showSpeed, overlayVisible) {+    DisposableEffect(+        sheets.showChapters, sheets.showQuality, sheets.showLanguage, sheets.showCaptions,+        sheets.showSpeed, overlayVisible,+    ) {         TvDpadInput.overlayDismiss = {             when {-                showChapters -> { showChapters = false; true }-                showQuality -> { showQuality = false; true }-                showLanguage -> { showLanguage = false; true }-                showCaptions -> { showCaptions = false; true }-                showSpeed -> { showSpeed = false; true }+                sheets.showChapters -> { sheets.onShowChapters(false); true }+                sheets.showQuality -> { sheets.onShowQuality(false); true }+                sheets.showLanguage -> { sheets.onShowLanguage(false); true }+                sheets.showCaptions -> { sheets.onShowCaptions(false); true }+                sheets.showSpeed -> { sheets.onShowSpeed(false); true }                 overlayVisible -> { TvTransportState.hide(); true }                 else -> false             }@@ -291,56 +387,68 @@ internal fun TvPlayer(         TvTransportState.reveal()         onDispose { TvTransportState.hide() }     }+} -    val focusRequester = remember { FocusRequester() }-    TvInitialFocus(focusRequester)+private data class TvPlayerOverlayArgs(+    val ypvm: YouPipeViewModel,+    val videoInfo: VideoInfo,+    val videoStreams: List<VideoStream>,+    val subtitles: List<SubtitleTrack>,+    val segments: List<VideoChapter>,+    val transport: CastPlayback.Transport,+    val cues: List<Cue>,+    val overlayVisible: Boolean,+    val controller: MediaController?,+    val languageEntries: List<Pair<String, String>>,+    val language: String,+    val onLanguage: (String) -> Unit,+    val selectedSubtitle: SubtitleTrack?,+    val onSubtitle: (SubtitleTrack?) -> Unit,+    val currentVideoStream: VideoStream,+    val onVideoStream: (VideoStream) -> Unit,+    val sheets: TvPlayerSheetState,+    val chrome: TvPlayerChrome,+)++@OptIn(UnstableApi::class)+@Composable+private fun TvPlayerSurface(controller: MediaController?, focusRequester: FocusRequester) {+    controller?.let { player ->+        PlayerSurface(+            player = player,+            modifier = Modifier+                .fillMaxSize()+                .focusRequester(focusRequester)+                .focusable(),+            surfaceType = SURFACE_TYPE_SURFACE_VIEW,+        )+    } ?: Box(Modifier.fillMaxSize().background(Color.Black))+} +@Composable+private fun TvPlayerContent(+    controller: MediaController?,+    focusRequester: FocusRequester,+    args: TvPlayerOverlayArgs,+) {     Box(         Modifier             .fillMaxSize()             .background(Color.Black),     ) {-        controller?.let { player ->-            PlayerSurface(-                player = player,-                modifier = Modifier-                    .fillMaxSize()-                    .focusRequester(focusRequester)-                    .focusable(),-                surfaceType = SURFACE_TYPE_SURFACE_VIEW,-            )-        } ?: Box(Modifier.fillMaxSize().background(Color.Black))-+        TvPlayerSurface(controller, focusRequester)         TvPlayerOverlays(-            ypvm = ypvm,-            videoInfo = videoInfo,-            videoStreams = videoStreams,-            audioStreams = audioStreams,-            subtitles = subtitles,-            segments = segments,-            transport = transport,-            cues = cues,-            overlayVisible = overlayVisible,-            controller = controller,-            languageEntries = languageEntries,-            language = language,-            onLanguage = { language = it },-            selectedSubtitle = selectedSubtitle,-            onSubtitle = { selectedSubtitle = it },-            currentVideoStream = currentVideoStream,-            onVideoStream = { currentVideoStream = it },-            showChapters = showChapters,-            onShowChapters = { showChapters = it },-            sh

Diff truncated.