Yokan / rebuild
Course 1 8624561

PlayerChrome.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/player/PlayerChrome.kt

implementation607 lines
1package eu.friedcutlet.yokan.ui.screens.player23import androidx.compose.foundation.layout.Arrangement4import androidx.compose.foundation.layout.Box5import androidx.compose.foundation.layout.Column6import androidx.compose.foundation.layout.PaddingValues7import androidx.compose.foundation.layout.Row8import androidx.compose.foundation.layout.RowScope9import androidx.compose.foundation.layout.Spacer10import androidx.compose.foundation.layout.fillMaxWidth11import androidx.compose.foundation.layout.height12import androidx.compose.foundation.layout.padding13import androidx.compose.foundation.layout.size14import androidx.compose.foundation.layout.width15import androidx.compose.foundation.shape.RoundedCornerShape16import androidx.compose.material.icons.Icons17import androidx.compose.material.icons.automirrored.filled.ArrowBack18import androidx.compose.material.icons.automirrored.filled.PlaylistPlay19import androidx.compose.material.icons.filled.Close20import androidx.compose.material.icons.filled.FitScreen21import androidx.compose.material.icons.filled.Fullscreen22import androidx.compose.material.icons.filled.HighQuality23import androidx.compose.material.icons.filled.Memory24import androidx.compose.material.icons.filled.Pause25import androidx.compose.material.icons.filled.PictureInPictureAlt26import androidx.compose.material.icons.filled.PlayArrow27import androidx.compose.material.icons.filled.Screenshot28import androidx.compose.material.icons.filled.SkipNext29import androidx.compose.material.icons.filled.SkipPrevious30import androidx.compose.material.icons.filled.Terminal31import androidx.compose.material.icons.filled.VideoLibrary32import androidx.compose.material3.Button33import androidx.compose.material3.DropdownMenu34import androidx.compose.material3.DropdownMenuItem35import androidx.compose.material3.Icon36import androidx.compose.material3.IconButton37import androidx.compose.material3.LinearProgressIndicator38import androidx.compose.material3.MaterialTheme39import androidx.compose.material3.Slider40import androidx.compose.material3.Surface41import androidx.compose.material3.Text42import androidx.compose.material3.TextButton43import androidx.compose.runtime.Composable44import androidx.compose.runtime.LaunchedEffect45import androidx.compose.runtime.getValue46import androidx.compose.runtime.mutableStateOf47import androidx.compose.runtime.remember48import androidx.compose.runtime.setValue49import androidx.compose.ui.Alignment50import androidx.compose.ui.BiasAlignment51import androidx.compose.ui.Modifier52import androidx.compose.ui.draw.clip53import androidx.compose.ui.graphics.Color54import androidx.compose.ui.graphics.ImageBitmap55import androidx.compose.ui.semantics.contentDescription56import androidx.compose.ui.semantics.semantics57import androidx.compose.ui.text.font.FontWeight58import androidx.compose.ui.text.style.TextOverflow59import androidx.compose.ui.unit.dp60import eu.friedcutlet.yokan.database.DbCustomButton61import eu.friedcutlet.yokan.database.DbSettings62import eu.friedcutlet.yokan.services.logging.AppLogger63import eu.friedcutlet.yokan.services.media.player.MediaPlayerController64import eu.friedcutlet.yokan.services.media.player.MpvChapterMark65import eu.friedcutlet.yokan.services.media.player.MpvMenuAction66import eu.friedcutlet.yokan.services.media.player.MpvShaderActions67import eu.friedcutlet.yokan.services.media.player.MpvStatsActions68import eu.friedcutlet.yokan.services.media.player.MpvVideoFit69import eu.friedcutlet.yokan.services.media.player.SeekThumbnail70import eu.friedcutlet.yokan.services.media.player.SleepTimer71import eu.friedcutlet.yokan.services.media.player.at72import eu.friedcutlet.yokan.services.media.player.selectMpvShader73import eu.friedcutlet.yokan.services.media.player.setMpvVideoFit74import eu.friedcutlet.yokan.services.media.player.showMpvStats75import eu.friedcutlet.yokan.ui.status.GlobalStatusAccessButton76import eu.friedcutlet.yokan.util.nowMillis77import org.jetbrains.compose.resources.stringResource78import yokan.composeapp.generated.resources.Res79import yokan.composeapp.generated.resources.action_back80import yokan.composeapp.generated.resources.custom_buttons81import yokan.composeapp.generated.resources.player_screenshot82import yokan.composeapp.generated.resources.ui_player_settings8384/**85 * Flutter's player used a transparent top button bar over one dimmed full-screen backdrop,86 * rather than an opaque Material app bar.87 */88@Composable89internal fun PlayerTopBar(90    title: String,91    episodeName: String,92    minimized: Boolean,93    sleepTimer: SleepTimer?,94    castSupported: Boolean,95    casting: Boolean,96    onLeave: () -> Unit,97    onRestore: () -> Unit,98    onDismiss: () -> Unit,99    onSetSleepTimer: (minutes: Int?) -> Unit,100    onCancelSleepTimer: () -> Unit,101    onCast: () -> Unit,102    onOpenEpisodes: () -> Unit,103    onScreenshot: () -> Unit,104) {105    Row(106        modifier = Modifier107            .fillMaxWidth()108            .padding(horizontal = 4.dp, vertical = 6.dp),109        verticalAlignment = Alignment.CenterVertically,110    ) {111        IconButton(onClick = onLeave) {112            Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(Res.string.action_back), tint = Color.White)113        }114        if (minimized) {115            IconButton(116                onClick = onRestore,117                modifier = Modifier.semantics { contentDescription = "Restore full player" },118            ) {119                Icon(Icons.Filled.Fullscreen, contentDescription = "Restore full player", tint = Color.White)120            }121            IconButton(122                onClick = onDismiss,123                modifier = Modifier.semantics { contentDescription = "Dismiss mini player" },124            ) {125                Icon(Icons.Filled.Close, contentDescription = "Dismiss mini player", tint = Color.White)126            }127        }128        Column(modifier = Modifier.weight(1f)) {129            Text(130                title,131                maxLines = 1,132                overflow = TextOverflow.Ellipsis,133                color = Color.White,134                style = MaterialTheme.typography.titleMedium,135                fontWeight = FontWeight.Bold,136            )137            Text(138                episodeName,139                maxLines = 1,140                overflow = TextOverflow.Ellipsis,141                style = MaterialTheme.typography.bodySmall,142                color = Color.White.copy(alpha = 0.70f),143            )144        }145        SleepTimerButton(146            remainingLabel = sleepTimer?.let { timer ->147                timer.deadlineMs?.let { "${((it - nowMillis()).coerceAtLeast(0L) + 59_999L) / 60_000L}m" } ?: "End"148            },149            onSelect = onSetSleepTimer,150            onCancel = onCancelSleepTimer,151        )152        if (castSupported) CastButton(casting = casting, onClick = onCast)153        GlobalStatusAccessButton(tint = Color.White)154        IconButton(onClick = onOpenEpisodes) {155            Icon(Icons.AutoMirrored.Filled.PlaylistPlay, contentDescription = "Episodes", tint = Color.White)156        }157        IconButton(onClick = onScreenshot) {158            Icon(Icons.Filled.Screenshot, contentDescription = stringResource(Res.string.player_screenshot), tint = Color.White)159        }160    }161}162163@Composable164internal fun PlayerNotice(text: String, modifier: Modifier = Modifier) {165    Surface(166        modifier = modifier,167        color = Color.Black.copy(alpha = 0.78f),168        shape = RoundedCornerShape(8.dp),169    ) {170        Text(171            text,172            modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp),173            color = Color.White,174            style = MaterialTheme.typography.bodySmall,175            maxLines = 2,176            overflow = TextOverflow.Ellipsis,177        )178    }179}180181/**182 * Mobile controls in Mangayomi: previous episode / play-pause / next episode, with double-tap183 * seeking handled by the video gesture layer. [onPictureInPicture] null hides the PiP button.184 */185@Composable186internal fun PlayerCenterControls(187    isPlaying: Boolean,188    onPrevious: () -> Unit,189    onPlayPause: () -> Unit,190    onNext: () -> Unit,191    onPictureInPicture: (() -> Unit)?,192) {193    Row(194        horizontalArrangement = Arrangement.spacedBy(32.dp),195        verticalAlignment = Alignment.CenterVertically,196    ) {197        IconButton(onClick = onPrevious) {198            Icon(Icons.Filled.SkipPrevious, contentDescription = "Previous episode", tint = Color.White, modifier = Modifier.size(40.dp))199        }200        IconButton(onClick = onPlayPause, modifier = Modifier.size(72.dp)) {201            Icon(202                imageVector = if (isPlaying) Icons.Filled.Pause else Icons.Filled.PlayArrow,203                contentDescription = if (isPlaying) "Pause" else "Play",204                tint = Color.White,205                modifier = Modifier.size(56.dp),206            )207        }208        IconButton(onClick = onNext) {209            Icon(Icons.Filled.SkipNext, contentDescription = "Next episode", tint = Color.White, modifier = Modifier.size(40.dp))210        }211        if (onPictureInPicture != null) {212            IconButton(onClick = onPictureInPicture) {213                Icon(Icons.Filled.PictureInPictureAlt, contentDescription = "Enter picture-in-picture", tint = Color.White)214            }215        }216    }217}218219/**220 * Loading bar, stream error, seek preview and the seek slider. While the user drags,221 * [dragFraction] holds the in-flight value so the slider doesn't fight the player's tick.222 */223@Composable224internal fun PlayerTimeline(225    loading: Boolean,226    error: String?,227    position: Float,228    dragFraction: Float?,229    durationMs: Long,230    seekThumbnails: List<SeekThumbnail>,231    seekSprites: Map<String, ImageBitmap>,232    onDrag: (Float) -> Unit,233    onDragFinished: () -> Unit,234    onLoadSeekSprite: (url: String) -> Unit,235) {236    if (loading) {237        LinearProgressIndicator(238            modifier = Modifier239                .fillMaxWidth()240                .height(4.dp)241                .clip(RoundedCornerShape(50))242                .padding(bottom = 4.dp),243        )244    }245    if (!error.isNullOrBlank()) {246        Surface(247            shape = RoundedCornerShape(50),248            color = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.9f),249        ) {250            Text(251                error,252                modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp),253                color = MaterialTheme.colorScheme.onErrorContainer,254                style = MaterialTheme.typography.bodySmall,255            )256        }257    }258    val previewTile = dragFraction?.let { seekThumbnails.at((it * durationMs).toLong()) }259    if (dragFraction != null && previewTile != null) {260        LaunchedEffect(previewTile.imageUrl) { onLoadSeekSprite(previewTile.imageUrl) }261        seekSprites[previewTile.imageUrl]?.let { sprite ->262            // Align over the thumb; the 70 dp padding matches the time pills around the slider.263            Box(Modifier.fillMaxWidth().padding(horizontal = 70.dp)) {264                SeekPreview(previewTile, sprite, Modifier.align(BiasAlignment(dragFraction * 2f - 1f, 0f)))265            }266        }267    }268    Row(verticalAlignment = Alignment.CenterVertically) {269        PlayerTimePill(formatPlayerTime(((position * durationMs) / 1000L).toLong()))270        Slider(271            value = position,272            onValueChange = onDrag,273            onValueChangeFinished = onDragFinished,274            modifier = Modifier.weight(1f),275        )276        PlayerTimePill(formatPlayerTime(durationMs / 1000L))277    }278}279280/**281 * Bottom actions of the old mobile player: skip, chapter, settings, [mpvMenus], speed, fit and282 * fullscreen. [aniSkipType] names the active AniSkip segment; otherwise skip jumps [skipIntroSeconds].283 */284@Composable285internal fun PlayerActionRow(286    aniSkipType: String?,287    skipIntroSeconds: Int,288    onSkip: () -> Unit,289    chapterMarks: List<MpvChapterMark>,290    currentChapterMark: Int,291    onSeekToMark: (positionMs: Long) -> Unit,292    onOpenSettings: () -> Unit,293    speed: Float,294    speedPresets: List<Double>,295    onSelectSpeed: (Float) -> Unit,296    videoFit: MpvVideoFit,297    onCycleVideoFit: () -> Unit,298    onToggleFullscreen: () -> Unit,299    mpvMenus: @Composable RowScope.() -> Unit,300) {301    Row(302        modifier = Modifier303            .fillMaxWidth()304            .padding(horizontal = 8.dp),305        verticalAlignment = Alignment.CenterVertically,306        horizontalArrangement = Arrangement.End,307    ) {308        Button(309            onClick = onSkip,310            modifier = Modifier.height(35.dp),311            contentPadding = PaddingValues(horizontal = 12.dp, vertical = 0.dp),312        ) {313            Text(aniSkipType?.let { "AniSkip $it" } ?: "+$skipIntroSeconds", fontWeight = FontWeight.Light)314        }315        if (aniSkipType != null) Spacer(Modifier.width(4.dp))316        chapterMarks.getOrNull(currentChapterMark)?.let { currentMark ->317            PlayerChapterMenu(currentMark, chapterMarks, onSeekToMark)318        }319        Spacer(Modifier.weight(1f))320        IconButton(onClick = onOpenSettings) {321            Icon(Icons.Filled.VideoLibrary, contentDescription = stringResource(Res.string.ui_player_settings), tint = Color.White)322        }323        mpvMenus()324        SpeedPresetButton(speed = speed, presets = speedPresets, onSelect = onSelectSpeed)325        IconButton(onClick = onCycleVideoFit) {326            Column(horizontalAlignment = Alignment.CenterHorizontally) {327                Icon(Icons.Filled.FitScreen, contentDescription = "Fit / Zoom", tint = Color.White)328                Text(videoFit.label, color = Color.White, style = MaterialTheme.typography.labelSmall)329            }330        }331        IconButton(onClick = onToggleFullscreen) {332            Icon(Icons.Filled.Fullscreen, contentDescription = "Fullscreen", tint = Color.White)333        }334    }335}336337@Composable338private fun PlayerChapterMenu(current: MpvChapterMark, marks: List<MpvChapterMark>, onSeekToMark: (Long) -> Unit) {339    var open by remember { mutableStateOf(false) }340    Box {341        TextButton(onClick = { open = true }, modifier = Modifier.height(35.dp)) {342            Text(343                "${current.title} · ${formatPlayerTime(current.positionMs / 1000L)}",344                maxLines = 1,345                overflow = TextOverflow.Ellipsis,346                color = Color.White,347                style = MaterialTheme.typography.labelSmall,348            )349        }350        DropdownMenu(expanded = open, onDismissRequest = { open = false }) {351            marks.forEach { mark ->352                DropdownMenuItem(353                    text = { Text("${mark.title} · ${formatPlayerTime(mark.positionMs / 1000L)}") },354                    onClick = {355                        open = false356                        onSeekToMark(mark.positionMs)357                    },358                )359            }360        }361    }362}363364/**365 * mpv-only menus: shaders and stats when [shadersAndStats], and the user's custom buttons while366 * [customButtonVisible]. [onCustomButton] runs a button's press or long-press script.367 */368@Composable369internal fun PlayerMpvMenus(370    shadersAndStats: Boolean,371    selectedShader: String,372    onShader: (MpvMenuAction) -> Unit,373    onStats: (MpvMenuAction) -> Unit,374    customButtons: List<DbCustomButton>,375    customButtonVisible: Boolean,376    primaryCustomButtonId: Long?,377    activeCustomButtonTitle: String,378    onCustomButton: (button: DbCustomButton, longPress: Boolean) -> Unit,379) {380    if (shadersAndStats) {381        PlayerMenuButton(382            icon = { Icon(Icons.Filled.HighQuality, contentDescription = "Shaders", tint = Color.White) },383            actions = MpvShaderActions,384            label = { action ->385                Text(action.label, fontWeight = if (selectedShader == action.label) FontWeight.Bold else FontWeight.Normal)386            },387            onSelect = onShader,388        )389        PlayerMenuButton(390            icon = { Icon(Icons.Filled.Memory, contentDescription = "Stats", tint = Color.White) },391            actions = MpvStatsActions,392            label = { action -> Text(action.label) },393            onSelect = onStats,394        )395    }396    if (customButtons.isEmpty() || !customButtonVisible) return397    var open by remember { mutableStateOf(false) }398    Box {399        IconButton(onClick = { open = true }) {400            Column(horizontalAlignment = Alignment.CenterHorizontally) {401                Icon(Icons.Filled.Terminal, contentDescription = stringResource(Res.string.custom_buttons), tint = Color.White)402                activeCustomButtonTitle.takeIf { it.isNotBlank() }?.let {403                    Text(it, maxLines = 1, color = Color.White, style = MaterialTheme.typography.labelSmall)404                }405            }406        }407        DropdownMenu(expanded = open, onDismissRequest = { open = false }) {408            customButtons.forEach { button ->409                val label = if (button.id == primaryCustomButtonId) {410                    activeCustomButtonTitle.ifBlank { button.title ?: "Button" }411                } else {412                    button.title ?: "Button"413                }414                DropdownMenuItem(415                    text = { Text(label) },416                    onClick = {417                        open = false418                        AppLogger.info("custom-button press '$label'")419                        onCustomButton(button, false)420                    },421                )422                if (button.codeLongPress.isNotBlank()) {423                    DropdownMenuItem(424                        text = { Text("$label (long press)") },425                        onClick = {426                            open = false427                            onCustomButton(button, true)428                        },429                    )430                }431            }432        }433    }434}435436@Composable437private fun PlayerMenuButton(438    icon: @Composable () -> Unit,439    actions: List<MpvMenuAction>,440    label: @Composable (MpvMenuAction) -> Unit,441    onSelect: (MpvMenuAction) -> Unit,442) {443    var open by remember { mutableStateOf(false) }444    Box {445        IconButton(onClick = { open = true }, content = icon)446        DropdownMenu(expanded = open, onDismissRequest = { open = false }) {447            actions.forEach { action ->448                DropdownMenuItem(449                    text = { label(action) },450                    onClick = {451                        open = false452                        onSelect(action)453                    },454                )455            }456        }457    }458}459460private fun formatPlayerTime(seconds: Long): String {461    val s = seconds.coerceAtLeast(0)462    val mm = s / 60463    val ss = s % 60464    return "${mm.toString().padStart(2, '0')}:${ss.toString().padStart(2, '0')}"465}466467/** Fixed-width timestamp used by Mangayomi's mobile seek bar. */468@Composable469private fun PlayerTimePill(text: String) {470    Box(471        modifier = Modifier.width(70.dp),472        contentAlignment = Alignment.Center,473    ) {474        Text(475            text = text,476            color = Color.White,477            style = MaterialTheme.typography.labelSmall,478        )479    }480}481482/**483 * Timeline and action row. Reads the controller's position on every tick; the drag position and484 * the fit mode are local to the controller.485 */486@Composable487internal fun PlayerBottomControls(488    state: PlayerState,489    settings: DbSettings,490    controller: MediaPlayerController,491    tracks: PlayerTrackState,492    chapterMarks: List<MpvChapterMark>,493    currentChapterMark: Int,494    selectedShader: String,495    onShaderSelected: (String) -> Unit,496    customButtonVisible: Boolean,497    primaryCustomButtonId: Long?,498    activeCustomButtonTitle: String,499    onOpenSettings: () -> Unit,500    onEvent: (PlayerEvent) -> Unit,501    onNotice: (String) -> Unit,502    onUpdateSettings: ((DbSettings) -> DbSettings) -> Unit,503    onInteraction: () -> Unit,504) {505    val playerPreferences = settings.features.player506    var dragPosition by remember(controller) { mutableStateOf<Float?>(null) }507    var videoFit by remember(controller) { mutableStateOf(MpvVideoFit.Contain) }508    // Subscribed reads: these recompose as the player ticks.509    val positionMs = controller.currentPositionMs()510    val durationMs = controller.durationMs()511    val aniSkipEpisodeLength = state.aniSkipMarkers.firstOrNull()?.episodeLengthSeconds?.takeIf { it > 0 } ?: 0.0512    // Prefer the file's real duration; fall back to AniSkip's reported episode length, then a513    // 10-minute sentinel so the slider isn't zero-width before metadata arrives.514    val effectiveDurationMs = when {515        durationMs > 0L -> durationMs516        aniSkipEpisodeLength > 0.0 -> (aniSkipEpisodeLength * 1000).toLong()517        else -> 600_000L518    }519    val position = dragPosition ?: (positionMs.toFloat() / effectiveDurationMs.toFloat()).coerceIn(0f, 1f)520    // The AniSkip segment around the current position powers the "Skip" button. Markers are scoped521    // to AniSkip's own episode length, which can differ from the file's duration.522    val activeAniSkipMarker = state.aniSkipMarkers.firstOrNull { marker ->523        if (marker.episodeLengthSeconds <= 0) return@firstOrNull false524        positionMs / 1000.0 in marker.startSeconds..marker.endSeconds525    }526    Column(527        modifier = Modifier528            .fillMaxWidth()529            .padding(bottom = 18.dp),530        verticalArrangement = Arrangement.spacedBy(8.dp),531    ) {532        PlayerTimeline(533            loading = state.loading,534            error = state.error,535            position = position,536            dragFraction = dragPosition,537            durationMs = effectiveDurationMs,538            seekThumbnails = state.seekThumbnails,539            seekSprites = state.seekSprites,540            onDrag = {541                dragPosition = it542                onInteraction()543            },544            onDragFinished = {545                controller.seekTo(((dragPosition ?: position) * effectiveDurationMs).toLong())546                dragPosition = null547            },548            onLoadSeekSprite = { onEvent(PlayerEvent.LoadSeekSprite(it)) },549        )550        PlayerActionRow(551            aniSkipType = activeAniSkipMarker?.type,552            skipIntroSeconds = settings.defaultSkipIntroLength,553            onSkip = {554                val targetMs = activeAniSkipMarker?.let { (it.endSeconds * 1000).toLong() }555                    ?: (positionMs + settings.defaultSkipIntroLength * 1000L)556                controller.seekTo(targetMs.coerceAtMost(effectiveDurationMs))557                onInteraction()558            },559            chapterMarks = chapterMarks,560            currentChapterMark = currentChapterMark,561            onSeekToMark = {562                controller.seekTo(it)563                onInteraction()564            },565            onOpenSettings = onOpenSettings,566            speed = tracks.playbackSpeed,567            speedPresets = playerPreferences.speedPresets,568            onSelectSpeed = { selected ->569                tracks.playbackSpeed = selected570                onUpdateSettings { it.copy(defaultPlaybackSpeed = selected.toDouble()) }571                onInteraction()572            },573            videoFit = videoFit,574            onCycleVideoFit = {575                videoFit = MpvVideoFit.entries[(videoFit.ordinal + 1) % MpvVideoFit.entries.size]576                if (!controller.setMpvVideoFit(videoFit)) onNotice("Fit modes require the mpv backend")577                onInteraction()578            },579            onToggleFullscreen = {580                onUpdateSettings { it.copy(fullScreenPlayer = !it.fullScreenPlayer) }581                onInteraction()582            },583        ) {584            PlayerMpvMenus(585                shadersAndStats = controller.isMpvBackend && settings.useMpvConfig,586                selectedShader = selectedShader,587                onShader = { action ->588                    onShaderSelected(action.label)589                    controller.selectMpvShader(action.command)590                    onInteraction()591                },592                onStats = { action ->593                    controller.showMpvStats(action.command)594                    onInteraction()595                },596                customButtons = state.customButtons,597                customButtonVisible = customButtonVisible,598                primaryCustomButtonId = primaryCustomButtonId,599                activeCustomButtonTitle = activeCustomButtonTitle,600                onCustomButton = { button, longPress ->601                    val sent = controller.executeMpvCommand("script-message", "call_button_${button.id}${if (longPress) "_long" else ""}")602                    if (!sent && !longPress) onNotice("Custom buttons require the mpv backend")603                },604            )605        }606    }607}608

Search chapters, reference and source filenames.