package eu.friedcutlet.yokan.ui.screens.player 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.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Bedtime import androidx.compose.material.icons.filled.Cast import androidx.compose.material.icons.filled.CastConnected import androidx.compose.material.icons.filled.Pause import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.material.icons.filled.SkipNext import androidx.compose.material.icons.filled.SkipPrevious import androidx.compose.material.icons.filled.Speed import androidx.compose.material3.AlertDialog 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.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState 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.graphics.ImageBitmap import androidx.compose.ui.graphics.painter.BitmapPainter import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.dp import eu.friedcutlet.yokan.database.DbPlayerSubtitleSettings import eu.friedcutlet.yokan.database.DbVideo import eu.friedcutlet.yokan.domain.Chapter import eu.friedcutlet.yokan.domain.Manga import eu.friedcutlet.yokan.services.media.cast.CastDevice import eu.friedcutlet.yokan.services.media.cast.CastMedia import eu.friedcutlet.yokan.services.media.cast.CastStatus import eu.friedcutlet.yokan.services.media.cast.CastSubtitle import eu.friedcutlet.yokan.services.media.cast.CastTextStyle import eu.friedcutlet.yokan.services.media.player.SeekThumbnail import eu.friedcutlet.yokan.ui.formatDecimal import org.jetbrains.compose.resources.stringResource import yokan.composeapp.generated.resources.Res import yokan.composeapp.generated.resources.action_cancel /** The Default Media Receiver fetches the URL itself: no request headers, no device-local addresses. */ internal fun DbVideo.isCastable(): Boolean { if (!headers.isNullOrEmpty()) return false val host = url.substringAfter("://", "").substringBefore('/').substringBefore(':').lowercase() return (url.startsWith("http://") || url.startsWith("https://")) && host.isNotEmpty() && host != "localhost" && host != "127.0.0.1" && host != "[::1]" } internal fun DbVideo.toCastMedia(manga: Manga, episode: Chapter): CastMedia = CastMedia( url = url, title = episode.name, subtitle = manga.name, posterUrl = manga.imageUrl?.takeIf { it.startsWith("http") }, subtitles = subtitles.mapNotNull { track -> track.file?.let { CastSubtitle(it, track.label ?: "Subtitle") } }, itemKey = episode.id.toString(), ) internal fun DbPlayerSubtitleSettings?.toCastTextStyle(): CastTextStyle { val style = this ?: DbPlayerSubtitleSettings() fun argb(a: Int, r: Int, g: Int, b: Int) = (a shl 24) or (r shl 16) or (g shl 8) or b return CastTextStyle( foregroundArgb = argb(style.textColorA, style.textColorR, style.textColorG, style.textColorB), edgeArgb = argb(style.borderColorA, style.borderColorR, style.borderColorG, style.borderColorB), backgroundArgb = argb(style.backgroundColorA, style.backgroundColorR, style.backgroundColorG, style.backgroundColorB), fontScale = style.fontSize / 45.0, bold = style.useBold, italic = style.useItalic, ) } /** Lists discovered receivers; [onDiscovery] runs discovery while the dialog is composed. */ @Composable internal fun CastDeviceDialog( devices: List, onDiscovery: (active: Boolean) -> Unit, onSelect: (CastDevice) -> Unit, onDismiss: () -> Unit, ) { val discovery by rememberUpdatedState(onDiscovery) DisposableEffect(Unit) { discovery(true) onDispose { discovery(false) } } AlertDialog( onDismissRequest = onDismiss, title = { Text("Cast to") }, text = { if (devices.isEmpty()) { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { LinearProgressIndicator(Modifier.fillMaxWidth()) Text("Searching for Chromecast devices on this network…", style = MaterialTheme.typography.bodySmall) } } else { LazyColumn(Modifier.heightIn(max = 320.dp)) { items(devices, key = { it.id }) { device -> TextButton(onClick = { onSelect(device) }, modifier = Modifier.fillMaxWidth()) { Text(device.name, modifier = Modifier.fillMaxWidth(), maxLines = 1, overflow = TextOverflow.Ellipsis) } } } } }, confirmButton = {}, dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(Res.string.action_cancel)) } }, ) } /** Remote playback controls; doubles as the mini controls when the player is minimized. */ @Composable internal fun CastPanel( status: CastStatus, compact: Boolean, onPlayPause: () -> Unit, onSeek: (Long) -> Unit, onPrevious: () -> Unit, onNext: () -> Unit, onJumpTo: (Int) -> Unit, onDisconnect: () -> Unit, modifier: Modifier = Modifier, ) { var dragFraction by remember { mutableStateOf(null) } var queueOpen by remember { mutableStateOf(false) } val current = status.queue.getOrNull(status.currentIndex) Surface(modifier = modifier, color = Color.Black.copy(alpha = 0.85f), shape = RoundedCornerShape(12.dp)) { Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) { Row(verticalAlignment = Alignment.CenterVertically) { Icon(Icons.Filled.CastConnected, contentDescription = null, tint = Color.White) Column(Modifier.weight(1f).padding(horizontal = 8.dp)) { Text("Casting to ${status.device.name}", color = Color.White, style = MaterialTheme.typography.labelMedium, maxLines = 1, overflow = TextOverflow.Ellipsis) current?.let { Text(it.title, color = Color.White.copy(alpha = 0.7f), style = MaterialTheme.typography.bodySmall, maxLines = 1, overflow = TextOverflow.Ellipsis) } } TextButton(onClick = onDisconnect) { Text("Stop casting") } } status.error?.let { Text(it, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodySmall) } if (!compact && status.durationMs > 0) { Slider( value = dragFraction ?: (status.positionMs.toFloat() / status.durationMs).coerceIn(0f, 1f), onValueChange = { dragFraction = it }, onValueChangeFinished = { dragFraction?.let { onSeek((it * status.durationMs).toLong()) } dragFraction = null }, ) } Row(horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { IconButton(onClick = onPrevious, enabled = status.currentIndex > 0) { Icon(Icons.Filled.SkipPrevious, contentDescription = "Previous in cast queue", tint = Color.White) } IconButton(onClick = onPlayPause) { Icon(if (status.playing) Icons.Filled.Pause else Icons.Filled.PlayArrow, contentDescription = if (status.playing) "Pause" else "Play", tint = Color.White) } IconButton(onClick = onNext, enabled = status.currentIndex in 0 until status.queue.lastIndex) { Icon(Icons.Filled.SkipNext, contentDescription = "Next in cast queue", tint = Color.White) } if (status.queue.size > 1) { Box { TextButton(onClick = { queueOpen = true }) { Text("Queue (${status.queue.size})") } DropdownMenu(expanded = queueOpen, onDismissRequest = { queueOpen = false }) { status.queue.forEachIndexed { index, item -> DropdownMenuItem( text = { Text(item.title, fontWeight = if (index == status.currentIndex) FontWeight.Bold else FontWeight.Normal) }, onClick = { queueOpen = false; onJumpTo(index) }, ) } } } } } } } } @Composable internal fun CastButton(casting: Boolean, onClick: () -> Unit) { IconButton(onClick = onClick) { Icon(if (casting) Icons.Filled.CastConnected else Icons.Filled.Cast, contentDescription = "Cast", tint = Color.White) } } /** A cropped sprite tile above the seek bar; nothing until the sheet has loaded. */ @Composable internal fun SeekPreview(tile: SeekThumbnail, sprite: ImageBitmap, modifier: Modifier = Modifier) { val width = if (tile.width > 0) tile.width.coerceAtMost(sprite.width - tile.x) else sprite.width val height = if (tile.height > 0) tile.height.coerceAtMost(sprite.height - tile.y) else sprite.height if (width <= 0 || height <= 0) return val painter = remember(sprite, tile) { BitmapPainter(sprite, IntOffset(tile.x, tile.y), IntSize(width, height)) } Image( painter = painter, contentDescription = null, modifier = modifier .width(160.dp) .background(Color.Black, RoundedCornerShape(6.dp)) .padding(2.dp), ) } /** Sleep timer menu: fixed durations, end of episode, or off. */ @Composable internal fun SleepTimerButton(remainingLabel: String?, onSelect: (minutes: Int?) -> Unit, onCancel: () -> Unit) { var open by remember { mutableStateOf(false) } Box { IconButton(onClick = { open = true }) { Column(horizontalAlignment = Alignment.CenterHorizontally) { Icon(Icons.Filled.Bedtime, contentDescription = "Sleep timer", tint = Color.White, modifier = Modifier.size(22.dp)) remainingLabel?.let { Text(it, color = Color.White, style = MaterialTheme.typography.labelSmall) } } } DropdownMenu(expanded = open, onDismissRequest = { open = false }) { DropdownMenuItem(text = { Text("Off") }, onClick = { open = false; onCancel() }) SleepTimerMinutes.forEach { minutes -> DropdownMenuItem(text = { Text("$minutes minutes") }, onClick = { open = false; onSelect(minutes) }) } DropdownMenuItem(text = { Text("End of episode") }, onClick = { open = false; onSelect(null) }) } } } private val SleepTimerMinutes = listOf(5, 15, 30, 45, 60, 90) @Composable internal fun SpeedPresetButton(speed: Float, presets: List, onSelect: (Float) -> Unit) { var open by remember { mutableStateOf(false) } Box { IconButton(onClick = { open = true }) { Column(horizontalAlignment = Alignment.CenterHorizontally) { Icon(Icons.Filled.Speed, contentDescription = "Playback speed", tint = Color.White) Text("${formatDecimal(speed.toDouble(), 2)}x", color = Color.White, style = MaterialTheme.typography.labelSmall) } } DropdownMenu(expanded = open, onDismissRequest = { open = false }) { presets.forEach { preset -> DropdownMenuItem( text = { Text("${formatDecimal(preset, 2)}x", fontWeight = if (preset.toFloat() == speed) FontWeight.Bold else FontWeight.Normal) }, onClick = { open = false; onSelect(preset.toFloat()) }, ) } } } }