package eu.friedcutlet.yokan.ui.screens.player import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.automirrored.filled.PlaylistPlay import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.FitScreen import androidx.compose.material.icons.filled.Fullscreen import androidx.compose.material.icons.filled.HighQuality import androidx.compose.material.icons.filled.Memory import androidx.compose.material.icons.filled.Pause import androidx.compose.material.icons.filled.PictureInPictureAlt import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.material.icons.filled.Screenshot import androidx.compose.material.icons.filled.SkipNext import androidx.compose.material.icons.filled.SkipPrevious import androidx.compose.material.icons.filled.Terminal import androidx.compose.material.icons.filled.VideoLibrary import androidx.compose.material3.Button import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Slider import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.BiasAlignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import eu.friedcutlet.yokan.database.DbCustomButton import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.services.logging.AppLogger import eu.friedcutlet.yokan.services.media.player.MediaPlayerController import eu.friedcutlet.yokan.services.media.player.MpvChapterMark import eu.friedcutlet.yokan.services.media.player.MpvMenuAction import eu.friedcutlet.yokan.services.media.player.MpvShaderActions import eu.friedcutlet.yokan.services.media.player.MpvStatsActions import eu.friedcutlet.yokan.services.media.player.MpvVideoFit import eu.friedcutlet.yokan.services.media.player.SeekThumbnail import eu.friedcutlet.yokan.services.media.player.SleepTimer import eu.friedcutlet.yokan.services.media.player.at import eu.friedcutlet.yokan.services.media.player.selectMpvShader import eu.friedcutlet.yokan.services.media.player.setMpvVideoFit import eu.friedcutlet.yokan.services.media.player.showMpvStats import eu.friedcutlet.yokan.ui.status.GlobalStatusAccessButton import eu.friedcutlet.yokan.util.nowMillis import org.jetbrains.compose.resources.stringResource import yokan.composeapp.generated.resources.Res import yokan.composeapp.generated.resources.action_back import yokan.composeapp.generated.resources.custom_buttons import yokan.composeapp.generated.resources.player_screenshot import yokan.composeapp.generated.resources.ui_player_settings /** * Flutter's player used a transparent top button bar over one dimmed full-screen backdrop, * rather than an opaque Material app bar. */ @Composable internal fun PlayerTopBar( title: String, episodeName: String, minimized: Boolean, sleepTimer: SleepTimer?, castSupported: Boolean, casting: Boolean, onLeave: () -> Unit, onRestore: () -> Unit, onDismiss: () -> Unit, onSetSleepTimer: (minutes: Int?) -> Unit, onCancelSleepTimer: () -> Unit, onCast: () -> Unit, onOpenEpisodes: () -> Unit, onScreenshot: () -> Unit, ) { Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 4.dp, vertical = 6.dp), verticalAlignment = Alignment.CenterVertically, ) { IconButton(onClick = onLeave) { Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(Res.string.action_back), tint = Color.White) } if (minimized) { IconButton( onClick = onRestore, modifier = Modifier.semantics { contentDescription = "Restore full player" }, ) { Icon(Icons.Filled.Fullscreen, contentDescription = "Restore full player", tint = Color.White) } IconButton( onClick = onDismiss, modifier = Modifier.semantics { contentDescription = "Dismiss mini player" }, ) { Icon(Icons.Filled.Close, contentDescription = "Dismiss mini player", tint = Color.White) } } Column(modifier = Modifier.weight(1f)) { Text( title, maxLines = 1, overflow = TextOverflow.Ellipsis, color = Color.White, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold, ) Text( episodeName, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodySmall, color = Color.White.copy(alpha = 0.70f), ) } SleepTimerButton( remainingLabel = sleepTimer?.let { timer -> timer.deadlineMs?.let { "${((it - nowMillis()).coerceAtLeast(0L) + 59_999L) / 60_000L}m" } ?: "End" }, onSelect = onSetSleepTimer, onCancel = onCancelSleepTimer, ) if (castSupported) CastButton(casting = casting, onClick = onCast) GlobalStatusAccessButton(tint = Color.White) IconButton(onClick = onOpenEpisodes) { Icon(Icons.AutoMirrored.Filled.PlaylistPlay, contentDescription = "Episodes", tint = Color.White) } IconButton(onClick = onScreenshot) { Icon(Icons.Filled.Screenshot, contentDescription = stringResource(Res.string.player_screenshot), tint = Color.White) } } } @Composable internal fun PlayerNotice(text: String, modifier: Modifier = Modifier) { Surface( modifier = modifier, color = Color.Black.copy(alpha = 0.78f), shape = RoundedCornerShape(8.dp), ) { Text( text, modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp), color = Color.White, style = MaterialTheme.typography.bodySmall, maxLines = 2, overflow = TextOverflow.Ellipsis, ) } } /** * Mobile controls in Mangayomi: previous episode / play-pause / next episode, with double-tap * seeking handled by the video gesture layer. [onPictureInPicture] null hides the PiP button. */ @Composable internal fun PlayerCenterControls( isPlaying: Boolean, onPrevious: () -> Unit, onPlayPause: () -> Unit, onNext: () -> Unit, onPictureInPicture: (() -> Unit)?, ) { Row( horizontalArrangement = Arrangement.spacedBy(32.dp), verticalAlignment = Alignment.CenterVertically, ) { IconButton(onClick = onPrevious) { Icon(Icons.Filled.SkipPrevious, contentDescription = "Previous episode", tint = Color.White, modifier = Modifier.size(40.dp)) } IconButton(onClick = onPlayPause, modifier = Modifier.size(72.dp)) { Icon( imageVector = if (isPlaying) Icons.Filled.Pause else Icons.Filled.PlayArrow, contentDescription = if (isPlaying) "Pause" else "Play", tint = Color.White, modifier = Modifier.size(56.dp), ) } IconButton(onClick = onNext) { Icon(Icons.Filled.SkipNext, contentDescription = "Next episode", tint = Color.White, modifier = Modifier.size(40.dp)) } if (onPictureInPicture != null) { IconButton(onClick = onPictureInPicture) { Icon(Icons.Filled.PictureInPictureAlt, contentDescription = "Enter picture-in-picture", tint = Color.White) } } } } /** * Loading bar, stream error, seek preview and the seek slider. While the user drags, * [dragFraction] holds the in-flight value so the slider doesn't fight the player's tick. */ @Composable internal fun PlayerTimeline( loading: Boolean, error: String?, position: Float, dragFraction: Float?, durationMs: Long, seekThumbnails: List, seekSprites: Map, onDrag: (Float) -> Unit, onDragFinished: () -> Unit, onLoadSeekSprite: (url: String) -> Unit, ) { if (loading) { LinearProgressIndicator( modifier = Modifier .fillMaxWidth() .height(4.dp) .clip(RoundedCornerShape(50)) .padding(bottom = 4.dp), ) } if (!error.isNullOrBlank()) { Surface( shape = RoundedCornerShape(50), color = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.9f), ) { Text( error, modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), color = MaterialTheme.colorScheme.onErrorContainer, style = MaterialTheme.typography.bodySmall, ) } } val previewTile = dragFraction?.let { seekThumbnails.at((it * durationMs).toLong()) } if (dragFraction != null && previewTile != null) { LaunchedEffect(previewTile.imageUrl) { onLoadSeekSprite(previewTile.imageUrl) } seekSprites[previewTile.imageUrl]?.let { sprite -> // Align over the thumb; the 70 dp padding matches the time pills around the slider. Box(Modifier.fillMaxWidth().padding(horizontal = 70.dp)) { SeekPreview(previewTile, sprite, Modifier.align(BiasAlignment(dragFraction * 2f - 1f, 0f))) } } } Row(verticalAlignment = Alignment.CenterVertically) { PlayerTimePill(formatPlayerTime(((position * durationMs) / 1000L).toLong())) Slider( value = position, onValueChange = onDrag, onValueChangeFinished = onDragFinished, modifier = Modifier.weight(1f), ) PlayerTimePill(formatPlayerTime(durationMs / 1000L)) } } /** * Bottom actions of the old mobile player: skip, chapter, settings, [mpvMenus], speed, fit and * fullscreen. [aniSkipType] names the active AniSkip segment; otherwise skip jumps [skipIntroSeconds]. */ @Composable internal fun PlayerActionRow( aniSkipType: String?, skipIntroSeconds: Int, onSkip: () -> Unit, chapterMarks: List, currentChapterMark: Int, onSeekToMark: (positionMs: Long) -> Unit, onOpenSettings: () -> Unit, speed: Float, speedPresets: List, onSelectSpeed: (Float) -> Unit, videoFit: MpvVideoFit, onCycleVideoFit: () -> Unit, onToggleFullscreen: () -> Unit, mpvMenus: @Composable RowScope.() -> Unit, ) { Row( modifier = Modifier .fillMaxWidth() .padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.End, ) { Button( onClick = onSkip, modifier = Modifier.height(35.dp), contentPadding = PaddingValues(horizontal = 12.dp, vertical = 0.dp), ) { Text(aniSkipType?.let { "AniSkip $it" } ?: "+$skipIntroSeconds", fontWeight = FontWeight.Light) } if (aniSkipType != null) Spacer(Modifier.width(4.dp)) chapterMarks.getOrNull(currentChapterMark)?.let { currentMark -> PlayerChapterMenu(currentMark, chapterMarks, onSeekToMark) } Spacer(Modifier.weight(1f)) IconButton(onClick = onOpenSettings) { Icon(Icons.Filled.VideoLibrary, contentDescription = stringResource(Res.string.ui_player_settings), tint = Color.White) } mpvMenus() SpeedPresetButton(speed = speed, presets = speedPresets, onSelect = onSelectSpeed) IconButton(onClick = onCycleVideoFit) { Column(horizontalAlignment = Alignment.CenterHorizontally) { Icon(Icons.Filled.FitScreen, contentDescription = "Fit / Zoom", tint = Color.White) Text(videoFit.label, color = Color.White, style = MaterialTheme.typography.labelSmall) } } IconButton(onClick = onToggleFullscreen) { Icon(Icons.Filled.Fullscreen, contentDescription = "Fullscreen", tint = Color.White) } } } @Composable private fun PlayerChapterMenu(current: MpvChapterMark, marks: List, onSeekToMark: (Long) -> Unit) { var open by remember { mutableStateOf(false) } Box { TextButton(onClick = { open = true }, modifier = Modifier.height(35.dp)) { Text( "${current.title} · ${formatPlayerTime(current.positionMs / 1000L)}", maxLines = 1, overflow = TextOverflow.Ellipsis, color = Color.White, style = MaterialTheme.typography.labelSmall, ) } DropdownMenu(expanded = open, onDismissRequest = { open = false }) { marks.forEach { mark -> DropdownMenuItem( text = { Text("${mark.title} · ${formatPlayerTime(mark.positionMs / 1000L)}") }, onClick = { open = false onSeekToMark(mark.positionMs) }, ) } } } } /** * mpv-only menus: shaders and stats when [shadersAndStats], and the user's custom buttons while * [customButtonVisible]. [onCustomButton] runs a button's press or long-press script. */ @Composable internal fun PlayerMpvMenus( shadersAndStats: Boolean, selectedShader: String, onShader: (MpvMenuAction) -> Unit, onStats: (MpvMenuAction) -> Unit, customButtons: List, customButtonVisible: Boolean, primaryCustomButtonId: Long?, activeCustomButtonTitle: String, onCustomButton: (button: DbCustomButton, longPress: Boolean) -> Unit, ) { if (shadersAndStats) { PlayerMenuButton( icon = { Icon(Icons.Filled.HighQuality, contentDescription = "Shaders", tint = Color.White) }, actions = MpvShaderActions, label = { action -> Text(action.label, fontWeight = if (selectedShader == action.label) FontWeight.Bold else FontWeight.Normal) }, onSelect = onShader, ) PlayerMenuButton( icon = { Icon(Icons.Filled.Memory, contentDescription = "Stats", tint = Color.White) }, actions = MpvStatsActions, label = { action -> Text(action.label) }, onSelect = onStats, ) } if (customButtons.isEmpty() || !customButtonVisible) return var open by remember { mutableStateOf(false) } Box { IconButton(onClick = { open = true }) { Column(horizontalAlignment = Alignment.CenterHorizontally) { Icon(Icons.Filled.Terminal, contentDescription = stringResource(Res.string.custom_buttons), tint = Color.White) activeCustomButtonTitle.takeIf { it.isNotBlank() }?.let { Text(it, maxLines = 1, color = Color.White, style = MaterialTheme.typography.labelSmall) } } } DropdownMenu(expanded = open, onDismissRequest = { open = false }) { customButtons.forEach { button -> val label = if (button.id == primaryCustomButtonId) { activeCustomButtonTitle.ifBlank { button.title ?: "Button" } } else { button.title ?: "Button" } DropdownMenuItem( text = { Text(label) }, onClick = { open = false AppLogger.info("custom-button press '$label'") onCustomButton(button, false) }, ) if (button.codeLongPress.isNotBlank()) { DropdownMenuItem( text = { Text("$label (long press)") }, onClick = { open = false onCustomButton(button, true) }, ) } } } } } @Composable private fun PlayerMenuButton( icon: @Composable () -> Unit, actions: List, label: @Composable (MpvMenuAction) -> Unit, onSelect: (MpvMenuAction) -> Unit, ) { var open by remember { mutableStateOf(false) } Box { IconButton(onClick = { open = true }, content = icon) DropdownMenu(expanded = open, onDismissRequest = { open = false }) { actions.forEach { action -> DropdownMenuItem( text = { label(action) }, onClick = { open = false onSelect(action) }, ) } } } } private fun formatPlayerTime(seconds: Long): String { val s = seconds.coerceAtLeast(0) val mm = s / 60 val ss = s % 60 return "${mm.toString().padStart(2, '0')}:${ss.toString().padStart(2, '0')}" } /** Fixed-width timestamp used by Mangayomi's mobile seek bar. */ @Composable private fun PlayerTimePill(text: String) { Box( modifier = Modifier.width(70.dp), contentAlignment = Alignment.Center, ) { Text( text = text, color = Color.White, style = MaterialTheme.typography.labelSmall, ) } } /** * Timeline and action row. Reads the controller's position on every tick; the drag position and * the fit mode are local to the controller. */ @Composable internal fun PlayerBottomControls( state: PlayerState, settings: DbSettings, controller: MediaPlayerController, tracks: PlayerTrackState, chapterMarks: List, currentChapterMark: Int, selectedShader: String, onShaderSelected: (String) -> Unit, customButtonVisible: Boolean, primaryCustomButtonId: Long?, activeCustomButtonTitle: String, onOpenSettings: () -> Unit, onEvent: (PlayerEvent) -> Unit, onNotice: (String) -> Unit, onUpdateSettings: ((DbSettings) -> DbSettings) -> Unit, onInteraction: () -> Unit, ) { val playerPreferences = settings.features.player var dragPosition by remember(controller) { mutableStateOf(null) } var videoFit by remember(controller) { mutableStateOf(MpvVideoFit.Contain) } // Subscribed reads: these recompose as the player ticks. val positionMs = controller.currentPositionMs() val durationMs = controller.durationMs() val aniSkipEpisodeLength = state.aniSkipMarkers.firstOrNull()?.episodeLengthSeconds?.takeIf { it > 0 } ?: 0.0 // Prefer the file's real duration; fall back to AniSkip's reported episode length, then a // 10-minute sentinel so the slider isn't zero-width before metadata arrives. val effectiveDurationMs = when { durationMs > 0L -> durationMs aniSkipEpisodeLength > 0.0 -> (aniSkipEpisodeLength * 1000).toLong() else -> 600_000L } val position = dragPosition ?: (positionMs.toFloat() / effectiveDurationMs.toFloat()).coerceIn(0f, 1f) // The AniSkip segment around the current position powers the "Skip" button. Markers are scoped // to AniSkip's own episode length, which can differ from the file's duration. val activeAniSkipMarker = state.aniSkipMarkers.firstOrNull { marker -> if (marker.episodeLengthSeconds <= 0) return@firstOrNull false positionMs / 1000.0 in marker.startSeconds..marker.endSeconds } Column( modifier = Modifier .fillMaxWidth() .padding(bottom = 18.dp), verticalArrangement = Arrangement.spacedBy(8.dp), ) { PlayerTimeline( loading = state.loading, error = state.error, position = position, dragFraction = dragPosition, durationMs = effectiveDurationMs, seekThumbnails = state.seekThumbnails, seekSprites = state.seekSprites, onDrag = { dragPosition = it onInteraction() }, onDragFinished = { controller.seekTo(((dragPosition ?: position) * effectiveDurationMs).toLong()) dragPosition = null }, onLoadSeekSprite = { onEvent(PlayerEvent.LoadSeekSprite(it)) }, ) PlayerActionRow( aniSkipType = activeAniSkipMarker?.type, skipIntroSeconds = settings.defaultSkipIntroLength, onSkip = { val targetMs = activeAniSkipMarker?.let { (it.endSeconds * 1000).toLong() } ?: (positionMs + settings.defaultSkipIntroLength * 1000L) controller.seekTo(targetMs.coerceAtMost(effectiveDurationMs)) onInteraction() }, chapterMarks = chapterMarks, currentChapterMark = currentChapterMark, onSeekToMark = { controller.seekTo(it) onInteraction() }, onOpenSettings = onOpenSettings, speed = tracks.playbackSpeed, speedPresets = playerPreferences.speedPresets, onSelectSpeed = { selected -> tracks.playbackSpeed = selected onUpdateSettings { it.copy(defaultPlaybackSpeed = selected.toDouble()) } onInteraction() }, videoFit = videoFit, onCycleVideoFit = { videoFit = MpvVideoFit.entries[(videoFit.ordinal + 1) % MpvVideoFit.entries.size] if (!controller.setMpvVideoFit(videoFit)) onNotice("Fit modes require the mpv backend") onInteraction() }, onToggleFullscreen = { onUpdateSettings { it.copy(fullScreenPlayer = !it.fullScreenPlayer) } onInteraction() }, ) { PlayerMpvMenus( shadersAndStats = controller.isMpvBackend && settings.useMpvConfig, selectedShader = selectedShader, onShader = { action -> onShaderSelected(action.label) controller.selectMpvShader(action.command) onInteraction() }, onStats = { action -> controller.showMpvStats(action.command) onInteraction() }, customButtons = state.customButtons, customButtonVisible = customButtonVisible, primaryCustomButtonId = primaryCustomButtonId, activeCustomButtonTitle = activeCustomButtonTitle, onCustomButton = { button, longPress -> val sent = controller.executeMpvCommand("script-message", "call_button_${button.id}${if (longPress) "_long" else ""}") if (!sent && !longPress) onNotice("Custom buttons require the mpv backend") }, ) } } }