StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
feat: Implement ProviderTextField composable for enhanced user input handling
David Nashashca363c16c36c
diff --git a/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.ktindex e8431442..09f396d0 100644--- a/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt+++ b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt@@ -56,305 +56,6 @@ import kotlinx.coroutines.launchimport kotlinx.coroutines.suspendCancellableCoroutine-private const val PLAYER_REQUEST_KEY = "player_request"-internal const val MOVIE_DETAIL_PRESENTATION_HINT_KEY = "movie_detail_presentation_hint"-internal const val SERIES_DETAIL_PRESENTATION_HINT_KEY = "series_detail_presentation_hint"-private const val TAG = "AppNavigation"--private fun requiresResolvedStartupTarget(landingDestination: AppLandingDestination): Boolean =- landingDestination == AppLandingDestination.FIRST_FAVORITE_LIVE ||- landingDestination == AppLandingDestination.LAST_WATCHED_LIVE--internal fun resolveCatalogRoute(- layout: CatalogLayout?,- requestedRoute: String,- lastSplitCatalogType: ContentType,- splitPreferenceReady: Boolean-): String = when {- layout != CatalogLayout.SPLIT && requestedRoute in setOf(Routes.MOVIES, Routes.SERIES) -> Routes.VOD- layout == CatalogLayout.SPLIT && requestedRoute == Routes.VOD && splitPreferenceReady ->- if (lastSplitCatalogType == ContentType.SERIES) Routes.SERIES else Routes.MOVIES- else -> requestedRoute-}--data class PlayerNavigationRequest(- val streamUrl: String,- val title: String,- val channelId: String? = null,- val internalId: Long = -1L,- val categoryId: Long? = null,- val providerId: Long? = null,- val isVirtual: Boolean = false,- val combinedProfileId: Long? = null,- val combinedSourceFilterProviderId: Long? = null,- val contentType: String = "LIVE",- val artworkUrl: String? = null,- val archiveStartMs: Long? = null,- val archiveEndMs: Long? = null,- val archiveTitle: String? = null,- val returnRoute: String? = null,- val seriesId: Long? = null,- val seasonNumber: Int? = null,- val episodeNumber: Int? = null,- val episodeId: Long? = null-) : Serializable--object Routes {- const val PROVIDER_SETUP = "provider_setup?providerId={providerId}&importUri={importUri}"- const val HOME = "home"- const val LIVE_TV = "live_tv"- const val LIVE_TV_DESTINATION = "live_tv?categoryId={categoryId}"- const val MOVIES = "movies"- const val SERIES = "series"- const val VOD = "vod"- const val DOWNLOADS = "downloads"- const val EPG = "epg"- const val EPG_DESTINATION = "epg?categoryId={categoryId}&anchorTime={anchorTime}&favoritesOnly={favoritesOnly}"- const val SETTINGS = "settings"- const val SETTINGS_DESTINATION = "settings?backupUri={backupUri}"- const val PLUGINS = "plugins"- const val PLAYER = "player"- const val SEARCH = "search"- const val SEARCH_DESTINATION = "search?query={query}"- const val MOVIE_DETAIL = "movie_detail/{movieId}?returnRoute={returnRoute}"- const val SERIES_DETAIL = "series_detail/{seriesId}?returnRoute={returnRoute}"- const val WELCOME = "welcome"- const val PARENTAL_CONTROL_GROUPS = "parental_control_groups/{providerId}"- const val MULTI_VIEW = "multi_view"--- fun providerSetup(providerId: Long? = null, importUri: String? = null): String {- val encodedImportUri = Uri.encode(importUri ?: "")- return "provider_setup?providerId=${providerId ?: -1L}&importUri=$encodedImportUri"- }- fun liveTv(categoryId: Long? = null) = if (categoryId == null) LIVE_TV else "$LIVE_TV?categoryId=$categoryId"- fun epg(categoryId: Long? = null, anchorTime: Long? = null, favoritesOnly: Boolean? = null): String {- val resolvedCategoryId = categoryId ?: -1L- val resolvedAnchorTime = anchorTime ?: -1L- val resolvedFavoritesOnly = favoritesOnly ?: false- return "$EPG?categoryId=$resolvedCategoryId&anchorTime=$resolvedAnchorTime&favoritesOnly=$resolvedFavoritesOnly"- }-- fun livePlayer(- channel: Channel,- categoryId: Long? = channel.categoryId,- providerId: Long? = channel.providerId,- isVirtual: Boolean = false,- combinedProfileId: Long? = null,- combinedSourceFilterProviderId: Long? = null,- returnRoute: String? = null- ): PlayerNavigationRequest {- val effectiveCategoryId = categoryId ?: ChannelRepository.ALL_CHANNELS_ID- return player(- streamUrl = channel.streamUrl,- title = channel.name,- channelId = channel.epgChannelId,- internalId = channel.id,- categoryId = effectiveCategoryId,- providerId = providerId,- isVirtual = isVirtual,- combinedProfileId = combinedProfileId,- combinedSourceFilterProviderId = combinedSourceFilterProviderId,- contentType = "LIVE",- returnRoute = returnRoute- )- }-- fun moviePlayer(movie: Movie): PlayerNavigationRequest {- return player(- streamUrl = movie.streamUrl,- title = movie.name,- internalId = movie.id,- categoryId = movie.categoryId,- providerId = movie.providerId,- contentType = "MOVIE",- artworkUrl = movie.posterUrl ?: movie.backdropUrl- )- }-- fun episodePlayer(episode: Episode): PlayerNavigationRequest {- return player(- streamUrl = episode.streamUrl,- title = "${episode.title} - S${episode.seasonNumber}E${episode.episodeNumber}",- internalId = episode.id,- providerId = episode.providerId,- contentType = "SERIES_EPISODE",- artworkUrl = episode.coverUrl,- seriesId = episode.seriesId.takeIf { it > 0L },- seasonNumber = episode.seasonNumber,- episodeNumber = episode.episodeNumber,- episodeId = episode.episodeId.takeIf { it > 0L }- )- }-- fun search(query: String? = null): String =- if (query.isNullOrBlank()) SEARCH else "$SEARCH?query=${Uri.encode(query)}"-- fun settings(backupUri: String? = null): String =- if (backupUri.isNullOrBlank()) SETTINGS else "$SETTINGS?backupUri=${Uri.encode(backupUri)}"-- fun player(- streamUrl: String,- title: String,- channelId: String? = null,- internalId: Long = -1L,- categoryId: Long? = null,- providerId: Long? = null,- isVirtual: Boolean = false,- combinedProfileId: Long? = null,- combinedSourceFilterProviderId: Long? = null,- contentType: String = "LIVE",- artworkUrl: String? = null,- archiveStartMs: Long? = null,- archiveEndMs: Long? = null,- archiveTitle: String? = null,- returnRoute: String? = null,- seriesId: Long? = null,- seasonNumber: Int? = null,- episodeNumber: Int? = null,- episodeId: Long? = null- ): PlayerNavigationRequest {- return PlayerNavigationRequest(- streamUrl = streamUrl,- title = title,- channelId = channelId,- internalId = internalId,- categoryId = categoryId,- providerId = providerId,- isVirtual = isVirtual,- combinedProfileId = combinedProfileId,- combinedSourceFilterProviderId = combinedSourceFilterProviderId,- contentType = contentType,- artworkUrl = artworkUrl,- archiveStartMs = archiveStartMs,- archiveEndMs = archiveEndMs,- archiveTitle = archiveTitle,- returnRoute = returnRoute,- seriesId = seriesId,- seasonNumber = seasonNumber,- episodeNumber = episodeNumber,- episodeId = episodeId- )- }-- fun movieDetail(movieId: Long, returnRoute: String? = null) =- "movie_detail/$movieId?returnRoute=${Uri.encode(returnRoute ?: "")}"- fun seriesDetail(seriesId: Long, returnRoute: String? = null) =- "series_detail/$seriesId?returnRoute=${Uri.encode(returnRoute ?: "")}"- fun parentalControlGroups(providerId: Long) = "parental_control_groups/$providerId"-}--/** Accepts app-supported media schemes while still rejecting obviously unsafe ones. */-private fun isStreamUrlSafe(url: String?): Boolean {- if (url.isNullOrBlank()) return false- val scheme = url.substringBefore("://").lowercase()- return scheme in setOf("http", "https", "rtsp", "rtmp", "rtsps", "mms", "xtream", "stalker", "content", "file")-}--internal fun safePlayerNavigationRequest(request: PlayerNavigationRequest?): PlayerNavigationRequest? =- request?.takeIf { isStreamUrlSafe(it.streamUrl) }--/** Navigate only when the current destination is fully resumed – prevents double-navigation during transitions. */-private fun NavHostController.navigateIfResumed(route: String, builder: NavOptionsBuilder.() -> Unit = {}): Boolean {- if (currentBackStackEntry?.lifecycle?.currentState?.isAtLeast(Lifecycle.State.RESUMED) != true) return false- navigate(route, builder)- return true-}--private suspend fun Lifecycle.awaitResumed() {- if (currentState.isAtLeast(Lifecycle.State.RESUMED)) return- suspendCancellableCoroutine { continuation ->- lateinit var observer: LifecycleEventObserver- observer = LifecycleEventObserver { _, _ ->- when {- currentState.isAtLeast(Lifecycle.State.RESUMED) -> {- removeObserver(observer)- if (continuation.isActive) continuation.resume(Unit)- }- currentState == Lifecycle.State.DESTROYED -> {- removeObserver(observer)- continuation.cancel()- }- }- }- addObserver(observer)- continuation.invokeOnCancellation { removeObserver(observer) }- }-}--private fun NavHostController.navigateToPlayer(request: PlayerNavigationRequest): Boolean {- if (currentBackStackEntry?.lifecycle?.currentState?.isAtLeast(Lifecycle.State.RESUMED) != true) return false- currentBackStackEntry?.savedStateHandle?.set(PLAYER_REQUEST_KEY, request)- navigate(Routes.PLAYER) { launchSingleTop = true }- return true-}--private fun NavHostController.navigateToMovieDetail(movie: Movie, returnRoute: String? = null): Boolean {- if (currentBackStackEntry?.lifecycle?.currentState?.isAtLeast(Lifecycle.State.RESUMED) != true) return false- currentBackStackEntry?.savedStateHandle?.set(MOVIE_DETAIL_PRESENTATION_HINT_KEY, movie.toMovieDetailPresentationHint())- navigate(Routes.movieDetail(movie.id, returnRoute))- return true-}--private fun Movie.toMovieDetailPresentationHint(): MovieDetailPresentationHint? {- if (variants.isEmpty()) return null- return MovieDetailPresentationHint(- providerId = providerId,- logicalGroupId = logicalGroupId,- variants = variants,- duplicateConfidence = duplicateConfidence- )-}--private fun NavHostController.navigateToSeriesDetail(series: Series, returnRoute: String? = null): Boolean {- if (currentBackStackEntry?.lifecycle?.currentState?.isAtLeast(Lifecycle.State.RESUMED) != true) return false- currentBackStackEntry?.savedStateHandle?.set(SERIES_DETAIL_PRESENTATION_HINT_KEY, series.toSeriesDetailPresentationHint())- navigate(Routes.seriesDetail(series.id, returnRoute))- return true-}--private fun Series.toSeriesDetailPresentationHint(): SeriesDetailPresentationHint? {- if (variants.isEmpty()) return null- return SeriesDetailPresentationHint(- providerId = providerId,- logicalGroupId = logicalGroupId,- variants = variants,- duplicateConfidence = duplicateConfidence- )-}--private fun NavHostController.navigateToExternalPlayer(request: PlayerNavigationRequest): Boolean {- if (currentBackStackEntry?.lifecycle?.currentState?.isAtLeast(Lifecycle.State.RESUMED) != true) return false- currentBackStackEntry?.savedStateHandle?.set(PLAYER_REQUEST_KEY, request)- navigate(Routes.PLAYER) { launchSingleTop = true }- return true-}--internal fun AppLandingDestination.toAppRoute(): String = when (this) {- AppLandingDestination.HOME -> Routes.HOME- AppLandingDestination.LIVE_TV -> Routes.LIVE_TV- AppLandingDestination.FIRST_FAVORITE_LIVE -> Routes.LIVE_TV- AppLandingDestination.LAST_WATCHED_LIVE -> Routes.LIVE_TV- AppLandingDestination.MOVIES -> Routes.MOVIES- AppLandingDestination.SERIES -> Routes.SERIES- AppLandingDestination.GUIDE -> Routes.EPG- AppLandingDestination.DOWNLOADS -> Routes.DOWNLOADS- AppLandingDestination.PLUGINS -> Routes.PLUGINS- AppLandingDestination.SETTINGS -> Routes.SETTINGS-}--internal fun AppTopLevelDestination.toAppRoute(): String = when (this) {- AppTopLevelDestination.HOME -> Routes.HOME- AppTopLevelDestination.LIVE_TV -> Routes.LIVE_TV- AppTopLevelDestination.MOVIES -> Routes.MOVIES- AppTopLevelDestination.SERIES -> Routes.SERIES- AppTopLevelDestination.DOWNLOADS -> Routes.DOWNLOADS- AppTopLevelDestination.GUIDE -> Routes.EPG- AppTopLevelDestination.SEARCH -> Routes.SEARCH- AppTopLevelDestination.PLUGINS -> Routes.PLUGINS- AppTopLevelDestination.SETTINGS -> Routes.SETTINGS-}-@Composablefun AppNavigation(mainActivity: MainActivity) {val navController = rememberNavController()@@ -431,43 +132,12 @@ fun AppNavigation(mainActivity: MainActivity) {}}- LaunchedEffect(externalNavigationRequest, currentBackStackEntry) {- val entry = currentBackStackEntry ?: return@LaunchedEffect- entry.lifecycle.awaitResumed()- when (val request = externalNavigationRequest) {- is ExternalNavigationRequest.Player -> {- if (navController.navigateToExternalPlayer(request.request)) {- mainActivity.clearExternalNavigationRequest()- }- }-- is ExternalNavigationRequest.Destination -> {- if (navController.navigateIfResumed(request.destination.toRoute()) { launchSingleTop = true }) {- mainActivity.clearExternalNavigationRequest()- }- }-- is ExternalNavigationRequest.ImportM3u -> {- if (navController.navigateIfResumed(Routes.providerSetup(importUri = request.uri)) { launchSingleTop = true }) {- mainActivity.clearExternalNavigationRequest()- }- }-- is ExternalNavigationRequest.ImportBackup -> {- if (navController.navigateIfResumed(Routes.settings(backupUri = request.uri)) { launchSingleTop = true }) {- mainActivity.clearExternalNavigationRequest()- }- }-- is ExternalNavigationRequest.Search -> {- if (navController.navigateIfResumed(Routes.search(request.query)) { launchSingleTop = true }) {- mainActivity.clearExternalNavigationRequest()- }- }-- null -> Unit- }- }+ ExternalNavigationHost(+ request = externalNavigationRequest,+ currentBackStackEntry = currentBackStackEntry,+ navController = navController,+ onRequestHandled = mainActivity::clearExternalNavigationRequest+ )// NAV-M02/NAV-H02: Single helper replacing repeated tab lambdas without serializing// each tab's full UI tree into saved state on every switch.@@ -517,591 +187,10 @@ fun AppNavigation(mainActivity: MainActivity) {}}- NavHost(+ AppNavigationGraph(navController = navController,- startDestination = Routes.WELCOME- ) {- composable(Routes.WELCOME) {- WelcomeScreen(- onNavigateToHome = dropUnlessResumed {- navigateToStartupTarget(Routes.WELCOME)- },- startupReady = startupRoute != null,- onNavigateToSetup = dropUnlessResumed {- navController.navigate(Routes.providerSetup()) {- popUpTo(Routes.WELCOME) { inclusive = true }- }- }- )- }-- composable(- route = Routes.PROVIDER_SETUP,- arguments = listOf(- navArgument("providerId") { type = NavType.LongType; defaultValue = -1L },- navArgument("importUri") { type = NavType.StringType; defaultValue = "" }- )- ) { backStackEntry ->- val providerId = backStackEntry.arguments?.getLong("providerId")?.takeIf { it != -1L }- val importUri = backStackEntry.arguments?.getString("importUri")?.takeIf { it.isNotBlank() }-- ProviderSetupScreen(- editProviderId = providerId,- initialImportUri = importUri,- onBack = { navController.popBackStack() },- onProviderAdded = dropUnlessResumed {- navigateToStartupTarget(Routes.PROVIDER_SETUP)- }- )- }-// ...-- composable(Routes.HOME) {- DashboardScreen(- onNavigate = { route -> tabNavigate(route) },- onAddProvider = dropUnlessResumed {- navController.navigate(Routes.providerSetup(null))- },- onRecentChannelClick = { channel, combinedProfileId ->- navController.navigateToPlayer(- Routes.livePlayer(- channel = channel,- categoryId = com.streamvault.domain.model.VirtualCategoryIds.RECENT,- providerId = channel.providerId,- isVirtual = true,- combinedProfileId = combinedProfileId,- returnRoute = Routes.HOME- )- )- },- onFavoriteChannelClick = { channel, combinedProfileId ->- navController.navigateToPlayer(- Routes.livePlayer(- channel = channel,- categoryId = com.streamvault.domain.model.VirtualCategoryIds.FAVORITES,- providerId = channel.providerId,- isVirtual = true,- combinedProfileId = combinedProfileId,- returnRoute = Routes.HOME- )- )- },- onMovieClick = { movie ->- navController.navigateToMovieDetail(movie, Routes.HOME)- },- onSeriesClick = { series ->- navController.navigateToSeriesDetail(series, Routes.HOME)- },- onPlaybackHistoryClick = { history ->- val route = when (history.contentType) {- com.streamvault.domain.model.ContentType.LIVE -> {- Routes.player(- streamUrl = history.streamUrl,- title = history.title,- internalId = history.contentId,- providerId = history.providerId,- contentType = history.contentType.name,- returnRoute = Routes.HOME- )- }- com.streamvault.domain.model.ContentType.MOVIE,- com.streamvault.domain.model.ContentType.VOD -> {- Routes.player(- streamUrl = history.streamUrl,- title = history.title,- internalId = history.contentId,- providerId = history.providerId,- contentType = history.contentType.name,- returnRoute = Routes.HOME- )- }- com.streamvault.domain.model.ContentType.SERIES -> {- Routes.seriesDetail(history.contentId, Routes.HOME)- }- com.streamvault.domain.model.ContentType.SERIES_EPISODE -> {- Routes.player(- streamUrl = history.streamUrl,- title = history.title,- internalId = history.contentId,- providerId = history.providerId,- contentType = history.contentType.name,- returnRoute = Routes.HOME,- seriesId = history.seriesId,- seasonNumber = history.seasonNumber,- episodeNumber = history.episodeNumber- )- }- }- if (route is PlayerNavigationRequest) {- navController.navigateToPlayer(route)- } else {- navController.navigateIfResumed(route as String) { launchSingleTop = true }- }- },- currentRoute = Routes.HOME- )- }-- composable(- route = Routes.LIVE_TV_DESTINATION,- arguments = listOf(- navArgument("categoryId") { type = NavType.LongType; defaultValue = -1L }- )- ) { backStackEntry ->- val initialCategoryId = backStackEntry.arguments?.getLong("categoryId")?.takeIf { it != -1L }- HomeScreen(- onChannelClick = { channel, category, provider, combinedProfileId, combinedSourceFilterProviderId ->- navController.navigateToPlayer(- Routes.livePlayer(- channel = channel,- categoryId = category?.id,- providerId = provider?.id,- isVirtual = category?.isVirtual == true,- combinedProfileId = combinedProfileId,- combinedSourceFilterProviderId = combinedSourceFilterProviderId,- returnRoute = Routes.liveTv(category?.id)- )- )- },- onNavigate = { route -> tabNavigate(route) },- currentRoute = Routes.LIVE_TV,- initialCategoryId = initialCategoryId- )- }-// ... (rest of file)-- composable(Routes.MOVIES) {- MoviesScreen(- onMovieClick = { movie ->- navController.navigateToMovieDetail(movie, Routes.MOVIES)- },- onContinueWatchingPlay = { history ->- navController.navigateToPlayer(- history.toPlayerNavigationRequest().copy(returnRoute = Routes.MOVIES)- )- },- onNavigate = { route -> tabNavigate(route) },- currentRoute = Routes.MOVIES- )- }-- composable(Routes.SERIES) {- SeriesScreen(- onSeriesClick = { series ->- navController.navigateToSeriesDetail(series, Routes.SERIES)- },- onSeriesIdClick = { seriesId ->- navController.navigateIfResumed(Routes.seriesDetail(seriesId, Routes.SERIES))- },- onNavigate = { route -> tabNavigate(route) },- currentRoute = Routes.SERIES- )- }-- composable(Routes.VOD) {- VodScreen(- onMovieClick = { movie ->- navController.navigateToMovieDetail(movie, Routes.VOD)- },- onSeriesClick = { series ->- navController.navigateToSeriesDetail(series, Routes.VOD)- },- onNavigate = { route -> tabNavigate(route) },- currentRoute = Routes.VOD- )- }-- composable(Routes.DOWNLOADS) {- DownloadsScreen(- onNavigate = { route -> tabNavigate(route) },- currentRoute = Routes.DOWNLOADS- )- }-- composable(- route = Routes.EPG_DESTINATION,- arguments = listOf(- navArgument("categoryId") { type = NavType.LongType; defaultValue = -1L },- navArgument("anchorTime") { type = NavType.LongType; defaultValue = -1L },- navArgument("favoritesOnly") { type = NavType.BoolType; defaultValue = false }- )- ) { backStackEntry ->- val epgCategoryId = backStackEntry.arguments?.getLong("categoryId")?.takeIf { it != -1L }- val epgAnchorTime = backStackEntry.arguments?.getLong("anchorTime")?.takeIf { it != -1L }- val epgFavoritesOnly = backStackEntry.arguments?.getBoolean("favoritesOnly") ?: false- com.streamvault.app.ui.screens.epg.FullEpgScreen(- currentRoute = Routes.EPG,- initialCategoryId = epgCategoryId,- initialAnchorTime = epgAnchorTime,- initialFavoritesOnly = epgFavoritesOnly,- onPlayChannel = { channel, categoryId, isVirtual, combinedProfileId, returnRoute ->- navController.navigateToPlayer(- Routes.livePlayer(- channel = channel,- categoryId = categoryId,- providerId = channel.providerId,- isVirtual = isVirtual,- combinedProfileId = combinedProfileId,- returnRoute = returnRoute- )- )- },- onPlayArchive = { channel, program, categoryId, isVirtual, combinedProfileId, returnRoute ->- if (!channel.isArchivePlayable(program)) {- return@FullEpgScreen- }- navController.navigateToPlayer(- Routes.player(- streamUrl = channel.streamUrl,- title = channel.name,- channelId = channel.epgChannelId,- internalId = channel.id,- categoryId = categoryId,- providerId = channel.providerId,- isVirtual = isVirtual,- combinedProfileId = combinedProfileId,- contentType = "LIVE",- archiveStartMs = program.startTime,- archiveEndMs = program.endTime,- archiveTitle = "${channel.name}: ${program.title}",- returnRoute = returnRoute- )- )- },- onNavigate = { route -> tabNavigate(route) }- )- }-- composable(- route = Routes.SETTINGS_DESTINATION,- arguments = listOf(- navArgument("backupUri") { type = NavType.StringType; defaultValue = "" }- )- ) { backStackEntry ->- val backupUri = backStackEntry.arguments?.getString("backupUri")?.takeIf { it.isNotBlank() }- SettingsScreen(- onNavigate = { route -> tabNavigate(route) },- onAddProvider = dropUnlessResumed {- navController.navigate(Routes.providerSetup(null))- },- onEditProvider = { provider ->- navController.navigateIfResumed(Routes.providerSetup(provider.id))- },- onNavigateToParentalControl = { providerId ->- navController.navigateIfResumed(Routes.parentalControlGroups(providerId))- },- currentRoute = Routes.SETTINGS,- initialBackupImportUri = backupUri- )- }-- composable(Routes.PLUGINS) {- PluginsScreen(- currentRoute = Routes.PLUGINS,- onNavigate = { route -> tabNavigate(route) }- )- }-- composable(- route = Routes.PARENTAL_CONTROL_GROUPS,- arguments = listOf(- navArgument("providerId") { type = NavType.LongType }- )- ) {- com.streamvault.app.ui.screens.settings.parental.ParentalControlGroupScreen(- currentRoute = Routes.SETTINGS,- onNavigate = { route -> tabNavigate(route) },- onBack = { navController.popBackStack() }- )- }-- composable(- route = Routes.SEARCH_DESTINATION,- arguments = listOf(- navArgument("query") { type = NavType.StringType; defaultValue = "" }- )- ) { backStackEntry ->- com.streamvault.app.ui.screens.search.SearchScreen(- initialQuery = backStackEntry.arguments?.getString("query").orEmpty(),- onChannelClick = { channel ->- navController.navigateToPlayer(- Routes.livePlayer(- channel = channel,- categoryId = channel.categoryId ?: ChannelRepository.ALL_CHANNELS_ID,- providerId = channel.providerId,- isVirtual = false,- returnRoute = Routes.search(backStackEntry.arguments?.getString("query").orEmpty())- )- )- },- onMovieClick = { movie ->- navController.navigateToMovieDetail(- movie,- Routes.search(backStackEntry.arguments?.getString("query").orEmpty())- )- },- onSeriesClick = { series ->- navController.navigateToSeriesDetail(- series,- Routes.search(backStackEntry.arguments?.getString("query").orEmpty())- )- },- onNavigate = { route -> tabNavigate(route) },- currentRoute = Routes.SEARCH- )- }-- composable(route = Routes.PLAYER) { backStackEntry ->- val playerRequest = backStackEntry.savedStateHandle.get<PlayerNavigationRequest>(PLAYER_REQUEST_KEY)- ?: navController.previousBackStackEntry?.savedStateHandle?.get<PlayerNavigationRequest>(PLAYER_REQUEST_KEY)?.also {- backStackEntry.savedStateHandle[PLAYER_REQUEST_KEY] = it- }- val safePlayerRequest = safePlayerNavigationRequest(playerRequest)- if (safePlayerRequest == null) {- LaunchedEffect(playerRequest) {- Log.w(TAG, "Missing or invalid player request; returning to previous destination")- if (!navController.popBackStack()) {- navController.navigate(Routes.HOME) {- popUpTo(Routes.PLAYER) { inclusive = true }- launchSingleTop = true- }- }- }- } else {- PlayerScreen(- streamUrl = safePlayerRequest.streamUrl,- title = safePlayerRequest.title,- epgChannelId = safePlayerRequest.channelId,- internalChannelId = safePlayerRequest.internalId,- categoryId = safePlayerRequest.categoryId,- providerId = safePlayerRequest.providerId,- isVirtual = safePlayerRequest.isVirtual,- combinedProfileId = safePlayerRequest.combinedProfileId,- combinedSourceFilterProviderId = safePlayerRequest.combinedSourceFilterProviderId,- contentType = safePlayerRequest.contentType,- artworkUrl = safePlayerRequest.artworkUrl,- archiveStartMs = safePlayerRequest.archiveStartMs,- archiveEndMs = safePlayerRequest.archiveEndMs,- archiveTitle = safePlayerRequest.archiveTitle,- returnRoute = safePlayerRequest.returnRoute,- seriesId = safePlayerRequest.seriesId,- seasonNumber = safePlayerRequest.seasonNumber,- episodeNumber = safePlayerRequest.episodeNumber,- episodeId = safePlayerRequest.episodeId,- onBack = {- val route = safePlayerRequest.returnRoute- if (!route.isNullOrBlank() && navController.popBackStack(route, false)) {- // Popped back to the exact route already in the backstack (same VM, handoff works)- Unit- } else if (!route.isNullOrBlank()) {- // Nothing left to pop — navigate to the return route or home as a last resort- navController.navigate(route) {- popUpTo(Routes.PLAYER) { inclusive = true }- launchSingleTop = true- restoreState = true- }- } else if (!navController.popBackStack()) {- navController.navigate(Routes.HOME) {- popUpTo(Routes.PLAYER) { inclusive = true }- launchSingleTop = true- restoreState = true- }- }- // else: plain popBackStack() succeeded — returns to existing Guide entry, preserving EpgViewModel- },- onNavigate = { route ->- navController.navigateIfResumed(route) {- launchSingleTop = true- if (route == Routes.MULTI_VIEW) {- popUpTo(Routes.PLAYER) { inclusive = true }- }- }- }- )- }- }-- composable(- route = Routes.MOVIE_DETAIL,- arguments = listOf(- navArgument("movieId") { type = NavType.LongType },- navArgument("returnRoute") { type = NavType.StringType; defaultValue = "" }- )- ) { backStackEntry ->- val moviePresentationHint = backStackEntry.savedStateHandle.get<MovieDetailPresentationHint>(MOVIE_DETAIL_PRESENTATION_HINT_KEY)- ?: navController.previousBackStackEntry?.savedStateHandle?.get<MovieDetailPresentationHint>(MOVIE_DETAIL_PRESENTATION_HINT_KEY)?.also {- backStackEntry.savedStateHandle[MOVIE_DETAIL_PRESENTATION_HINT_KEY] = it- }- val returnRoute = backStackEntry.arguments?.getString("returnRoute").orEmpty().takeIf { it.isNotBlank() }- val movieId = backStackEntry.arguments?.getLong("movieId") ?: -1L- com.streamvault.app.ui.screens.movies.MovieDetailScreen(- onPlay = { movie ->- navController.navigateToPlayer(- Routes.moviePlayer(movie).copy(- returnRoute = Routes.movieDetail(- movieId = movie.id.takeIf { it > 0L } ?: movieId,- returnRoute = returnRoute- )- )- )- },- onBack = {- if (!returnRoute.isNullOrBlank()) {- navController.navigate(returnRoute) {- popUpTo(backStackEntry.destination.route ?: Routes.MOVIE_DETAIL) { inclusive = true }- launchSingleTop = true- }- } else {- navController.popBackStack()- }- }- )- }-- composable(- route = Routes.SERIES_DETAIL,- arguments = listOf(- navArgument("seriesId") { type = NavType.LongType },- navArgument("returnRoute") { type = NavType.StringType; defaultValue = "" }- )- ) { backStackEntry ->- val seriesPresentationHint = backStackEntry.savedStateHandle.get<SeriesDetailPresentationHint>(SERIES_DETAIL_PRESENTATION_HINT_KEY)- ?: navController.previousBackStackEntry?.savedStateHandle?.get<SeriesDetailPresentationHint>(SERIES_DETAIL_PRESENTATION_HINT_KEY)?.also {- backStackEntry.savedStateHandle[SERIES_DETAIL_PRESENTATION_HINT_KEY] = it- }- val returnRoute = backStackEntry.arguments?.getString("returnRoute").orEmpty().takeIf { it.isNotBlank() }- val seriesId = backStackEntry.arguments?.getLong("seriesId") ?: -1L- com.streamvault.app.ui.screens.series.SeriesDetailScreen(- onEpisodeClick = { episode ->- navController.navigateToPlayer(- Routes.episodePlayer(episode).copy(- returnRoute = Routes.seriesDetail(- seriesId = episode.seriesId.takeIf { it > 0L } ?: seriesId,- returnRoute = returnRoute- )- )- )- },- onBack = {- if (!returnRoute.isNullOrBlank()) {- navController.navigate(returnRoute) {- popUpTo(backStackEntry.destination.route ?: Routes.SERIES_DETAIL) { inclusive = true }- launchSingleTop = true- }- } else {- navController.popBackStack()- }- }- )- }-- composable(Routes.MULTI_VIEW) {- MultiViewScreen(- onBack = { navController.popBackStack() }- )- }- }-}--private suspend fun resolveStartupPlayerRequest(- mainActivity: MainActivity,- landingDestination: AppLandingDestination-): PlayerNavigationRequest? = when (landingDestination) {- AppLandingDestination.FIRST_FAVORITE_LIVE -> resolveFirstFavoriteStartupTarget(mainActivity)- AppLandingDestination.LAST_WATCHED_LIVE -> resolveLastWatchedStartupTarget(mainActivity)- else -> null-}--private suspend fun resolveFirstFavoriteStartupTarget(- mainActivity: MainActivity-): PlayerNavigationRequest? {- if (!mainActivity.preferencesRepository.showFavoritesCategory.first()) return null- val context = resolveLiveStartupContext(mainActivity) ?: return null- val favorites = when (context) {- is LiveStartupContext.Provider -> mainActivity.favoriteRepository.getFavorites(context.providerId, ContentType.LIVE).first()- is LiveStartupContext.Combined -> mainActivity.favoriteRepository.getFavorites(context.providerIds, ContentType.LIVE).first()- }.sortedBy { it.position }- return resolveStartupChannelTarget(- mainActivity = mainActivity,- channelIds = favorites.map { it.contentId },- sourceContext = context,- virtualCategoryId = VirtualCategoryIds.FAVORITES- )-}--private suspend fun resolveLastWatchedStartupTarget(- mainActivity: MainActivity-): PlayerNavigationRequest? {- val context = resolveLiveStartupContext(mainActivity) ?: return null- val recentHistory = when (context) {- is LiveStartupContext.Provider -> mainActivity.playbackHistoryRepository.getRecentlyWatchedByProvider(context.providerId, limit = 24).first()- is LiveStartupContext.Combined -> mainActivity.playbackHistoryRepository.getRecentlyWatchedByProviders(context.providerIds.toSet(), limit = 24).first()- }- return resolveStartupChannelTarget(- mainActivity = mainActivity,- channelIds = recentHistory- .filter { it.contentType == ContentType.LIVE }- .sortedByDescending { it.lastWatchedAt }- .map { it.contentId },- sourceContext = context,- virtualCategoryId = VirtualCategoryIds.RECENT+ startupRoute = startupRoute,+ navigateToStartupTarget = { popUpRoute -> navigateToStartupTarget(popUpRoute) },+ tabNavigate = { route -> tabNavigate(route) })}--private suspend fun resolveStartupChannelTarget(- mainActivity: MainActivity,- channelIds: List<Long>,- sourceContext: LiveStartupContext,- virtualCategoryId: Long-): PlayerNavigationRequest? {- if (channelIds.isEmpty()) return null- val hiddenChannelIdsByProvider = sourceContext.providerIds.associateWith { providerId ->- mainActivity.preferencesRepository.getHiddenChannelIds(providerId).first()- }- for (channelId in channelIds.distinct()) {- val channel = mainActivity.channelRepository.getChannel(channelId) ?: continue- if (channel.providerId !in sourceContext.providerIds) continue- if (channel.id in hiddenChannelIdsByProvider[channel.providerId].orEmpty()) continue- return Routes.livePlayer(- channel = channel,- categoryId = virtualCategoryId,- providerId = channel.providerId,- isVirtual = true,- combinedProfileId = (sourceContext as? LiveStartupContext.Combined)?.profileId,- returnRoute = Routes.LIVE_TV- )- }- return null-}--private suspend fun resolveLiveStartupContext(- mainActivity: MainActivity-): LiveStartupContext? {- return when (val activeSource = mainActivity.combinedM3uRepository.getActiveLiveSource().first()) {- is ActiveLiveSource.ProviderSource -> LiveStartupContext.Provider(activeSource.providerId)- is ActiveLiveSource.CombinedM3uSource -> {- val providerIds = mainActivity.combinedM3uRepository.getProfile(activeSource.profileId)- ?.members- .orEmpty()- .filter { it.enabled }- .map { it.providerId }- .distinct()- if (providerIds.isEmpty()) null else LiveStartupContext.Combined(activeSource.profileId, providerIds)- }- null -> {- mainActivity.providerRepository.getActiveProvider().first()?.id?.let { providerId ->- LiveStartupContext.Provider(providerId)- }- }- }-}--private sealed interface LiveStartupContext {- val providerIds: List<Long>-- data class Provider(val providerId: Long) : LiveStartupContext {- override val providerIds: List<Long> = listOf(providerId)- }-- data class Combined(val profileId: Long, override val providerIds: List<Long>) : LiveStartupContext-}diff --git a/app/src/main/java/com/streamvault/app/navigation/AppNavigationAdapters.kt b/app/src/main/java/com/streamvault/app/navigation/AppNavigationAdapters.ktnew file mode 100644index 00000000..e64e1145--- /dev/null+++ b/app/src/main/java/com/streamvault/app/navigation/AppNavigationAdapters.kt@@ -0,0 +1,160 @@+package com.streamvault.app.navigation++import android.net.Uri+import android.util.Log+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.produceState+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import androidx.lifecycle.compose.dropUnlessResumed+import androidx.navigation.NavHostController+import androidx.navigation.NavOptionsBuilder+import androidx.navigation.NavType+import androidx.navigation.compose.NavHost+import androidx.navigation.compose.composable+import androidx.navigation.compose.currentBackStackEntryAsState+import androidx.navigation.compose.rememberNavController+import androidx.navigation.navArgument+import com.streamvault.app.ui.model.isArchivePlayable+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.Episode+import com.streamvault.domain.model.Movie+import com.streamvault.domain.repository.ChannelRepository+import com.streamvault.app.ui.screens.dashboard.DashboardScreen+import com.streamvault.app.ui.screens.multiview.MultiViewScreen+import com.streamvault.app.ui.screens.home.HomeScreen+import com.streamvault.app.ui.screens.movies.MoviesScreen+import com.streamvault.app.ui.screens.player.PlayerScreen+import com.streamvault.app.ui.screens.plugins.PluginsScreen+import com.streamvault.app.ui.screens.provider.ProviderSetupScreen+import com.streamvault.app.ui.screens.series.SeriesScreen+import com.streamvault.app.ui.screens.vod.VodScreen+import com.streamvault.app.ui.screens.settings.SettingsScreen+import com.streamvault.app.ui.screens.welcome.WelcomeScreen+import com.streamvault.app.ui.screens.downloads.DownloadsScreen+import com.streamvault.app.MainActivity+import com.streamvault.domain.model.AppLandingDestination+import com.streamvault.domain.model.AppTopLevelDestination+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.CatalogLayout+import com.streamvault.domain.model.MovieDetailPresentationHint+import com.streamvault.domain.model.ActiveLiveSource+import com.streamvault.domain.model.Series+import com.streamvault.domain.model.SeriesDetailPresentationHint+import com.streamvault.domain.model.VirtualCategoryIds+import java.io.Serializable+import kotlin.coroutines.resume+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch+import kotlinx.coroutines.suspendCancellableCoroutine+++/** Navigate only when the current destination is fully resumed – prevents double-navigation during transitions. */+internal fun NavHostController.navigateIfResumed(route: String, builder: NavOptionsBuilder.() -> Unit = {}): Boolean {+ if (currentBackStackEntry?.lifecycle?.currentState?.isAtLeast(Lifecycle.State.RESUMED) != true) return false+ navigate(route, builder)+ return true+}++internal suspend fun Lifecycle.awaitResumed() {+ if (currentState.isAtLeast(Lifecycle.State.RESUMED)) return+ suspendCancellableCoroutine { continuation ->+ lateinit var observer: LifecycleEventObserver+ observer = LifecycleEventObserver { _, _ ->+ when {+ currentState.isAtLeast(Lifecycle.State.RESUMED) -> {+ removeObserver(observer)+ if (continuation.isActive) continuation.resume(Unit)+ }+ currentState == Lifecycle.State.DESTROYED -> {+ removeObserver(observer)+ continuation.cancel()+ }+ }+ }+ addObserver(observer)+ continuation.invokeOnCancellation { removeObserver(observer) }+ }+}++internal fun NavHostController.navigateToPlayer(request: PlayerNavigationRequest): Boolean {+ if (currentBackStackEntry?.lifecycle?.currentState?.isAtLeast(Lifecycle.State.RESUMED) != true) return false+ currentBackStackEntry?.savedStateHandle?.set(PLAYER_REQUEST_KEY, request)+ navigate(Routes.PLAYER) { launchSingleTop = true }+ return true+}++internal fun NavHostController.navigateToMovieDetail(movie: Movie, returnRoute: String? = null): Boolean {+ if (currentBackStackEntry?.lifecycle?.currentState?.isAtLeast(Lifecycle.State.RESUMED) != true) return false+ currentBackStackEntry?.savedStateHandle?.set(MOVIE_DETAIL_PRESENTATION_HINT_KEY, movie.toMovieDetailPresentationHint())+ navigate(Routes.movieDetail(movie.id, returnRoute))+ return true+}++private fun Movie.toMovieDetailPresentationHint(): MovieDetailPresentationHint? {+ if (variants.isEmpty()) return null+ return MovieDetailPresentationHint(+ providerId = providerId,+ logicalGroupId = logicalGroupId,+ variants = variants,+ duplicateConfidence = duplicateConfidence+ )+}++internal fun NavHostController.navigateToSeriesDetail(series: Series, returnRoute: String? = null): Boolean {+ if (currentBackStackEntry?.lifecycle?.currentState?.isAtLeast(Lifecycle.State.RESUMED) != true) return false+ currentBackStackEntry?.savedStateHandle?.set(SERIES_DETAIL_PRESENTATION_HINT_KEY, series.toSeriesDetailPresentationHint())+ navigate(Routes.seriesDetail(series.id, returnRoute))+ return true+}++private fun Series.toSeriesDetailPresentationHint(): SeriesDetailPresentationHint? {+ if (variants.isEmpty()) return null+ return SeriesDetailPresentationHint(+ providerId = providerId,+ logicalGroupId = logicalGroupId,+ variants = variants,+ duplicateConfidence = duplicateConfidence+ )+}++internal fun NavHostController.navigateToExternalPlayer(request: PlayerNavigationRequest): Boolean {+ if (currentBackStackEntry?.lifecycle?.currentState?.isAtLeast(Lifecycle.State.RESUMED) != true) return false+ currentBackStackEntry?.savedStateHandle?.set(PLAYER_REQUEST_KEY, request)+ navigate(Routes.PLAYER) { launchSingleTop = true }+ return true+}++internal fun AppLandingDestination.toAppRoute(): String = when (this) {+ AppLandingDestination.HOME -> Routes.HOME+ AppLandingDestination.LIVE_TV -> Routes.LIVE_TV+ AppLandingDestination.FIRST_FAVORITE_LIVE -> Routes.LIVE_TV+ AppLandingDestination.LAST_WATCHED_LIVE -> Routes.LIVE_TV+ AppLandingDestination.MOVIES -> Routes.MOVIES+ AppLandingDestination.SERIES -> Routes.SERIES+ AppLandingDestination.GUIDE -> Routes.EPG+ AppLandingDestination.DOWNLOADS -> Routes.DOWNLOADS+ AppLandingDestination.PLUGINS -> Routes.PLUGINS+ AppLandingDestination.SETTINGS -> Routes.SETTINGS+}++internal fun AppTopLevelDestination.toAppRoute(): String = when (this) {+ AppTopLevelDestination.HOME -> Routes.HOME+ AppTopLevelDestination.LIVE_TV -> Routes.LIVE_TV+ AppTopLevelDestination.MOVIES -> Routes.MOVIES+ AppTopLevelDestination.SERIES -> Routes.SERIES+ AppTopLevelDestination.DOWNLOADS -> Routes.DOWNLOADS+ AppTopLevelDestination.GUIDE -> Routes.EPG+ AppTopLevelDestination.SEARCH -> Routes.SEARCH+ AppTopLevelDestination.PLUGINS -> Routes.PLUGINS+ AppTopLevelDestination.SETTINGS -> Routes.SETTINGS+}++diff --git a/app/src/main/java/com/streamvault/app/navigation/AppNavigationContracts.kt b/app/src/main/java/com/streamvault/app/navigation/AppNavigationContracts.ktnew file mode 100644index 00000000..5f96a9f4--- /dev/null+++ b/app/src/main/java/com/streamvault/app/navigation/AppNavigationContracts.kt@@ -0,0 +1,240 @@+package com.streamvault.app.navigation++import android.net.Uri+import android.util.Log+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.produceState+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import androidx.lifecycle.compose.dropUnlessResumed+import androidx.navigation.NavHostController+import androidx.navigation.NavOptionsBuilder+import androidx.navigation.NavType+import androidx.navigation.compose.NavHost+import androidx.navigation.compose.composable+import androidx.navigation.compose.currentBackStackEntryAsState+import androidx.navigation.compose.rememberNavController+import androidx.navigation.navArgument+import com.streamvault.app.ui.model.isArchivePlayable+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.Episode+import com.streamvault.domain.model.Movie+import com.streamvault.domain.repository.ChannelRepository+import com.streamvault.app.ui.screens.dashboard.DashboardScreen+import com.streamvault.app.ui.screens.multiview.MultiViewScreen+import com.streamvault.app.ui.screens.home.HomeScreen+import com.streamvault.app.ui.screens.movies.MoviesScreen+import com.streamvault.app.ui.screens.player.PlayerScreen+import com.streamvault.app.ui.screens.plugins.PluginsScreen+import com.streamvault.app.ui.screens.provider.ProviderSetupScreen+import com.streamvault.app.ui.screens.series.SeriesScreen+import com.streamvault.app.ui.screens.vod.VodScreen+import com.streamvault.app.ui.screens.settings.SettingsScreen+import com.streamvault.app.ui.screens.welcome.WelcomeScreen+import com.streamvault.app.ui.screens.downloads.DownloadsScreen+import com.streamvault.app.MainActivity+import com.streamvault.domain.model.AppLandingDestination+import com.streamvault.domain.model.AppTopLevelDestination+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.CatalogLayout+import com.streamvault.domain.model.MovieDetailPresentationHint+import com.streamvault.domain.model.ActiveLiveSource+import com.streamvault.domain.model.Series+import com.streamvault.domain.model.SeriesDetailPresentationHint+import com.streamvault.domain.model.VirtualCategoryIds+import java.io.Serializable+import kotlin.coroutines.resume+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch+import kotlinx.coroutines.suspendCancellableCoroutine+++internal const val PLAYER_REQUEST_KEY = "player_request"+internal const val MOVIE_DETAIL_PRESENTATION_HINT_KEY = "movie_detail_presentation_hint"+internal const val SERIES_DETAIL_PRESENTATION_HINT_KEY = "series_detail_presentation_hint"+internal const val APP_NAVIGATION_TAG = "AppNavigation"++data class PlayerNavigationRequest(+ val streamUrl: String,+ val title: String,+ val channelId: String? = null,+ val internalId: Long = -1L,+ val categoryId: Long? = null,+ val providerId: Long? = null,+ val isVirtual: Boolean = false,+ val combinedProfileId: Long? = null,+ val combinedSourceFilterProviderId: Long? = null,+ val contentType: String = "LIVE",+ val artworkUrl: String? = null,+ val archiveStartMs: Long? = null,+ val archiveEndMs: Long? = null,+ val archiveTitle: String? = null,+ val returnRoute: String? = null,+ val seriesId: Long? = null,+ val seasonNumber: Int? = null,+ val episodeNumber: Int? = null,+ val episodeId: Long? = null+) : Serializable++object Routes {+ const val PROVIDER_SETUP = "provider_setup?providerId={providerId}&importUri={importUri}"+ const val HOME = "home"+ const val LIVE_TV = "live_tv"+ const val LIVE_TV_DESTINATION = "live_tv?categoryId={categoryId}"+ const val MOVIES = "movies"+ const val SERIES = "series"+ const val VOD = "vod"+ const val DOWNLOADS = "downloads"+ const val EPG = "epg"+ const val EPG_DESTINATION = "epg?categoryId={categoryId}&anchorTime={anchorTime}&favoritesOnly={favoritesOnly}"+ const val SETTINGS = "settings"+ const val SETTINGS_DESTINATION = "settings?backupUri={backupUri}"+ const val PLUGINS = "plugins"+ const val PLAYER = "player"+ const val SEARCH = "search"+ const val SEARCH_DESTINATION = "search?query={query}"+ const val MOVIE_DETAIL = "movie_detail/{movieId}?returnRoute={returnRoute}"+ const val SERIES_DETAIL = "series_detail/{seriesId}?returnRoute={returnRoute}"+ const val WELCOME = "welcome"+ const val PARENTAL_CONTROL_GROUPS = "parental_control_groups/{providerId}"+ const val MULTI_VIEW = "multi_view"+++ fun providerSetup(providerId: Long? = null, importUri: String? = null): String {+ val encodedImportUri = Uri.encode(importUri ?: "")+ return "provider_setup?providerId=${providerId ?: -1L}&importUri=$encodedImportUri"+ }+ fun liveTv(categoryId: Long? = null) = if (categoryId == null) LIVE_TV else "$LIVE_TV?categoryId=$categoryId"+ fun epg(categoryId: Long? = null, anchorTime: Long? = null, favoritesOnly: Boolean? = null): String {+ val resolvedCategoryId = categoryId ?: -1L+ val resolvedAnchorTime = anchorTime ?: -1L+ val resolvedFavoritesOnly = favoritesOnly ?: false+ return "$EPG?categoryId=$resolvedCategoryId&anchorTime=$resolvedAnchorTime&favoritesOnly=$resolvedFavoritesOnly"+ }++ fun livePlayer(+ channel: Channel,+ categoryId: Long? = channel.categoryId,+ providerId: Long? = channel.providerId,+ isVirtual: Boolean = false,+ combinedProfileId: Long? = null,+ combinedSourceFilterProviderId: Long? = null,+ returnRoute: String? = null+ ): PlayerNavigationRequest {+ val effectiveCategoryId = categoryId ?: ChannelRepository.ALL_CHANNELS_ID+ return player(+ streamUrl = channel.streamUrl,+ title = channel.name,+ channelId = channel.epgChannelId,+ internalId = channel.id,+ categoryId = effectiveCategoryId,+ providerId = providerId,+ isVirtual = isVirtual,+ combinedProfileId = combinedProfileId,+ combinedSourceFilterProviderId = combinedSourceFilterProviderId,+ contentType = "LIVE",+ returnRoute = returnRoute+ )+ }++ fun moviePlayer(movie: Movie): PlayerNavigationRequest {+ return player(+ streamUrl = movie.streamUrl,+ title = movie.name,+ internalId = movie.id,+ categoryId = movie.categoryId,+ providerId = movie.providerId,+ contentType = "MOVIE",+ artworkUrl = movie.posterUrl ?: movie.backdropUrl+ )+ }++ fun episodePlayer(episode: Episode): PlayerNavigationRequest {+ return player(+ streamUrl = episode.streamUrl,+ title = "${episode.title} - S${episode.seasonNumber}E${episode.episodeNumber}",+ internalId = episode.id,+ providerId = episode.providerId,+ contentType = "SERIES_EPISODE",+ artworkUrl = episode.coverUrl,+ seriesId = episode.seriesId.takeIf { it > 0L },+ seasonNumber = episode.seasonNumber,+ episodeNumber = episode.episodeNumber,+ episodeId = episode.episodeId.takeIf { it > 0L }+ )+ }++ fun search(query: String? = null): String =+ if (query.isNullOrBlank()) SEARCH else "$SEARCH?query=${Uri.encode(query)}"++ fun settings(backupUri: String? = null): String =+ if (backupUri.isNullOrBlank()) SETTINGS else "$SETTINGS?backupUri=${Uri.encode(backupUri)}"++ fun player(+ streamUrl: String,+ title: String,+ channelId: String? = null,+ internalId: Long = -1L,+ categoryId: Long? = null,+ providerId: Long? = null,+ isVirtual: Boolean = false,+ combinedProfileId: Long? = null,+ combinedSourceFilterProviderId: Long? = null,+ contentType: String = "LIVE",+ artworkUrl: String? = null,+ archiveStartMs: Long? = null,+ archiveEndMs: Long? = null,+ archiveTitle: String? = null,+ returnRoute: String? = null,+ seriesId: Long? = null,+ seasonNumber: Int? = null,+ episodeNumber: Int? = null,+ episodeId: Long? = null+ ): PlayerNavigationRequest {+ return PlayerNavigationRequest(+ streamUrl = streamUrl,+ title = title,+ channelId = channelId,+ internalId = internalId,+ categoryId = categoryId,+ providerId = providerId,+ isVirtual = isVirtual,+ combinedProfileId = combinedProfileId,+ combinedSourceFilterProviderId = combinedSourceFilterProviderId,+ contentType = contentType,+ artworkUrl = artworkUrl,+ archiveStartMs = archiveStartMs,+ archiveEndMs = archiveEndMs,+ archiveTitle = archiveTitle,+ returnRoute = returnRoute,+ seriesId = seriesId,+ seasonNumber = seasonNumber,+ episodeNumber = episodeNumber,+ episodeId = episodeId+ )+ }++ fun movieDetail(movieId: Long, returnRoute: String? = null) =+ "movie_detail/$movieId?returnRoute=${Uri.encode(returnRoute ?: "")}"+ fun seriesDetail(seriesId: Long, returnRoute: String? = null) =+ "series_detail/$seriesId?returnRoute=${Uri.encode(returnRoute ?: "")}"+ fun parentalControlGroups(providerId: Long) = "parental_control_groups/$providerId"+}++/** Accepts app-supported media schemes while still rejecting obviously unsafe ones. */+private fun isStreamUrlSafe(url: String?): Boolean {+ if (url.isNullOrBlank()) return false+ val scheme = url.substringBefore("://").lowercase()+ return scheme in setOf("http", "https", "rtsp", "rtmp", "rtsps", "mms", "xtream", "stalker", "content", "file")+}++internal fun safePlayerNavigationRequest(request: PlayerNavigationRequest?): PlayerNavigationRequest? =+ request?.takeIf { isStreamUrlSafe(it.streamUrl) }+diff --git a/app/src/main/java/com/streamvault/app/navigation/AppNavigationExternalNavigation.kt b/app/src/main/java/com/streamvault/app/navigation/AppNavigationExternalNavigation.ktnew file mode 100644index 00000000..fee486bb--- /dev/null+++ b/app/src/main/java/com/streamvault/app/navigation/AppNavigationExternalNavigation.kt@@ -0,0 +1,52 @@+package com.streamvault.app.navigation++import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.navigation.NavBackStackEntry+import androidx.navigation.NavHostController++@Composable+internal fun ExternalNavigationHost(+ request: ExternalNavigationRequest?,+ currentBackStackEntry: NavBackStackEntry?,+ navController: NavHostController,+ onRequestHandled: () -> Unit+) {+ LaunchedEffect(request, currentBackStackEntry) {+ val entry = currentBackStackEntry ?: return@LaunchedEffect+ entry.lifecycle.awaitResumed()+ when (request) {+ is ExternalNavigationRequest.Player -> {+ if (navController.navigateToExternalPlayer(request.request)) {+ onRequestHandled()+ }+ }++ is ExternalNavigationRequest.Destination -> {+ if (navController.navigateIfResumed(request.destination.toRoute()) { launchSingleTop = true }) {+ onRequestHandled()+ }+ }++ is ExternalNavigationRequest.ImportM3u -> {+ if (navController.navigateIfResumed(Routes.providerSetup(importUri = request.uri)) { launchSingleTop = true }) {+ onRequestHandled()+ }+ }++ is ExternalNavigationRequest.ImportBackup -> {+ if (navController.navigateIfResumed(Routes.settings(backupUri = request.uri)) { launchSingleTop = true }) {+ onRequestHandled()+ }+ }++ is ExternalNavigationRequest.Search -> {+ if (navController.navigateIfResumed(Routes.search(request.query)) { launchSingleTop = true }) {+ onRequestHandled()+ }+ }++ null -> Unit+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/navigation/AppNavigationGraph.kt b/app/src/main/java/com/streamvault/app/navigation/AppNavigationGraph.ktnew file mode 100644index 00000000..266ceed7--- /dev/null+++ b/app/src/main/java/com/streamvault/app/navigation/AppNavigationGraph.kt@@ -0,0 +1,550 @@+package com.streamvault.app.navigation++import android.net.Uri+import android.util.Log+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.produceState+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import androidx.lifecycle.compose.dropUnlessResumed+import androidx.navigation.NavHostController+import androidx.navigation.NavOptionsBuilder+import androidx.navigation.NavType+import androidx.navigation.compose.NavHost+import androidx.navigation.compose.composable+import androidx.navigation.compose.currentBackStackEntryAsState+import androidx.navigation.compose.rememberNavController+import androidx.navigation.navArgument+import com.streamvault.app.ui.model.isArchivePlayable+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.Episode+import com.streamvault.domain.model.Movie+import com.streamvault.domain.repository.ChannelRepository+import com.streamvault.app.ui.screens.dashboard.DashboardScreen+import com.streamvault.app.ui.screens.multiview.MultiViewScreen+import com.streamvault.app.ui.screens.home.HomeScreen+import com.streamvault.app.ui.screens.movies.MoviesScreen+import com.streamvault.app.ui.screens.player.PlayerScreen+import com.streamvault.app.ui.screens.plugins.PluginsScreen+import com.streamvault.app.ui.screens.provider.ProviderSetupScreen+import com.streamvault.app.ui.screens.series.SeriesScreen+import com.streamvault.app.ui.screens.vod.VodScreen+import com.streamvault.app.ui.screens.settings.SettingsScreen+import com.streamvault.app.ui.screens.welcome.WelcomeScreen+import com.streamvault.app.ui.screens.downloads.DownloadsScreen+import com.streamvault.app.MainActivity+import com.streamvault.domain.model.AppLandingDestination+import com.streamvault.domain.model.AppTopLevelDestination+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.CatalogLayout+import com.streamvault.domain.model.MovieDetailPresentationHint+import com.streamvault.domain.model.ActiveLiveSource+import com.streamvault.domain.model.Series+import com.streamvault.domain.model.SeriesDetailPresentationHint+import com.streamvault.domain.model.VirtualCategoryIds+import java.io.Serializable+import kotlin.coroutines.resume+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch+import kotlinx.coroutines.suspendCancellableCoroutine+++@Composable+internal fun AppNavigationGraph(+ navController: NavHostController,+ startupRoute: String?,+ navigateToStartupTarget: (String) -> Boolean,+ tabNavigate: (String) -> Unit+) {+ NavHost(+ navController = navController,+ startDestination = Routes.WELCOME+ ) {+ composable(Routes.WELCOME) {+ WelcomeScreen(+ onNavigateToHome = dropUnlessResumed {+ navigateToStartupTarget(Routes.WELCOME)+ },+ startupReady = startupRoute != null,+ onNavigateToSetup = dropUnlessResumed {+ navController.navigate(Routes.providerSetup()) {+ popUpTo(Routes.WELCOME) { inclusive = true }+ }+ }+ )+ }++ composable(+ route = Routes.PROVIDER_SETUP,+ arguments = listOf(+ navArgument("providerId") { type = NavType.LongType; defaultValue = -1L },+ navArgument("importUri") { type = NavType.StringType; defaultValue = "" }+ )+ ) { backStackEntry ->+ val providerId = backStackEntry.arguments?.getLong("providerId")?.takeIf { it != -1L }+ val importUri = backStackEntry.arguments?.getString("importUri")?.takeIf { it.isNotBlank() }++ ProviderSetupScreen(+ editProviderId = providerId,+ initialImportUri = importUri,+ onBack = { navController.popBackStack() },+ onProviderAdded = dropUnlessResumed {+ navigateToStartupTarget(Routes.PROVIDER_SETUP)+ }+ )+ }+// ...++ composable(Routes.HOME) {+ DashboardScreen(+ onNavigate = { route -> tabNavigate(route) },+ onAddProvider = dropUnlessResumed {+ navController.navigate(Routes.providerSetup(null))+ },+ onRecentChannelClick = { channel, combinedProfileId ->+ navController.navigateToPlayer(+ Routes.livePlayer(+ channel = channel,+ categoryId = com.streamvault.domain.model.VirtualCategoryIds.RECENT,+ providerId = channel.providerId,+ isVirtual = true,+ combinedProfileId = combinedProfileId,+ returnRoute = Routes.HOME+ )+ )+ },+ onFavoriteChannelClick = { channel, combinedProfileId ->+ navController.navigateToPlayer(+ Routes.livePlayer(+ channel = channel,+ categoryId = com.streamvault.domain.model.VirtualCategoryIds.FAVORITES,+ providerId = channel.providerId,+ isVirtual = true,+ combinedProfileId = combinedProfileId,+ returnRoute = Routes.HOME+ )+ )+ },+ onMovieClick = { movie ->+ navController.navigateToMovieDetail(movie, Routes.HOME)+ },+ onSeriesClick = { series ->+ navController.navigateToSeriesDetail(series, Routes.HOME)+ },+ onPlaybackHistoryClick = { history ->+ val route = when (history.contentType) {+ com.streamvault.domain.model.ContentType.LIVE -> {+ Routes.player(+ streamUrl = history.streamUrl,+ title = history.title,+ internalId = history.contentId,+ providerId = history.providerId,+ contentType = history.contentType.name,+ returnRoute = Routes.HOME+ )+ }+ com.streamvault.domain.model.ContentType.MOVIE,+ com.streamvault.domain.model.ContentType.VOD -> {+ Routes.player(+ streamUrl = history.streamUrl,+ title = history.title,+ internalId = history.contentId,+ providerId = history.providerId,+ contentType = history.contentType.name,+ returnRoute = Routes.HOME+ )+ }+ com.streamvault.domain.model.ContentType.SERIES -> {+ Routes.seriesDetail(history.contentId, Routes.HOME)+ }+ com.streamvault.domain.model.ContentType.SERIES_EPISODE -> {+ Routes.player(+ streamUrl = history.streamUrl,+ title = history.title,+ internalId = history.contentId,+ providerId = history.providerId,+ contentType = history.contentType.name,+ returnRoute = Routes.HOME,+ seriesId = history.seriesId,+ seasonNumber = history.seasonNumber,+ episodeNumber = history.episodeNumber+ )+ }+ }+ if (route is PlayerNavigationRequest) {+ navController.navigateToPlayer(route)+ } else {+ navController.navigateIfResumed(route as String) { launchSingleTop = true }+ }+ },+ currentRoute = Routes.HOME+ )+ }++ composable(+ route = Routes.LIVE_TV_DESTINATION,+ arguments = listOf(+ navArgument("categoryId") { type = NavType.LongType; defaultValue = -1L }+ )+ ) { backStackEntry ->+ val initialCategoryId = backStackEntry.arguments?.getLong("categoryId")?.takeIf { it != -1L }+ HomeScreen(+ onChannelClick = { channel, category, provider, combinedProfileId, combinedSourceFilterProviderId ->+ navController.navigateToPlayer(+ Routes.livePlayer(+ channel = channel,+ categoryId = category?.id,+ providerId = provider?.id,+ isVirtual = category?.isVirtual == true,+ combinedProfileId = combinedProfileId,+ combinedSourceFilterProviderId = combinedSourceFilterProviderId,+ returnRoute = Routes.liveTv(category?.id)+ )+ )+ },+ onNavigate = { route -> tabNavigate(route) },+ currentRoute = Routes.LIVE_TV,+ initialCategoryId = initialCategoryId+ )+ }+// ... (rest of file)++ composable(Routes.MOVIES) {+ MoviesScreen(+ onMovieClick = { movie ->+ navController.navigateToMovieDetail(movie, Routes.MOVIES)+ },+ onContinueWatchingPlay = { history ->+ navController.navigateToPlayer(+ history.toPlayerNavigationRequest().copy(returnRoute = Routes.MOVIES)+ )+ },+ onNavigate = { route -> tabNavigate(route) },+ currentRoute = Routes.MOVIES+ )+ }++ composable(Routes.SERIES) {+ SeriesScreen(+ onSeriesClick = { series ->+ navController.navigateToSeriesDetail(series, Routes.SERIES)+ },+ onSeriesIdClick = { seriesId ->+ navController.navigateIfResumed(Routes.seriesDetail(seriesId, Routes.SERIES))+ },+ onNavigate = { route -> tabNavigate(route) },+ currentRoute = Routes.SERIES+ )+ }++ composable(Routes.VOD) {+ VodScreen(+ onMovieClick = { movie ->+ navController.navigateToMovieDetail(movie, Routes.VOD)+ },+ onSeriesClick = { series ->+ navController.navigateToSeriesDetail(series, Routes.VOD)+ },+ onNavigate = { route -> tabNavigate(route) },+ currentRoute = Routes.VOD+ )+ }++ composable(Routes.DOWNLOADS) {+ DownloadsScreen(+ onNavigate = { route -> tabNavigate(route) },+ currentRoute = Routes.DOWNLOADS+ )+ }++ composable(+ route = Routes.EPG_DESTINATION,+ arguments = listOf(+ navArgument("categoryId") { type = NavType.LongType; defaultValue = -1L },+ navArgument("anchorTime") { type = NavType.LongType; defaultValue = -1L },+ navArgument("favoritesOnly") { type = NavType.BoolType; defaultValue = false }+ )+ ) { backStackEntry ->+ val epgCategoryId = backStackEntry.arguments?.getLong("categoryId")?.takeIf { it != -1L }+ val epgAnchorTime = backStackEntry.arguments?.getLong("anchorTime")?.takeIf { it != -1L }+ val epgFavoritesOnly = backStackEntry.arguments?.getBoolean("favoritesOnly") ?: false+ com.streamvault.app.ui.screens.epg.FullEpgScreen(+ currentRoute = Routes.EPG,+ initialCategoryId = epgCategoryId,+ initialAnchorTime = epgAnchorTime,+ initialFavoritesOnly = epgFavoritesOnly,+ onPlayChannel = { channel, categoryId, isVirtual, combinedProfileId, returnRoute ->+ navController.navigateToPlayer(+ Routes.livePlayer(+ channel = channel,+ categoryId = categoryId,+ providerId = channel.providerId,+ isVirtual = isVirtual,+ combinedProfileId = combinedProfileId,+ returnRoute = returnRoute+ )+ )+ },+ onPlayArchive = { channel, program, categoryId, isVirtual, combinedProfileId, returnRoute ->+ if (!channel.isArchivePlayable(program)) {+ return@FullEpgScreen+ }+ navController.navigateToPlayer(+ Routes.player(+ streamUrl = channel.streamUrl,+ title = channel.name,+ channelId = channel.epgChannelId,+ internalId = channel.id,+ categoryId = categoryId,+ providerId = channel.providerId,+ isVirtual = isVirtual,+ combinedProfileId = combinedProfileId,+ contentType = "LIVE",+ archiveStartMs = program.startTime,+ archiveEndMs = program.endTime,+ archiveTitle = "${channel.name}: ${program.title}",+ returnRoute = returnRoute+ )+ )+ },+ onNavigate = { route -> tabNavigate(route) }+ )+ }++ composable(+ route = Routes.SETTINGS_DESTINATION,+ arguments = listOf(+ navArgument("backupUri") { type = NavType.StringType; defaultValue = "" }+ )+ ) { backStackEntry ->+ val backupUri = backStackEntry.arguments?.getString("backupUri")?.takeIf { it.isNotBlank() }+ SettingsScreen(+ onNavigate = { route -> tabNavigate(route) },+ onAddProvider = dropUnlessResumed {+ navController.navigate(Routes.providerSetup(null))+ },+ onEditProvider = { provider ->+ navController.navigateIfResumed(Routes.providerSetup(provider.id))+ },+ onNavigateToParentalControl = { providerId ->+ navController.navigateIfResumed(Routes.parentalControlGroups(providerId))+ },+ currentRoute = Routes.SETTINGS,+ initialBackupImportUri = backupUri+ )+ }++ composable(Routes.PLUGINS) {+ PluginsScreen(+ currentRoute = Routes.PLUGINS,+ onNavigate = { route -> tabNavigate(route) }+ )+ }++ composable(+ route = Routes.PARENTAL_CONTROL_GROUPS,+ arguments = listOf(+ navArgument("providerId") { type = NavType.LongType }+ )+ ) {+ com.streamvault.app.ui.screens.settings.parental.ParentalControlGroupScreen(+ currentRoute = Routes.SETTINGS,+ onNavigate = { route -> tabNavigate(route) },+ onBack = { navController.popBackStack() }+ )+ }++ composable(+ route = Routes.SEARCH_DESTINATION,+ arguments = listOf(+ navArgument("query") { type = NavType.StringType; defaultValue = "" }+ )+ ) { backStackEntry ->+ com.streamvault.app.ui.screens.search.SearchScreen(+ initialQuery = backStackEntry.arguments?.getString("query").orEmpty(),+ onChannelClick = { channel ->+ navController.navigateToPlayer(+ Routes.livePlayer(+ channel = channel,+ categoryId = channel.categoryId ?: ChannelRepository.ALL_CHANNELS_ID,+ providerId = channel.providerId,+ isVirtual = false,+ returnRoute = Routes.search(backStackEntry.arguments?.getString("query").orEmpty())+ )+ )+ },+ onMovieClick = { movie ->+ navController.navigateToMovieDetail(+ movie,+ Routes.search(backStackEntry.arguments?.getString("query").orEmpty())+ )+ },+ onSeriesClick = { series ->+ navController.navigateToSeriesDetail(+ series,+ Routes.search(backStackEntry.arguments?.getString("query").orEmpty())+ )+ },+ onNavigate = { route -> tabNavigate(route) },+ currentRoute = Routes.SEARCH+ )+ }++ composable(route = Routes.PLAYER) { backStackEntry ->+ val playerRequest = backStackEntry.savedStateHandle.get<PlayerNavigationRequest>(PLAYER_REQUEST_KEY)+ ?: navController.previousBackStackEntry?.savedStateHandle?.get<PlayerNavigationRequest>(PLAYER_REQUEST_KEY)?.also {+ backStackEntry.savedStateHandle[PLAYER_REQUEST_KEY] = it+ }+ val safePlayerRequest = safePlayerNavigationRequest(playerRequest)+ if (safePlayerRequest == null) {+ LaunchedEffect(playerRequest) {+ Log.w(APP_NAVIGATION_TAG, "Missing or invalid player request; returning to previous destination")+ if (!navController.popBackStack()) {+ navController.navigate(Routes.HOME) {+ popUpTo(Routes.PLAYER) { inclusive = true }+ launchSingleTop = true+ }+ }+ }+ } else {+ PlayerScreen(+ streamUrl = safePlayerRequest.streamUrl,+ title = safePlayerRequest.title,+ epgChannelId = safePlayerRequest.channelId,+ internalChannelId = safePlayerRequest.internalId,+ categoryId = safePlayerRequest.categoryId,+ providerId = safePlayerRequest.providerId,+ isVirtual = safePlayerRequest.isVirtual,+ combinedProfileId = safePlayerRequest.combinedProfileId,+ combinedSourceFilterProviderId = safePlayerRequest.combinedSourceFilterProviderId,+ contentType = safePlayerRequest.contentType,+ artworkUrl = safePlayerRequest.artworkUrl,+ archiveStartMs = safePlayerRequest.archiveStartMs,+ archiveEndMs = safePlayerRequest.archiveEndMs,+ archiveTitle = safePlayerRequest.archiveTitle,+ returnRoute = safePlayerRequest.returnRoute,+ seriesId = safePlayerRequest.seriesId,+ seasonNumber = safePlayerRequest.seasonNumber,+ episodeNumber = safePlayerRequest.episodeNumber,+ episodeId = safePlayerRequest.episodeId,+ onBack = {+ val route = safePlayerRequest.returnRoute+ if (!route.isNullOrBlank() && navController.popBackStack(route, false)) {+ // Popped back to the exact route already in the backstack (same VM, handoff works)+ Unit+ } else if (!route.isNullOrBlank()) {+ // Nothing left to pop — navigate to the return route or home as a last resort+ navController.navigate(route) {+ popUpTo(Routes.PLAYER) { inclusive = true }+ launchSingleTop = true+ restoreState = true+ }+ } else if (!navController.popBackStack()) {+ navController.navigate(Routes.HOME) {+ popUpTo(Routes.PLAYER) { inclusive = true }+ launchSingleTop = true+ restoreState = true+ }+ }+ // else: plain popBackStack() succeeded — returns to existing Guide entry, preserving EpgViewModel+ },+ onNavigate = { route ->+ navController.navigateIfResumed(route) {+ launchSingleTop = true+ if (route == Routes.MULTI_VIEW) {+ popUpTo(Routes.PLAYER) { inclusive = true }+ }+ }+ }+ )+ }+ }++ composable(+ route = Routes.MOVIE_DETAIL,+ arguments = listOf(+ navArgument("movieId") { type = NavType.LongType },+ navArgument("returnRoute") { type = NavType.StringType; defaultValue = "" }+ )+ ) { backStackEntry ->+ val moviePresentationHint = backStackEntry.savedStateHandle.get<MovieDetailPresentationHint>(MOVIE_DETAIL_PRESENTATION_HINT_KEY)+ ?: navController.previousBackStackEntry?.savedStateHandle?.get<MovieDetailPresentationHint>(MOVIE_DETAIL_PRESENTATION_HINT_KEY)?.also {+ backStackEntry.savedStateHandle[MOVIE_DETAIL_PRESENTATION_HINT_KEY] = it+ }+ val returnRoute = backStackEntry.arguments?.getString("returnRoute").orEmpty().takeIf { it.isNotBlank() }+ val movieId = backStackEntry.arguments?.getLong("movieId") ?: -1L+ com.streamvault.app.ui.screens.movies.MovieDetailScreen(+ onPlay = { movie ->+ navController.navigateToPlayer(+ Routes.moviePlayer(movie).copy(+ returnRoute = Routes.movieDetail(+ movieId = movie.id.takeIf { it > 0L } ?: movieId,+ returnRoute = returnRoute+ )+ )+ )+ },+ onBack = {+ if (!returnRoute.isNullOrBlank()) {+ navController.navigate(returnRoute) {+ popUpTo(backStackEntry.destination.route ?: Routes.MOVIE_DETAIL) { inclusive = true }+ launchSingleTop = true+ }+ } else {+ navController.popBackStack()+ }+ }+ )+ }++ composable(+ route = Routes.SERIES_DETAIL,+ arguments = listOf(+ navArgument("seriesId") { type = NavType.LongType },+ navArgument("returnRoute") { type = NavType.StringType; defaultValue = "" }+ )+ ) { backStackEntry ->+ val seriesPresentationHint = backStackEntry.savedStateHandle.get<SeriesDetailPresentationHint>(SERIES_DETAIL_PRESENTATION_HINT_KEY)+ ?: navController.previousBackStackEntry?.savedStateHandle?.get<SeriesDetailPresentationHint>(SERIES_DETAIL_PRESENTATION_HINT_KEY)?.also {+ backStackEntry.savedStateHandle[SERIES_DETAIL_PRESENTATION_HINT_KEY] = it+ }+ val returnRoute = backStackEntry.arguments?.getString("returnRoute").orEmpty().takeIf { it.isNotBlank() }+ val seriesId = backStackEntry.arguments?.getLong("seriesId") ?: -1L+ com.streamvault.app.ui.screens.series.SeriesDetailScreen(+ onEpisodeClick = { episode ->+ navController.navigateToPlayer(+ Routes.episodePlayer(episode).copy(+ returnRoute = Routes.seriesDetail(+ seriesId = episode.seriesId.takeIf { it > 0L } ?: seriesId,+ returnRoute = returnRoute+ )+ )+ )+ },+ onBack = {+ if (!returnRoute.isNullOrBlank()) {+ navController.navigate(returnRoute) {+ popUpTo(backStackEntry.destination.route ?: Routes.SERIES_DETAIL) { inclusive = true }+ launchSingleTop = true+ }+ } else {+ navController.popBackStack()+ }+ }+ )+ }++ composable(Routes.MULTI_VIEW) {+ MultiViewScreen(+ onBack = { navController.popBackStack() }+ )+ }+ }}+diff --git a/app/src/main/java/com/streamvault/app/navigation/AppNavigationPolicy.kt b/app/src/main/java/com/streamvault/app/navigation/AppNavigationPolicy.ktnew file mode 100644index 00000000..7f80e7ed--- /dev/null+++ b/app/src/main/java/com/streamvault/app/navigation/AppNavigationPolicy.kt@@ -0,0 +1,21 @@+package com.streamvault.app.navigation++import com.streamvault.domain.model.AppLandingDestination+import com.streamvault.domain.model.CatalogLayout+import com.streamvault.domain.model.ContentType++internal fun requiresResolvedStartupTarget(landingDestination: AppLandingDestination): Boolean =+ landingDestination == AppLandingDestination.FIRST_FAVORITE_LIVE ||+ landingDestination == AppLandingDestination.LAST_WATCHED_LIVE++internal fun resolveCatalogRoute(+ layout: CatalogLayout?,+ requestedRoute: String,+ lastSplitCatalogType: ContentType,+ splitPreferenceReady: Boolean+): String = when {+ layout != CatalogLayout.SPLIT && requestedRoute in setOf(Routes.MOVIES, Routes.SERIES) -> Routes.VOD+ layout == CatalogLayout.SPLIT && requestedRoute == Routes.VOD && splitPreferenceReady ->+ if (lastSplitCatalogType == ContentType.SERIES) Routes.SERIES else Routes.MOVIES+ else -> requestedRoute+}diff --git a/app/src/main/java/com/streamvault/app/navigation/AppNavigationStartupPolicy.kt b/app/src/main/java/com/streamvault/app/navigation/AppNavigationStartupPolicy.ktnew file mode 100644index 00000000..a9cdc4b0--- /dev/null+++ b/app/src/main/java/com/streamvault/app/navigation/AppNavigationStartupPolicy.kt@@ -0,0 +1,112 @@+package com.streamvault.app.navigation++import com.streamvault.app.MainActivity+import com.streamvault.domain.model.ActiveLiveSource+import com.streamvault.domain.model.AppLandingDestination+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.VirtualCategoryIds+import kotlinx.coroutines.flow.first++internal suspend fun resolveStartupPlayerRequest(+ mainActivity: MainActivity,+ landingDestination: AppLandingDestination+): PlayerNavigationRequest? = when (landingDestination) {+ AppLandingDestination.FIRST_FAVORITE_LIVE -> resolveFirstFavoriteStartupTarget(mainActivity)+ AppLandingDestination.LAST_WATCHED_LIVE -> resolveLastWatchedStartupTarget(mainActivity)+ else -> null+}++private suspend fun resolveFirstFavoriteStartupTarget(+ mainActivity: MainActivity+): PlayerNavigationRequest? {+ if (!mainActivity.preferencesRepository.showFavoritesCategory.first()) return null+ val context = resolveLiveStartupContext(mainActivity) ?: return null+ val favorites = when (context) {+ is LiveStartupContext.Provider -> mainActivity.favoriteRepository.getFavorites(context.providerId, ContentType.LIVE).first()+ is LiveStartupContext.Combined -> mainActivity.favoriteRepository.getFavorites(context.providerIds, ContentType.LIVE).first()+ }.sortedBy { it.position }+ return resolveStartupChannelTarget(+ mainActivity = mainActivity,+ channelIds = favorites.map { it.contentId },+ sourceContext = context,+ virtualCategoryId = VirtualCategoryIds.FAVORITES+ )+}++private suspend fun resolveLastWatchedStartupTarget(+ mainActivity: MainActivity+): PlayerNavigationRequest? {+ val context = resolveLiveStartupContext(mainActivity) ?: return null+ val recentHistory = when (context) {+ is LiveStartupContext.Provider -> mainActivity.playbackHistoryRepository.getRecentlyWatchedByProvider(context.providerId, limit = 24).first()+ is LiveStartupContext.Combined -> mainActivity.playbackHistoryRepository.getRecentlyWatchedByProviders(context.providerIds.toSet(), limit = 24).first()+ }+ return resolveStartupChannelTarget(+ mainActivity = mainActivity,+ channelIds = recentHistory+ .filter { it.contentType == ContentType.LIVE }+ .sortedByDescending { it.lastWatchedAt }+ .map { it.contentId },+ sourceContext = context,+ virtualCategoryId = VirtualCategoryIds.RECENT+ )+}++private suspend fun resolveStartupChannelTarget(+ mainActivity: MainActivity,+ channelIds: List<Long>,+ sourceContext: LiveStartupContext,+ virtualCategoryId: Long+): PlayerNavigationRequest? {+ if (channelIds.isEmpty()) return null+ val hiddenChannelIdsByProvider = sourceContext.providerIds.associateWith { providerId ->+ mainActivity.preferencesRepository.getHiddenChannelIds(providerId).first()+ }+ for (channelId in channelIds.distinct()) {+ val channel = mainActivity.channelRepository.getChannel(channelId) ?: continue+ if (channel.providerId !in sourceContext.providerIds) continue+ if (channel.id in hiddenChannelIdsByProvider[channel.providerId].orEmpty()) continue+ return Routes.livePlayer(+ channel = channel,+ categoryId = virtualCategoryId,+ providerId = channel.providerId,+ isVirtual = true,+ combinedProfileId = (sourceContext as? LiveStartupContext.Combined)?.profileId,+ returnRoute = Routes.LIVE_TV+ )+ }+ return null+}++private suspend fun resolveLiveStartupContext(+ mainActivity: MainActivity+): LiveStartupContext? {+ return when (val activeSource = mainActivity.combinedM3uRepository.getActiveLiveSource().first()) {+ is ActiveLiveSource.ProviderSource -> LiveStartupContext.Provider(activeSource.providerId)+ is ActiveLiveSource.CombinedM3uSource -> {+ val providerIds = mainActivity.combinedM3uRepository.getProfile(activeSource.profileId)+ ?.members+ .orEmpty()+ .filter { it.enabled }+ .map { it.providerId }+ .distinct()+ if (providerIds.isEmpty()) null else LiveStartupContext.Combined(activeSource.profileId, providerIds)+ }+ null -> {+ mainActivity.providerRepository.getActiveProvider().first()?.id?.let { providerId ->+ LiveStartupContext.Provider(providerId)+ }+ }+ }+}++private sealed interface LiveStartupContext {+ val providerIds: List<Long>++ data class Provider(val providerId: Long) : LiveStartupContext {+ override val providerIds: List<Long> = listOf(providerId)+ }++ data class Combined(val profileId: Long, override val providerIds: List<Long>) : LiveStartupContext+}+diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerBackNavigationPolicy.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerBackNavigationPolicy.ktindex 12a60412..ca7421ed 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerBackNavigationPolicy.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerBackNavigationPolicy.kt@@ -67,3 +67,8 @@ internal fun playerBackAction(state: PlayerBackNavigationState): PlayerBackActiostate.showControls -> PlayerBackAction.TOGGLE_CONTROLSelse -> PlayerBackAction.NAVIGATE_BACK}++/** Builds the Back decision from current state when the event is handled. */+internal fun playerBackActionAtEvent(+ stateProvider: () -> PlayerBackNavigationState+): PlayerBackAction = playerBackAction(stateProvider())diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerControlsOverlayHost.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerControlsOverlayHost.ktindex 78767304..530ad56a 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerControlsOverlayHost.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerControlsOverlayHost.kt@@ -22,6 +22,7 @@ internal fun PlayerControlsOverlayHost(visible: Boolean,title: String,contentType: String,+ modifier: Modifier = Modifier,isCatchUpPlayback: Boolean = false,isPlaying: Boolean,currentProgram: Program?,@@ -41,7 +42,6 @@ internal fun PlayerControlsOverlayHost(timeshiftUiState: PlayerTimeshiftUiState,playButtonFocusRequester: FocusRequester,quickActionsFocusRequester: FocusRequester,- modifier: Modifier = Modifier,onClose: () -> Unit,onTogglePlayPause: () -> Unit,onSeekBackward: () -> Unit,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerInputPolicy.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerInputPolicy.ktnew file mode 100644index 00000000..f781a62f--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerInputPolicy.kt@@ -0,0 +1,349 @@+package com.streamvault.app.ui.screens.player++internal sealed interface PlayerInputKey {+ data object DpadCenter : PlayerInputKey+ data object Enter : PlayerInputKey+ data object NumpadEnter : PlayerInputKey+ data object DpadLeft : PlayerInputKey+ data object DpadRight : PlayerInputKey+ data object DpadUp : PlayerInputKey+ data object DpadDown : PlayerInputKey+ data object DpadUpRight : PlayerInputKey+ data object DpadDownLeft : PlayerInputKey+ data object Back : PlayerInputKey+ data object MediaPlayPause : PlayerInputKey+ data class Mute(val isRepeat: Boolean) : PlayerInputKey+ data object ChannelUp : PlayerInputKey+ data object ChannelDown : PlayerInputKey+ data object MediaPrevious : PlayerInputKey+ data object Guide : PlayerInputKey+ data object Info : PlayerInputKey+ data object Menu : PlayerInputKey+ data class Digit(val value: Int) : PlayerInputKey+ data object Other : PlayerInputKey+}++internal data class PlayerInputState(+ val contentType: String,+ val isCatchUpPlayback: Boolean,+ val isRtl: Boolean,+ val nextEpisodeCountdownVisible: Boolean = false,+ val showChannelListOverlay: Boolean = false,+ val showCategoryListOverlay: Boolean = false,+ val showEpgOverlay: Boolean = false,+ val showChannelInfoOverlay: Boolean = false,+ val channelInfoSubPanelOpen: Boolean = false,+ val showDiagnostics: Boolean = false,+ val showTrackSelection: Boolean = false,+ val showVariantSelection: Boolean = false,+ val showSpeedSelection: Boolean = false,+ val showAudioVideoOffsetDialog: Boolean = false,+ val showStopPlaybackTimerDialog: Boolean = false,+ val showIdleStandbyTimerDialog: Boolean = false,+ val showProgramHistory: Boolean = false,+ val showSplitDialog: Boolean = false,+ val showEpisodePicker: Boolean = false,+ val showControls: Boolean = false,+ val hasPendingNumericChannelInput: Boolean = false,+ val canOpenEpisodePicker: Boolean = false+)++/**+ * Builds the input snapshot when an event is handled instead of reusing a+ * snapshot captured during composition. This matters for ViewModel-backed+ * buffers, whose value can change before Compose has had a chance to+ * recompose the screen.+ */+internal fun playerInputDecisionAtEvent(+ stateProvider: () -> PlayerInputState,+ key: PlayerInputKey+): PlayerInputDecision = playerInputDecision(stateProvider(), key)++internal sealed interface PlayerInputAction {+ data object Pass : PlayerInputAction+ data object Consume : PlayerInputAction+ data object PlayNext : PlayerInputAction+ data object PlayPrevious : PlayerInputAction+ data object CancelAutoPlay : PlayerInputAction+ data object DismissAudioVideoOffset : PlayerInputAction+ data object CloseSpeedSelection : PlayerInputAction+ data object CloseVariantSelection : PlayerInputAction+ data object CloseStopIdleTimersAndTrackSelection : PlayerInputAction+ data object CommitNumericChannelInput : PlayerInputAction+ data object OpenChannelInfo : PlayerInputAction+ data object CloseChannelInfo : PlayerInputAction+ data object OpenChannelList : PlayerInputAction+ data object OpenCategoryList : PlayerInputAction+ data object OpenEpg : PlayerInputAction+ data object SeekBackward : PlayerInputAction+ data object SeekForward : PlayerInputAction+ data object ToggleControls : PlayerInputAction+ data object TogglePlayback : PlayerInputAction+ data object ToggleMute : PlayerInputAction+ data object ZapToLastChannel : PlayerInputAction+ data object ShowEpisodePicker : PlayerInputAction+ data class InputNumericDigit(val digit: Int) : PlayerInputAction+ data object DelegateBack : PlayerInputAction+}++internal data class PlayerInputDecision(+ val action: PlayerInputAction,+ val notifyLiveOverlayInteraction: Boolean = false+)++internal fun playerPreviewInputDecision(+ state: PlayerInputState,+ key: PlayerInputKey+): PlayerInputDecision {+ if (state.nextEpisodeCountdownVisible || state.contentType != "LIVE") {+ return PlayerInputDecision(PlayerInputAction.Pass)+ }+ if (+ state.showChannelListOverlay ||+ state.showCategoryListOverlay ||+ state.showEpgOverlay ||+ state.showDiagnostics ||+ state.showTrackSelection ||+ state.showVariantSelection ||+ state.showSpeedSelection ||+ state.showAudioVideoOffsetDialog ||+ state.showStopPlaybackTimerDialog ||+ state.showIdleStandbyTimerDialog ||+ state.showProgramHistory ||+ state.showSplitDialog ||+ state.showEpisodePicker ||+ (state.showChannelInfoOverlay && state.channelInfoSubPanelOpen)+ ) {+ return PlayerInputDecision(PlayerInputAction.Pass)+ }++ val notifyInteraction = state.showChannelInfoOverlay || state.showDiagnostics+ return when (key) {+ PlayerInputKey.DpadUp,+ PlayerInputKey.ChannelUp,+ PlayerInputKey.DpadUpRight -> PlayerInputDecision(PlayerInputAction.PlayNext, notifyInteraction)+ PlayerInputKey.DpadDown,+ PlayerInputKey.ChannelDown,+ PlayerInputKey.DpadDownLeft -> PlayerInputDecision(PlayerInputAction.PlayPrevious, notifyInteraction)+ else -> PlayerInputDecision(PlayerInputAction.Pass)+ }+}++internal fun playerInputDecision(+ state: PlayerInputState,+ key: PlayerInputKey+): PlayerInputDecision {+ if (state.nextEpisodeCountdownVisible) {+ return if (key == PlayerInputKey.Back) {+ PlayerInputDecision(PlayerInputAction.CancelAutoPlay)+ } else {+ PlayerInputDecision(PlayerInputAction.Consume)+ }+ }++ when {+ state.showAudioVideoOffsetDialog ->+ return modalInputDecision(PlayerInputAction.DismissAudioVideoOffset, key)+ state.showSpeedSelection ->+ return modalInputDecision(PlayerInputAction.CloseSpeedSelection, key)+ state.showVariantSelection ->+ return modalInputDecision(PlayerInputAction.CloseVariantSelection, key)+ state.showTrackSelection || state.showStopPlaybackTimerDialog || state.showIdleStandbyTimerDialog ->+ return modalInputDecision(PlayerInputAction.CloseStopIdleTimersAndTrackSelection, key)+ }++ return when (key) {+ PlayerInputKey.DpadCenter,+ PlayerInputKey.Enter -> {+ val notifyInteraction = state.showChannelListOverlay ||+ state.showEpgOverlay ||+ state.showChannelInfoOverlay ||+ state.showDiagnostics+ val action = when {+ state.contentType == "LIVE" && !state.isCatchUpPlayback && state.hasPendingNumericChannelInput ->+ PlayerInputAction.CommitNumericChannelInput+ state.contentType == "LIVE" && !state.isCatchUpPlayback ->+ if (state.showChannelInfoOverlay) PlayerInputAction.CloseChannelInfo+ else PlayerInputAction.OpenChannelInfo+ state.showControls -> PlayerInputAction.Pass+ else -> PlayerInputAction.ToggleControls+ }+ PlayerInputDecision(action, notifyInteraction)+ }++ PlayerInputKey.DpadLeft -> directionalInputDecision(state, isLeft = true)+ PlayerInputKey.DpadRight -> directionalInputDecision(state, isLeft = false)+ PlayerInputKey.DpadUp -> verticalInputDecision(state, isUp = true)+ PlayerInputKey.DpadDown -> verticalInputDecision(state, isUp = false)+ PlayerInputKey.Back -> PlayerInputDecision(PlayerInputAction.DelegateBack)+ PlayerInputKey.MediaPlayPause -> PlayerInputDecision(PlayerInputAction.TogglePlayback)+ is PlayerInputKey.Mute -> PlayerInputDecision(+ if (key.isRepeat) PlayerInputAction.Consume else PlayerInputAction.ToggleMute+ )+ PlayerInputKey.ChannelUp,+ PlayerInputKey.DpadUpRight -> channelStepDecision(state, isUp = true)+ PlayerInputKey.ChannelDown,+ PlayerInputKey.DpadDownLeft -> channelStepDecision(state, isUp = false)+ PlayerInputKey.MediaPrevious -> if (state.channelInfoSubPanelOpen) {+ PlayerInputDecision(PlayerInputAction.Consume)+ } else if (state.contentType == "LIVE") {+ PlayerInputDecision(PlayerInputAction.ZapToLastChannel)+ } else {+ PlayerInputDecision(PlayerInputAction.Pass)+ }+ PlayerInputKey.Guide -> if (state.contentType == "LIVE") {+ PlayerInputDecision(PlayerInputAction.OpenEpg)+ } else {+ PlayerInputDecision(PlayerInputAction.Pass)+ }+ PlayerInputKey.Info -> PlayerInputDecision(+ action = if (state.contentType == "LIVE") {+ if (state.showChannelInfoOverlay) PlayerInputAction.CloseChannelInfo+ else PlayerInputAction.OpenChannelInfo+ } else {+ PlayerInputAction.ToggleControls+ },+ notifyLiveOverlayInteraction = state.showChannelListOverlay ||+ state.showEpgOverlay ||+ state.showChannelInfoOverlay ||+ state.showDiagnostics+ )+ PlayerInputKey.Menu -> PlayerInputDecision(+ action = PlayerInputAction.ToggleControls,+ notifyLiveOverlayInteraction = state.showChannelListOverlay ||+ state.showEpgOverlay ||+ state.showChannelInfoOverlay ||+ state.showDiagnostics+ )+ is PlayerInputKey.Digit -> if (state.contentType == "LIVE") {+ PlayerInputDecision(PlayerInputAction.InputNumericDigit(key.value))+ } else {+ PlayerInputDecision(PlayerInputAction.Pass)+ }+ PlayerInputKey.NumpadEnter,+ PlayerInputKey.Other -> PlayerInputDecision(PlayerInputAction.Pass)+ }+}++private fun modalInputDecision(+ backAction: PlayerInputAction,+ key: PlayerInputKey+): PlayerInputDecision = when {+ key == PlayerInputKey.Back -> PlayerInputDecision(backAction)+ key.isDialogNavigationKey() -> PlayerInputDecision(PlayerInputAction.Pass)+ else -> PlayerInputDecision(PlayerInputAction.Consume)+}++private fun PlayerInputKey.isDialogNavigationKey(): Boolean = when (this) {+ PlayerInputKey.DpadUp,+ PlayerInputKey.DpadDown,+ PlayerInputKey.DpadLeft,+ PlayerInputKey.DpadRight,+ PlayerInputKey.DpadCenter,+ PlayerInputKey.Enter,+ PlayerInputKey.NumpadEnter -> true+ else -> false+}++private fun directionalInputDecision(+ state: PlayerInputState,+ isLeft: Boolean+): PlayerInputDecision {+ val notifyInteraction = if (isLeft) {+ state.showChannelListOverlay ||+ state.showCategoryListOverlay ||+ state.showEpgOverlay ||+ state.showChannelInfoOverlay ||+ state.showDiagnostics+ } else {+ state.showChannelListOverlay ||+ state.showEpgOverlay ||+ state.showChannelInfoOverlay ||+ state.showDiagnostics+ }++ if (state.showControls && (state.contentType != "LIVE" || state.isCatchUpPlayback)) {+ return PlayerInputDecision(PlayerInputAction.Pass, notifyInteraction)+ }++ if (isLeft && state.showChannelListOverlay && state.contentType == "LIVE" && !state.isCatchUpPlayback) {+ return PlayerInputDecision(PlayerInputAction.OpenCategoryList, notifyInteraction)+ }+ val liveWithoutOverlay = state.contentType == "LIVE" &&+ !state.isCatchUpPlayback &&+ !state.showChannelListOverlay &&+ !state.showEpgOverlay &&+ !state.showChannelInfoOverlay &&+ (isLeft.not() || !state.showCategoryListOverlay)+ if (liveWithoutOverlay) {+ val openChannelList = if (isLeft) !state.isRtl else state.isRtl+ return PlayerInputDecision(+ if (openChannelList) PlayerInputAction.OpenChannelList else PlayerInputAction.OpenEpg,+ notifyInteraction+ )+ }++ val noSeekBlockingOverlay = if (isLeft) {+ !state.showChannelListOverlay &&+ !state.showCategoryListOverlay &&+ !state.showEpgOverlay &&+ !state.showChannelInfoOverlay+ } else {+ !state.showChannelListOverlay &&+ !state.showEpgOverlay &&+ !state.showChannelInfoOverlay+ }+ if (!noSeekBlockingOverlay) {+ return PlayerInputDecision(PlayerInputAction.Pass, notifyInteraction)+ }++ val seekBackward = if (isLeft) !state.isRtl else state.isRtl+ return PlayerInputDecision(+ if (seekBackward) PlayerInputAction.SeekBackward else PlayerInputAction.SeekForward,+ notifyInteraction+ )+}++private fun channelStepDecision(+ state: PlayerInputState,+ isUp: Boolean+): PlayerInputDecision = when {+ state.showDiagnostics || (state.showChannelInfoOverlay && state.channelInfoSubPanelOpen) ->+ PlayerInputDecision(PlayerInputAction.Consume)+ state.contentType == "LIVE" ->+ PlayerInputDecision(if (isUp) PlayerInputAction.PlayNext else PlayerInputAction.PlayPrevious)+ else -> PlayerInputDecision(PlayerInputAction.Pass)+}++private fun verticalInputDecision(+ state: PlayerInputState,+ isUp: Boolean+): PlayerInputDecision {+ val notifyInteraction = state.showChannelListOverlay ||+ state.showCategoryListOverlay ||+ state.showEpgOverlay ||+ state.showChannelInfoOverlay ||+ state.showDiagnostics+ if (state.showChannelInfoOverlay && state.channelInfoSubPanelOpen) {+ return PlayerInputDecision(PlayerInputAction.Pass, notifyInteraction)+ }+ val blocksVerticalNavigation = state.showChannelListOverlay ||+ state.showCategoryListOverlay ||+ state.showEpgOverlay ||+ state.showDiagnostics ||+ (isUp && state.showChannelInfoOverlay)+ if (blocksVerticalNavigation) {+ return PlayerInputDecision(PlayerInputAction.Pass, notifyInteraction)+ }+ if (state.showControls && (state.contentType != "LIVE" || state.isCatchUpPlayback)) {+ return PlayerInputDecision(PlayerInputAction.Pass, notifyInteraction)+ }+ val action = if (state.contentType == "LIVE" && !state.isCatchUpPlayback) {+ if (isUp) PlayerInputAction.PlayNext else PlayerInputAction.PlayPrevious+ } else if (isUp && state.canOpenEpisodePicker) {+ PlayerInputAction.ShowEpisodePicker+ } else {+ PlayerInputAction.ToggleControls+ }+ return PlayerInputDecision(action, notifyInteraction)+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerModalHosts.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerModalHosts.ktnew file mode 100644index 00000000..a17f2133--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerModalHosts.kt@@ -0,0 +1,162 @@+package com.streamvault.app.ui.screens.player++import androidx.compose.runtime.Composable+import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel+import com.streamvault.app.ui.components.dialogs.ProgramHistoryDialog+import com.streamvault.app.ui.screens.multiview.MultiViewPlannerDialog+import com.streamvault.app.ui.screens.multiview.MultiViewViewModel+import com.streamvault.app.ui.screens.player.overlay.ChannelVariantSelectionDialog+import com.streamvault.app.ui.screens.player.overlay.PlayerAudioVideoOffsetDialog+import com.streamvault.app.ui.screens.player.overlay.PlayerEpisodeSelectionDialog+import com.streamvault.app.ui.screens.player.overlay.PlayerSleepTimerDialog+import com.streamvault.app.ui.screens.player.overlay.PlayerSpeedSelectionDialog+import com.streamvault.app.ui.screens.player.overlay.PlayerTrackSelectionDialog+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.Episode+import com.streamvault.domain.model.Program+import com.streamvault.domain.model.Season+import com.streamvault.player.PlayerTrack+import com.streamvault.player.TrackType++@Composable+internal fun PlayerTopLevelModalHost(+ isInPictureInPictureMode: Boolean,+ showProgramHistory: Boolean,+ programHistory: List<Program>,+ onDismissProgramHistory: () -> Unit,+ onSelectProgramHistory: (Program) -> Unit,+ showSplitDialog: Boolean,+ currentChannel: Channel?,+ onDismissSplitDialog: () -> Unit,+ onLaunchMultiView: () -> Unit,+) {+ if (!isInPictureInPictureMode && showProgramHistory) {+ ProgramHistoryDialog(+ programs = programHistory,+ onDismiss = onDismissProgramHistory,+ onProgramSelect = onSelectProgramHistory+ )+ }++ if (showSplitDialog && currentChannel != null) {+ val multiViewViewModel: MultiViewViewModel = hiltViewModel()+ MultiViewPlannerDialog(+ pendingChannel = currentChannel,+ onDismiss = onDismissSplitDialog,+ onLaunch = onLaunchMultiView,+ viewModel = multiViewViewModel+ )+ }+}++@Composable+internal fun PlayerControlsModalHost(+ isInPictureInPictureMode: Boolean,+ showTrackSelection: TrackType?,+ availableAudioTracks: List<PlayerTrack>,+ availableSubtitleTracks: List<PlayerTrack>,+ availableVideoQualities: List<PlayerTrack>,+ liveTranslationAvailable: Boolean,+ liveTranslationActive: Boolean,+ onDismissTrackSelection: () -> Unit,+ onSelectAudio: (String) -> Unit,+ onSelectVideo: (String) -> Unit,+ onSelectSubtitle: (String?) -> Unit,+ onSelectLiveTranslation: () -> Unit,+ showVariantSelection: Boolean,+ currentChannel: Channel?,+ onDismissVariantSelection: () -> Unit,+ onSelectVariant: (Long) -> Unit,+ showSpeedSelection: Boolean,+ playbackSpeed: Float,+ onDismissSpeedSelection: () -> Unit,+ onSelectSpeed: (Float) -> Unit,+ showStopPlaybackTimerDialog: Boolean,+ stopPlaybackTimerTitle: String,+ stopPlaybackTimerMinutes: Int,+ onDismissStopPlaybackTimer: () -> Unit,+ onSelectStopPlaybackTimer: (Int) -> Unit,+ showIdleStandbyTimerDialog: Boolean,+ idleStandbyTimerTitle: String,+ idleStandbyTimerMinutes: Int,+ onDismissIdleStandbyTimer: () -> Unit,+ onSelectIdleStandbyTimer: (Int) -> Unit,+ audioVideoOffsetVisible: Boolean,+ audioVideoOffsetState: PlayerAudioVideoOffsetUiState,+ canSaveChannel: Boolean,+ onDismissAudioVideoOffset: () -> Unit,+ onAdjustAudioVideoOffset: (Int) -> Unit,+ onResetAudioVideoOffset: () -> Unit,+ onSaveAudioVideoOffsetForChannel: () -> Unit,+ onSaveAudioVideoOffsetAsGlobal: () -> Unit,+ onUseGlobalAudioVideoOffset: () -> Unit,+ showEpisodePicker: Boolean,+ seriesTitle: String,+ seasons: List<Season>,+ currentEpisodeId: Long,+ currentSeasonNumber: Int?,+ onDismissEpisodePicker: () -> Unit,+ onSelectEpisode: (Episode) -> Unit,+) {+ if (!isInPictureInPictureMode) {+ PlayerTrackSelectionDialog(+ trackType = showTrackSelection,+ audioTracks = availableAudioTracks,+ subtitleTracks = availableSubtitleTracks,+ videoTracks = availableVideoQualities,+ liveTranslationAvailable = liveTranslationAvailable,+ liveTranslationActive = liveTranslationActive,+ onDismiss = onDismissTrackSelection,+ onSelectAudio = onSelectAudio,+ onSelectVideo = onSelectVideo,+ onSelectSubtitle = onSelectSubtitle,+ onSelectLiveTranslation = onSelectLiveTranslation+ )+ ChannelVariantSelectionDialog(+ visible = showVariantSelection,+ channel = currentChannel,+ onDismiss = onDismissVariantSelection,+ onSelectVariant = onSelectVariant+ )+ PlayerSpeedSelectionDialog(+ visible = showSpeedSelection,+ selectedSpeed = playbackSpeed,+ onDismiss = onDismissSpeedSelection,+ onSelectSpeed = onSelectSpeed+ )+ PlayerSleepTimerDialog(+ visible = showStopPlaybackTimerDialog,+ title = stopPlaybackTimerTitle,+ selectedMinutes = stopPlaybackTimerMinutes,+ onDismiss = onDismissStopPlaybackTimer,+ onSelectMinutes = onSelectStopPlaybackTimer+ )+ PlayerSleepTimerDialog(+ visible = showIdleStandbyTimerDialog,+ title = idleStandbyTimerTitle,+ selectedMinutes = idleStandbyTimerMinutes,+ onDismiss = onDismissIdleStandbyTimer,+ onSelectMinutes = onSelectIdleStandbyTimer+ )+ PlayerAudioVideoOffsetDialog(+ visible = audioVideoOffsetVisible,+ state = audioVideoOffsetState,+ canSaveChannel = canSaveChannel,+ onDismiss = onDismissAudioVideoOffset,+ onAdjust = onAdjustAudioVideoOffset,+ onReset = onResetAudioVideoOffset,+ onSaveForChannel = onSaveAudioVideoOffsetForChannel,+ onSaveAsGlobal = onSaveAudioVideoOffsetAsGlobal,+ onUseGlobal = onUseGlobalAudioVideoOffset+ )+ PlayerEpisodeSelectionDialog(+ visible = showEpisodePicker,+ seriesTitle = seriesTitle,+ seasons = seasons,+ currentEpisodeId = currentEpisodeId,+ currentSeasonNumber = currentSeasonNumber,+ onDismiss = onDismissEpisodePicker,+ onSelectEpisode = onSelectEpisode+ )+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.ktindex 2d002f3e..692b2499 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt@@ -70,7 +70,6 @@ import androidx.compose.ui.input.pointer.pointerInputimport androidx.compose.material3.Sliderimport androidx.compose.material3.SliderDefaultsimport androidx.compose.material3.CircularProgressIndicator-import com.streamvault.app.ui.components.dialogs.ProgramHistoryDialogimport androidx.compose.ui.res.stringResourceimport com.streamvault.app.Rimport com.streamvault.app.MainActivity@@ -79,26 +78,18 @@ import com.streamvault.app.ui.components.PlayerRenderViewimport com.streamvault.app.ui.design.requestFocusSafelyimport com.streamvault.app.ui.notifications.rememberNotificationPermissionGateimport com.streamvault.app.ui.screens.player.overlay.ChannelInfoOverlay-import com.streamvault.app.ui.screens.player.overlay.ChannelVariantSelectionDialogimport com.streamvault.app.ui.screens.player.overlay.CategoryListOverlayimport com.streamvault.app.ui.screens.player.overlay.ChannelListOverlayimport com.streamvault.app.ui.screens.player.overlay.DiagnosticsOverlayimport com.streamvault.app.ui.screens.player.overlay.EpgOverlayimport com.streamvault.app.ui.screens.player.overlay.PlayerErrorOverlayimport com.streamvault.app.ui.screens.player.overlay.PlayerNoticeBanner-import com.streamvault.app.ui.screens.player.overlay.PlayerEpisodeSelectionDialogimport com.streamvault.app.ui.screens.player.overlay.PlayerResumePrompt-import com.streamvault.app.ui.screens.player.overlay.PlayerTrackSelectionDialogimport com.streamvault.app.ui.screens.player.overlay.PlayerAspectRatioToastimport com.streamvault.app.ui.screens.player.overlay.PlayerNumericInputOverlayimport com.streamvault.app.ui.screens.player.overlay.PlayerResolutionBadge-import com.streamvault.app.ui.screens.player.overlay.PlayerAudioVideoOffsetDialog-import com.streamvault.app.ui.screens.player.overlay.PlayerSpeedSelectionDialog-import com.streamvault.app.ui.screens.player.overlay.PlayerSleepTimerDialogimport com.streamvault.app.ui.screens.player.overlay.PlayerSleepTimerWarningOverlayimport com.streamvault.app.ui.screens.player.overlay.NextEpisodeCountdownOverlay-import com.streamvault.app.ui.screens.multiview.MultiViewViewModel-import com.streamvault.app.ui.screens.multiview.MultiViewPlannerDialogimport com.streamvault.app.navigation.Routes@@ -343,31 +334,24 @@ fun PlayerScreen(viewModel.recordLiveVariantObservation(playbackState, videoFormat)}- if (!isInPictureInPictureMode && showProgramHistory) {- ProgramHistoryDialog(- programs = programHistory,- onDismiss = { showProgramHistory = false },- onProgramSelect = { program ->- viewModel.playCatchUp(program)- showProgramHistory = false- }- )- }-- // Split Screen Manager dialog- if (showSplitDialog && currentChannel != null) {- val multiViewViewModel: MultiViewViewModel = hiltViewModel()- MultiViewPlannerDialog(- pendingChannel = currentChannel,- onDismiss = { showSplitDialog = false },- onLaunch = {- showSplitDialog = false- viewModel.handOffPlaybackToMultiView()- onNavigate?.invoke(Routes.MULTI_VIEW)- },- viewModel = multiViewViewModel- )- }+ PlayerTopLevelModalHost(+ isInPictureInPictureMode = isInPictureInPictureMode,+ showProgramHistory = showProgramHistory,+ programHistory = programHistory,+ onDismissProgramHistory = { showProgramHistory = false },+ onSelectProgramHistory = { program ->+ viewModel.playCatchUp(program)+ showProgramHistory = false+ },+ showSplitDialog = showSplitDialog,+ currentChannel = currentChannel,+ onDismissSplitDialog = { showSplitDialog = false },+ onLaunchMultiView = {+ showSplitDialog = false+ viewModel.handOffPlaybackToMultiView()+ onNavigate?.invoke(Routes.MULTI_VIEW)+ }+ )val prepareIdentity = buildPlayerPrepareIdentity(streamUrl = streamUrl,@@ -457,30 +441,8 @@ fun PlayerScreen(}}- val handleBackPress = remember(- autoPlayCountdown,- playerNotice,- showProgramHistory,- showSplitDialog,- showEpisodePicker,- showSpeedSelection,- showAudioVideoOffsetDialog,- showStopPlaybackTimerDialog,- showIdleStandbyTimerDialog,- showTrackSelection,- showVariantSelection,- showDiagnostics,- showChannelInfoOverlay,- showChannelListOverlay,- showCategoryListOverlay,- showEpgOverlay,- showControls,- numericChannelInput,- onBack,- viewModel- ) {- {- when (playerBackAction(+ val handleBackPress: () -> Unit = {+ when (playerBackActionAtEvent {PlayerBackNavigationState(hasPendingNumericChannelInput = viewModel.hasPendingNumericChannelInput(),hasAutoPlayCountdown = autoPlayCountdown != null,@@ -501,7 +463,7 @@ fun PlayerScreen(showEpgOverlay = showEpgOverlay,showControls = showControls)- )) {+ }) {PlayerBackAction.CLEAR_NUMERIC_CHANNEL_INPUT -> viewModel.clearNumericChannelInput()PlayerBackAction.CANCEL_AUTO_PLAY -> viewModel.cancelAutoPlay()PlayerBackAction.DISMISS_PLAYER_NOTICE -> viewModel.dismissPlayerNotice()@@ -523,13 +485,39 @@ fun PlayerScreen(PlayerBackAction.TOGGLE_CONTROLS -> viewModel.toggleControls()PlayerBackAction.NAVIGATE_BACK -> onBack()}- }}BackHandler(enabled = !resumePrompt.show) {handleBackPress()}+ val playerInputState = {+ PlayerInputState(+ contentType = contentType,+ isCatchUpPlayback = isCatchUpPlayback,+ isRtl = isRtl,+ nextEpisodeCountdownVisible = nextEpisodeCountdownVisible,+ showChannelListOverlay = showChannelListOverlay,+ showCategoryListOverlay = showCategoryListOverlay,+ showEpgOverlay = showEpgOverlay,+ showChannelInfoOverlay = showChannelInfoOverlay,+ channelInfoSubPanelOpen = channelInfoSubPanelOpen,+ showDiagnostics = showDiagnostics,+ showTrackSelection = showTrackSelection != null,+ showVariantSelection = showVariantSelection,+ showSpeedSelection = showSpeedSelection,+ showAudioVideoOffsetDialog = showAudioVideoOffsetDialog,+ showStopPlaybackTimerDialog = showStopPlaybackTimerDialog,+ showIdleStandbyTimerDialog = showIdleStandbyTimerDialog,+ showProgramHistory = showProgramHistory,+ showSplitDialog = showSplitDialog,+ showEpisodePicker = showEpisodePicker,+ showControls = showControls,+ hasPendingNumericChannelInput = viewModel.hasPendingNumericChannelInput(),+ canOpenEpisodePicker = canOpenEpisodePicker+ )+ }+Box(modifier = Modifier.fillMaxSize()@@ -568,38 +556,19 @@ fun PlayerScreen(return@onPreviewKeyEvent false}viewModel.notifyUserActivity()- if (nextEpisodeCountdownVisible) {- return@onPreviewKeyEvent false- }- if (contentType != "LIVE") {- return@onPreviewKeyEvent false- }- if (showChannelListOverlay || showCategoryListOverlay || showEpgOverlay || showDiagnostics) {- return@onPreviewKeyEvent false- }- if (showTrackSelection != null || showVariantSelection || showSpeedSelection || showAudioVideoOffsetDialog || showStopPlaybackTimerDialog || showIdleStandbyTimerDialog || showProgramHistory || showSplitDialog || showEpisodePicker) {- return@onPreviewKeyEvent false- }- if (showChannelInfoOverlay && channelInfoSubPanelOpen) {- return@onPreviewKeyEvent false+ val decision = playerPreviewInputDecision(+ state = playerInputState(),+ key = playerInputKey(event.nativeKeyEvent)+ )+ if (decision.notifyLiveOverlayInteraction) {+ viewModel.onLiveOverlayInteraction()}-- when (event.nativeKeyEvent.keyCode) {- KeyEvent.KEYCODE_DPAD_UP,- KeyEvent.KEYCODE_CHANNEL_UP,- KeyEvent.KEYCODE_DPAD_UP_RIGHT -> {- if (showChannelInfoOverlay || showDiagnostics) {- viewModel.onLiveOverlayInteraction()- }+ when (decision.action) {+ PlayerInputAction.PlayNext -> {viewModel.playNext()true}- KeyEvent.KEYCODE_DPAD_DOWN,- KeyEvent.KEYCODE_CHANNEL_DOWN,- KeyEvent.KEYCODE_DPAD_DOWN_LEFT -> {- if (showChannelInfoOverlay || showDiagnostics) {- viewModel.onLiveOverlayInteraction()- }+ PlayerInputAction.PlayPrevious -> {viewModel.playPrevious()true}@@ -607,265 +576,111 @@ fun PlayerScreen(}}.onKeyEvent { event ->- // Only handle KeyDown to avoid double actions- if (event.nativeKeyEvent.action == KeyEvent.ACTION_DOWN) {- viewModel.notifyUserActivity()- if (nextEpisodeCountdownVisible) {- return@onKeyEvent when (event.nativeKeyEvent.keyCode) {- KeyEvent.KEYCODE_BACK -> {- viewModel.cancelAutoPlay()- true- }- else -> true- }+ if (event.nativeKeyEvent.action != KeyEvent.ACTION_DOWN) {+ return@onKeyEvent false+ }+ viewModel.notifyUserActivity()+ val decision = playerInputDecisionAtEvent(+ stateProvider = playerInputState,+ key = playerInputKey(event.nativeKeyEvent)+ )+ if (decision.notifyLiveOverlayInteraction) {+ viewModel.onLiveOverlayInteraction()+ }+ when (val action = decision.action) {+ PlayerInputAction.Pass -> false+ PlayerInputAction.Consume -> true+ PlayerInputAction.CancelAutoPlay -> {+ viewModel.cancelAutoPlay()+ true}- if (showTrackSelection != null || showVariantSelection || showSpeedSelection || showAudioVideoOffsetDialog || showStopPlaybackTimerDialog || showIdleStandbyTimerDialog) {- if (showAudioVideoOffsetDialog) {- return@onKeyEvent when (event.nativeKeyEvent.keyCode) {- KeyEvent.KEYCODE_BACK -> {- showAudioVideoOffsetDialog = false- viewModel.dismissAudioVideoOffsetPreview()- true- }- KeyEvent.KEYCODE_DPAD_UP,- KeyEvent.KEYCODE_DPAD_DOWN,- KeyEvent.KEYCODE_DPAD_LEFT,- KeyEvent.KEYCODE_DPAD_RIGHT,- KeyEvent.KEYCODE_DPAD_CENTER,- KeyEvent.KEYCODE_ENTER,- KeyEvent.KEYCODE_NUMPAD_ENTER -> false- else -> true- }- }- if (showSpeedSelection) {- return@onKeyEvent when (event.nativeKeyEvent.keyCode) {- KeyEvent.KEYCODE_BACK -> {- showSpeedSelection = false- true- }- KeyEvent.KEYCODE_DPAD_UP,- KeyEvent.KEYCODE_DPAD_DOWN,- KeyEvent.KEYCODE_DPAD_LEFT,- KeyEvent.KEYCODE_DPAD_RIGHT,- KeyEvent.KEYCODE_DPAD_CENTER,- KeyEvent.KEYCODE_ENTER,- KeyEvent.KEYCODE_NUMPAD_ENTER -> false- else -> true- }- }- if (showVariantSelection) {- return@onKeyEvent when (event.nativeKeyEvent.keyCode) {- KeyEvent.KEYCODE_BACK -> {- showVariantSelection = false- true- }- KeyEvent.KEYCODE_DPAD_UP,- KeyEvent.KEYCODE_DPAD_DOWN,- KeyEvent.KEYCODE_DPAD_LEFT,- KeyEvent.KEYCODE_DPAD_RIGHT,- KeyEvent.KEYCODE_DPAD_CENTER,- KeyEvent.KEYCODE_ENTER,- KeyEvent.KEYCODE_NUMPAD_ENTER -> false- else -> true- }- }- return@onKeyEvent when (event.nativeKeyEvent.keyCode) {- KeyEvent.KEYCODE_BACK -> {- showStopPlaybackTimerDialog = false- showIdleStandbyTimerDialog = false- showTrackSelection = null- true- }- KeyEvent.KEYCODE_DPAD_UP,- KeyEvent.KEYCODE_DPAD_DOWN,- KeyEvent.KEYCODE_DPAD_LEFT,- KeyEvent.KEYCODE_DPAD_RIGHT,- KeyEvent.KEYCODE_DPAD_CENTER,- KeyEvent.KEYCODE_ENTER,- KeyEvent.KEYCODE_NUMPAD_ENTER -> false- else -> true- }+ PlayerInputAction.DismissAudioVideoOffset -> {+ showAudioVideoOffsetDialog = false+ viewModel.dismissAudioVideoOffsetPreview()+ true}- when (event.nativeKeyEvent.keyCode) {- KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER -> {- if (showChannelListOverlay || showEpgOverlay || showChannelInfoOverlay || showDiagnostics) {- viewModel.onLiveOverlayInteraction()- }- if (contentType == "LIVE" && !isCatchUpPlayback && viewModel.hasPendingNumericChannelInput()) {- viewModel.commitNumericChannelInput()- true- } else if (contentType == "LIVE" && !isCatchUpPlayback) {- if (showChannelInfoOverlay) viewModel.closeChannelInfoOverlay()- else viewModel.openChannelInfoOverlay()- true- } else if (showControls) {- false- } else {- viewModel.toggleControls()- true- }- }- KeyEvent.KEYCODE_DPAD_LEFT -> {- if (showChannelListOverlay || showCategoryListOverlay || showEpgOverlay || showChannelInfoOverlay || showDiagnostics) {- viewModel.onLiveOverlayInteraction()- }- if (showControls && (contentType != "LIVE" || isCatchUpPlayback)) return@onKeyEvent false- if (showChannelListOverlay && contentType == "LIVE" && !isCatchUpPlayback) {- // Second left press while channel list is open → open category list- viewModel.openCategoryListOverlay()- true- } else if (contentType == "LIVE" && !isCatchUpPlayback && !showChannelListOverlay && !showCategoryListOverlay && !showEpgOverlay && !showChannelInfoOverlay) {- if (isRtl) viewModel.openEpgOverlay() else viewModel.openChannelListOverlay()- true- } else if (!showChannelListOverlay && !showCategoryListOverlay && !showEpgOverlay && !showChannelInfoOverlay) {- if (isRtl) viewModel.seekForward() else viewModel.seekBackward()- true- } else {- false- }- }- KeyEvent.KEYCODE_DPAD_RIGHT -> {- if (showChannelListOverlay || showEpgOverlay || showChannelInfoOverlay || showDiagnostics) {- viewModel.onLiveOverlayInteraction()- }- if (showControls && (contentType != "LIVE" || isCatchUpPlayback)) return@onKeyEvent false- if (contentType == "LIVE" && !isCatchUpPlayback && !showChannelListOverlay && !showEpgOverlay && !showChannelInfoOverlay) {- if (isRtl) viewModel.openChannelListOverlay() else viewModel.openEpgOverlay()- true- } else if (!showChannelListOverlay && !showEpgOverlay && !showChannelInfoOverlay) {- if (isRtl) viewModel.seekBackward() else viewModel.seekForward()- true- } else {- false- }- }- KeyEvent.KEYCODE_DPAD_UP -> {- if (showChannelListOverlay || showCategoryListOverlay || showEpgOverlay || showChannelInfoOverlay || showDiagnostics) {- viewModel.onLiveOverlayInteraction()- }- if (showChannelInfoOverlay && channelInfoSubPanelOpen) return@onKeyEvent false- if (showChannelListOverlay || showCategoryListOverlay || showEpgOverlay || showChannelInfoOverlay || showDiagnostics) return@onKeyEvent false- if (showControls && (contentType != "LIVE" || isCatchUpPlayback)) return@onKeyEvent false-- if (contentType == "LIVE" && !isCatchUpPlayback) {- viewModel.playNext()- } else if (canOpenEpisodePicker) {- showEpisodePicker = true- } else {- viewModel.toggleControls()- }- true- }- KeyEvent.KEYCODE_DPAD_DOWN -> {- if (showChannelListOverlay || showCategoryListOverlay || showEpgOverlay || showChannelInfoOverlay || showDiagnostics) {- viewModel.onLiveOverlayInteraction()- }- if (showChannelInfoOverlay && channelInfoSubPanelOpen) return@onKeyEvent false- if (showChannelListOverlay || showCategoryListOverlay || showEpgOverlay || showDiagnostics) return@onKeyEvent false- if (showControls && (contentType != "LIVE" || isCatchUpPlayback)) return@onKeyEvent false-- if (contentType == "LIVE" && !isCatchUpPlayback) {- viewModel.playPrevious()- } else {- viewModel.toggleControls()- }- true- }- KeyEvent.KEYCODE_BACK -> {- handleBackPress()- true- }- KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> {- if (isPlaying) viewModel.pause() else viewModel.play()- true- }- KeyEvent.KEYCODE_MUTE, KeyEvent.KEYCODE_VOLUME_MUTE -> {- if (event.nativeKeyEvent.repeatCount == 0) {- viewModel.toggleMute()- }- true- }- KeyEvent.KEYCODE_CHANNEL_UP, KeyEvent.KEYCODE_DPAD_UP_RIGHT -> {- if (showDiagnostics) {- true- } else if (showChannelInfoOverlay && channelInfoSubPanelOpen) {- true- } else if (contentType == "LIVE") {- viewModel.playNext()- true- } else {- false- }- }- KeyEvent.KEYCODE_CHANNEL_DOWN, KeyEvent.KEYCODE_DPAD_DOWN_LEFT -> {- if (showDiagnostics) {- true- } else if (showChannelInfoOverlay && channelInfoSubPanelOpen) {- true- } else if (contentType == "LIVE") {- viewModel.playPrevious()- true- } else {- false- }- }- KeyEvent.KEYCODE_MEDIA_PREVIOUS -> {- if (showChannelInfoOverlay && channelInfoSubPanelOpen) {- true- } else- if (contentType == "LIVE") {- viewModel.zapToLastChannel()- true- } else {- false- }- }- KeyEvent.KEYCODE_GUIDE -> {- if (contentType == "LIVE") {- viewModel.openEpgOverlay()- true- } else {- false- }- }- KeyEvent.KEYCODE_INFO -> {- if (showChannelListOverlay || showEpgOverlay || showChannelInfoOverlay || showDiagnostics) {- viewModel.onLiveOverlayInteraction()- }- if (contentType == "LIVE") {- if (showChannelInfoOverlay) viewModel.closeChannelInfoOverlay()- else viewModel.openChannelInfoOverlay()- } else {- viewModel.toggleControls()- }- true- }- KeyEvent.KEYCODE_MENU -> {- if (showChannelListOverlay || showEpgOverlay || showChannelInfoOverlay || showDiagnostics) {- viewModel.onLiveOverlayInteraction()- }- viewModel.toggleControls()- true- }- in KeyEvent.KEYCODE_0..KeyEvent.KEYCODE_9,- in KeyEvent.KEYCODE_NUMPAD_0..KeyEvent.KEYCODE_NUMPAD_9 -> {- if (contentType == "LIVE") {- val keyCode = event.nativeKeyEvent.keyCode- val digit = when (keyCode) {- in KeyEvent.KEYCODE_0..KeyEvent.KEYCODE_9 -> keyCode - KeyEvent.KEYCODE_0- in KeyEvent.KEYCODE_NUMPAD_0..KeyEvent.KEYCODE_NUMPAD_9 -> keyCode - KeyEvent.KEYCODE_NUMPAD_0- else -> return@onKeyEvent false- }- viewModel.inputNumericChannelDigit(digit)- true- } else {- false- }- }- else -> false+ PlayerInputAction.CloseSpeedSelection -> {+ showSpeedSelection = false+ true+ }+ PlayerInputAction.CloseVariantSelection -> {+ showVariantSelection = false+ true+ }+ PlayerInputAction.CloseStopIdleTimersAndTrackSelection -> {+ showStopPlaybackTimerDialog = false+ showIdleStandbyTimerDialog = false+ showTrackSelection = null+ true+ }+ PlayerInputAction.CommitNumericChannelInput -> {+ viewModel.commitNumericChannelInput()+ true+ }+ PlayerInputAction.OpenChannelInfo -> {+ viewModel.openChannelInfoOverlay()+ true+ }+ PlayerInputAction.CloseChannelInfo -> {+ viewModel.closeChannelInfoOverlay()+ true+ }+ PlayerInputAction.OpenChannelList -> {+ viewModel.openChannelListOverlay()+ true+ }+ PlayerInputAction.OpenCategoryList -> {+ viewModel.openCategoryListOverlay()+ true+ }+ PlayerInputAction.OpenEpg -> {+ viewModel.openEpgOverlay()+ true+ }+ PlayerInputAction.SeekBackward -> {+ viewModel.seekBackward()+ true+ }+ PlayerInputAction.SeekForward -> {+ viewModel.seekForward()+ true+ }+ PlayerInputAction.ToggleControls -> {+ viewModel.toggleControls()+ true+ }+ PlayerInputAction.TogglePlayback -> {+ if (isPlaying) viewModel.pause() else viewModel.play()+ true+ }+ PlayerInputAction.ToggleMute -> {+ viewModel.toggleMute()+ true+ }+ PlayerInputAction.PlayNext -> {+ viewModel.playNext()+ true+ }+ PlayerInputAction.PlayPrevious -> {+ viewModel.playPrevious()+ true+ }+ PlayerInputAction.ZapToLastChannel -> {+ viewModel.zapToLastChannel()+ true+ }+ PlayerInputAction.ShowEpisodePicker -> {+ showEpisodePicker = true+ true+ }+ is PlayerInputAction.InputNumericDigit -> {+ viewModel.inputNumericChannelDigit(action.digit)+ true+ }+ PlayerInputAction.DelegateBack -> {+ handleBackPress()+ true}- } else {- false}}) {@@ -1134,90 +949,76 @@ fun PlayerScreen()}- // Track Selection Dialog- if (!isInPictureInPictureMode) {- PlayerTrackSelectionDialog(- trackType = showTrackSelection,- audioTracks = availableAudioTracks,- subtitleTracks = availableSubtitleTracks,- videoTracks = availableVideoQualities,- liveTranslationAvailable = liveTranslationAvailable,- liveTranslationActive = liveTranslationActive,- onDismiss = { showTrackSelection = null },- onSelectAudio = viewModel::selectAudioTrack,- onSelectVideo = viewModel::selectVideoQuality,- onSelectSubtitle = { trackId ->- viewModel.deactivateLiveTranslation()- viewModel.selectSubtitleTrack(trackId)- },- onSelectLiveTranslation = {- viewModel.selectSubtitleTrack(null)- viewModel.activateLiveTranslation()- }- )- ChannelVariantSelectionDialog(- visible = showVariantSelection,- channel = currentChannel,- onDismiss = { showVariantSelection = false },- onSelectVariant = viewModel::selectLiveVariant- )- PlayerSpeedSelectionDialog(- visible = showSpeedSelection,- selectedSpeed = playbackSpeed,- onDismiss = { showSpeedSelection = false },- onSelectSpeed = viewModel::setPlaybackSpeed- )- PlayerSleepTimerDialog(- visible = showStopPlaybackTimerDialog,- title = stringResource(R.string.player_stop_playback_after),- selectedMinutes = sleepTimerUiState.stopTimerMinutes,- onDismiss = { showStopPlaybackTimerDialog = false },- onSelectMinutes = { minutes ->- viewModel.notifyUserActivity()- viewModel.setStopPlaybackTimer(minutes)- showStopPlaybackTimerDialog = false- }- )- PlayerSleepTimerDialog(- visible = showIdleStandbyTimerDialog,- title = stringResource(R.string.player_idle_standby_after),- selectedMinutes = sleepTimerUiState.idleTimerMinutes,- onDismiss = { showIdleStandbyTimerDialog = false },- onSelectMinutes = { minutes ->- viewModel.notifyUserActivity()- viewModel.setIdleStandbyTimer(minutes)- showIdleStandbyTimerDialog = false- }- )- PlayerAudioVideoOffsetDialog(- visible = showAudioVideoOffsetDialog &&- audioVideoSyncEnabled &&- castConnectionState != CastConnectionState.CONNECTED,- state = audioVideoOffsetState,- canSaveChannel = currentChannel != null,- onDismiss = {- showAudioVideoOffsetDialog = false- viewModel.dismissAudioVideoOffsetPreview()- },- onAdjust = viewModel::adjustAudioVideoOffset,- onReset = viewModel::resetAudioVideoOffsetPreview,- onSaveForChannel = viewModel::saveAudioVideoOffsetForChannel,- onSaveAsGlobal = viewModel::saveAudioVideoOffsetAsGlobal,- onUseGlobal = viewModel::useGlobalAudioVideoOffset- )- PlayerEpisodeSelectionDialog(- visible = showEpisodePicker,- seriesTitle = currentSeries?.name ?: playbackTitle.ifBlank { title },- seasons = currentSeriesSeasons.orEmpty(),- currentEpisodeId = currentEpisode?.id ?: internalChannelId,- currentSeasonNumber = currentEpisode?.seasonNumber ?: seasonNumber,- onDismiss = { showEpisodePicker = false },- onSelectEpisode = { episode ->- showEpisodePicker = false- viewModel.playEpisode(episode)- }- )- }+ PlayerControlsModalHost(+ isInPictureInPictureMode = isInPictureInPictureMode,+ showTrackSelection = showTrackSelection,+ availableAudioTracks = availableAudioTracks,+ availableSubtitleTracks = availableSubtitleTracks,+ availableVideoQualities = availableVideoQualities,+ liveTranslationAvailable = liveTranslationAvailable,+ liveTranslationActive = liveTranslationActive,+ onDismissTrackSelection = { showTrackSelection = null },+ onSelectAudio = viewModel::selectAudioTrack,+ onSelectVideo = viewModel::selectVideoQuality,+ onSelectSubtitle = { trackId ->+ viewModel.deactivateLiveTranslation()+ viewModel.selectSubtitleTrack(trackId)+ },+ onSelectLiveTranslation = {+ viewModel.selectSubtitleTrack(null)+ viewModel.activateLiveTranslation()+ },+ showVariantSelection = showVariantSelection,+ currentChannel = currentChannel,+ onDismissVariantSelection = { showVariantSelection = false },+ onSelectVariant = viewModel::selectLiveVariant,+ showSpeedSelection = showSpeedSelection,+ playbackSpeed = playbackSpeed,+ onDismissSpeedSelection = { showSpeedSelection = false },+ onSelectSpeed = viewModel::setPlaybackSpeed,+ showStopPlaybackTimerDialog = showStopPlaybackTimerDialog,+ stopPlaybackTimerTitle = stringResource(R.string.player_stop_playback_after),+ stopPlaybackTimerMinutes = sleepTimerUiState.stopTimerMinutes,+ onDismissStopPlaybackTimer = { showStopPlaybackTimerDialog = false },+ onSelectStopPlaybackTimer = { minutes ->+ viewModel.notifyUserActivity()+ viewModel.setStopPlaybackTimer(minutes)+ showStopPlaybackTimerDialog = false+ },+ showIdleStandbyTimerDialog = showIdleStandbyTimerDialog,+ idleStandbyTimerTitle = stringResource(R.string.player_idle_standby_after),+ idleStandbyTimerMinutes = sleepTimerUiState.idleTimerMinutes,+ onDismissIdleStandbyTimer = { showIdleStandbyTimerDialog = false },+ onSelectIdleStandbyTimer = { minutes ->+ viewModel.notifyUserActivity()+ viewModel.setIdleStandbyTimer(minutes)+ showIdleStandbyTimerDialog = false+ },+ audioVideoOffsetVisible = showAudioVideoOffsetDialog &&+ audioVideoSyncEnabled &&+ castConnectionState != CastConnectionState.CONNECTED,+ audioVideoOffsetState = audioVideoOffsetState,+ canSaveChannel = currentChannel != null,+ onDismissAudioVideoOffset = {+ showAudioVideoOffsetDialog = false+ viewModel.dismissAudioVideoOffsetPreview()+ },+ onAdjustAudioVideoOffset = viewModel::adjustAudioVideoOffset,+ onResetAudioVideoOffset = viewModel::resetAudioVideoOffsetPreview,+ onSaveAudioVideoOffsetForChannel = viewModel::saveAudioVideoOffsetForChannel,+ onSaveAudioVideoOffsetAsGlobal = viewModel::saveAudioVideoOffsetAsGlobal,+ onUseGlobalAudioVideoOffset = viewModel::useGlobalAudioVideoOffset,+ showEpisodePicker = showEpisodePicker,+ seriesTitle = currentSeries?.name ?: playbackTitle.ifBlank { title },+ seasons = currentSeriesSeasons.orEmpty(),+ currentEpisodeId = currentEpisode?.id ?: internalChannelId,+ currentSeasonNumber = currentEpisode?.seasonNumber ?: seasonNumber,+ onDismissEpisodePicker = { showEpisodePicker = false },+ onSelectEpisode = { episode ->+ showEpisodePicker = false+ viewModel.playEpisode(episode)+ }+ )// --- Overlays ---if (!isInPictureInPictureMode && showDiagnostics) {@@ -1390,6 +1191,32 @@ fun PlayerScreen(}}+private fun playerInputKey(event: KeyEvent): PlayerInputKey = when (event.keyCode) {+ KeyEvent.KEYCODE_DPAD_CENTER -> PlayerInputKey.DpadCenter+ KeyEvent.KEYCODE_ENTER -> PlayerInputKey.Enter+ KeyEvent.KEYCODE_NUMPAD_ENTER -> PlayerInputKey.NumpadEnter+ KeyEvent.KEYCODE_DPAD_LEFT -> PlayerInputKey.DpadLeft+ KeyEvent.KEYCODE_DPAD_RIGHT -> PlayerInputKey.DpadRight+ KeyEvent.KEYCODE_DPAD_UP -> PlayerInputKey.DpadUp+ KeyEvent.KEYCODE_DPAD_DOWN -> PlayerInputKey.DpadDown+ KeyEvent.KEYCODE_DPAD_UP_RIGHT -> PlayerInputKey.DpadUpRight+ KeyEvent.KEYCODE_DPAD_DOWN_LEFT -> PlayerInputKey.DpadDownLeft+ KeyEvent.KEYCODE_BACK -> PlayerInputKey.Back+ KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> PlayerInputKey.MediaPlayPause+ KeyEvent.KEYCODE_MUTE,+ KeyEvent.KEYCODE_VOLUME_MUTE -> PlayerInputKey.Mute(event.repeatCount > 0)+ KeyEvent.KEYCODE_CHANNEL_UP -> PlayerInputKey.ChannelUp+ KeyEvent.KEYCODE_CHANNEL_DOWN -> PlayerInputKey.ChannelDown+ KeyEvent.KEYCODE_MEDIA_PREVIOUS -> PlayerInputKey.MediaPrevious+ KeyEvent.KEYCODE_GUIDE -> PlayerInputKey.Guide+ KeyEvent.KEYCODE_INFO -> PlayerInputKey.Info+ KeyEvent.KEYCODE_MENU -> PlayerInputKey.Menu+ in KeyEvent.KEYCODE_0..KeyEvent.KEYCODE_9 -> PlayerInputKey.Digit(event.keyCode - KeyEvent.KEYCODE_0)+ in KeyEvent.KEYCODE_NUMPAD_0..KeyEvent.KEYCODE_NUMPAD_9 ->+ PlayerInputKey.Digit(event.keyCode - KeyEvent.KEYCODE_NUMPAD_0)+ else -> PlayerInputKey.Other+}+private fun AspectRatio.toPlayerSurfaceResizeMode(): PlayerSurfaceResizeMode = when (this) {AspectRatio.FIT -> PlayerSurfaceResizeMode.FITAspectRatio.FILL -> PlayerSurfaceResizeMode.FILLdiff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupActionButtons.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupActionButtons.ktnew file mode 100644index 00000000..7129dad9--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupActionButtons.kt@@ -0,0 +1,93 @@+package com.streamvault.app.ui.screens.provider++import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.unit.dp+import androidx.tv.material3.Border+import androidx.tv.material3.ClickableSurfaceDefaults+import androidx.tv.material3.Glow+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.streamvault.app.ui.interaction.TvClickableSurface+import com.streamvault.app.ui.theme.FocusBorder+import com.streamvault.app.ui.theme.OnBackground+import com.streamvault.app.ui.theme.Primary+import com.streamvault.app.ui.theme.PrimaryLight+import com.streamvault.app.ui.theme.SurfaceHighlight++@Composable+internal fun ActionButton(+ text: String,+ isLoading: Boolean = false,+ onClick: () -> Unit+) {+ ProviderActionButton(+ text = text,+ height = 52.dp,+ isLoading = isLoading,+ onClick = onClick+ )+}++@Composable+internal fun SmallActionButton(+ text: String,+ isLoading: Boolean = false,+ onClick: () -> Unit+) {+ ProviderActionButton(+ text = text,+ height = 40.dp,+ isLoading = isLoading,+ onClick = onClick+ )+}++@Composable+private fun ProviderActionButton(+ text: String,+ height: androidx.compose.ui.unit.Dp,+ isLoading: Boolean = false,+ onClick: () -> Unit+) {+ TvClickableSurface(+ onClick = onClick,+ enabled = !isLoading,+ modifier = androidx.compose.ui.Modifier+ .fillMaxWidth()+ .height(height),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (!isLoading) Primary else SurfaceHighlight,+ focusedContainerColor = if (!isLoading) Primary else SurfaceHighlight+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),+ glow = ClickableSurfaceDefaults.glow(focusedGlow = Glow.None),+ border = ClickableSurfaceDefaults.border(+ border = Border(BorderStroke(1.dp, if (!isLoading) PrimaryLight else SurfaceHighlight)),+ focusedBorder = Border(BorderStroke(2.dp, FocusBorder))+ )+ ) {+ Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {+ if (isLoading) {+ CircularProgressIndicator(+ modifier = Modifier.size(20.dp),+ strokeWidth = 2.dp,+ color = OnBackground.copy(alpha = 0.6f)+ )+ } else {+ Text(text = text, style = MaterialTheme.typography.bodySmall, color = Color.White)+ }+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupAdvancedOptions.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupAdvancedOptions.ktnew file mode 100644index 00000000..10986e21--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupAdvancedOptions.kt@@ -0,0 +1,701 @@+package com.streamvault.app.ui.screens.provider++import androidx.compose.animation.AnimatedVisibility+import androidx.compose.foundation.*+import androidx.compose.foundation.layout.*+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.material3.HorizontalDivider+import androidx.compose.material3.Switch+import androidx.compose.runtime.*+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.unit.dp+import androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.text.input.KeyboardCapitalization+import androidx.compose.ui.text.input.KeyboardType+import androidx.tv.material3.Border+import androidx.tv.material3.ClickableSurfaceDefaults+import androidx.tv.material3.Glow+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Surface as TvSurface+import androidx.tv.material3.Text+import com.streamvault.app.R+import com.streamvault.app.ui.interaction.TvClickableSurface+import com.streamvault.app.ui.interaction.mouseClickable+import com.streamvault.app.ui.theme.*+import com.streamvault.data.remote.stalker.StalkerAdvancedOptions+import com.streamvault.domain.model.ChannelLogoSourcePolicy+import com.streamvault.domain.model.GuideSourcePolicy+import com.streamvault.domain.model.ProviderEpgSyncMode+import com.streamvault.domain.model.ProviderXtreamLiveSyncMode+import com.streamvault.domain.model.StalkerAuthMode+import com.streamvault.domain.model.StalkerCatalogMode++@Composable+internal fun AdvancedProviderOptionsSection(options: ProviderAdvancedOptions) {+ AdvancedProviderOptionsSection(+ sourceType = options.sourceType,+ uiState = options.uiState,+ httpUserAgent = options.httpUserAgent,+ onHttpUserAgentChange = options.onHttpUserAgentChange,+ httpHeaders = options.httpHeaders,+ onHttpHeadersChange = options.onHttpHeadersChange,+ onToggleM3uVodClassification = options.onToggleM3uVodClassification,+ onSelectEpgSyncMode = options.onSelectEpgSyncMode,+ onSelectStalkerCatalogMode = options.onSelectStalkerCatalogMode,+ onSelectXtreamLiveSyncMode = options.onSelectXtreamLiveSyncMode,+ onSelectGuideSourcePolicy = options.onSelectGuideSourcePolicy,+ onSelectChannelLogoSourcePolicy = options.onSelectChannelLogoSourcePolicy,+ username = options.username,+ onUsernameChange = options.onUsernameChange,+ password = options.password,+ onPasswordChange = options.onPasswordChange,+ stalkerAuthMode = options.stalkerAuthMode,+ onStalkerAuthModeChange = options.onStalkerAuthModeChange,+ stalkerMacAddress = options.stalkerMacAddress,+ stalkerDeviceProfile = options.stalkerDeviceProfile,+ onStalkerDeviceProfileChange = options.onStalkerDeviceProfileChange,+ stalkerDeviceTimezone = options.stalkerDeviceTimezone,+ onStalkerDeviceTimezoneChange = options.onStalkerDeviceTimezoneChange,+ stalkerDeviceLocale = options.stalkerDeviceLocale,+ onStalkerDeviceLocaleChange = options.onStalkerDeviceLocaleChange,+ stalkerSerialNumber = options.stalkerSerialNumber,+ onStalkerSerialNumberChange = options.onStalkerSerialNumberChange,+ stalkerDeviceId = options.stalkerDeviceId,+ onStalkerDeviceIdChange = options.onStalkerDeviceIdChange,+ stalkerDeviceId2 = options.stalkerDeviceId2,+ onStalkerDeviceId2Change = options.onStalkerDeviceId2Change,+ stalkerSignature = options.stalkerSignature,+ onStalkerSignatureChange = options.onStalkerSignatureChange,+ stalkerHwVersion = options.stalkerHwVersion,+ onStalkerHwVersionChange = options.onStalkerHwVersionChange,+ stalkerApiUserAgent = options.stalkerApiUserAgent,+ onStalkerApiUserAgentChange = options.onStalkerApiUserAgentChange,+ stalkerPlayerUserAgent = options.stalkerPlayerUserAgent,+ onStalkerPlayerUserAgentChange = options.onStalkerPlayerUserAgentChange,+ stalkerPlayerHeaders = options.stalkerPlayerHeaders,+ onStalkerPlayerHeadersChange = options.onStalkerPlayerHeadersChange,+ stalkerXUserAgentLink = options.stalkerXUserAgentLink,+ onStalkerXUserAgentLinkChange = options.onStalkerXUserAgentLinkChange,+ stalkerProxyEnabled = options.stalkerProxyEnabled,+ onStalkerProxyEnabledChange = options.onStalkerProxyEnabledChange,+ stalkerProxyHost = options.stalkerProxyHost,+ onStalkerProxyHostChange = options.onStalkerProxyHostChange,+ stalkerProxyPort = options.stalkerProxyPort,+ onStalkerProxyPortChange = options.onStalkerProxyPortChange,+ stalkerRequestRules = options.stalkerRequestRules,+ onAddStalkerRequestRule = options.onAddStalkerRequestRule,+ onUpdateStalkerRequestRule = options.onUpdateStalkerRequestRule,+ onRemoveStalkerRequestRule = options.onRemoveStalkerRequestRule+ )+}++@Composable+internal fun AdvancedProviderOptionsSection(+ sourceType: SourceType,+ uiState: ProviderSetupState,+ httpUserAgent: String,+ onHttpUserAgentChange: (String) -> Unit,+ httpHeaders: String,+ onHttpHeadersChange: (String) -> Unit,+ onToggleM3uVodClassification: () -> Unit,+ onSelectEpgSyncMode: (ProviderEpgSyncMode) -> Unit,+ onSelectStalkerCatalogMode: (StalkerCatalogMode) -> Unit,+ onSelectXtreamLiveSyncMode: (ProviderXtreamLiveSyncMode) -> Unit,+ onSelectGuideSourcePolicy: (GuideSourcePolicy) -> Unit,+ onSelectChannelLogoSourcePolicy: (ChannelLogoSourcePolicy) -> Unit,+ username: String,+ onUsernameChange: (String) -> Unit,+ password: String,+ onPasswordChange: (String) -> Unit,+ stalkerAuthMode: StalkerAuthMode,+ onStalkerAuthModeChange: (StalkerAuthMode) -> Unit,+ stalkerMacAddress: String,+ stalkerDeviceProfile: String,+ onStalkerDeviceProfileChange: (String) -> Unit,+ stalkerDeviceTimezone: String,+ onStalkerDeviceTimezoneChange: (String) -> Unit,+ stalkerDeviceLocale: String,+ onStalkerDeviceLocaleChange: (String) -> Unit,+ stalkerSerialNumber: String,+ onStalkerSerialNumberChange: (String) -> Unit,+ stalkerDeviceId: String,+ onStalkerDeviceIdChange: (String) -> Unit,+ stalkerDeviceId2: String,+ onStalkerDeviceId2Change: (String) -> Unit,+ stalkerSignature: String,+ onStalkerSignatureChange: (String) -> Unit,+ stalkerHwVersion: String = "",+ onStalkerHwVersionChange: (String) -> Unit = {},+ stalkerApiUserAgent: String = "",+ onStalkerApiUserAgentChange: (String) -> Unit = {},+ stalkerPlayerUserAgent: String = "",+ onStalkerPlayerUserAgentChange: (String) -> Unit = {},+ stalkerPlayerHeaders: String = "",+ onStalkerPlayerHeadersChange: (String) -> Unit = {},+ stalkerXUserAgentLink: String = StalkerAdvancedOptions.LINK_ETHERNET,+ onStalkerXUserAgentLinkChange: (String) -> Unit = {},+ stalkerProxyEnabled: Boolean = false,+ onStalkerProxyEnabledChange: (Boolean) -> Unit = {},+ stalkerProxyHost: String = "",+ onStalkerProxyHostChange: (String) -> Unit = {},+ stalkerProxyPort: String = "",+ onStalkerProxyPortChange: (String) -> Unit = {},+ stalkerRequestRules: List<StalkerRequestRuleUiState> = emptyList(),+ onAddStalkerRequestRule: () -> Unit = {},+ onUpdateStalkerRequestRule: (Int, StalkerRequestRuleUiState) -> Unit = { _, _ -> },+ onRemoveStalkerRequestRule: (Int) -> Unit = {}+) {+ var showAdvancedOptions by rememberSaveable(sourceType) { mutableStateOf(false) }+ val defaultEpgSyncMode = when (sourceType) {+ SourceType.STALKER -> ProviderEpgSyncMode.BACKGROUND+ SourceType.XTREAM,+ SourceType.M3U_URL,+ SourceType.M3U_FILE,+ SourceType.JELLYFIN -> ProviderEpgSyncMode.UPFRONT+ }++ LaunchedEffect(uiState.isEditing, uiState.epgSyncMode, uiState.stalkerCatalogMode, uiState.xtreamLiveSyncMode, uiState.guideSourcePolicy, uiState.channelLogoSourcePolicy, sourceType) {+ val hasNonDefaultSelection = ((sourceType == SourceType.XTREAM || sourceType == SourceType.STALKER) && uiState.epgSyncMode != defaultEpgSyncMode) ||+ (sourceType == SourceType.STALKER && uiState.stalkerCatalogMode != StalkerCatalogMode.ON_DEMAND) ||+ (sourceType == SourceType.XTREAM && uiState.xtreamLiveSyncMode != ProviderXtreamLiveSyncMode.AUTO) ||+ (supportsGuideAndLogoPolicy(sourceType) && uiState.guideSourcePolicy != GuideSourcePolicy.AUTO) ||+ (supportsGuideAndLogoPolicy(sourceType) && uiState.channelLogoSourcePolicy != ChannelLogoSourcePolicy.SUPPLIER_PREFERRED) ||+ ((sourceType == SourceType.M3U_URL || sourceType == SourceType.M3U_FILE) && !uiState.m3uVodClassificationEnabled) ||+ ((sourceType == SourceType.XTREAM || sourceType == SourceType.M3U_URL || sourceType == SourceType.M3U_FILE) &&+ httpUserAgent.isNotBlank()) ||+ ((sourceType == SourceType.XTREAM || sourceType == SourceType.STALKER || sourceType == SourceType.M3U_URL || sourceType == SourceType.M3U_FILE) &&+ httpHeaders.isNotBlank()) ||+ (sourceType == SourceType.STALKER && (+ stalkerAuthMode != StalkerAuthMode.AUTO ||+ username.isNotBlank() ||+ password.isNotBlank() ||+ stalkerMacAddress.isBlank() ||+ stalkerDeviceProfile.isNotBlank() ||+ stalkerDeviceTimezone.isNotBlank() ||+ stalkerDeviceLocale.isNotBlank() ||+ stalkerSerialNumber.isNotBlank() ||+ stalkerDeviceId.isNotBlank() ||+ stalkerDeviceId2.isNotBlank() ||+ stalkerSignature.isNotBlank() ||+ stalkerHwVersion.isNotBlank() ||+ stalkerApiUserAgent.isNotBlank() ||+ stalkerPlayerUserAgent.isNotBlank() ||+ stalkerPlayerHeaders.isNotBlank() ||+ stalkerXUserAgentLink != StalkerAdvancedOptions.LINK_ETHERNET ||+ stalkerProxyEnabled ||+ stalkerProxyHost.isNotBlank() ||+ stalkerProxyPort.isNotBlank() ||+ stalkerRequestRules.isNotEmpty()+ ))+ if (uiState.isEditing && hasNonDefaultSelection) {+ showAdvancedOptions = true+ }+ }++ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {+ TvSurface(+ onClick = { showAdvancedOptions = !showAdvancedOptions },+ modifier = Modifier+ .fillMaxWidth()+ .mouseClickable(onClick = { showAdvancedOptions = !showAdvancedOptions }),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (showAdvancedOptions) Primary.copy(alpha = 0.12f) else Surface,+ focusedContainerColor = Primary.copy(alpha = 0.24f)+ ),+ border = ClickableSurfaceDefaults.border(+ border = Border(+ BorderStroke(+ 1.dp,+ if (showAdvancedOptions) Primary.copy(alpha = 0.45f) else SurfaceHighlight+ )+ ),+ focusedBorder = Border(BorderStroke(3.dp, PrimaryLight))+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Row(+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(+ modifier = Modifier.weight(1f),+ verticalArrangement = Arrangement.spacedBy(4.dp)+ ) {+ Text(+ text = androidx.compose.ui.res.stringResource(R.string.setup_advanced_options_label),+ style = MaterialTheme.typography.titleSmall,+ color = TextPrimary+ )+ Text(+ text = androidx.compose.ui.res.stringResource(R.string.setup_advanced_options_helper),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ Text(+ text = if (showAdvancedOptions) {+ androidx.compose.ui.res.stringResource(R.string.setup_advanced_options_hide)+ } else {+ androidx.compose.ui.res.stringResource(R.string.setup_advanced_options_show)+ },+ style = MaterialTheme.typography.labelMedium,+ color = PrimaryLight+ )+ }+ }++ AnimatedVisibility(visible = showAdvancedOptions) {+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {+ if (sourceType == SourceType.M3U_URL || sourceType == SourceType.M3U_FILE) {+ TvSurface(+ onClick = onToggleM3uVodClassification,+ modifier = Modifier+ .fillMaxWidth()+ .mouseClickable(onClick = onToggleM3uVodClassification),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (uiState.m3uVodClassificationEnabled) Primary.copy(alpha = 0.1f) else Surface,+ focusedContainerColor = Primary.copy(alpha = 0.22f)+ ),+ border = ClickableSurfaceDefaults.border(+ border = Border(+ BorderStroke(+ 1.dp,+ if (uiState.m3uVodClassificationEnabled) Primary.copy(alpha = 0.4f) else SurfaceHighlight+ )+ ),+ focusedBorder = Border(BorderStroke(3.dp, PrimaryLight))+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Row(+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Text(+ text = androidx.compose.ui.res.stringResource(R.string.setup_m3u_vod_classification_label),+ style = MaterialTheme.typography.titleSmall,+ color = TextPrimary+ )+ Text(+ text = androidx.compose.ui.res.stringResource(R.string.setup_m3u_vod_classification_helper),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ Switch(+ checked = uiState.m3uVodClassificationEnabled,+ onCheckedChange = { onToggleM3uVodClassification() }+ )+ }+ }+ }++ if (sourceType == SourceType.XTREAM || sourceType == SourceType.M3U_URL || sourceType == SourceType.M3U_FILE) {+ ProviderTextField(+ value = httpUserAgent,+ onValueChange = onHttpUserAgentChange,+ placeholder = "User-Agent override (optional)",+ keyboardOptions = KeyboardOptions(+ capitalization = KeyboardCapitalization.None,+ autoCorrectEnabled = false,+ keyboardType = KeyboardType.Ascii,+ imeAction = ImeAction.Next+ )+ )+ }++ if (sourceType == SourceType.XTREAM || sourceType == SourceType.STALKER || sourceType == SourceType.M3U_URL || sourceType == SourceType.M3U_FILE) {+ ProviderTextField(+ value = httpHeaders,+ onValueChange = onHttpHeadersChange,+ placeholder = if (sourceType == SourceType.STALKER) {+ "Headers (API, optional, Header: Value | HeaderToRemove:)"+ } else {+ "Custom headers (optional, Header: Value | Header2: Value)"+ },+ keyboardOptions = KeyboardOptions(+ capitalization = KeyboardCapitalization.None,+ autoCorrectEnabled = false,+ keyboardType = KeyboardType.Ascii,+ imeAction = ImeAction.Next+ )+ )+ }++ if (supportsGuideAndLogoPolicy(sourceType)) {+ if (sourceType == SourceType.XTREAM) {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .background(Surface, RoundedCornerShape(12.dp))+ .border(1.dp, SurfaceHighlight, RoundedCornerShape(12.dp))+ .padding(horizontal = 16.dp, vertical = 12.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ Text(+ text = androidx.compose.ui.res.stringResource(R.string.setup_xtream_live_sync_mode_label),+ style = MaterialTheme.typography.titleSmall,+ color = TextPrimary+ )+ Text(+ text = androidx.compose.ui.res.stringResource(R.string.setup_xtream_live_sync_mode_helper),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ ProviderXtreamLiveSyncMode.entries.forEach { mode ->+ XtreamLiveSyncModeOptionRow(+ mode = mode,+ selected = uiState.xtreamLiveSyncMode == mode,+ onSelect = { onSelectXtreamLiveSyncMode(mode) }+ )+ }+ }+ }++ Column(+ modifier = Modifier+ .fillMaxWidth()+ .background(Surface, RoundedCornerShape(12.dp))+ .border(1.dp, SurfaceHighlight, RoundedCornerShape(12.dp))+ .padding(horizontal = 16.dp, vertical = 12.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ Text(+ text = "Guide source",+ style = MaterialTheme.typography.titleSmall,+ color = TextPrimary+ )+ Text(+ text = "Choose whether this provider uses its supplier guide, your assigned external XMLTV sources, or no guide at all.",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ GuideSourcePolicy.entries.forEach { policy ->+ GuideSourcePolicyOptionRow(+ policy = policy,+ selected = uiState.guideSourcePolicy == policy,+ onSelect = { onSelectGuideSourcePolicy(policy) }+ )+ }+ }++ Column(+ modifier = Modifier+ .fillMaxWidth()+ .background(Surface, RoundedCornerShape(12.dp))+ .border(1.dp, SurfaceHighlight, RoundedCornerShape(12.dp))+ .padding(horizontal = 16.dp, vertical = 12.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ Text(+ text = "Channel logos",+ style = MaterialTheme.typography.titleSmall,+ color = TextPrimary+ )+ Text(+ text = "Pick whether channel logos come from the supplier, the matched EPG channel icon, or a strict single source.",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ ChannelLogoSourcePolicy.entries.forEach { policy ->+ ChannelLogoSourcePolicyOptionRow(+ policy = policy,+ selected = uiState.channelLogoSourcePolicy == policy,+ onSelect = { onSelectChannelLogoSourcePolicy(policy) }+ )+ }+ }++ Column(+ modifier = Modifier+ .fillMaxWidth()+ .background(Surface, RoundedCornerShape(12.dp))+ .border(1.dp, SurfaceHighlight, RoundedCornerShape(12.dp))+ .padding(horizontal = 16.dp, vertical = 12.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ Text(+ text = androidx.compose.ui.res.stringResource(R.string.setup_epg_sync_mode_label),+ style = MaterialTheme.typography.titleSmall,+ color = TextPrimary+ )+ Text(+ text = androidx.compose.ui.res.stringResource(+ if (sourceType == SourceType.STALKER) {+ R.string.setup_stalker_epg_sync_mode_helper+ } else {+ R.string.setup_epg_sync_mode_helper+ }+ ),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ ProviderEpgSyncMode.entries.forEach { mode ->+ EpgSyncModeOptionRow(+ mode = mode,+ sourceType = sourceType,+ selected = uiState.epgSyncMode == mode,+ onSelect = { onSelectEpgSyncMode(mode) }+ )+ }+ }+ }++ if (sourceType == SourceType.STALKER) {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .background(Surface, RoundedCornerShape(12.dp))+ .border(1.dp, SurfaceHighlight, RoundedCornerShape(12.dp))+ .padding(horizontal = 16.dp, vertical = 12.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ Text(+ text = "Movie and series catalog",+ style = MaterialTheme.typography.titleSmall,+ color = TextPrimary+ )+ Text(+ text = "This is separate from EPG loading. On demand makes the provider ready after categories load; background indexing downloads the complete catalog later.",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ PolicyOptionRow(+ title = "On demand (recommended)",+ description = "Load visible shelves and opened categories as needed. Existing cached items are kept.",+ selected = uiState.stalkerCatalogMode == StalkerCatalogMode.ON_DEMAND,+ onSelect = { onSelectStalkerCatalogMode(StalkerCatalogMode.ON_DEMAND) }+ )+ PolicyOptionRow(+ title = "Complete background index",+ description = "Make the provider ready first, then maintain a complete searchable catalog in the background.",+ selected = uiState.stalkerCatalogMode == StalkerCatalogMode.BACKGROUND_INDEX,+ onSelect = { onSelectStalkerCatalogMode(StalkerCatalogMode.BACKGROUND_INDEX) }+ )+ }++ Column(+ modifier = Modifier+ .fillMaxWidth()+ .background(Surface, RoundedCornerShape(12.dp))+ .border(1.dp, SurfaceHighlight, RoundedCornerShape(12.dp))+ .padding(horizontal = 16.dp, vertical = 12.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ Text(+ text = "Stalker auth mode",+ style = MaterialTheme.typography.titleSmall,+ color = TextPrimary+ )+ Text(+ text = "Auto-detect is the default. Override it only when the portal needs credentials or a mixed MAG + account login flow.",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ StalkerAuthMode.entries.forEach { mode ->+ StalkerAuthModeOptionRow(+ mode = mode,+ selected = stalkerAuthMode == mode,+ onSelect = { onStalkerAuthModeChange(mode) }+ )+ }+ }+ if (stalkerAuthMode != StalkerAuthMode.MAC_ONLY) {+ ProviderTextField(+ value = username,+ onValueChange = onUsernameChange,+ placeholder = if (stalkerAuthMode == StalkerAuthMode.AUTO) {+ "Portal username (optional)"+ } else {+ "Portal username"+ },+ keyboardOptions = KeyboardOptions(+ capitalization = KeyboardCapitalization.None,+ autoCorrectEnabled = false,+ keyboardType = KeyboardType.Ascii,+ imeAction = ImeAction.Next+ )+ )+ ProviderTextField(+ value = password,+ onValueChange = onPasswordChange,+ placeholder = if (stalkerAuthMode == StalkerAuthMode.AUTO) {+ "Portal password (optional)"+ } else {+ "Portal password"+ },+ isPassword = true,+ keyboardOptions = KeyboardOptions(+ capitalization = KeyboardCapitalization.None,+ autoCorrectEnabled = false,+ keyboardType = KeyboardType.Password,+ imeAction = ImeAction.Next+ )+ )+ }+ ProviderTextField(+ value = stalkerDeviceProfile,+ onValueChange = onStalkerDeviceProfileChange,+ placeholder = "MAG Type (optional)"+ )+ ProviderTextField(+ value = stalkerDeviceTimezone,+ onValueChange = onStalkerDeviceTimezoneChange,+ placeholder = "Timezone (optional)"+ )+ ProviderTextField(+ value = stalkerDeviceLocale,+ onValueChange = onStalkerDeviceLocaleChange,+ placeholder = "Locale (optional)"+ )+ ProviderTextField(+ value = stalkerSerialNumber,+ onValueChange = onStalkerSerialNumberChange,+ placeholder = "Serial number (optional)"+ )+ ProviderTextField(+ value = stalkerDeviceId,+ onValueChange = onStalkerDeviceIdChange,+ placeholder = "Device ID (optional)"+ )+ ProviderTextField(+ value = stalkerDeviceId2,+ onValueChange = onStalkerDeviceId2Change,+ placeholder = "Device ID2 (optional)"+ )+ ProviderTextField(+ value = stalkerSignature,+ onValueChange = onStalkerSignatureChange,+ placeholder = "Signature (optional)"+ )+ HorizontalDivider(color = SurfaceHighlight.copy(alpha = 0.45f))+ Text(+ text = "Stalker compatibility",+ style = MaterialTheme.typography.titleSmall,+ color = TextPrimary+ )+ Text(+ text = "Portal-specific overrides for stubborn MAG/Stalker servers. Leave fields empty unless a server needs them.",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ ProviderTextField(+ value = stalkerHwVersion,+ onValueChange = onStalkerHwVersionChange,+ placeholder = "hw_version override (optional)"+ )+ ProviderTextField(+ value = stalkerApiUserAgent,+ onValueChange = onStalkerApiUserAgentChange,+ placeholder = "User-Agent (API, optional)"+ )+ ProviderTextField(+ value = stalkerPlayerUserAgent,+ onValueChange = onStalkerPlayerUserAgentChange,+ placeholder = "User-Agent (Player, optional)"+ )+ ProviderTextField(+ value = stalkerPlayerHeaders,+ onValueChange = onStalkerPlayerHeadersChange,+ placeholder = "Headers (Player, optional, Header: Value | HeaderToRemove:)"+ )+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {+ Text(+ text = "X-User-Agent Link",+ style = MaterialTheme.typography.bodyMedium,+ color = TextPrimary+ )+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ StalkerLinkOptionButton(+ text = StalkerAdvancedOptions.LINK_ETHERNET,+ selected = stalkerXUserAgentLink == StalkerAdvancedOptions.LINK_ETHERNET,+ onClick = { onStalkerXUserAgentLinkChange(StalkerAdvancedOptions.LINK_ETHERNET) }+ )+ StalkerLinkOptionButton(+ text = StalkerAdvancedOptions.LINK_WIFI,+ selected = stalkerXUserAgentLink == StalkerAdvancedOptions.LINK_WIFI,+ onClick = { onStalkerXUserAgentLinkChange(StalkerAdvancedOptions.LINK_WIFI) }+ )+ }+ }+ TvClickableSurface(+ onClick = { onStalkerProxyEnabledChange(!stalkerProxyEnabled) },+ modifier = Modifier+ .fillMaxWidth()+ .semantics { contentDescription = "Use HTTP proxy" },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (stalkerProxyEnabled) Primary.copy(alpha = 0.1f) else Surface,+ focusedContainerColor = Primary.copy(alpha = 0.22f)+ ),+ border = ClickableSurfaceDefaults.border(+ border = Border(+ BorderStroke(+ 1.dp,+ if (stalkerProxyEnabled) Primary.copy(alpha = 0.4f) else SurfaceHighlight+ )+ ),+ focusedBorder = Border(BorderStroke(3.dp, PrimaryLight))+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Row(+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Text(+ text = "Use HTTP proxy",+ style = MaterialTheme.typography.titleSmall,+ color = TextPrimary+ )+ Text(+ text = "Applies to Stalker API and playback only.",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ Switch(+ checked = stalkerProxyEnabled,+ onCheckedChange = onStalkerProxyEnabledChange+ )+ }+ }+ AnimatedVisibility(stalkerProxyEnabled) {+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+ ProviderTextField(+ value = stalkerProxyHost,+ onValueChange = onStalkerProxyHostChange,+ placeholder = "Proxy host"+ )+ ProviderTextField(+ value = stalkerProxyPort,+ onValueChange = onStalkerProxyPortChange,+ placeholder = "Proxy port",+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)+ )+ }+ }+ StalkerRequestRulesEditor(+ rules = stalkerRequestRules,+ onAddRule = onAddStalkerRequestRule,+ onUpdateRule = onUpdateStalkerRequestRule,+ onRemoveRule = onRemoveStalkerRequestRule+ )+ }+ }+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupAdvancedOptionsModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupAdvancedOptionsModel.ktnew file mode 100644index 00000000..6fc59ae5--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupAdvancedOptionsModel.kt@@ -0,0 +1,66 @@+package com.streamvault.app.ui.screens.provider++import com.streamvault.data.remote.stalker.StalkerAdvancedOptions+import com.streamvault.domain.model.ChannelLogoSourcePolicy+import com.streamvault.domain.model.GuideSourcePolicy+import com.streamvault.domain.model.ProviderEpgSyncMode+import com.streamvault.domain.model.ProviderXtreamLiveSyncMode+import com.streamvault.domain.model.StalkerAuthMode+import com.streamvault.domain.model.StalkerCatalogMode++/** UI values and callbacks shared by the provider-specific advanced sections. */+internal data class ProviderAdvancedOptions(+ val sourceType: SourceType,+ val uiState: ProviderSetupState,+ val httpUserAgent: String,+ val onHttpUserAgentChange: (String) -> Unit,+ val httpHeaders: String,+ val onHttpHeadersChange: (String) -> Unit,+ val onToggleM3uVodClassification: () -> Unit,+ val onSelectEpgSyncMode: (ProviderEpgSyncMode) -> Unit,+ val onSelectStalkerCatalogMode: (StalkerCatalogMode) -> Unit,+ val onSelectXtreamLiveSyncMode: (ProviderXtreamLiveSyncMode) -> Unit,+ val onSelectGuideSourcePolicy: (GuideSourcePolicy) -> Unit,+ val onSelectChannelLogoSourcePolicy: (ChannelLogoSourcePolicy) -> Unit,+ val username: String,+ val onUsernameChange: (String) -> Unit,+ val password: String,+ val onPasswordChange: (String) -> Unit,+ val stalkerAuthMode: StalkerAuthMode,+ val onStalkerAuthModeChange: (StalkerAuthMode) -> Unit,+ val stalkerMacAddress: String,+ val stalkerDeviceProfile: String,+ val onStalkerDeviceProfileChange: (String) -> Unit,+ val stalkerDeviceTimezone: String,+ val onStalkerDeviceTimezoneChange: (String) -> Unit,+ val stalkerDeviceLocale: String,+ val onStalkerDeviceLocaleChange: (String) -> Unit,+ val stalkerSerialNumber: String,+ val onStalkerSerialNumberChange: (String) -> Unit,+ val stalkerDeviceId: String,+ val onStalkerDeviceIdChange: (String) -> Unit,+ val stalkerDeviceId2: String,+ val onStalkerDeviceId2Change: (String) -> Unit,+ val stalkerSignature: String,+ val onStalkerSignatureChange: (String) -> Unit,+ val stalkerHwVersion: String,+ val onStalkerHwVersionChange: (String) -> Unit,+ val stalkerApiUserAgent: String,+ val onStalkerApiUserAgentChange: (String) -> Unit,+ val stalkerPlayerUserAgent: String,+ val onStalkerPlayerUserAgentChange: (String) -> Unit,+ val stalkerPlayerHeaders: String,+ val onStalkerPlayerHeadersChange: (String) -> Unit,+ val stalkerXUserAgentLink: String = StalkerAdvancedOptions.LINK_ETHERNET,+ val onStalkerXUserAgentLinkChange: (String) -> Unit = {},+ val stalkerProxyEnabled: Boolean = false,+ val onStalkerProxyEnabledChange: (Boolean) -> Unit = {},+ val stalkerProxyHost: String = "",+ val onStalkerProxyHostChange: (String) -> Unit = {},+ val stalkerProxyPort: String = "",+ val onStalkerProxyPortChange: (String) -> Unit = {},+ val stalkerRequestRules: List<StalkerRequestRuleUiState> = emptyList(),+ val onAddStalkerRequestRule: () -> Unit = {},+ val onUpdateStalkerRequestRule: (Int, StalkerRequestRuleUiState) -> Unit = { _, _ -> },+ val onRemoveStalkerRequestRule: (Int) -> Unit = {}+)diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupCompletionHost.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupCompletionHost.ktnew file mode 100644index 00000000..6b10bdfd--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupCompletionHost.kt@@ -0,0 +1,92 @@+package com.streamvault.app.ui.screens.provider++import android.widget.Toast+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.ui.platform.LocalContext+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import androidx.lifecycle.compose.LocalLifecycleOwner+import androidx.tv.material3.Text+import com.streamvault.app.ui.components.dialogs.PremiumDialog+import com.streamvault.app.ui.components.dialogs.PremiumDialogFooterButton+import kotlinx.coroutines.suspendCancellableCoroutine+import kotlin.coroutines.resume++@Composable+internal fun ProviderSetupCompletionLayer(+ uiState: ProviderSetupState,+ knownLocalM3uUrls: Set<String>,+ selectedM3uUrl: String,+ filesDir: java.io.File,+ onProviderAdded: () -> Unit,+ onAttachCreatedProvider: () -> Unit,+ onSkipCreatedProviderCombinedAttach: () -> Unit,+ cleanupImportedFiles: suspend (java.io.File, Set<String>, Int) -> Unit = ::cleanupOldImportedM3uFilesAsync+) {+ val context = LocalContext.current+ val lifecycle = LocalLifecycleOwner.current.lifecycle+ LaunchedEffect(uiState.onboardingCompletion, uiState.completionWarning, uiState.pendingCombinedAttachProfileId) {+ if (+ uiState.onboardingCompletion != ProviderSetupViewModel.OnboardingCompletion.NONE &&+ uiState.pendingCombinedAttachProfileId == null+ ) {+ if (uiState.completionWarning != null) {+ Toast.makeText(+ context,+ "Provider saved. Sync will resume in background.",+ Toast.LENGTH_LONG+ ).show()+ }+ val previousLocal = uiState.m3uUrl.takeIf { it.startsWith("file://") }+ val selectedLocal = selectedM3uUrl.takeIf { it.startsWith("file://") }+ val protectedUris = buildSet {+ knownLocalM3uUrls.forEach { knownUri ->+ if (knownUri != previousLocal || previousLocal == selectedLocal) add(knownUri)+ }+ selectedLocal?.let(::add)+ }+ cleanupImportedFiles(filesDir, protectedUris, 20)+ lifecycle.awaitResumedForProviderSetup()+ onProviderAdded()+ }+ }++ if (uiState.pendingCombinedAttachProfileId != null) {+ PremiumDialog(+ title = "Add Playlist To Combined M3U?",+ subtitle = "Add ${uiState.createdProviderName ?: "this playlist"} to " ++ "${uiState.pendingCombinedAttachProfileName ?: "the active combined source"} " ++ "and keep that combined source active for Live TV?",+ onDismissRequest = onSkipCreatedProviderCombinedAttach,+ content = {},+ footer = {+ PremiumDialogFooterButton(+ label = "Not Now",+ onClick = onSkipCreatedProviderCombinedAttach+ )+ PremiumDialogFooterButton(+ label = "Add To Combined",+ onClick = onAttachCreatedProvider,+ emphasized = true+ )+ }+ )+ }+}++private suspend fun Lifecycle.awaitResumedForProviderSetup() {+ if (currentState.isAtLeast(Lifecycle.State.RESUMED)) return++ suspendCancellableCoroutine { continuation ->+ lateinit var observer: LifecycleEventObserver+ observer = LifecycleEventObserver { source, _ ->+ if (source.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) {+ source.lifecycle.removeObserver(observer)+ if (continuation.isActive) continuation.resume(Unit)+ }+ }+ addObserver(observer)+ continuation.invokeOnCancellation { removeObserver(observer) }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupFormModels.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupFormModels.ktnew file mode 100644index 00000000..56730356--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupFormModels.kt@@ -0,0 +1,33 @@+package com.streamvault.app.ui.screens.provider++import com.streamvault.data.remote.stalker.StalkerParamOverride+import com.streamvault.data.remote.stalker.StalkerRequestRule++internal data class StalkerRequestRuleUiState(+ val action: String = "",+ val blockRequest: Boolean = false,+ val paramsText: String = ""+)++internal fun StalkerRequestRuleUiState.toRule(): StalkerRequestRule =+ StalkerRequestRule(+ action = action.trim(),+ blockRequest = blockRequest,+ paramOverrides = paramsText+ .split('|', '\n')+ .mapNotNull { entry ->+ val trimmed = entry.trim()+ if (trimmed.isBlank()) return@mapNotNull null+ val separator = trimmed.indexOf('=').takeIf { it >= 0 } ?: trimmed.indexOf(':')+ val name = if (separator >= 0) trimmed.substring(0, separator).trim() else trimmed+ val value = if (separator >= 0) trimmed.substring(separator + 1).trim() else ""+ name.takeIf { it.isNotBlank() }?.let { StalkerParamOverride(it, value) }+ }+ )++internal fun StalkerRequestRule.toUiState(): StalkerRequestRuleUiState =+ StalkerRequestRuleUiState(+ action = action,+ blockRequest = blockRequest,+ paramsText = paramOverrides.joinToString(" | ") { "${it.name}=${it.value}" }+ )diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupFormPrimitives.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupFormPrimitives.ktnew file mode 100644index 00000000..4de580f1--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupFormPrimitives.kt@@ -0,0 +1,33 @@+package com.streamvault.app.ui.screens.provider++import androidx.compose.runtime.Composable+import androidx.compose.ui.text.AnnotatedString+import androidx.compose.ui.text.input.OffsetMapping+import androidx.compose.ui.text.input.TransformedText+import androidx.compose.ui.text.input.VisualTransformation+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.streamvault.app.ui.theme.ErrorColor++@Composable+internal fun FormErrors(validationError: String?, error: String?) {+ validationError?.let {+ Text(text = it, style = MaterialTheme.typography.bodyMedium, color = ErrorColor)+ }+ error?.let {+ Text(text = it, style = MaterialTheme.typography.bodyMedium, color = ErrorColor)+ }+}++internal class RevealingPasswordVisualTransformation(+ private val revealedIndex: Int?+) : VisualTransformation {+ override fun filter(text: AnnotatedString): TransformedText {+ val transformed = buildString(text.length) {+ text.text.forEachIndexed { index, ch ->+ append(if (revealedIndex != null && index == revealedIndex) ch else '*')+ }+ }+ return TransformedText(AnnotatedString(transformed), OffsetMapping.Identity)+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupImportDialogs.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupImportDialogs.ktnew file mode 100644index 00000000..3394ba20--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupImportDialogs.kt@@ -0,0 +1,245 @@+package com.streamvault.app.ui.screens.provider++import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.layout.*+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.SettingsBackupRestore+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.focus.onFocusEvent+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.tv.material3.Border+import androidx.tv.material3.ClickableSurfaceDefaults+import androidx.tv.material3.Icon+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Surface as TvSurface+import androidx.tv.material3.Text+import com.streamvault.app.R+import com.streamvault.app.ui.components.dialogs.PremiumDialog+import com.streamvault.app.ui.components.dialogs.PremiumDialogFooterButton+import com.streamvault.app.ui.interaction.TvClickableSurface+import com.streamvault.app.ui.interaction.mouseClickable+import com.streamvault.app.ui.theme.*+import com.streamvault.domain.manager.DriveBackupSnapshot++@Composable+internal fun ImportOptionsButton(+ text: String,+ onClick: () -> Unit,+ modifier: Modifier = Modifier,+ compact: Boolean = false+) {+ var isFocused by remember { mutableStateOf(false) }++ TvClickableSurface(+ onClick = onClick,+ modifier = modifier+ .height(if (compact) 38.dp else 44.dp)+ .onFocusEvent { isFocused = it.hasFocus }+ .semantics { contentDescription = text },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Surface.copy(alpha = 0.9f),+ focusedContainerColor = SurfaceHighlight+ ),+ border = ClickableSurfaceDefaults.border(+ border = Border(BorderStroke(1.dp, if (isFocused) PrimaryLight else SurfaceHighlight)),+ focusedBorder = Border(BorderStroke(2.dp, FocusBorder))+ )+ ) {+ Row(+ modifier = Modifier+ .fillMaxSize()+ .padding(horizontal = if (compact) 10.dp else 14.dp),+ horizontalArrangement = Arrangement.Center,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Icon(+ imageVector = Icons.Default.SettingsBackupRestore,+ contentDescription = null,+ modifier = Modifier.size(if (compact) 18.dp else 22.dp),+ tint = if (isFocused) TextPrimary else OnSurface+ )+ Spacer(modifier = Modifier.width(if (compact) 6.dp else 8.dp))+ Text(+ text = text,+ style = if (compact) MaterialTheme.typography.labelSmall else MaterialTheme.typography.labelMedium,+ color = if (isFocused) TextPrimary else OnSurface+ )+ }+ }+}++@Composable+internal fun ImportOptionsDialog(+ isImportingBackup: Boolean,+ driveSignedIn: Boolean,+ onDismiss: () -> Unit,+ onImportBackup: () -> Unit,+ onImportFromDrive: () -> Unit,+ onDriveSignIn: () -> Unit+) {+ PremiumDialog(+ title = stringResource(R.string.settings_backup_restore),+ subtitle = stringResource(R.string.settings_restore_subtitle),+ onDismissRequest = onDismiss,+ widthFraction = 0.34f,+ heightFraction = null,+ bodyHeightFraction = 0.28f,+ content = {+ Column(+ verticalArrangement = Arrangement.spacedBy(12.dp),+ horizontalAlignment = Alignment.CenterHorizontally,+ modifier = Modifier.fillMaxWidth()+ ) {+ ImportDialogActionButton(+ text = stringResource(R.string.setup_import_backup),+ isLoading = isImportingBackup,+ onClick = onImportBackup+ )+ if (driveSignedIn) {+ ImportDialogActionButton(+ text = stringResource(R.string.settings_drive_pull),+ isLoading = isImportingBackup,+ onClick = onImportFromDrive+ )+ } else {+ ImportDialogActionButton(+ text = stringResource(R.string.settings_drive_signin),+ isLoading = false,+ onClick = onDriveSignIn+ )+ }+ }+ },+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.add_group_cancel),+ onClick = onDismiss+ )+ }+ )+}++@Composable+internal fun DriveBackupSnapshotChoiceDialog(+ snapshots: List<DriveBackupSnapshot>,+ onSelect: (String) -> Unit,+ onDismiss: () -> Unit,+) {+ PremiumDialog(+ title = stringResource(R.string.settings_drive_choose_backup_title),+ subtitle = stringResource(R.string.settings_drive_choose_backup_subtitle),+ onDismissRequest = onDismiss,+ widthFraction = 0.52f,+ heightFraction = 0.82f,+ bodyHeightFraction = 0.64f,+ content = {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .verticalScroll(rememberScrollState()),+ verticalArrangement = Arrangement.spacedBy(10.dp),+ ) {+ snapshots.forEach { snapshot ->+ SmallActionButton(+ text = snapshot.fileName,+ isLoading = false,+ onClick = { onSelect(snapshot.id) },+ )+ Text(+ text = formatDriveSnapshotDetails(snapshot),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurface.copy(alpha = 0.72f),+ modifier = Modifier.padding(horizontal = 8.dp),+ )+ }+ }+ },+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_drive_cancel_backup_choice),+ onClick = onDismiss,+ )+ },+ )+}++private fun formatDriveSnapshotDetails(snapshot: DriveBackupSnapshot): String {+ val date = snapshot.modifiedAtMs?.let {+ java.text.DateFormat.getDateTimeInstance(+ java.text.DateFormat.SHORT,+ java.text.DateFormat.SHORT,+ ).format(java.util.Date(it))+ } ?: "Date unavailable"+ val size = if (snapshot.sizeBytes > 0L) "${snapshot.sizeBytes / 1024L} KB" else "Size unavailable"+ return "$date · $size"+}++@Composable+private fun ImportDialogActionButton(+ text: String,+ isLoading: Boolean,+ onClick: () -> Unit+) {+ Box(modifier = Modifier.fillMaxWidth(0.72f)) {+ SmallActionButton(+ text = text,+ isLoading = isLoading,+ onClick = onClick+ )+ }+}++// ??? FileSelectorCard ?????????????????????????????????????????????????????????++@Composable+internal fun FileSelectorCard(+ fileName: String?,+ fileSelectedHint: String,+ emptySelectionTitle: String,+ emptySelectionHint: String,+ onClick: () -> Unit+) {+ var isFocused by remember { mutableStateOf(false) }+ val borderColor = if (isFocused) Primary else SurfaceHighlight+ val bgColor = if (isFocused) Surface else SurfaceElevated++ TvSurface(+ onClick = onClick,+ modifier = Modifier.fillMaxWidth().height(80.dp).onFocusEvent { isFocused = it.hasFocus }.mouseClickable(onClick = onClick),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),+ border = ClickableSurfaceDefaults.border(+ border = Border(BorderStroke(1.dp, borderColor)),+ focusedBorder = Border(BorderStroke(2.dp, FocusBorder))+ ),+ colors = ClickableSurfaceDefaults.colors(containerColor = bgColor, focusedContainerColor = bgColor)+ ) {+ Column(+ modifier = Modifier.fillMaxSize().padding(16.dp),+ verticalArrangement = Arrangement.Center,+ horizontalAlignment = Alignment.CenterHorizontally+ ) {+ if (fileName != null) {+ Text(text = fileName, style = MaterialTheme.typography.bodyLarge, color = OnBackground, textAlign = TextAlign.Center)+ Text(text = fileSelectedHint, style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim)+ } else {+ Text(text = emptySelectionTitle, style = MaterialTheme.typography.bodyLarge, color = OnBackground)+ Text(text = emptySelectionHint, style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim)+ }+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupImportSupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupImportSupport.ktnew file mode 100644index 00000000..0e1a91b2--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupImportSupport.kt@@ -0,0 +1,45 @@+package com.streamvault.app.ui.screens.provider++import android.content.Context+import com.streamvault.app.R+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++internal fun cleanupOldImportedM3uFiles(+ filesDir: java.io.File,+ protectedFileUris: Set<String>,+ keepLatest: Int+) {+ val protectedPaths = protectedFileUris+ .mapNotNull { it.removePrefix("file://").takeIf { p -> p.isNotBlank() } }+ .toSet()++ val importedFiles = filesDir+ .listFiles { file ->+ file.isFile && file.name.startsWith("m3u_") &&+ (file.name.endsWith(".m3u") || file.name.endsWith(".m3u8"))+ }+ ?.sortedByDescending { it.lastModified() }+ ?: return++ importedFiles.drop(keepLatest).forEach { stale ->+ if (stale.absolutePath !in protectedPaths) runCatching { stale.delete() }+ }+}++internal suspend fun cleanupOldImportedM3uFilesAsync(+ filesDir: java.io.File,+ protectedFileUris: Set<String>,+ keepLatest: Int+) = withContext(Dispatchers.IO) {+ cleanupOldImportedM3uFiles(filesDir, protectedFileUris, keepLatest)+}++internal fun resolveFileImportError(context: Context, error: Throwable): String {+ val msg = error.message.orEmpty()+ val isStorageFull = msg.contains("ENOSPC", ignoreCase = true) ||+ msg.contains("no space", ignoreCase = true) ||+ msg.contains("space left", ignoreCase = true)+ return if (isStorageFull) context.getString(R.string.setup_file_import_storage_full)+ else context.getString(R.string.setup_file_import_failed)+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupJellyfinForm.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupJellyfinForm.ktnew file mode 100644index 00000000..5997e11f--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupJellyfinForm.kt@@ -0,0 +1,138 @@+@file:Suppress("UseKtx")++package com.streamvault.app.ui.screens.provider++import android.graphics.Bitmap+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.*+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.tv.material3.ButtonDefaults+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.google.zxing.BarcodeFormat+import com.google.zxing.qrcode.QRCodeWriter+import com.streamvault.app.R+import com.streamvault.app.ui.interaction.TvButton+import com.streamvault.app.ui.theme.AccentCyan+import com.streamvault.app.ui.theme.TextPrimary+import com.streamvault.app.ui.theme.TextSecondary+import com.streamvault.app.ui.theme.TextTertiary++@Composable+internal fun JellyfinProviderForm(+ serverUrl: String,+ onServerUrlChange: (String) -> Unit,+ username: String,+ onUsernameChange: (String) -> Unit,+ password: String,+ onPasswordChange: (String) -> Unit,+ name: String,+ onNameChange: (String) -> Unit,+ quickConnectCode: String,+ onQuickConnectRequest: () -> Unit,+ isEditing: Boolean+) {+ Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {+ Text(+ text = stringResource(R.string.setup_tab_jellyfin),+ style = MaterialTheme.typography.titleLarge,+ color = TextPrimary+ )++ // Step 1: Server URL+ ProviderTextField(+ value = serverUrl,+ onValueChange = onServerUrlChange,+ placeholder = stringResource(R.string.setup_server_url)+ )++ // Quick Connect button + QR code display+ if (!isEditing) {+ TvButton(+ onClick = onQuickConnectRequest,+ colors = ButtonDefaults.colors(containerColor = AccentCyan, contentColor = Color.Black)+ ) {+ Text(stringResource(R.string.setup_jellyfin_quick_connect))+ }+ }++ // QR code and code text (shown after quick connect is initiated)+ if (quickConnectCode.isNotBlank()) {+ Spacer(modifier = Modifier.height(8.dp))+ val qrCodeBitmap = remember(quickConnectCode, serverUrl) {+ generateJellyfinQuickConnectQrCode(serverUrl, quickConnectCode)+ }+ if (qrCodeBitmap != null) {+ Box(+ modifier = Modifier+ .size(240.dp)+ .background(Color.White, RoundedCornerShape(12.dp))+ .padding(8.dp),+ contentAlignment = Alignment.Center+ ) {+ Image(+ bitmap = qrCodeBitmap.asImageBitmap(),+ contentDescription = "Quick Connect QR Code",+ modifier = Modifier.fillMaxSize()+ )+ }+ Spacer(modifier = Modifier.height(8.dp))+ }+ Text(+ text = stringResource(R.string.setup_jellyfin_quick_connect_code, quickConnectCode),+ style = MaterialTheme.typography.bodyMedium,+ color = TextSecondary+ )+ Text(+ text = stringResource(R.string.setup_jellyfin_quick_connect_code_instructions),+ style = MaterialTheme.typography.bodySmall,+ color = TextTertiary+ )+ Spacer(modifier = Modifier.height(14.dp))+ }++ // Step 2: Manual credentials (for password auth or existing provider edit)+ ProviderTextField(+ value = username,+ onValueChange = onUsernameChange,+ placeholder = stringResource(R.string.setup_username)+ )+ ProviderTextField(+ value = password,+ onValueChange = onPasswordChange,+ placeholder = stringResource(R.string.setup_password),+ isPassword = true+ )+ ProviderTextField(+ value = name,+ onValueChange = onNameChange,+ placeholder = stringResource(R.string.setup_name_placeholder)+ )+ }+}++internal fun generateJellyfinQuickConnectQrCode(serverUrl: String, code: String): Bitmap? {+ return try {+ val qrUrl = "${serverUrl.trimEnd('/')}/web/index.html#!/quickconnect.html?code=$code"+ val writer = QRCodeWriter()+ val bitMatrix = writer.encode(qrUrl, BarcodeFormat.QR_CODE, 512, 512)+ val bitmap = Bitmap.createBitmap(512, 512, Bitmap.Config.RGB_565)+ for (x in 0 until 512) {+ for (y in 0 until 512) {+ bitmap.setPixel(x, y, if (bitMatrix[x, y]) android.graphics.Color.BLACK else android.graphics.Color.WHITE)+ }+ }+ bitmap+ } catch (e: Exception) {+ null+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupPairingCard.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupPairingCard.ktnew file mode 100644index 00000000..21203da1--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupPairingCard.kt@@ -0,0 +1,142 @@+package com.streamvault.app.ui.screens.provider++import androidx.compose.foundation.Image+import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.*+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.tv.material3.Border+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Surface+import androidx.tv.material3.SurfaceDefaults+import androidx.tv.material3.Text+import com.streamvault.app.R+import com.streamvault.app.pairing.ProviderQrPairingState+import com.streamvault.app.pairing.ProviderQrPairingStatus+import com.streamvault.app.ui.components.shell.StatusPill+import com.streamvault.app.ui.theme.*++@Composable+internal fun PhonePairingCard(+ pairingState: ProviderQrPairingState,+ onStart: () -> Unit,+ onStop: () -> Unit+) {+ val isActive = pairingState.status == ProviderQrPairingStatus.READY ||+ pairingState.status == ProviderQrPairingStatus.RECEIVING+ val message = pairingState.message ?: stringResource(R.string.setup_phone_pairing_body)++ Surface(+ modifier = Modifier.fillMaxWidth(),+ shape = RoundedCornerShape(16.dp),+ colors = SurfaceDefaults.colors(containerColor = Surface.copy(alpha = 0.72f)),+ border = Border(+ border = BorderStroke(+ 1.dp,+ if (isActive) Primary.copy(alpha = 0.55f) else SurfaceHighlight+ ),+ shape = RoundedCornerShape(16.dp)+ )+ ) {+ Column(+ modifier = Modifier.padding(16.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Text(+ text = stringResource(R.string.setup_phone_pairing_title),+ style = MaterialTheme.typography.titleMedium,+ color = OnBackground+ )+ Text(+ text = message,+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ StatusPill(+ label = when (pairingState.status) {+ ProviderQrPairingStatus.IDLE -> stringResource(R.string.setup_phone_pairing_idle)+ ProviderQrPairingStatus.READY -> stringResource(R.string.setup_phone_pairing_ready)+ ProviderQrPairingStatus.RECEIVING -> stringResource(R.string.setup_phone_pairing_receiving)+ ProviderQrPairingStatus.COMPLETE -> stringResource(R.string.setup_phone_pairing_complete)+ ProviderQrPairingStatus.ERROR -> stringResource(R.string.setup_phone_pairing_error)+ },+ containerColor = if (pairingState.status == ProviderQrPairingStatus.ERROR) {+ ErrorColor.copy(alpha = 0.35f)+ } else {+ PrimaryGlow+ }+ )+ }++ pairingState.qrBitmap?.let { bitmap ->+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.spacedBy(16.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Image(+ bitmap = bitmap.asImageBitmap(),+ contentDescription = stringResource(R.string.setup_phone_pairing_qr_description),+ modifier = Modifier+ .size(156.dp)+ .background(Color.White, RoundedCornerShape(12.dp))+ .padding(8.dp)+ )+ Column(+ modifier = Modifier.weight(1f),+ verticalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ Text(+ text = stringResource(R.string.setup_phone_pairing_same_wifi),+ style = MaterialTheme.typography.bodyMedium,+ color = OnBackground+ )+ pairingState.url?.let { url ->+ Text(+ text = url,+ style = MaterialTheme.typography.bodySmall,+ color = Primary,+ maxLines = 3+ )+ }+ }+ }+ }++ Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {+ Box(modifier = Modifier.weight(1f)) {+ SmallActionButton(+ text = if (isActive) {+ stringResource(R.string.setup_phone_pairing_restart)+ } else {+ stringResource(R.string.setup_phone_pairing_start)+ },+ onClick = onStart+ )+ }+ if (isActive) {+ Box(modifier = Modifier.weight(1f)) {+ SmallActionButton(+ text = stringResource(R.string.setup_phone_pairing_stop),+ onClick = onStop+ )+ }+ }+ }+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupPasswordGlyph.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupPasswordGlyph.ktnew file mode 100644index 00000000..fa3618e4--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupPasswordGlyph.kt@@ -0,0 +1,39 @@+package com.streamvault.app.ui.screens.provider++import androidx.compose.foundation.Canvas+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.drawscope.Stroke+import androidx.compose.ui.unit.dp++@Composable+internal fun PasswordVisibilityGlyph(+ isVisible: Boolean,+ tint: Color,+ modifier: Modifier = Modifier+) {+ Canvas(modifier = modifier.size(18.dp)) {+ val stroke = Stroke(width = size.minDimension * 0.11f)+ drawOval(+ color = tint,+ topLeft = androidx.compose.ui.geometry.Offset(1.6f, size.height * 0.22f),+ size = androidx.compose.ui.geometry.Size(size.width - 3.2f, size.height * 0.56f),+ style = stroke+ )+ drawCircle(+ color = tint,+ radius = size.minDimension * 0.14f,+ center = center+ )+ if (!isVisible) {+ drawLine(+ color = tint,+ start = androidx.compose.ui.geometry.Offset(size.width * 0.18f, size.height * 0.82f),+ end = androidx.compose.ui.geometry.Offset(size.width * 0.82f, size.height * 0.18f),+ strokeWidth = size.minDimension * 0.11f+ )+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupPolicyOptions.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupPolicyOptions.ktnew file mode 100644index 00000000..ccd31a90--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupPolicyOptions.kt@@ -0,0 +1,321 @@+package com.streamvault.app.ui.screens.provider++import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.RadioButton+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.unit.dp+import androidx.tv.material3.Border+import androidx.tv.material3.ClickableSurfaceDefaults+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Surface as TvSurface+import androidx.tv.material3.Text+import com.streamvault.app.R+import com.streamvault.app.ui.interaction.mouseClickable+import com.streamvault.app.ui.theme.*+import com.streamvault.domain.model.ChannelLogoSourcePolicy+import com.streamvault.domain.model.GuideSourcePolicy+import com.streamvault.domain.model.ProviderEpgSyncMode+import com.streamvault.domain.model.ProviderXtreamLiveSyncMode+import com.streamvault.domain.model.StalkerAuthMode++@Composable+internal fun XtreamLiveSyncModeOptionRow(+ mode: ProviderXtreamLiveSyncMode,+ selected: Boolean,+ onSelect: () -> Unit+) {+ val titleRes = when (mode) {+ ProviderXtreamLiveSyncMode.AUTO -> R.string.setup_xtream_live_sync_mode_auto_title+ ProviderXtreamLiveSyncMode.CATEGORY_BY_CATEGORY -> R.string.setup_xtream_live_sync_mode_category_title+ ProviderXtreamLiveSyncMode.STREAM_ALL -> R.string.setup_xtream_live_sync_mode_stream_all_title+ }+ val descriptionRes = when (mode) {+ ProviderXtreamLiveSyncMode.AUTO -> R.string.setup_xtream_live_sync_mode_auto_description+ ProviderXtreamLiveSyncMode.CATEGORY_BY_CATEGORY -> R.string.setup_xtream_live_sync_mode_category_description+ ProviderXtreamLiveSyncMode.STREAM_ALL -> R.string.setup_xtream_live_sync_mode_stream_all_description+ }+ TvSurface(+ onClick = onSelect,+ modifier = Modifier+ .fillMaxWidth()+ .mouseClickable(onClick = onSelect),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (selected) Primary.copy(alpha = 0.12f) else Color.Transparent,+ focusedContainerColor = if (selected) Primary.copy(alpha = 0.26f) else SurfaceHighlight.copy(alpha = 0.9f)+ ),+ border = ClickableSurfaceDefaults.border(+ border = Border(+ BorderStroke(+ 1.dp,+ if (selected) Primary.copy(alpha = 0.45f) else Color.Transparent+ )+ ),+ focusedBorder = Border(BorderStroke(3.dp, PrimaryLight))+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Row(+ modifier = Modifier.padding(horizontal = 8.dp, vertical = 8.dp),+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ RadioButton(+ selected = selected,+ onClick = onSelect+ )+ Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {+ Text(+ text = androidx.compose.ui.res.stringResource(titleRes),+ style = MaterialTheme.typography.bodyMedium,+ color = TextPrimary+ )+ Text(+ text = androidx.compose.ui.res.stringResource(descriptionRes),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ }+ }+}++@Composable+internal fun StalkerAuthModeOptionRow(+ mode: StalkerAuthMode,+ selected: Boolean,+ onSelect: () -> Unit+) {+ val title = when (mode) {+ StalkerAuthMode.AUTO -> "Auto-detect"+ StalkerAuthMode.MAC_ONLY -> "MAC only"+ StalkerAuthMode.MAC_PLUS_CREDENTIALS -> "MAC + credentials"+ StalkerAuthMode.CREDENTIALS_ONLY -> "Credentials only"+ }+ val description = when (mode) {+ StalkerAuthMode.AUTO -> "Try the portal's likely auth flow first and retry once if a different Stalker mode fits better."+ StalkerAuthMode.MAC_ONLY -> "Use MAG-style MAC authentication without a portal account login."+ StalkerAuthMode.MAC_PLUS_CREDENTIALS -> "Keep the MAG identity and add portal account credentials for stricter portals."+ StalkerAuthMode.CREDENTIALS_ONLY -> "Use portal account credentials even if the MAC address is optional or ignored."+ }+ TvSurface(+ onClick = onSelect,+ modifier = Modifier+ .fillMaxWidth()+ .mouseClickable(onClick = onSelect),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (selected) Primary.copy(alpha = 0.12f) else Color.Transparent,+ focusedContainerColor = if (selected) Primary.copy(alpha = 0.26f) else SurfaceHighlight.copy(alpha = 0.9f)+ ),+ border = ClickableSurfaceDefaults.border(+ border = Border(+ BorderStroke(+ 1.dp,+ if (selected) Primary.copy(alpha = 0.45f) else Color.Transparent+ )+ ),+ focusedBorder = Border(BorderStroke(3.dp, PrimaryLight))+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Row(+ modifier = Modifier.padding(horizontal = 8.dp, vertical = 8.dp),+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ RadioButton(+ selected = selected,+ onClick = onSelect+ )+ Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {+ Text(+ text = title,+ style = MaterialTheme.typography.bodyMedium,+ color = TextPrimary+ )+ Text(+ text = description,+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ }+ }+}++@Composable+internal fun EpgSyncModeOptionRow(+ mode: ProviderEpgSyncMode,+ sourceType: SourceType,+ selected: Boolean,+ onSelect: () -> Unit+) {+ val titleRes = when (mode) {+ ProviderEpgSyncMode.UPFRONT -> R.string.setup_epg_sync_mode_upfront_title+ ProviderEpgSyncMode.BACKGROUND -> R.string.setup_epg_sync_mode_background_title+ ProviderEpgSyncMode.SKIP -> R.string.setup_epg_sync_mode_skip_title+ }+ val descriptionRes = when (mode) {+ ProviderEpgSyncMode.UPFRONT -> if (sourceType == SourceType.STALKER) {+ R.string.setup_stalker_epg_sync_mode_upfront_description+ } else {+ R.string.setup_epg_sync_mode_upfront_description+ }+ ProviderEpgSyncMode.BACKGROUND -> if (sourceType == SourceType.STALKER) {+ R.string.setup_stalker_epg_sync_mode_background_description+ } else {+ R.string.setup_epg_sync_mode_background_description+ }+ ProviderEpgSyncMode.SKIP -> if (sourceType == SourceType.STALKER) {+ R.string.setup_stalker_epg_sync_mode_skip_description+ } else {+ R.string.setup_epg_sync_mode_skip_description+ }+ }+ TvSurface(+ onClick = onSelect,+ modifier = Modifier+ .fillMaxWidth()+ .mouseClickable(onClick = onSelect),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (selected) Primary.copy(alpha = 0.12f) else Color.Transparent,+ focusedContainerColor = if (selected) Primary.copy(alpha = 0.26f) else SurfaceHighlight.copy(alpha = 0.9f)+ ),+ border = ClickableSurfaceDefaults.border(+ border = Border(+ BorderStroke(+ 1.dp,+ if (selected) Primary.copy(alpha = 0.45f) else Color.Transparent+ )+ ),+ focusedBorder = Border(BorderStroke(3.dp, PrimaryLight))+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Row(+ modifier = Modifier.padding(horizontal = 8.dp, vertical = 8.dp),+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ RadioButton(+ selected = selected,+ onClick = onSelect+ )+ Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {+ Text(+ text = androidx.compose.ui.res.stringResource(titleRes),+ style = MaterialTheme.typography.bodyMedium,+ color = TextPrimary+ )+ Text(+ text = androidx.compose.ui.res.stringResource(descriptionRes),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ }+ }+}++internal fun supportsGuideAndLogoPolicy(sourceType: SourceType): Boolean = when (sourceType) {+ SourceType.XTREAM,+ SourceType.STALKER,+ SourceType.M3U_URL,+ SourceType.M3U_FILE -> true+ SourceType.JELLYFIN -> false+}++@Composable+internal fun GuideSourcePolicyOptionRow(+ policy: GuideSourcePolicy,+ selected: Boolean,+ onSelect: () -> Unit+) {+ val title = when (policy) {+ GuideSourcePolicy.AUTO -> "Auto"+ GuideSourcePolicy.EXTERNAL_ONLY -> "Use external EPG only"+ GuideSourcePolicy.PROVIDER_ONLY -> "Use supplier EPG only"+ GuideSourcePolicy.DISABLED -> "Disable guide data"+ }+ val description = when (policy) {+ GuideSourcePolicy.AUTO -> "Keep the current mixed behavior: external XMLTV can override supplier guide data, and unmatched channels may still use supplier fallback."+ GuideSourcePolicy.EXTERNAL_ONLY -> "Use only assigned external XMLTV sources. Unmatched channels stay without guide data."+ GuideSourcePolicy.PROVIDER_ONLY -> "Ignore assigned external XMLTV sources for this provider and use only the supplier guide paths."+ GuideSourcePolicy.DISABLED -> "Do not import or resolve guide data for this provider."+ }+ PolicyOptionRow(title = title, description = description, selected = selected, onSelect = onSelect)+}++@Composable+internal fun ChannelLogoSourcePolicyOptionRow(+ policy: ChannelLogoSourcePolicy,+ selected: Boolean,+ onSelect: () -> Unit+) {+ val title = when (policy) {+ ChannelLogoSourcePolicy.SUPPLIER_PREFERRED -> "Supplier logos first"+ ChannelLogoSourcePolicy.EPG_PREFERRED -> "Prefer EPG logos"+ ChannelLogoSourcePolicy.SUPPLIER_ONLY -> "Supplier logos only"+ ChannelLogoSourcePolicy.EPG_ONLY -> "EPG logos only"+ }+ val description = when (policy) {+ ChannelLogoSourcePolicy.SUPPLIER_PREFERRED -> "Use the supplier logo when it exists, then fall back to the matched EPG icon."+ ChannelLogoSourcePolicy.EPG_PREFERRED -> "Use the matched EPG icon first, then fall back to the supplier logo."+ ChannelLogoSourcePolicy.SUPPLIER_ONLY -> "Always use supplier logos for this provider."+ ChannelLogoSourcePolicy.EPG_ONLY -> "Always use matched EPG icons for this provider."+ }+ PolicyOptionRow(title = title, description = description, selected = selected, onSelect = onSelect)+}++@Composable+internal fun PolicyOptionRow(+ title: String,+ description: String,+ selected: Boolean,+ onSelect: () -> Unit+) {+ TvSurface(+ onClick = onSelect,+ modifier = Modifier+ .fillMaxWidth()+ .mouseClickable(onClick = onSelect),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (selected) Primary.copy(alpha = 0.12f) else Color.Transparent,+ focusedContainerColor = if (selected) Primary.copy(alpha = 0.26f) else SurfaceHighlight.copy(alpha = 0.9f)+ ),+ border = ClickableSurfaceDefaults.border(+ border = Border(+ BorderStroke(+ 1.dp,+ if (selected) Primary.copy(alpha = 0.45f) else Color.Transparent+ )+ ),+ focusedBorder = Border(BorderStroke(3.dp, PrimaryLight))+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Row(+ modifier = Modifier.padding(horizontal = 8.dp, vertical = 8.dp),+ horizontalArrangement = Arrangement.spacedBy(12.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ RadioButton(selected = selected, onClick = onSelect)+ Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {+ Text(text = title, style = MaterialTheme.typography.bodyMedium, color = TextPrimary)+ Text(text = description, style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim)+ }+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupProviderForms.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupProviderForms.ktnew file mode 100644index 00000000..599e59e0--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupProviderForms.kt@@ -0,0 +1,264 @@+package com.streamvault.app.ui.screens.provider++import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.imePadding+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.verticalScroll+import androidx.compose.material3.HorizontalDivider+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.tv.material3.Border+import androidx.tv.material3.Surface as TvSurface+import androidx.tv.material3.SurfaceDefaults+import com.streamvault.app.R+import com.streamvault.app.device.rememberIsTelevisionDevice+import com.streamvault.app.pairing.ProviderQrPairingState+import com.streamvault.app.ui.theme.SurfaceElevated+import com.streamvault.app.ui.theme.SurfaceHighlight+import com.streamvault.domain.model.ChannelLogoSourcePolicy+import com.streamvault.domain.model.GuideSourcePolicy+import com.streamvault.domain.model.ProviderEpgSyncMode+import com.streamvault.domain.model.ProviderXtreamLiveSyncMode+import com.streamvault.domain.model.StalkerAuthMode+import com.streamvault.domain.model.StalkerCatalogMode+import com.streamvault.domain.model.StalkerProtocolPreference++@Composable+internal fun ProviderFormContent(+ sourceType: SourceType,+ uiState: ProviderSetupState,+ pairingState: ProviderQrPairingState,+ name: String,+ onNameChange: (String) -> Unit,+ serverUrl: String,+ onServerUrlChange: (String) -> Unit,+ username: String,+ onUsernameChange: (String) -> Unit,+ password: String,+ onPasswordChange: (String) -> Unit,+ m3uUrl: String,+ onM3uUrlChange: (String) -> Unit,+ httpUserAgent: String,+ onHttpUserAgentChange: (String) -> Unit,+ httpHeaders: String,+ onHttpHeadersChange: (String) -> Unit,+ stalkerMacAddress: String,+ onStalkerMacAddressChange: (String) -> Unit,+ stalkerAuthMode: StalkerAuthMode,+ onStalkerAuthModeChange: (StalkerAuthMode) -> Unit,+ stalkerDeviceProfile: String,+ onStalkerDeviceProfileChange: (String) -> Unit,+ stalkerDeviceTimezone: String,+ onStalkerDeviceTimezoneChange: (String) -> Unit,+ stalkerDeviceLocale: String,+ onStalkerDeviceLocaleChange: (String) -> Unit,+ stalkerSerialNumber: String,+ onStalkerSerialNumberChange: (String) -> Unit,+ stalkerDeviceId: String,+ onStalkerDeviceIdChange: (String) -> Unit,+ stalkerDeviceId2: String,+ onStalkerDeviceId2Change: (String) -> Unit,+ stalkerSignature: String,+ onStalkerSignatureChange: (String) -> Unit,+ stalkerHwVersion: String,+ onStalkerHwVersionChange: (String) -> Unit,+ stalkerApiUserAgent: String,+ onStalkerApiUserAgentChange: (String) -> Unit,+ stalkerPlayerUserAgent: String,+ onStalkerPlayerUserAgentChange: (String) -> Unit,+ stalkerPlayerHeaders: String,+ onStalkerPlayerHeadersChange: (String) -> Unit,+ stalkerXUserAgentLink: String,+ onStalkerXUserAgentLinkChange: (String) -> Unit,+ stalkerProxyEnabled: Boolean,+ onStalkerProxyEnabledChange: (Boolean) -> Unit,+ stalkerProxyHost: String,+ onStalkerProxyHostChange: (String) -> Unit,+ stalkerProxyPort: String,+ onStalkerProxyPortChange: (String) -> Unit,+ stalkerRequestRules: List<StalkerRequestRuleUiState>,+ onAddStalkerRequestRule: () -> Unit,+ onUpdateStalkerRequestRule: (Int, StalkerRequestRuleUiState) -> Unit,+ onRemoveStalkerRequestRule: (Int) -> Unit,+ fileImportError: String?,+ onFilePick: () -> Unit,+ onLoginXtream: () -> Unit,+ onLoginStalker: () -> Unit,+ onRepairStalker: () -> Unit,+ onAddM3u: () -> Unit,+ onLoginJellyfin: () -> Unit,+ quickConnectCode: String,+ onQuickConnectRequest: () -> Unit,+ onStartPhonePairing: () -> Unit,+ onStopPhonePairing: () -> Unit,+ onToggleM3uVodClassification: () -> Unit,+ onSelectEpgSyncMode: (ProviderEpgSyncMode) -> Unit,+ onSelectStalkerCatalogMode: (StalkerCatalogMode) -> Unit,+ onSelectStalkerProtocolPreference: (StalkerProtocolPreference) -> Unit,+ onSelectStalkerProfile: (String) -> Unit,+ onSelectXtreamLiveSyncMode: (ProviderXtreamLiveSyncMode) -> Unit,+ onSelectGuideSourcePolicy: (GuideSourcePolicy) -> Unit,+ onSelectChannelLogoSourcePolicy: (ChannelLogoSourcePolicy) -> Unit,+ modifier: Modifier = Modifier+) {+ val scrollState = rememberScrollState()+ val isTelevisionDevice = rememberIsTelevisionDevice()+ val advancedOptions = ProviderAdvancedOptions(+ sourceType = sourceType,+ uiState = uiState,+ httpUserAgent = httpUserAgent,+ onHttpUserAgentChange = onHttpUserAgentChange,+ httpHeaders = httpHeaders,+ onHttpHeadersChange = onHttpHeadersChange,+ onToggleM3uVodClassification = onToggleM3uVodClassification,+ onSelectEpgSyncMode = onSelectEpgSyncMode,+ onSelectStalkerCatalogMode = onSelectStalkerCatalogMode,+ onSelectXtreamLiveSyncMode = onSelectXtreamLiveSyncMode,+ onSelectGuideSourcePolicy = onSelectGuideSourcePolicy,+ onSelectChannelLogoSourcePolicy = onSelectChannelLogoSourcePolicy,+ username = username,+ onUsernameChange = onUsernameChange,+ password = password,+ onPasswordChange = onPasswordChange,+ stalkerAuthMode = stalkerAuthMode,+ onStalkerAuthModeChange = onStalkerAuthModeChange,+ stalkerMacAddress = stalkerMacAddress,+ stalkerDeviceProfile = stalkerDeviceProfile,+ onStalkerDeviceProfileChange = onStalkerDeviceProfileChange,+ stalkerDeviceTimezone = stalkerDeviceTimezone,+ onStalkerDeviceTimezoneChange = onStalkerDeviceTimezoneChange,+ stalkerDeviceLocale = stalkerDeviceLocale,+ onStalkerDeviceLocaleChange = onStalkerDeviceLocaleChange,+ stalkerSerialNumber = stalkerSerialNumber,+ onStalkerSerialNumberChange = onStalkerSerialNumberChange,+ stalkerDeviceId = stalkerDeviceId,+ onStalkerDeviceIdChange = onStalkerDeviceIdChange,+ stalkerDeviceId2 = stalkerDeviceId2,+ onStalkerDeviceId2Change = onStalkerDeviceId2Change,+ stalkerSignature = stalkerSignature,+ onStalkerSignatureChange = onStalkerSignatureChange,+ stalkerHwVersion = stalkerHwVersion,+ onStalkerHwVersionChange = onStalkerHwVersionChange,+ stalkerApiUserAgent = stalkerApiUserAgent,+ onStalkerApiUserAgentChange = onStalkerApiUserAgentChange,+ stalkerPlayerUserAgent = stalkerPlayerUserAgent,+ onStalkerPlayerUserAgentChange = onStalkerPlayerUserAgentChange,+ stalkerPlayerHeaders = stalkerPlayerHeaders,+ onStalkerPlayerHeadersChange = onStalkerPlayerHeadersChange,+ stalkerXUserAgentLink = stalkerXUserAgentLink,+ onStalkerXUserAgentLinkChange = onStalkerXUserAgentLinkChange,+ stalkerProxyEnabled = stalkerProxyEnabled,+ onStalkerProxyEnabledChange = onStalkerProxyEnabledChange,+ stalkerProxyHost = stalkerProxyHost,+ onStalkerProxyHostChange = onStalkerProxyHostChange,+ stalkerProxyPort = stalkerProxyPort,+ onStalkerProxyPortChange = onStalkerProxyPortChange,+ stalkerRequestRules = stalkerRequestRules,+ onAddStalkerRequestRule = onAddStalkerRequestRule,+ onUpdateStalkerRequestRule = onUpdateStalkerRequestRule,+ onRemoveStalkerRequestRule = onRemoveStalkerRequestRule+ )++ TvSurface(+ modifier = modifier,+ shape = RoundedCornerShape(20.dp),+ border = Border(+ border = BorderStroke(1.dp, SurfaceHighlight),+ shape = RoundedCornerShape(20.dp)+ ),+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated.copy(alpha = 0.95f))+ ) {+ Column(+ modifier = Modifier+ .fillMaxSize()+ .verticalScroll(scrollState)+ .imePadding()+ .padding(20.dp),+ verticalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ ProviderTextField(+ value = name,+ onValueChange = onNameChange,+ placeholder = stringResource(R.string.setup_name_hint)+ )+ if (!uiState.isEditing) {+ PhonePairingCard(+ pairingState = pairingState,+ onStart = onStartPhonePairing,+ onStop = onStopPhonePairing+ )+ }+ HorizontalDivider(color = SurfaceHighlight.copy(alpha = 0.6f))++ when (sourceType) {+ SourceType.XTREAM -> XtreamProviderForm(+ uiState = uiState,+ isTelevisionDevice = isTelevisionDevice,+ serverUrl = serverUrl,+ onServerUrlChange = onServerUrlChange,+ username = username,+ onUsernameChange = onUsernameChange,+ password = password,+ onPasswordChange = onPasswordChange,+ options = advancedOptions,+ onLogin = onLoginXtream+ )+ SourceType.STALKER -> StalkerProviderForm(+ uiState = uiState,+ isTelevisionDevice = isTelevisionDevice,+ serverUrl = serverUrl,+ onServerUrlChange = onServerUrlChange,+ stalkerMacAddress = stalkerMacAddress,+ onStalkerMacAddressChange = onStalkerMacAddressChange,+ stalkerAuthMode = stalkerAuthMode,+ options = advancedOptions,+ onLogin = onLoginStalker,+ onRepair = onRepairStalker,+ onSelectProtocol = onSelectStalkerProtocolPreference,+ onSelectProfile = onSelectStalkerProfile+ )+ SourceType.M3U_URL -> M3uProviderForm(+ uiState = uiState,+ m3uUrl = m3uUrl,+ onM3uUrlChange = onM3uUrlChange,+ fileImportError = fileImportError,+ isFile = false,+ onFilePick = onFilePick,+ options = advancedOptions,+ onAdd = onAddM3u+ )+ SourceType.M3U_FILE -> M3uProviderForm(+ uiState = uiState,+ m3uUrl = m3uUrl,+ onM3uUrlChange = onM3uUrlChange,+ fileImportError = fileImportError,+ isFile = true,+ onFilePick = onFilePick,+ options = advancedOptions,+ onAdd = onAddM3u+ )+ SourceType.JELLYFIN -> JellyfinProviderSetupForm(+ uiState = uiState,+ serverUrl = serverUrl,+ onServerUrlChange = onServerUrlChange,+ username = username,+ onUsernameChange = onUsernameChange,+ password = password,+ onPasswordChange = onPasswordChange,+ name = name,+ onNameChange = onNameChange,+ quickConnectCode = quickConnectCode,+ onQuickConnectRequest = onQuickConnectRequest,+ onLogin = onLoginJellyfin+ )+ }+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.ktindex 1c3a3435..504e4e38 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt@@ -85,8 +85,6 @@ import com.streamvault.app.ui.screens.settings.BackupImportPreviewDialogimport com.streamvault.app.ui.theme.*import com.streamvault.data.remote.stalker.StalkerAdvancedOptionsimport com.streamvault.data.remote.stalker.StalkerAdvancedOptionsCodec-import com.streamvault.data.remote.stalker.StalkerParamOverride-import com.streamvault.data.remote.stalker.StalkerRequestRuleimport com.streamvault.data.remote.stalker.StalkerCompatibilityRegistryimport com.streamvault.domain.model.StalkerCatalogModeimport com.streamvault.domain.model.StalkerCompatibilityProfileIds@@ -115,126 +113,6 @@ import kotlin.coroutines.resume// ??? Source type ?????????????????????????????????????????????????????????????-private enum class SourceType { XTREAM, STALKER, M3U_URL, M3U_FILE, JELLYFIN }--private data class StalkerRequestRuleUiState(- val action: String = "",- val blockRequest: Boolean = false,- val paramsText: String = ""-)--@Composable-private fun StalkerCompatibilitySelector(- protocol: StalkerProtocolPreference,- profileId: String,- onProtocolSelected: (StalkerProtocolPreference) -> Unit,- onProfileSelected: (String) -> Unit-) {- var showProtocols by rememberSaveable { mutableStateOf(false) }- var showProfiles by rememberSaveable { mutableStateOf(false) }- val selectedProfile = StalkerCompatibilityRegistry.find(profileId)-- Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {- Text("Compatibility", style = MaterialTheme.typography.titleSmall, color = OnBackground)- SmallActionButton(- text = "Protocol: ${protocol.name.replace('_', ' ')}",- onClick = { showProtocols = !showProtocols }- )- AnimatedVisibility(showProtocols) {- Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {- StalkerProtocolPreference.entries- .filterNot { it == StalkerProtocolPreference.MINISTRA_API_V3 }- .forEach { option ->- SmallActionButton(- text = if (option == protocol) "✓ ${option.name.replace('_', ' ')}" else option.name.replace('_', ' '),- onClick = {- onProtocolSelected(option)- onProfileSelected(StalkerCompatibilityProfileIds.AUTO)- showProtocols = false- }- )- }- }- }- SmallActionButton(- text = "Model: ${selectedProfile?.displayName ?: "Automatic"}",- onClick = { showProfiles = !showProfiles }- )- AnimatedVisibility(showProfiles) {- Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {- SmallActionButton(- text = if (profileId == StalkerCompatibilityProfileIds.AUTO) "✓ Automatic" else "Automatic",- onClick = {- onProfileSelected(StalkerCompatibilityProfileIds.AUTO)- showProfiles = false- }- )- val family = if (protocol == StalkerProtocolPreference.MINISTRA_API_V3) {- com.streamvault.domain.model.StalkerProtocolFamily.MINISTRA_API_V3- } else {- com.streamvault.domain.model.StalkerProtocolFamily.CLASSIC_MAG- }- StalkerCompatibilityRegistry.profiles- .filter { it.protocolFamily == family }- .groupBy { it.generation }- .forEach { (generation, profiles) ->- Text(generation, style = MaterialTheme.typography.labelMedium, color = OnBackground.copy(alpha = 0.72f))- profiles.forEach { option ->- val experimental = option.verification == StalkerProfileVerification.EXPERIMENTAL- SmallActionButton(- text = buildString {- if (option.id == profileId) append("✓ ")- append(option.displayName)- if (experimental) append(" — EXPERIMENTAL")- },- onClick = {- onProfileSelected(option.id)- showProfiles = false- }- )- }- }- if (family == com.streamvault.domain.model.StalkerProtocolFamily.CLASSIC_MAG) {- Text(- "Experimental profiles require captured/manual identity fields and are excluded from automatic discovery.",- style = MaterialTheme.typography.bodySmall,- color = AccentAmber- )- SmallActionButton(- text = if (profileId == StalkerCompatibilityProfileIds.CUSTOM) "✓ Custom profile" else "Custom profile",- onClick = {- onProfileSelected(StalkerCompatibilityProfileIds.CUSTOM)- showProfiles = false- }- )- }- }- }- }-}--private fun StalkerRequestRuleUiState.toRule(): StalkerRequestRule =- StalkerRequestRule(- action = action.trim(),- blockRequest = blockRequest,- paramOverrides = paramsText- .split('|', '\n')- .mapNotNull { entry ->- val trimmed = entry.trim()- if (trimmed.isBlank()) return@mapNotNull null- val separator = trimmed.indexOf('=').takeIf { it >= 0 } ?: trimmed.indexOf(':')- val name = if (separator >= 0) trimmed.substring(0, separator).trim() else trimmed- val value = if (separator >= 0) trimmed.substring(separator + 1).trim() else ""- name.takeIf { it.isNotBlank() }?.let { StalkerParamOverride(it, value) }- }- )--private fun StalkerRequestRule.toUiState(): StalkerRequestRuleUiState =- StalkerRequestRuleUiState(- action = action,- blockRequest = blockRequest,- paramsText = paramOverrides.joinToString(" | ") { "${it.name}=${it.value}" }- )// ??? Screen ??????????????????????????????????????????????????????????????????@@ -827,2824 +705,37 @@ uiState.stalkerTransportChallenge?.let { challenge ->}- @Composable- internal fun ProviderSetupCompletionLayer(- uiState: ProviderSetupState,- knownLocalM3uUrls: Set<String>,- selectedM3uUrl: String,- filesDir: java.io.File,- onProviderAdded: () -> Unit,- onAttachCreatedProvider: () -> Unit,- onSkipCreatedProviderCombinedAttach: () -> Unit,- cleanupImportedFiles: suspend (java.io.File, Set<String>, Int) -> Unit = ::cleanupOldImportedM3uFilesAsync- ) {- val context = LocalContext.current- val lifecycle = LocalLifecycleOwner.current.lifecycle- LaunchedEffect(uiState.onboardingCompletion, uiState.completionWarning, uiState.pendingCombinedAttachProfileId) {- if (- uiState.onboardingCompletion != ProviderSetupViewModel.OnboardingCompletion.NONE &&- uiState.pendingCombinedAttachProfileId == null- ) {- if (uiState.completionWarning != null) {- Toast.makeText(- context,- "Provider saved. Sync will resume in background.",- Toast.LENGTH_LONG- ).show()- }- val previousLocal = uiState.m3uUrl.takeIf { it.startsWith("file://") }- val selectedLocal = selectedM3uUrl.takeIf { it.startsWith("file://") }- val protectedUris = buildSet {- knownLocalM3uUrls.forEach { knownUri ->- if (knownUri != previousLocal || previousLocal == selectedLocal) add(knownUri)- }- selectedLocal?.let(::add)- }- cleanupImportedFiles(filesDir, protectedUris, 20)- lifecycle.awaitResumed()- onProviderAdded()- }- }-- if (uiState.pendingCombinedAttachProfileId != null) {- PremiumDialog(- title = "Add Playlist To Combined M3U?",- subtitle = "Add ${uiState.createdProviderName ?: "this playlist"} to " +- "${uiState.pendingCombinedAttachProfileName ?: "the active combined source"} " +- "and keep that combined source active for Live TV?",- onDismissRequest = onSkipCreatedProviderCombinedAttach,- content = {},- footer = {- PremiumDialogFooterButton(- label = "Not Now",- onClick = onSkipCreatedProviderCombinedAttach- )- PremiumDialogFooterButton(- label = "Add To Combined",- onClick = onAttachCreatedProvider,- emphasized = true- )- }- )- }- }// ??? Form content ?????????????????????????????????????????????????????????????-private suspend fun Lifecycle.awaitResumed() {- if (currentState.isAtLeast(Lifecycle.State.RESUMED)) return-- suspendCancellableCoroutine { continuation ->- lateinit var observer: LifecycleEventObserver- observer = LifecycleEventObserver { source, _ ->- if (source.lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) {- source.lifecycle.removeObserver(observer)- if (continuation.isActive) continuation.resume(Unit)- }- }- addObserver(observer)- continuation.invokeOnCancellation { removeObserver(observer) }- }-}--@Composable-private fun PhonePairingCard(- pairingState: ProviderQrPairingState,- onStart: () -> Unit,- onStop: () -> Unit-) {- val isActive = pairingState.status == ProviderQrPairingStatus.READY ||- pairingState.status == ProviderQrPairingStatus.RECEIVING- val message = pairingState.message ?: stringResource(R.string.setup_phone_pairing_body)-- Surface(- modifier = Modifier.fillMaxWidth(),- shape = RoundedCornerShape(16.dp),- colors = SurfaceDefaults.colors(containerColor = Surface.copy(alpha = 0.72f)),- border = Border(- border = BorderStroke(- 1.dp,- if (isActive) Primary.copy(alpha = 0.55f) else SurfaceHighlight- ),- shape = RoundedCornerShape(16.dp)- )- ) {- Column(- modifier = Modifier.padding(16.dp),- verticalArrangement = Arrangement.spacedBy(12.dp)- ) {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {- Text(- text = stringResource(R.string.setup_phone_pairing_title),- style = MaterialTheme.typography.titleMedium,- color = OnBackground- )- Text(- text = message,- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- StatusPill(- label = when (pairingState.status) {- ProviderQrPairingStatus.IDLE -> stringResource(R.string.setup_phone_pairing_idle)- ProviderQrPairingStatus.READY -> stringResource(R.string.setup_phone_pairing_ready)- ProviderQrPairingStatus.RECEIVING -> stringResource(R.string.setup_phone_pairing_receiving)- ProviderQrPairingStatus.COMPLETE -> stringResource(R.string.setup_phone_pairing_complete)- ProviderQrPairingStatus.ERROR -> stringResource(R.string.setup_phone_pairing_error)- },- containerColor = if (pairingState.status == ProviderQrPairingStatus.ERROR) {- ErrorColor.copy(alpha = 0.35f)- } else {- PrimaryGlow- }- )- }-- pairingState.qrBitmap?.let { bitmap ->- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.spacedBy(16.dp),- verticalAlignment = Alignment.CenterVertically- ) {- Image(- bitmap = bitmap.asImageBitmap(),- contentDescription = stringResource(R.string.setup_phone_pairing_qr_description),- modifier = Modifier- .size(156.dp)- .background(Color.White, RoundedCornerShape(12.dp))- .padding(8.dp)- )- Column(- modifier = Modifier.weight(1f),- verticalArrangement = Arrangement.spacedBy(8.dp)- ) {- Text(- text = stringResource(R.string.setup_phone_pairing_same_wifi),- style = MaterialTheme.typography.bodyMedium,- color = OnBackground- )- pairingState.url?.let { url ->- Text(- text = url,- style = MaterialTheme.typography.bodySmall,- color = Primary,- maxLines = 3- )- }- }- }- }-- Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {- Box(modifier = Modifier.weight(1f)) {- SmallActionButton(- text = if (isActive) {- stringResource(R.string.setup_phone_pairing_restart)- } else {- stringResource(R.string.setup_phone_pairing_start)- },- onClick = onStart- )- }- if (isActive) {- Box(modifier = Modifier.weight(1f)) {- SmallActionButton(- text = stringResource(R.string.setup_phone_pairing_stop),- onClick = onStop- )- }- }- }- }- }-}--@OptIn(ExperimentalLayoutApi::class)-@Composable-private fun ProviderFormContent(- sourceType: SourceType,- uiState: ProviderSetupState,- pairingState: ProviderQrPairingState,- name: String, onNameChange: (String) -> Unit,- serverUrl: String, onServerUrlChange: (String) -> Unit,- username: String, onUsernameChange: (String) -> Unit,- password: String, onPasswordChange: (String) -> Unit,- m3uUrl: String, onM3uUrlChange: (String) -> Unit,- httpUserAgent: String, onHttpUserAgentChange: (String) -> Unit,- httpHeaders: String, onHttpHeadersChange: (String) -> Unit,- stalkerMacAddress: String, onStalkerMacAddressChange: (String) -> Unit,- stalkerAuthMode: StalkerAuthMode, onStalkerAuthModeChange: (StalkerAuthMode) -> Unit,- stalkerDeviceProfile: String, onStalkerDeviceProfileChange: (String) -> Unit,- stalkerDeviceTimezone: String, onStalkerDeviceTimezoneChange: (String) -> Unit,- stalkerDeviceLocale: String, onStalkerDeviceLocaleChange: (String) -> Unit,- stalkerSerialNumber: String, onStalkerSerialNumberChange: (String) -> Unit,- stalkerDeviceId: String, onStalkerDeviceIdChange: (String) -> Unit,- stalkerDeviceId2: String, onStalkerDeviceId2Change: (String) -> Unit,- stalkerSignature: String, onStalkerSignatureChange: (String) -> Unit,- stalkerHwVersion: String, onStalkerHwVersionChange: (String) -> Unit,- stalkerApiUserAgent: String, onStalkerApiUserAgentChange: (String) -> Unit,- stalkerPlayerUserAgent: String, onStalkerPlayerUserAgentChange: (String) -> Unit,- stalkerPlayerHeaders: String, onStalkerPlayerHeadersChange: (String) -> Unit,- stalkerXUserAgentLink: String, onStalkerXUserAgentLinkChange: (String) -> Unit,- stalkerProxyEnabled: Boolean, onStalkerProxyEnabledChange: (Boolean) -> Unit,- stalkerProxyHost: String, onStalkerProxyHostChange: (String) -> Unit,- stalkerProxyPort: String, onStalkerProxyPortChange: (String) -> Unit,- stalkerRequestRules: List<StalkerRequestRuleUiState>,- onAddStalkerRequestRule: () -> Unit,- onUpdateStalkerRequestRule: (Int, StalkerRequestRuleUiState) -> Unit,- onRemoveStalkerRequestRule: (Int) -> Unit,- fileImportError: String?,- onFilePick: () -> Unit,- onLoginXtream: () -> Unit,- onLoginStalker: () -> Unit,- onRepairStalker: () -> Unit,- onAddM3u: () -> Unit,- onLoginJellyfin: () -> Unit,- quickConnectCode: String,- onQuickConnectRequest: () -> Unit,- onStartPhonePairing: () -> Unit,- onStopPhonePairing: () -> Unit,- onToggleM3uVodClassification: () -> Unit,- onSelectEpgSyncMode: (ProviderEpgSyncMode) -> Unit,- onSelectStalkerCatalogMode: (StalkerCatalogMode) -> Unit,- onSelectStalkerProtocolPreference: (StalkerProtocolPreference) -> Unit,- onSelectStalkerProfile: (String) -> Unit,- onSelectXtreamLiveSyncMode: (ProviderXtreamLiveSyncMode) -> Unit,- onSelectGuideSourcePolicy: (GuideSourcePolicy) -> Unit,- onSelectChannelLogoSourcePolicy: (ChannelLogoSourcePolicy) -> Unit,- modifier: Modifier = Modifier-) {- val scrollState = rememberScrollState()- val isTelevisionDevice = rememberIsTelevisionDevice()-- Surface(- modifier = modifier,- shape = RoundedCornerShape(20.dp),- border = Border(border = BorderStroke(1.dp, SurfaceHighlight), shape = RoundedCornerShape(20.dp)),- colors = SurfaceDefaults.colors(containerColor = SurfaceElevated.copy(alpha = 0.95f))- ) {- Column(- modifier = Modifier- .fillMaxSize()- .verticalScroll(scrollState)- .imePadding()- .padding(20.dp),- verticalArrangement = Arrangement.spacedBy(12.dp)- ) {- // Playlist name ן¿½ always shown- ProviderTextField(- value = name,- onValueChange = onNameChange,- placeholder = androidx.compose.ui.res.stringResource(R.string.setup_name_hint)- )-- if (!uiState.isEditing) {- PhonePairingCard(- pairingState = pairingState,- onStart = onStartPhonePairing,- onStop = onStopPhonePairing- )- }-- HorizontalDivider(color = SurfaceHighlight.copy(alpha = 0.6f))-- when (sourceType) {- SourceType.XTREAM -> {- ProviderTextField(- value = serverUrl, onValueChange = onServerUrlChange,- placeholder = androidx.compose.ui.res.stringResource(R.string.setup_server_hint),- keyboardOptions = KeyboardOptions(- capitalization = KeyboardCapitalization.None,- autoCorrectEnabled = false,- keyboardType = if (isTelevisionDevice) KeyboardType.Ascii else KeyboardType.Uri,- imeAction = ImeAction.Next- )- )- ProviderTextField(- value = username, onValueChange = onUsernameChange,- placeholder = androidx.compose.ui.res.stringResource(R.string.setup_user_hint),- keyboardOptions = KeyboardOptions(- capitalization = KeyboardCapitalization.None,- autoCorrectEnabled = false,- keyboardType = KeyboardType.Ascii,- imeAction = ImeAction.Next- )- )- ProviderTextField(- value = password, onValueChange = onPasswordChange,- placeholder = androidx.compose.ui.res.stringResource(R.string.setup_pass_hint),- isPassword = true,- keyboardOptions = KeyboardOptions(- capitalization = KeyboardCapitalization.None,- autoCorrectEnabled = false,- keyboardType = if (isTelevisionDevice) KeyboardType.Ascii else KeyboardType.Password,- imeAction = ImeAction.Done- )- )- AdvancedProviderOptionsSection(- sourceType = sourceType,- uiState = uiState,- httpUserAgent = httpUserAgent,- onHttpUserAgentChange = onHttpUserAgentChange,- httpHeaders = httpHeaders,- onHttpHeadersChange = onHttpHeadersChange,- onToggleM3uVodClassification = onToggleM3uVodClassification,- onSelectEpgSyncMode = onSelectEpgSyncMode,- onSelectStalkerCatalogMode = onSelectStalkerCatalogMode,- onSelectXtreamLiveSyncMode = onSelectXtreamLiveSyncMode,- onSelectGuideSourcePolicy = onSelectGuideSourcePolicy,- onSelectChannelLogoSourcePolicy = onSelectChannelLogoSourcePolicy,- username = username,- onUsernameChange = onUsernameChange,- password = password,- onPasswordChange = onPasswordChange,- stalkerAuthMode = stalkerAuthMode,- onStalkerAuthModeChange = onStalkerAuthModeChange,- stalkerMacAddress = stalkerMacAddress,- stalkerDeviceProfile = stalkerDeviceProfile,- onStalkerDeviceProfileChange = onStalkerDeviceProfileChange,- stalkerDeviceTimezone = stalkerDeviceTimezone,- onStalkerDeviceTimezoneChange = onStalkerDeviceTimezoneChange,- stalkerDeviceLocale = stalkerDeviceLocale,- onStalkerDeviceLocaleChange = onStalkerDeviceLocaleChange,- stalkerSerialNumber = stalkerSerialNumber,- onStalkerSerialNumberChange = onStalkerSerialNumberChange,- stalkerDeviceId = stalkerDeviceId,- onStalkerDeviceIdChange = onStalkerDeviceIdChange,- stalkerDeviceId2 = stalkerDeviceId2,- onStalkerDeviceId2Change = onStalkerDeviceId2Change,- stalkerSignature = stalkerSignature,- onStalkerSignatureChange = onStalkerSignatureChange,- stalkerHwVersion = stalkerHwVersion,- onStalkerHwVersionChange = onStalkerHwVersionChange,- stalkerApiUserAgent = stalkerApiUserAgent,- onStalkerApiUserAgentChange = onStalkerApiUserAgentChange,- stalkerPlayerUserAgent = stalkerPlayerUserAgent,- onStalkerPlayerUserAgentChange = onStalkerPlayerUserAgentChange,- stalkerPlayerHeaders = stalkerPlayerHeaders,- onStalkerPlayerHeadersChange = onStalkerPlayerHeadersChange,- stalkerXUserAgentLink = stalkerXUserAgentLink,- onStalkerXUserAgentLinkChange = onStalkerXUserAgentLinkChange,- stalkerProxyEnabled = stalkerProxyEnabled,- onStalkerProxyEnabledChange = onStalkerProxyEnabledChange,- stalkerProxyHost = stalkerProxyHost,- onStalkerProxyHostChange = onStalkerProxyHostChange,- stalkerProxyPort = stalkerProxyPort,- onStalkerProxyPortChange = onStalkerProxyPortChange,- stalkerRequestRules = stalkerRequestRules,- onAddStalkerRequestRule = onAddStalkerRequestRule,- onUpdateStalkerRequestRule = onUpdateStalkerRequestRule,- onRemoveStalkerRequestRule = onRemoveStalkerRequestRule- )- FormErrors(uiState.validationError, uiState.error)- ActionButton(- text = when {- uiState.isLoading -> androidx.compose.ui.res.stringResource(R.string.setup_connecting)- uiState.isEditing -> androidx.compose.ui.res.stringResource(R.string.setup_save)- else -> androidx.compose.ui.res.stringResource(R.string.setup_login)- },- isLoading = uiState.isLoading,- onClick = onLoginXtream- )- }-- SourceType.STALKER -> {- ProviderTextField(- value = serverUrl, onValueChange = onServerUrlChange,- placeholder = "Portal URL",- keyboardOptions = KeyboardOptions(- capitalization = KeyboardCapitalization.None,- autoCorrectEnabled = false,- keyboardType = if (isTelevisionDevice) KeyboardType.Ascii else KeyboardType.Uri,- imeAction = ImeAction.Next- )- )- ProviderTextField(- value = stalkerMacAddress, onValueChange = onStalkerMacAddressChange,- placeholder = if (stalkerAuthMode == StalkerAuthMode.CREDENTIALS_ONLY) {- "MAC address (optional)"- } else {- "MAC address"- },- keyboardOptions = KeyboardOptions(- capitalization = KeyboardCapitalization.Characters,- autoCorrectEnabled = false,- keyboardType = KeyboardType.Ascii,- imeAction = ImeAction.Next- )- )- StalkerCompatibilitySelector(- protocol = uiState.stalkerProtocolPreference,- profileId = uiState.stalkerRequestedProfileId,- onProtocolSelected = onSelectStalkerProtocolPreference,- onProfileSelected = onSelectStalkerProfile- )- AdvancedProviderOptionsSection(- sourceType = sourceType,- uiState = uiState,- httpUserAgent = httpUserAgent,- onHttpUserAgentChange = onHttpUserAgentChange,- httpHeaders = httpHeaders,- onHttpHeadersChange = onHttpHeadersChange,- onToggleM3uVodClassification = onToggleM3uVodClassification,- onSelectEpgSyncMode = onSelectEpgSyncMode,- onSelectStalkerCatalogMode = onSelectStalkerCatalogMode,- onSelectXtreamLiveSyncMode = onSelectXtreamLiveSyncMode,- onSelectGuideSourcePolicy = onSelectGuideSourcePolicy,- onSelectChannelLogoSourcePolicy = onSelectChannelLogoSourcePolicy,- username = username,- onUsernameChange = onUsernameChange,- password = password,- onPasswordChange = onPasswordChange,- stalkerAuthMode = stalkerAuthMode,- onStalkerAuthModeChange = onStalkerAuthModeChange,- stalkerMacAddress = stalkerMacAddress,- stalkerDeviceProfile = stalkerDeviceProfile,- onStalkerDeviceProfileChange = onStalkerDeviceProfileChange,- stalkerDeviceTimezone = stalkerDeviceTimezone,- onStalkerDeviceTimezoneChange = onStalkerDeviceTimezoneChange,- stalkerDeviceLocale = stalkerDeviceLocale,- onStalkerDeviceLocaleChange = onStalkerDeviceLocaleChange,- stalkerSerialNumber = stalkerSerialNumber,- onStalkerSerialNumberChange = onStalkerSerialNumberChange,- stalkerDeviceId = stalkerDeviceId,- onStalkerDeviceIdChange = onStalkerDeviceIdChange,- stalkerDeviceId2 = stalkerDeviceId2,- onStalkerDeviceId2Change = onStalkerDeviceId2Change,- stalkerSignature = stalkerSignature,- onStalkerSignatureChange = onStalkerSignatureChange,- stalkerHwVersion = stalkerHwVersion,- onStalkerHwVersionChange = onStalkerHwVersionChange,- stalkerApiUserAgent = stalkerApiUserAgent,- onStalkerApiUserAgentChange = onStalkerApiUserAgentChange,- stalkerPlayerUserAgent = stalkerPlayerUserAgent,- onStalkerPlayerUserAgentChange = onStalkerPlayerUserAgentChange,- stalkerPlayerHeaders = stalkerPlayerHeaders,- onStalkerPlayerHeadersChange = onStalkerPlayerHeadersChange,- stalkerXUserAgentLink = stalkerXUserAgentLink,- onStalkerXUserAgentLinkChange = onStalkerXUserAgentLinkChange,- stalkerProxyEnabled = stalkerProxyEnabled,- onStalkerProxyEnabledChange = onStalkerProxyEnabledChange,- stalkerProxyHost = stalkerProxyHost,- onStalkerProxyHostChange = onStalkerProxyHostChange,- stalkerProxyPort = stalkerProxyPort,- onStalkerProxyPortChange = onStalkerProxyPortChange,- stalkerRequestRules = stalkerRequestRules,- onAddStalkerRequestRule = onAddStalkerRequestRule,- onUpdateStalkerRequestRule = onUpdateStalkerRequestRule,- onRemoveStalkerRequestRule = onRemoveStalkerRequestRule- )- FormErrors(uiState.validationError, uiState.error)- ActionButton(- text = when {- uiState.isLoading -> androidx.compose.ui.res.stringResource(R.string.setup_connecting)- uiState.isEditing -> androidx.compose.ui.res.stringResource(R.string.setup_save)- else -> androidx.compose.ui.res.stringResource(R.string.setup_login)- },- isLoading = uiState.isLoading,- onClick = onLoginStalker- )- if (uiState.isEditing) {- SmallActionButton(- text = androidx.compose.ui.res.stringResource(R.string.stalker_repair_connection),- isLoading = uiState.isLoading,- onClick = onRepairStalker- )- }- }-- SourceType.M3U_URL -> {- ProviderTextField(- value = m3uUrl, onValueChange = onM3uUrlChange,- placeholder = androidx.compose.ui.res.stringResource(R.string.setup_m3u_hint),- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Done)- )- AdvancedProviderOptionsSection(- sourceType = sourceType,- uiState = uiState,- httpUserAgent = httpUserAgent,- onHttpUserAgentChange = onHttpUserAgentChange,- httpHeaders = httpHeaders,- onHttpHeadersChange = onHttpHeadersChange,- onToggleM3uVodClassification = onToggleM3uVodClassification,- onSelectEpgSyncMode = onSelectEpgSyncMode,- onSelectStalkerCatalogMode = onSelectStalkerCatalogMode,- onSelectXtreamLiveSyncMode = onSelectXtreamLiveSyncMode,- onSelectGuideSourcePolicy = onSelectGuideSourcePolicy,- onSelectChannelLogoSourcePolicy = onSelectChannelLogoSourcePolicy,- username = username,- onUsernameChange = onUsernameChange,- password = password,- onPasswordChange = onPasswordChange,- stalkerAuthMode = stalkerAuthMode,- onStalkerAuthModeChange = onStalkerAuthModeChange,- stalkerMacAddress = stalkerMacAddress,- stalkerDeviceProfile = stalkerDeviceProfile,- onStalkerDeviceProfileChange = onStalkerDeviceProfileChange,- stalkerDeviceTimezone = stalkerDeviceTimezone,- onStalkerDeviceTimezoneChange = onStalkerDeviceTimezoneChange,- stalkerDeviceLocale = stalkerDeviceLocale,- onStalkerDeviceLocaleChange = onStalkerDeviceLocaleChange,- stalkerSerialNumber = stalkerSerialNumber,- onStalkerSerialNumberChange = onStalkerSerialNumberChange,- stalkerDeviceId = stalkerDeviceId,- onStalkerDeviceIdChange = onStalkerDeviceIdChange,- stalkerDeviceId2 = stalkerDeviceId2,- onStalkerDeviceId2Change = onStalkerDeviceId2Change,- stalkerSignature = stalkerSignature,- onStalkerSignatureChange = onStalkerSignatureChange- )- FormErrors(uiState.validationError, uiState.error)- ActionButton(- text = when {- uiState.isLoading -> androidx.compose.ui.res.stringResource(R.string.setup_validating)- uiState.isEditing -> androidx.compose.ui.res.stringResource(R.string.setup_save)- else -> androidx.compose.ui.res.stringResource(R.string.setup_add)- },- isLoading = uiState.isLoading,- onClick = onAddM3u- )- }-- SourceType.M3U_FILE -> {- FileSelectorCard(- fileName = if (m3uUrl.startsWith("file://")) m3uUrl.substringAfterLast("/") else null,- fileSelectedHint = androidx.compose.ui.res.stringResource(R.string.setup_file_replace_hint),- emptySelectionTitle = androidx.compose.ui.res.stringResource(R.string.setup_file_select_title),- emptySelectionHint = androidx.compose.ui.res.stringResource(R.string.setup_file_browse_hint),- onClick = onFilePick- )- fileImportError?.let {- Text(text = it, style = MaterialTheme.typography.bodyMedium, color = ErrorColor)- }- AdvancedProviderOptionsSection(- sourceType = sourceType,- uiState = uiState,- httpUserAgent = httpUserAgent,- onHttpUserAgentChange = onHttpUserAgentChange,- httpHeaders = httpHeaders,- onHttpHeadersChange = onHttpHeadersChange,- onToggleM3uVodClassification = onToggleM3uVodClassification,- onSelectEpgSyncMode = onSelectEpgSyncMode,- onSelectStalkerCatalogMode = onSelectStalkerCatalogMode,- onSelectXtreamLiveSyncMode = onSelectXtreamLiveSyncMode,- onSelectGuideSourcePolicy = onSelectGuideSourcePolicy,- onSelectChannelLogoSourcePolicy = onSelectChannelLogoSourcePolicy,- username = username,- onUsernameChange = onUsernameChange,- password = password,- onPasswordChange = onPasswordChange,- stalkerAuthMode = stalkerAuthMode,- onStalkerAuthModeChange = onStalkerAuthModeChange,- stalkerMacAddress = stalkerMacAddress,- stalkerDeviceProfile = stalkerDeviceProfile,- onStalkerDeviceProfileChange = onStalkerDeviceProfileChange,- stalkerDeviceTimezone = stalkerDeviceTimezone,- onStalkerDeviceTimezoneChange = onStalkerDeviceTimezoneChange,- stalkerDeviceLocale = stalkerDeviceLocale,- onStalkerDeviceLocaleChange = onStalkerDeviceLocaleChange,- stalkerSerialNumber = stalkerSerialNumber,- onStalkerSerialNumberChange = onStalkerSerialNumberChange,- stalkerDeviceId = stalkerDeviceId,- onStalkerDeviceIdChange = onStalkerDeviceIdChange,- stalkerDeviceId2 = stalkerDeviceId2,- onStalkerDeviceId2Change = onStalkerDeviceId2Change,- stalkerSignature = stalkerSignature,- onStalkerSignatureChange = onStalkerSignatureChange- )- FormErrors(uiState.validationError, uiState.error)- ActionButton(- text = when {- uiState.isLoading -> androidx.compose.ui.res.stringResource(R.string.setup_validating)- uiState.isEditing -> androidx.compose.ui.res.stringResource(R.string.setup_save)- else -> androidx.compose.ui.res.stringResource(R.string.setup_add)- },- isLoading = uiState.isLoading,- onClick = onAddM3u- )- }-- SourceType.JELLYFIN -> {- JellyfinProviderForm(- serverUrl = serverUrl,- onServerUrlChange = onServerUrlChange,- username = username,- onUsernameChange = onUsernameChange,- password = password,- onPasswordChange = onPasswordChange,- name = name,- onNameChange = onNameChange,- quickConnectCode = quickConnectCode,- onQuickConnectRequest = onQuickConnectRequest,- isEditing = uiState.isEditing- )- FormErrors(uiState.validationError, uiState.error)- ActionButton(- text = when {- uiState.isLoading -> stringResource(R.string.setup_validating)- uiState.isEditing -> stringResource(R.string.setup_save)- else -> stringResource(R.string.setup_add)- },- isLoading = uiState.isLoading,- onClick = onLoginJellyfin- )- }- }- }- }-}--@Composable-private fun AdvancedProviderOptionsSection(- sourceType: SourceType,- uiState: ProviderSetupState,- httpUserAgent: String,- onHttpUserAgentChange: (String) -> Unit,- httpHeaders: String,- onHttpHeadersChange: (String) -> Unit,- onToggleM3uVodClassification: () -> Unit,- onSelectEpgSyncMode: (ProviderEpgSyncMode) -> Unit,- onSelectStalkerCatalogMode: (StalkerCatalogMode) -> Unit,- onSelectXtreamLiveSyncMode: (ProviderXtreamLiveSyncMode) -> Unit,- onSelectGuideSourcePolicy: (GuideSourcePolicy) -> Unit,- onSelectChannelLogoSourcePolicy: (ChannelLogoSourcePolicy) -> Unit,- username: String,- onUsernameChange: (String) -> Unit,- password: String,- onPasswordChange: (String) -> Unit,- stalkerAuthMode: StalkerAuthMode,- onStalkerAuthModeChange: (StalkerAuthMode) -> Unit,- stalkerMacAddress: String,- stalkerDeviceProfile: String,- onStalkerDeviceProfileChange: (String) -> Unit,- stalkerDeviceTimezone: String,- onStalkerDeviceTimezoneChange: (String) -> Unit,- stalkerDeviceLocale: String,- onStalkerDeviceLocaleChange: (String) -> Unit,- stalkerSerialNumber: String,- onStalkerSerialNumberChange: (String) -> Unit,- stalkerDeviceId: String,- onStalkerDeviceIdChange: (String) -> Unit,- stalkerDeviceId2: String,- onStalkerDeviceId2Change: (String) -> Unit,- stalkerSignature: String,- onStalkerSignatureChange: (String) -> Unit,- stalkerHwVersion: String = "",- onStalkerHwVersionChange: (String) -> Unit = {},- stalkerApiUserAgent: String = "",- onStalkerApiUserAgentChange: (String) -> Unit = {},- stalkerPlayerUserAgent: String = "",- onStalkerPlayerUserAgentChange: (String) -> Unit = {},- stalkerPlayerHeaders: String = "",- onStalkerPlayerHeadersChange: (String) -> Unit = {},- stalkerXUserAgentLink: String = StalkerAdvancedOptions.LINK_ETHERNET,- onStalkerXUserAgentLinkChange: (String) -> Unit = {},- stalkerProxyEnabled: Boolean = false,- onStalkerProxyEnabledChange: (Boolean) -> Unit = {},- stalkerProxyHost: String = "",- onStalkerProxyHostChange: (String) -> Unit = {},- stalkerProxyPort: String = "",- onStalkerProxyPortChange: (String) -> Unit = {},- stalkerRequestRules: List<StalkerRequestRuleUiState> = emptyList(),- onAddStalkerRequestRule: () -> Unit = {},- onUpdateStalkerRequestRule: (Int, StalkerRequestRuleUiState) -> Unit = { _, _ -> },- onRemoveStalkerRequestRule: (Int) -> Unit = {}-) {- var showAdvancedOptions by rememberSaveable(sourceType) { mutableStateOf(false) }- val defaultEpgSyncMode = when (sourceType) {- SourceType.STALKER -> ProviderEpgSyncMode.BACKGROUND- SourceType.XTREAM,- SourceType.M3U_URL,- SourceType.M3U_FILE,- SourceType.JELLYFIN -> ProviderEpgSyncMode.UPFRONT- }- LaunchedEffect(uiState.isEditing, uiState.epgSyncMode, uiState.stalkerCatalogMode, uiState.xtreamLiveSyncMode, uiState.guideSourcePolicy, uiState.channelLogoSourcePolicy, sourceType) {- val hasNonDefaultSelection = ((sourceType == SourceType.XTREAM || sourceType == SourceType.STALKER) && uiState.epgSyncMode != defaultEpgSyncMode) ||- (sourceType == SourceType.STALKER && uiState.stalkerCatalogMode != StalkerCatalogMode.ON_DEMAND) ||- (sourceType == SourceType.XTREAM && uiState.xtreamLiveSyncMode != ProviderXtreamLiveSyncMode.AUTO) ||- (supportsGuideAndLogoPolicy(sourceType) && uiState.guideSourcePolicy != GuideSourcePolicy.AUTO) ||- (supportsGuideAndLogoPolicy(sourceType) && uiState.channelLogoSourcePolicy != ChannelLogoSourcePolicy.SUPPLIER_PREFERRED) ||- ((sourceType == SourceType.M3U_URL || sourceType == SourceType.M3U_FILE) && !uiState.m3uVodClassificationEnabled) ||- ((sourceType == SourceType.XTREAM || sourceType == SourceType.M3U_URL || sourceType == SourceType.M3U_FILE) &&- httpUserAgent.isNotBlank()) ||- ((sourceType == SourceType.XTREAM || sourceType == SourceType.STALKER || sourceType == SourceType.M3U_URL || sourceType == SourceType.M3U_FILE) &&- httpHeaders.isNotBlank()) ||- (sourceType == SourceType.STALKER && (- stalkerAuthMode != StalkerAuthMode.AUTO ||- username.isNotBlank() ||- password.isNotBlank() ||- stalkerMacAddress.isBlank() ||- stalkerDeviceProfile.isNotBlank() ||- stalkerDeviceTimezone.isNotBlank() ||- stalkerDeviceLocale.isNotBlank() ||- stalkerSerialNumber.isNotBlank() ||- stalkerDeviceId.isNotBlank() ||- stalkerDeviceId2.isNotBlank() ||- stalkerSignature.isNotBlank() ||- stalkerHwVersion.isNotBlank() ||- stalkerApiUserAgent.isNotBlank() ||- stalkerPlayerUserAgent.isNotBlank() ||- stalkerPlayerHeaders.isNotBlank() ||- stalkerXUserAgentLink != StalkerAdvancedOptions.LINK_ETHERNET ||- stalkerProxyEnabled ||- stalkerProxyHost.isNotBlank() ||- stalkerProxyPort.isNotBlank() ||- stalkerRequestRules.isNotEmpty()- ))- if (uiState.isEditing && hasNonDefaultSelection) {- showAdvancedOptions = true- }- }- Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {- Surface(- onClick = { showAdvancedOptions = !showAdvancedOptions },- modifier = Modifier- .fillMaxWidth()- .mouseClickable(onClick = { showAdvancedOptions = !showAdvancedOptions }),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (showAdvancedOptions) Primary.copy(alpha = 0.12f) else Surface,- focusedContainerColor = Primary.copy(alpha = 0.24f)- ),- border = ClickableSurfaceDefaults.border(- border = Border(- BorderStroke(- 1.dp,- if (showAdvancedOptions) Primary.copy(alpha = 0.45f) else SurfaceHighlight- )- ),- focusedBorder = Border(BorderStroke(3.dp, PrimaryLight))- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Row(- modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Column(- modifier = Modifier.weight(1f),- verticalArrangement = Arrangement.spacedBy(4.dp)- ) {- Text(- text = androidx.compose.ui.res.stringResource(R.string.setup_advanced_options_label),- style = MaterialTheme.typography.titleSmall,- color = TextPrimary- )- Text(- text = androidx.compose.ui.res.stringResource(R.string.setup_advanced_options_helper),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- Text(- text = if (showAdvancedOptions) {- androidx.compose.ui.res.stringResource(R.string.setup_advanced_options_hide)- } else {- androidx.compose.ui.res.stringResource(R.string.setup_advanced_options_show)- },- style = MaterialTheme.typography.labelMedium,- color = PrimaryLight- )- }- }- AnimatedVisibility(visible = showAdvancedOptions) {- Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {- if (sourceType == SourceType.M3U_URL || sourceType == SourceType.M3U_FILE) {- Surface(- onClick = onToggleM3uVodClassification,- modifier = Modifier- .fillMaxWidth()- .mouseClickable(onClick = onToggleM3uVodClassification),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (uiState.m3uVodClassificationEnabled) Primary.copy(alpha = 0.1f) else Surface,- focusedContainerColor = Primary.copy(alpha = 0.22f)- ),- border = ClickableSurfaceDefaults.border(- border = Border(- BorderStroke(- 1.dp,- if (uiState.m3uVodClassificationEnabled) Primary.copy(alpha = 0.4f) else SurfaceHighlight- )- ),- focusedBorder = Border(BorderStroke(3.dp, PrimaryLight))- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Row(- modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),- horizontalArrangement = Arrangement.spacedBy(12.dp),- verticalAlignment = Alignment.CenterVertically- ) {- Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {- Text(- text = androidx.compose.ui.res.stringResource(R.string.setup_m3u_vod_classification_label),- style = MaterialTheme.typography.titleSmall,- color = TextPrimary- )- Text(- text = androidx.compose.ui.res.stringResource(R.string.setup_m3u_vod_classification_helper),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- Switch(- checked = uiState.m3uVodClassificationEnabled,- onCheckedChange = { onToggleM3uVodClassification() }- )- }- }- }- if (sourceType == SourceType.XTREAM || sourceType == SourceType.M3U_URL || sourceType == SourceType.M3U_FILE) {- ProviderTextField(- value = httpUserAgent,- onValueChange = onHttpUserAgentChange,- placeholder = "User-Agent override (optional)",- keyboardOptions = KeyboardOptions(- capitalization = KeyboardCapitalization.None,- autoCorrectEnabled = false,- keyboardType = KeyboardType.Ascii,- imeAction = ImeAction.Next- )- )- }- if (sourceType == SourceType.XTREAM || sourceType == SourceType.STALKER || sourceType == SourceType.M3U_URL || sourceType == SourceType.M3U_FILE) {- ProviderTextField(- value = httpHeaders,- onValueChange = onHttpHeadersChange,- placeholder = if (sourceType == SourceType.STALKER) {- "Headers (API, optional, Header: Value | HeaderToRemove:)"- } else {- "Custom headers (optional, Header: Value | Header2: Value)"- },- keyboardOptions = KeyboardOptions(- capitalization = KeyboardCapitalization.None,- autoCorrectEnabled = false,- keyboardType = KeyboardType.Ascii,- imeAction = ImeAction.Next- )- )- }- if (supportsGuideAndLogoPolicy(sourceType)) {- if (sourceType == SourceType.XTREAM) {- Column(- modifier = Modifier- .fillMaxWidth()- .background(Surface, RoundedCornerShape(12.dp))- .border(1.dp, SurfaceHighlight, RoundedCornerShape(12.dp))- .padding(horizontal = 16.dp, vertical = 12.dp),- verticalArrangement = Arrangement.spacedBy(10.dp)- ) {- Text(- text = androidx.compose.ui.res.stringResource(R.string.setup_xtream_live_sync_mode_label),- style = MaterialTheme.typography.titleSmall,- color = TextPrimary- )- Text(- text = androidx.compose.ui.res.stringResource(R.string.setup_xtream_live_sync_mode_helper),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- ProviderXtreamLiveSyncMode.entries.forEach { mode ->- XtreamLiveSyncModeOptionRow(- mode = mode,- selected = uiState.xtreamLiveSyncMode == mode,- onSelect = { onSelectXtreamLiveSyncMode(mode) }- )- }- }- }+// ??? Source type selector ׳ֲ¿ֲ½ wide layout (left sidebar) ????????????????????????- Column(- modifier = Modifier- .fillMaxWidth()- .background(Surface, RoundedCornerShape(12.dp))- .border(1.dp, SurfaceHighlight, RoundedCornerShape(12.dp))- .padding(horizontal = 16.dp, vertical = 12.dp),- verticalArrangement = Arrangement.spacedBy(10.dp)- ) {- Text(- text = "Guide source",- style = MaterialTheme.typography.titleSmall,- color = TextPrimary- )- Text(- text = "Choose whether this provider uses its supplier guide, your assigned external XMLTV sources, or no guide at all.",- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- GuideSourcePolicy.entries.forEach { policy ->- GuideSourcePolicyOptionRow(- policy = policy,- selected = uiState.guideSourcePolicy == policy,- onSelect = { onSelectGuideSourcePolicy(policy) }- )- }- }- Column(- modifier = Modifier- .fillMaxWidth()- .background(Surface, RoundedCornerShape(12.dp))- .border(1.dp, SurfaceHighlight, RoundedCornerShape(12.dp))- .padding(horizontal = 16.dp, vertical = 12.dp),- verticalArrangement = Arrangement.spacedBy(10.dp)- ) {- Text(- text = "Channel logos",- style = MaterialTheme.typography.titleSmall,- color = TextPrimary- )- Text(- text = "Pick whether channel logos come from the supplier, the matched EPG channel icon, or a strict single source.",- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- ChannelLogoSourcePolicy.entries.forEach { policy ->- ChannelLogoSourcePolicyOptionRow(- policy = policy,- selected = uiState.channelLogoSourcePolicy == policy,- onSelect = { onSelectChannelLogoSourcePolicy(policy) }- )- }- }+// ??? Source type row ׳ֲ¿ֲ½ narrow layout (top tabs) ???????????????????????????????- Column(- modifier = Modifier- .fillMaxWidth()- .background(Surface, RoundedCornerShape(12.dp))- .border(1.dp, SurfaceHighlight, RoundedCornerShape(12.dp))- .padding(horizontal = 16.dp, vertical = 12.dp),- verticalArrangement = Arrangement.spacedBy(10.dp)- ) {- Text(- text = androidx.compose.ui.res.stringResource(R.string.setup_epg_sync_mode_label),- style = MaterialTheme.typography.titleSmall,- color = TextPrimary- )- Text(- text = androidx.compose.ui.res.stringResource(- if (sourceType == SourceType.STALKER) {- R.string.setup_stalker_epg_sync_mode_helper- } else {- R.string.setup_epg_sync_mode_helper- }- ),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- ProviderEpgSyncMode.entries.forEach { mode ->- EpgSyncModeOptionRow(- mode = mode,- sourceType = sourceType,- selected = uiState.epgSyncMode == mode,- onSelect = { onSelectEpgSyncMode(mode) }- )- }- }- }+// ??? ProviderTextField ????????????????????????????????????????????????????????+//+// Key fix: uses BasicTextField with decorationBox and tracks focus via+// onFocusEvent { it.hasFocus } ׳ֲ¿ֲ½ hasFocus is true when this node OR any+// descendant (the actual cursor/text composable) has focus. The old approach+// used onFocusChanged { isFocused } on an outer Box, which became false the+// moment the inner BasicTextField took focus, breaking keyboard scroll.- if (sourceType == SourceType.STALKER) {- Column(- modifier = Modifier- .fillMaxWidth()- .background(Surface, RoundedCornerShape(12.dp))- .border(1.dp, SurfaceHighlight, RoundedCornerShape(12.dp))- .padding(horizontal = 16.dp, vertical = 12.dp),- verticalArrangement = Arrangement.spacedBy(10.dp)- ) {- Text(- text = "Movie and series catalog",- style = MaterialTheme.typography.titleSmall,- color = TextPrimary- )- Text(- text = "This is separate from EPG loading. On demand makes the provider ready after categories load; background indexing downloads the complete catalog later.",- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- PolicyOptionRow(- title = "On demand (recommended)",- description = "Load visible shelves and opened categories as needed. Existing cached items are kept.",- selected = uiState.stalkerCatalogMode == StalkerCatalogMode.ON_DEMAND,- onSelect = { onSelectStalkerCatalogMode(StalkerCatalogMode.ON_DEMAND) }- )- PolicyOptionRow(- title = "Complete background index",- description = "Make the provider ready first, then maintain a complete searchable catalog in the background.",- selected = uiState.stalkerCatalogMode == StalkerCatalogMode.BACKGROUND_INDEX,- onSelect = { onSelectStalkerCatalogMode(StalkerCatalogMode.BACKGROUND_INDEX) }- )- }- Column(- modifier = Modifier- .fillMaxWidth()- .background(Surface, RoundedCornerShape(12.dp))- .border(1.dp, SurfaceHighlight, RoundedCornerShape(12.dp))- .padding(horizontal = 16.dp, vertical = 12.dp),- verticalArrangement = Arrangement.spacedBy(10.dp)- ) {- Text(- text = "Stalker auth mode",- style = MaterialTheme.typography.titleSmall,- color = TextPrimary- )- Text(- text = "Auto-detect is the default. Override it only when the portal needs credentials or a mixed MAG + account login flow.",- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- StalkerAuthMode.entries.forEach { mode ->- StalkerAuthModeOptionRow(- mode = mode,- selected = stalkerAuthMode == mode,- onSelect = { onStalkerAuthModeChange(mode) }- )- }- }- if (stalkerAuthMode != StalkerAuthMode.MAC_ONLY) {- ProviderTextField(- value = username,- onValueChange = onUsernameChange,- placeholder = if (stalkerAuthMode == StalkerAuthMode.AUTO) {- "Portal username (optional)"- } else {- "Portal username"- },- keyboardOptions = KeyboardOptions(- capitalization = KeyboardCapitalization.None,- autoCorrectEnabled = false,- keyboardType = KeyboardType.Ascii,- imeAction = ImeAction.Next- )- )- ProviderTextField(- value = password,- onValueChange = onPasswordChange,- placeholder = if (stalkerAuthMode == StalkerAuthMode.AUTO) {- "Portal password (optional)"- } else {- "Portal password"- },- isPassword = true,- keyboardOptions = KeyboardOptions(- capitalization = KeyboardCapitalization.None,- autoCorrectEnabled = false,- keyboardType = KeyboardType.Password,- imeAction = ImeAction.Next- )- )- }- ProviderTextField(- value = stalkerDeviceProfile,- onValueChange = onStalkerDeviceProfileChange,- placeholder = "MAG Type (optional)"- )- ProviderTextField(- value = stalkerDeviceTimezone,- onValueChange = onStalkerDeviceTimezoneChange,- placeholder = "Timezone (optional)"- )- ProviderTextField(- value = stalkerDeviceLocale,- onValueChange = onStalkerDeviceLocaleChange,- placeholder = "Locale (optional)"- )- ProviderTextField(- value = stalkerSerialNumber,- onValueChange = onStalkerSerialNumberChange,- placeholder = "Serial number (optional)"- )- ProviderTextField(- value = stalkerDeviceId,- onValueChange = onStalkerDeviceIdChange,- placeholder = "Device ID (optional)"- )- ProviderTextField(- value = stalkerDeviceId2,- onValueChange = onStalkerDeviceId2Change,- placeholder = "Device ID2 (optional)"- )- ProviderTextField(- value = stalkerSignature,- onValueChange = onStalkerSignatureChange,- placeholder = "Signature (optional)"- )- HorizontalDivider(color = SurfaceHighlight.copy(alpha = 0.45f))- Text(- text = "Stalker compatibility",- style = MaterialTheme.typography.titleSmall,- color = TextPrimary- )- Text(- text = "Portal-specific overrides for stubborn MAG/Stalker servers. Leave fields empty unless a server needs them.",- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- ProviderTextField(- value = stalkerHwVersion,- onValueChange = onStalkerHwVersionChange,- placeholder = "hw_version override (optional)"- )- ProviderTextField(- value = stalkerApiUserAgent,- onValueChange = onStalkerApiUserAgentChange,- placeholder = "User-Agent (API, optional)"- )- ProviderTextField(- value = stalkerPlayerUserAgent,- onValueChange = onStalkerPlayerUserAgentChange,- placeholder = "User-Agent (Player, optional)"- )- ProviderTextField(- value = stalkerPlayerHeaders,- onValueChange = onStalkerPlayerHeadersChange,- placeholder = "Headers (Player, optional, Header: Value | HeaderToRemove:)"- )- Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {- Text(- text = "X-User-Agent Link",- style = MaterialTheme.typography.bodyMedium,- color = TextPrimary- )- Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {- StalkerLinkOptionButton(- text = StalkerAdvancedOptions.LINK_ETHERNET,- selected = stalkerXUserAgentLink == StalkerAdvancedOptions.LINK_ETHERNET,- onClick = { onStalkerXUserAgentLinkChange(StalkerAdvancedOptions.LINK_ETHERNET) }- )- StalkerLinkOptionButton(- text = StalkerAdvancedOptions.LINK_WIFI,- selected = stalkerXUserAgentLink == StalkerAdvancedOptions.LINK_WIFI,- onClick = { onStalkerXUserAgentLinkChange(StalkerAdvancedOptions.LINK_WIFI) }- )- }- }- TvClickableSurface(- onClick = { onStalkerProxyEnabledChange(!stalkerProxyEnabled) },- modifier = Modifier- .fillMaxWidth()- .semantics { contentDescription = "Use HTTP proxy" },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (stalkerProxyEnabled) Primary.copy(alpha = 0.1f) else Surface,- focusedContainerColor = Primary.copy(alpha = 0.22f)- ),- border = ClickableSurfaceDefaults.border(- border = Border(- BorderStroke(- 1.dp,- if (stalkerProxyEnabled) Primary.copy(alpha = 0.4f) else SurfaceHighlight- )- ),- focusedBorder = Border(BorderStroke(3.dp, PrimaryLight))- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Row(- modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),- horizontalArrangement = Arrangement.spacedBy(12.dp),- verticalAlignment = Alignment.CenterVertically- ) {- Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {- Text(- text = "Use HTTP proxy",- style = MaterialTheme.typography.titleSmall,- color = TextPrimary- )- Text(- text = "Applies to Stalker API and playback only.",- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- Switch(- checked = stalkerProxyEnabled,- onCheckedChange = onStalkerProxyEnabledChange- )- }- }- AnimatedVisibility(stalkerProxyEnabled) {- Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {- ProviderTextField(- value = stalkerProxyHost,- onValueChange = onStalkerProxyHostChange,- placeholder = "Proxy host"- )- ProviderTextField(- value = stalkerProxyPort,- onValueChange = onStalkerProxyPortChange,- placeholder = "Proxy port",- keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)- )- }- }- StalkerRequestRulesEditor(- rules = stalkerRequestRules,- onAddRule = onAddStalkerRequestRule,- onUpdateRule = onUpdateStalkerRequestRule,- onRemoveRule = onRemoveStalkerRequestRule- )- }- }- }- }-}-@Composable-private fun StalkerLinkOptionButton(- text: String,- selected: Boolean,- onClick: () -> Unit-) {- Surface(- onClick = onClick,- modifier = Modifier.mouseClickable(onClick = onClick),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (selected) Primary.copy(alpha = 0.18f) else Surface,- focusedContainerColor = Primary.copy(alpha = 0.28f)- ),- border = ClickableSurfaceDefaults.border(- border = Border(BorderStroke(1.dp, if (selected) Primary else SurfaceHighlight)),- focusedBorder = Border(BorderStroke(3.dp, PrimaryLight))- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Text(- text = text,- modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp),- style = MaterialTheme.typography.bodySmall,- color = TextPrimary- )- }-}-@Composable-private fun StalkerRequestRulesEditor(- rules: List<StalkerRequestRuleUiState>,- onAddRule: () -> Unit,- onUpdateRule: (Int, StalkerRequestRuleUiState) -> Unit,- onRemoveRule: (Int) -> Unit-) {- val newestRuleBringIntoViewRequester = remember { BringIntoViewRequester() }- var previousRuleCount by remember { mutableIntStateOf(rules.size) }+// ??? TabButton (used by SourceTypeTabRow) ?????????????????????????????????????- LaunchedEffect(rules.size) {- if (rules.size > previousRuleCount) {- delay(120)- runCatching { newestRuleBringIntoViewRequester.bringIntoView() }- }- previousRuleCount = rules.size- }+// ג”€ג”€ג”€ Revealing password visual transformation ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€- Column(- modifier = Modifier- .fillMaxWidth()- .background(Surface, RoundedCornerShape(12.dp))- .border(1.dp, SurfaceHighlight, RoundedCornerShape(12.dp))- .padding(12.dp),- verticalArrangement = Arrangement.spacedBy(10.dp)- ) {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Column(modifier = Modifier.weight(1f)) {- Text("Request rules", style = MaterialTheme.typography.titleSmall, color = TextPrimary)- Text(- "Match by action, block calls, or override params. Blank values remove params.",- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- RequestRuleActionButton(text = "Add Rule", onClick = onAddRule)- }- rules.forEachIndexed { index, rule ->- Column(- modifier = Modifier- .fillMaxWidth()- .then(- if (index == rules.lastIndex) {- Modifier.bringIntoViewRequester(newestRuleBringIntoViewRequester)- } else {- Modifier- }- )- .border(1.dp, SurfaceHighlight.copy(alpha = 0.7f), RoundedCornerShape(10.dp))- .padding(10.dp),- verticalArrangement = Arrangement.spacedBy(8.dp)- ) {- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Text("Rule ${index + 1}", style = MaterialTheme.typography.bodyMedium, color = TextPrimary)- RequestRuleActionButton(- text = "Delete",- onClick = { onRemoveRule(index) },- compact = true- )- }- ProviderTextField(- value = rule.action,- onValueChange = { onUpdateRule(index, rule.copy(action = it.trim())) },- placeholder = "action, e.g. get_profile"- )- Row(- modifier = Modifier.fillMaxWidth(),- horizontalArrangement = Arrangement.SpaceBetween,- verticalAlignment = Alignment.CenterVertically- ) {- Text("Block this request", style = MaterialTheme.typography.bodySmall, color = TextPrimary)- Switch(- checked = rule.blockRequest,- onCheckedChange = { onUpdateRule(index, rule.copy(blockRequest = it)) }- )- }- if (rule.blockRequest && rule.action.trim() in setOf("handshake", "get_profile")) {- Text(- text = "Warning: blocking ${rule.action.trim()} can prevent login.",- style = MaterialTheme.typography.bodySmall,- color = AccentAmber- )- }- ProviderTextField(- value = rule.paramsText,- onValueChange = { onUpdateRule(index, rule.copy(paramsText = it)) },- placeholder = "Param overrides: name=value | remove_me="- )- }- }- }-}-@Composable-private fun RequestRuleActionButton(- text: String,- onClick: () -> Unit,- compact: Boolean = false-) {- TvClickableSurface(- onClick = onClick,- modifier = Modifier- .width(if (compact) 88.dp else 124.dp)- .height(40.dp)- .mouseClickable(onClick = onClick)- .semantics { contentDescription = text },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (compact) SurfaceHighlight.copy(alpha = 0.9f) else Primary,- focusedContainerColor = if (compact) SurfaceHighlight else PrimaryLight- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),- glow = ClickableSurfaceDefaults.glow(focusedGlow = Glow.None),- border = ClickableSurfaceDefaults.border(- border = Border(- BorderStroke(- 1.dp,- if (compact) SurfaceHighlight.copy(alpha = 0.8f) else PrimaryLight- )- ),- focusedBorder = Border(BorderStroke(3.dp, FocusBorder))- )- ) {- Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {- Text(- text = text,- style = MaterialTheme.typography.bodySmall,- color = TextPrimary,- textAlign = TextAlign.Center- )- }- }-}--@Composable-private fun XtreamLiveSyncModeOptionRow(- mode: ProviderXtreamLiveSyncMode,- selected: Boolean,- onSelect: () -> Unit-) {- val titleRes = when (mode) {- ProviderXtreamLiveSyncMode.AUTO -> R.string.setup_xtream_live_sync_mode_auto_title- ProviderXtreamLiveSyncMode.CATEGORY_BY_CATEGORY -> R.string.setup_xtream_live_sync_mode_category_title- ProviderXtreamLiveSyncMode.STREAM_ALL -> R.string.setup_xtream_live_sync_mode_stream_all_title- }- val descriptionRes = when (mode) {- ProviderXtreamLiveSyncMode.AUTO -> R.string.setup_xtream_live_sync_mode_auto_description- ProviderXtreamLiveSyncMode.CATEGORY_BY_CATEGORY -> R.string.setup_xtream_live_sync_mode_category_description- ProviderXtreamLiveSyncMode.STREAM_ALL -> R.string.setup_xtream_live_sync_mode_stream_all_description- }- Surface(- onClick = onSelect,- modifier = Modifier- .fillMaxWidth()- .mouseClickable(onClick = onSelect),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (selected) Primary.copy(alpha = 0.12f) else Color.Transparent,- focusedContainerColor = if (selected) Primary.copy(alpha = 0.26f) else SurfaceHighlight.copy(alpha = 0.9f)- ),- border = ClickableSurfaceDefaults.border(- border = Border(- BorderStroke(- 1.dp,- if (selected) Primary.copy(alpha = 0.45f) else Color.Transparent- )- ),- focusedBorder = Border(BorderStroke(3.dp, PrimaryLight))- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Row(- modifier = Modifier.padding(horizontal = 8.dp, vertical = 8.dp),- horizontalArrangement = Arrangement.spacedBy(12.dp),- verticalAlignment = Alignment.CenterVertically- ) {- RadioButton(- selected = selected,- onClick = onSelect- )- Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {- Text(- text = androidx.compose.ui.res.stringResource(titleRes),- style = MaterialTheme.typography.bodyMedium,- color = TextPrimary- )- Text(- text = androidx.compose.ui.res.stringResource(descriptionRes),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- }- }-}--@Composable-private fun StalkerAuthModeOptionRow(- mode: StalkerAuthMode,- selected: Boolean,- onSelect: () -> Unit-) {- val title = when (mode) {- StalkerAuthMode.AUTO -> "Auto-detect"- StalkerAuthMode.MAC_ONLY -> "MAC only"- StalkerAuthMode.MAC_PLUS_CREDENTIALS -> "MAC + credentials"- StalkerAuthMode.CREDENTIALS_ONLY -> "Credentials only"- }- val description = when (mode) {- StalkerAuthMode.AUTO -> "Try the portal's likely auth flow first and retry once if a different Stalker mode fits better."- StalkerAuthMode.MAC_ONLY -> "Use MAG-style MAC authentication without a portal account login."- StalkerAuthMode.MAC_PLUS_CREDENTIALS -> "Keep the MAG identity and add portal account credentials for stricter portals."- StalkerAuthMode.CREDENTIALS_ONLY -> "Use portal account credentials even if the MAC address is optional or ignored."- }- Surface(- onClick = onSelect,- modifier = Modifier- .fillMaxWidth()- .mouseClickable(onClick = onSelect),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (selected) Primary.copy(alpha = 0.12f) else Color.Transparent,- focusedContainerColor = if (selected) Primary.copy(alpha = 0.26f) else SurfaceHighlight.copy(alpha = 0.9f)- ),- border = ClickableSurfaceDefaults.border(- border = Border(- BorderStroke(- 1.dp,- if (selected) Primary.copy(alpha = 0.45f) else Color.Transparent- )- ),- focusedBorder = Border(BorderStroke(3.dp, PrimaryLight))- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Row(- modifier = Modifier.padding(horizontal = 8.dp, vertical = 8.dp),- horizontalArrangement = Arrangement.spacedBy(12.dp),- verticalAlignment = Alignment.CenterVertically- ) {- RadioButton(- selected = selected,- onClick = onSelect- )- Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {- Text(- text = title,- style = MaterialTheme.typography.bodyMedium,- color = TextPrimary- )- Text(- text = description,- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- }- }-}--@Composable-private fun EpgSyncModeOptionRow(- mode: ProviderEpgSyncMode,- sourceType: SourceType,- selected: Boolean,- onSelect: () -> Unit-) {- val titleRes = when (mode) {- ProviderEpgSyncMode.UPFRONT -> R.string.setup_epg_sync_mode_upfront_title- ProviderEpgSyncMode.BACKGROUND -> R.string.setup_epg_sync_mode_background_title- ProviderEpgSyncMode.SKIP -> R.string.setup_epg_sync_mode_skip_title- }- val descriptionRes = when (mode) {- ProviderEpgSyncMode.UPFRONT -> if (sourceType == SourceType.STALKER) {- R.string.setup_stalker_epg_sync_mode_upfront_description- } else {- R.string.setup_epg_sync_mode_upfront_description- }- ProviderEpgSyncMode.BACKGROUND -> if (sourceType == SourceType.STALKER) {- R.string.setup_stalker_epg_sync_mode_background_description- } else {- R.string.setup_epg_sync_mode_background_description- }- ProviderEpgSyncMode.SKIP -> if (sourceType == SourceType.STALKER) {- R.string.setup_stalker_epg_sync_mode_skip_description- } else {- R.string.setup_epg_sync_mode_skip_description- }- }- Surface(- onClick = onSelect,- modifier = Modifier- .fillMaxWidth()- .mouseClickable(onClick = onSelect),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (selected) Primary.copy(alpha = 0.12f) else Color.Transparent,- focusedContainerColor = if (selected) Primary.copy(alpha = 0.26f) else SurfaceHighlight.copy(alpha = 0.9f)- ),- border = ClickableSurfaceDefaults.border(- border = Border(- BorderStroke(- 1.dp,- if (selected) Primary.copy(alpha = 0.45f) else Color.Transparent- )- ),- focusedBorder = Border(BorderStroke(3.dp, PrimaryLight))- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Row(- modifier = Modifier.padding(horizontal = 8.dp, vertical = 8.dp),- horizontalArrangement = Arrangement.spacedBy(12.dp),- verticalAlignment = Alignment.CenterVertically- ) {- RadioButton(- selected = selected,- onClick = onSelect- )- Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {- Text(- text = androidx.compose.ui.res.stringResource(titleRes),- style = MaterialTheme.typography.bodyMedium,- color = TextPrimary- )- Text(- text = androidx.compose.ui.res.stringResource(descriptionRes),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- }- }- }-}--private fun supportsGuideAndLogoPolicy(sourceType: SourceType): Boolean = when (sourceType) {- SourceType.XTREAM,- SourceType.STALKER,- SourceType.M3U_URL,- SourceType.M3U_FILE -> true- SourceType.JELLYFIN -> false-}--@Composable-private fun GuideSourcePolicyOptionRow(- policy: GuideSourcePolicy,- selected: Boolean,- onSelect: () -> Unit-) {- val title = when (policy) {- GuideSourcePolicy.AUTO -> "Auto"- GuideSourcePolicy.EXTERNAL_ONLY -> "Use external EPG only"- GuideSourcePolicy.PROVIDER_ONLY -> "Use supplier EPG only"- GuideSourcePolicy.DISABLED -> "Disable guide data"- }- val description = when (policy) {- GuideSourcePolicy.AUTO -> "Keep the current mixed behavior: external XMLTV can override supplier guide data, and unmatched channels may still use supplier fallback."- GuideSourcePolicy.EXTERNAL_ONLY -> "Use only assigned external XMLTV sources. Unmatched channels stay without guide data."- GuideSourcePolicy.PROVIDER_ONLY -> "Ignore assigned external XMLTV sources for this provider and use only the supplier guide paths."- GuideSourcePolicy.DISABLED -> "Do not import or resolve guide data for this provider."- }- PolicyOptionRow(title = title, description = description, selected = selected, onSelect = onSelect)-}--@Composable-private fun ChannelLogoSourcePolicyOptionRow(- policy: ChannelLogoSourcePolicy,- selected: Boolean,- onSelect: () -> Unit-) {- val title = when (policy) {- ChannelLogoSourcePolicy.SUPPLIER_PREFERRED -> "Supplier logos first"- ChannelLogoSourcePolicy.EPG_PREFERRED -> "Prefer EPG logos"- ChannelLogoSourcePolicy.SUPPLIER_ONLY -> "Supplier logos only"- ChannelLogoSourcePolicy.EPG_ONLY -> "EPG logos only"- }- val description = when (policy) {- ChannelLogoSourcePolicy.SUPPLIER_PREFERRED -> "Use the supplier logo when it exists, then fall back to the matched EPG icon."- ChannelLogoSourcePolicy.EPG_PREFERRED -> "Use the matched EPG icon first, then fall back to the supplier logo."- ChannelLogoSourcePolicy.SUPPLIER_ONLY -> "Always use supplier logos for this provider."- ChannelLogoSourcePolicy.EPG_ONLY -> "Always use matched EPG icons for this provider."- }- PolicyOptionRow(title = title, description = description, selected = selected, onSelect = onSelect)-}--@Composable-private fun PolicyOptionRow(- title: String,- description: String,- selected: Boolean,- onSelect: () -> Unit-) {- Surface(- onClick = onSelect,- modifier = Modifier- .fillMaxWidth()- .mouseClickable(onClick = onSelect),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (selected) Primary.copy(alpha = 0.12f) else Color.Transparent,- focusedContainerColor = if (selected) Primary.copy(alpha = 0.26f) else SurfaceHighlight.copy(alpha = 0.9f)- ),- border = ClickableSurfaceDefaults.border(- border = Border(- BorderStroke(- 1.dp,- if (selected) Primary.copy(alpha = 0.45f) else Color.Transparent- )- ),- focusedBorder = Border(BorderStroke(3.dp, PrimaryLight))- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)- ) {- Row(- modifier = Modifier.padding(horizontal = 8.dp, vertical = 8.dp),- horizontalArrangement = Arrangement.spacedBy(12.dp),- verticalAlignment = Alignment.CenterVertically- ) {- RadioButton(selected = selected, onClick = onSelect)- Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {- Text(text = title, style = MaterialTheme.typography.bodyMedium, color = TextPrimary)- Text(text = description, style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim)- }- }- }-}--@Composable-private fun FormErrors(validationError: String?, error: String?) {- validationError?.let {- Text(text = it, style = MaterialTheme.typography.bodyMedium, color = ErrorColor)- }- error?.let {- Text(text = it, style = MaterialTheme.typography.bodyMedium, color = ErrorColor)- }-}--// ??? Source type selector ן¿½ wide layout (left sidebar) ????????????????????????--@Composable-private fun SourceTypeSelectorPanel(- sourceType: SourceType,- isEditing: Boolean,- isEditLabel: String,- onSelect: (SourceType) -> Unit,- onImportClick: () -> Unit,- modifier: Modifier = Modifier-) {- Surface(- modifier = modifier,- shape = RoundedCornerShape(20.dp),- colors = SurfaceDefaults.colors(containerColor = Surface.copy(alpha = 0.92f))- ) {- Column(- modifier = Modifier.fillMaxSize().padding(14.dp),- verticalArrangement = Arrangement.spacedBy(8.dp)- ) {- Text(- text = isEditLabel,- style = MaterialTheme.typography.titleMedium,- color = TextPrimary- )- Text(- text = androidx.compose.ui.res.stringResource(R.string.setup_shell_subtitle),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- Text(- text = androidx.compose.ui.res.stringResource(R.string.setup_source_type_label),- style = MaterialTheme.typography.labelSmall,- color = TextTertiary- )- if (!isEditing || sourceType == SourceType.XTREAM) {- SourceTypeCard(- title = androidx.compose.ui.res.stringResource(R.string.setup_xtream),- subtitle = androidx.compose.ui.res.stringResource(R.string.setup_info_xtream_body),- selected = sourceType == SourceType.XTREAM,- enabled = !isEditing,- onClick = { onSelect(SourceType.XTREAM) }- )- }- if (!isEditing || sourceType == SourceType.STALKER) {- SourceTypeCard(- title = androidx.compose.ui.res.stringResource(R.string.setup_stalker),- badge = androidx.compose.ui.res.stringResource(R.string.badge_beta),- subtitle = androidx.compose.ui.res.stringResource(R.string.setup_info_stalker_body),- selected = sourceType == SourceType.STALKER,- enabled = !isEditing,- onClick = { onSelect(SourceType.STALKER) }- )- }- if (!isEditing || sourceType == SourceType.M3U_URL) {- SourceTypeCard(- title = androidx.compose.ui.res.stringResource(R.string.setup_tab_url),- subtitle = androidx.compose.ui.res.stringResource(R.string.setup_info_m3u_body),- selected = sourceType == SourceType.M3U_URL,- enabled = !isEditing,- onClick = { onSelect(SourceType.M3U_URL) }- )- }- if (!isEditing || sourceType == SourceType.M3U_FILE) {- SourceTypeCard(- title = androidx.compose.ui.res.stringResource(R.string.setup_tab_file),- subtitle = androidx.compose.ui.res.stringResource(R.string.setup_file_browse_hint),- selected = sourceType == SourceType.M3U_FILE,- enabled = !isEditing,- onClick = { onSelect(SourceType.M3U_FILE) }- )- }- if (!isEditing || sourceType == SourceType.JELLYFIN) {- SourceTypeCard(- title = androidx.compose.ui.res.stringResource(R.string.setup_tab_jellyfin),- subtitle = "Jellyfin media server",- selected = sourceType == SourceType.JELLYFIN,- enabled = !isEditing,- onClick = { onSelect(SourceType.JELLYFIN) }- )- }- if (!isEditing) {- ImportOptionsButton(- text = stringResource(R.string.settings_restore_data),- onClick = onImportClick,- compact = true,- modifier = Modifier.fillMaxWidth()- )- }- Spacer(modifier = Modifier.weight(1f))- Text(- text = androidx.compose.ui.res.stringResource(R.string.setup_info_manage_title),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim- )- Text(- text = androidx.compose.ui.res.stringResource(R.string.setup_info_manage_body),- style = MaterialTheme.typography.bodySmall,- color = OnSurfaceDim.copy(alpha = 0.55f)- )- }- }-}--@Composable-private fun SourceTypeCard(- title: String,- badge: String? = null,- subtitle: String,- selected: Boolean,- enabled: Boolean,- onClick: () -> Unit-) {- Surface(- onClick = { if (enabled) onClick() },- modifier = Modifier.fillMaxWidth().mouseClickable(enabled = enabled, onClick = onClick),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (selected) Primary.copy(alpha = 0.18f) else SurfaceElevated,- focusedContainerColor = if (selected) Primary.copy(alpha = 0.28f) else SurfaceHighlight- ),- border = ClickableSurfaceDefaults.border(- border = Border(BorderStroke(1.dp, if (selected) Primary.copy(alpha = 0.5f) else SurfaceHighlight)),- focusedBorder = Border(BorderStroke(2.dp, FocusBorder))- )- ) {- Column(- modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),- verticalArrangement = Arrangement.spacedBy(3.dp)- ) {- Row(- horizontalArrangement = Arrangement.spacedBy(8.dp),- verticalAlignment = Alignment.CenterVertically- ) {- Text(- text = title,- style = MaterialTheme.typography.bodyMedium,- color = if (selected) Primary else TextPrimary- )- badge?.let {- StatusPill(- label = it,- containerColor = AccentAmber,- contentColor = Color.Black,- horizontalPadding = 6.dp,- verticalPadding = 2.dp,- cornerRadius = 6.dp- )- }- }- Text(text = subtitle, style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim, maxLines = 2)- }- }-}--// ??? Source type row ן¿½ narrow layout (top tabs) ???????????????????????????????--@Composable-private fun SourceTypeTabRow(- sourceType: SourceType,- isEditing: Boolean,- onSelect: (SourceType) -> Unit,- modifier: Modifier = Modifier-) {- Row(modifier = modifier, horizontalArrangement = Arrangement.spacedBy(8.dp)) {- if (!isEditing || sourceType == SourceType.XTREAM) {- TabButton(- text = androidx.compose.ui.res.stringResource(R.string.setup_xtream),- isSelected = sourceType == SourceType.XTREAM,- onClick = { if (!isEditing) onSelect(SourceType.XTREAM) }- )- }- if (!isEditing || sourceType == SourceType.STALKER) {- TabButton(- text = androidx.compose.ui.res.stringResource(R.string.setup_stalker),- badge = androidx.compose.ui.res.stringResource(R.string.badge_beta),- isSelected = sourceType == SourceType.STALKER,- onClick = { if (!isEditing) onSelect(SourceType.STALKER) }- )- }- if (!isEditing || sourceType == SourceType.M3U_URL) {- TabButton(- text = androidx.compose.ui.res.stringResource(R.string.setup_tab_url),- isSelected = sourceType == SourceType.M3U_URL,- onClick = { if (!isEditing) onSelect(SourceType.M3U_URL) }- )- }- if (!isEditing || sourceType == SourceType.M3U_FILE) {- TabButton(- text = androidx.compose.ui.res.stringResource(R.string.setup_tab_file),- isSelected = sourceType == SourceType.M3U_FILE,- onClick = { if (!isEditing) onSelect(SourceType.M3U_FILE) }- )- }- if (!isEditing || sourceType == SourceType.JELLYFIN) {- TabButton(- text = androidx.compose.ui.res.stringResource(R.string.setup_tab_jellyfin),- isSelected = sourceType == SourceType.JELLYFIN,- onClick = { if (!isEditing) onSelect(SourceType.JELLYFIN) }- )- }- }-}--// ??? ProviderTextField ????????????????????????????????????????????????????????-//-// Key fix: uses BasicTextField with decorationBox and tracks focus via-// onFocusEvent { it.hasFocus } ן¿½ hasFocus is true when this node OR any-// descendant (the actual cursor/text composable) has focus. The old approach-// used onFocusChanged { isFocused } on an outer Box, which became false the-// moment the inner BasicTextField took focus, breaking keyboard scroll.--@Composable-private fun ProviderTextField(- value: String,- onValueChange: (String) -> Unit,- placeholder: String,- modifier: Modifier = Modifier,- isPassword: Boolean = false,- keyboardOptions: KeyboardOptions = KeyboardOptions.Default,- keyboardActions: KeyboardActions = KeyboardActions.Default-) {- val isTelevisionDevice = rememberIsTelevisionDevice()- var hasContainerFocus by remember { mutableStateOf(false) }- var hasInputFocus by remember { mutableStateOf(false) }- var acceptsInput by remember(isTelevisionDevice) { mutableStateOf(!isTelevisionDevice) }- var pendingInputActivation by remember { mutableStateOf(false) }- var editBaselineValue by remember { mutableStateOf(value) }- var fieldValue by remember {- mutableStateOf(TextFieldValue(text = value, selection = TextRange(value.length)))- }- var isPasswordVisible by rememberSaveable(isPassword) { mutableStateOf(false) }- var revealedPasswordIndex by remember { mutableStateOf<Int?>(null) }- var previousValue by remember { mutableStateOf(value) }- val containerFocusRequester = remember { FocusRequester() }- val inputFocusRequester = remember { FocusRequester() }- val visibilityToggleFocusRequester = remember { FocusRequester() }- val keyboardController = LocalSoftwareKeyboardController.current- val bringIntoViewRequester = remember { BringIntoViewRequester() }- val coroutineScope = rememberCoroutineScope()- val isFocused = hasContainerFocus || hasInputFocus- val passwordVisibilityDescription = if (isPassword) {- androidx.compose.ui.res.stringResource(- if (isPasswordVisible) R.string.setup_hide_password else R.string.setup_show_password- )- } else {- null- }-- fun activateInput() {- if (!acceptsInput) {- editBaselineValue = value- }- if (!isTelevisionDevice) {- acceptsInput = true- inputFocusRequester.requestFocus()- keyboardController?.show()- coroutineScope.launch {- runCatching { bringIntoViewRequester.bringIntoView() }- delay(180)- runCatching { bringIntoViewRequester.bringIntoView() }- }- return- }- acceptsInput = true- pendingInputActivation = true- coroutineScope.launch {- runCatching { bringIntoViewRequester.bringIntoView() }- }- }-- LaunchedEffect(value) {- if (value != fieldValue.text) {- val coercedSelectionStart = fieldValue.selection.start.coerceIn(0, value.length)- val coercedSelectionEnd = fieldValue.selection.end.coerceIn(0, value.length)- val coercedComposition = fieldValue.composition?.let { composition ->- val compositionStart = composition.start.coerceIn(0, value.length)- val compositionEnd = composition.end.coerceIn(0, value.length)- if (compositionStart <= compositionEnd) {- TextRange(compositionStart, compositionEnd)- } else {- null- }- }- fieldValue = fieldValue.copy(- text = value,- selection = TextRange(coercedSelectionStart, coercedSelectionEnd),- composition = coercedComposition- )- }- }-- LaunchedEffect(acceptsInput, pendingInputActivation) {- if (!isTelevisionDevice || !acceptsInput || !pendingInputActivation) {- return@LaunchedEffect- }- inputFocusRequester.requestFocus()- keyboardController?.show()- coroutineScope.launch {- delay(120)- runCatching { bringIntoViewRequester.bringIntoView() }- }- pendingInputActivation = false- }-- LaunchedEffect(isPassword) {- if (!isPassword) {- isPasswordVisible = false- }- }-- // Show most-recently typed character briefly before masking- LaunchedEffect(value, isPassword) {- if (!isPassword) { previousValue = value; revealedPasswordIndex = null; return@LaunchedEffect }- revealedPasswordIndex = when {- value.length > previousValue.length && value.isNotEmpty() -> value.lastIndex- value.isEmpty() -> null- else -> revealedPasswordIndex?.takeIf { it < value.length }- }- previousValue = value- }- LaunchedEffect(revealedPasswordIndex, value, isPassword) {- val idx = revealedPasswordIndex ?: return@LaunchedEffect- if (!isPassword || idx >= value.length) return@LaunchedEffect- delay(1500)- if (revealedPasswordIndex == idx) revealedPasswordIndex = null- }-- val borderColor by animateColorAsState(if (isFocused) Primary else SurfaceHighlight, tween(150), label = "border")- val bgColor by animateColorAsState(if (isFocused) Surface else SurfaceElevated, tween(150), label = "bg")-- Box(- modifier = modifier- .fillMaxWidth()- .focusRequester(containerFocusRequester)- .bringIntoViewRequester(bringIntoViewRequester)- .onFocusEvent {- hasContainerFocus = it.hasFocus- if (!it.hasFocus && isTelevisionDevice) {- acceptsInput = false- keyboardController?.hide()- }- }- .mouseClickable(focusRequester = containerFocusRequester, onClick = ::activateInput)- .clickable(onClick = ::activateInput)- .focusable()- .padding(0.dp)- ) {- androidx.compose.foundation.text.BasicTextField(- value = fieldValue,- onValueChange = { updatedValue ->- fieldValue = updatedValue- if (updatedValue.text != value) {- onValueChange(updatedValue.text)- }- },- modifier = Modifier- .fillMaxWidth()- .focusRequester(inputFocusRequester)- .focusProperties {- canFocus = !isTelevisionDevice || acceptsInput- if (isTelevisionDevice && acceptsInput) {- left = FocusRequester.Cancel- right = if (isPassword) visibilityToggleFocusRequester else FocusRequester.Cancel- }- }- .onPreviewKeyEvent { event ->- if (!isTelevisionDevice || !acceptsInput || event.nativeKeyEvent.action != android.view.KeyEvent.ACTION_DOWN) {- return@onPreviewKeyEvent false- }- val cursor = fieldValue.selection.end- when (event.nativeKeyEvent.keyCode) {- android.view.KeyEvent.KEYCODE_BACK -> {- fieldValue = TextFieldValue(- text = editBaselineValue,- selection = TextRange(editBaselineValue.length)- )- if (editBaselineValue != value) {- onValueChange(editBaselineValue)- }- acceptsInput = false- pendingInputActivation = false- keyboardController?.hide()- containerFocusRequester.requestFocus()- true- }- android.view.KeyEvent.KEYCODE_DPAD_LEFT -> {- val nextCursor = (cursor - 1).coerceAtLeast(0)- fieldValue = fieldValue.copy(selection = TextRange(nextCursor))- true- }- android.view.KeyEvent.KEYCODE_DPAD_RIGHT -> {- if (isPassword && cursor >= fieldValue.text.length) {- visibilityToggleFocusRequester.requestFocus()- return@onPreviewKeyEvent true- }- val nextCursor = (cursor + 1).coerceAtMost(fieldValue.text.length)- fieldValue = fieldValue.copy(selection = TextRange(nextCursor))- true- }- else -> false- }- }- .onFocusEvent {- hasInputFocus = it.hasFocus- if (it.hasFocus) {- coroutineScope.launch {- delay(120)- runCatching { bringIntoViewRequester.bringIntoView() }- }- } else if (isTelevisionDevice) {- keyboardController?.hide()- }- },- singleLine = true,- readOnly = isTelevisionDevice && !acceptsInput,- keyboardOptions = keyboardOptions,- keyboardActions = keyboardActions,- textStyle = MaterialTheme.typography.bodyMedium.copy(color = OnBackground),- visualTransformation = when {- !isPassword || isPasswordVisible -> VisualTransformation.None- else -> RevealingPasswordVisualTransformation(revealedPasswordIndex)- },- cursorBrush = SolidColor(Primary),- decorationBox = { innerTextField ->- Row(- modifier = Modifier- .background(bgColor, RoundedCornerShape(10.dp))- .border(if (isFocused) 2.dp else 1.dp, borderColor, RoundedCornerShape(10.dp))- .padding(horizontal = 16.dp, vertical = 14.dp),- verticalAlignment = Alignment.CenterVertically- ) {- Box(- modifier = Modifier.weight(1f),- contentAlignment = Alignment.CenterStart- ) {- if (fieldValue.text.isEmpty()) {- Text(text = placeholder, style = MaterialTheme.typography.bodyMedium, color = OnSurfaceDim)- }- innerTextField()- }-- if (isPassword) {- Box(- modifier = Modifier- .padding(start = 12.dp)- .size(24.dp)- .focusRequester(visibilityToggleFocusRequester)- .focusProperties {- canFocus = !isTelevisionDevice || acceptsInput- left = inputFocusRequester- }- .onFocusEvent {- if (it.hasFocus) {- coroutineScope.launch {- delay(120)- runCatching { bringIntoViewRequester.bringIntoView() }- }- }- }- .semantics {- contentDescription = passwordVisibilityDescription.orEmpty()- }- .clickable {- isPasswordVisible = !isPasswordVisible- }- .mouseClickable(focusRequester = visibilityToggleFocusRequester) {- isPasswordVisible = !isPasswordVisible- }- .focusable(enabled = !isTelevisionDevice || acceptsInput)- ) {- PasswordVisibilityGlyph(- isVisible = isPasswordVisible,- tint = if (isFocused) Primary else OnSurfaceDim,- modifier = Modifier.align(Alignment.Center)- )- }- }- }- }- )- }-}--@Composable-private fun PasswordVisibilityGlyph(- isVisible: Boolean,- tint: Color,- modifier: Modifier = Modifier-) {- Canvas(modifier = modifier.size(18.dp)) {- val stroke = Stroke(width = size.minDimension * 0.11f)- drawOval(- color = tint,- topLeft = androidx.compose.ui.geometry.Offset(1.6f, size.height * 0.22f),- size = androidx.compose.ui.geometry.Size(size.width - 3.2f, size.height * 0.56f),- style = stroke- )- drawCircle(- color = tint,- radius = size.minDimension * 0.14f,- center = center- )- if (!isVisible) {- drawLine(- color = tint,- start = androidx.compose.ui.geometry.Offset(size.width * 0.18f, size.height * 0.82f),- end = androidx.compose.ui.geometry.Offset(size.width * 0.82f, size.height * 0.18f),- strokeWidth = size.minDimension * 0.11f- )- }- }-}--// ??? Sync progress dialog ?????????????????????????????????????????????????????--@Composable-fun SyncProgressDialog(- message: String,- quickConnectCode: String? = null,- serverUrl: String? = null,- onCancel: (() -> Unit)? = null-) {- if (quickConnectCode != null && serverUrl != null) {- val qrCodeBitmap = remember(quickConnectCode, serverUrl) {- generateJellyfinQuickConnectQrCode(serverUrl, quickConnectCode)- }- PremiumDialog(- title = "Quick Connect",- subtitle = "Enter this code on your Jellyfin server",- onDismissRequest = {},- widthFraction = 0.38f,- heightFraction = null,- content = {- Column(- modifier = Modifier.fillMaxWidth(),- horizontalAlignment = Alignment.CenterHorizontally,- verticalArrangement = Arrangement.spacedBy(12.dp)- ) {- if (qrCodeBitmap != null) {- Box(- modifier = Modifier- .size(200.dp)- .background(Color.White, RoundedCornerShape(12.dp))- .padding(8.dp),- contentAlignment = Alignment.Center- ) {- Image(- bitmap = qrCodeBitmap.asImageBitmap(),- contentDescription = "Quick Connect QR Code",- modifier = Modifier.fillMaxSize()- )- }- }- Text(- text = stringResource(R.string.setup_jellyfin_quick_connect_code, quickConnectCode),- style = MaterialTheme.typography.headlineMedium,- color = Color.White- )- Text(- text = message,- style = MaterialTheme.typography.bodyMedium,- color = TextSecondary,- textAlign = TextAlign.Center- )- if (onCancel != null) {- TextButton(onClick = onCancel) {- Text("Cancel", color = Color.White)- }- }- }- }- )- } else {- val fraction = extractProgressFraction(message)- val animatedFraction by animateFloatAsState(- targetValue = fraction ?: 0f,- animationSpec = tween(durationMillis = 400),- label = "syncFraction"- )- PremiumDialog(- title = androidx.compose.ui.res.stringResource(R.string.settings_syncing_title),- subtitle = androidx.compose.ui.res.stringResource(R.string.settings_syncing_subtitle),- onDismissRequest = {},- widthFraction = 0.32f,- heightFraction = null,- content = {- Column(- modifier = Modifier.fillMaxWidth(),- horizontalAlignment = Alignment.CenterHorizontally,- verticalArrangement = Arrangement.spacedBy(16.dp)- ) {- CircularProgressIndicator(color = Primary)- StatusPill(- label = androidx.compose.ui.res.stringResource(R.string.settings_syncing_btn),- containerColor = PrimaryGlow- )- if (fraction != null) {- LinearProgressIndicator(- progress = { animatedFraction },- color = Primary,- modifier = Modifier.fillMaxWidth()- )- } else {- LinearProgressIndicator(- color = Primary,- modifier = Modifier.fillMaxWidth()- )- }- Text(- text = message,- style = MaterialTheme.typography.bodyMedium,- color = OnBackground,- textAlign = TextAlign.Center- )- }- }- )- }-}--// ??? ActionButton ?????????????????????????????????????????????????????????????--@Composable-private fun ActionButton(- text: String,- isLoading: Boolean = false,- onClick: () -> Unit-) {- ProviderActionButton(- text = text,- height = 52.dp,- isLoading = isLoading,- onClick = onClick- )-}--@Composable-private fun SmallActionButton(- text: String,- isLoading: Boolean = false,- onClick: () -> Unit-) {- ProviderActionButton(- text = text,- height = 40.dp,- isLoading = isLoading,- onClick = onClick- )-}--@Composable-private fun ProviderActionButton(- text: String,- height: androidx.compose.ui.unit.Dp,- isLoading: Boolean = false,- onClick: () -> Unit-) {- TvClickableSurface(- onClick = onClick,- enabled = !isLoading,- modifier = Modifier- .fillMaxWidth()- .height(height),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (!isLoading) Primary else SurfaceHighlight,- focusedContainerColor = if (!isLoading) Primary else SurfaceHighlight- ),- scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),- glow = ClickableSurfaceDefaults.glow(focusedGlow = Glow.None),- border = ClickableSurfaceDefaults.border(- border = Border(BorderStroke(1.dp, if (!isLoading) PrimaryLight else SurfaceHighlight)),- focusedBorder = Border(BorderStroke(2.dp, FocusBorder))- )- ) {- Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {- if (isLoading) {- CircularProgressIndicator(- modifier = Modifier.size(20.dp),- strokeWidth = 2.dp,- color = OnBackground.copy(alpha = 0.6f)- )- } else {- Text(text = text, style = MaterialTheme.typography.bodySmall, color = Color.White)- }- }- }-}--@Composable-private fun ImportOptionsButton(- text: String,- onClick: () -> Unit,- compact: Boolean = false,- modifier: Modifier = Modifier-) {- var isFocused by remember { mutableStateOf(false) }-- TvClickableSurface(- onClick = onClick,- modifier = modifier- .height(if (compact) 38.dp else 44.dp)- .onFocusEvent { isFocused = it.hasFocus }- .semantics { contentDescription = text },- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = Surface.copy(alpha = 0.9f),- focusedContainerColor = SurfaceHighlight- ),- border = ClickableSurfaceDefaults.border(- border = Border(BorderStroke(1.dp, if (isFocused) PrimaryLight else SurfaceHighlight)),- focusedBorder = Border(BorderStroke(2.dp, FocusBorder))- )- ) {- Row(- modifier = Modifier- .fillMaxSize()- .padding(horizontal = if (compact) 10.dp else 14.dp),- horizontalArrangement = Arrangement.Center,- verticalAlignment = Alignment.CenterVertically- ) {- Icon(- imageVector = Icons.Default.SettingsBackupRestore,- contentDescription = null,- modifier = Modifier.size(if (compact) 18.dp else 22.dp),- tint = if (isFocused) TextPrimary else OnSurface- )- Spacer(modifier = Modifier.width(if (compact) 6.dp else 8.dp))- Text(- text = text,- style = if (compact) MaterialTheme.typography.labelSmall else MaterialTheme.typography.labelMedium,- color = if (isFocused) TextPrimary else OnSurface- )- }- }-}--@Composable-private fun ImportOptionsDialog(- isImportingBackup: Boolean,- driveSignedIn: Boolean,- onDismiss: () -> Unit,- onImportBackup: () -> Unit,- onImportFromDrive: () -> Unit,- onDriveSignIn: () -> Unit-) {- PremiumDialog(- title = stringResource(R.string.settings_backup_restore),- subtitle = stringResource(R.string.settings_restore_subtitle),- onDismissRequest = onDismiss,- widthFraction = 0.34f,- heightFraction = null,- bodyHeightFraction = 0.28f,- content = {- Column(- verticalArrangement = Arrangement.spacedBy(12.dp),- horizontalAlignment = Alignment.CenterHorizontally,- modifier = Modifier.fillMaxWidth()- ) {- ImportDialogActionButton(- text = stringResource(R.string.setup_import_backup),- isLoading = isImportingBackup,- onClick = onImportBackup- )- if (driveSignedIn) {- ImportDialogActionButton(- text = stringResource(R.string.settings_drive_pull),- isLoading = isImportingBackup,- onClick = onImportFromDrive- )- } else {- ImportDialogActionButton(- text = stringResource(R.string.settings_drive_signin),- isLoading = false,- onClick = onDriveSignIn- )- }- }- },- footer = {- PremiumDialogFooterButton(- label = stringResource(R.string.add_group_cancel),- onClick = onDismiss- )- }- )-}--@Composable-private fun DriveBackupSnapshotChoiceDialog(- snapshots: List<DriveBackupSnapshot>,- onSelect: (String) -> Unit,- onDismiss: () -> Unit,-) {- PremiumDialog(- title = stringResource(R.string.settings_drive_choose_backup_title),- subtitle = stringResource(R.string.settings_drive_choose_backup_subtitle),- onDismissRequest = onDismiss,- widthFraction = 0.52f,- heightFraction = 0.82f,- bodyHeightFraction = 0.64f,- content = {- Column(- modifier = Modifier- .fillMaxWidth()- .verticalScroll(rememberScrollState()),- verticalArrangement = Arrangement.spacedBy(10.dp),- ) {- snapshots.forEach { snapshot ->- SmallActionButton(- text = snapshot.fileName,- isLoading = false,- onClick = { onSelect(snapshot.id) },- )- Text(- text = formatDriveSnapshotDetails(snapshot),- style = MaterialTheme.typography.bodySmall,- color = OnSurface.copy(alpha = 0.72f),- modifier = Modifier.padding(horizontal = 8.dp),- )- }- }- },- footer = {- PremiumDialogFooterButton(- label = stringResource(R.string.settings_drive_cancel_backup_choice),- onClick = onDismiss,- )- },- )-}--private fun formatDriveSnapshotDetails(snapshot: DriveBackupSnapshot): String {- val date = snapshot.modifiedAtMs?.let {- java.text.DateFormat.getDateTimeInstance(- java.text.DateFormat.SHORT,- java.text.DateFormat.SHORT,- ).format(java.util.Date(it))- } ?: "Date unavailable"- val size = if (snapshot.sizeBytes > 0L) "${snapshot.sizeBytes / 1024L} KB" else "Size unavailable"- return "$date · $size"-}--@Composable-private fun ImportDialogActionButton(- text: String,- isLoading: Boolean,- onClick: () -> Unit-) {- Box(modifier = Modifier.fillMaxWidth(0.72f)) {- SmallActionButton(- text = text,- isLoading = isLoading,- onClick = onClick- )- }-}--// ??? FileSelectorCard ?????????????????????????????????????????????????????????--@Composable-private fun FileSelectorCard(- fileName: String?,- fileSelectedHint: String,- emptySelectionTitle: String,- emptySelectionHint: String,- onClick: () -> Unit-) {- var isFocused by remember { mutableStateOf(false) }- val borderColor = if (isFocused) Primary else SurfaceHighlight- val bgColor = if (isFocused) Surface else SurfaceElevated-- Surface(- onClick = onClick,- modifier = Modifier.fillMaxWidth().height(80.dp).onFocusEvent { isFocused = it.hasFocus }.mouseClickable(onClick = onClick),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),- border = ClickableSurfaceDefaults.border(- border = Border(BorderStroke(1.dp, borderColor)),- focusedBorder = Border(BorderStroke(2.dp, FocusBorder))- ),- colors = ClickableSurfaceDefaults.colors(containerColor = bgColor, focusedContainerColor = bgColor)- ) {- Column(- modifier = Modifier.fillMaxSize().padding(16.dp),- verticalArrangement = Arrangement.Center,- horizontalAlignment = Alignment.CenterHorizontally- ) {- if (fileName != null) {- Text(text = fileName, style = MaterialTheme.typography.bodyLarge, color = OnBackground, textAlign = TextAlign.Center)- Text(text = fileSelectedHint, style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim)- } else {- Text(text = emptySelectionTitle, style = MaterialTheme.typography.bodyLarge, color = OnBackground)- Text(text = emptySelectionHint, style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim)- }- }- }-}--// ??? TabButton (used by SourceTypeTabRow) ?????????????????????????????????????--@Composable-private fun TabButton(text: String, isSelected: Boolean, onClick: () -> Unit, badge: String? = null) {- var isFocused by remember { mutableStateOf(false) }- Surface(- onClick = onClick,- modifier = Modifier.onFocusEvent { isFocused = it.hasFocus }.mouseClickable(onClick = onClick),- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),- colors = ClickableSurfaceDefaults.colors(- containerColor = if (isSelected) Primary.copy(alpha = 0.2f) else Surface,- focusedContainerColor = SurfaceHighlight- ),- border = ClickableSurfaceDefaults.border(- border = Border(BorderStroke(1.dp, if (isSelected) Primary.copy(alpha = 0.4f) else SurfaceHighlight)),- focusedBorder = Border(BorderStroke(2.dp, FocusBorder))- )- ) {- Row(- modifier = Modifier.padding(horizontal = 20.dp, vertical = 10.dp),- horizontalArrangement = Arrangement.spacedBy(8.dp),- verticalAlignment = Alignment.CenterVertically- ) {- Text(- text = text,- style = MaterialTheme.typography.bodySmall,- color = if (isSelected) Primary else if (isFocused) TextPrimary else OnSurface- )- badge?.let {- StatusPill(- label = it,- containerColor = AccentAmber,- contentColor = Color.Black,- horizontalPadding = 6.dp,- verticalPadding = 2.dp,- cornerRadius = 6.dp- )- }- }- }-}--// ─── Revealing password visual transformation ─────────────────────────────────--private class RevealingPasswordVisualTransformation(- private val revealedIndex: Int?-) : VisualTransformation {- override fun filter(text: AnnotatedString): TransformedText {- val transformed = buildString(text.length) {- text.text.forEachIndexed { index, ch ->- append(if (revealedIndex != null && index == revealedIndex) ch else '*')- }- }- return TransformedText(AnnotatedString(transformed), OffsetMapping.Identity)- }-}--// ─── File cleanup helpers ─────────────────────────────────────────────────────--private fun cleanupOldImportedM3uFiles(- filesDir: java.io.File,- protectedFileUris: Set<String>,- keepLatest: Int-) {- val protectedPaths = protectedFileUris- .mapNotNull { it.removePrefix("file://").takeIf { p -> p.isNotBlank() } }- .toSet()-- val importedFiles = filesDir- .listFiles { file ->- file.isFile && file.name.startsWith("m3u_") &&- (file.name.endsWith(".m3u") || file.name.endsWith(".m3u8"))- }- ?.sortedByDescending { it.lastModified() }- ?: return-- importedFiles.drop(keepLatest).forEach { stale ->- if (stale.absolutePath !in protectedPaths) runCatching { stale.delete() }- }-}--private suspend fun cleanupOldImportedM3uFilesAsync(- filesDir: java.io.File,- protectedFileUris: Set<String>,- keepLatest: Int-) = withContext(Dispatchers.IO) {- cleanupOldImportedM3uFiles(filesDir, protectedFileUris, keepLatest)-}--private fun resolveFileImportError(context: android.content.Context, error: Throwable): String {- val msg = error.message.orEmpty()- val isStorageFull = msg.contains("ENOSPC", ignoreCase = true) ||- msg.contains("no space", ignoreCase = true) ||- msg.contains("space left", ignoreCase = true)- return if (isStorageFull) context.getString(R.string.setup_file_import_storage_full)- else context.getString(R.string.setup_file_import_failed)-}+// ג”€ג”€ג”€ File cleanup helpers ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€ג”€// ??? Jellyfin form ?????????????????????????????????????????????????????????????--@Composable-private fun JellyfinProviderForm(- serverUrl: String,- onServerUrlChange: (String) -> Unit,- username: String,- onUsernameChange: (String) -> Unit,- password: String,- onPasswordChange: (String) -> Unit,- name: String,- onNameChange: (String) -> Unit,- quickConnectCode: String,- onQuickConnectRequest: () -> Unit,- isEditing: Boolean-) {- Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {- Text(- text = stringResource(R.string.setup_tab_jellyfin),- style = MaterialTheme.typography.titleLarge,- color = TextPrimary- )-- // Step 1: Server URL- ProviderTextField(- value = serverUrl,- onValueChange = onServerUrlChange,- placeholder = stringResource(R.string.setup_server_url)- )-- // Quick Connect button + QR code display- if (!isEditing) {- TvButton(- onClick = onQuickConnectRequest,- colors = ButtonDefaults.colors(containerColor = AccentCyan, contentColor = Color.Black)- ) {- Text(stringResource(R.string.setup_jellyfin_quick_connect))- }- }-- // QR code and code text (shown after quick connect is initiated)- if (quickConnectCode.isNotBlank()) {- Spacer(modifier = Modifier.height(8.dp))- val qrCodeBitmap = remember(quickConnectCode, serverUrl) {- generateJellyfinQuickConnectQrCode(serverUrl, quickConnectCode)- }- if (qrCodeBitmap != null) {- Box(- modifier = Modifier- .size(240.dp)- .background(Color.White, RoundedCornerShape(12.dp))- .padding(8.dp),- contentAlignment = Alignment.Center- ) {- Image(- bitmap = qrCodeBitmap.asImageBitmap(),- contentDescription = "Quick Connect QR Code",- modifier = Modifier.fillMaxSize()- )- }- Spacer(modifier = Modifier.height(8.dp))- }- Text(- text = stringResource(R.string.setup_jellyfin_quick_connect_code, quickConnectCode),- style = MaterialTheme.typography.bodyMedium,- color = TextSecondary- )- Text(- text = stringResource(R.string.setup_jellyfin_quick_connect_code_instructions),- style = MaterialTheme.typography.bodySmall,- color = TextTertiary- )- Spacer(modifier = Modifier.height(14.dp))- }-- // Step 2: Manual credentials (for password auth or existing provider edit)- ProviderTextField(- value = username,- onValueChange = onUsernameChange,- placeholder = stringResource(R.string.setup_username)- )- ProviderTextField(- value = password,- onValueChange = onPasswordChange,- placeholder = stringResource(R.string.setup_password),- isPassword = true- )- ProviderTextField(- value = name,- onValueChange = onNameChange,- placeholder = stringResource(R.string.setup_name_placeholder)- )- }-}--private fun generateJellyfinQuickConnectQrCode(serverUrl: String, code: String): Bitmap? {- return try {- val qrUrl = "${serverUrl.trimEnd('/')}/web/index.html#!/quickconnect.html?code=$code"- val writer = QRCodeWriter()- val bitMatrix = writer.encode(qrUrl, BarcodeFormat.QR_CODE, 512, 512)- val bitmap = Bitmap.createBitmap(512, 512, Bitmap.Config.RGB_565)- for (x in 0 until 512) {- for (y in 0 until 512) {- bitmap.setPixel(x, y, if (bitMatrix[x, y]) android.graphics.Color.BLACK else android.graphics.Color.WHITE)- }- }- bitmap- } catch (e: Exception) {- null- }-}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupSourceForms.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupSourceForms.ktnew file mode 100644index 00000000..6abee507--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupSourceForms.kt@@ -0,0 +1,227 @@+package com.streamvault.app.ui.screens.provider++import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.material3.Text+import androidx.compose.runtime.Composable+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.text.input.KeyboardCapitalization+import androidx.compose.ui.text.input.KeyboardType+import androidx.tv.material3.MaterialTheme+import com.streamvault.app.R+import com.streamvault.app.pairing.ProviderQrPairingState+import com.streamvault.app.ui.theme.ErrorColor+import com.streamvault.domain.model.StalkerAuthMode++@Composable+internal fun XtreamProviderForm(+ uiState: ProviderSetupState,+ isTelevisionDevice: Boolean,+ serverUrl: String,+ onServerUrlChange: (String) -> Unit,+ username: String,+ onUsernameChange: (String) -> Unit,+ password: String,+ onPasswordChange: (String) -> Unit,+ options: ProviderAdvancedOptions,+ onLogin: () -> Unit+) {+ ProviderTextField(+ value = serverUrl,+ onValueChange = onServerUrlChange,+ placeholder = stringResource(R.string.setup_server_hint),+ keyboardOptions = KeyboardOptions(+ capitalization = KeyboardCapitalization.None,+ autoCorrectEnabled = false,+ keyboardType = if (isTelevisionDevice) KeyboardType.Ascii else KeyboardType.Uri,+ imeAction = ImeAction.Next+ )+ )+ ProviderTextField(+ value = username,+ onValueChange = onUsernameChange,+ placeholder = stringResource(R.string.setup_user_hint),+ keyboardOptions = KeyboardOptions(+ capitalization = KeyboardCapitalization.None,+ autoCorrectEnabled = false,+ keyboardType = KeyboardType.Ascii,+ imeAction = ImeAction.Next+ )+ )+ ProviderTextField(+ value = password,+ onValueChange = onPasswordChange,+ placeholder = stringResource(R.string.setup_pass_hint),+ isPassword = true,+ keyboardOptions = KeyboardOptions(+ capitalization = KeyboardCapitalization.None,+ autoCorrectEnabled = false,+ keyboardType = if (isTelevisionDevice) KeyboardType.Ascii else KeyboardType.Password,+ imeAction = ImeAction.Done+ )+ )+ AdvancedProviderOptionsSection(options)+ FormErrors(uiState.validationError, uiState.error)+ ActionButton(+ text = when {+ uiState.isLoading -> stringResource(R.string.setup_connecting)+ uiState.isEditing -> stringResource(R.string.setup_save)+ else -> stringResource(R.string.setup_login)+ },+ isLoading = uiState.isLoading,+ onClick = onLogin+ )+}++@Composable+internal fun StalkerProviderForm(+ uiState: ProviderSetupState,+ isTelevisionDevice: Boolean,+ serverUrl: String,+ onServerUrlChange: (String) -> Unit,+ stalkerMacAddress: String,+ onStalkerMacAddressChange: (String) -> Unit,+ stalkerAuthMode: StalkerAuthMode,+ options: ProviderAdvancedOptions,+ onLogin: () -> Unit,+ onRepair: () -> Unit,+ onSelectProtocol: (com.streamvault.domain.model.StalkerProtocolPreference) -> Unit,+ onSelectProfile: (String) -> Unit+) {+ ProviderTextField(+ value = serverUrl,+ onValueChange = onServerUrlChange,+ placeholder = "Portal URL",+ keyboardOptions = KeyboardOptions(+ capitalization = KeyboardCapitalization.None,+ autoCorrectEnabled = false,+ keyboardType = if (isTelevisionDevice) KeyboardType.Ascii else KeyboardType.Uri,+ imeAction = ImeAction.Next+ )+ )+ ProviderTextField(+ value = stalkerMacAddress,+ onValueChange = onStalkerMacAddressChange,+ placeholder = if (stalkerAuthMode == StalkerAuthMode.CREDENTIALS_ONLY) {+ "MAC address (optional)"+ } else {+ "MAC address"+ },+ keyboardOptions = KeyboardOptions(+ capitalization = KeyboardCapitalization.Characters,+ autoCorrectEnabled = false,+ keyboardType = KeyboardType.Ascii,+ imeAction = ImeAction.Next+ )+ )+ StalkerCompatibilitySelector(+ protocol = uiState.stalkerProtocolPreference,+ profileId = uiState.stalkerRequestedProfileId,+ onProtocolSelected = onSelectProtocol,+ onProfileSelected = onSelectProfile+ )+ AdvancedProviderOptionsSection(options)+ FormErrors(uiState.validationError, uiState.error)+ ActionButton(+ text = when {+ uiState.isLoading -> stringResource(R.string.setup_connecting)+ uiState.isEditing -> stringResource(R.string.setup_save)+ else -> stringResource(R.string.setup_login)+ },+ isLoading = uiState.isLoading,+ onClick = onLogin+ )+ if (uiState.isEditing) {+ SmallActionButton(+ text = stringResource(R.string.stalker_repair_connection),+ isLoading = uiState.isLoading,+ onClick = onRepair+ )+ }+}++@Composable+internal fun M3uProviderForm(+ uiState: ProviderSetupState,+ m3uUrl: String,+ onM3uUrlChange: (String) -> Unit,+ fileImportError: String?,+ isFile: Boolean,+ onFilePick: () -> Unit,+ options: ProviderAdvancedOptions,+ onAdd: () -> Unit+) {+ if (isFile) {+ FileSelectorCard(+ fileName = if (m3uUrl.startsWith("file://")) m3uUrl.substringAfterLast("/") else null,+ fileSelectedHint = stringResource(R.string.setup_file_replace_hint),+ emptySelectionTitle = stringResource(R.string.setup_file_select_title),+ emptySelectionHint = stringResource(R.string.setup_file_browse_hint),+ onClick = onFilePick+ )+ fileImportError?.let {+ Text(text = it, style = MaterialTheme.typography.bodyMedium, color = ErrorColor)+ }+ } else {+ ProviderTextField(+ value = m3uUrl,+ onValueChange = onM3uUrlChange,+ placeholder = stringResource(R.string.setup_m3u_hint),+ keyboardOptions = KeyboardOptions(+ keyboardType = KeyboardType.Uri,+ imeAction = ImeAction.Done+ )+ )+ }+ AdvancedProviderOptionsSection(options)+ FormErrors(uiState.validationError, uiState.error)+ ActionButton(+ text = when {+ uiState.isLoading -> stringResource(R.string.setup_validating)+ uiState.isEditing -> stringResource(R.string.setup_save)+ else -> stringResource(R.string.setup_add)+ },+ isLoading = uiState.isLoading,+ onClick = onAdd+ )+}++@Composable+internal fun JellyfinProviderSetupForm(+ uiState: ProviderSetupState,+ serverUrl: String,+ onServerUrlChange: (String) -> Unit,+ username: String,+ onUsernameChange: (String) -> Unit,+ password: String,+ onPasswordChange: (String) -> Unit,+ name: String,+ onNameChange: (String) -> Unit,+ quickConnectCode: String,+ onQuickConnectRequest: () -> Unit,+ onLogin: () -> Unit+) {+ JellyfinProviderForm(+ serverUrl = serverUrl,+ onServerUrlChange = onServerUrlChange,+ username = username,+ onUsernameChange = onUsernameChange,+ password = password,+ onPasswordChange = onPasswordChange,+ name = name,+ onNameChange = onNameChange,+ quickConnectCode = quickConnectCode,+ onQuickConnectRequest = onQuickConnectRequest,+ isEditing = uiState.isEditing+ )+ FormErrors(uiState.validationError, uiState.error)+ ActionButton(+ text = when {+ uiState.isLoading -> stringResource(R.string.setup_validating)+ uiState.isEditing -> stringResource(R.string.setup_save)+ else -> stringResource(R.string.setup_add)+ },+ isLoading = uiState.isLoading,+ onClick = onLogin+ )+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupSourcePanel.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupSourcePanel.ktnew file mode 100644index 00000000..3dc16377--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupSourcePanel.kt@@ -0,0 +1,174 @@+package com.streamvault.app.ui.screens.provider++import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.layout.*+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.tv.material3.Border+import androidx.tv.material3.ClickableSurfaceDefaults+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Surface as TvSurface+import androidx.tv.material3.SurfaceDefaults+import androidx.tv.material3.Text+import com.streamvault.app.R+import com.streamvault.app.ui.components.shell.StatusPill+import com.streamvault.app.ui.interaction.mouseClickable+import com.streamvault.app.ui.theme.*++@Composable+internal fun SourceTypeSelectorPanel(+ sourceType: SourceType,+ isEditing: Boolean,+ isEditLabel: String,+ onSelect: (SourceType) -> Unit,+ onImportClick: () -> Unit,+ modifier: Modifier = Modifier+) {+ TvSurface(+ modifier = modifier,+ shape = RoundedCornerShape(20.dp),+ colors = SurfaceDefaults.colors(containerColor = Surface.copy(alpha = 0.92f))+ ) {+ Column(+ modifier = Modifier.fillMaxSize().padding(14.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ Text(+ text = isEditLabel,+ style = MaterialTheme.typography.titleMedium,+ color = TextPrimary+ )+ Text(+ text = androidx.compose.ui.res.stringResource(R.string.setup_shell_subtitle),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ Text(+ text = androidx.compose.ui.res.stringResource(R.string.setup_source_type_label),+ style = MaterialTheme.typography.labelSmall,+ color = TextTertiary+ )+ if (!isEditing || sourceType == SourceType.XTREAM) {+ SourceTypeCard(+ title = androidx.compose.ui.res.stringResource(R.string.setup_xtream),+ subtitle = androidx.compose.ui.res.stringResource(R.string.setup_info_xtream_body),+ selected = sourceType == SourceType.XTREAM,+ enabled = !isEditing,+ onClick = { onSelect(SourceType.XTREAM) }+ )+ }+ if (!isEditing || sourceType == SourceType.STALKER) {+ SourceTypeCard(+ title = androidx.compose.ui.res.stringResource(R.string.setup_stalker),+ badge = androidx.compose.ui.res.stringResource(R.string.badge_beta),+ subtitle = androidx.compose.ui.res.stringResource(R.string.setup_info_stalker_body),+ selected = sourceType == SourceType.STALKER,+ enabled = !isEditing,+ onClick = { onSelect(SourceType.STALKER) }+ )+ }+ if (!isEditing || sourceType == SourceType.M3U_URL) {+ SourceTypeCard(+ title = androidx.compose.ui.res.stringResource(R.string.setup_tab_url),+ subtitle = androidx.compose.ui.res.stringResource(R.string.setup_info_m3u_body),+ selected = sourceType == SourceType.M3U_URL,+ enabled = !isEditing,+ onClick = { onSelect(SourceType.M3U_URL) }+ )+ }+ if (!isEditing || sourceType == SourceType.M3U_FILE) {+ SourceTypeCard(+ title = androidx.compose.ui.res.stringResource(R.string.setup_tab_file),+ subtitle = androidx.compose.ui.res.stringResource(R.string.setup_file_browse_hint),+ selected = sourceType == SourceType.M3U_FILE,+ enabled = !isEditing,+ onClick = { onSelect(SourceType.M3U_FILE) }+ )+ }+ if (!isEditing || sourceType == SourceType.JELLYFIN) {+ SourceTypeCard(+ title = androidx.compose.ui.res.stringResource(R.string.setup_tab_jellyfin),+ subtitle = "Jellyfin media server",+ selected = sourceType == SourceType.JELLYFIN,+ enabled = !isEditing,+ onClick = { onSelect(SourceType.JELLYFIN) }+ )+ }+ if (!isEditing) {+ ImportOptionsButton(+ text = stringResource(R.string.settings_restore_data),+ onClick = onImportClick,+ compact = true,+ modifier = Modifier.fillMaxWidth()+ )+ }+ Spacer(modifier = Modifier.weight(1f))+ Text(+ text = androidx.compose.ui.res.stringResource(R.string.setup_info_manage_title),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ Text(+ text = androidx.compose.ui.res.stringResource(R.string.setup_info_manage_body),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim.copy(alpha = 0.55f)+ )+ }+ }+}++@Composable+internal fun SourceTypeCard(+ title: String,+ badge: String? = null,+ subtitle: String,+ selected: Boolean,+ enabled: Boolean,+ onClick: () -> Unit+) {+ TvSurface(+ onClick = { if (enabled) onClick() },+ modifier = Modifier.fillMaxWidth().mouseClickable(enabled = enabled, onClick = onClick),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (selected) Primary.copy(alpha = 0.18f) else SurfaceElevated,+ focusedContainerColor = if (selected) Primary.copy(alpha = 0.28f) else SurfaceHighlight+ ),+ border = ClickableSurfaceDefaults.border(+ border = Border(BorderStroke(1.dp, if (selected) Primary.copy(alpha = 0.5f) else SurfaceHighlight)),+ focusedBorder = Border(BorderStroke(2.dp, FocusBorder))+ )+ ) {+ Column(+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),+ verticalArrangement = Arrangement.spacedBy(3.dp)+ ) {+ Row(+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(+ text = title,+ style = MaterialTheme.typography.bodyMedium,+ color = if (selected) Primary else TextPrimary+ )+ badge?.let {+ StatusPill(+ label = it,+ containerColor = AccentAmber,+ contentColor = Color.Black,+ horizontalPadding = 6.dp,+ verticalPadding = 2.dp,+ cornerRadius = 6.dp+ )+ }+ }+ Text(text = subtitle, style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim, maxLines = 2)+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupSourceSelector.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupSourceSelector.ktnew file mode 100644index 00000000..91ee2896--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupSourceSelector.kt@@ -0,0 +1,120 @@+package com.streamvault.app.ui.screens.provider++import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.onFocusEvent+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.unit.dp+import androidx.tv.material3.Border+import androidx.tv.material3.ClickableSurfaceDefaults+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Surface+import androidx.tv.material3.Text+import com.streamvault.app.R+import com.streamvault.app.ui.components.shell.StatusPill+import com.streamvault.app.ui.interaction.mouseClickable+import com.streamvault.app.ui.theme.AccentAmber+import com.streamvault.app.ui.theme.FocusBorder+import com.streamvault.app.ui.theme.OnSurface+import com.streamvault.app.ui.theme.Primary+import com.streamvault.app.ui.theme.Surface as SurfaceColor+import com.streamvault.app.ui.theme.SurfaceHighlight+import com.streamvault.app.ui.theme.TextPrimary++internal enum class SourceType { XTREAM, STALKER, M3U_URL, M3U_FILE, JELLYFIN }++@Composable+internal fun SourceTypeTabRow(+ sourceType: SourceType,+ isEditing: Boolean,+ onSelect: (SourceType) -> Unit,+ modifier: Modifier = Modifier+) {+ Row(modifier = modifier, horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ if (!isEditing || sourceType == SourceType.XTREAM) {+ TabButton(+ text = androidx.compose.ui.res.stringResource(R.string.setup_xtream),+ isSelected = sourceType == SourceType.XTREAM,+ onClick = { if (!isEditing) onSelect(SourceType.XTREAM) }+ )+ }+ if (!isEditing || sourceType == SourceType.STALKER) {+ TabButton(+ text = androidx.compose.ui.res.stringResource(R.string.setup_stalker),+ badge = androidx.compose.ui.res.stringResource(R.string.badge_beta),+ isSelected = sourceType == SourceType.STALKER,+ onClick = { if (!isEditing) onSelect(SourceType.STALKER) }+ )+ }+ if (!isEditing || sourceType == SourceType.M3U_URL) {+ TabButton(+ text = androidx.compose.ui.res.stringResource(R.string.setup_tab_url),+ isSelected = sourceType == SourceType.M3U_URL,+ onClick = { if (!isEditing) onSelect(SourceType.M3U_URL) }+ )+ }+ if (!isEditing || sourceType == SourceType.M3U_FILE) {+ TabButton(+ text = androidx.compose.ui.res.stringResource(R.string.setup_tab_file),+ isSelected = sourceType == SourceType.M3U_FILE,+ onClick = { if (!isEditing) onSelect(SourceType.M3U_FILE) }+ )+ }+ if (!isEditing || sourceType == SourceType.JELLYFIN) {+ TabButton(+ text = androidx.compose.ui.res.stringResource(R.string.setup_tab_jellyfin),+ isSelected = sourceType == SourceType.JELLYFIN,+ onClick = { if (!isEditing) onSelect(SourceType.JELLYFIN) }+ )+ }+ }+}++@Composable+private fun TabButton(text: String, isSelected: Boolean, onClick: () -> Unit, badge: String? = null) {+ var isFocused by remember { mutableStateOf(false) }+ Surface(+ onClick = onClick,+ modifier = Modifier.onFocusEvent { isFocused = it.hasFocus }.mouseClickable(onClick = onClick),+ shape = ClickableSurfaceDefaults.shape(androidx.compose.foundation.shape.RoundedCornerShape(10.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (isSelected) Primary.copy(alpha = 0.2f) else SurfaceColor,+ focusedContainerColor = SurfaceHighlight+ ),+ border = ClickableSurfaceDefaults.border(+ border = Border(BorderStroke(1.dp, if (isSelected) Primary.copy(alpha = 0.4f) else SurfaceHighlight)),+ focusedBorder = Border(BorderStroke(2.dp, FocusBorder))+ )+ ) {+ Row(+ modifier = Modifier.padding(horizontal = 20.dp, vertical = 10.dp),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text(+ text = text,+ style = MaterialTheme.typography.bodySmall,+ color = if (isSelected) Primary else if (isFocused) TextPrimary else OnSurface+ )+ badge?.let {+ StatusPill(+ label = it,+ containerColor = AccentAmber,+ contentColor = Color.Black,+ horizontalPadding = 6.dp,+ verticalPadding = 2.dp,+ cornerRadius = 6.dp+ )+ }+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupStalkerCompatibilitySelector.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupStalkerCompatibilitySelector.ktnew file mode 100644index 00000000..1fbb11e9--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupStalkerCompatibilitySelector.kt@@ -0,0 +1,109 @@+package com.streamvault.app.ui.screens.provider++import androidx.compose.animation.AnimatedVisibility+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.unit.dp+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.streamvault.app.ui.theme.AccentAmber+import com.streamvault.app.ui.theme.OnBackground+import com.streamvault.data.remote.stalker.StalkerCompatibilityRegistry+import com.streamvault.domain.model.StalkerCompatibilityProfileIds+import com.streamvault.domain.model.StalkerProfileVerification+import com.streamvault.domain.model.StalkerProtocolPreference++@Composable+internal fun StalkerCompatibilitySelector(+ protocol: StalkerProtocolPreference,+ profileId: String,+ onProtocolSelected: (StalkerProtocolPreference) -> Unit,+ onProfileSelected: (String) -> Unit+) {+ var showProtocols by rememberSaveable { mutableStateOf(false) }+ var showProfiles by rememberSaveable { mutableStateOf(false) }+ val selectedProfile = StalkerCompatibilityRegistry.find(profileId)++ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+ Text("Compatibility", style = MaterialTheme.typography.titleSmall, color = OnBackground)+ SmallActionButton(+ text = "Protocol: ${protocol.name.replace('_', ' ')}",+ onClick = { showProtocols = !showProtocols }+ )+ AnimatedVisibility(showProtocols) {+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {+ StalkerProtocolPreference.entries+ .filterNot { it == StalkerProtocolPreference.MINISTRA_API_V3 }+ .forEach { option ->+ SmallActionButton(+ text = if (option == protocol) "✓ ${option.name.replace('_', ' ')}" else option.name.replace('_', ' '),+ onClick = {+ onProtocolSelected(option)+ onProfileSelected(StalkerCompatibilityProfileIds.AUTO)+ showProtocols = false+ }+ )+ }+ }+ }+ SmallActionButton(+ text = "Model: ${selectedProfile?.displayName ?: "Automatic"}",+ onClick = { showProfiles = !showProfiles }+ )+ AnimatedVisibility(showProfiles) {+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {+ SmallActionButton(+ text = if (profileId == StalkerCompatibilityProfileIds.AUTO) "✓ Automatic" else "Automatic",+ onClick = {+ onProfileSelected(StalkerCompatibilityProfileIds.AUTO)+ showProfiles = false+ }+ )+ val family = if (protocol == StalkerProtocolPreference.MINISTRA_API_V3) {+ com.streamvault.domain.model.StalkerProtocolFamily.MINISTRA_API_V3+ } else {+ com.streamvault.domain.model.StalkerProtocolFamily.CLASSIC_MAG+ }+ StalkerCompatibilityRegistry.profiles+ .filter { it.protocolFamily == family }+ .groupBy { it.generation }+ .forEach { (generation, profiles) ->+ Text(generation, style = MaterialTheme.typography.labelMedium, color = OnBackground.copy(alpha = 0.72f))+ profiles.forEach { option ->+ val experimental = option.verification == StalkerProfileVerification.EXPERIMENTAL+ SmallActionButton(+ text = buildString {+ if (option.id == profileId) append("✓ ")+ append(option.displayName)+ if (experimental) append(" — EXPERIMENTAL")+ },+ onClick = {+ onProfileSelected(option.id)+ showProfiles = false+ }+ )+ }+ }+ if (family == com.streamvault.domain.model.StalkerProtocolFamily.CLASSIC_MAG) {+ Text(+ "Experimental profiles require captured/manual identity fields and are excluded from automatic discovery.",+ style = MaterialTheme.typography.bodySmall,+ color = AccentAmber+ )+ SmallActionButton(+ text = if (profileId == StalkerCompatibilityProfileIds.CUSTOM) "✓ Custom profile" else "Custom profile",+ onClick = {+ onProfileSelected(StalkerCompatibilityProfileIds.CUSTOM)+ showProfiles = false+ }+ )+ }+ }+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupStalkerRules.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupStalkerRules.ktnew file mode 100644index 00000000..1db0a346--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupStalkerRules.kt@@ -0,0 +1,198 @@+package com.streamvault.app.ui.screens.provider++import androidx.compose.foundation.BorderStroke+import androidx.compose.foundation.background+import androidx.compose.foundation.border+import androidx.compose.foundation.layout.*+import androidx.compose.foundation.relocation.BringIntoViewRequester+import androidx.compose.foundation.relocation.bringIntoViewRequester+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Switch+import androidx.compose.runtime.*+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.tv.material3.Border+import androidx.tv.material3.ClickableSurfaceDefaults+import androidx.tv.material3.Glow+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Surface as TvSurface+import androidx.tv.material3.Text+import com.streamvault.app.ui.interaction.TvClickableSurface+import com.streamvault.app.ui.interaction.mouseClickable+import com.streamvault.app.ui.theme.*+import kotlinx.coroutines.delay++@Composable+internal fun StalkerLinkOptionButton(+ text: String,+ selected: Boolean,+ onClick: () -> Unit+) {+ TvSurface(+ onClick = onClick,+ modifier = Modifier.mouseClickable(onClick = onClick),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (selected) Primary.copy(alpha = 0.18f) else Surface,+ focusedContainerColor = Primary.copy(alpha = 0.28f)+ ),+ border = ClickableSurfaceDefaults.border(+ border = Border(BorderStroke(1.dp, if (selected) Primary else SurfaceHighlight)),+ focusedBorder = Border(BorderStroke(3.dp, PrimaryLight))+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Text(+ text = text,+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp),+ style = MaterialTheme.typography.bodySmall,+ color = TextPrimary+ )+ }+}++@Composable+internal fun StalkerRequestRulesEditor(+ rules: List<StalkerRequestRuleUiState>,+ onAddRule: () -> Unit,+ onUpdateRule: (Int, StalkerRequestRuleUiState) -> Unit,+ onRemoveRule: (Int) -> Unit+) {+ val newestRuleBringIntoViewRequester = remember { BringIntoViewRequester() }+ var previousRuleCount by remember { mutableIntStateOf(rules.size) }++ LaunchedEffect(rules.size) {+ if (rules.size > previousRuleCount) {+ delay(120)+ runCatching { newestRuleBringIntoViewRequester.bringIntoView() }+ }+ previousRuleCount = rules.size+ }++ Column(+ modifier = Modifier+ .fillMaxWidth()+ .background(Surface, RoundedCornerShape(12.dp))+ .border(1.dp, SurfaceHighlight, RoundedCornerShape(12.dp))+ .padding(12.dp),+ verticalArrangement = Arrangement.spacedBy(10.dp)+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Column(modifier = Modifier.weight(1f)) {+ Text("Request rules", style = MaterialTheme.typography.titleSmall, color = TextPrimary)+ Text(+ "Match by action, block calls, or override params. Blank values remove params.",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ RequestRuleActionButton(text = "Add Rule", onClick = onAddRule)+ }+ rules.forEachIndexed { index, rule ->+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .then(+ if (index == rules.lastIndex) {+ Modifier.bringIntoViewRequester(newestRuleBringIntoViewRequester)+ } else {+ Modifier+ }+ )+ .border(1.dp, SurfaceHighlight.copy(alpha = 0.7f), RoundedCornerShape(10.dp))+ .padding(10.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp)+ ) {+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text("Rule ${index + 1}", style = MaterialTheme.typography.bodyMedium, color = TextPrimary)+ RequestRuleActionButton(+ text = "Delete",+ onClick = { onRemoveRule(index) },+ compact = true+ )+ }+ ProviderTextField(+ value = rule.action,+ onValueChange = { onUpdateRule(index, rule.copy(action = it.trim())) },+ placeholder = "action, e.g. get_profile"+ )+ Row(+ modifier = Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically+ ) {+ Text("Block this request", style = MaterialTheme.typography.bodySmall, color = TextPrimary)+ Switch(+ checked = rule.blockRequest,+ onCheckedChange = { onUpdateRule(index, rule.copy(blockRequest = it)) }+ )+ }+ if (rule.blockRequest && rule.action.trim() in setOf("handshake", "get_profile")) {+ Text(+ text = "Warning: blocking ${rule.action.trim()} can prevent login.",+ style = MaterialTheme.typography.bodySmall,+ color = AccentAmber+ )+ }+ ProviderTextField(+ value = rule.paramsText,+ onValueChange = { onUpdateRule(index, rule.copy(paramsText = it)) },+ placeholder = "Param overrides: name=value | remove_me="+ )+ }+ }+ }+}++@Composable+internal fun RequestRuleActionButton(+ text: String,+ onClick: () -> Unit,+ compact: Boolean = false+) {+ TvClickableSurface(+ onClick = onClick,+ modifier = Modifier+ .width(if (compact) 88.dp else 124.dp)+ .height(40.dp)+ .mouseClickable(onClick = onClick)+ .semantics { contentDescription = text },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = if (compact) SurfaceHighlight.copy(alpha = 0.9f) else Primary,+ focusedContainerColor = if (compact) SurfaceHighlight else PrimaryLight+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),+ glow = ClickableSurfaceDefaults.glow(focusedGlow = Glow.None),+ border = ClickableSurfaceDefaults.border(+ border = Border(+ BorderStroke(+ 1.dp,+ if (compact) SurfaceHighlight.copy(alpha = 0.8f) else PrimaryLight+ )+ ),+ focusedBorder = Border(BorderStroke(3.dp, FocusBorder))+ )+ ) {+ Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {+ Text(+ text = text,+ style = MaterialTheme.typography.bodySmall,+ color = TextPrimary,+ textAlign = TextAlign.Center+ )+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupSyncDialog.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupSyncDialog.ktnew file mode 100644index 00000000..ea5439ec--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupSyncDialog.kt@@ -0,0 +1,141 @@+package com.streamvault.app.ui.screens.provider++import androidx.compose.animation.core.animateFloatAsState+import androidx.compose.animation.core.tween+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.LinearProgressIndicator+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.dp+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.streamvault.app.R+import com.streamvault.app.ui.components.dialogs.PremiumDialog+import com.streamvault.app.ui.components.extractProgressFraction+import com.streamvault.app.ui.components.shell.StatusPill+import com.streamvault.app.ui.theme.*++@Composable+fun SyncProgressDialog(+ message: String,+ quickConnectCode: String? = null,+ serverUrl: String? = null,+ onCancel: (() -> Unit)? = null+) {+ if (quickConnectCode != null && serverUrl != null) {+ val qrCodeBitmap = remember(quickConnectCode, serverUrl) {+ generateJellyfinQuickConnectQrCode(serverUrl, quickConnectCode)+ }+ PremiumDialog(+ title = "Quick Connect",+ subtitle = "Enter this code on your Jellyfin server",+ onDismissRequest = {},+ widthFraction = 0.38f,+ heightFraction = null,+ content = {+ Column(+ modifier = Modifier.fillMaxWidth(),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(12.dp)+ ) {+ if (qrCodeBitmap != null) {+ Box(+ modifier = Modifier+ .size(200.dp)+ .background(Color.White, RoundedCornerShape(12.dp))+ .padding(8.dp),+ contentAlignment = Alignment.Center+ ) {+ Image(+ bitmap = qrCodeBitmap.asImageBitmap(),+ contentDescription = "Quick Connect QR Code",+ modifier = Modifier.fillMaxSize()+ )+ }+ }+ Text(+ text = stringResource(R.string.setup_jellyfin_quick_connect_code, quickConnectCode),+ style = MaterialTheme.typography.headlineMedium,+ color = Color.White+ )+ Text(+ text = message,+ style = MaterialTheme.typography.bodyMedium,+ color = TextSecondary,+ textAlign = TextAlign.Center+ )+ if (onCancel != null) {+ TextButton(onClick = onCancel) {+ Text("Cancel", color = Color.White)+ }+ }+ }+ }+ )+ } else {+ val fraction = extractProgressFraction(message)+ val animatedFraction by animateFloatAsState(+ targetValue = fraction ?: 0f,+ animationSpec = tween(durationMillis = 400),+ label = "syncFraction"+ )+ PremiumDialog(+ title = androidx.compose.ui.res.stringResource(R.string.settings_syncing_title),+ subtitle = androidx.compose.ui.res.stringResource(R.string.settings_syncing_subtitle),+ onDismissRequest = {},+ widthFraction = 0.32f,+ heightFraction = null,+ content = {+ Column(+ modifier = Modifier.fillMaxWidth(),+ horizontalAlignment = Alignment.CenterHorizontally,+ verticalArrangement = Arrangement.spacedBy(16.dp)+ ) {+ CircularProgressIndicator(color = Primary)+ StatusPill(+ label = androidx.compose.ui.res.stringResource(R.string.settings_syncing_btn),+ containerColor = PrimaryGlow+ )+ if (fraction != null) {+ LinearProgressIndicator(+ progress = { animatedFraction },+ color = Primary,+ modifier = Modifier.fillMaxWidth()+ )+ } else {+ LinearProgressIndicator(+ color = Primary,+ modifier = Modifier.fillMaxWidth()+ )+ }+ Text(+ text = message,+ style = MaterialTheme.typography.bodyMedium,+ color = OnBackground,+ textAlign = TextAlign.Center+ )+ }+ }+ )+ }+}++// ??? ActionButton ?????????????????????????????????????????????????????????????diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupTextField.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupTextField.ktnew file mode 100644index 00000000..b74c99f4--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupTextField.kt@@ -0,0 +1,306 @@+package com.streamvault.app.ui.screens.provider++import androidx.compose.foundation.*+import androidx.compose.animation.animateColorAsState+import androidx.compose.animation.core.tween+import androidx.compose.foundation.layout.*+import androidx.compose.foundation.relocation.BringIntoViewRequester+import androidx.compose.foundation.relocation.bringIntoViewRequester+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.KeyboardActions+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.runtime.*+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.*+import androidx.compose.ui.graphics.*+import androidx.compose.ui.unit.dp+import androidx.compose.ui.input.key.onPreviewKeyEvent+import androidx.compose.ui.platform.LocalSoftwareKeyboardController+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semantics+import androidx.compose.ui.text.TextRange+import androidx.compose.ui.text.input.*+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.streamvault.app.R+import com.streamvault.app.device.rememberIsTelevisionDevice+import com.streamvault.app.ui.interaction.mouseClickable+import com.streamvault.app.ui.theme.*+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch++@Composable+internal fun ProviderTextField(+ value: String,+ onValueChange: (String) -> Unit,+ placeholder: String,+ modifier: Modifier = Modifier,+ isPassword: Boolean = false,+ keyboardOptions: KeyboardOptions = KeyboardOptions.Default,+ keyboardActions: KeyboardActions = KeyboardActions.Default+) {+ val isTelevisionDevice = rememberIsTelevisionDevice()+ var hasContainerFocus by remember { mutableStateOf(false) }+ var hasInputFocus by remember { mutableStateOf(false) }+ var acceptsInput by remember(isTelevisionDevice) { mutableStateOf(!isTelevisionDevice) }+ var pendingInputActivation by remember { mutableStateOf(false) }+ var editBaselineValue by remember { mutableStateOf(value) }+ var fieldValue by remember {+ mutableStateOf(TextFieldValue(text = value, selection = TextRange(value.length)))+ }+ var isPasswordVisible by rememberSaveable(isPassword) { mutableStateOf(false) }+ var revealedPasswordIndex by remember { mutableStateOf<Int?>(null) }+ var previousValue by remember { mutableStateOf(value) }+ val containerFocusRequester = remember { FocusRequester() }+ val inputFocusRequester = remember { FocusRequester() }+ val visibilityToggleFocusRequester = remember { FocusRequester() }+ val keyboardController = LocalSoftwareKeyboardController.current+ val bringIntoViewRequester = remember { BringIntoViewRequester() }+ val coroutineScope = rememberCoroutineScope()+ val isFocused = hasContainerFocus || hasInputFocus+ val passwordVisibilityDescription = if (isPassword) {+ androidx.compose.ui.res.stringResource(+ if (isPasswordVisible) R.string.setup_hide_password else R.string.setup_show_password+ )+ } else {+ null+ }++ fun activateInput() {+ if (!acceptsInput) {+ editBaselineValue = value+ }+ if (!isTelevisionDevice) {+ acceptsInput = true+ inputFocusRequester.requestFocus()+ keyboardController?.show()+ coroutineScope.launch {+ runCatching { bringIntoViewRequester.bringIntoView() }+ delay(180)+ runCatching { bringIntoViewRequester.bringIntoView() }+ }+ return+ }+ acceptsInput = true+ pendingInputActivation = true+ coroutineScope.launch {+ runCatching { bringIntoViewRequester.bringIntoView() }+ }+ }++ LaunchedEffect(value) {+ if (value != fieldValue.text) {+ val coercedSelectionStart = fieldValue.selection.start.coerceIn(0, value.length)+ val coercedSelectionEnd = fieldValue.selection.end.coerceIn(0, value.length)+ val coercedComposition = fieldValue.composition?.let { composition ->+ val compositionStart = composition.start.coerceIn(0, value.length)+ val compositionEnd = composition.end.coerceIn(0, value.length)+ if (compositionStart <= compositionEnd) {+ TextRange(compositionStart, compositionEnd)+ } else {+ null+ }+ }+ fieldValue = fieldValue.copy(+ text = value,+ selection = TextRange(coercedSelectionStart, coercedSelectionEnd),+ composition = coercedComposition+ )+ }+ }++ LaunchedEffect(acceptsInput, pendingInputActivation) {+ if (!isTelevisionDevice || !acceptsInput || !pendingInputActivation) {+ return@LaunchedEffect+ }+ inputFocusRequester.requestFocus()+ keyboardController?.show()+ coroutineScope.launch {+ delay(120)+ runCatching { bringIntoViewRequester.bringIntoView() }+ }+ pendingInputActivation = false+ }++ LaunchedEffect(isPassword) {+ if (!isPassword) {+ isPasswordVisible = false+ }+ }++ // Show most-recently typed character briefly before masking+ LaunchedEffect(value, isPassword) {+ if (!isPassword) { previousValue = value; revealedPasswordIndex = null; return@LaunchedEffect }+ revealedPasswordIndex = when {+ value.length > previousValue.length && value.isNotEmpty() -> value.lastIndex+ value.isEmpty() -> null+ else -> revealedPasswordIndex?.takeIf { it < value.length }+ }+ previousValue = value+ }+ LaunchedEffect(revealedPasswordIndex, value, isPassword) {+ val idx = revealedPasswordIndex ?: return@LaunchedEffect+ if (!isPassword || idx >= value.length) return@LaunchedEffect+ delay(1500)+ if (revealedPasswordIndex == idx) revealedPasswordIndex = null+ }++ val borderColor by animateColorAsState(if (isFocused) Primary else SurfaceHighlight, tween(150), label = "border")+ val bgColor by animateColorAsState(if (isFocused) Surface else SurfaceElevated, tween(150), label = "bg")++ Box(+ modifier = modifier+ .fillMaxWidth()+ .focusRequester(containerFocusRequester)+ .bringIntoViewRequester(bringIntoViewRequester)+ .onFocusEvent {+ hasContainerFocus = it.hasFocus+ if (!it.hasFocus && isTelevisionDevice) {+ acceptsInput = false+ keyboardController?.hide()+ }+ }+ .mouseClickable(focusRequester = containerFocusRequester, onClick = ::activateInput)+ .clickable(onClick = ::activateInput)+ .focusable()+ .padding(0.dp)+ ) {+ androidx.compose.foundation.text.BasicTextField(+ value = fieldValue,+ onValueChange = { updatedValue ->+ fieldValue = updatedValue+ if (updatedValue.text != value) {+ onValueChange(updatedValue.text)+ }+ },+ modifier = Modifier+ .fillMaxWidth()+ .focusRequester(inputFocusRequester)+ .focusProperties {+ canFocus = !isTelevisionDevice || acceptsInput+ if (isTelevisionDevice && acceptsInput) {+ left = FocusRequester.Cancel+ right = if (isPassword) visibilityToggleFocusRequester else FocusRequester.Cancel+ }+ }+ .onPreviewKeyEvent { event ->+ if (!isTelevisionDevice || !acceptsInput || event.nativeKeyEvent.action != android.view.KeyEvent.ACTION_DOWN) {+ return@onPreviewKeyEvent false+ }+ val cursor = fieldValue.selection.end+ when (event.nativeKeyEvent.keyCode) {+ android.view.KeyEvent.KEYCODE_BACK -> {+ fieldValue = TextFieldValue(+ text = editBaselineValue,+ selection = TextRange(editBaselineValue.length)+ )+ if (editBaselineValue != value) {+ onValueChange(editBaselineValue)+ }+ acceptsInput = false+ pendingInputActivation = false+ keyboardController?.hide()+ containerFocusRequester.requestFocus()+ true+ }+ android.view.KeyEvent.KEYCODE_DPAD_LEFT -> {+ val nextCursor = (cursor - 1).coerceAtLeast(0)+ fieldValue = fieldValue.copy(selection = TextRange(nextCursor))+ true+ }+ android.view.KeyEvent.KEYCODE_DPAD_RIGHT -> {+ if (isPassword && cursor >= fieldValue.text.length) {+ visibilityToggleFocusRequester.requestFocus()+ return@onPreviewKeyEvent true+ }+ val nextCursor = (cursor + 1).coerceAtMost(fieldValue.text.length)+ fieldValue = fieldValue.copy(selection = TextRange(nextCursor))+ true+ }+ else -> false+ }+ }+ .onFocusEvent {+ hasInputFocus = it.hasFocus+ if (it.hasFocus) {+ coroutineScope.launch {+ delay(120)+ runCatching { bringIntoViewRequester.bringIntoView() }+ }+ } else if (isTelevisionDevice) {+ keyboardController?.hide()+ }+ },+ singleLine = true,+ readOnly = isTelevisionDevice && !acceptsInput,+ keyboardOptions = keyboardOptions,+ keyboardActions = keyboardActions,+ textStyle = MaterialTheme.typography.bodyMedium.copy(color = OnBackground),+ visualTransformation = when {+ !isPassword || isPasswordVisible -> VisualTransformation.None+ else -> RevealingPasswordVisualTransformation(revealedPasswordIndex)+ },+ cursorBrush = SolidColor(Primary),+ decorationBox = { innerTextField ->+ Row(+ modifier = Modifier+ .background(bgColor, RoundedCornerShape(10.dp))+ .border(if (isFocused) 2.dp else 1.dp, borderColor, RoundedCornerShape(10.dp))+ .padding(horizontal = 16.dp, vertical = 14.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ Box(+ modifier = Modifier.weight(1f),+ contentAlignment = Alignment.CenterStart+ ) {+ if (fieldValue.text.isEmpty()) {+ Text(text = placeholder, style = MaterialTheme.typography.bodyMedium, color = OnSurfaceDim)+ }+ innerTextField()+ }++ if (isPassword) {+ Box(+ modifier = Modifier+ .padding(start = 12.dp)+ .size(24.dp)+ .focusRequester(visibilityToggleFocusRequester)+ .focusProperties {+ canFocus = !isTelevisionDevice || acceptsInput+ left = inputFocusRequester+ }+ .onFocusEvent {+ if (it.hasFocus) {+ coroutineScope.launch {+ delay(120)+ runCatching { bringIntoViewRequester.bringIntoView() }+ }+ }+ }+ .semantics {+ contentDescription = passwordVisibilityDescription.orEmpty()+ }+ .clickable {+ isPasswordVisible = !isPasswordVisible+ }+ .mouseClickable(focusRequester = visibilityToggleFocusRequester) {+ isPasswordVisible = !isPasswordVisible+ }+ .focusable(enabled = !isTelevisionDevice || acceptsInput)+ ) {+ PasswordVisibilityGlyph(+ isVisible = isPasswordVisible,+ tint = if (isFocused) Primary else OnSurfaceDim,+ modifier = Modifier.align(Alignment.Center)+ )+ }+ }+ }+ }+ )+ }+}++// ??? Sync progress dialog ?????????????????????????????????????????????????????diff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerBackNavigationPolicyTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerBackNavigationPolicyTest.ktindex 104447fd..064bde0b 100644--- a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerBackNavigationPolicyTest.kt+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerBackNavigationPolicyTest.kt@@ -16,6 +16,22 @@ class PlayerBackNavigationPolicyTest {assertThat(playerBackAction(state)).isEqualTo(PlayerBackAction.CLEAR_NUMERIC_CHANNEL_INPUT)}+ @Test+ fun `event-time Back decision sees numeric input added after the previous composition`() {+ var hasPendingNumericInput = false+ val stateProvider = {+ PlayerBackNavigationState(hasPendingNumericChannelInput = hasPendingNumericInput)+ }++ assertThat(playerBackActionAtEvent(stateProvider))+ .isEqualTo(PlayerBackAction.NAVIGATE_BACK)++ hasPendingNumericInput = true++ assertThat(playerBackActionAtEvent(stateProvider))+ .isEqualTo(PlayerBackAction.CLEAR_NUMERIC_CHANNEL_INPUT)+ }+@Testfun `dialogs close before live overlays`() {val state = PlayerBackNavigationState(diff --git a/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerInputPolicyTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerInputPolicyTest.ktnew file mode 100644index 00000000..9514a465--- /dev/null+++ b/app/src/test/java/com/streamvault/app/ui/screens/player/PlayerInputPolicyTest.kt@@ -0,0 +1,241 @@+package com.streamvault.app.ui.screens.player++import com.google.common.truth.Truth.assertThat+import org.junit.Test++class PlayerInputPolicyTest {++ @Test+ fun `preview zaps live channels and reports channel info interaction`() {+ val decision = playerPreviewInputDecision(+ state = liveState(showChannelInfoOverlay = true),+ key = PlayerInputKey.DpadUp+ )++ assertThat(decision.action).isEqualTo(PlayerInputAction.PlayNext)+ assertThat(decision.notifyLiveOverlayInteraction).isTrue()+ }++ @Test+ fun `preview blocks zapping while a modal is visible`() {+ val decision = playerPreviewInputDecision(+ state = liveState(showSpeedSelection = true),+ key = PlayerInputKey.DpadUp+ )++ assertThat(decision).isEqualTo(PlayerInputDecision(PlayerInputAction.Pass))+ }++ @Test+ fun `preview ignores channel zapping for non-live content`() {+ val decision = playerPreviewInputDecision(+ state = liveState(contentType = "MOVIE"),+ key = PlayerInputKey.ChannelUp+ )++ assertThat(decision.action).isEqualTo(PlayerInputAction.Pass)+ }++ @Test+ fun `audio video offset Back dismisses preview and directional keys pass through`() {+ val state = liveState(showAudioVideoOffsetDialog = true)++ assertThat(playerInputDecision(state, PlayerInputKey.Back).action)+ .isEqualTo(PlayerInputAction.DismissAudioVideoOffset)+ assertThat(playerInputDecision(state, PlayerInputKey.DpadRight).action)+ .isEqualTo(PlayerInputAction.Pass)+ }++ @Test+ fun `speed modal consumes unrelated keys but passes navigation`() {+ val state = liveState(showSpeedSelection = true)++ assertThat(playerInputDecision(state, PlayerInputKey.Back).action)+ .isEqualTo(PlayerInputAction.CloseSpeedSelection)+ assertThat(playerInputDecision(state, PlayerInputKey.Info).action)+ .isEqualTo(PlayerInputAction.Consume)+ assertThat(playerInputDecision(state, PlayerInputKey.DpadCenter).action)+ .isEqualTo(PlayerInputAction.Pass)+ }++ @Test+ fun `center commits pending numeric live input before opening channel info`() {+ val decision = playerInputDecision(+ liveState(hasPendingNumericChannelInput = true),+ PlayerInputKey.DpadCenter+ )++ assertThat(decision.action).isEqualTo(PlayerInputAction.CommitNumericChannelInput)+ }++ @Test+ fun `event-time decision reads a pending numeric input that changed since the prior event`() {+ var hasPendingNumericInput = false+ val stateProvider = {+ liveState(hasPendingNumericChannelInput = hasPendingNumericInput)+ }++ assertThat(+ playerInputDecisionAtEvent(stateProvider, PlayerInputKey.DpadCenter).action+ ).isEqualTo(PlayerInputAction.OpenChannelInfo)++ hasPendingNumericInput = true++ assertThat(+ playerInputDecisionAtEvent(stateProvider, PlayerInputKey.DpadCenter).action+ ).isEqualTo(PlayerInputAction.CommitNumericChannelInput)+ }++ @Test+ fun `center opens or closes live channel info`() {+ assertThat(playerInputDecision(liveState(), PlayerInputKey.DpadCenter).action)+ .isEqualTo(PlayerInputAction.OpenChannelInfo)+ assertThat(+ playerInputDecision(+ liveState(showChannelInfoOverlay = true),+ PlayerInputKey.Enter+ ).action+ ).isEqualTo(PlayerInputAction.CloseChannelInfo)+ }++ @Test+ fun `numpad enter remains unhandled like the original root key branch`() {+ assertThat(playerInputDecision(liveState(), PlayerInputKey.NumpadEnter).action)+ .isEqualTo(PlayerInputAction.Pass)+ }++ @Test+ fun `channel info overlay blocks up but allows down channel navigation without subpanel`() {+ val state = liveState(showChannelInfoOverlay = true)++ assertThat(playerInputDecision(state, PlayerInputKey.DpadUp).action)+ .isEqualTo(PlayerInputAction.Pass)+ assertThat(playerInputDecision(state, PlayerInputKey.DpadDown).action)+ .isEqualTo(PlayerInputAction.PlayPrevious)+ }++ @Test+ fun `left and right map channel list and EPG according to layout direction`() {+ assertThat(playerInputDecision(liveState(), PlayerInputKey.DpadLeft).action)+ .isEqualTo(PlayerInputAction.OpenChannelList)+ assertThat(playerInputDecision(liveState(), PlayerInputKey.DpadRight).action)+ .isEqualTo(PlayerInputAction.OpenEpg)+ assertThat(playerInputDecision(liveState(isRtl = true), PlayerInputKey.DpadLeft).action)+ .isEqualTo(PlayerInputAction.OpenEpg)+ assertThat(playerInputDecision(liveState(isRtl = true), PlayerInputKey.DpadRight).action)+ .isEqualTo(PlayerInputAction.OpenChannelList)+ }++ @Test+ fun `left opens categories from channel list and right keeps the existing category behavior`() {+ assertThat(+ playerInputDecision(+ liveState(showChannelListOverlay = true),+ PlayerInputKey.DpadLeft+ ).action+ ).isEqualTo(PlayerInputAction.OpenCategoryList)+ assertThat(+ playerInputDecision(+ liveState(showCategoryListOverlay = true),+ PlayerInputKey.DpadRight+ ).action+ ).isEqualTo(PlayerInputAction.OpenEpg)+ }++ @Test+ fun `left and right seek when non-live overlays are absent`() {+ val state = liveState(contentType = "MOVIE")++ assertThat(playerInputDecision(state, PlayerInputKey.DpadLeft).action)+ .isEqualTo(PlayerInputAction.SeekBackward)+ assertThat(playerInputDecision(state, PlayerInputKey.DpadRight).action)+ .isEqualTo(PlayerInputAction.SeekForward)+ assertThat(playerInputDecision(state.copy(isRtl = true), PlayerInputKey.DpadLeft).action)+ .isEqualTo(PlayerInputAction.SeekForward)+ }++ @Test+ fun `up opens episode picker for eligible non-live content`() {+ val decision = playerInputDecision(+ liveState(contentType = "SERIES_EPISODE", canOpenEpisodePicker = true),+ PlayerInputKey.DpadUp+ )++ assertThat(decision.action).isEqualTo(PlayerInputAction.ShowEpisodePicker)+ }++ @Test+ fun `media guide info menu previous and mute map to typed actions`() {+ assertThat(playerInputDecision(liveState(), PlayerInputKey.MediaPlayPause).action)+ .isEqualTo(PlayerInputAction.TogglePlayback)+ assertThat(playerInputDecision(liveState(), PlayerInputKey.Guide).action)+ .isEqualTo(PlayerInputAction.OpenEpg)+ assertThat(playerInputDecision(liveState(), PlayerInputKey.Info).action)+ .isEqualTo(PlayerInputAction.OpenChannelInfo)+ assertThat(playerInputDecision(liveState(), PlayerInputKey.Menu).action)+ .isEqualTo(PlayerInputAction.ToggleControls)+ assertThat(playerInputDecision(liveState(), PlayerInputKey.MediaPrevious).action)+ .isEqualTo(PlayerInputAction.ZapToLastChannel)+ assertThat(playerInputDecision(liveState(), PlayerInputKey.Mute(isRepeat = false)).action)+ .isEqualTo(PlayerInputAction.ToggleMute)+ assertThat(playerInputDecision(liveState(), PlayerInputKey.Mute(isRepeat = true)).action)+ .isEqualTo(PlayerInputAction.Consume)+ }++ @Test+ fun `numeric digits become actions only for live content`() {+ assertThat(playerInputDecision(liveState(), PlayerInputKey.Digit(7)).action)+ .isEqualTo(PlayerInputAction.InputNumericDigit(7))+ assertThat(+ playerInputDecision(liveState(contentType = "MOVIE"), PlayerInputKey.Digit(7)).action+ ).isEqualTo(PlayerInputAction.Pass)+ }++ private fun liveState(+ contentType: String = "LIVE",+ isCatchUpPlayback: Boolean = false,+ isRtl: Boolean = false,+ nextEpisodeCountdownVisible: Boolean = false,+ showChannelListOverlay: Boolean = false,+ showCategoryListOverlay: Boolean = false,+ showEpgOverlay: Boolean = false,+ showChannelInfoOverlay: Boolean = false,+ channelInfoSubPanelOpen: Boolean = false,+ showDiagnostics: Boolean = false,+ showTrackSelection: Boolean = false,+ showVariantSelection: Boolean = false,+ showSpeedSelection: Boolean = false,+ showAudioVideoOffsetDialog: Boolean = false,+ showStopPlaybackTimerDialog: Boolean = false,+ showIdleStandbyTimerDialog: Boolean = false,+ showProgramHistory: Boolean = false,+ showSplitDialog: Boolean = false,+ showEpisodePicker: Boolean = false,+ showControls: Boolean = false,+ hasPendingNumericChannelInput: Boolean = false,+ canOpenEpisodePicker: Boolean = false+ ) = PlayerInputState(+ contentType = contentType,+ isCatchUpPlayback = isCatchUpPlayback,+ isRtl = isRtl,+ nextEpisodeCountdownVisible = nextEpisodeCountdownVisible,+ showChannelListOverlay = showChannelListOverlay,+ showCategoryListOverlay = showCategoryListOverlay,+ showEpgOverlay = showEpgOverlay,+ showChannelInfoOverlay = showChannelInfoOverlay,+ channelInfoSubPanelOpen = channelInfoSubPanelOpen,+ showDiagnostics = showDiagnostics,+ showTrackSelection = showTrackSelection,+ showVariantSelection = showVariantSelection,+ showSpeedSelection = showSpeedSelection,+ showAudioVideoOffsetDialog = showAudioVideoOffsetDialog,+ showStopPlaybackTimerDialog = showStopPlaybackTimerDialog,+ showIdleStandbyTimerDialog = showIdleStandbyTimerDialog,+ showProgramHistory = showProgramHistory,+ showSplitDialog = showSplitDialog,+ showEpisodePicker = showEpisodePicker,+ showControls = showControls,+ hasPendingNumericChannelInput = hasPendingNumericChannelInput,+ canOpenEpisodePicker = canOpenEpisodePicker+ )+}diff --git a/docs/COMPOSE_REDUCTION_AND_UI_ARCHITECTURE_PLAN.md b/docs/COMPOSE_REDUCTION_AND_UI_ARCHITECTURE_PLAN.mdindex e4c10384..3c248c3d 100644--- a/docs/COMPOSE_REDUCTION_AND_UI_ARCHITECTURE_PLAN.md+++ b/docs/COMPOSE_REDUCTION_AND_UI_ARCHITECTURE_PLAN.md@@ -9,10 +9,16 @@ Scope: Android application UI, navigation, build structure, and UI-facing modulePhase 0 is complete for the available development environment. The build, artifact, memory, Compose compiler, Macrobenchmark, and live-playback baseline is recorded in [`COMPOSE_REDUCTION_BASELINE.md`](COMPOSE_REDUCTION_BASELINE.md), and the Compose compiler diagnostic outputs are generated under `app/build/reports/compose-compiler/`. Physical-device measurements and a stable provider stream are explicitly listed as follow-up limitations, not treated as successful release-quality measurements.-The first Phase 1 refactor has also started: `PlayerControlsOverlayHost` was moved out of `PlayerScreen.kt` into its own file without changing its parameters, callbacks, routes, or playback behavior. The player Back-navigation priority is now also isolated in the platform-free `PlayerBackNavigationPolicy`, with focused unit tests. Android lifecycle, Picture-in-Picture cleanup, and keep-screen-on effects are now isolated in `PlayerLifecycleHost` while preserving the original effect keys and callback order. These changes reduced the root screen's coordination responsibilities while preserving the existing callback behavior. `:app:compileDebugKotlin` and the app unit-test suite pass.+The first Phase 1 refactor has also started: `PlayerControlsOverlayHost` was moved out of `PlayerScreen.kt` into its own file without changing its parameters, callbacks, routes, or playback behavior. The player Back-navigation priority is now also isolated in the platform-free `PlayerBackNavigationPolicy`, with focused unit tests. Android lifecycle, Picture-in-Picture cleanup, and keep-screen-on effects are now isolated in `PlayerLifecycleHost` while preserving the original effect keys and callback order. The placement-preserving player modal-host slice is now implemented in `PlayerModalHosts.kt` and wired into `PlayerScreen.kt`; its compile, assemble, unit-test, structural, and two-channel long-duration playback checks pass, while the remaining manual and baseline instrumentation gates are recorded as incomplete in the execution plan. Provider setup decomposition has now started with behavior-neutral extraction of file-import support, Stalker form models, source tabs, action buttons, password glyph/text-field behavior, the Jellyfin form/QR helper, the sync-progress dialog, policy option rows, phone pairing, import dialogs/cards, and Stalker request-rule editing; the root still owns draft state, launchers, effects, and ViewModel calls. These changes reduced the root screens' coordination responsibilities while preserving the existing callback behavior. `:app:compileDebugKotlin` and the app unit-test suite pass.The full `:app:testDebugUnitTest` task now passes after the test fixture was updated to provide the already-required `m3uClassificationRepository` mock. No production behavior was changed; existing coroutine opt-in warnings remain.+The ProviderSetup slice now also places the source selector panel, provider-specific form content, and advanced-options section in dedicated files; the root continues to own draft state, launchers, effects, and ViewModel calls. The second no-behavior-change decomposition moved the remaining provider branches into explicit Xtream, Stalker, M3U, and Jellyfin form composables, and moved completion, compatibility-selector, validation-error, and password-transformation leaves into dedicated same-package files.++The AppNavigation split is now complete for Phase 1: startup resolution, route/request contracts, navigation adapters, external-navigation dispatch, and graph registration are in dedicated same-package files; `AppNavigation.kt` retains state collection and orchestration only. No typed-route or module boundary was introduced.++The review follow-up also closed player input freshness regressions: input and Back decisions now build their snapshots at event time, including the ViewModel-backed numeric-channel buffer, with regression tests covering digit-entry updates followed by immediate confirmation or Back. Focused player, provider, and navigation unit tests pass. Long-duration live playback and manual TV smoke checks remain required Phase 1 gates whenever the environment is available; this workspace currently has no `adb` executable/device, so those gates remain explicitly unvalidated.+## 1. Executive summaryStreamVault should reduce Compose by making it an intentional UI technology choice instead of the default location for all application behavior. Compose should remain the primary technology for dynamic, focus-heavy TV experiences such as Live TV, EPG, playback overlays, media shelves, and MultiView. Form-heavy and mostly static surfaces such as provider setup, settings, backup/import, and simple onboarding should be evaluated for classic Views after their state and navigation boundaries are cleaned up.@@ -716,17 +722,20 @@ Purpose: make later changes reviewable and lower merge risk.Deliverables:- Split `ProviderSetupScreen.kt` into provider-specific forms, dialogs, import helpers, and components.-- Split `PlayerScreen.kt` into lifecycle, input, overlay host, and modal host files.+- Split `PlayerScreen.kt` into lifecycle, input, overlay host, and modal host files. For the modal slice, preserve the current two composition locations and source order rather than forcing every dialog through one relocated call site: top-level program-history/MultiView dialogs remain before the root player `Box`, while controls-related dialogs remain inside it after `PlayerResumePrompt`. The detailed contract is defined in [`superpowers/specs/2026-08-17-player-modal-host-design.md`](superpowers/specs/2026-08-17-player-modal-host-design.md).- Split `AppNavigation.kt` into startup/external navigation policy and graph registration files.- Keep packages and Gradle modules unchanged.- Add or move tests around extracted pure policies.+- During source-only player splits, preserve every existing visibility predicate, composition order, callback sequence, Back/input/focus rule, effect key, state owner, and ViewModel scope. In particular, do not add a new Picture-in-Picture restriction to MultiView, and preserve the audio/video-offset dialog's sync-enabled and cast-disconnected gates.+- Do not introduce Phase 2 modal exclusivity or grouped modal state merely to simplify a Phase 1 host API. Callback-heavy, placement-preserving interfaces are acceptable temporary boundaries when they make the mechanical diff safer.Exit criteria:- No intended UI behavior change.- Screenshots/golden tests remain equivalent.-- Existing unit and instrumentation suites pass.+- Existing unit and applicable instrumentation suites pass; if a repository baseline test fails, record the exact command and failure and keep the Phase 1 gate open rather than attributing it to the extraction without evidence.- Live TV validation passes if player composition or lifecycle code moved.+- Manual TV smoke coverage passes for affected dialogs, Back/focus behavior, controls auto-hide, and Picture-in-Picture behavior. Unavailable scenarios are recorded as incomplete gates, not counted as passes.### Phase 2 - Runtime state isolation@@ -962,7 +971,7 @@ This sequence keeps reviews focused and creates rollback points:1. Add build/runtime benchmark infrastructure and capture baseline.2. Add Compose compiler report configuration and stability audit notes.-3. Extract pure player input/modal policies with tests.+3. Extract pure player input policies with tests, and extract modal composition through placement-preserving hosts with explicit visibility and callback contracts.4. Split `PlayerScreen` files without behavior changes.5. Isolate player real-time state and validate Live TV fully.6. Split provider setup files without behavior changes.@@ -1035,11 +1044,15 @@ The modernization is complete when:- [x] Complete the first no-behavior-change slice by extracting `PlayerControlsOverlayHost`.- [x] Extract and unit-test the player Back-navigation priority policy without changing event handling.- [x] Extract player lifecycle/window effects into `PlayerLifecycleHost` without changing effect keys or callbacks.+- [x] Extract and unit-test the player root input decision policy while keeping Android event adaptation, state mutation, focus, pointer, and Back execution in `PlayerScreen.kt`.+- [x] Add event-time freshness guards for player input and Back decisions, including numeric-channel buffer regressions.+- [x] Complete the second no-behavior-change `ProviderSetup` decomposition slice; package it as a review PR after the remaining manual gates.+- [x] Complete the Phase 1 `AppNavigation` policy, adapter, external-request, and graph-registration split.- [ ] Run a manual app smoke test for player launch, controls, remote/back handling, seeking, and overlay actions.- [ ] Run full multi-channel Live TV validation before marking the player phase complete.- [x] Add or define the Macrobenchmark module and constrained-device benchmark flows.- [ ] Create the first no-behavior-change PR for `PlayerScreen` decomposition after the manual smoke test.-- [ ] Create the second no-behavior-change PR for `ProviderSetupScreen` decomposition.+- [ ] Package the completed second no-behavior-change `ProviderSetupScreen` decomposition as a review PR.- [ ] Revisit the initial success targets after baseline data is available.## 19. PR #162 assessmentdiff --git a/docs/superpowers/plans/2026-08-17-player-input-policy.md b/docs/superpowers/plans/2026-08-17-player-input-policy.mdnew file mode 100644index 00000000..14393f56--- /dev/null+++ b/docs/superpowers/plans/2026-08-17-player-input-policy.md@@ -0,0 +1,61 @@+# Player Input Policy Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task with verification checkpoints.++**Goal:** Extract the player root key-routing decisions into a tested, platform-free policy without changing TV input behavior.++**Architecture:** `PlayerInputPolicy.kt` owns immutable state snapshots, platform-free keys, typed decisions, and pure preview/normal decision functions. `PlayerScreen.kt` keeps Android event conversion, Compose modifiers, focus/pointer behavior, state mutation, ViewModel calls, and Back execution.++**Tech Stack:** Kotlin, Jetpack Compose, Android `KeyEvent` adapter, JUnit4, Truth.++## Global Constraints++- Preserve separate preview and normal key phases.+- Preserve action-down-only handling and `notifyUserActivity()` ordering.+- Preserve all current overlay/modal/RTL/catch-up predicates and command ordering.+- Keep `PlayerBackNavigationPolicy` and all mutable state in `PlayerScreen.kt`.+- Do not introduce Phase 2 modal state, navigation contracts, or ViewModel APIs.++### Task 1: Add the platform-free policy contract and tests++**Files:**+- Create: `app/src/main/java/com/streamvault/app/ui/screens/player/PlayerInputPolicy.kt`+- Test: `app/src/test/java/com/streamvault/app/ui/screens/player/PlayerInputPolicyTest.kt`++**Interfaces:**+- Produces `PlayerInputKey`, `PlayerInputState`, `PlayerInputAction`, `PlayerInputDecision`, `playerPreviewInputDecision()`, and `playerInputDecision()`.++- [x] **Step 1: Write failing policy tests** covering preview zapping/blocking, modal Back/pass-through, center numeric/live behavior, RTL left/right mapping, seek, episode picker, media/guide/info/menu, channel previous, mute repeat, and numeric digits.+- [x] **Step 2: Run the focused test and verify it fails because the policy contract is absent.**+- [x] **Step 3: Implement the smallest pure policy model and decision functions matching the design invariants.**+- [x] **Step 4: Run the focused policy test until all cases pass.**++### Task 2: Wire the policy into `PlayerScreen`++**Files:**+- Modify: `app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt` in the root modifier key handlers.+- Modify: `app/src/main/java/com/streamvault/app/ui/screens/player/PlayerInputPolicy.kt` only if adapter visibility requires it.++**Interfaces:**+- Consumes the pure decisions from Task 1.+- Produces the same existing ViewModel/state mutations and modifier return values.++- [x] **Step 1: Add the Android key-code adapter at the screen boundary, including numeric digit conversion.**+- [x] **Step 2: Build one `PlayerInputState` snapshot from the existing screen values without moving ownership.**+- [x] **Step 3: Replace only the preview handler’s branching with `playerPreviewInputDecision()`, preserving notification and callback order.**+- [x] **Step 4: Replace only the normal handler’s branching with `playerInputDecision()`, preserving the existing `handleBackPress()` call and all side effects.**+- [x] **Step 5: Compile and run focused policy tests.**++### Task 3: Verify behavior-preserving decomposition++**Files:**+- Inspect: `PlayerScreen.kt`, `PlayerInputPolicy.kt`, and `PlayerInputPolicyTest.kt`.++- [x] **Step 1: Run source checks confirming Back policy, pointer input, focus properties, and ViewModel ownership remain in `PlayerScreen.kt`.**+- [x] **Step 2: Run `:app:testDebugUnitTest` and `:app:compileDebugKotlin`.**+- [x] **Step 3: Run `git diff --check` and `graphify update .`.**+- [ ] **Step 4: Re-run applicable player/golden/live validation; record any existing environment failures without attributing them to this extraction.**++Verification recorded 2026-08-17: the focused policy test and full `:app:testDebugUnitTest` pass, and `:app:compileDebugKotlin` passes. `:app:lintDebug` still reports the repository’s 56 unsuppressed baseline findings; none reference the changed player input/modal files. Fresh emulator evidence captured 61 frames at a 2-second cadence for USA CBSN Minnesota (provider HTTP 509, one unique frame, terminal provider-limit error) and USA Fox News (21 unique frames, HLS first frame followed by provider-limit recovery to MPEG-TS; media session was PLAYING during recovery but the final post-window dump was STOPPED). These are provider/environment outcomes, not attributed to the input extraction, but they do not satisfy the clean live gate. The manual TV matrix and final player acceptance therefore remain open Phase 1 gates.++`:app:connectedDebugAndroidTest '-Pandroid.testInstrumentationRunnerArguments.class=com.streamvault.app.ui.PlayerSmokeTest'` also reproduces the existing three failures (category search-field focus, controls play-button focus, and track-selection fixture setup); the mute-action smoke test passes. No failure points at the extracted policy.diff --git a/docs/superpowers/plans/2026-08-17-player-modal-hosts.md b/docs/superpowers/plans/2026-08-17-player-modal-hosts.mdnew file mode 100644index 00000000..236087d9--- /dev/null+++ b/docs/superpowers/plans/2026-08-17-player-modal-hosts.md@@ -0,0 +1,263 @@+# Player Modal Hosts Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task with verification checkpoints.++**Goal:** Extract the nine player dialog call sites into placement-preserving internal hosts without changing player behavior.++**Architecture:** Add `PlayerModalHosts.kt` with `PlayerTopLevelModalHost` for the two dialogs currently composed before the root player `Box`, and `PlayerControlsModalHost` for the seven dialogs currently composed inside the `Box`. Keep all state, effects, Back/input policy, navigation callbacks, and ViewModel ownership in `PlayerScreen.kt`; move only dialog invocation composition and its direct arguments/callbacks.++**Tech Stack:** Kotlin, Jetpack Compose, Hilt Compose ViewModels, Android Gradle Plugin, existing app unit/instrumentation tests.++## Global Constraints++- Preserve every existing visibility predicate, composition location, source order, callback order, state owner, effect key, Back/focus/input rule, and ViewModel scope.+- MultiView remains visible under its existing `showSplitDialog && currentChannel != null` predicate; do not add a PiP restriction.+- Audio/video offset remains gated by `showAudioVideoOffsetDialog && audioVideoSyncEnabled && castConnectionState != CastConnectionState.CONNECTED`, in addition to the non-PiP host guard.+- Do not introduce Phase 2 modal exclusivity, sealed modal state, state grouping, route contracts, feature modules, or player behavior changes.+- Keep `PlayerModalHosts.kt` internal to `com.streamvault.app.ui.screens.player`.+- Run `graphify update .` only if Kotlin source changes are made.++---++### Task 1: Establish a clean implementation baseline++**Files:**+- Read: `docs/superpowers/specs/2026-08-17-player-modal-host-design.md`+- Read: `app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt`+- Read: `app/src/main/java/com/streamvault/app/ui/screens/player/overlay/PlayerSystemOverlays.kt`+- Read: `app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewPlannerDialog.kt`++**Interfaces:**+- Consumes: the approved modal-host design and current dialog call sites.+- Produces: a verified baseline and a line-by-line call-site map for Tasks 2–3.++- [x] **Step 1: Verify the current working tree and source inventory**++Run:++```powershell+git status --short+rg -n "ProgramHistoryDialog\(|MultiViewPlannerDialog\(|PlayerTrackSelectionDialog\(|ChannelVariantSelectionDialog\(|PlayerSpeedSelectionDialog\(|PlayerSleepTimerDialog\(|PlayerAudioVideoOffsetDialog\(|PlayerEpisodeSelectionDialog\(" app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt+```++Expected: only the approved documentation edits are present; exactly nine dialog invocations are found.++- [x] **Step 2: Run the existing app unit-test baseline**++Run:++```powershell+.\gradlew.bat :app:testDebugUnitTest --no-daemon --console=plain+```++Expected: exit code 0. If the baseline fails, record the existing failure before changing Kotlin and do not attribute it to this extraction.++### Task 2: Create the placement-preserving modal hosts++**Files:**+- Create: `app/src/main/java/com/streamvault/app/ui/screens/player/PlayerModalHosts.kt`+- Test: no new production test seam; this is a mechanical composition extraction verified by source mapping and existing Compose/instrumentation coverage.++**Interfaces:**+- Consumes: existing dialog argument types and callbacks from `PlayerScreen.kt`.+- Produces: `internal @Composable fun PlayerTopLevelModalHost(...)` and `internal @Composable fun PlayerControlsModalHost(...)` in the player package.++- [x] **Step 1: Write the failing structural check**++Before creating the file, run:++```powershell+if (Test-Path 'app/src/main/java/com/streamvault/app/ui/screens/player/PlayerModalHosts.kt') { throw 'PlayerModalHosts.kt already exists; inspect before proceeding.' }+```++Expected: the check succeeds because the new host file does not yet exist.++- [x] **Step 2: Add the top-level host with the exact existing predicates and order**++Implement `PlayerTopLevelModalHost` with read-only values and callbacks for:++```kotlin+@Composable+internal fun PlayerTopLevelModalHost(+ isInPictureInPictureMode: Boolean,+ showProgramHistory: Boolean,+ programHistory: List<Program>,+ onDismissProgramHistory: () -> Unit,+ onSelectProgramHistory: (Program) -> Unit,+ showSplitDialog: Boolean,+ currentChannel: Channel?,+ onDismissSplitDialog: () -> Unit,+ onLaunchMultiView: () -> Unit,+)+```++Inside the host, preserve this order and no other wrapper:++1. Compose `ProgramHistoryDialog` only when `!isInPictureInPictureMode && showProgramHistory`.+2. Compose `MultiViewPlannerDialog` only when `showSplitDialog && currentChannel != null`.+3. Obtain `MultiViewViewModel` with `hiltViewModel()` inside that second branch only.++Do not add `!isInPictureInPictureMode` to the MultiView branch.++- [x] **Step 3: Add the in-Box host with the exact existing order**++Implement `PlayerControlsModalHost` with parameters corresponding directly to the current seven invocations: PiP flag, track state/lists, variant state/channel, speed state, both timer states/titles, precomputed audio/video-offset visibility and state, channel-save capability, episode presentation data, and narrow callbacks.++Inside the host, preserve this order and no other wrapper:++1. `PlayerTrackSelectionDialog`+2. `ChannelVariantSelectionDialog`+3. `PlayerSpeedSelectionDialog`+4. stop-playback `PlayerSleepTimerDialog`+5. idle-standby `PlayerSleepTimerDialog`+6. `PlayerAudioVideoOffsetDialog`+7. `PlayerEpisodeSelectionDialog`++Guard all seven with the existing non-PiP condition. Pass audio/video offset `visible` as the complete existing predicate, not merely `showAudioVideoOffsetDialog`.++- [x] **Step 4: Compile the new file before wiring it**++Run:++```powershell+.\gradlew.bat :app:compileDebugKotlin --no-daemon --console=plain+```++Expected: exit code 0. Fix only imports, parameter types, and syntax needed for the standalone host file; do not alter dialog implementations.++### Task 3: Replace the two contiguous call-site blocks in `PlayerScreen.kt`++**Files:**+- Modify: `app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt:346-370`+- Modify: `app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt:1137-1220`++**Interfaces:**+- Consumes: `PlayerTopLevelModalHost` and `PlayerControlsModalHost` from Task 2.+- Produces: the same player screen behavior with only dialog invocation composition moved.++- [x] **Step 1: Wire `PlayerTopLevelModalHost` at the old top-level position**++Replace only the current program-history/MultiView contiguous block with one call at the same location. Keep callback bodies equivalent:++```kotlin+PlayerTopLevelModalHost(+ isInPictureInPictureMode = isInPictureInPictureMode,+ showProgramHistory = showProgramHistory,+ programHistory = programHistory,+ onDismissProgramHistory = { showProgramHistory = false },+ onSelectProgramHistory = { program ->+ viewModel.playCatchUp(program)+ showProgramHistory = false+ },+ showSplitDialog = showSplitDialog,+ currentChannel = currentChannel,+ onDismissSplitDialog = { showSplitDialog = false },+ onLaunchMultiView = {+ showSplitDialog = false+ viewModel.handOffPlaybackToMultiView()+ onNavigate?.invoke(Routes.MULTI_VIEW)+ }+)+```++Use the actual parameter names from the host implementation; do not move `currentChannel`, state declarations, or navigation policy.++- [x] **Step 2: Wire `PlayerControlsModalHost` at the old in-Box position**++Replace only the current track-through-episode contiguous block with one call after `PlayerResumePrompt` and before diagnostics/live overlays. Preserve the exact callback bodies from the current call sites, including:++- subtitle deactivation before subtitle selection;+- live translation clearing before activation;+- user activity before each timer mutation and flag clear;+- audio/video-offset flag clear before preview dismissal;+- episode picker flag clear before playback.++Compute and pass:++```kotlin+audioVideoOffsetVisible = showAudioVideoOffsetDialog &&+ audioVideoSyncEnabled &&+ castConnectionState != CastConnectionState.CONNECTED+```++Keep `PlayerResumePrompt`, diagnostics, live overlays, `anyOverlayVisible`, Back handling, effects, and focus/input code in `PlayerScreen.kt`.++- [x] **Step 3: Remove only imports made unused by the move**++Retain imports still used elsewhere in `PlayerScreen.kt`; remove only dialog imports no longer referenced there. Do not remove `Routes`, `MultiViewViewModel`, or other imports until compilation proves they are unused and the host owns the corresponding reference.++- [x] **Step 4: Run the focused compile check**++Run:++```powershell+.\gradlew.bat :app:compileDebugKotlin --no-daemon --console=plain+```++Expected: exit code 0 with no new Kotlin errors.++### Task 4: Verify the mechanical extraction and regression gates++**Files:**+- Inspect: `app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt`+- Inspect: `app/src/main/java/com/streamvault/app/ui/screens/player/PlayerModalHosts.kt`+- Inspect: `docs/superpowers/specs/2026-08-17-player-modal-host-design.md`++**Interfaces:**+- Consumes: the wired hosts from Task 3.+- Produces: evidence that the Phase 1 slice is behavior-preserving and ready for manual/live validation.++- [x] **Step 1: Verify all nine call sites moved exactly once**++Run:++```powershell+rg -n "ProgramHistoryDialog\(|MultiViewPlannerDialog\(|PlayerTrackSelectionDialog\(|ChannelVariantSelectionDialog\(|PlayerSpeedSelectionDialog\(|PlayerSleepTimerDialog\(|PlayerAudioVideoOffsetDialog\(|PlayerEpisodeSelectionDialog\(" app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt app/src/main/java/com/streamvault/app/ui/screens/player/PlayerModalHosts.kt+```++Expected: every dialog invocation appears in `PlayerModalHosts.kt` and no dialog invocation remains in `PlayerScreen.kt`.++- [x] **Step 2: Verify source constraints**++Run:++```powershell+rg -n "PlayerViewModel|NavController|BackHandler|LaunchedEffect|remember\(|PlayerResumePrompt|DiagnosticsOverlay|ChannelInfoOverlay|EpgOverlay" app/src/main/java/com/streamvault/app/ui/screens/player/PlayerModalHosts.kt+```++Expected: no forbidden host-owned state/effect/input/navigation references; only the dialog-specific implementation references are outside the host.++- [x] **Step 3: Run scoped automated checks**++Run:++```powershell+.\gradlew.bat :app:testDebugUnitTest --no-daemon --console=plain+.\gradlew.bat :app:lintDebug --no-daemon --console=plain+git diff --check+```++Result: `compileDebugKotlin`, `testDebugUnitTest`, and `git diff --check` passed. `lintDebug` originally failed on 57 unfiltered repository findings: dependency/version freshness checks, missing translations, Compose resource-access checks, unused resources, KTX/recycle suggestions, and one `ModifierParameter` finding in the earlier `PlayerControlsOverlayHost.kt` extraction. The `ModifierParameter` issue was corrected by moving `modifier` before the first optional parameter; a fresh `compileDebugKotlin` passed and a fresh `lintDebug` now fails only on the remaining 56 unrelated repository findings. No finding names the new `PlayerModalHosts.kt` or the modified `PlayerScreen.kt`; this lint baseline remains a repository gate, not a finding in the modal-host slice.++- [x] **Step 4: Refresh the graph after Kotlin changes**++Run:++```powershell+graphify update .+```++Expected: graphify reports the changed Kotlin files and updates `graphify-out/` without modifying unrelated source.++- [ ] **Step 5: Run required manual and live validation before declaring Phase 1 slice complete**++Use the repository protocol from the design spec: TV smoke coverage for all applicable dialogs, PiP, Back/focus, controls auto-hide, and cast gating; then validate at least two live channels with 2-second screenshots for at least 45 captures (prefer 61), changing screenshot hashes, media-session `PLAYING`/`error=null`, and sanitized logs showing no fatal/stuck/fallback regressions.++If an emulator, provider, or stream prevents a gate from running, record the exact limitation and leave the gate incomplete.++Validation evidence (2026-08-17, `emulator-5554`, `com.streamvault.app.debug`, APK installed from the current workspace):++- TV smoke path reached seeded Live TV data and full playback using keyboard focus; no provider credentials were required. CBSN New York and F1 Channel both opened through the seeded preview-to-full-playback flow.+- CBSN New York: 61 screenshots at a 2-second cadence (`C:\Temp\streamvault_live_validation_cbsn`), 61 unique SHA-256 hashes, visible frame progression, media session `PLAYING` with `error=null`, metadata `US CBSN New York (D)`. Logs showed HLS prepare and first-frame success; no player fatal/stuck/recovery/fallback diagnostics. Two unrelated historical Bluetooth service `state=ERROR` lines were excluded from player findings.+- F1 Channel: 61 screenshots at a 2-second cadence (`C:\Temp\streamvault_live_validation_f1`), 61 unique SHA-256 hashes, visible frame progression, media session `PLAYING` with `error=null`, metadata `F1 Channel`. Logs showed HLS prepare and first-frame success; no player fatal/stuck/recovery/fallback diagnostics.+- Additional smoke evidence: the player controls opened on the TV emulator, Back dismissed the variant dialog, and the extracted subtitle and video-quality dialogs rendered (`Select Subtitles` and `Video Quality`). `PlayerOverlayGoldenTest` passed all 6 tests on the same emulator. `PlayerSmokeTest` executed but failed 3 existing overlay/focus assertions (play-button focus lookup, category-rail search focus lookup, and audio-track selection); no failure names `PlayerScreen` or `PlayerModalHosts`, and the class does not compose either host. Full manual coverage of every timer/speed/episode/PiP/cast scenario remains incomplete, so Step 5 stays open and Phase 1 is not being marked fully accepted.diff --git a/docs/superpowers/plans/2026-08-18-phase-1-architecture-continuation.md b/docs/superpowers/plans/2026-08-18-phase-1-architecture-continuation.mdnew file mode 100644index 00000000..04e73d9b--- /dev/null+++ b/docs/superpowers/plans/2026-08-18-phase-1-architecture-continuation.md@@ -0,0 +1,29 @@+# Phase 1 Architecture Continuation++## Goal++Finish the remaining Phase 1 source decomposition while preserving runtime behavior and keeping state ownership changes out of scope.++## Acceptance criteria++- Player input decisions read mutable input state at event time; rapid numeric-entry confirmation cannot observe a stale composition snapshot.+- ProviderSetup retains draft state, launchers, effects, and ViewModel calls in its root, while provider-specific UI branches and leaf utilities/hosts are separated into same-package files.+- AppNavigation retains root orchestration and `NavController` ownership, while route/request contracts, adapters, external-navigation handling, policy, and graph registrations are separated into same-package files.+- Existing focused and unit tests pass, whitespace/static checks pass, and graphify is updated.+- No typed-route, feature-module, or Phase 2 state-ownership redesign is introduced.++## Implementation tasks++1. Add a failing regression test for rapid numeric input followed by Enter, then make player event callbacks construct `PlayerInputState` from current values at event time. Run the focused test before and after the fix.+2. Extract the remaining `ProviderFormContent` branches into provider-specific composables with unchanged parameters and named call sites. Move `StalkerCompatibilitySelector`, `FormErrors`, password transformation, completion effects/dialogs, and remaining leaf dialogs to same-package host/component files without moving root-owned state or effects.+3. Split `AppNavigation.kt` into same-package contracts/adapters, external-navigation host, top-level navigation policy, and graph-registration extensions. Keep behavior, registration order, and root orchestration unchanged.+4. Run focused tests, the debug unit-test suite, `git diff --check`, and `graphify update .`. Review the diff for accidental behavior or ownership changes and update the architecture plan with status/gaps.++## Verification commands++```powershell+.\gradlew.bat :app:testDebugUnitTest --tests "com.streamvault.app.ui.screens.player.*" --tests "com.streamvault.app.ui.screens.provider.*" --tests "com.streamvault.app.navigation.*" --rerun --no-daemon --console=plain+.\gradlew.bat :app:testDebugUnitTest --rerun-tasks --no-daemon --console=plain+git diff --check HEAD+graphify update .+```diff --git a/docs/superpowers/specs/2026-08-17-player-input-policy-design.md b/docs/superpowers/specs/2026-08-17-player-input-policy-design.mdnew file mode 100644index 00000000..2f6574fe--- /dev/null+++ b/docs/superpowers/specs/2026-08-17-player-input-policy-design.md@@ -0,0 +1,63 @@+# Player Input Policy Design++**Date:** 2026-08-17++**Phase:** Phase 1 — source decomposition without behavior change++## Decision++Extract the root player key-routing decisions from `PlayerScreen.kt` into a+platform-free `PlayerInputPolicy.kt`. The policy receives an immutable snapshot+of the state that currently gates the root handlers and returns a typed action+plus whether the existing `onLiveOverlayInteraction()` callback must run first.+`PlayerScreen.kt` remains the owner of Compose state, `PlayerViewModel`, focus,+pointer input, Back execution, and all side effects.++The Android `KeyEvent` to policy-key conversion stays at the screen boundary in+a small adapter. This keeps Android constants out of the policy and allows the+decision rules to be unit-tested with ordinary Kotlin values.++## Invariants++- Preserve the separate `onPreviewKeyEvent` and `onKeyEvent` phases.+- Preserve action-down-only handling and the existing `notifyUserActivity()` call+ before every handled key decision.+- Preserve preview priority: live channel-up/down zapping runs only when no+ blocking overlay/dialog is active; channel-info without its sub-panel may still+ receive the interaction callback before zapping.+- Preserve modal key behavior: Back closes audio/video offset, speed, variant,+ or timer/track state in the existing order; directional/center keys pass to the+ dialog; unrelated keys are consumed.+- Preserve every center, directional, media, guide/info/menu, channel, previous,+ mute, and numeric-key branch, including RTL and catch-up conditions.+- Preserve callback order: `onLiveOverlayInteraction()` is executed before the+ selected player command, exactly as in `PlayerScreen.kt`.+- Do not move or redesign `PlayerBackNavigationPolicy`; default Back continues+ through the existing `handleBackPress()` mapping.+- Do not introduce Phase 2 modal state, navigation contracts, ViewModel APIs, or+ behavior changes.++## Policy model++`PlayerInputState` contains only values needed by the two current handlers:+content type, catch-up/RTL flags, countdown and modal visibility, live overlay+visibility, channel-info sub-panel state, controls state, numeric-input state,+and episode-picker eligibility.++`PlayerInputKey` is a platform-free sealed value with fixed keys and+`Digit(value)` for numeric input. `playerPreviewInputDecision()` returns+`PASS`, `PLAY_NEXT`, or `PLAY_PREVIOUS`, with the existing overlay-interaction+flag. `playerInputDecision()` returns typed commands such as `OPEN_EPG`,+`OPEN_CHANNEL_LIST`, `SEEK_FORWARD`, `TOGGLE_CONTROLS`, `SHOW_EPISODES`,+`TOGGLE_PLAYBACK`, `TOGGLE_MUTE`, `INPUT_NUMERIC_DIGIT`, and the modal dismissal+commands. `PASS` means the modifier returns `false`; `CONSUME` means it returns+`true` without a ViewModel/state mutation.++## Verification++Add unit tests for preview blocking/RTL-independent zapping, modal Back and+directional pass-through priority, center numeric/live behavior, RTL channel/EPG+mapping, seek behavior, episode-picker eligibility, media/guide/info/menu,+channel previous, mute repeat handling, and numeric digits. Then run the focused+policy tests, app unit tests, compile, structural checks, graph refresh, and the+existing player validation gates.diff --git a/docs/superpowers/specs/2026-08-17-player-modal-host-design.md b/docs/superpowers/specs/2026-08-17-player-modal-host-design.mdindex 560cefe4..c1423f38 100644--- a/docs/superpowers/specs/2026-08-17-player-modal-host-design.md+++ b/docs/superpowers/specs/2026-08-17-player-modal-host-design.md@@ -1,56 +1,261 @@-# Player Modal Host Design+# Player Modal Hosts Design**Date:** 2026-08-17+**Phase:** Phase 1 — source decomposition without behavior change+**Parent plan:** [`COMPOSE_REDUCTION_AND_UI_ARCHITECTURE_PLAN.md`](../../COMPOSE_REDUCTION_AND_UI_ARCHITECTURE_PLAN.md)++## Decision summary++Extract the nine existing player-dialog call sites from `PlayerScreen.kt` into `PlayerModalHosts.kt` while preserving their current composition placement, order, predicates, state ownership, callback order, ViewModel scope, Back behavior, focus behavior, navigation behavior, and Picture-in-Picture behavior.++The file will contain two internal composable hosts rather than one host moved to a new common location:++- `PlayerTopLevelModalHost` contains `ProgramHistoryDialog` and `MultiViewPlannerDialog` and is invoked at their current top-level position before the root player `Box`.+- `PlayerControlsModalHost` contains the remaining seven call sites and is invoked at their current position inside the root player `Box`, after `PlayerResumePrompt` and before diagnostics/live overlays.++This placement-preserving split is intentionally safer than the parent plan's conceptual single `PlayerDialogHost`. The hosts may be consolidated after Phase 2 introduces explicit mutually exclusive modal state and validates the resulting composition-order change. Phase 1 will not make that state or ordering change.++## Alternatives considered++1. **Two placement-preserving hosts in one file — selected.** This extracts the responsibility without moving either dialog group across the root player `Box` or `PlayerResumePrompt`. Its temporary cost is two callback-heavy host APIs.+2. **One host at the controls-dialog location.** This is visually simpler, but it moves program history and MultiView into the root player `Box` and changes their ordering relative to `PlayerResumePrompt`.+3. **One host at the current top-level location.** This moves all controls-related dialogs out of the root player `Box` and changes their ordering relative to the prompt and overlays.+4. **Introduce explicit modal state and then use one host.** This is the preferred eventual shape, but it changes state representation and exclusivity and therefore remains Phase 2 work.+## Goal-Extract the existing player dialog composition from `PlayerScreen.kt` into a focused `PlayerModalHost.kt` without changing playback behavior, navigation, state ownership, callback order, visibility rules, or Picture-in-Picture behavior.+Make player modal rendering a clearly located presentation responsibility so later state isolation and `:feature:playback` extraction are easier to review, without changing runtime behavior in this slice.++Success means that a reviewer can map every old dialog invocation to one new invocation with the same data, predicate, order, and callback body. Reducing line count is secondary to preserving behavior.## Current context-`PlayerScreen.kt` currently owns the player coordinator, lifecycle effects, Back handling, overlay composition, and the invocation of nine dialog call sites representing eight dialog types:+`PlayerScreen.kt` currently owns the player coordinator, modal state, lifecycle and Picture-in-Picture handling, Back handling, input routing, focus restoration, controls auto-hide policy, overlay composition, and nine dialog call sites representing eight dialog types:-- `ProgramHistoryDialog`-- `MultiViewPlannerDialog`-- `PlayerTrackSelectionDialog`-- `ChannelVariantSelectionDialog`-- `PlayerSpeedSelectionDialog`-- two `PlayerSleepTimerDialog` instances-- `PlayerAudioVideoOffsetDialog`-- `PlayerEpisodeSelectionDialog`+1. `ProgramHistoryDialog`+2. `MultiViewPlannerDialog`+3. `PlayerTrackSelectionDialog`+4. `ChannelVariantSelectionDialog`+5. `PlayerSpeedSelectionDialog`+6. `PlayerSleepTimerDialog` for stop playback+7. `PlayerSleepTimerDialog` for idle standby+8. `PlayerAudioVideoOffsetDialog`+9. `PlayerEpisodeSelectionDialog`-The screen also owns every state variable that controls those dialogs. The extraction must leave that state in `PlayerScreen.kt` so this remains a source decomposition rather than a runtime-state change.+The first two are composed before the root player `Box`. The remaining seven are composed inside that `Box`. `PlayerResumePrompt` is a full-screen in-content prompt between those groups, not one of the extracted dialog call sites.-## Design+Multiple modal booleans can currently be true at the same time. Phase 2 will replace that representation with explicit modal state; Phase 1 must preserve the current possibility, source order, Back priority, and resulting presentation behavior.-Create `app/src/main/java/com/streamvault/app/ui/screens/player/PlayerModalHost.kt` with one internal composable. Its parameter list will contain the current Picture-in-Picture flag, dialog visibility/state values, dialog presentation data, and explicit dismiss/selection/action callbacks derived from the existing call sites. Parameters are read-only values and explicit callbacks. The host will not receive `PlayerViewModel`, mutate `PlayerScreen` state directly, create new effects, or alter navigation decisions.+## Architecture and ownership-The host will preserve these existing rules:+Create:-1. Program history and split-screen dialogs are hidden in Picture-in-Picture mode.-2. The split-screen dialog is rendered only when `showSplitDialog` is true and `currentChannel` is non-null; its `MultiViewViewModel` remains obtained with `hiltViewModel()` at the dialog boundary.-3. Track, variant, speed, timer, audio/video offset, and episode dialogs remain inside the non-Picture-in-Picture guard.-4. Existing callback sequencing remains unchanged, including clearing dialog state before episode playback or multi-view handoff, dismissing audio/video offset previews, and deactivating live translation before subtitle selection.-5. The host does not include `PlayerResumePrompt` or diagnostic/live overlays; those are separate composition concerns and remain in `PlayerScreen.kt` for this slice.+```text+app/src/main/java/com/streamvault/app/ui/screens/player/PlayerModalHosts.kt+```-## Alternatives considered+Both hosts are `internal` and presentation-only. Their inputs are read-only values and narrow callbacks copied from the existing call sites.++The hosts must not:++- Receive `PlayerViewModel`, `NavController`, `MainActivity`, a player engine, or mutable state holders.+- Read flows, create `remember` state, launch effects, install a `BackHandler`, or mutate `PlayerScreen` state.+- Compute navigation destinations or call navigation directly.+- Change modal exclusivity, dismissal policy, focus restoration, controls auto-hide behavior, or overlay priority.+- Introduce a sealed modal type, grouped modal state, route contract, new ViewModel API, or new dependency.++`MultiViewViewModel` is the one explicit dependency-injection exception. `PlayerTopLevelModalHost` obtains it with `hiltViewModel()` only inside the existing `showSplitDialog && currentChannel != null` branch and passes it to `MultiViewPlannerDialog`. This preserves lazy creation and the current `ViewModelStoreOwner`; it must not be hoisted into `PlayerScreen` or created when the dialog is absent.++All modal booleans and `showTrackSelection` remain owned by `PlayerScreen`. The following also remain in `PlayerScreen` unchanged:++- `anyOverlayVisible` and its focus-restoration effect.+- Controls auto-hide inputs and effect keys.+- `PlayerBackNavigationState`, `playerBackAction`, and the existing action-to-mutation mapping.+- Root pointer/key interception while a modal is active.+- Modal-opening callbacks supplied to controls and live overlays.+- Audio/video-sync disabling cleanup.++## Exact composition placement and order++`PlayerTopLevelModalHost` replaces only the current contiguous top-level block. It remains after live-variant observation and before player preparation identity/effects. Within the host, composition order is:++1. `ProgramHistoryDialog`+2. `MultiViewPlannerDialog`++`PlayerControlsModalHost` replaces only the current contiguous dialog block inside the root player `Box`. It remains after `PlayerResumePrompt` and before diagnostics and live overlays. Within the host, composition order is:++1. `PlayerTrackSelectionDialog`+2. `ChannelVariantSelectionDialog`+3. `PlayerSpeedSelectionDialog`+4. Stop-playback `PlayerSleepTimerDialog`+5. Idle-standby `PlayerSleepTimerDialog`+6. `PlayerAudioVideoOffsetDialog`+7. `PlayerEpisodeSelectionDialog`++No dialog call may move across `PlayerResumePrompt`, the root player `Box`, diagnostics, or live-overlay composition during this phase. Parameter evaluation must also remain at the equivalent call-site scope; presentation strings may be passed into a host after evaluation with the same resources and fallbacks.++## Visibility contract++The hosts preserve these exact predicates:++| Dialog | Required visibility predicate |+|---|---|+| Program history | `!isInPictureInPictureMode && showProgramHistory` |+| MultiView planner | `showSplitDialog && currentChannel != null` |+| Track selection | Host is outside PiP and `showTrackSelection != null` remains interpreted by the existing dialog |+| Channel variant selection | Host is outside PiP; pass `showVariantSelection` and `currentChannel` unchanged |+| Playback speed | Host is outside PiP; pass `showSpeedSelection` unchanged |+| Stop-playback timer | Host is outside PiP; pass `showStopPlaybackTimerDialog` unchanged |+| Idle-standby timer | Host is outside PiP; pass `showIdleStandbyTimerDialog` unchanged |+| Audio/video offset | Host is outside PiP and `visible` remains `showAudioVideoOffsetDialog && audioVideoSyncEnabled && castConnectionState != CastConnectionState.CONNECTED` |+| Episode selection | Host is outside PiP; pass `showEpisodePicker` unchanged |++MultiView is intentionally **not** newly hidden in Picture-in-Picture mode. That is the current behavior. Changing it, even if desirable, requires a separately scoped behavior proposal and is prohibited here.++Visibility booleans must not be cleared merely because Picture-in-Picture or another eligibility condition temporarily prevents composition. Phase 1 preserves the existing state lifetime and cleanup behavior.++## Data and callback contract++Every host parameter maps directly to an existing dialog argument. Do not replace narrow callbacks with a feature-wide action type in this phase.++The following data expressions must remain equivalent:++- Program history receives `programHistory`.+- MultiView receives the non-null `currentChannel` as `pendingChannel`.+- Track selection receives the current track type, audio tracks, subtitle tracks, video qualities, and live-translation availability/activity values.+- Variant selection receives `currentChannel`.+- Speed selection receives `playbackSpeed`.+- Timer dialogs receive their existing resource titles and the corresponding stop/idle selected minutes.+- Audio/video offset receives `audioVideoOffsetState` and `canSaveChannel = currentChannel != null`.+- Episode selection preserves `currentSeries?.name ?: playbackTitle.ifBlank { title }`, `currentSeriesSeasons.orEmpty()`, `currentEpisode?.id ?: internalChannelId`, and `currentEpisode?.seasonNumber ?: seasonNumber`.++Callbacks passed from `PlayerScreen` preserve these exact orders:-1. **Extract the modal host now — recommended.** It directly matches the Phase 1 plan, removes a cohesive rendering responsibility, and keeps state/effects in the root. The main cost is an explicit callback-heavy interface.-2. **Extract key-event handling first.** This could remove more lines, but it crosses input routing, overlay priority, ViewModel actions, and mutable screen state, making behavior comparison and review riskier.-3. **Start `ProviderSetupScreen` decomposition.** That file is substantially larger, but its source-specific form split is a broader slice with more state and import flows. It should follow a smaller player boundary.+| Interaction | Required callback order |+|---|---|+| Select program history item | Play catch-up, then clear `showProgramHistory` |+| Dismiss program history | Clear `showProgramHistory` |+| Launch MultiView | Clear `showSplitDialog`, hand off playback, then invoke navigation to `Routes.MULTI_VIEW` |+| Dismiss MultiView | Clear `showSplitDialog` |+| Select subtitle | Deactivate live translation, then select the subtitle track |+| Select live translation | Clear the selected subtitle track, then activate live translation |+| Select stop-playback timer | Notify user activity, set the timer, then clear its dialog flag |+| Select idle-standby timer | Notify user activity, set the timer, then clear its dialog flag |+| Dismiss audio/video offset | Clear its dialog flag, then dismiss the preview |+| Select episode | Clear `showEpisodePicker`, then start episode playback |-## Verification+All remaining method references and dismiss callbacks are passed through unchanged. The extraction must not add automatic dismissal after audio, video, variant, speed, offset-save, or offset-reset callbacks unless the current dialog or ViewModel already performs it.-- Inspect the before/after diff to confirm only dialog invocation moved and callback expressions remain equivalent.-- Run `:app:compileDebugKotlin --no-daemon --console=plain`.-- Run `:app:testDebugUnitTest --no-daemon --console=plain`.+## Back, focus, and input invariants++This extraction does not move or rewrite Back, focus, or input policy.++- `BackHandler(enabled = !resumePrompt.show)` remains in `PlayerScreen`.+- `PlayerBackNavigationState` receives the same modal inputs in the same priority order.+- Closing audio/video offset from Back still clears the flag before dismissing the preview.+- `anyOverlayVisible` contains the same modal terms and continues to gate root focus and pointer handling.+- Controls auto-hide observes the same modal keys and conditions.+- Dialog-specific focus requesters and key handling remain inside their existing dialog implementations.++The new hosts must not wrap dialogs in focus groups, key handlers, additional layout containers, animations, or semantics nodes.++## Error handling and nullability++No new error state is introduced.++- A null `currentChannel` suppresses the MultiView dialog without clearing `showSplitDialog`, matching current behavior.+- Existing nullable track type, channel, series, season, episode, and title fallbacks are preserved.+- The host does not catch callback exceptions or reorder actions to compensate for them; existing failure behavior remains unchanged.++## Verification and acceptance gates++### Mechanical review++- Compare the before/after diff and account for all nine old call sites and all nine new call sites.+- Confirm only imports and the two contiguous dialog blocks moved; state declarations, effects, Back/input logic, modal-opening callbacks, and dialog implementations remain unchanged.+- Confirm host call placement and internal call order match this document.+- Confirm every argument expression and callback body is textually identical or demonstrably equivalent.- Run `git diff --check`.-- Run `graphify update .` after the Kotlin source change.-- Preserve the existing Phase 1 requirement for manual player smoke testing and full multi-channel playback validation; this extraction does not claim those gates are complete.-## Non-goals+### Automated checks++Run from the repository root:++```powershell+.\gradlew.bat :app:compileDebugKotlin --no-daemon --console=plain+.\gradlew.bat :app:testDebugUnitTest --no-daemon --console=plain+.\gradlew.bat :app:lintDebug --no-daemon --console=plain+```++Run the existing player/instrumentation and golden coverage on the Television 1080p emulator. If the complete connected suite cannot run because of an external environment failure, record the exact command, failing infrastructure condition, and the narrower successful checks; do not report the acceptance gate as passed.++No new production abstraction solely for testing is required in this mechanical slice. If focused host tests can use the existing Compose test infrastructure without changing dialog behavior, add coverage for:++- Program history hidden in PiP.+- MultiView retaining its current non-PiP-gated predicate.+- The composite audio/video-offset predicate.+- Callback ordering for program selection, MultiView launch, timer selection, audio/video-offset dismissal, subtitle/live-translation selection, and episode selection.++### Manual functional smoke test++On a TV emulator or device, verify:++- Player launch and normal playback.+- Controls open/close and auto-hide.+- Remote Back priority and focus restoration.+- Program history open, dismiss, and selection.+- MultiView planner open, dismiss, and launch.+- Track, variant, speed, both timer, audio/video-offset, and episode dialogs where applicable.+- Picture-in-Picture entry/exit, including program-history suppression and no newly introduced MultiView rule.+- Cast-connected suppression of audio/video offset where applicable.++Record unavailable scenarios explicitly; an untested scenario is not a pass.++### Full player and Live TV validation++Because dialog composition moves, this change is not merge-ready until the repository's full player protocol passes:++- Validate more than one live channel.+- Capture at a 2-second cadence for at least 45 screenshots over roughly 90 seconds; prefer 61 screenshots over roughly two minutes.+- Confirm changing screenshot hashes throughout the full window.+- Confirm the media session remains `PLAYING` with `error=null`.+- Confirm logs contain no fatal player error, stuck-player timeout, or unintended MPEG-TS fallback.+- Record sanitized HLS prepare/read/first-frame or expected recovery evidence.+- Report channel names, screenshot count, interval, unique hash count, media-session result, and log findings.++Build, installation, launch, a single screenshot, or one live channel is not sufficient validation.++### Documentation and graph++- Update the Phase 1 status in the parent plan only after the applicable gates pass.+- Run `graphify update .` after Kotlin source changes. Documentation-only edits do not require claiming that the implementation graph is current.++## Rollback++Keep the extraction as a standalone, history-preserving change where practical. Rolling back `PlayerModalHosts.kt` and restoring the two original contiguous blocks must restore the prior composition without data, state, ViewModel API, or navigation migrations.++Do not combine this extraction with playback fixes, modal-state cleanup, visual changes, or dependency movement.++## Non-goals and future-phase boundary++- No new dialog behavior or corrected modal behavior, including no new MultiView PiP restriction.+- No modal exclusivity enforcement or sealed `PlayerModal`/`PlayerDialogState`.+- No state grouping, state-frequency isolation, or relocation from `PlayerScreen`.+- No route/screen split, navigation contract, or feature-module extraction.+- No change to player preparation, recovery, timeshift, surface ownership, lifecycle, or window behavior.+- No ViewModel API or dependency changes other than imports required by the file move.+- No baseline-profile work and no changes to PR #162.++Those items remain governed by their existing later phases in the parent plan.++## Definition of done++This slice is complete only when:-- No new dialog behavior, state model, navigation route, ViewModel API, or dependency.-- No Phase 2 runtime-state isolation or baseline-profile work.-- No changes to PR #162.+- Both placement-preserving hosts exist in `PlayerModalHosts.kt` and all nine call sites have moved.+- The visibility, ordering, data, callback, Back, focus, input, ViewModel-scope, and nullability contracts above are preserved.+- No future-phase state or navigation design has been introduced.+- Mechanical review, compile, unit, lint, applicable instrumentation/golden checks, manual smoke testing, and full multi-channel Live TV validation have passed or are explicitly reported as incomplete blockers.+- The parent plan describes the same Phase 1 boundary and does not claim completion prematurely.