package tv.tivilux.nativeplayer.ui import android.app.Activity import android.content.Context import android.content.ContextWrapper import tv.tivilux.nativeplayer.ui.components.panelReveal import androidx.activity.compose.BackHandler import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.focusGroup import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.tween import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.focus.FocusDirection import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusProperties import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.KeyEventType import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.input.key.type import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.viewmodel.compose.viewModel import tv.tivilux.nativeplayer.AppScreen import tv.tivilux.nativeplayer.BuildConfig import tv.tivilux.nativeplayer.R import tv.tivilux.nativeplayer.TiviLuxViewModel import tv.tivilux.nativeplayer.model.ContentType import tv.tivilux.nativeplayer.data.SupportReportContext import tv.tivilux.nativeplayer.model.MediaEntry import tv.tivilux.nativeplayer.ui.components.BusyOverlay import tv.tivilux.nativeplayer.ui.components.LuxBackground import tv.tivilux.nativeplayer.ui.components.LuxNavItem import tv.tivilux.nativeplayer.ui.components.UpdateOverlay import tv.tivilux.nativeplayer.ui.components.VideoSurface import tv.tivilux.nativeplayer.ui.components.rememberTiviLuxPlayer import tv.tivilux.nativeplayer.ui.screens.CatalogScreen import tv.tivilux.nativeplayer.ui.screens.FavoritesScreen import tv.tivilux.nativeplayer.ui.screens.HomeScreenV2 import tv.tivilux.nativeplayer.ui.screens.TIVILUX_HOME_NEXT_ENABLED import tv.tivilux.nativeplayer.ui.screens.LiveScreen import tv.tivilux.nativeplayer.ui.screens.MovieDetailScreen import tv.tivilux.nativeplayer.ui.screens.MultiViewScreen import tv.tivilux.nativeplayer.ui.screens.PlayerScreen import tv.tivilux.nativeplayer.ui.screens.ProfilesScreen import tv.tivilux.nativeplayer.ui.screens.SearchScreen import tv.tivilux.nativeplayer.ui.screens.SeriesDetailScreen import tv.tivilux.nativeplayer.ui.screens.SettingsScreen import tv.tivilux.nativeplayer.ui.screens.SportsScreenV2 import tv.tivilux.nativeplayer.ui.screens.StartupLoadingScreen import tv.tivilux.nativeplayer.ui.theme.LuxGold import tv.tivilux.nativeplayer.ui.theme.LuxLine import tv.tivilux.nativeplayer.ui.theme.LuxMuted import kotlin.math.roundToInt @Composable fun TiviLuxApp(vm: TiviLuxViewModel = viewModel()) { val credentials = vm.credentials if (credentials == null) { tv.tivilux.nativeplayer.ui.screens.LoginScreen(error = vm.error, loading = vm.loading, onLogin = vm::login) return } if (vm.startupLoading) { StartupLoadingScreen( stage = vm.startupStage, progress = vm.startupProgress, detail = vm.startupDetail, liveCount = vm.startupLiveCount, epgCompleted = vm.startupEpgCompleted, epgFound = vm.startupEpgFound, epgTotal = vm.startupEpgTotal, movieCount = vm.startupMovieCount, seriesCount = vm.startupSeriesCount, ) return } // One ExoPlayer + one PlayerView now survives the Guide <-> Fullscreen handoff. // The same Android video surface is resized from the guide preview bounds to the // whole TV instead of being destroyed/recreated, eliminating the black handoff. val sharedLivePlayer = rememberTiviLuxPlayer(vm.settings.bufferPreset, vodOptimized = false) // VOD gets a deeper forward/back buffer than Live TV. This keeps Movies/Series // playback ahead of the viewer without slowing channel changes or consuming a // second provider stream while the user is merely browsing the catalog. val sharedVodPlayer = rememberTiviLuxPlayer(vm.settings.bufferPreset, vodOptimized = true) var livePreviewBounds by remember { mutableStateOf(null) } var liveDrawerOffsetTarget by remember { mutableStateOf(0.dp) } val liveDrawerOffset = animateDpAsState( targetValue = liveDrawerOffsetTarget, animationSpec = tween(durationMillis = 180), label = "live-preview-drawer-offset", ) val density = LocalDensity.current val context = LocalContext.current val activity = context.findActivity() val lifecycleOwner = activity as? LifecycleOwner var exitGuideArmed by remember { mutableStateOf(false) } // Never allow Live/VOD audio to survive after TiviLux leaves the foreground. // MainActivity removes the task for an explicit HOME/app-switch. This observer is // the playback safety net: ON_STOP stops/clears Live TV and pauses VOD immediately, before // Compose disposal/release finishes tearing the Activity down. HOME then removes // the task, which disposes and releases the players completely. DisposableEffect(lifecycleOwner, sharedLivePlayer, sharedVodPlayer) { val observer = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_STOP) { sharedLivePlayer.playWhenReady = false sharedLivePlayer.stop() sharedLivePlayer.clearMediaItems() sharedVodPlayer.pause() } } lifecycleOwner?.lifecycle?.addObserver(observer) onDispose { lifecycleOwner?.lifecycle?.removeObserver(observer) } } LaunchedEffect(exitGuideArmed) { if (exitGuideArmed) { kotlinx.coroutines.delay(1800) exitGuideArmed = false } } val liveFullscreen = vm.currentScreen == AppScreen.PLAYER && vm.playingItem?.type == ContentType.LIVE // When fullscreen was entered from the TV Guide, keep that guide composition alive behind // the player. Returning is then just a surface resize + HUD removal instead of rebuilding the // entire guide tree, which removes most of the old black/slow handoff. val keepLiveGuideWarm = liveFullscreen && vm.previousScreen in setOf(AppScreen.LIVE, AppScreen.FAVORITES) // v0.4.6: the TV Guide preview is a permanent part of the guide. Do not let an // older saved "preview off" preference collapse the video surface after an update. val liveGuideSurface = vm.currentScreen in setOf(AppScreen.LIVE, AppScreen.FAVORITES) && vm.tunedChannel != null val liveSurfaceUrl = when { liveFullscreen -> vm.playingUrl liveGuideSurface -> { if (vm.playingItem?.type == ContentType.LIVE && vm.playingItem?.id == vm.tunedChannel?.id && !vm.playingUrl.isNullOrBlank()) vm.playingUrl else vm.previewUrl(vm.tunedChannel) } else -> null } // Startup/restored preview can have a tuned channel without a playingItem yet. // Resolve its own live fallback list rather than reusing stale VOD candidates. val liveSurfaceCandidates = when { liveFullscreen -> vm.playingUrlCandidates liveGuideSurface && vm.playingItem?.type == ContentType.LIVE && vm.playingItem?.id == vm.tunedChannel?.id -> vm.playingUrlCandidates liveGuideSurface -> vm.livePreviewUrlCandidates(vm.tunedChannel) else -> emptyList() } val livePlaybackActive = !liveSurfaceUrl.isNullOrBlank() val vodPlaybackActive = vm.currentScreen == AppScreen.PLAYER && vm.playingItem?.type in setOf(ContentType.MOVIE, ContentType.EPISODE) // Pause retains prepared decoders and can keep buffering a stream no longer on // screen. Stop/clear inactive shared players so the active player (or MultiView) // gets those resources. Guide <-> live fullscreen remains the same active player. LaunchedEffect(livePlaybackActive, vodPlaybackActive, sharedLivePlayer, sharedVodPlayer) { if (!livePlaybackActive) { sharedLivePlayer.stop() sharedLivePlayer.clearMediaItems() livePreviewBounds = null } if (!vodPlaybackActive) { sharedVodPlayer.stop() sharedVodPlayer.clearMediaItems() } } LaunchedEffect(vm.currentScreen) { if (vm.currentScreen != AppScreen.LIVE) exitGuideArmed = false } val focusManager = LocalFocusManager.current // HOME V2 owns a permanent left navigation rail. If the one-line V2 rollback flag is // disabled, HOME immediately regains the legacy edge-LEFT overlay behavior too. val railEligible = vm.currentScreen in setOf( AppScreen.HOME, AppScreen.LIVE, AppScreen.SPORTS, AppScreen.MOVIES, AppScreen.SERIES, AppScreen.FAVORITES, AppScreen.SEARCH, AppScreen.SETTINGS ) && !(vm.currentScreen == AppScreen.HOME && TIVILUX_HOME_NEXT_ENABLED) var railVisible by rememberSaveable { mutableStateOf(false) } LaunchedEffect(vm.currentScreen) { // Content gets the full TV canvas. The navigation rail is an on-demand overlay only: // press LEFT at the edge to reveal it, then RIGHT/select to hide it again. if (vm.currentScreen != AppScreen.PLAYER) railVisible = false } if (vm.currentScreen != AppScreen.PLAYER) { if (railVisible) { BackHandler { railVisible = false focusManager.moveFocus(FocusDirection.Right) } } else if (vm.currentScreen in setOf( AppScreen.SPORTS, AppScreen.MOVIES, AppScreen.SERIES, AppScreen.FAVORITES, AppScreen.SEARCH, AppScreen.SETTINGS, AppScreen.PROFILES ) ) { BackHandler { vm.navigate(AppScreen.HOME) } } } fun navigateFromRail(screen: AppScreen) { vm.navigate(screen) focusManager.moveFocus(FocusDirection.Right) railVisible = false } Box(Modifier.fillMaxSize().background(Color.Black)) { if (vm.currentScreen != AppScreen.PLAYER || keepLiveGuideWarm) { LuxBackground { Box( Modifier.fillMaxSize().onPreviewKeyEvent { event -> if (event.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false when (event.key) { Key.DirectionLeft -> { if (!railEligible) false else if (railVisible) false else if (vm.currentScreen == AppScreen.LIVE && vm.settings.remoteShortcutsEnabled) false // Let Settings rows consume LEFT themselves (category organizer uses // LEFT/RIGHT to reorder). Back still exits the Settings section. else if (vm.currentScreen == AppScreen.SETTINGS) false else { val movedInsideContent = focusManager.moveFocus(FocusDirection.Left) if (!movedInsideContent) railVisible = true true } } Key.DirectionRight -> { if (railVisible) { focusManager.moveFocus(FocusDirection.Right) railVisible = false true } else false } else -> false } } ) { when (if (keepLiveGuideWarm) vm.previousScreen else vm.currentScreen) { AppScreen.HOME -> HomeScreenV2( session = vm.session, activeProfile = vm.activeProfile, profilesCount = vm.profiles.size, lastPlayed = vm.lastPlayed(), continueWatching = vm.continueWatching(), sportsLiveCount = vm.sportsLiveCount(), sportsChannelCount = vm.sportsCandidateChannels().size, sportsScanning = vm.sportsScanning, sportsBackgroundLoading = vm.sportsBackgroundLoading, sportsBackgroundCategory = vm.sportsBackgroundCategory, sportsBackgroundReady = vm.sportsBackgroundReady, onNavigate = vm::navigate, onResume = { vm.play(it, AppScreen.HOME) }, onContinue = vm::playContinueWatching, onRemoveContinue = vm::removeFromContinueWatching, onProfiles = { vm.navigate(AppScreen.PROFILES) }, onLastChannel = vm::openLastChannelInGuide, onRefreshGuide = vm::refreshTvGuideFromHome, ) AppScreen.LIVE -> LiveScreen( categories = vm.liveGuideCategories(), selectedCategory = vm.selectedCategories[ContentType.LIVE], channels = vm.catalogForDisplay(ContentType.LIVE), tunedChannel = vm.tunedChannel, epgByChannel = vm.epgByChannel, settings = vm.settings, onPreviewBoundsChanged = { bounds -> if (livePreviewBounds != bounds) livePreviewBounds = bounds }, onDrawerOffsetTargetChanged = { target -> if (liveDrawerOffsetTarget != target) liveDrawerOffsetTarget = target }, drawerOffset = { liveDrawerOffset.value }, onCategory = { vm.loadCategory(ContentType.LIVE, it) }, onChannel = vm::selectChannel, onNeedEpg = vm::ensureEpg, onPlayFullScreen = { vm.play(it, AppScreen.LIVE) }, onOpenMultiView = { vm.navigate(AppScreen.MULTIVIEW) }, onShortBack = { if (exitGuideArmed) { sharedLivePlayer.stop() if (android.os.Build.VERSION.SDK_INT >= 21) activity?.finishAndRemoveTask() else activity?.finish() } else { exitGuideArmed = true } }, onOpenSettings = { vm.navigate(AppScreen.SETTINGS) }, onSettingsChanged = vm::updateSettings, onRequestMainMenu = { railVisible = true }, onFavorite = vm::toggleFavorite, onHideChannel = vm::toggleLiveChannelHidden, isFavorite = vm::isFavorite, favoriteKeys = vm.favoriteKeysState, initialAnchorChannelId = vm.guideOpenAnchorChannelId, onGuideInteractionChanged = vm::setGuideInteractionBusy, favoritesGuide = vm.isFavoritesGuideSelected(), categorySort = vm.guideSortForCategory(vm.selectedCategories[ContentType.LIVE]), onCategorySortChanged = { vm.setGuideSortForCategory(vm.selectedCategories[ContentType.LIVE], it) }, manualOrder = vm.manualGuideOrder(vm.isFavoritesGuideSelected(), if (vm.isFavoritesGuideSelected()) null else vm.selectedCategories[ContentType.LIVE]), onManualOrderChanged = { vm.saveManualGuideOrder(it, vm.isFavoritesGuideSelected(), if (vm.isFavoritesGuideSelected()) null else vm.selectedCategories[ContentType.LIVE]) }, interactive = !liveFullscreen && !railVisible, ) AppScreen.MULTIVIEW -> MultiViewScreen( channels = vm.allVisibleLiveChannels(), categories = vm.liveGuideCategories(), selectedCategoryId = vm.selectedCategories[ContentType.LIVE], channelsForCategory = vm::liveChannelsForCategory, slots = vm.multiViewSlots, bufferPreset = vm.settings.bufferPreset, maxConnections = vm.session?.maxConnections ?: 0, streamUrlFor = vm::previewUrl, onSetSlot = vm::setMultiViewSlot, onPlayFullScreen = { vm.play(it, AppScreen.MULTIVIEW) }, onBack = vm::exitMultiView, ) AppScreen.SPORTS -> SportsScreenV2( selectedLeague = vm.selectedSportsLeague, summaries = vm.sportsLeagueSummaries(), events = vm.sportsEvents(), channels = vm.sportsCandidateChannels(vm.selectedSportsLeague), scanning = vm.sportsScanning, scanCompleted = vm.sportsScanCompleted, scanTotal = vm.sportsScanTotal, preparing = vm.sportsPreparing, loadingStage = vm.sportsLoadingStage, readyNoticeToken = vm.sportsReadyNoticeToken, readyNoticePending = vm.sportsReadyNoticePending, onReadyNoticeShown = vm::consumeSportsReadyNotice, onLeague = vm::selectSportsLeague, onRefresh = { vm.refreshSports(force = true, league = vm.selectedSportsLeague) }, onPlayChannel = vm::playSportsChannel, ) AppScreen.MOVIES -> CatalogScreen( title = "Movies", eyebrow = "ON DEMAND", categories = vm.visibleCategories(ContentType.MOVIE), selectedCategory = vm.selectedCategories[ContentType.MOVIE], entries = vm.catalogForDisplay(ContentType.MOVIE), searchEntries = vm.catalogForSearch(ContentType.MOVIE), refreshStatus = vm.playlistRefreshStatus, onRefresh = vm::updatePlaylistManually, onCategory = { vm.loadCategory(ContentType.MOVIE, it) }, onEntry = { vm.openMovie(it, AppScreen.MOVIES) }, ) AppScreen.SERIES -> CatalogScreen( title = "Series", eyebrow = "YOUR LIBRARY", categories = vm.visibleCategories(ContentType.SERIES), selectedCategory = vm.selectedCategories[ContentType.SERIES], entries = vm.catalogForDisplay(ContentType.SERIES), searchEntries = vm.catalogForSearch(ContentType.SERIES), refreshStatus = vm.playlistRefreshStatus, onRefresh = vm::updatePlaylistManually, onCategory = { vm.loadCategory(ContentType.SERIES, it) }, onEntry = { vm.openSeries(it, AppScreen.SERIES) }, ) AppScreen.MOVIE_DETAIL -> { BackHandler { vm.backFromDetail() } val detail = vm.selectedMovieDetail MovieDetailScreen( detail = detail, isFavorite = detail?.movie?.let(vm::isFavorite) == true, resumePositionMs = vm.playbackPosition(detail?.movie), onBack = vm::backFromDetail, onPlay = { detail?.movie?.let { vm.play(it, AppScreen.MOVIE_DETAIL) } }, onFavorite = { detail?.movie?.let(vm::toggleFavorite) }, ) } AppScreen.SERIES_DETAIL -> { BackHandler { vm.backFromDetail() } val detail = vm.selectedSeriesDetail SeriesDetailScreen( detail = detail, isFavorite = detail?.series?.let(vm::isFavorite) == true, onBack = vm::backFromDetail, onFavorite = { detail?.series?.let(vm::toggleFavorite) }, onPlayEpisode = vm::playEpisode, progressForEpisode = vm::episodeProgress, ) } AppScreen.FAVORITES -> { val favoriteLive = vm.favoriteLiveChannels() if (favoriteLive.isNotEmpty()) { LiveScreen( categories = emptyList(), selectedCategory = null, channels = favoriteLive, tunedChannel = vm.tunedChannel, epgByChannel = vm.epgByChannel, settings = vm.settings, onPreviewBoundsChanged = { bounds -> if (livePreviewBounds != bounds) livePreviewBounds = bounds }, onDrawerOffsetTargetChanged = { target -> if (liveDrawerOffsetTarget != target) liveDrawerOffsetTarget = target }, drawerOffset = { liveDrawerOffset.value }, onCategory = { }, onChannel = vm::selectChannel, onNeedEpg = vm::ensureEpg, onPlayFullScreen = { vm.play(it, AppScreen.FAVORITES) }, onOpenMultiView = { vm.navigate(AppScreen.MULTIVIEW) }, onShortBack = { vm.navigate(AppScreen.HOME) }, onOpenSettings = { vm.navigate(AppScreen.SETTINGS) }, onSettingsChanged = vm::updateSettings, onRequestMainMenu = { railVisible = true }, onFavorite = vm::toggleFavorite, onHideChannel = vm::toggleLiveChannelHidden, isFavorite = vm::isFavorite, favoriteKeys = vm.favoriteKeysState, initialAnchorChannelId = vm.guideOpenAnchorChannelId, onGuideInteractionChanged = vm::setGuideInteractionBusy, favoritesGuide = true, manualOrder = vm.manualGuideOrder(favorites = true), onManualOrderChanged = { vm.saveManualGuideOrder(it, favorites = true) }, interactive = !liveFullscreen && !railVisible, ) } else { FavoritesScreen(vm.favoritesFromLoaded()) { handleEntry(vm, it, AppScreen.FAVORITES) } } } AppScreen.SEARCH -> SearchScreen(vm.searchQuery, vm.searchResults(), vm::updateSearchQuery) { handleEntry(vm, it, AppScreen.SEARCH) } AppScreen.SETTINGS -> SettingsScreen( session = vm.session, settings = vm.settings, onSettings = vm::updateSettings, onLogout = vm::logout, onCheckUpdates = { vm.checkForUpdates(silent = false) }, onUpdatePlaylist = vm::updatePlaylistManually, playlistRefreshStatus = vm.playlistRefreshStatus, onManageProfiles = { vm.navigate(AppScreen.PROFILES) }, reportContext = run { val reportItem = vm.playingItem val reportNow = System.currentTimeMillis() / 1000L val reportProgram = reportItem?.takeIf { it.type == ContentType.LIVE }?.let { liveItem -> vm.epgByChannel[liveItem.id].orEmpty().firstOrNull { reportNow in it.startEpoch until it.endEpoch }?.title }.orEmpty() SupportReportContext( accountHint = vm.session?.username.orEmpty(), profile = vm.activeProfile.name, channelName = reportItem?.name.orEmpty(), channelNumber = reportItem?.number?.takeIf { it > 0 }?.toString().orEmpty(), program = reportProgram, contentType = reportItem?.type?.name.orEmpty(), sportsEvent = if (vm.previousScreen == AppScreen.SPORTS) reportProgram else "", sportsFeed = if (vm.previousScreen == AppScreen.SPORTS) reportItem?.name.orEmpty() else "", ) }, categoryLists = mapOf( ContentType.LIVE to vm.categoryManagementList(ContentType.LIVE), ContentType.MOVIE to vm.categoryManagementList(ContentType.MOVIE), ContentType.SERIES to vm.categoryManagementList(ContentType.SERIES), ), hiddenCategoryIds = mapOf( ContentType.LIVE to vm.hiddenCategoryIds(ContentType.LIVE), ContentType.MOVIE to vm.hiddenCategoryIds(ContentType.MOVIE), ContentType.SERIES to vm.hiddenCategoryIds(ContentType.SERIES), ), hiddenLiveChannels = vm.hiddenLiveChannels(), onMoveCategory = vm::moveCategory, onToggleCategoryHidden = vm::toggleCategoryHidden, onUnhideLiveChannel = vm::toggleLiveChannelHidden, updateStatus = vm.updateStatus, ) AppScreen.PROFILES -> ProfilesScreen( profiles = vm.profiles, activeProfile = vm.activeProfile, onSelect = vm::selectProfile, onCreate = vm::createProfile, onRename = vm::renameProfile, onDelete = vm::deleteProfile, onBack = { vm.navigate(AppScreen.HOME) }, ) AppScreen.PLAYER -> Unit } } } } // Persistent live video layer. During guide browsing it occupies only the preview // rectangle. Entering fullscreen simply resizes this exact PlayerView in-place. if (liveFullscreen) { Box(Modifier.fillMaxSize().background(Color.Black)) } if ((liveFullscreen || liveGuideSurface) && !liveSurfaceUrl.isNullOrBlank()) { val surfaceModifier = if (liveFullscreen) { Modifier.fillMaxSize() } else { val bounds = livePreviewBounds if (bounds == null || bounds.width <= 1f || bounds.height <= 1f) { Modifier.size(1.dp) } else { Modifier .offset { IntOffset(bounds.left.roundToInt(), bounds.top.roundToInt()) } .graphicsLayer { // GPU-only translation: move the persistent PlayerView with Groups // without reallocating/resizing the Android video surface every frame. translationX = liveDrawerOffset.value.toPx() } .size( width = with(density) { bounds.width.toDp() }, height = with(density) { bounds.height.toDp() }, ) .clip(RoundedCornerShape(12.dp)) .border(1.dp, Color(0xFF394553), RoundedCornerShape(12.dp)) } } VideoSurface( url = liveSurfaceUrl, modifier = surfaceModifier, autoPlay = true, controller = false, bufferPreset = vm.settings.bufferPreset, externalPlayer = sharedLivePlayer, managedLive = true, liveCandidates = liveSurfaceCandidates, diagnosticChannelKey = (if (liveFullscreen) vm.playingItem else vm.tunedChannel)?.id?.toString().orEmpty(), diagnosticChannelName = (if (liveFullscreen) vm.playingItem else vm.tunedChannel)?.name ?: "Live channel", // Build 78: both Guide preview and fullscreen use SurfaceView-backed PlayerView // rendering for direct hardware composition and steadier frame pacing while the // Compose guide scrolls. The ExoPlayer instance remains shared, so this does not // create a second stream/provider connection. preferSurfaceView = liveFullscreen, ) } if (vm.currentScreen == AppScreen.PLAYER) { val playerItem = vm.playingItem PlayerScreen( item = playerItem, url = vm.playingUrl, urlCandidates = vm.playingUrlCandidates, bufferPreset = vm.settings.bufferPreset, livePlayer = sharedLivePlayer, vodPlayer = sharedVodPlayer, initialPositionMs = vm.playbackPosition(playerItem), videoSurfaceOwnedExternally = liveFullscreen, remoteShortcutsEnabled = vm.settings.remoteShortcutsEnabled, showFullscreenClock = vm.settings.showFullscreenClock, fullscreenClockSize = vm.settings.fullscreenClockSize, fullscreenClockPosition = vm.settings.fullscreenClockPosition, liveChannels = vm.catalogForDisplay(ContentType.LIVE), liveCategories = vm.visibleCategories(ContentType.LIVE), recentChannels = vm.recentLiveChannels, selectedLiveCategory = vm.selectedCategories[ContentType.LIVE], epgByChannel = vm.epgByChannel, isFavorite = playerItem?.let(vm::isFavorite) == true, accountHint = vm.session?.username.orEmpty(), profileName = vm.activeProfile.name, launchedFromSports = vm.previousScreen == AppScreen.SPORTS, onBack = vm::backFromPlayer, onOpenGuide = vm::openGuideForPlayingChannel, onOpenSearch = { vm.navigate(AppScreen.SEARCH) }, onOpenSettings = { vm.navigate(AppScreen.SETTINGS) }, onPreviousChannel = vm::tunePreviousLive, onChannelUp = { vm.tuneAdjacentLive(-1) }, onChannelDown = { vm.tuneAdjacentLive(1) }, onTuneChannel = vm::tuneLiveFromPlayer, onSelectCategory = { vm.loadCategory(ContentType.LIVE, it) }, onToggleFavorite = { vm.playingItem?.let(vm::toggleFavorite) }, onRemoveFromHistory = vm::removeCurrentLiveFromHistory, onPlaybackProgress = { position, duration, ended -> vm.recordPlaybackProgress(playerItem, position, duration, ended) }, ) } if (vm.currentScreen != AppScreen.PLAYER && railVisible) { SideRail(vm.currentScreen, ::navigateFromRail) } if (vm.currentScreen == AppScreen.LIVE && exitGuideArmed && !railVisible) { Box( Modifier.align(Alignment.BottomCenter) .padding(bottom = 34.dp) .background(Color(0xED0A0F14), RoundedCornerShape(10.dp)) .border(1.dp, LuxGold.copy(alpha = .8f), RoundedCornerShape(10.dp)) .padding(horizontal = 18.dp, vertical = 10.dp) ) { Text( "Press BACK again to exit TiviLux", color = Color.White, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, ) } } if (vm.currentScreen != AppScreen.PLAYER) { BusyOverlay(vm.loading) ErrorBanner(vm.error, vm::clearError) } vm.availableUpdate?.let { update -> UpdateOverlay( update = update, downloading = vm.updateDownloading, progress = vm.updateProgress, status = vm.updateStatus, error = vm.updateError, onUpdate = vm::beginUpdate, onLater = vm::dismissUpdate, onResume = vm::onAppResumed, ) } } } private fun handleEntry(vm: TiviLuxViewModel, item: MediaEntry, returnTo: AppScreen) { when (item.type) { ContentType.SERIES -> vm.openSeries(item, returnTo) ContentType.MOVIE -> vm.openMovie(item, returnTo) else -> vm.play(item, returnTo) } } @Composable private fun SideRail(active: AppScreen, onNavigate: (AppScreen) -> Unit) { // Explicit D-pad focus links keep the rail focus inside the rail. Android TV's // spatial focus search was occasionally jumping from Movies back into the guide // because the guide sits immediately to the right of this overlay. val requesters = remember { List(8) { FocusRequester() } } val activeIndex = when (active) { AppScreen.HOME -> 0 AppScreen.LIVE -> 1 AppScreen.SPORTS -> 2 AppScreen.MOVIES, AppScreen.MOVIE_DETAIL -> 3 AppScreen.SERIES, AppScreen.SERIES_DETAIL -> 4 AppScreen.FAVORITES -> 5 AppScreen.SEARCH -> 6 AppScreen.SETTINGS -> 7 else -> 0 } // The rail is a modal focus surface. When it appears, explicitly take focus away from // Live TV so repeated D-pad events cannot keep moving the guide behind the menu. val railFocusManager = LocalFocusManager.current LaunchedEffect(activeIndex) { railFocusManager.clearFocus(force = true) androidx.compose.runtime.withFrameNanos { } runCatching { requesters[activeIndex].requestFocus() } } fun navModifier(index: Int): Modifier = Modifier.focusProperties { up = requesters[(index - 1).coerceAtLeast(0)] down = requesters[(index + 1).coerceAtMost(requesters.lastIndex)] } Column( Modifier.width(148.dp).fillMaxHeight() .panelReveal() .focusGroup() .background(Color(0xF5090B10)) .border(width = 1.dp, color = LuxLine) .padding(12.dp, 18.dp), verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(4.dp), ) { Image( painter = painterResource(R.drawable.tivilux_wordmark), contentDescription = "TiviLux", modifier = Modifier.width(116.dp).height(42.dp), ) Spacer(Modifier.height(12.dp)) LuxNavItem( "Home", active == AppScreen.HOME, requestFocus = active == AppScreen.HOME, modifier = navModifier(0), focusRequester = requesters[0], ) { onNavigate(AppScreen.HOME) } LuxNavItem( "Live TV", active == AppScreen.LIVE, requestFocus = active == AppScreen.LIVE, modifier = navModifier(1), focusRequester = requesters[1], ) { onNavigate(AppScreen.LIVE) } LuxNavItem( "Sports", active == AppScreen.SPORTS, requestFocus = active == AppScreen.SPORTS, modifier = navModifier(2), focusRequester = requesters[2], ) { onNavigate(AppScreen.SPORTS) } LuxNavItem( "Movies", active == AppScreen.MOVIES || active == AppScreen.MOVIE_DETAIL, requestFocus = active == AppScreen.MOVIES || active == AppScreen.MOVIE_DETAIL, modifier = navModifier(3), focusRequester = requesters[3], ) { onNavigate(AppScreen.MOVIES) } LuxNavItem( "Series", active == AppScreen.SERIES || active == AppScreen.SERIES_DETAIL, requestFocus = active == AppScreen.SERIES || active == AppScreen.SERIES_DETAIL, modifier = navModifier(4), focusRequester = requesters[4], ) { onNavigate(AppScreen.SERIES) } Spacer(Modifier.height(8.dp)) LuxNavItem( "Favorites", active == AppScreen.FAVORITES, requestFocus = active == AppScreen.FAVORITES, modifier = navModifier(5), focusRequester = requesters[5], ) { onNavigate(AppScreen.FAVORITES) } LuxNavItem( "Search", active == AppScreen.SEARCH, requestFocus = active == AppScreen.SEARCH, modifier = navModifier(6), focusRequester = requesters[6], ) { onNavigate(AppScreen.SEARCH) } Spacer(Modifier.weight(1f)) LuxNavItem( "Settings", active == AppScreen.SETTINGS, requestFocus = active == AppScreen.SETTINGS, modifier = navModifier(7), focusRequester = requesters[7], ) { onNavigate(AppScreen.SETTINGS) } Text("NATIVE ${BuildConfig.VERSION_NAME}", color = LuxMuted.copy(alpha = .6f), fontSize = 8.sp, letterSpacing = 1.0.sp, modifier = Modifier.padding(8.dp, 6.dp)) } } @Composable private fun ErrorBanner(error: String?, onDismiss: () -> Unit) { if (error.isNullOrBlank()) return Box( Modifier.fillMaxWidth().padding(18.dp) .background(Color(0xFF5A252B), RoundedCornerShape(12.dp)) .border(1.dp, Color(0xFFFF9DA8), RoundedCornerShape(12.dp)) .padding(12.dp) ) { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { Text(error, color = Color.White, modifier = Modifier.weight(1f), fontSize = 12.sp) Text("DISMISS", color = LuxGold, fontWeight = FontWeight.Bold, modifier = Modifier.padding(start = 14.dp)) } } LaunchedEffect(error) { kotlinx.coroutines.delay(6000) onDismiss() } } private tailrec fun Context.findActivity(): Activity? = when (this) { is Activity -> this is ContextWrapper -> baseContext.findActivity() else -> null }