diff --git a/AGENTS.md b/AGENTS.md index b86c847..05acd1b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,7 +37,7 @@ This section is updated whenever a phase's milestone closes. | core/ | Core modules that every feature can use. docs/architecture.md describes each one | | core/database/schemas/ | The Room database schemas that the build writes, one JSON file per database version | | core/youtube/src/test/resources/youtube/ | The saved YouTube responses that the YouTube layer's tests replay, which the recorder writes | -| feature/ | Feature modules, two for each feature. Today the Search YouTube screen, the video screen, and the YouTube layer's debug screen, which only debug builds contain | +| feature/ | Feature modules, two for each feature. Today the Search YouTube screen, the video screen with the mini player and the fullscreen player, and the YouTube layer's debug screen, which only debug builds contain | | feature/*-ui/src/screenshotTest/ | The screenshot tests: one-call @PreviewTest wrappers of the previews in src/main. The reference images they are compared with are in src/screenshotTestDefaultDebug/reference/ next to it. docs/testing.md#screenshot-tests explains them | | build-logic/ | Convention plugins with the build settings that every module shares | | lint-rules/ | Dewfall's own lint checks, which lint runs on every module of the app. They enforce ADR 0007's logging rules, and nothing from them ships | @@ -93,12 +93,12 @@ These apply from Phase 2 on. A pull request that refines them updates this secti - Kotlin, Jetpack Compose, Material 3, Hilt, Room, WorkManager and Media3. - Follow Android's current official guidance, such as the app architecture recommendations and the Compose docs on developer.android.com. If the android CLI is installed, `android docs search` and `android docs fetch` read the same guidance from the Android Knowledge Base. For any API, library or Gradle setting that may have changed, check the current docs instead of relying on memory. Don't use deprecated APIs in new code. If the guidance conflicts with a rule in this file, follow this file and point out the conflict. - Modules: `:app`, the plain Kotlin/JVM modules `:core:logging`, `:core:model`, `:core:mvi` and `:core:youtube` (the YouTube layer), and the Android libraries `:core:data`, `:core:database`, `:core:designsystem` and `:core:playback` (the player). The Search YouTube screen adds `:feature:youtube-search-logic` and `:feature:youtube-search-ui`, and the video screen adds `:feature:player-logic` and `:feature:player-ui`. The YouTube layer's debug screen adds `:feature:youtube-debug-logic` and `:feature:youtube-debug-ui`, which `:app` adds to debug builds only, with debugImplementation. The plain Kotlin/JVM module `:lint-rules` holds Dewfall's own lint checks, which the module plugins add to every module's lint, and which never ship. docs/architecture.md describes each one. Shared UI goes in `:core:designsystem`, or in `:core:ui` once it needs domain models, as docs/architecture.md describes. -- Each feature has two modules: `:feature:-logic`, plain Kotlin/JVM, with the State, Intent, Effect and reducer, and `:feature:-ui`, an Android library with the screens and the ViewModel. Feature modules depend on core modules, never on another feature's modules. A feature's `-ui` module also depends on its own `-logic` module. Only `:app` sees Navigation 3: a feature whose screen sits on `:app`'s back stack exposes one public composable from its `-ui` module, which takes plain values and actions, such as `onOpenVideo`, and `:app` turns those actions into navigation. The YouTube layer's debug screen has its own activity instead. Features reach YouTube only through repositories in `:core:data`, never through `:core:youtube`. The one exception is `:feature:youtube-debug-ui`, the debug screen, whose job is to call the YouTube layer's functions themselves. `:app`'s androidTest also depends on `:core:youtube`, for the layer's interfaces only, so the emulator tests can replace the layer with fakes. It is test code that ships nowhere, and no feature module can see the layer through it. +- Each feature has two modules: `:feature:-logic`, plain Kotlin/JVM, with the State, Intent, Effect and reducer, and `:feature:-ui`, an Android library with the screens and the ViewModel. Feature modules depend on core modules, never on another feature's modules. A feature's `-ui` module also depends on its own `-logic` module. Only `:app` sees Navigation 3: a feature whose screen sits on `:app`'s back stack exposes one public composable from its `-ui` module, which takes plain values and actions, such as `onOpenVideo`, and `:app` turns those actions into navigation. The one exception is `:feature:player-ui`, which also exposes the mini player, a bar that `:app` places under the back stack, as ADR 0002's note of November 21, 2026 records. The YouTube layer's debug screen has its own activity instead. Features reach YouTube only through repositories in `:core:data`, never through `:core:youtube`. The one exception is `:feature:youtube-debug-ui`, the debug screen, whose job is to call the YouTube layer's functions themselves. `:app`'s androidTest also depends on `:core:youtube`, for the layer's interfaces only, so the emulator tests can replace the layer with fakes. It is test code that ships nowhere, and no feature module can see the layer through it. - Code that needs nothing from Android lives in plain Kotlin/JVM modules with no Android imports: the YouTube layer, the domain models, the MVI base types, the reducers and the logger. See ADR 0006. - Only the YouTube layer module may use NewPipeExtractor. It maps every NewPipeExtractor type to Dewfall's own models, so nothing else in the app knows which library sits underneath. - The YouTube layer's functions are main-safe suspend functions that return YouTubeResult and throw only CancellationException. No NewPipeExtractor exception leaves the module. Video and channel IDs are VideoId and ChannelId, never plain strings. See ADR 0008. The one exception is MediaRequests, the layer's client for the player's requests to googlevideo.com, whose calls throw IOException, as ADR 0008's note of November 20, 2026 says. - Every request to YouTube asks for British English (en-GB), and for the device's country, or GB when YouTube doesn't support it. The subtitle download and MediaRequests name no country, because their links already carry the country of the call that made them, as ADR 0009's notes say. NewPipeExtractor reads some of YouTube's answers by their English text, so another language breaks the marks of upcoming streams and some error categories. See ADR 0009. -- Every screen uses MVI: an immutable State, an Intent sealed interface, one-time Effects, and a reducer that is a pure function. The ViewModel runs side effects. Every reducer has unit tests. An action that starts in the UI, changes no state and needs no business logic, such as opening or closing a screen, goes straight to `:app`'s navigation, with no intent or effect. Player commands from the video screen, such as play, pause and seek, go straight to the player through PlaybackConnection, not through intents, and the screen reads playback state through the player's state holders. See ADR 0002. +- Every screen uses MVI: an immutable State, an Intent sealed interface, one-time Effects, and a reducer that is a pure function. The ViewModel runs side effects. Every reducer has unit tests. An action that starts in the UI, changes no state and needs no business logic, such as opening or closing a screen, goes straight to `:app`'s navigation, with no intent or effect. Player commands from the video screen and the mini player, such as play, pause, seek and the mini player's close, go straight to the player through PlaybackConnection, not through intents, and they read playback state through the player's state holders. The mini player has no screen state and no ViewModel. See ADR 0002. - Every screen's ViewModel extends MviViewModel from `:core:mvi`. Intents include the results of the ViewModel's work, and effects stay pending as state until the UI reports them handled. docs/architecture.md describes the MVI contract. - Playback state never goes into screen state. The player lives in a MediaSessionService and exposes its state through its MediaController, which screens read with media3-ui-compose's state holders or as Flows. Position updates run only as often as the visible UI needs them. - Download, sync and cleanup logic must not depend on any screen being open, because background WorkManager jobs reuse it. Background jobs run only on unmetered networks while charging. diff --git a/app/src/main/kotlin/io/github/dewfallapp/MainActivity.kt b/app/src/main/kotlin/io/github/dewfallapp/MainActivity.kt index 74619c9..f75a26c 100644 --- a/app/src/main/kotlin/io/github/dewfallapp/MainActivity.kt +++ b/app/src/main/kotlin/io/github/dewfallapp/MainActivity.kt @@ -10,8 +10,9 @@ import javax.inject.Inject /** * The app's only activity. It shows the Compose UI and is Hilt's entry point for it. It tells the - * player whether the app can be seen, so the player shows no picture in the background, whichever - * screen played the video. See docs/architecture.md#the-player. + * player when the app can be seen and when it stops, so the player shows no picture in the + * background and a video that hasn't played waits, whichever screen played it. See + * docs/architecture.md#the-player. */ @AndroidEntryPoint class MainActivity : ComponentActivity() { @@ -27,12 +28,12 @@ class MainActivity : ComponentActivity() { override fun onStart() { super.onStart() - playback.setAppVisible(true) + playback.appStarted() } override fun onStop() { super.onStop() - // A configuration change brings the activity back at once, and keeps the picture. - if (!isChangingConfigurations) playback.setAppVisible(false) + // A configuration change brings the activity back at once, so the connection does nothing. + playback.appStopped(changingConfigurations = isChangingConfigurations) } } diff --git a/app/src/main/kotlin/io/github/dewfallapp/navigation/BackStack.kt b/app/src/main/kotlin/io/github/dewfallapp/navigation/BackStack.kt index e4e6a42..b007a5d 100644 --- a/app/src/main/kotlin/io/github/dewfallapp/navigation/BackStack.kt +++ b/app/src/main/kotlin/io/github/dewfallapp/navigation/BackStack.kt @@ -13,9 +13,10 @@ internal fun MutableList.openVideo(videoId: VideoId) { } /** - * Closes the video screen of [key], if it is still on the back stack. A second tap on the close - * button, or one during the back gesture, finds it gone and does nothing, so Search YouTube always - * stays. An empty back stack would crash, because NavDisplay requires at least one entry. + * Closes the video screen of [key], if it is still on the back stack, as its minimize button does. + * Its playback goes on in the mini player. A second tap on the button, or one during the back + * gesture, finds it gone and does nothing, so Search YouTube always stays. An empty back stack + * would crash, because NavDisplay requires at least one entry. */ internal fun MutableList.close(key: PlayerKey) { remove(key) @@ -25,3 +26,9 @@ internal fun MutableList.close(key: PlayerKey) { internal fun MutableList.goBack() { if (size > 1) removeAt(lastIndex) } + +/** + * Whether the mini player shows under the back stack: while no video screen is on top. It draws + * nothing itself while the player has no video. + */ +internal fun List.showsMiniPlayer(): Boolean = lastOrNull() !is PlayerKey diff --git a/app/src/main/kotlin/io/github/dewfallapp/navigation/DewfallNavigation.kt b/app/src/main/kotlin/io/github/dewfallapp/navigation/DewfallNavigation.kt index b5b8460..9076151 100644 --- a/app/src/main/kotlin/io/github/dewfallapp/navigation/DewfallNavigation.kt +++ b/app/src/main/kotlin/io/github/dewfallapp/navigation/DewfallNavigation.kt @@ -1,41 +1,78 @@ package io.github.dewfallapp.navigation +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.consumeWindowInsets +import androidx.compose.foundation.layout.fillMaxSize 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.Modifier +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalDensity +import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.navigation3.rememberViewModelStoreNavEntryDecorator import androidx.navigation3.runtime.entryProvider import androidx.navigation3.runtime.rememberNavBackStack import androidx.navigation3.runtime.rememberSaveableStateHolderNavEntryDecorator import androidx.navigation3.ui.NavDisplay +import io.github.dewfallapp.feature.player.ui.MiniPlayer import io.github.dewfallapp.feature.player.ui.PlayerRoute import io.github.dewfallapp.feature.youtubesearch.ui.YouTubeSearch /** - * The app's screens and the back stack between them. Only :app knows Navigation 3. Features take - * plain actions, such as opening a video, and never see each other. The back stack survives - * configuration changes and process death, and each entry keeps its own saved state and ViewModels, - * which are cleared when it leaves the back stack. See docs/architecture.md#navigation. + * The app's screens, the back stack between them, and the mini player under them. Only :app knows + * Navigation 3. Features take plain actions, such as opening a video, and never see each other. The + * back stack survives configuration changes and process death, and each entry keeps its own saved + * state and ViewModels, which are cleared when it leaves the back stack. See + * docs/architecture.md#navigation. + * + * The mini player sits under the screens while no video screen is on top, and the screens end at + * its top edge: the box above it gives up the mini player's height from the window insets at its + * bottom, so a screen's own safe drawing padding leaves out the navigation bar, and keeps the part + * of the keyboard that reaches above the mini player. */ @Composable internal fun DewfallNavigation(modifier: Modifier = Modifier) { val backStack = rememberNavBackStack(SearchKey) - NavDisplay( - backStack = backStack, - onBack = { backStack.goBack() }, - modifier = modifier, - entryDecorators = - listOf( - rememberSaveableStateHolderNavEntryDecorator(), - rememberViewModelStoreNavEntryDecorator(), - ), - entryProvider = - entryProvider { - entry { - YouTubeSearch(onOpenVideo = { videoId -> backStack.openVideo(videoId) }) - } - entry(clazzContentKey = { key -> key.entryId }) { key -> - PlayerRoute(videoId = key.videoId, onClose = { backStack.close(key) }) - } - }, - ) + val showsMiniPlayer = backStack.showsMiniPlayer() + var miniPlayerHeight by remember { mutableStateOf(0.dp) } + val density = LocalDensity.current + Column(modifier = modifier.fillMaxSize()) { + NavDisplay( + backStack = backStack, + onBack = { backStack.goBack() }, + modifier = + Modifier.weight(1f) + .consumeWindowInsets( + PaddingValues(bottom = if (showsMiniPlayer) miniPlayerHeight else 0.dp), + ), + entryDecorators = + listOf( + rememberSaveableStateHolderNavEntryDecorator(), + rememberViewModelStoreNavEntryDecorator(), + ), + entryProvider = + entryProvider { + entry { + YouTubeSearch(onOpenVideo = { videoId -> backStack.openVideo(videoId) }) + } + entry(clazzContentKey = { key -> key.entryId }) { key -> + PlayerRoute(videoId = key.videoId, onMinimize = { backStack.close(key) }) + } + }, + ) + if (showsMiniPlayer) { + // The box reports 0 when the mini player draws nothing, such as after it closes, so + // the screens above get the navigation bar's inset back. + Box( + Modifier.onSizeChanged { miniPlayerHeight = with(density) { it.height.toDp() } }, + ) { + MiniPlayer(onOpenVideo = { videoId -> backStack.openVideo(videoId) }) + } + } + } } diff --git a/app/src/test/kotlin/io/github/dewfallapp/navigation/BackStackTest.kt b/app/src/test/kotlin/io/github/dewfallapp/navigation/BackStackTest.kt index acdd29e..e6e5595 100644 --- a/app/src/test/kotlin/io/github/dewfallapp/navigation/BackStackTest.kt +++ b/app/src/test/kotlin/io/github/dewfallapp/navigation/BackStackTest.kt @@ -4,7 +4,9 @@ import androidx.navigation3.runtime.NavKey import io.github.dewfallapp.core.model.VideoId import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertIs +import kotlin.test.assertTrue private val VIDEO = VideoId("aqz-KE-bpKQ") private val OTHER = VideoId("dQw4w9WgXcQ") @@ -61,4 +63,15 @@ class BackStackTest { assertEquals(listOf(SearchKey), backStack) } + + @Test + fun `the mini player shows on search, and not over a video screen`() { + assertTrue(backStack.showsMiniPlayer()) + + backStack.openVideo(VIDEO) + assertFalse(backStack.showsMiniPlayer()) + + backStack.goBack() + assertTrue(backStack.showsMiniPlayer()) + } } diff --git a/core/designsystem/src/main/kotlin/io/github/dewfallapp/core/designsystem/theme/DewfallOpacity.kt b/core/designsystem/src/main/kotlin/io/github/dewfallapp/core/designsystem/theme/DewfallOpacity.kt new file mode 100644 index 0000000..b82b16b --- /dev/null +++ b/core/designsystem/src/main/kotlin/io/github/dewfallapp/core/designsystem/theme/DewfallOpacity.kt @@ -0,0 +1,14 @@ +package io.github.dewfallapp.core.designsystem.theme + +/** + * Dewfall's opacities that Material 3's components don't already apply, from the opacity tokens in + * docs/design/claude-design/design-system/tokens.json. Each one comes with its first use. A token + * edit there is copied here by hand, and DesignTokensTest fails until both agree. + */ +object DewfallOpacity { + /** + * duration-scrim, 0.8. `surface` at this opacity behind the duration tag on a thumbnail, and + * behind the fullscreen player's controls over video. + */ + const val DURATION_SCRIM = 0.8f +} diff --git a/core/designsystem/src/main/res/drawable/ic_fullscreen.xml b/core/designsystem/src/main/res/drawable/ic_fullscreen.xml new file mode 100644 index 0000000..9f929d8 --- /dev/null +++ b/core/designsystem/src/main/res/drawable/ic_fullscreen.xml @@ -0,0 +1,18 @@ + + + + + diff --git a/core/designsystem/src/main/res/drawable/ic_fullscreen_exit.xml b/core/designsystem/src/main/res/drawable/ic_fullscreen_exit.xml new file mode 100644 index 0000000..ebe017c --- /dev/null +++ b/core/designsystem/src/main/res/drawable/ic_fullscreen_exit.xml @@ -0,0 +1,18 @@ + + + + + diff --git a/core/designsystem/src/test/kotlin/io/github/dewfallapp/core/designsystem/theme/DesignTokensTest.kt b/core/designsystem/src/test/kotlin/io/github/dewfallapp/core/designsystem/theme/DesignTokensTest.kt index 0e1ea44..eba75d4 100644 --- a/core/designsystem/src/test/kotlin/io/github/dewfallapp/core/designsystem/theme/DesignTokensTest.kt +++ b/core/designsystem/src/test/kotlin/io/github/dewfallapp/core/designsystem/theme/DesignTokensTest.kt @@ -28,9 +28,9 @@ import kotlinx.serialization.json.jsonPrimitive * the tokens by hand, so a typo, or a token edit that wasn't copied, fails here. Each test also * fails when its token group gains or loses a token. * - * The opacity tokens aren't checked, because the theme doesn't set them. Material 3's components - * already use the same state layer and disabled opacities. docs/architecture.md#the-theme says - * where scrim-modal and duration-scrim stand. + * Of the opacity tokens, only duration-scrim is checked, because DewfallOpacity holds only it. + * Material 3's components already use the same state layer and disabled opacities. + * docs/architecture.md#the-theme says where scrim-modal stands. */ class DesignTokensTest { private val tokens: JsonObject = run { @@ -125,6 +125,12 @@ class DesignTokensTest { } } + @Test + fun `duration-scrim matches its opacity token`() { + val token = tokens.tokenGroup("opacity").single { it.string("name") == "duration-scrim" } + assertEquals(token.string("value").toFloat(), DewfallOpacity.DURATION_SCRIM) + } + private fun JsonObject.tokenGroup(name: String): List = getValue(name).jsonObject.getValue("tokens").jsonArray.map { it.jsonObject } diff --git a/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/MediaControllerConnection.kt b/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/MediaControllerConnection.kt index e9679c5..0cc9431 100644 --- a/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/MediaControllerConnection.kt +++ b/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/MediaControllerConnection.kt @@ -32,7 +32,8 @@ import kotlinx.coroutines.launch * The PlaybackConnection over a MediaController. It starts PlaybackService, connects one * MediaController for the application's context to the service's session, and keeps it while the * session lives, so a configuration change finds it as it was. When the session is gone, the next - * [prepare] starts the service and connects again. + * [prepare] starts the service and connects again. It listens to the controller for the playback ID + * that last played, which decides what leaving the app pauses. */ @Singleton internal class MediaControllerConnection @@ -54,6 +55,9 @@ constructor( private var connecting: Job? = null private var pending: Pending? = null + /** The playback ID that last played. Only the main thread touches it. */ + private var playedId: String? = null + override val player: StateFlow = controller.asStateFlow() override val failure: StateFlow @@ -75,15 +79,7 @@ constructor( return playbackId } - override fun isKnown(playbackId: String): Boolean = items.contains(playbackId) - - override fun pause(playbackId: String) { - val connected = controller.value - val decision = - pauseDecision(pending?.playbackId, connected?.currentMediaItem?.mediaId, playbackId) - if (decision.waitingStart) pending?.play = false - if (decision.player) connected?.pause() - } + override fun videoOf(playbackId: String): VideoId? = items.videoId(playbackId) override fun stop(playbackId: String) { if (pending?.playbackId == playbackId) pending = null @@ -97,12 +93,33 @@ constructor( } } + override fun release(playbackId: String) { + val currentItemId = controller.value?.currentMediaItem?.mediaId + if (releaseDrops(pending?.playbackId, currentItemId, playbackId)) items.remove(playbackId) + } + override fun describe(playbackId: String, title: String, channelName: String) { items.describe(playbackId, PlaybackDescription(title, channelName)) } - override fun setAppVisible(visible: Boolean) { - sessions.setAppVisible(visible) + override fun holdPicture(): PictureHold = sessions.holdPicture() + + override fun appStarted() { + sessions.setAppVisible(true) + } + + override fun appStopped(changingConfigurations: Boolean) { + val connected = controller.value + val decision = + leaveDecision( + changingConfigurations, + waitingId = pending?.playbackId, + currentItemId = connected?.currentMediaItem?.mediaId, + playedId = playedId, + ) + if (decision.hidesApp) sessions.setAppVisible(false) + if (decision.stopsWaitingStart) pending?.play = false + if (decision.pausesPlayer) connected?.pause() } private fun connect() { @@ -138,7 +155,10 @@ constructor( null } controller.value = connected - if (connected != null) pending?.runOn(connected) + if (connected != null) { + connected.addListener(Played()) + pending?.runOn(connected) + } pending = null } @@ -151,8 +171,8 @@ constructor( /** * A start of [playbackId] from [startPositionMs], which waits for the connection when there is - * none yet. A pause before it connects turns [play] off, so it never plays with its screen - * gone. + * none yet. Leaving the app before it connects turns [play] off, so it never starts in the + * background. */ private class Pending(val playbackId: String, val startPositionMs: Long, var play: Boolean) { fun runOn(player: Player) { @@ -162,6 +182,13 @@ constructor( } } + /** Keeps the playback ID of the current item once it plays. */ + private inner class Played : Player.Listener { + override fun onEvents(player: Player, events: Player.Events) { + if (player.isPlaying) playedId = player.currentMediaItem?.mediaId + } + } + private inner class Disconnection : MediaController.Listener { override fun onDisconnected(controller: MediaController) { if (this@MediaControllerConnection.controller.value === controller) { diff --git a/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/PlaybackConnection.kt b/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/PlaybackConnection.kt index 3f4e936..e5e230e 100644 --- a/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/PlaybackConnection.kt +++ b/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/PlaybackConnection.kt @@ -9,9 +9,10 @@ import io.github.dewfallapp.core.model.VideoId import kotlinx.coroutines.flow.StateFlow /** - * How screens reach the player in PlaybackService. Screens read the playback state through - * [player], with media3-ui-compose's state holders or as Flows, never in screen state, and send - * play, pause and seek straight to it. See docs/architecture.md#the-player. + * How screens and the mini player reach the player in PlaybackService. They read the playback state + * through [player], with media3-ui-compose's state holders or as Flows, never in screen state, and + * send play, pause and seek straight to it. Playback belongs to the app, not to a screen: closing + * the video screen leaves it to the mini player. See docs/architecture.md#the-player. */ interface PlaybackConnection { /** The player while the connection to the service's session is up, or null. */ @@ -26,22 +27,26 @@ interface PlaybackConnection { */ fun prepare(videoId: VideoId, play: Boolean, startPositionMs: Long = C.TIME_UNSET): String - /** Whether [playbackId] still has its video, which it doesn't after the session was gone. */ - fun isKnown(playbackId: String): Boolean - /** - * Pauses [playbackId], if it is the player's item, or keeps it from playing if it still waits - * for the connection, so leaving the screen never leaves it playing. + * The video of [playbackId], while the ID has one, which it doesn't after the session was gone. + * The mini player opens its screen with it. */ - fun pause(playbackId: String) + fun videoOf(playbackId: String): VideoId? /** * Stops playback and clears the player's items, if the player's current item is still * [playbackId], as [stopsPlayback] decides. A video opened since keeps playing. The ID's video - * is dropped either way. + * is dropped either way. The mini player's close button calls it. */ fun stop(playbackId: String) + /** + * The screen of [playbackId] closed, such as when the user minimized it. Its playback goes on + * while it is the player's item or the start that waits for the connection, and the mini player + * shows it. Otherwise the ID's video is dropped, as [releaseDrops] decides. + */ + fun release(playbackId: String) + /** * Gives [playbackId] the video's [title] and [channelName], which the media notification and * Android's media session show while that playback lasts. Nothing happens once the ID has no @@ -50,10 +55,29 @@ interface PlaybackConnection { fun describe(playbackId: String, title: String, channelName: String) /** - * Tells the player whether one of the app's screens can be seen. While none can, the player - * shows no picture, so it decodes none, and fetches none that comes in its own file. + * Shows the picture while the app can be seen, until the returned hold is released. A video + * screen holds it while it exists. While nothing holds it, as while a video is minimized, or + * while the app can't be seen, the player decodes no picture, and fetches none that comes in + * its own file. */ - fun setAppVisible(visible: Boolean) + fun holdPicture(): PictureHold + + /** One of the app's screens can be seen again. MainActivity calls it in onStart. */ + fun appStarted() + + /** + * The app's screens can no longer be seen, unless the activity is only + * [changingConfigurations]. MainActivity calls it in onStop. A playback that hasn't played yet + * then waits, paused, as [leaveDecision] decides, because its foreground service would start + * from the background. + */ + fun appStopped(changingConfigurations: Boolean) +} + +/** A hold on the picture, from [PlaybackConnection.holdPicture]. */ +fun interface PictureHold { + /** Lets go of the picture. A second call does nothing. */ + fun release() } /** @@ -65,28 +89,50 @@ fun interface SessionActivity { fun pendingIntent(context: Context): PendingIntent } -/** What pausing a playback ID acts on. */ -internal data class PauseDecision( - /** The start that waits for the connection is that ID's, so it won't play. */ - val waitingStart: Boolean, - /** The player's item is that ID's, so the player pauses. */ - val player: Boolean, +/** What the app becoming hidden does. */ +internal data class LeaveDecision( + /** The app counts as hidden, so the player shows no picture. */ + val hidesApp: Boolean, + /** The start that waits for the connection won't play. */ + val stopsWaitingStart: Boolean, + /** The player pauses its current item. */ + val pausesPlayer: Boolean, ) /** - * What pausing [playbackId] acts on, with [waitingId] the ID of a start that still waits for the - * connection, and [currentItemId] the player's item. It never pauses another screen's video. + * What the app's screens stopping does, unless the activity is only [changingConfigurations], with + * [waitingId] the ID of a start that still waits for the connection, [currentItemId] the player's + * item, and [playedId] the ID that last played. A configuration change does nothing. Otherwise a + * video that has played keeps playing in the background, and one that hasn't, waiting or the + * player's, waits paused, because its foreground service would start from the background, which + * Android refuses. */ -internal fun pauseDecision( +internal fun leaveDecision( + changingConfigurations: Boolean, waitingId: String?, currentItemId: String?, - playbackId: String, -): PauseDecision = - PauseDecision(waitingStart = waitingId == playbackId, player = currentItemId == playbackId) + playedId: String?, +): LeaveDecision = + if (changingConfigurations) { + LeaveDecision(hidesApp = false, stopsWaitingStart = false, pausesPlayer = false) + } else { + LeaveDecision( + hidesApp = true, + stopsWaitingStart = waitingId != null, + pausesPlayer = currentItemId != null && currentItemId != playedId, + ) + } + +/** + * Whether releasing [playbackId] drops its video: only when it is neither the player's + * [currentItemId] nor the start that waits for the connection, [waitingId]. Otherwise it goes on in + * the mini player. + */ +internal fun releaseDrops(waitingId: String?, currentItemId: String?, playbackId: String): Boolean = + playbackId != waitingId && playbackId != currentItemId /** * Whether stopping [playbackId] stops the player, whose current item is [currentItemId]: only when - * it is still that item. A screen's ViewModel is cleared after its exit animation, so a video - * opened meanwhile can already be playing. + * it is still that item, so a video opened meanwhile keeps playing. */ fun stopsPlayback(currentItemId: String?, playbackId: String): Boolean = currentItemId == playbackId diff --git a/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/PlaybackService.kt b/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/PlaybackService.kt index 97373ee..00c1d96 100644 --- a/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/PlaybackService.kt +++ b/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/PlaybackService.kt @@ -35,6 +35,8 @@ import javax.inject.Inject import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch /** The notification channel of the media notification. Media3 names it "Now playing". */ @@ -103,7 +105,9 @@ class PlaybackService : MediaSessionService() { .build() addSession(session) sessions.publish(session) - scope.launch { sessions.appVisible.collect(::showPicture) } + scope.launch { + sessions.picture.map { it.showsPicture }.distinctUntilChanged().collect(::showPicture) + } scope.launch { items.described.collect { sessionPlayer.descriptionsChanged() } } } @@ -174,7 +178,8 @@ class PlaybackService : MediaSessionService() { when (val resolution = resolver.resolve(playbackId, videoId, tag.metered)) { is Resolution.Resolved -> { if (player.currentMediaItem?.mediaId == playbackId) { - refresh(PlayerTarget(), resolution.item, point) + val playsNow = resumesAfterRefresh(point.wasPlaying, player.playWhenReady) + refresh(PlayerTarget(), resolution.item, point.copy(wasPlaying = playsNow)) } } is Resolution.Failed -> report(resolution.failure, errorCode) @@ -205,9 +210,10 @@ class PlaybackService : MediaSessionService() { } /** - * Turns the video track off while no screen of the app can be seen, so the player decodes no - * picture, and fetches none that comes in its own file, and on again when one can. It builds on - * the current parameters, so a live stream's variant override stays. + * Turns the video track off while no video screen can be seen, because the app is in the + * background or the video is minimized, so the player decodes no picture, and fetches none that + * comes in its own file, and on again when one can. It builds on the current parameters, so a + * live stream's variant override stays. */ private fun showPicture(visible: Boolean) { val parameters = player.trackSelectionParameters diff --git a/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/PlaybackSessions.kt b/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/PlaybackSessions.kt index a871e62..9394dda 100644 --- a/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/PlaybackSessions.kt +++ b/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/PlaybackSessions.kt @@ -2,23 +2,34 @@ package io.github.dewfallapp.core.playback import androidx.media3.session.MediaSession import io.github.dewfallapp.core.model.PlaybackFailure +import java.util.concurrent.atomic.AtomicBoolean import javax.inject.Inject import javax.inject.Singleton import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update + +/** + * Whether the player shows the picture: only while the app can be seen, [appVisible], and at least + * one video screen holds the picture, [holds]. A minimized video has no holder. + */ +internal data class PictureState(val appVisible: Boolean = true, val holds: Int = 0) { + val showsPicture: Boolean + get() = appVisible && holds > 0 +} /** * What PlaybackService shares with PlaybackConnection inside the process: its media session, whose * token the connection's controller connects with, the current playback failure, which only the - * service sees in full, and whether the app can be seen, which decides whether the player shows the - * picture. + * service sees in full, and whether the app can be seen and a video screen holds the picture, which + * decide whether the player shows it. */ @Singleton internal class PlaybackSessions @Inject constructor() { private val session = MutableStateFlow(null) private val failureState = MutableStateFlow(null) - private val visibleState = MutableStateFlow(true) + private val pictureState = MutableStateFlow(PictureState()) /** The service's session while it runs, or null. */ val current: StateFlow = session.asStateFlow() @@ -27,10 +38,10 @@ internal class PlaybackSessions @Inject constructor() { val failure: StateFlow = failureState.asStateFlow() /** - * Whether one of the app's screens can be seen. It starts true, because the service starts only - * while a screen shows. + * Whether one of the app's screens can be seen, which starts true, because the service starts + * only while a screen shows, and how many video screens hold the picture. */ - val appVisible: StateFlow = visibleState.asStateFlow() + val picture: StateFlow = pictureState.asStateFlow() fun publish(session: MediaSession?) { this.session.value = session @@ -45,6 +56,17 @@ internal class PlaybackSessions @Inject constructor() { } fun setAppVisible(visible: Boolean) { - visibleState.value = visible + pictureState.update { it.copy(appVisible = visible) } + } + + /** Holds the picture until the returned hold is released, once. */ + fun holdPicture(): PictureHold { + pictureState.update { it.copy(holds = it.holds + 1) } + val released = AtomicBoolean(false) + return PictureHold { + if (released.compareAndSet(false, true)) { + pictureState.update { it.copy(holds = it.holds - 1) } + } + } } } diff --git a/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/Refresh.kt b/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/Refresh.kt index d060ab2..525ef87 100644 --- a/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/Refresh.kt +++ b/core/playback/src/main/kotlin/io/github/dewfallapp/core/playback/Refresh.kt @@ -35,6 +35,14 @@ internal fun refresh(target: RefreshTarget, item: Item, point: Refr if (point.wasPlaying) target.play() } +/** + * Whether a refresh plays once its new links are in place: only if the player [wasPlaying] when the + * link was refused and [playsNow], its play still on when the links arrive. A pause while the links + * load, such as leaving the app before the video played, stays. + */ +internal fun resumesAfterRefresh(wasPlaying: Boolean, playsNow: Boolean): Boolean = + wasPlaying && playsNow + /** * Allows one refresh of expired links for each failure. The limit resets once the refreshed item is * ready to play again, so a second expiry hours later refreshes too, while two refusals in a row diff --git a/core/playback/src/test/kotlin/io/github/dewfallapp/core/playback/PlaybackPartsTest.kt b/core/playback/src/test/kotlin/io/github/dewfallapp/core/playback/PlaybackPartsTest.kt index 59222f1..05aeda4 100644 --- a/core/playback/src/test/kotlin/io/github/dewfallapp/core/playback/PlaybackPartsTest.kt +++ b/core/playback/src/test/kotlin/io/github/dewfallapp/core/playback/PlaybackPartsTest.kt @@ -123,13 +123,46 @@ class PlaybackPartsTest { @Test fun `the app counts as visible until a screen says otherwise`() { val sessions = PlaybackSessions() - assertTrue(sessions.appVisible.value) + assertTrue(sessions.picture.value.appVisible) sessions.setAppVisible(false) - assertFalse(sessions.appVisible.value) + assertFalse(sessions.picture.value.appVisible) sessions.setAppVisible(true) - assertTrue(sessions.appVisible.value) + assertTrue(sessions.picture.value.appVisible) + } + + @Test + fun `the picture shows only while the app can be seen and a screen holds it`() { + val sessions = PlaybackSessions() + assertFalse(sessions.picture.value.showsPicture, "no holder") + + val first = sessions.holdPicture() + assertTrue(sessions.picture.value.showsPicture, "one holder") + + sessions.setAppVisible(false) + assertFalse(sessions.picture.value.showsPicture, "the app hidden") + sessions.setAppVisible(true) + + val second = sessions.holdPicture() + first.release() + assertTrue(sessions.picture.value.showsPicture, "the second holder") + + second.release() + assertFalse(sessions.picture.value.showsPicture, "both released") + } + + @Test + fun `releasing a hold twice lowers the count once`() { + val sessions = PlaybackSessions() + val first = sessions.holdPicture() + sessions.holdPicture() + + first.release() + first.release() + + assertEquals(1, sessions.picture.value.holds) + assertTrue(sessions.picture.value.showsPicture) } @Test @@ -174,21 +207,64 @@ class StopsPlaybackTest { } } -class PauseDecisionTest { +class LeaveDecisionTest { + private val nothing = + LeaveDecision(hidesApp = false, stopsWaitingStart = false, pausesPlayer = false) + @Test - fun `pausing acts on the screen's own waiting start and player item only`() { + fun `leaving pauses only a playback that hasn't played`() { assertEquals( - PauseDecision(waitingStart = true, player = false), - pauseDecision(waitingId = "first", currentItemId = null, playbackId = "first"), + LeaveDecision(hidesApp = true, stopsWaitingStart = false, pausesPlayer = true), + leaveDecision(false, waitingId = null, currentItemId = "first", playedId = null), ) assertEquals( - PauseDecision(waitingStart = false, player = true), - pauseDecision(waitingId = null, currentItemId = "first", playbackId = "first"), + LeaveDecision(hidesApp = true, stopsWaitingStart = false, pausesPlayer = false), + leaveDecision(false, waitingId = null, currentItemId = "first", playedId = "first"), ) - // Another screen's video, waiting or playing, is left alone. + } + + @Test + fun `a configuration change does nothing, whether the playback played or not`() { + assertEquals(nothing, leaveDecision(true, waitingId = null, "first", playedId = null)) + assertEquals(nothing, leaveDecision(true, waitingId = null, "first", playedId = "first")) + assertEquals(nothing, leaveDecision(true, waitingId = "second", null, playedId = null)) + } + + @Test + fun `a start that waits for the connection won't play`() { assertEquals( - PauseDecision(waitingStart = false, player = false), - pauseDecision(waitingId = "second", currentItemId = "second", playbackId = "first"), + LeaveDecision(hidesApp = true, stopsWaitingStart = true, pausesPlayer = false), + leaveDecision(false, waitingId = "second", currentItemId = null, playedId = "first"), + ) + } + + @Test + fun `a new video that hasn't played pauses, though an older one did`() { + assertTrue( + leaveDecision(false, waitingId = null, "second", playedId = "first").pausesPlayer, ) } + + @Test + fun `with no item and no waiting start, leaving only hides the app`() { + assertEquals( + LeaveDecision(hidesApp = true, stopsWaitingStart = false, pausesPlayer = false), + leaveDecision(false, waitingId = null, currentItemId = null, playedId = null), + ) + } +} + +class ReleaseDropsTest { + @Test + fun `releasing keeps the player's item and the waiting start for the mini player`() { + assertFalse(releaseDrops(waitingId = null, currentItemId = "first", playbackId = "first")) + assertFalse(releaseDrops(waitingId = "first", currentItemId = null, playbackId = "first")) + } + + @Test + fun `releasing drops a playback that has no item and doesn't wait`() { + assertTrue(releaseDrops(waitingId = null, currentItemId = null, playbackId = "first")) + // Another video took the player's place. + assertTrue(releaseDrops(waitingId = "third", currentItemId = "second", "first")) + } } diff --git a/core/playback/src/test/kotlin/io/github/dewfallapp/core/playback/RefreshTest.kt b/core/playback/src/test/kotlin/io/github/dewfallapp/core/playback/RefreshTest.kt index fed8f9e..86829d8 100644 --- a/core/playback/src/test/kotlin/io/github/dewfallapp/core/playback/RefreshTest.kt +++ b/core/playback/src/test/kotlin/io/github/dewfallapp/core/playback/RefreshTest.kt @@ -75,4 +75,13 @@ class RefreshTest { assertFalse(limit.shouldRefresh(404)) assertFalse(limit.shouldRefresh(null)) } + + @Test + fun `a refresh plays only if play was on at the refusal and is still on`() { + assertTrue(resumesAfterRefresh(wasPlaying = true, playsNow = true)) + // Paused while the new links loaded, such as by leaving the app before it played. + assertFalse(resumesAfterRefresh(wasPlaying = true, playsNow = false)) + assertFalse(resumesAfterRefresh(wasPlaying = false, playsNow = true)) + assertFalse(resumesAfterRefresh(wasPlaying = false, playsNow = false)) + } } diff --git a/docs/adr/0002-mvi-with-playback-state-outside.md b/docs/adr/0002-mvi-with-playback-state-outside.md index ea5cb4b..cb41799 100644 --- a/docs/adr/0002-mvi-with-playback-state-outside.md +++ b/docs/adr/0002-mvi-with-playback-state-outside.md @@ -10,6 +10,8 @@ Changed in #41, which the maintainer approved on November 19, 2026: an action th Changed in #42, which the maintainer approved on November 20, 2026: the video screen's player commands go straight to the player through PlaybackConnection, not through intents. They are play, pause, seek, the playback "Try again", the first start, and play after the session was gone. The screen reads playback state through the MediaController with media3-ui-compose's state holders, at the rate the visible controls need, never in screen state. This is an exception to the intent rule, not a new decision: this ADR already keeps playback state out of screen state, and an intent for each tap would only pass through the reducer unchanged. See [The player](../architecture.md#the-player). +Changed in #44, which the maintainer approved on November 21, 2026: the same exception covers the mini player. It is a bar that `:app` places under the back stack, with no screen state and no ViewModel. Its play, pause and close go straight to the player through PlaybackConnection, and its tap, which opens the video screen, goes straight to `:app`'s navigation. It reads playback state through the MediaController with media3-ui-compose's state holders, never in screen state. So `:feature:player-ui` exposes two public composables, the video screen and the mini player. The fullscreen player's state goes through the video screen's reducer as usual. See [The mini player](../architecture.md#the-mini-player). + ## Context Every screen needs a clear way to hold its state and handle what the user does. Screen logic should be easy to test without a phone. diff --git a/docs/architecture.md b/docs/architecture.md index bf028a6..c691366 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -4,7 +4,7 @@ This is the design document for Dewfall. It explains how the app is built: its m ## Modules -Dewfall is one Gradle build with an app module, core modules, and feature modules as features arrive. Today the feature modules hold the Search YouTube screen, the app's first screen, the video screen, which opens from it, and the YouTube layer's debug screen, which only debug builds contain. Some modules are plain Kotlin/JVM and the rest are Android modules. [ADR 0006](adr/0006-platform-and-android-versions.md) explains why. +Dewfall is one Gradle build with an app module, core modules, and feature modules as features arrive. Today the feature modules hold the Search YouTube screen, the app's first screen, the video screen, which opens from it, with the mini player and the fullscreen player, and the YouTube layer's debug screen, which only debug builds contain. Some modules are plain Kotlin/JVM and the rest are Android modules. [ADR 0006](adr/0006-platform-and-android-versions.md) explains why. - A plain Kotlin/JVM module can't see Android classes, so the build itself keeps Android code out of it. Its tests run on the computer's JVM with nothing from Android to fake. It can't hold user-facing text, because string resources are part of Android, so it returns types that the screens turn into text. - An Android module is the app or an Android library. It holds everything that needs Android, such as the database, screens, ViewModels, resources and background jobs. @@ -98,8 +98,8 @@ Android modules set a namespace. Plain Kotlin/JVM modules have no namespace, so | `:core:youtube` | core/youtube/ | Kotlin/JVM | io.github.dewfallapp.core.youtube | The YouTube layer: Dewfall's interfaces for search, video details, a channel's latest uploads, stream links and subtitles, and their NewPipeExtractor implementation. NewPipeYouTube, one of its two public classes, implements all five. The other, MediaRequests, makes the player's OkHttp clients for googlevideo.com. It also holds the HTTP code that NewPipeExtractor sends its requests through, and the code that runs each call. It is the only module that may use NewPipeExtractor. See [ADR 0001](adr/0001-newpipeextractor-behind-youtube-layer.md) and [The YouTube layer](#the-youtube-layer). | `:core:model`, `:core:logging`, kotlinx.coroutines and OkHttp, all four as api dependencies, because the interfaces return the models, NewPipeYouTube's constructor takes a Logger and a CoroutineDispatcher, and MediaRequests returns OkHttp's Call.Factory | | `:core:database` | core/database/ | Android library | io.github.dewfallapp.core.database | The Room database: entities, DAOs, migrations and the exported schemas | `:core:model` | | `:core:data` | core/data/ | Android library | io.github.dewfallapp.core.data | Repositories that combine the database and the YouTube layer. Today it holds YouTubeSearchRepository, which the Search YouTube screen uses, VideoDetailsRepository, which the video screen uses, StreamLinksRepository, which the player uses, and YouTubeModule, the Hilt module that provides the YouTube layer, and the player's two OkHttp Call.Factory providers, marked `@ProgressiveMediaCalls` and `@LiveMediaCalls`. See [How Hilt provides the layer](#how-hilt-provides-the-layer) and [Reading from YouTube](#reading-from-youtube). | `:core:model`, `:core:database`, `:core:youtube` | -| `:core:playback` | core/playback/ | Android library | io.github.dewfallapp.core.playback | The player: PlaybackService, the media session service with one ExoPlayer, and PlaybackConnection, which hands screens its MediaController, with the format choice's Android parts, the media sources and the error mapping. See [The player](#the-player). | `:core:model` as an api dependency, `:core:data`, `:core:logging`, Media3 with media3-session as an api dependency, because the connection exposes Media3's Player, and OkHttp | -| `:core:designsystem` | core/designsystem/ | Android library | io.github.dewfallapp.core.designsystem | The Compose theme built from the design tokens, with the Manrope font. See [The theme](#the-theme). It also holds the shared icons, today the search, close, error, keyboard_arrow_down, play_arrow and filled pause glyphs from Material Symbols Rounded, under the Apache License 2.0, ReadableWidth, the widest a screen's column gets, and the first shared component, Banner. | Nothing. It exposes Material 3 as an api dependency. | +| `:core:playback` | core/playback/ | Android library | io.github.dewfallapp.core.playback | The player: PlaybackService, the media session service with one ExoPlayer, and PlaybackConnection, which hands screens and the mini player its MediaController, with the format choice's Android parts, the media sources and the error mapping. See [The player](#the-player). | `:core:model` as an api dependency, `:core:data`, `:core:logging`, Media3 with media3-session as an api dependency, because the connection exposes Media3's Player, and OkHttp | +| `:core:designsystem` | core/designsystem/ | Android library | io.github.dewfallapp.core.designsystem | The Compose theme built from the design tokens, with the Manrope font. See [The theme](#the-theme). It also holds the shared icons, today the search, close, error, keyboard_arrow_down, play_arrow, filled pause, fullscreen and fullscreen_exit glyphs from Material Symbols Rounded, under the Apache License 2.0, ReadableWidth, the widest a screen's column gets, DewfallOpacity, with the opacities that the components use, and the first shared component, Banner. | Nothing. It exposes Material 3 as an api dependency. | `:core:mvi` holds the MVI base, `:core:designsystem` holds the theme, and `:core:logging` holds the logger. `:core:youtube` holds the YouTube layer's interfaces and the code that runs NewPipeExtractor, and `:core:model` the models they return. `:core:database` holds no code yet, and `:core:data` holds the search, video details and stream links repositories and the Hilt module that provides the YouTube layer. `:core:playback` holds the player. A module that logs depends on `:core:logging`. Today `:app`, `:core:youtube` and `:core:playback` do, and each other module adds the dependency when it first logs. `-logic` modules never do, because reducers don't log. `:core:database` has Room set up, but no database until Phase 5 adds the first tables (#48). NewPipeYouTube implements all five of the YouTube layer's interfaces. Compose is set up in `:app`, `:core:designsystem` and every feature's `-ui` module. Hilt is set up in `:app`, `:core:data`, `:core:playback` and every feature's `-ui` module. @@ -118,7 +118,7 @@ Each feature has two modules, because its reducer has to be plain Kotlin/JVM and - Feature modules depend on core modules, never on another feature's modules. A feature's `-ui` module also depends on its own `-logic` module. - The ViewModel goes in the `-ui` module and extends MviViewModel from `:core:mvi`. It runs side effects through `:core:data` and uses Hilt, and both are Android. A plain Kotlin/JVM module can't depend on an Android module. -- `:app` depends on every feature's `-ui` module and handles navigation between features. A feature whose screen sits on `:app`'s back stack exposes one public composable from its `-ui` module, which takes plain values and actions, such as `onOpenVideo`, and never sees Navigation 3. See [Navigation](#navigation). The YouTube layer's debug screen has its own activity instead. +- `:app` depends on every feature's `-ui` module and handles navigation between features. A feature whose screen sits on `:app`'s back stack exposes one public composable from its `-ui` module, which takes plain values and actions, such as `onOpenVideo`, and never sees Navigation 3. The one exception is `:feature:player-ui`, which also exposes the mini player, a bar that `:app` places under the back stack, with the same kind of actions. The maintainer approved it on November 21, 2026, as ADR 0002's note records. See [Navigation](#navigation). The YouTube layer's debug screen has its own activity instead. The Search YouTube screen is the first feature. Its pair: @@ -131,10 +131,10 @@ The video screen, which opens from a search result, is the second. Its pair: | Module | Folder | Type | Namespace or package | What it holds | Depends on | |---|---|---|---|---|---| -| `:feature:player-logic` | feature/player-logic/ | Kotlin/JVM | io.github.dewfallapp.feature.player.logic | PlayerState, PlayerIntent, the reducer, the channel's initial, which errors offer "Try again", the start decision, the shared failure rule, the playback times' text, and their tests | `:core:mvi`, `:core:model`, both as api dependencies | -| `:feature:player-ui` | feature/player-ui/ | Android library | io.github.dewfallapp.feature.player.ui | PlayerRoute, the Compose screen and its previews, the previews' screenshot tests in src/screenshotTest with their reference images, the video area and its playback status, PlayerViewModel and its tests, and string resources | `:feature:player-logic`, `:core:data`, `:core:designsystem`, `:core:model`, `:core:mvi`, `:core:playback`, media3-ui-compose and media3-common-ktx | +| `:feature:player-logic` | feature/player-logic/ | Kotlin/JVM | io.github.dewfallapp.feature.player.logic | PlayerState, PlayerIntent, the reducer, the channel's initial, which errors offer "Try again", the start decision, the shared failure rule, the playback times' text, what the mini player shows, when the fullscreen controls show, and their tests | `:core:mvi`, `:core:model`, both as api dependencies | +| `:feature:player-ui` | feature/player-ui/ | Android library | io.github.dewfallapp.feature.player.ui | PlayerRoute, the Compose screen and its previews, the previews' screenshot tests in src/screenshotTest with their reference images, the video area and its playback status, the fullscreen player, MiniPlayer and their previews, PlayerViewModel and its tests, and string resources | `:feature:player-logic`, `:core:data`, `:core:designsystem`, `:core:model`, `:core:mvi`, `:core:playback`, media3-ui-compose, media3-common-ktx and activity-compose, for fullscreen's window and back gesture | -The modules are named player, because #42 to #44 add playback to the same screen. The service that plays media doesn't depend on any screen, so it lives in a core module of its own, `:core:playback`. See [The player](#the-player). +The modules are named player, because #42 to #44 add playback to the same screen, and #44 adds the mini and fullscreen players. The service that plays media doesn't depend on any screen, so it lives in a core module of its own, `:core:playback`. See [The player](#the-player). The YouTube layer's debug screen has a pair of its own, which `:app` adds to debug builds only. [The YouTube layer's debug screen](#the-youtube-layers-debug-screen) explains it. @@ -746,7 +746,7 @@ A screen calls it with `viewModel.pendingEffects.collectAsStateWithLifecycle().v - MviViewModel takes no dispatcher. viewModelScope runs on Dispatchers.Main.immediate, and tests replace Main with Dispatchers.setMain, as Google's [coroutine testing guide](https://developer.android.com/kotlin/coroutines/test#setting-main-dispatcher) does. - Code that moves work to another thread, such as a repository, receives a CoroutineDispatcher in its constructor, so a test can pass a TestDispatcher. Its suspend functions are safe to call from the main thread, so the ViewModel calls them from viewModelScope without switching threads ([coroutines best practices](https://developer.android.com/kotlin/coroutines/coroutines-best-practices)). - The reducer never runs side effects. Only runSideEffects starts work. -- Playback state never goes into screen state. A screen that shows playback reads two sources: its own state, and the player, through its MediaController, with media3-ui-compose's state holders or as Flows, at the rate the visible UI needs. Player commands go straight to the player, not through intents. See [ADR 0002](adr/0002-mvi-with-playback-state-outside.md) and its note of November 20, 2026. +- Playback state never goes into screen state. A screen that shows playback reads two sources: its own state, and the player, through its MediaController, with media3-ui-compose's state holders or as Flows, at the rate the visible UI needs. Player commands go straight to the player, not through intents. The mini player has no screen state, and reads only the player. See [ADR 0002](adr/0002-mvi-with-playback-state-outside.md) and its notes of November 20 and 21, 2026. ### Why the ViewModel base is in a plain Kotlin/JVM module @@ -758,14 +758,16 @@ On the computer's JVM there's no Main dispatcher, and viewModelScope then quietl ## Navigation -`:app` owns the back stack and the screens on it, with [Navigation 3](https://developer.android.com/guide/navigation/navigation-3). Only `:app` sees it. Each feature whose screen sits on the back stack exposes one public composable from its `-ui` module, which takes plain values and actions: `YouTubeSearch(onOpenVideo)` and `PlayerRoute(videoId, onClose)`. So features never depend on each other or on the navigation library, and replacing it would change only `:app`. +`:app` owns the back stack and the screens on it, with [Navigation 3](https://developer.android.com/guide/navigation/navigation-3). Only `:app` sees it. Each feature whose screen sits on the back stack exposes one public composable from its `-ui` module, which takes plain values and actions: `YouTubeSearch(onOpenVideo)` and `PlayerRoute(videoId, onMinimize)`. `:feature:player-ui` also exposes `MiniPlayer(onOpenVideo)`, which `:app` places under the back stack. So features never depend on each other or on the navigation library, and replacing it would change only `:app`. - **The keys.** Each screen has a key: SearchKey, an object, and PlayerKey, which holds the video's VideoId and an entry ID. They are `@Serializable` NavKeys, so `rememberNavBackStack(SearchKey)` saves the back stack across configuration changes and process death ([Save your back stack](https://developer.android.com/guide/navigation/navigation-3/save-state)). VideoId lives in `:core:model`, which has no serialization plugin, so `:app`'s VideoIdSerializer saves its text and restores it through VideoId's constructor, which checks it. - **The ID in saved state.** The back stack is saved in the state Android keeps for a process it ends in the background, so the video ID of an open video screen is in it, on the device only, as the search field's text is. PlayerKey's toString hides the ID, as VideoId's does ([ADR 0007](adr/0007-how-the-app-logs.md)). - **The content key.** Navigation 3 tells entries apart by their content key, and NavEntry's toString prints it. Since Navigation 3 1.1.6, its default is made from the key's toString and its class ([release notes](https://developer.android.com/jetpack/androidx/releases/navigation3)), and in 1.2.1 it is the string `"$key:${key::class}"` ([NavEntry.kt at 1.2.1](https://android.googlesource.com/platform/frameworks/support/+/65822252146d26e872acf03dc11bda43f11efa3b/navigation3/navigation3-runtime/src/commonMain/kotlin/androidx/navigation3/runtime/NavEntry.kt)). PlayerKey's toString hides the ID, so that default would be the same for every video. So PlayerKey's entry ID, a random UUID's text made when the key is created, is its content key. It keeps two entries apart, even two for the same video, and holds no ID. - **The decorators.** NavDisplay gets `rememberSaveableStateHolderNavEntryDecorator()` and `rememberViewModelStoreNavEntryDecorator()`, so each entry keeps its own saved state, such as the search field's text, and its own ViewModels, which are cleared when the entry leaves the back stack. From Lifecycle 2.11.0 the decorator passes the activity's default factory, which is Hilt's, on to each entry, so `viewModel()` works for a @HiltViewModel inside an entry ([Lifecycle 2.11.0](https://developer.android.com/jetpack/androidx/releases/lifecycle)). - **A ViewModel per video.** PlayerViewModel takes its video through Hilt's [assisted injection](https://dagger.dev/hilt/view-model.html): PlayerRoute adds a creation callback to the entry's default creation extras, which calls the ViewModel's assisted factory. The factory takes PlayerArgs, an ordinary class that holds the VideoId, because Kotlin renames any function that takes a value class ([inline classes](https://kotlinlang.org/docs/inline-classes.html)), and Dagger can't inject value classes ([google/dagger#2930](https://github.com/google/dagger/issues/2930)). -- **Opening and closing.** Three small functions of the back stack, in BackStack.kt, change it. openVideo adds a PlayerKey only while SearchKey is on top, so a second tap while the video screen opens opens nothing. close removes that entry's own key, if it is still there. goBack, which NavDisplay calls for the system's back gesture, removes the top key only while there is more than one. So a double tap on close can't empty the back stack, which would crash NavDisplay: it requires at least one entry, and throws "NavDisplay backstack cannot be empty" otherwise ([NavDisplay.kt at 1.2.1](https://android.googlesource.com/platform/frameworks/support/+/65822252146d26e872acf03dc11bda43f11efa3b/navigation3/navigation3-ui/src/commonMain/kotlin/androidx/navigation3/ui/NavDisplay.kt)). +- **Opening and minimizing.** Three small functions of the back stack, in BackStack.kt, change it. openVideo adds a PlayerKey only while SearchKey is on top, so a second tap while the video screen opens opens nothing. close removes that entry's own key, if it is still there, for the video screen's minimize button. goBack, which NavDisplay calls for the system's back gesture, removes the top key only while there is more than one. So a double tap on minimize can't empty the back stack, which would crash NavDisplay: it requires at least one entry, and throws "NavDisplay backstack cannot be empty" otherwise ([NavDisplay.kt at 1.2.1](https://android.googlesource.com/platform/frameworks/support/+/65822252146d26e872acf03dc11bda43f11efa3b/navigation3/navigation3-ui/src/commonMain/kotlin/androidx/navigation3/ui/NavDisplay.kt)). + +- **The mini player.** DewfallNavigation puts NavDisplay and MiniPlayer in a Column. MiniPlayer shows while `showsMiniPlayer`, a function of the back stack, is true: while no PlayerKey is on top. It draws nothing while the player has no video. Its action is `openVideo`. The mini player pads its content with the system bars and the display cutout, bottom and sides, but not the keyboard, so the keyboard covers it. DewfallNavigation measures the mini player's height, in a box that reports 0 when the mini player draws nothing, and NavDisplay gives it up from the window insets with `consumeWindowInsets(PaddingValues(bottom = height))`. So a screen's own `safeDrawing` padding leaves out the navigation bar, and keeps only the part of the keyboard that reaches above the mini player. The three facts about Navigation 3 above, NavEntry's toString, the default content key and the empty back stack, were checked on November 19, 2026, in version 1.2.1, the one the app uses, both in its source at the release commit and in its compiled classes. @@ -775,10 +777,10 @@ The three facts about Navigation 3 above, NavEntry's toString, the default conte - `DewfallTheme` is the entry point. `:app` draws the whole UI inside it. Screens read colors, text styles and shapes from `MaterialTheme`, never fixed values, and take spacing from `DewfallSpacing`. - On Android 12 and later, the theme takes its colors from the wallpaper, because the [design brief](design/brief.md) turns dynamic color on by default. Older phones get Dewfall's own light and dark palettes. The brief has no setting to turn dynamic color off, so the app has none. The `dynamicColor` parameter is there for previews. -- The `darkTheme` parameter follows the system's dark theme. The fullscreen player will pass true, because it uses the dark scheme in light mode too. +- The `darkTheme` parameter follows the system's dark theme. The fullscreen player passes true, because it uses the dark scheme in light mode too. - The palettes, the type scale and the shapes are internal to the module, so screens reach them only through `MaterialTheme`. The palettes include the fixed roles, which Material 3's scheme builders accept. - Material 3 is an api dependency of the module, because screens use its components and `MaterialTheme`. -- The design system's opacity tokens aren't in the code. Material 3's components already use the same state layer and disabled opacities, and its modal bottom sheet puts `scrim` behind itself at 32%, as scrim-modal asks. Compose dialogs are different: they dim the screen through Android's dialog window, by an amount that comes from the window theme, not from `scrim`. The first dialog needs a check against the design system's 32%. duration-scrim comes with the first component that uses it. +- Of the design system's opacity tokens, only duration-scrim is in the code, as `DewfallOpacity.DURATION_SCRIM`, for the fullscreen player's overlays, and DesignTokensTest checks it. Material 3's components already use the same state layer and disabled opacities, and its modal bottom sheet puts `scrim` behind itself at 32%, as scrim-modal asks. Compose dialogs are different: they dim the screen through Android's dialog window, by an amount that comes from the window theme, not from `scrim`. The first dialog needs a check against the design system's 32%. **Manrope.** All text is set in Manrope, the design system's typeface. The module's res/font/manrope.ttf is the variable font Manrope[wght].ttf, version 4.505, from [googlefonts/manrope](https://github.com/googlefonts/manrope) at commit 468c0db. The copy in Google Fonts' own repository, ofl/manrope/ in [google/fonts](https://github.com/google/fonts), is the same file, with the same Git blob hash. One file holds every weight from 200 to 800, at 164,700 bytes. The static files for the three weights the type scale uses, manrope-regular.ttf, manrope-medium.ttf and manrope-semibold.ttf in fonts/ttf/ at the same commit, take 432,912 bytes together. Variable fonts need Android 8.0, below the app's minimum ([ADR 0006](adr/0006-platform-and-android-versions.md)). @@ -812,7 +814,7 @@ The other previews are SurfaceColorsPreview, AccentColorsDynamicPreview, Surface ## The player -Videos play in `:core:playback`, an Android library that no screen owns, so the sound plays on in the background, and #44's mini player can reuse it. It depends on `:core:data`, for the stream links and the YouTube layer's media requests, and on `:core:model` and `:core:logging`, never on `:core:youtube`. The facts about Media3 below were checked on November 19, 20 and 21, 2026, in Media3 1.11.1, the version the app uses, in its source at tag 1.11.1 and in its compiled classes. +Videos play in `:core:playback`, an Android library that no screen owns, so the sound plays on in the background, and the mini player goes on with a video after its screen closes. Playback belongs to the app, not to a screen. It depends on `:core:data`, for the stream links and the YouTube layer's media requests, and on `:core:model` and `:core:logging`, never on `:core:youtube`. The facts about Media3 below were checked on November 19, 20 and 21, 2026, in Media3 1.11.1, the version the app uses, in its source at tag 1.11.1 and in its compiled classes. ```mermaid sequenceDiagram @@ -834,7 +836,7 @@ sequenceDiagram ### The service and the connection - **PlaybackService** is a MediaSessionService with one ExoPlayer. It adds its session with `addSession` in `onCreate`, and publishes it to PlaybackSessions, a singleton inside the process. PlaybackConnection starts it with `startService` while a screen is visible. -- **PlaybackConnection** is how screens reach the player. Its one implementation builds one MediaController for the application's context from the session's own token, because a SessionToken that names the service needs the intent filter ([SessionToken.java at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/session/src/main/java/androidx/media3/session/SessionToken.java)). It keeps the controller while the session lives, so a configuration change finds it as it was. +- **PlaybackConnection** is how screens and the mini player reach the player. Its one implementation builds one MediaController for the application's context from the session's own token, because a SessionToken that names the service needs the intent filter ([SessionToken.java at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/session/src/main/java/androidx/media3/session/SessionToken.java)). It keeps the controller while the session lives, so a configuration change finds it as it was. - **When the service stops.** Android stops an app's started services a few minutes after the app leaves the screen, unless something binds to them or they run in the foreground ([background service limits](https://developer.android.com/about/versions/oreo/background#services)). Then `onDestroy` releases the session and the player and clears PlaybackSessions and PlaybackItems. `onStartCommand` returns START_NOT_STICKY, so Android never restarts an empty service. The connection drops its controller when it disconnects, and the next `prepare` starts the service again. ### The notification and the foreground service @@ -865,7 +867,8 @@ The playback commands are play and pause, prepare, stop, seeking within the item ### In the background -- **The picture.** MainActivity calls `PlaybackConnection.setAppVisible(true)` in `onStart`, and `false` in `onStop` unless `isChangingConfigurations`. PlaybackSessions keeps it, and PlaybackService turns the video track off while the app can't be seen, building on its track selection parameters, so a live stream's variant override stays. So it decodes no picture, and a ProgressiveMediaPeriod with no selected track cancels its loading ([ProgressiveMediaPeriod at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/source/ProgressiveMediaPeriod.java)), so a video-only file isn't fetched. A combined format, and a live stream's HLS segments, which carry both, keep loading. For a live stream, HLS keeps its last variant selection, which the override limited ([HlsSampleStreamWrapper at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/exoplayer_hls/src/main/java/androidx/media3/exoplayer/hls/HlsSampleStreamWrapper.java)). Coming back loads the video file from the current position, so the sound may pause for a moment. The signal comes from the app's one activity, so #44's players follow the same rule. +- **The picture.** MainActivity calls `PlaybackConnection.appStarted()` in `onStart`, and `appStopped(isChangingConfigurations)` in `onStop`. A video screen holds the picture with `holdPicture()` while its ViewModel exists, so a configuration change, such as turning to landscape for fullscreen, never lets go of it. PlaybackSessions keeps whether the app can be seen and how many holds there are, and PlaybackService turns the video track off while the app can't be seen or nothing holds the picture, as while a video is minimized, building on its track selection parameters, so a live stream's variant override stays. So it decodes no picture, and a ProgressiveMediaPeriod with no selected track cancels its loading ([ProgressiveMediaPeriod at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/source/ProgressiveMediaPeriod.java)), so a video-only file isn't fetched. A combined format, and a live stream's HLS segments, which carry both, keep loading. For a live stream, HLS keeps its last variant selection, which the override limited ([HlsSampleStreamWrapper at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/exoplayer_hls/src/main/java/androidx/media3/exoplayer/hls/HlsSampleStreamWrapper.java)). Coming back to the video screen loads the video file from the current position, so the sound may pause for a moment. The maintainer chose to turn the picture off while minimized on November 21, 2026, because it saves the data of a video-only file. +- **Leaving the app.** A video that has played keeps playing in the background. `appStopped` acts on the pure function `leaveDecision`: a configuration change does nothing, and otherwise a start that still waits for the connection won't play, and the player pauses its item unless it is the playback ID that last played. The connection keeps that ID from a listener on its controller. A video that hasn't played would start its foreground service from the background, which Android refuses, so it waits, paused, on the video screen or in the mini player. - **Failures.** A playback that failed keeps its notification, and its play button prepares the player again from the same position. When the service reports a failure, it turns play off. On Android 10 to 12, Media3's notification shows a play button for a failed player, because it is idle ([Util.shouldShowPlayButton at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/common/src/main/java/androidx/media3/common/util/Util.java)), but the button sends the play and pause toggle key ([PlaybackPendingIntentBuilder at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/session/src/main/java/androidx/media3/session/PlaybackPendingIntentBuilder.java)), and Media3 pauses a player whose play is on ([MediaSessionImpl at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/session/src/main/java/androidx/media3/session/MediaSessionImpl.java), `applyMediaButtonKeyEvent`). A failure leaves play on, so the first tap did nothing until the service turned it off, as hand checks on Android 10 and 12L showed on November 21, 2026. PlaybackService clears the failure in `onPlayerErrorChanged(null)`, so the video screen shows no old failure over a video that plays again. - **The end.** When a video ends, the service turns play off too. Media3 shows a play button for an ended player too ([Util.shouldShowPlayButton at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/common/src/main/java/androidx/media3/common/util/Util.java)), and a headset's play and pause button sends the same toggle as the notification's on every Android version, which Media3 turns into a pause while play is on ([MediaSessionImpl at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/session/src/main/java/androidx/media3/session/MediaSessionImpl.java), `applyMediaButtonKeyEvent`). With play off, one press plays the video again from the start, as a hand check on Android 10 showed on November 21, 2026. So after the end, seeking back on the video screen leaves the video paused there until the user presses play. @@ -878,7 +881,7 @@ Media3 copies an item's `mediaId` and the player's metadata into Android's media 3. The session's player is SessionPlayer, a ForwardingSimpleBasePlayer around the ExoPlayer. It shows the session each item reduced to its playback ID, with no link, no metadata of its own and no manifest. Its only metadata is the current item's title and channel name. Every error has the same code, no cause and a constant message, "This video stopped playing.", from `:core:playback`'s resources, because car displays and watches may show it. ExoPlayer's renderer errors append the format's codec, size, bitrate and language to their message ([ExoPlaybackException at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/exoplayer/src/main/java/androidx/media3/exoplayer/ExoPlaybackException.java)), and Media3 copies the message into the platform session. 4. When the details show, PlayerViewModel calls `PlaybackConnection.describe` with the playback ID, the title and the channel name. PlaybackItems keeps them with the ID's entry, and SessionPlayer builds its state again, so the notification shows them. -So other apps, Bluetooth devices and the lock screen see that a video plays, its title and channel name, its length and its position, never its ID or a link. That is an exception to the product rule "User data stays on the device", which the maintainer approved on November 21, 2026, and which AGENTS.md and PRIVACY.md record. PlaybackItems drops an entry when another item takes its place, when the items are cleared, when its playback can't start, and when its screen stops it, even if its item never became the player's. So in memory the process holds the ID, the title, the channel name and the links of one video at a time, and none after the screen closes. +So other apps, Bluetooth devices and the lock screen see that a video plays, its title and channel name, its length and its position, never its ID or a link. That is an exception to the product rule "User data stays on the device", which the maintainer approved on November 21, 2026, and which AGENTS.md and PRIVACY.md record. PlaybackItems drops an entry when another item takes its place, when the items are cleared, when its playback can't start, and when its screen closes, unless its item is the player's or the start that waits for the connection, as `releaseDrops` decides. So in memory the process holds the ID, the title, the channel name and the links of one video at a time, while it plays on the video screen or in the mini player, and none after the mini player closes it. ### Choosing the formats @@ -901,7 +904,7 @@ PlaybackSources is the ExoPlayer's MediaSource.Factory. It reads the item's tag: ### Errors -- **Expired links.** On HTTP 403 or 410, the service fetches new links once, puts the new item in place of the old one, goes back to the old position, or a live stream's live edge, and plays if it was playing. The refresh steps run over RefreshTarget, a small interface, so a JVM test checks them with a fake. The limit resets once the item is ready again, so a second refusal in a row stands. +- **Expired links.** On HTTP 403 or 410, the service fetches new links once, puts the new item in place of the old one, goes back to the old position, or a live stream's live edge, and plays only if play was on when the link was refused and is still on when the new links arrive, as `resumesAfterRefresh` decides, so a pause while they load stays. The refresh steps run over RefreshTarget, a small interface, so a JVM test checks them with a fake. The limit resets once the item is ready again, so a second refusal in a row stands. - **Retries.** PlaybackLoadErrorPolicy retries neither 403, 410 nor a MediaRequestRefused, so the refresh starts at once and a refused request is never sent again. Other errors keep DefaultLoadErrorHandlingPolicy's retries. - **Categories.** PlaybackFailure, in `:core:model`, names why a video can't play. The service maps the real PlaybackException, which only it sees, and a failed resolution maps the YouTubeError. MediaRequestRefused counts as YOUTUBE wherever it is in the cause chain, because OkHttpDataSource wraps it as an IOException around an ExecutionException ([OkHttpDataSource at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/datasource_okhttp/src/main/java/androidx/media3/datasource/okhttp/OkHttpDataSource.java)), and Media3 reports any IOException from a data source as a network error. A network that failed or timed out is NETWORK, a decoder that can't decode the format or fails while decoding is NOT_DECODABLE, and anything else is OTHER, including a decoder that fails to start, such as while another app holds it, or that the system took back. Each decision is a pure function of plain inputs, with its own tests. - **The screen.** The video area shows the failure in the details' words, plus "This video can't play on this phone." for NOT_DECODABLE and "This video stopped playing." for OTHER. "Try again" shows for NETWORK, YOUTUBE and OTHER, and prepares the video again from the last position. When the details failed with the same category, the video area shows no second message, and the details' "Try again" retries both. @@ -920,21 +923,41 @@ The video screen's VideoArea, in `:feature:player-ui`, sits above the details, a - The picture is media3-ui-compose's ContentFrame on a SurfaceView, in a 16:9 box that takes at most 45% of the window's height. Compose's clip doesn't round a SurfaceView, so the box draws its rounded corners over it in the screen's background role, `surface`. The shutter before the first frame is `surfaceContainerHighest`, not ContentFrame's black. - `Modifier.keepScreenOn()` applies while the player plays, so the screen doesn't time out while the user watches, which would stop the activity and turn the picture off. - The seek bar ticks as many times as it has pixels, with `rememberProgressStateWithTickCount`, and the times tick once a second, with `rememberProgressStateWithTickInterval`. The play and pause button uses `rememberPlayPauseButtonState`. At a video's end it offers to play it again from the start. A live stream says "Live" in place of the seek bar and the times. -- `rememberPlaybackStatus`, in the same module, listens with media3-common-ktx's `Player.listen` for loading, live and the end. It stays there until #44 needs to share it, so `:core:playback` has no Compose. +- `rememberPlaybackStatus`, in the same module, listens with media3-common-ktx's `Player.listen` for loading, live, the end and playing. The mini player and fullscreen live in the same module, so it stays there, and `:core:playback` has no Compose. +- A fullscreen button sits at the end of the play and pause row, as the "Player" frames show, while the player is connected. -**Starting, pausing and stopping.** PlayerRoute keeps four things in its saved state: whether playback started, the playback ID, the playback ID that has played, and the position. Each start saves the position it starts from. While the screen exists, even with the app in the background, a Player listener saves the position whenever this screen's item pauses or ends, so when Android stops a player that paused in the background, the screen waits where it paused. ON_STOP saves it too. Neither saves from an idle player, whose position after a failure may not be where the video was. Android writes the saved state only when the activity stops, so after the process ends the screen comes back at the position it had when the user last left the app, until #50 stores positions. The pure function `startAction` in `:feature:player-logic` decides from them: +**Starting, minimizing and stopping.** PlayerRoute keeps three things in its saved state: whether playback started, the playback ID, and the position. Each start saves the position it starts from. While the screen exists, even with the app in the background, a Player listener saves the position whenever this screen's item pauses or ends, so when Android stops a player that paused in the background, the screen waits where it paused. ON_STOP saves it too. Neither saves from an idle player, whose position after a failure may not be where the video was. Android writes the saved state only when the activity stops, so after the process ends the screen comes back at the position it had when the user last left the app, until #50 stores positions. The pure function `startAction` in `:feature:player-logic` decides from them: - The first opening plays from the start, or a live stream from its live edge. +- A first opening whose video the player already plays, from the mini player or from search, goes on with it as it is, GO_ON, and starts nothing. PlayerViewModel finds that playback with `PlaybackConnection.videoOf`. - After a configuration change, the playback goes on. - After the system ended the process, or stopped the service, the playback ID is unknown, so the screen waits at the saved position with the play button and no picture, and fetches nothing until the user presses play. -Leaving the app keeps a video that has played playing in the background. ON_STOP pauses through the connection only a playback that hasn't played yet, as the pure function `pausesOnLeave` decides, because its foreground service would start from the background, which Android refuses. A start that still waits for the connection then starts paused. A configuration change does neither. "Try again", and play after the session was gone, go on from the player's position, or the saved one when the player has no item. PlayerViewModel keeps the latest playback ID, from the first start, a play after the session was gone, or "Try again", and its `onCleared` asks the connection to stop. Navigation 3 clears it only after the screen's exit animation, so the connection stops only if the player's item is still that ID. An activity destroyed for good clears it too, so the developer option "Don't keep activities" stops background play, until #44 revisits the stop rule. +Leaving the app is the connection's rule, which [In the background](#in-the-background) describes. "Try again", and play after the session was gone, go on from the player's position, or the saved one when the player has no item. PlayerViewModel keeps the latest playback ID, from the first start, a play after the session was gone, "Try again", or GO_ON, and `follow` tells a ViewModel made again, as after "Don't keep activities", which ID is its own. Its `onCleared` releases that playback, so minimizing leaves it to the mini player, and lets go of the picture. Navigation 3 clears it only after the screen's exit animation. The mini player's close button stops playback, and so do removing the app from the recent apps and dismissing the paused notification. + +**Player commands skip intents.** Play, pause, seek and the playback starts go from the UI straight to the player, not through PlayerIntent, and the screen reads the playback state through the controller's state holders, never in PlayerState. A tap would only pass through the reducer unchanged. [ADR 0002](adr/0002-mvi-with-playback-state-outside.md)'s note of November 20, 2026 records it, and its note of November 21, 2026 extends it to the mini player. + +### The mini player + +MiniPlayer, in `:feature:player-ui`, shows the video that plays while no video screen is on top, after the "Mini player on the inbox" frames. It isn't a screen: it has no screen state and no ViewModel. It gets PlaybackConnection through a Hilt entry point, because a composable takes no injected constructor and the public composable takes only plain values and actions. It reads the controller through media3-ui-compose's `rememberCurrentMediaItemState`, `rememberPlayPauseButtonState` and `rememberProgressStateWithTickCount`. + +- **What it shows.** The pure function `miniPlayerContent`, in `:feature:player-logic`, returns nothing while there is no current item, and otherwise the playback ID, the title, the channel name and whether a progress line shows, which a live stream's doesn't. The title and channel name are the session's metadata, which PlayerViewModel's `describe` gave. Until then, or when the details failed, it says "Now playing", the name the design gives the mini player's region. Minimizing before the details load cancels their request, so the mini player says "Now playing" until the video screen opens again. +- **How it looks.** A `surfaceContainerHigh` bar, with a 2dp line along its top, `primary` on `surfaceContainerHighest`, drawn in the draw phase so its ticks redraw only the line, and hidden from screen readers. Then the title in `titleMedium`, which wraps, the channel name in `bodySmall`, the filled play and pause button, and a close button. Its background reaches under the navigation bar, and its content sits in a centered column of ReadableWidth. MiniPlayerBar draws it from plain values, for the previews and screenshot tests. +- **What it does.** Its play, pause and close go straight to the player: close calls `stop`, which clears the items, so the notification goes. A tap on the title, named "Open video" for screen readers, looks up the video with `videoOf` and calls `onOpenVideo`. After a failure, play prepares the player again from the same position, as Media3's play and pause action does for an idle player ([Util.java at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/common/src/main/java/androidx/media3/common/util/Util.java), `handlePlayButtonAction`). It gives no reason, and the video screen says why once it opens. +- **When Android stops the player.** A paused, minimized video in the background loses its mini player when Android stops the service, and its position with it, until #50 stores positions. The maintainer accepted that on November 21, 2026. + +### Fullscreen + +The fullscreen button on the video screen sends EnterFullscreen, and PlayerState's `fullscreen` makes PlayerRoute show FullscreenPlayer in place of the screen, after the "Player full screen" frames. PlayerViewModel also keeps it in its SavedStateHandle, so after the process ends the screen comes back in fullscreen, waiting for play, and can't stay turned to landscape out of fullscreen. Entry ViewModels get a SavedStateHandle because NavDisplay has the saveable state decorator before the ViewModel decorator, as the KDoc of ViewModelStoreNavEntryDecorator in lifecycle-viewmodel-navigation3 2.11.0 asks. The facts below were checked on November 21, 2026. -**Player commands skip intents.** Play, pause, seek and the playback starts go from the UI straight to the player, not through PlayerIntent, and the screen reads the playback state through the controller's state holders, never in PlayerState. A tap would only pass through the reducer unchanged. [ADR 0002](adr/0002-mvi-with-playback-state-outside.md)'s note of November 20, 2026 records it. +- **The window.** FullscreenWindow, while it is composed, asks for `SCREEN_ORIENTATION_USER_LANDSCAPE`, which is landscape either way round as the rotation lock allows ([activity element](https://developer.android.com/guide/topics/manifest/activity-element#screen)), sets `BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE`, and shows the system bars only while the controls show ([Hide system bars for immersive mode](https://developer.android.com/develop/ui/views/layout/immersive)). It gives the bars light icons over the black window, again after every configuration change, because Android 17 no longer restarts the activity for some changes ([Handle configuration changes](https://developer.android.com/guide/topics/resources/runtime-changes)) and activity 1.13.0 calls edge to edge again then ([activity release notes](https://developer.android.com/jetpack/androidx/releases/activity)). Leaving sets portrait, the manifest's orientation for MainActivity, restores the icons and shows the bars, unless the activity is only changing configurations. Android 17 ignores orientation requests, and `getRequestedOrientation()`, on displays whose smallest width is greater than 600dp ([Android 17's change](https://developer.android.com/about/versions/17/changes/ff-restrictions-ignored)), so fullscreen keeps the window's shape there, and leaving sets portrait instead of restoring a saved value. Lint's SourceLockedOrientationActivity check is suppressed for that call, as the manifest's LockedOrientationActivity is. +- **The back gesture.** PlayerContent calls `BackHandler(enabled = state.fullscreen)` every time, as its reference asks, because conditional calls can change which handler runs ([BackHandler](https://developer.android.com/reference/kotlin/androidx/activity/compose/BackHandler.composable)). The entry composes after NavDisplay's own handler, and the last one composed runs, so the gesture leaves fullscreen and not the screen. +- **The layout.** Inside `DewfallTheme(darkTheme = true)`, the window is `scrim`. The picture is ContentFrame with its default ContentScale.Fit, padded with the display cutout only, so showing the bars never moves it. Before the first frame a 16:9 box in `surfaceContainerHighest` stands in for it. The title in `titleMedium` and the channel name in `bodySmall` and `onSurfaceVariant` sit at the top in a box at most 480dp wide, and the play and pause button, the times, the seek bar and the exit button at the bottom, both on `surface` at `DewfallOpacity.DURATION_SCRIM`. They sit 16dp inside `WindowInsets.systemBarsIgnoringVisibility` and the cutout, which stay the same while the bars hide ([About window insets](https://developer.android.com/develop/ui/compose/system/insets)), so no bar ever covers them. The frames put the overlays inside a 16:9 picture, but a video of another shape would leave little room, so they follow the window. Fullscreen shows the player's own failure in a Banner in the picture's place, with "Try again" where it helps. +- **The controls.** FullscreenControls, in `:feature:player-logic`, decides with pure functions. They show while the video isn't playing, `Player.isPlaying` being false while it pauses, waits for data, has ended or failed, and while touch exploration is on, which fullscreen follows with `addTouchExplorationStateChangeListener`, because a screen reader's swipes send the app no pointer events. Otherwise a tap toggles them, and they hide after `calculateRecommendedTimeoutMillis(3000, ...)` milliseconds, which the accessibility settings may lengthen ([Android 10 features](https://developer.android.com/about/versions/10/features)). Every touch restarts the wait, and a key shows them and restarts it. Pausing, the end, a failure and playing again show them, as Media3's PlayerView does ([PlayerView.java at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/ui/src/main/java/androidx/media3/ui/PlayerView.java), `auto_show`). The picture's tap is named "Show controls" or "Hide controls". They appear without animation, because the design system's motion only answers a tap. ### How the playback tests run -`:core:playback`'s unit tests run on the JVM against AGP's stub android.jar, with no Robolectric. Media3's PlaybackException, HttpDataSourceException, MediaItem with a URI and LoadEventInfo call Android code that the stub throws on. So each decision is a pure function of plain inputs, and a thin adapter turns Media3's objects into them: the failure category, the cause-chain walk, the retry decision, the session's error, the source plan, the stop rule, the metered rule, the controller kind, the playback and skip command lists, whether to cancel a leftover notification, PlaybackItems' descriptions and PlaybackSessions' visibility state. Media3's command constants are plain ints, so the command lists are lists of ints, and the service builds Player.Commands from them. The refresh steps run over a fake RefreshTarget. The adapters only read fields and build Media3 objects, and the hand checks in [testing.md](testing.md#checking-the-player-by-hand) run them. +`:core:playback`'s unit tests run on the JVM against AGP's stub android.jar, with no Robolectric. Media3's PlaybackException, HttpDataSourceException, MediaItem with a URI and LoadEventInfo call Android code that the stub throws on. So each decision is a pure function of plain inputs, and a thin adapter turns Media3's objects into them: the failure category, the cause-chain walk, the retry decision, the session's error, the source plan, the stop rule, the metered rule, the controller kind, the playback and skip command lists, whether to cancel a leftover notification, the leave decision, the release decision, PlaybackItems' descriptions and PlaybackSessions' picture state. Media3's command constants are plain ints, so the command lists are lists of ints, and the service builds Player.Commands from them. The refresh steps run over a fake RefreshTarget. The adapters only read fields and build Media3 objects, and the hand checks in [testing.md](testing.md#checking-the-player-by-hand) run them. ## Downloads and cleanup diff --git a/docs/testing.md b/docs/testing.md index a8b9741..a59f77d 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -674,7 +674,7 @@ Both print 0. For app/build/outputs/apk/debug/app-debug.apk, the first prints se ## Checking the player by hand -The player's unit tests cover its decisions, as [The player](architecture.md#how-the-playback-tests-run) describes. The code that turns Media3's objects into those decisions, the service, the session, the notification and the screen run only on a device. So a change to `:core:playback`, the video area or MainActivity's visibility signal gets these checks, on emulators with Android 10 (API 29), Android 12L (API 32) and the newest Android, unless a check says it needs a real phone. Android 12L matters because Media3 starts the foreground service before play only on API 31 and 32. Install a debug build with `./gradlew :app:installDebug`, and open videos from Search YouTube. The developer option "Don't keep activities" stops background play, because the video screen's ViewModel stops playback when its activity is destroyed for good, so leave it off. +The player's unit tests cover its decisions, as [The player](architecture.md#how-the-playback-tests-run) describes. The code that turns Media3's objects into those decisions, the service, the session, the notification and the screen run only on a device. So a change to `:core:playback`, the video area, the mini player, fullscreen or MainActivity's visibility signal gets these checks, on emulators with Android 10 (API 29), Android 12L (API 32) and the newest Android, unless a check says it needs a real phone. Android 12L matters because Media3 starts the foreground service before play only on API 31 and 32. Install a debug build with `./gradlew :app:installDebug`, and open videos from Search YouTube. - **Playing.** Open a video and see it start, with sound and picture together. Seek, pause and play. Play a short video to its end, see the button offer to play it again, and replay it from the start. - **A long video.** Play a video an hour or longer for several minutes at 1080p, and seek near its end. This checks MediaRequests' request shape, which no unit test reaches. @@ -682,11 +682,20 @@ The player's unit tests cover its decisions, as [The player](architecture.md#how - **Networks.** Play once on Wi-Fi and once on mobile data only, after `adb shell svc wifi disable`, and turn Wi-Fi back on with `adb shell svc wifi enable`. Turn the network off while playing, see the failure, then "Try again" with it on. - **The background.** Play and go home: the sound goes on, and the notification shows the title, the channel name and pause. Pause and play from it, and from the lock screen. Turn the screen off for 10 minutes, then force Doze with `adb shell dumpsys deviceidle force-idle`: the sound goes on. Restore it with `adb shell dumpsys deviceidle unforce`. Tap the notification: Dewfall opens as it was. - **The picture in the background.** While a 1080p video plays, compare the received bytes in `adb shell cat /proc/net/dev` over one minute with the app visible and with it in the background: far fewer in the background. Come back: the picture shows again at the current position. Play a live stream on mobile data and go home for three minutes: the sound goes on, and the bytes per minute are no more than about 20 percent above those with the app visible. The segments keep their variant in the background, so the bytes should match, and the margin allows for segments of different sizes and for the variant ExoPlayer adapts to within the limit. Come back: the picture returns, within the 480p limit, as the platform codec's lines in `adb logcat` show by its size. -- **Leaving early.** Open a video and go home before it starts: no sound, and coming back it waits for play. -- **Stopping.** Close the video screen: the sound stops, the notification goes away, and `adb shell dumpsys media_session` shows no title or channel name. Remove Dewfall from the recent apps while it plays: the sound stops and the notification goes away. Resize a split screen window, or change the theme, while it plays, and see it keep playing. +- **Leaving early.** Open a video and go home before it starts: no sound, and coming back it waits for play. The developer option "Don't keep activities" no longer stops background play: with it on, play, go home, and come back: the video screen shows it still playing. +- **Stopping.** Minimize a playing video and tap the mini player's close button: the sound stops, the notification and the mini player go away, and `adb shell dumpsys media_session` shows no title or channel name. Remove Dewfall from the recent apps while it plays: the sound stops and the notification goes away. Resize a split screen window, or change the theme, while it plays, and see it keep playing. +- **Minimizing.** Minimize a playing video with the button, with the back gesture, and with a quick double tap: Search shows as it was, the app goes back once, and the mini player shows the title, the channel name and pause while the sound goes on. Minimize a paused video: it stays paused, and the mini player offers play. Minimize one that is still loading: it starts, and the mini player shows it. Minimize one whose details failed: the mini player says "Now playing". +- **The mini player.** Pause and play from it. Let a short video end and play it again from the start. Turn the network off until the player runs out of data, turn it on, and press play: it plays on. Tap its title: the video screen shows the video at the same position, playing or paused, without starting it again. Open the same video from search: the same. Open another video: it starts from the start. +- **The mini player's layout.** Scroll the search results to the end with the mini player, at the default and the largest font size, with gesture and three-button navigation: the last result is fully above it, and a long title wraps. Type in the search field: the keyboard covers the mini player, and the results end above the keyboard. On a tablet or a resizable emulator, its background fills the width and its content sits in a centered column. Minimize and open the video again a few times while watching the screen above it during the animation: no text hides under it. +- **Minimized in the background.** Minimize a playing video, go home, and tap the notification: Search shows with the mini player, still playing, and the received bytes in `adb shell cat /proc/net/dev` stay low, because the picture is off until the video screen opens. Compare the bytes of a 1080p video over one minute with the video screen open and minimized: far fewer minimized. Open it again: the picture shows at the current position. Minimize a video that is still loading and go home at once: no sound, and coming back the mini player offers play. On Android 10, make the back gesture on Search with the mini player, which finishes the root activity there: the sound plays on, and the notification reopens Search with the mini player. Minimize a playing video, go home, and end the process: coming back shows no mini player, and nothing plays. Minimize a paused video, go home, wait over 10 minutes until the service leaves the foreground, and stop it with `adb shell am make-uid-idle io.github.dewfallapp`: coming back shows no mini player, and opening the video starts it from the start. +- **A video that can't decode, minimized.** On the Android 17 emulator without `-feature -HardwareDecoder`, open a video and minimize it: if the mini player shows, play fails again and gives no reason, and opening the video screen says why. +- **Fullscreen on a phone.** In light mode, enter fullscreen while a video plays: the phone turns to landscape, the colors are dark, and the sound doesn't pause. The controls and the system bars hide 3 seconds after the last touch while it plays, with light bar icons while they show, and a tap brings them back. A tap while they show hides them. With them hidden, swipe from an edge: the bars show for a moment and hide again. In landscape with three-button navigation, show the bars: they cover no part of the title or the control row, and nothing moves. Turn the phone the other way round: it follows when auto-rotate is on. Exit with the button and with the back gesture: portrait, the bars back, still playing. +- **Fullscreen controls.** With them hidden, pause with `adb shell input keyevent KEYCODE_MEDIA_PAUSE`, let a short video end, and turn the network off until the player runs out of data: each time the controls show. Press play: they stay, and hide 3 seconds later. Tap while paused: they stay. Press a key on a hardware keyboard: they show. With `adb shell settings put secure accessibility_interactive_ui_timeout_ms 60000` they hide only after a minute. Put it back with `adb shell settings delete secure accessibility_interactive_ui_timeout_ms`. With TalkBack on, where the emulator has it, they show and stay. +- **More fullscreen.** On an emulator with a display cutout, no text, control or picture sits under it. A live stream says "Live". Turn the network off while it plays: the failure shows with "Try again" and the exit button. At the largest font size, the title wraps in its box and the controls are whole. On Android 17 in light mode, connect a hardware keyboard or change the navigation mode in fullscreen: the bar icons stay light. Go home and come back, and tap the notification: still fullscreen, still playing. Pause, go home, end the process with `adb shell am kill io.github.dewfallapp`, or, if that leaves it running, as on Android 10 while the paused service is in the foreground, with `adb shell kill -9` and the process ID from `adb shell pidof io.github.dewfallapp` after `adb root`, then `adb unroot`. On the Android 10 emulator, `run-as io.github.dewfallapp kill -9` answered "unknown pid" for it. Come back: fullscreen shows, waiting for play, and the back gesture leaves it and turns the phone back to portrait. +- **Fullscreen on large screens.** On a tablet in portrait, in split screen, and on a foldable or resizable emulator: fullscreen keeps the window's shape, with black around the video. Enter fullscreen unfolded, fold, and leave fullscreen: the phone is in portrait. On the Pixel Fold emulator, `adb shell cmd device_state state 0` folds it, and the outer screen asks for a swipe up before the app goes on there. In split screen Android keeps the status bar, which the app can't hide there, so check only that nothing sits under it. - **Dismissing.** On Android 10, pause in the background, wait over 10 minutes, and dismiss the notification: playback stops. Come back: the video waits at its position, and play goes on from it. Android 11 and later show media as a player in Quick Settings or the shade, and hide a paused one about 10 minutes after it pauses, the same moment the notification becomes dismissible, so this check runs on Android 10 only. - **Coming back.** Play, go home, let it play a minute, and pause from the notification. Wait over 10 minutes, so the service leaves the foreground, then stop it with `adb shell am make-uid-idle io.github.dewfallapp` where this Android has it. Send `adb shell input keyevent KEYCODE_MEDIA_PLAY` while the process lives on: nothing plays. Come back: the video waits at the paused position. Go home again, end the process with `adb shell am kill io.github.dewfallapp`, and send the key again: the app doesn't start, and nothing crashes. Come back: the video waits at the position it had when you left the app. -- **A notification left behind.** On Android 10: pause in the background and wait over 10 minutes, until the notification can be dismissed. Within about a minute, before Android stops the service, end the process with `adb shell am kill io.github.dewfallapp`, or, if that leaves it running, with `adb shell run-as io.github.dewfallapp kill -9` and the process ID from `adb shell pidof io.github.dewfallapp`. Check with `adb shell pidof` that the process ended and the notification still shows. Tap its play button: nothing plays, nothing crashes, and the notification goes away. +- **A notification left behind.** On Android 10: pause in the background and wait over 10 minutes, until the notification can be dismissed. Within about a minute, before Android stops the service, end the process with `adb shell am kill io.github.dewfallapp`. That works here, because the service has left the foreground. If it leaves the process running, use `adb shell kill -9` with the process ID from `adb shell pidof io.github.dewfallapp` after `adb root`, then `adb unroot`, as in [More fullscreen](#checking-the-player-by-hand). Check with `adb shell pidof` that the process ended and the notification still shows. Tap its play button: nothing plays, nothing crashes, and the notification goes away. - **The end in the background.** Let a short video end in the background, then press Play in the notification once, on Android 10 to 12, or send `adb shell input keyevent KEYCODE_HEADSETHOOK` once: it plays again from the start. - **Failures in the background.** Turn the network off while playing in the background, turn it on, and press play in the notification: it plays on from the same position, and the video screen shows no failure. - **Sound.** Start music in another app while a video plays, and see the video pause. On a real phone, unplug headphones, or turn off a Bluetooth headset, while a video plays, and see it pause. diff --git a/feature/player-logic/src/main/kotlin/io/github/dewfallapp/feature/player/logic/FullscreenControls.kt b/feature/player-logic/src/main/kotlin/io/github/dewfallapp/feature/player/logic/FullscreenControls.kt new file mode 100644 index 0000000..44fcf4c --- /dev/null +++ b/feature/player-logic/src/main/kotlin/io/github/dewfallapp/feature/player/logic/FullscreenControls.kt @@ -0,0 +1,36 @@ +package io.github.dewfallapp.feature.player.logic + +/** + * Whether the fullscreen player's title, controls and system bars show. [shown] is what the user + * last chose with a tap, or what the last change of playing set. They always show while the video + * isn't playing or a screen reader is on, as Media3's PlayerView does when playback pauses, ends or + * fails. See openspec/specs/player/spec.md. + */ +data class FullscreenControls(val shown: Boolean = true) { + /** Whether they show, while the video is [playing] or not and a [screenReader] is on or not. */ + fun visible(playing: Boolean, screenReader: Boolean): Boolean = + !playing || screenReader || shown + + /** + * After a tap on the picture: they toggle while the video is [playing] and no [screenReader] is + * on. Otherwise they stay, and a later tap starts from them showing. + */ + fun tapped(playing: Boolean, screenReader: Boolean): FullscreenControls = + if (playing && !screenReader) copy(shown = !shown) else copy(shown = true) + + /** After the video started or stopped playing: they show. */ + fun playingChanged(): FullscreenControls = copy(shown = true) + + /** After a touch or a key: they show, and the wait starts again. */ + fun touched(): FullscreenControls = copy(shown = true) + + /** After the wait while they showed and the video played: they hide. */ + fun timedOut(): FullscreenControls = copy(shown = false) + + /** + * Whether they hide after the wait: only while they show, the video is [playing], no + * [screenReader] is on, and no finger is [held] down, such as on the seek bar. + */ + fun hidesAfterTimeout(playing: Boolean, screenReader: Boolean, held: Boolean = false): Boolean = + shown && playing && !screenReader && !held +} diff --git a/feature/player-logic/src/main/kotlin/io/github/dewfallapp/feature/player/logic/MiniPlayerContent.kt b/feature/player-logic/src/main/kotlin/io/github/dewfallapp/feature/player/logic/MiniPlayerContent.kt new file mode 100644 index 0000000..5d93fc9 --- /dev/null +++ b/feature/player-logic/src/main/kotlin/io/github/dewfallapp/feature/player/logic/MiniPlayerContent.kt @@ -0,0 +1,52 @@ +package io.github.dewfallapp.feature.player.logic + +/** + * What the mini player shows for the player's current item. [playbackId] is what its tap opens and + * its close button stops. [title] is null when the item has none yet, and the mini player then says + * "Now playing". [channelName] is null when there is none. [showsProgress] is false for a live + * stream, which has no progress line. The title and the channel name are user data, so toString + * never shows them. + */ +class MiniPlayerContent( + val playbackId: String, + val title: String?, + val channelName: String?, + val showsProgress: Boolean, +) { + override fun equals(other: Any?): Boolean = + other is MiniPlayerContent && + playbackId == other.playbackId && + title == other.title && + channelName == other.channelName && + showsProgress == other.showsProgress + + override fun hashCode(): Int { + var result = playbackId.hashCode() + result = 31 * result + title.hashCode() + result = 31 * result + channelName.hashCode() + return 31 * result + showsProgress.hashCode() + } + + override fun toString(): String = "MiniPlayerContent(hidden)" +} + +/** + * What the mini player shows, from the player's [currentItemId], the item's [title] and + * [channelName] as the session gives them, and whether it is [live]. It returns null when there is + * no current item, so the mini player draws nothing. An empty or blank title or channel name counts + * as none. + */ +fun miniPlayerContent( + currentItemId: String?, + title: CharSequence?, + channelName: CharSequence?, + live: Boolean, +): MiniPlayerContent? { + val playbackId = currentItemId ?: return null + return MiniPlayerContent( + playbackId = playbackId, + title = title?.toString()?.takeIf { it.isNotBlank() }, + channelName = channelName?.toString()?.takeIf { it.isNotBlank() }, + showsProgress = !live, + ) +} diff --git a/feature/player-logic/src/main/kotlin/io/github/dewfallapp/feature/player/logic/PlayerContract.kt b/feature/player-logic/src/main/kotlin/io/github/dewfallapp/feature/player/logic/PlayerContract.kt index f682e8c..2115172 100644 --- a/feature/player-logic/src/main/kotlin/io/github/dewfallapp/feature/player/logic/PlayerContract.kt +++ b/feature/player-logic/src/main/kotlin/io/github/dewfallapp/feature/player/logic/PlayerContract.kt @@ -42,8 +42,14 @@ sealed interface DetailsArea { data class Failed(val number: Long, val error: YouTubeError) : DetailsArea } -/** The video screen's state. Playback state never goes here. See ADR 0002. */ -data class PlayerState(val details: DetailsArea = DetailsArea.Loading(number = 0)) : MviState +/** + * The video screen's state. Playback state never goes here. See ADR 0002. [fullscreen] says whether + * the screen shows the fullscreen player. The ViewModel keeps it in its saved state too. + */ +data class PlayerState( + val details: DetailsArea = DetailsArea.Loading(number = 0), + val fullscreen: Boolean = false, +) : MviState /** What happens on the video screen. */ sealed interface PlayerIntent : MviIntent { @@ -56,4 +62,10 @@ sealed interface PlayerIntent : MviIntent { /** Request [number] answered with [result]. */ data class DetailsFinished(val number: Long, val result: YouTubeResult) : PlayerIntent + + /** The user tapped the fullscreen button. */ + data object EnterFullscreen : PlayerIntent + + /** The user tapped the exit button, or made the back gesture, in fullscreen. */ + data object ExitFullscreen : PlayerIntent } diff --git a/feature/player-logic/src/main/kotlin/io/github/dewfallapp/feature/player/logic/PlayerReducer.kt b/feature/player-logic/src/main/kotlin/io/github/dewfallapp/feature/player/logic/PlayerReducer.kt index 0e88949..4c24232 100644 --- a/feature/player-logic/src/main/kotlin/io/github/dewfallapp/feature/player/logic/PlayerReducer.kt +++ b/feature/player-logic/src/main/kotlin/io/github/dewfallapp/feature/player/logic/PlayerReducer.kt @@ -8,7 +8,8 @@ import io.github.dewfallapp.core.mvi.Reducer /** * The video screen's reducer. Load starts the first request, and "Try again" starts the next one * only after a failure that offers it. An answer counts only while its own request is running. The - * screen has no effects, so its effect type is Nothing. + * fullscreen intents turn fullscreen on and off, and leave the details alone. The screen has no + * effects, so its effect type is Nothing. */ object PlayerReducer : Reducer { override fun reduce(state: PlayerState, intent: PlayerIntent): Next = @@ -17,6 +18,8 @@ object PlayerReducer : Reducer { PlayerIntent.Load -> state.loaded() PlayerIntent.TryAgain -> state.triedAgain() is PlayerIntent.DetailsFinished -> state.finished(intent) + PlayerIntent.EnterFullscreen -> state.copy(fullscreen = true) + PlayerIntent.ExitFullscreen -> state.copy(fullscreen = false) }, ) } diff --git a/feature/player-logic/src/main/kotlin/io/github/dewfallapp/feature/player/logic/StartAction.kt b/feature/player-logic/src/main/kotlin/io/github/dewfallapp/feature/player/logic/StartAction.kt index c5b732d..632d155 100644 --- a/feature/player-logic/src/main/kotlin/io/github/dewfallapp/feature/player/logic/StartAction.kt +++ b/feature/player-logic/src/main/kotlin/io/github/dewfallapp/feature/player/logic/StartAction.kt @@ -5,6 +5,12 @@ enum class StartAction { /** The entry opened for the first time: start playing. */ PLAY, + /** + * The entry opened for the first time, and the player already plays this video, such as from + * the mini player: go on with that playback as it is, and start nothing. + */ + GO_ON, + /** * The entry came back after the system ended the process or stopped the player: wait at the * saved position for the user to press play, and fetch nothing until then. @@ -17,21 +23,14 @@ enum class StartAction { /** * What the video screen does with playback when its entry shows: whether playback [started] before, - * as the entry's saved state says, and whether its playback ID is still [playbackIdKnown] to the - * player, which it isn't after the session was gone. + * as the entry's saved state says, whether its playback ID is still [playbackIdKnown] to the + * player, which it isn't after the session was gone, and whether the player's current item + * [playsThisVideo], a playback of this screen's video that another screen started. */ -fun startAction(started: Boolean, playbackIdKnown: Boolean): StartAction = +fun startAction(started: Boolean, playbackIdKnown: Boolean, playsThisVideo: Boolean): StartAction = when { + !started && playsThisVideo -> StartAction.GO_ON !started -> StartAction.PLAY playbackIdKnown -> StartAction.NOTHING else -> StartAction.WAIT_FOR_PLAY } - -/** - * Whether leaving the app pauses the video screen's playback: only when the activity isn't just - * [changingConfigurations], and the playback hasn't [played] yet. A video that has played keeps - * playing in the background. One that hasn't would start the foreground service from the - * background, which Android refuses, so it waits, paused, for the user to come back. - */ -fun pausesOnLeave(changingConfigurations: Boolean, played: Boolean): Boolean = - !changingConfigurations && !played diff --git a/feature/player-logic/src/test/kotlin/io/github/dewfallapp/feature/player/logic/FullscreenControlsTest.kt b/feature/player-logic/src/test/kotlin/io/github/dewfallapp/feature/player/logic/FullscreenControlsTest.kt new file mode 100644 index 0000000..d7b8a22 --- /dev/null +++ b/feature/player-logic/src/test/kotlin/io/github/dewfallapp/feature/player/logic/FullscreenControlsTest.kt @@ -0,0 +1,81 @@ +package io.github.dewfallapp.feature.player.logic + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +private val SHOWN = FullscreenControls(shown = true) +private val HIDDEN = FullscreenControls(shown = false) + +class FullscreenControlsTest { + @Test + fun `they start shown`() { + assertTrue(FullscreenControls().shown) + } + + @Test + fun `while playing without a screen reader, they show as the user chose`() { + assertTrue(SHOWN.visible(playing = true, screenReader = false)) + assertFalse(HIDDEN.visible(playing = true, screenReader = false)) + } + + @Test + fun `they show whenever the video isn't playing`() { + assertTrue(SHOWN.visible(playing = false, screenReader = false)) + assertTrue(HIDDEN.visible(playing = false, screenReader = false)) + } + + @Test + fun `they show whenever a screen reader is on`() { + assertTrue(SHOWN.visible(playing = true, screenReader = true)) + assertTrue(HIDDEN.visible(playing = true, screenReader = true)) + assertTrue(HIDDEN.visible(playing = false, screenReader = true)) + } + + @Test + fun `a tap toggles them only while playing without a screen reader`() { + assertEquals(HIDDEN, SHOWN.tapped(playing = true, screenReader = false)) + assertEquals(SHOWN, HIDDEN.tapped(playing = true, screenReader = false)) + } + + @Test + fun `a tap while paused or with a screen reader keeps them shown`() { + assertEquals(SHOWN, SHOWN.tapped(playing = false, screenReader = false)) + assertEquals(SHOWN, HIDDEN.tapped(playing = false, screenReader = false)) + assertEquals(SHOWN, SHOWN.tapped(playing = true, screenReader = true)) + assertEquals(SHOWN, HIDDEN.tapped(playing = true, screenReader = true)) + } + + @Test + fun `starting or stopping playing shows them`() { + assertEquals(SHOWN, HIDDEN.playingChanged()) + assertEquals(SHOWN, SHOWN.playingChanged()) + } + + @Test + fun `a touch or a key shows them`() { + assertEquals(SHOWN, HIDDEN.touched()) + assertEquals(SHOWN, SHOWN.touched()) + } + + @Test + fun `the wait hides them`() { + assertEquals(HIDDEN, SHOWN.timedOut()) + } + + @Test + fun `they hide after the wait only while shown and playing without a screen reader`() { + assertTrue(SHOWN.hidesAfterTimeout(playing = true, screenReader = false)) + assertFalse(HIDDEN.hidesAfterTimeout(playing = true, screenReader = false)) + assertFalse(SHOWN.hidesAfterTimeout(playing = false, screenReader = false)) + assertFalse(SHOWN.hidesAfterTimeout(playing = true, screenReader = true)) + assertFalse(HIDDEN.hidesAfterTimeout(playing = false, screenReader = true)) + } + + @Test + fun `they don't hide while a finger is held down, such as on the seek bar`() { + assertFalse(SHOWN.hidesAfterTimeout(playing = true, screenReader = false, held = true)) + assertTrue(SHOWN.hidesAfterTimeout(playing = true, screenReader = false, held = false)) + } +} diff --git a/feature/player-logic/src/test/kotlin/io/github/dewfallapp/feature/player/logic/MiniPlayerContentTest.kt b/feature/player-logic/src/test/kotlin/io/github/dewfallapp/feature/player/logic/MiniPlayerContentTest.kt new file mode 100644 index 0000000..984a256 --- /dev/null +++ b/feature/player-logic/src/test/kotlin/io/github/dewfallapp/feature/player/logic/MiniPlayerContentTest.kt @@ -0,0 +1,53 @@ +package io.github.dewfallapp.feature.player.logic + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue + +private const val ID = "playback 1" +private const val TITLE = "How reading rooms were lit before electric lamps" +private const val CHANNEL = "Larkspur Lectures" + +class MiniPlayerContentTest { + @Test + fun `no current item shows nothing`() { + assertNull(miniPlayerContent(currentItemId = null, TITLE, CHANNEL, live = false)) + } + + @Test + fun `a current item shows its title, channel and progress`() { + assertEquals( + MiniPlayerContent(ID, TITLE, CHANNEL, showsProgress = true), + miniPlayerContent(ID, TITLE, CHANNEL, live = false), + ) + } + + @Test + fun `an empty or blank title counts as none`() { + assertNull(miniPlayerContent(ID, title = null, CHANNEL, live = false)?.title) + assertNull(miniPlayerContent(ID, title = "", CHANNEL, live = false)?.title) + assertNull(miniPlayerContent(ID, title = " \n", CHANNEL, live = false)?.title) + } + + @Test + fun `no channel name counts as none`() { + assertNull(miniPlayerContent(ID, TITLE, channelName = null, live = false)?.channelName) + assertNull(miniPlayerContent(ID, TITLE, channelName = "", live = false)?.channelName) + } + + @Test + fun `a live stream has no progress line`() { + assertFalse(miniPlayerContent(ID, TITLE, CHANNEL, live = true)!!.showsProgress) + assertTrue(miniPlayerContent(ID, TITLE, CHANNEL, live = false)!!.showsProgress) + } + + @Test + fun `the text never shows the title or the channel`() { + val text = miniPlayerContent(ID, TITLE, CHANNEL, live = false).toString() + + assertFalse(TITLE in text) + assertFalse(CHANNEL in text) + } +} diff --git a/feature/player-logic/src/test/kotlin/io/github/dewfallapp/feature/player/logic/PlaybackTest.kt b/feature/player-logic/src/test/kotlin/io/github/dewfallapp/feature/player/logic/PlaybackTest.kt index bf44761..234adf9 100644 --- a/feature/player-logic/src/test/kotlin/io/github/dewfallapp/feature/player/logic/PlaybackTest.kt +++ b/feature/player-logic/src/test/kotlin/io/github/dewfallapp/feature/player/logic/PlaybackTest.kt @@ -11,21 +11,46 @@ import kotlin.test.assertTrue class PlaybackTest { @Test fun `the first opening plays, a configuration change does nothing, and a lost session waits`() { - assertEquals(StartAction.PLAY, startAction(started = false, playbackIdKnown = false)) - assertEquals(StartAction.PLAY, startAction(started = false, playbackIdKnown = true)) - assertEquals(StartAction.NOTHING, startAction(started = true, playbackIdKnown = true)) + assertEquals( + StartAction.PLAY, + startAction(started = false, playbackIdKnown = false, playsThisVideo = false), + ) + assertEquals( + StartAction.PLAY, + startAction(started = false, playbackIdKnown = true, playsThisVideo = false), + ) + assertEquals( + StartAction.NOTHING, + startAction(started = true, playbackIdKnown = true, playsThisVideo = false), + ) assertEquals( StartAction.WAIT_FOR_PLAY, - startAction(started = true, playbackIdKnown = false), + startAction(started = true, playbackIdKnown = false, playsThisVideo = false), + ) + } + + @Test + fun `a first opening goes on with a playback that already plays the video`() { + assertEquals( + StartAction.GO_ON, + startAction(started = false, playbackIdKnown = false, playsThisVideo = true), + ) + assertEquals( + StartAction.GO_ON, + startAction(started = false, playbackIdKnown = true, playsThisVideo = true), ) } @Test - fun `leaving pauses only a playback that hasn't played, and never on a configuration change`() { - assertTrue(pausesOnLeave(changingConfigurations = false, played = false)) - assertFalse(pausesOnLeave(changingConfigurations = false, played = true)) - assertFalse(pausesOnLeave(changingConfigurations = true, played = false)) - assertFalse(pausesOnLeave(changingConfigurations = true, played = true)) + fun `a screen that started its own playback never goes on with another`() { + assertEquals( + StartAction.NOTHING, + startAction(started = true, playbackIdKnown = true, playsThisVideo = true), + ) + assertEquals( + StartAction.WAIT_FOR_PLAY, + startAction(started = true, playbackIdKnown = false, playsThisVideo = true), + ) } @Test diff --git a/feature/player-logic/src/test/kotlin/io/github/dewfallapp/feature/player/logic/PlayerReducerTest.kt b/feature/player-logic/src/test/kotlin/io/github/dewfallapp/feature/player/logic/PlayerReducerTest.kt index cd5399d..7e26583 100644 --- a/feature/player-logic/src/test/kotlin/io/github/dewfallapp/feature/player/logic/PlayerReducerTest.kt +++ b/feature/player-logic/src/test/kotlin/io/github/dewfallapp/feature/player/logic/PlayerReducerTest.kt @@ -159,4 +159,30 @@ class PlayerReducerTest { assertEquals(DetailsArea.Failed(2, YouTubeError.BLOCKED), state.details) } + + @Test + fun `the screen starts out of fullscreen`() { + assertEquals(false, PlayerState().fullscreen) + } + + @Test + fun `the fullscreen intents turn fullscreen on and off`() { + val entered = PlayerReducer.reduce(PlayerState(), PlayerIntent.EnterFullscreen) + assertEquals(Next(PlayerState(fullscreen = true)), entered) + + val left = PlayerReducer.reduce(entered.state, PlayerIntent.ExitFullscreen) + assertEquals(Next(PlayerState(fullscreen = false)), left) + } + + @Test + fun `the fullscreen intents leave the details alone`() { + val shown = PlayerState(details = DetailsArea.Shown(PAGE)) + + val entered = PlayerReducer.reduce(shown, PlayerIntent.EnterFullscreen).state + assertEquals(shown.details, entered.details) + assertEquals( + shown.details, + PlayerReducer.reduce(entered, PlayerIntent.ExitFullscreen).state.details, + ) + } } diff --git a/feature/player-ui/build.gradle.kts b/feature/player-ui/build.gradle.kts index e3709a8..3f770f9 100644 --- a/feature/player-ui/build.gradle.kts +++ b/feature/player-ui/build.gradle.kts @@ -23,6 +23,9 @@ dependencies { // live. See docs/architecture.md#the-player. implementation(libs.androidx.media3.ui.compose) implementation(libs.androidx.media3.common.ktx) + // LocalActivity and BackHandler, for fullscreen's window and back gesture. :app ships the same + // version, so the APK gains no library. + implementation(libs.androidx.activity.compose) implementation(libs.androidx.lifecycle.runtime.compose) implementation(libs.androidx.lifecycle.viewmodel.compose) } diff --git a/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/FullscreenControlRow.kt b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/FullscreenControlRow.kt new file mode 100644 index 0000000..32232dd --- /dev/null +++ b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/FullscreenControlRow.kt @@ -0,0 +1,128 @@ +@file:OptIn(UnstableApi::class) + +package io.github.dewfallapp.feature.player.ui + +import androidx.annotation.OptIn +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +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.padding +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Slider +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.semantics +import androidx.media3.common.Player +import androidx.media3.common.util.UnstableApi +import androidx.media3.ui.compose.state.rememberPlayPauseButtonState +import io.github.dewfallapp.core.designsystem.R as DesignR +import io.github.dewfallapp.core.designsystem.theme.DewfallSpacing + +/** + * The play and pause button, the times, the seek bar and the exit button. A live stream says "Live" + * in place of the times and the seek bar. A failure keeps only the exit button. + */ +@Composable +internal fun ControlRow(content: VideoAreaContent, onPlay: () -> Unit, onExit: () -> Unit) { + Row( + modifier = + Modifier.fillMaxWidth() + .clip(MaterialTheme.shapes.large) + .background(overlayColor()) + .padding(DewfallSpacing.xs), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(DewfallSpacing.sm), + ) { + when (content) { + is VideoAreaContent.Failed -> Spacer(Modifier.weight(1f)) + is VideoAreaContent.Waiting -> { + PlayPauseButton(showPlay = true, ended = false, enabled = true, onClick = onPlay) + TimesAndSeekBar(Modifier.weight(1f)) { + content.positionMs?.let { TimesText(positionMs = it, durationMs = null) } + IdleSeekBar(Modifier.weight(1f)) + } + } + is VideoAreaContent.Playing -> { + val player = content.player + if (player == null) { + PlayPauseButton(showPlay = true, ended = false, enabled = false, onClick = {}) + IdleSeekBar(Modifier.weight(1f)) + } else { + PlayingControls(player) + } + } + } + IconButton(onClick = onExit) { + Icon( + painter = painterResource(DesignR.drawable.ic_fullscreen_exit), + contentDescription = stringResource(R.string.player_exit_fullscreen), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } +} + +/** The button, and the times and the seek bar, or "Live", for a connected [player]. */ +@Composable +private fun RowScope.PlayingControls(player: Player) { + val playPause = rememberPlayPauseButtonState(player) + val status = rememberPlaybackStatus(player) + PlayPauseButton( + showPlay = playPause.showPlay, + ended = status.ended, + enabled = playPause.isEnabled, + onClick = playPause::onClick, + ) + if (status.live) { + Text( + text = stringResource(R.string.player_video_live), + style = MaterialTheme.typography.titleSmall, + modifier = Modifier.weight(1f), + ) + } else { + TimesAndSeekBar(Modifier.weight(1f)) { + Times(player) + SeekBar(player, Modifier.weight(1f)) + } + } +} + +/** + * The times and the seek bar in a row of their own, which takes only the width the buttons leave, + * so in a narrow window at a large font the times can't squeeze the exit button out. + */ +@Composable +private fun TimesAndSeekBar( + modifier: Modifier = Modifier, + content: @Composable RowScope.() -> Unit, +) { + Row( + modifier = modifier, + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(DewfallSpacing.sm), + content = content, + ) +} + +/** The seek bar while no player is connected, turned off. */ +@Composable +private fun IdleSeekBar(modifier: Modifier = Modifier) { + val description = stringResource(R.string.player_video_position) + Slider( + value = 0f, + onValueChange = {}, + enabled = false, + modifier = modifier.semantics { contentDescription = description }, + ) +} diff --git a/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/FullscreenPlayer.kt b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/FullscreenPlayer.kt new file mode 100644 index 0000000..7fcd740 --- /dev/null +++ b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/FullscreenPlayer.kt @@ -0,0 +1,392 @@ +@file:OptIn(UnstableApi::class) + +package io.github.dewfallapp.feature.player.ui + +import androidx.annotation.OptIn +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.focusable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.displayCutout +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.systemBarsIgnoringVisibility +import androidx.compose.foundation.layout.union +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.Stable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +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.draw.clip +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.keepScreenOn +import androidx.compose.ui.platform.LocalAccessibilityManager +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.heading +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.unit.dp +import androidx.media3.common.util.UnstableApi +import androidx.media3.ui.compose.ContentFrame +import io.github.dewfallapp.core.designsystem.theme.DewfallOpacity +import io.github.dewfallapp.core.designsystem.theme.DewfallSpacing +import io.github.dewfallapp.core.designsystem.theme.DewfallTheme +import io.github.dewfallapp.core.designsystem.theme.ReadableWidth +import io.github.dewfallapp.feature.player.logic.FullscreenControls +import io.github.dewfallapp.feature.player.logic.VideoPage +import kotlinx.coroutines.delay + +/** + * How long the controls stay after the last touch while the video plays, before the accessibility + * settings ask for more. + */ +private const val CONTROLS_TIMEOUT_MS = 3000L + +/** The widest the title's box gets, as the "Player full screen" frames show. */ +private val TitleMaxWidth = 480.dp + +/** The shape of the box that stands in for the picture before the first frame. */ +private const val SHUTTER_ASPECT_RATIO = 16f / 9f + +/** + * The fullscreen player, after the "Player full screen" frames: the picture as large as the window + * allows on black, the title and channel name of [page] at the top, once the details show, and the + * controls at the bottom. It uses the dark scheme in light mode too. The title, the controls and + * the system bars hide while the video plays, as [FullscreenControls] decides. [FullscreenWindow] + * turns a phone to landscape while it shows. + * + * It shows [content] as the video area does: [onPlay] runs when the user presses play while it + * waits, [onTryAgain] for a failure's "Try again", and [onExit] for the exit button. The back + * gesture's handler is the caller's, because BackHandler must be called unconditionally. + * [dynamicColor] is for previews, which use Dewfall's own palette. + */ +@Composable +internal fun FullscreenPlayer( + content: VideoAreaContent, + page: VideoPage?, + onPlay: () -> Unit, + onTryAgain: () -> Unit, + onExit: () -> Unit, + modifier: Modifier = Modifier, + dynamicColor: Boolean = true, +) { + val player = (content as? VideoAreaContent.Playing)?.player + val status = player?.let { rememberPlaybackStatus(it) } + val playing = status?.playing == true + val controls = rememberControlsState(playing) + val visible = controls.visible + FullscreenWindow(barsShown = visible) + val focus = remember { FocusRequester() } + // Keys reach onPreviewKeyEvent only through a focused node, so fullscreen takes focus. + LaunchedEffect(focus, controls.screenReader) { + if (!controls.screenReader) focus.requestFocus() + } + DewfallTheme(darkTheme = true, dynamicColor = dynamicColor) { + // No Surface sits under the overlays, so their text takes the dark scheme's onSurface. + CompositionLocalProvider(LocalContentColor provides MaterialTheme.colorScheme.onSurface) { + FullscreenBox( + content = content, + page = page, + controls = controls, + playing = playing, + loading = + status?.loading == true || + (content is VideoAreaContent.Playing && player == null), + focus = focus, + onPlay = onPlay, + onTryAgain = onTryAgain, + onExit = onExit, + modifier = modifier, + ) + } + } +} + +/** + * The black window with the picture, the [controls] state's taps, touches and keys, and the + * overlays while they show. It takes focus through [focus], so keys reach it. + */ +@Composable +private fun FullscreenBox( + content: VideoAreaContent, + page: VideoPage?, + controls: ControlsState, + playing: Boolean, + loading: Boolean, + focus: FocusRequester, + onPlay: () -> Unit, + onTryAgain: () -> Unit, + onExit: () -> Unit, + modifier: Modifier = Modifier, +) { + val visible = controls.visible + Box( + modifier = + modifier + .fillMaxSize() + .background(MaterialTheme.colorScheme.scrim) + .then(if (playing) Modifier.keepScreenOn() else Modifier) + .pointerInput(controls) { + awaitPointerEventScope { + while (true) { + val event = awaitPointerEvent(PointerEventPass.Initial) + controls.onTouch(held = event.changes.any { it.pressed }) + } + } + } + .onPreviewKeyEvent { + controls.onKey() + false + } + .focusRequester(focus) + // A screen reader moves among the controls itself, and the controls always show + // then, so the root takes no focus and gives TalkBack no unnamed stop. + .focusable(enabled = !controls.screenReader), + ) { + val tapLabel = + stringResource( + if (visible) R.string.player_hide_controls else R.string.player_show_controls, + ) + FullscreenPicture( + content = content, + loading = loading, + modifier = + Modifier.fillMaxSize().clickable( + interactionSource = null, + indication = null, + onClickLabel = tapLabel, + ) { + controls.onTap() + }, + ) + if (visible) { + Overlays( + content = content, + page = page, + onPlay = onPlay, + onTryAgain = onTryAgain, + onExit = onExit, + ) + } + } +} + +/** + * Whether the fullscreen controls show, after [FullscreenControls], and what touches, keys and taps + * do to them. See [rememberControlsState]. + */ +@Stable +private class ControlsState { + var controls by mutableStateOf(FullscreenControls()) + var playing by mutableStateOf(false) + var screenReader by mutableStateOf(false) + + /** Counts touches and keys, so each one starts the wait again. */ + var touches by mutableIntStateOf(0) + private set + + val visible: Boolean + get() = controls.visible(playing, screenReader) + + /** Whether a finger is down, such as holding the seek bar, so the controls don't hide. */ + var held by mutableStateOf(false) + private set + + /** + * A touch anywhere starts the wait again, and [held] says whether a finger stays down. A tap on + * the picture also calls [onTap]. + */ + fun onTouch(held: Boolean) { + this.held = held + touches++ + } + + /** A key, such as from a hardware keyboard or Switch Access, shows them and starts the wait. */ + fun onKey() { + controls = controls.touched() + touches++ + } + + fun onTap() { + controls = controls.tapped(playing, screenReader) + } +} + +/** + * The fullscreen controls' state while the video is [playing] or not. Pausing, the end, a failure + * and playing again bring them back. While they show, the video plays and no screen reader is on, + * they hide after the recommended timeout, which the accessibility settings may lengthen. + */ +@Composable +private fun rememberControlsState(playing: Boolean): ControlsState { + val state = remember { ControlsState() } + state.playing = playing + state.screenReader = rememberTouchExploration() + val timeoutMs = + LocalAccessibilityManager.current?.calculateRecommendedTimeoutMillis( + CONTROLS_TIMEOUT_MS, + containsIcons = true, + containsText = true, + containsControls = true, + ) ?: CONTROLS_TIMEOUT_MS + LaunchedEffect(playing) { state.controls = state.controls.playingChanged() } + LaunchedEffect( + state.controls, + playing, + state.screenReader, + state.held, + state.touches, + timeoutMs, + ) { + if (state.controls.hidesAfterTimeout(playing, state.screenReader, state.held)) { + delay(timeoutMs) + state.controls = state.controls.timedOut() + } + } + return state +} + +/** + * The picture, fitted to the window and kept clear of the display cutout, so showing or hiding the + * system bars never moves it. Before the first frame a 16:9 box in `surfaceContainerHighest` stands + * in for it, as in the frames. A failure leaves it black: its Banner is laid out with the overlays. + */ +@Composable +private fun FullscreenPicture( + content: VideoAreaContent, + loading: Boolean, + modifier: Modifier = Modifier, +) { + val shutter = MaterialTheme.colorScheme.surfaceContainerHighest + Box( + modifier = modifier.windowInsetsPadding(WindowInsets.displayCutout), + contentAlignment = Alignment.Center, + ) { + val player = (content as? VideoAreaContent.Playing)?.player + when { + // A failure's Banner is laid out with the overlays, so the title never covers it. + content is VideoAreaContent.Failed -> Unit + player != null -> { + ContentFrame( + player = player, + modifier = Modifier.fillMaxSize(), + shutter = { Shutter(shutter) }, + ) + } + else -> Shutter(shutter) + } + if (loading) { + val description = stringResource(R.string.player_loading) + CircularProgressIndicator(Modifier.semantics { contentDescription = description }) + } + } +} + +@Composable +private fun Shutter(color: Color) { + Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { + Box(Modifier.aspectRatio(SHUTTER_ASPECT_RATIO).background(color)) + } +} + +/** + * The title's box at the top and the control row at the bottom, 16dp inside the system bars, even + * while they are hidden, and the display cutout, so no bar ever covers them, and showing the bars + * moves nothing. + */ +// systemBarsIgnoringVisibility is still marked experimental in the Compose version the app uses. +// Kotlin's OptIn, because androidx.annotation.OptIn in this file is for Media3's UnstableApi. +@kotlin.OptIn(ExperimentalLayoutApi::class) +@Composable +private fun Overlays( + content: VideoAreaContent, + page: VideoPage?, + onPlay: () -> Unit, + onTryAgain: () -> Unit, + onExit: () -> Unit, +) { + Column( + modifier = + Modifier.fillMaxSize() + .windowInsetsPadding( + WindowInsets.systemBarsIgnoringVisibility.union(WindowInsets.displayCutout), + ) + .padding(DewfallSpacing.md), + verticalArrangement = Arrangement.SpaceBetween, + ) { + // The title is the only weighted child, so the row, and a failure's Banner, are measured + // first and keep their space. The title takes what is left and scrolls there, so it is + // never cut off, and SpaceBetween puts the row at the bottom and the Banner between them. + // Without a title, the spacer pushes them down. + if (page != null) { + TitleBox(page, Modifier.weight(1f, fill = false)) + } else { + Spacer(Modifier.weight(1f)) + } + if (content is VideoAreaContent.Failed) { + PlaybackFailureBanner( + failure = content.failure, + onTryAgain = onTryAgain, + modifier = + Modifier.align(Alignment.CenterHorizontally).widthIn(max = ReadableWidth), + ) + } + ControlRow(content = content, onPlay = onPlay, onExit = onExit) + } +} + +/** The title and the channel name on `surface` at the duration-scrim opacity. */ +@Composable +private fun TitleBox(page: VideoPage, modifier: Modifier = Modifier) { + Column( + modifier = + modifier + .widthIn(max = TitleMaxWidth) + .clip(MaterialTheme.shapes.large) + .background(overlayColor()) + .padding(horizontal = DewfallSpacing.md, vertical = DewfallSpacing.sm) + // Only the text scrolls, inside the box, so its corners and padding stay whole. + .verticalScroll(rememberScrollState()), + ) { + Text( + text = page.title, + style = MaterialTheme.typography.titleMedium, + modifier = Modifier.semantics { heading() }, + ) + Text( + text = page.channelName, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } +} + +/** `surface` at the design system's duration-scrim opacity, behind text and controls over video. */ +@Composable +internal fun overlayColor() = + MaterialTheme.colorScheme.surface.copy(alpha = DewfallOpacity.DURATION_SCRIM) diff --git a/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/FullscreenPreviews.kt b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/FullscreenPreviews.kt new file mode 100644 index 0000000..4cbe2b8 --- /dev/null +++ b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/FullscreenPreviews.kt @@ -0,0 +1,59 @@ +@file:OptIn(UnstableApi::class) + +package io.github.dewfallapp.feature.player.ui + +import androidx.annotation.OptIn +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.media3.common.util.UnstableApi +import io.github.dewfallapp.core.model.PlaybackFailure + +// Previews of the fullscreen player, with the made-up video and player in PlayerPreviewParts.kt. +// The @PreviewTest wrappers in src/screenshotTest render them. See +// docs/testing.md#screenshot-tests. + +/** The fullscreen player showing [video], with the made-up video's title. */ +@Composable +private fun FullscreenPreview(dynamicColor: Boolean = false, video: () -> VideoAreaContent) { + val content = remember { video() } + FullscreenPlayer( + content = content, + page = previewPage, + onPlay = {}, + onTryAgain = {}, + onExit = {}, + dynamicColor = dynamicColor, + ) +} + +@Composable +internal fun FullscreenPlayingPreview() { + FullscreenPreview { VideoAreaContent.Playing(PreviewPlayer(playing = true)) } +} + +@Composable +internal fun FullscreenPausedPreview() { + FullscreenPreview { VideoAreaContent.Playing(PreviewPlayer(playing = false)) } +} + +@Composable +internal fun FullscreenPausedDynamicPreview() { + FullscreenPreview(dynamicColor = true) { + VideoAreaContent.Playing(PreviewPlayer(playing = false)) + } +} + +@Composable +internal fun FullscreenLivePreview() { + FullscreenPreview { VideoAreaContent.Playing(PreviewPlayer(playing = false, live = true)) } +} + +@Composable +internal fun FullscreenFailurePreview() { + FullscreenPreview { VideoAreaContent.Failed(PlaybackFailure.NETWORK) } +} + +@Composable +internal fun FullscreenWaitingPreview() { + FullscreenPreview { VideoAreaContent.Waiting(PREVIEW_POSITION_MS) } +} diff --git a/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/FullscreenWindow.kt b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/FullscreenWindow.kt new file mode 100644 index 0000000..6505752 --- /dev/null +++ b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/FullscreenWindow.kt @@ -0,0 +1,85 @@ +package io.github.dewfallapp.feature.player.ui + +import android.annotation.SuppressLint +import android.content.pm.ActivityInfo +import android.view.accessibility.AccessibilityManager +import androidx.activity.compose.LocalActivity +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.setValue +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import androidx.core.view.WindowCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.WindowInsetsControllerCompat + +/** + * Whether touch exploration is on, as for TalkBack, following its changes while composed. A screen + * reader's swipes between controls send the app no pointer events, so the controls stay while it is + * on. + */ +@Composable +internal fun rememberTouchExploration(): Boolean { + val context = LocalContext.current + val manager = remember(context) { context.getSystemService(AccessibilityManager::class.java) } + var enabled by remember(manager) { mutableStateOf(manager?.isTouchExplorationEnabled == true) } + DisposableEffect(manager) { + val listener = AccessibilityManager.TouchExplorationStateChangeListener { enabled = it } + manager?.addTouchExplorationStateChangeListener(listener) + onDispose { manager?.removeTouchExplorationStateChangeListener(listener) } + } + return enabled +} + +/** + * The window while fullscreen shows. On entering, it turns a phone to landscape, either way round + * as its rotation setting allows, keeps hidden system bars to a swipe from the edge, and gives the + * bars light icons over the black window, again after every configuration change, because activity + * calls edge to edge again then. The bars show while [barsShown], with the controls. Leaving turns + * the screen back to portrait, the orientation that the manifest gives MainActivity and the design + * brief keeps phones in, and restores the bars and their icons. A configuration change restores + * nothing, because the new activity composes this again. Android ignores the orientation on large + * screens, where fullscreen keeps the window's shape. + */ +// Portrait is the orientation that the manifest gives MainActivity, and the design brief keeps +// phones in it, as the manifest's LockedOrientationActivity suppression says. Android ignores it on +// large screens. +@SuppressLint("SourceLockedOrientationActivity") +@Composable +internal fun FullscreenWindow(barsShown: Boolean) { + val activity = LocalActivity.current ?: return + val configuration = LocalConfiguration.current + val bars = + remember(activity) { + WindowCompat.getInsetsController(activity.window, activity.window.decorView) + } + DisposableEffect(activity) { + val lightStatusBars = bars.isAppearanceLightStatusBars + val lightNavigationBars = bars.isAppearanceLightNavigationBars + bars.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE + activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE + onDispose { + if (!activity.isChangingConfigurations) { + activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT + bars.isAppearanceLightStatusBars = lightStatusBars + bars.isAppearanceLightNavigationBars = lightNavigationBars + bars.show(WindowInsetsCompat.Type.systemBars()) + } + } + } + LaunchedEffect(bars, configuration) { + bars.isAppearanceLightStatusBars = false + bars.isAppearanceLightNavigationBars = false + } + LaunchedEffect(bars, barsShown) { + if (barsShown) { + bars.show(WindowInsetsCompat.Type.systemBars()) + } else { + bars.hide(WindowInsetsCompat.Type.systemBars()) + } + } +} diff --git a/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/MiniPlayer.kt b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/MiniPlayer.kt new file mode 100644 index 0000000..9328c6f --- /dev/null +++ b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/MiniPlayer.kt @@ -0,0 +1,274 @@ +@file:OptIn(UnstableApi::class) + +package io.github.dewfallapp.feature.player.ui + +import androidx.annotation.OptIn +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +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.Spacer +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.WindowInsetsSides +import androidx.compose.foundation.layout.displayCutout +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.only +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.systemBars +import androidx.compose.foundation.layout.union +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LocalContentColor +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.drawBehind +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.geometry.Size +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.unit.LayoutDirection +import androidx.compose.ui.unit.dp +import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.media3.common.Player +import androidx.media3.common.util.UnstableApi +import androidx.media3.ui.compose.state.rememberCurrentMediaItemState +import androidx.media3.ui.compose.state.rememberPlayPauseButtonState +import androidx.media3.ui.compose.state.rememberProgressStateWithTickCount +import dagger.hilt.EntryPoint +import dagger.hilt.InstallIn +import dagger.hilt.android.EntryPointAccessors +import dagger.hilt.components.SingletonComponent +import io.github.dewfallapp.core.designsystem.R as DesignR +import io.github.dewfallapp.core.designsystem.theme.DewfallSpacing +import io.github.dewfallapp.core.designsystem.theme.ReadableWidth +import io.github.dewfallapp.core.model.VideoId +import io.github.dewfallapp.core.playback.PlaybackConnection +import io.github.dewfallapp.feature.player.logic.miniPlayerContent + +/** The progress line along the mini player's top edge, as the frames draw it. */ +private val ProgressLineHeight = 2.dp + +/** The smallest touch target, which the title's tap area keeps at any font size. */ +private val MinTouchTarget = 48.dp + +/** + * Hands the mini player the app's PlaybackConnection. A composable can't take an injected + * constructor, and the public composable takes only plain values and actions. + */ +@EntryPoint +@InstallIn(SingletonComponent::class) +internal interface MiniPlayerEntryPoint { + fun playbackConnection(): PlaybackConnection +} + +/** + * The mini player, after the "Mini player on the inbox" frames: the video that plays, while no + * video screen shows. `:app` places it at the bottom of the screen. It draws nothing while the + * player has no video. Tapping its title calls [onOpenVideo] with the video, and its play, pause + * and close go straight to the player, as ADR 0002's note of November 21, 2026 allows. It reads the + * player through media3-ui-compose's state holders, never through screen state. + */ +@Composable +fun MiniPlayer(onOpenVideo: (VideoId) -> Unit, modifier: Modifier = Modifier) { + val context = LocalContext.current.applicationContext + val connection = + remember(context) { + EntryPointAccessors.fromApplication(context, MiniPlayerEntryPoint::class.java) + .playbackConnection() + } + val player by connection.player.collectAsStateWithLifecycle() + player?.let { MiniPlayerFor(it, connection, onOpenVideo, modifier) } +} + +/** The mini player for the connected [player], or nothing while it has no item. */ +@Composable +private fun MiniPlayerFor( + player: Player, + connection: PlaybackConnection, + onOpenVideo: (VideoId) -> Unit, + modifier: Modifier = Modifier, +) { + val item = rememberCurrentMediaItemState(player) + val content = + miniPlayerContent( + currentItemId = item.mediaItem?.mediaId, + title = item.mediaMetadata.title, + channelName = item.mediaMetadata.artist, + live = item.isLive, + ) ?: return + val playPause = rememberPlayPauseButtonState(player) + val status = rememberPlaybackStatus(player) + var ticks by remember { mutableIntStateOf(1) } + val progress = rememberProgressStateWithTickCount(player, ticks) + LaunchedEffect(progress, ticks) { progress.updateTotalTickCount(ticks) } + MiniPlayerBar( + title = content.title ?: stringResource(R.string.mini_player_now_playing), + channelName = content.channelName, + progress = if (content.showsProgress) ({ progress.currentPositionProgress }) else null, + showPlay = playPause.showPlay, + ended = status.ended, + playEnabled = playPause.isEnabled, + onPlayPause = playPause::onClick, + onOpen = { connection.videoOf(content.playbackId)?.let(onOpenVideo) }, + onClose = { connection.stop(content.playbackId) }, + modifier = modifier.onSizeChanged { ticks = it.width.coerceAtLeast(1) }, + ) +} + +/** + * The mini player's bar, with plain values, for the previews and screenshot tests: a line along the + * top that [progress] fills, or none for a live stream, then the [title] and [channelName], which + * [onOpen] opens, the play and pause button, and the close button. Its background reaches under the + * navigation bar, and its content stays clear of the system bars and the display cutout, in a + * column of readable width. + */ +@Composable +internal fun MiniPlayerBar( + title: String, + channelName: String?, + progress: (() -> Float)?, + showPlay: Boolean, + ended: Boolean, + playEnabled: Boolean, + onPlayPause: () -> Unit, + onOpen: () -> Unit, + onClose: () -> Unit, + modifier: Modifier = Modifier, +) { + // No Surface sits under the bar in :app, so its text takes onSurface, as the role pair asks. + CompositionLocalProvider(LocalContentColor provides MaterialTheme.colorScheme.onSurface) { + Column( + modifier = + modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surfaceContainerHigh), + ) { + if (progress != null) { + ProgressLine(progress) + } else { + Spacer(Modifier.height(ProgressLineHeight)) + } + Box( + modifier = + Modifier.fillMaxWidth() + .windowInsetsPadding( + WindowInsets.systemBars + .union(WindowInsets.displayCutout) + .only(WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom), + ), + contentAlignment = Alignment.TopCenter, + ) { + MiniPlayerRow( + title = title, + channelName = channelName, + showPlay = showPlay, + ended = ended, + playEnabled = playEnabled, + onPlayPause = onPlayPause, + onOpen = onOpen, + onClose = onClose, + ) + } + } + } +} + +/** The title and channel name, which [onOpen] opens, the play and pause button and the close. */ +@Composable +private fun MiniPlayerRow( + title: String, + channelName: String?, + showPlay: Boolean, + ended: Boolean, + playEnabled: Boolean, + onPlayPause: () -> Unit, + onOpen: () -> Unit, + onClose: () -> Unit, +) { + Row( + modifier = + Modifier.widthIn(max = ReadableWidth) + .fillMaxWidth() + .padding( + start = DewfallSpacing.md, + end = DewfallSpacing.xs, + top = DewfallSpacing.sm, + bottom = DewfallSpacing.sm, + ), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(DewfallSpacing.sm), + ) { + Column( + modifier = + Modifier.weight(1f) + .heightIn(min = MinTouchTarget) + .clickable( + onClickLabel = stringResource(R.string.mini_player_open), + onClick = onOpen, + ), + verticalArrangement = Arrangement.Center, + ) { + Text(text = title, style = MaterialTheme.typography.titleMedium) + if (channelName != null) { + Text( + text = channelName, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + PlayPauseButton( + showPlay = showPlay, + ended = ended, + enabled = playEnabled, + onClick = onPlayPause, + ) + IconButton(onClick = onClose) { + Icon( + painter = painterResource(DesignR.drawable.ic_close), + contentDescription = stringResource(R.string.mini_player_close), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } +} + +/** + * The line that shows how much has played: `primary` on `surfaceContainerHighest`. It reads + * [progress] while drawing, so its ticks redraw only the line. Screen readers skip it. + */ +@Composable +private fun ProgressLine(progress: () -> Float) { + val track = MaterialTheme.colorScheme.surfaceContainerHighest + val indicator = MaterialTheme.colorScheme.primary + Spacer( + modifier = + Modifier.fillMaxWidth() + .height(ProgressLineHeight) + .clearAndSetSemantics {} + .drawBehind { + drawRect(track) + val width = size.width * progress().coerceIn(0f, 1f) + // It fills from the start edge, as the seek bar does in either direction. + val left = + if (layoutDirection == LayoutDirection.Rtl) size.width - width else 0f + drawRect(indicator, topLeft = Offset(left, 0f), size = Size(width, size.height)) + }, + ) +} diff --git a/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/MiniPlayerPreviews.kt b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/MiniPlayerPreviews.kt new file mode 100644 index 0000000..327050b --- /dev/null +++ b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/MiniPlayerPreviews.kt @@ -0,0 +1,75 @@ +@file:OptIn(UnstableApi::class) + +package io.github.dewfallapp.feature.player.ui + +import androidx.annotation.OptIn +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.media3.common.util.UnstableApi +import io.github.dewfallapp.core.designsystem.theme.DewfallTheme + +// Previews of the mini player, with the made-up video and player in +// PlayerPreviewParts.kt. The @PreviewTest wrappers in src/screenshotTest carry their @Preview +// annotations and render them as screenshot tests. They use Dewfall's own palette, except the +// dynamic color previews, whose wrappers name a fixed wallpaper. See +// docs/testing.md#screenshot-tests. + +/** How much of the made-up video has played, 18:24 of 1:14:02, as in the frames. */ +private const val PREVIEW_PROGRESS = 0.249f + +/** + * The mini player's bar at the bottom of an empty screen, with no Surface, as in :app, so the bar's + * own content color shows. + */ +@Composable +private fun MiniPreview( + title: String = previewPage.title, + channelName: String? = previewPage.channelName, + showPlay: Boolean = false, + dynamicColor: Boolean = false, +) { + DewfallTheme(dynamicColor = dynamicColor) { + Box( + Modifier.fillMaxSize().background(MaterialTheme.colorScheme.surface), + contentAlignment = Alignment.BottomCenter, + ) { + MiniPlayerBar( + title = title, + channelName = channelName, + progress = { PREVIEW_PROGRESS }, + showPlay = showPlay, + ended = false, + playEnabled = true, + onPlayPause = {}, + onOpen = {}, + onClose = {}, + ) + } + } +} + +@Composable +internal fun MiniPlayerPlayingPreview() { + MiniPreview() +} + +@Composable +internal fun MiniPlayerPlayingDynamicPreview() { + MiniPreview(dynamicColor = true) +} + +@Composable +internal fun MiniPlayerPausedPreview() { + MiniPreview(showPlay = true) +} + +@Composable +internal fun MiniPlayerNowPlayingPreview() { + MiniPreview(title = stringResource(R.string.mini_player_now_playing), channelName = null) +} diff --git a/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlaybackStatus.kt b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlaybackStatus.kt index 32f0f16..c9732f1 100644 --- a/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlaybackStatus.kt +++ b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlaybackStatus.kt @@ -15,9 +15,10 @@ import androidx.media3.common.listen import androidx.media3.common.util.UnstableApi /** - * What the video area reads from the player beyond its buttons and times: whether it is loading, - * whether the item is live, and whether it has ended. It updates on the player's events, never in - * screen state. It lives here until #44 needs to share it, so :core:playback has no Compose. + * What the video area and fullscreen read from the player beyond their buttons and times: whether + * it is loading, whether the item is live, whether it has ended, and whether it is playing. It + * updates on the player's events, never in screen state. The mini player and fullscreen live in + * this module too, so it stays here, and :core:playback has no Compose. */ @Stable internal class PlaybackStatus { @@ -33,10 +34,18 @@ internal class PlaybackStatus { var ended by mutableStateOf(false) private set + /** + * The player is playing: play is on, it has data, and nothing holds it back. It is false while + * it waits for data, has ended or failed. + */ + var playing by mutableStateOf(false) + private set + fun update(player: Player) { loading = player.playbackState == Player.STATE_BUFFERING live = player.isCurrentMediaItemLive ended = player.playbackState == Player.STATE_ENDED + playing = player.isPlaying } } diff --git a/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerPreviewParts.kt b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerPreviewParts.kt index 69c6369..4b3247f 100644 --- a/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerPreviewParts.kt +++ b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerPreviewParts.kt @@ -109,9 +109,15 @@ internal fun PlayerScreenPreview( now = previewNow, zone = previewZone, onIntent = {}, - onClose = {}, + onMinimize = {}, videoArea = { modifier -> - VideoArea(content = content, onPlay = {}, onTryAgain = {}, modifier = modifier) + VideoArea( + content = content, + onPlay = {}, + onTryAgain = {}, + onFullscreen = {}, + modifier = modifier, + ) }, ) } diff --git a/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerRoute.kt b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerRoute.kt index 3c97281..f28a05a 100644 --- a/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerRoute.kt +++ b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerRoute.kt @@ -1,8 +1,7 @@ package io.github.dewfallapp.feature.player.ui -import android.app.Activity -import android.content.Context -import android.content.ContextWrapper +import androidx.activity.compose.BackHandler +import androidx.activity.compose.LocalActivity import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect @@ -14,7 +13,6 @@ import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier -import androidx.compose.ui.platform.LocalContext import androidx.lifecycle.HasDefaultViewModelProviderFactory import androidx.lifecycle.Lifecycle import androidx.lifecycle.compose.LifecycleEventEffect @@ -27,33 +25,40 @@ import androidx.media3.common.Player import dagger.hilt.android.lifecycle.withCreationCallback import io.github.dewfallapp.core.model.PlaybackFailure import io.github.dewfallapp.core.model.VideoId +import io.github.dewfallapp.feature.player.logic.DetailsArea import io.github.dewfallapp.feature.player.logic.PlayerIntent +import io.github.dewfallapp.feature.player.logic.PlayerState import io.github.dewfallapp.feature.player.logic.StartAction -import io.github.dewfallapp.feature.player.logic.pausesOnLeave import io.github.dewfallapp.feature.player.logic.startAction import io.github.dewfallapp.feature.player.logic.videoAreaFailure import java.time.ZoneId import kotlin.time.Clock /** - * The video screen for [videoId], with its ViewModel and its playback. [onClose] runs when the user - * taps the close button. The app's navigation gives each screen its own ViewModelStoreOwner, so - * each video gets its own ViewModel. See openspec/specs/player/spec.md. + * The video screen for [videoId], with its ViewModel and its playback. [onMinimize] runs when the + * user taps the minimize button. The app's navigation gives each screen its own + * ViewModelStoreOwner, so each video gets its own ViewModel. See openspec/specs/player/spec.md. * - * Playback starts the first time the screen opens. Leaving the app keeps it playing in the - * background, unless it hasn't played yet, and closing the screen stops it, through the ViewModel. - * When the screen comes back after the system ended the process or stopped the player, it waits at - * the saved position for the user to press play. + * Playback starts the first time the screen opens, unless the player already plays this video, + * which goes on as it is. Leaving the app keeps it playing in the background, unless it hasn't + * played yet, as the connection decides, and minimizing leaves it to the mini player. When the + * screen comes back after the system ended the process or stopped the player, it waits at the saved + * position for the user to press play. The fullscreen button shows the fullscreen player, and the + * back gesture leaves it. */ @Composable -fun PlayerRoute(videoId: VideoId, onClose: () -> Unit, modifier: Modifier = Modifier) { - PlayerContent(onClose = onClose, viewModel = playerViewModel(videoId), modifier = modifier) +fun PlayerRoute(videoId: VideoId, onMinimize: () -> Unit, modifier: Modifier = Modifier) { + PlayerContent( + onMinimize = onMinimize, + viewModel = playerViewModel(videoId), + modifier = modifier, + ) } /** Connects the screen to its ViewModel and to the player. */ @Composable internal fun PlayerContent( - onClose: () -> Unit, + onMinimize: () -> Unit, viewModel: PlayerViewModel, modifier: Modifier = Modifier, ) { @@ -65,10 +70,8 @@ internal fun PlayerContent( var started by rememberSaveable { mutableStateOf(false) } var playbackId by rememberSaveable { mutableStateOf(null) } var savedPositionMs by rememberSaveable { mutableLongStateOf(C.TIME_UNSET) } - // The playback ID that has played, so leaving the app keeps it playing. - var playedId by rememberSaveable { mutableStateOf(null) } // Read again when the player connects or goes, because the session's end clears the IDs. - val known = remember(player, playbackId) { playbackId?.let(playback::isKnown) == true } + val known = remember(player, playbackId) { playbackId?.let(playback::videoOf) != null } // Each start keeps its playback ID and the position it starts from, so a retry that fails // before the player has an item still goes on from that position. @@ -82,30 +85,112 @@ internal fun PlayerContent( recordStart(viewModel.startPlayback(positionMs), positionMs) } - LaunchedEffect(Unit) { - if (startAction(started, known) == StartAction.PLAY) start(C.TIME_UNSET) - } - LeavingRules( - player = player, + StartOnOpen( + started = started, + known = known, playbackId = playbackId, - playedId = playedId, - onPlaying = { playedId = it }, - onSave = { savedPositionMs = it }, - onPause = playback::pause, + playbackOfThisVideo = viewModel::playbackOfThisVideo, + onPlay = { start(C.TIME_UNSET) }, + onGoOn = { id -> recordStart(id, C.TIME_UNSET) }, + onFollow = viewModel::follow, ) + FollowPlayback(player, playbackId, onSave = { savedPositionMs = it }) + SaveOnStop(player, playbackId, onSave = { savedPositionMs = it }) + // Called every time, with enabled, as BackHandler's reference asks, so the order of the back + // handlers stays the same. The entry composes after NavDisplay's handler, so this one runs. + BackHandler(enabled = state.fullscreen) { viewModel.dispatch(PlayerIntent.ExitFullscreen) } // Try again, or play after the session was gone, goes on from the last position. val retryPositionMs = { player?.takeIf { it.currentMediaItem?.mediaId == playbackId }?.let(::resumePosition) ?: savedPositionMs } - - val content = - videoAreaContent( - failure = videoAreaFailure(state.details, failure), - waiting = started && !known, - savedPositionMs = savedPositionMs, - player = player, + val waiting = started && !known + if (state.fullscreen) { + FullscreenPlayer( + // Fullscreen has no details' message to share a failure with, so it shows the player's. + content = videoAreaContent(failure, waiting, savedPositionMs, player), + page = (state.details as? DetailsArea.Shown)?.page, + onPlay = { start(retryPositionMs()) }, + onTryAgain = { start(retryPositionMs()) }, + onExit = { viewModel.dispatch(PlayerIntent.ExitFullscreen) }, + modifier = modifier, + ) + } else { + VideoScreen( + state = state, + content = + videoAreaContent( + videoAreaFailure(state.details, failure), + waiting, + savedPositionMs, + player, + ), + onTryAgainDetails = { + val positionMs = retryPositionMs() + viewModel.tryAgainDetails(failure, positionMs)?.let { id -> + recordStart(id, positionMs) + } + }, + onPlay = { start(retryPositionMs()) }, + onIntent = viewModel::dispatch, + onMinimize = onMinimize, + modifier = modifier, ) + } +} + +/** + * Starts playback the first time the screen opens, or goes on with the playback of this screen's + * video that [playbackOfThisVideo] finds, as [startAction] decides from whether playback [started], + * whether its [playbackId] is still [known], and that playback. [onPlay] starts it, and [onGoOn] + * keeps the playback it goes on with. [onFollow] tells the ViewModel which playback is its own: the + * one it goes on with, or its own after it was made again, as after "Don't keep activities". + */ +@Composable +private fun StartOnOpen( + started: Boolean, + known: Boolean, + playbackId: String?, + playbackOfThisVideo: () -> String?, + onPlay: () -> Unit, + onGoOn: (String) -> Unit, + onFollow: (String) -> Unit, +) { + val find by rememberUpdatedState(playbackOfThisVideo) + val play by rememberUpdatedState(onPlay) + val goOn by rememberUpdatedState(onGoOn) + val follow by rememberUpdatedState(onFollow) + LaunchedEffect(Unit) { + val playing = find() + when (startAction(started, known, playsThisVideo = playing != null)) { + StartAction.PLAY -> play() + StartAction.GO_ON -> { + if (playing != null) { + goOn(playing) + follow(playing) + } + } + StartAction.NOTHING -> playbackId?.let(follow) + StartAction.WAIT_FOR_PLAY -> Unit + } + } +} + +/** + * The video screen with its video area showing [content]. [onTryAgainDetails] runs for the details' + * "Try again", [onPlay] for play while it waits and the playback's "Try again", and the fullscreen + * button and the other intents go to [onIntent]. + */ +@Composable +private fun VideoScreen( + state: PlayerState, + content: VideoAreaContent, + onTryAgainDetails: () -> Unit, + onPlay: () -> Unit, + onIntent: (PlayerIntent) -> Unit, + onMinimize: () -> Unit, + modifier: Modifier = Modifier, +) { // The clock is read once per answer, so the screen itself stays a function of what it gets. val now = remember(state.details) { Clock.System.now() } val zone = remember(state.details) { ZoneId.systemDefault() } @@ -114,22 +199,16 @@ internal fun PlayerContent( now = now, zone = zone, onIntent = { intent -> - if (intent == PlayerIntent.TryAgain) { - val positionMs = retryPositionMs() - viewModel.tryAgainDetails(failure, positionMs)?.let { id -> - recordStart(id, positionMs) - } - } else { - viewModel.dispatch(intent) - } + if (intent == PlayerIntent.TryAgain) onTryAgainDetails() else onIntent(intent) }, - onClose = onClose, + onMinimize = onMinimize, modifier = modifier, videoArea = { areaModifier -> VideoArea( content = content, - onPlay = { start(retryPositionMs()) }, - onTryAgain = { start(retryPositionMs()) }, + onPlay = onPlay, + onTryAgain = onPlay, + onFullscreen = { onIntent(PlayerIntent.EnterFullscreen) }, modifier = areaModifier, ) }, @@ -137,50 +216,18 @@ internal fun PlayerContent( } /** - * What leaving the app does with this screen's playback, [playbackId]: [FollowPlayback] keeps the - * position and which ID has played, [playedId], up to date, and [SaveAndPauseOnStop] acts when the - * screen stops. - */ -@Composable -private fun LeavingRules( - player: Player?, - playbackId: String?, - playedId: String?, - onPlaying: (String) -> Unit, - onSave: (Long) -> Unit, - onPause: (String) -> Unit, -) { - FollowPlayback(player, playbackId, onPlaying = onPlaying, onSave = onSave) - SaveAndPauseOnStop( - player, - playbackId, - played = playbackId != null && playedId == playbackId, - onSave = onSave, - onPause = onPause, - ) -} - -/** - * While the screen exists, even with the app in the background, tells [onPlaying] the playback ID - * once its item plays, and hands [onSave] the position whenever this screen's item pauses or ends. - * So when Android stops a player that paused in the background, the screen waits at the position - * where it paused. Like ON_STOP, it never saves from an idle player, whose position after a failure - * may not be where the video was. + * While the screen exists, even with the app in the background, hands [onSave] the position + * whenever this screen's item pauses or ends. So when Android stops a player that paused in the + * background, the screen waits at the position where it paused. Like ON_STOP, it never saves from + * an idle player, whose position after a failure may not be where the video was. */ @Composable -private fun FollowPlayback( - player: Player?, - playbackId: String?, - onPlaying: (String) -> Unit, - onSave: (Long) -> Unit, -) { - val played by rememberUpdatedState(onPlaying) +private fun FollowPlayback(player: Player?, playbackId: String?, onSave: (Long) -> Unit) { val save by rememberUpdatedState(onSave) DisposableEffect(player, playbackId) { if (player == null || playbackId == null) return@DisposableEffect onDispose {} fun follow() { if (player.currentMediaItem?.mediaId != playbackId) return - if (player.isPlaying) played(playbackId) val state = player.playbackState if ( state != Player.STATE_IDLE && (!player.playWhenReady || state == Player.STATE_ENDED) @@ -202,30 +249,20 @@ private fun FollowPlayback( /** * When the screen stops, unless the activity is only changing configurations, hands [onSave] the - * position to keep in the saved state, and [onPause] this screen's playback ID if it hasn't - * [played] yet, as [pausesOnLeave] decides. A video that has played keeps playing in the - * background. The connection pauses a start that still waits for the player too. An idle player - * failed or never loaded, so its position may not be where the video was: the position its playback - * started from stays saved instead. + * position to keep in the saved state. An idle player failed or never loaded, so its position may + * not be where the video was: the position its playback started from stays saved instead. Whether a + * playback that hasn't played pauses is the connection's rule, which MainActivity's onStop runs. */ @Composable -private fun SaveAndPauseOnStop( - player: Player?, - playbackId: String?, - played: Boolean, - onSave: (Long) -> Unit, - onPause: (String) -> Unit, -) { - val activity = LocalContext.current.findActivity() +private fun SaveOnStop(player: Player?, playbackId: String?, onSave: (Long) -> Unit) { + val activity = LocalActivity.current val save by rememberUpdatedState(onSave) - val pause by rememberUpdatedState(onPause) LifecycleEventEffect(Lifecycle.Event.ON_STOP) { val changing = activity?.isChangingConfigurations == true val current = player?.takeIf { it.currentMediaItem?.mediaId == playbackId } if (!changing && current != null && current.playbackState != Player.STATE_IDLE) { save(resumePosition(current)) } - if (playbackId != null && pausesOnLeave(changing, played)) pause(playbackId) } } @@ -249,14 +286,6 @@ private fun videoAreaContent( private fun resumePosition(player: Player): Long = if (player.isCurrentMediaItemLive) C.TIME_UNSET else player.currentPosition -/** The activity that [this] context belongs to, if any. */ -private tailrec fun Context.findActivity(): Activity? = - when (this) { - is Activity -> this - is ContextWrapper -> baseContext.findActivity() - else -> null - } - /** * The ViewModel for [videoId], from the current ViewModelStoreOwner's default factory, which is * Hilt's. Hilt's creation callback hands the ID to the ViewModel's assisted factory. diff --git a/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerScreen.kt b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerScreen.kt index 516fb1e..fc9cdf5 100644 --- a/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerScreen.kt +++ b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerScreen.kt @@ -57,9 +57,9 @@ import kotlin.time.Instant private val EmblemSize = 36.dp /** - * The video screen: a close button, then [videoArea], then the video's details, or loading, or a + * The video screen: a minimize button, then [videoArea], then the video's details, or loading, or a * failure. It is stateless: it shows [state], with the time ago counted from [now] in [zone], and - * reports what the user does through [onIntent] and [onClose]. The video area reads the player + * reports what the user does through [onIntent] and [onMinimize]. The video area reads the player * itself, so playback state never enters [state]. * * Its background fills the window behind the system bars. Its content sits inside the safe drawing @@ -72,7 +72,7 @@ internal fun PlayerScreen( now: Instant, zone: ZoneId, onIntent: (PlayerIntent) -> Unit, - onClose: () -> Unit, + onMinimize: () -> Unit, modifier: Modifier = Modifier, videoArea: @Composable (Modifier) -> Unit = {}, ) { @@ -83,12 +83,12 @@ internal fun PlayerScreen( ) { Column(modifier = Modifier.widthIn(max = ReadableWidth).fillMaxWidth()) { IconButton( - onClick = onClose, + onClick = onMinimize, modifier = Modifier.padding(horizontal = DewfallSpacing.xs), ) { Icon( painter = painterResource(DesignR.drawable.ic_keyboard_arrow_down), - contentDescription = stringResource(R.string.player_close), + contentDescription = stringResource(R.string.player_minimize), tint = MaterialTheme.colorScheme.onSurfaceVariant, ) } diff --git a/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerViewModel.kt b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerViewModel.kt index 5a4511d..69b89f7 100644 --- a/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerViewModel.kt +++ b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/PlayerViewModel.kt @@ -1,5 +1,6 @@ package io.github.dewfallapp.feature.player.ui +import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.viewModelScope import dagger.assisted.Assisted import dagger.assisted.AssistedFactory @@ -9,6 +10,7 @@ import io.github.dewfallapp.core.data.video.VideoDetailsRepository import io.github.dewfallapp.core.model.PlaybackFailure import io.github.dewfallapp.core.model.VideoId import io.github.dewfallapp.core.mvi.MviViewModel +import io.github.dewfallapp.core.playback.PictureHold import io.github.dewfallapp.core.playback.PlaybackConnection import io.github.dewfallapp.feature.player.logic.DetailsArea import io.github.dewfallapp.feature.player.logic.PlayerIntent @@ -25,15 +27,31 @@ import kotlinx.coroutines.launch */ internal class PlayerArgs(val videoId: VideoId) +/** The key of whether the screen shows fullscreen in the ViewModel's saved state. */ +private const val FULLSCREEN_KEY = "fullscreen" + +/** + * The playback ID of the player's [currentItemId] when it plays [videoId], as [videoOf] says, so a + * screen that opens goes on with it, or null. + */ +internal fun playbackOfVideo( + currentItemId: String?, + videoId: VideoId, + videoOf: (String) -> VideoId?, +): String? = currentItemId?.takeIf { videoOf(it) == videoId } + /** * Loads the video screen's details, one request at a time. It sends Load once when it is created, * and a request starts only when the reducer made a new one, so "Try again" with nothing to try * sends nothing. Leaving the screen cancels the running request. * * It takes no dispatcher, because the repository's call is main-safe. It also holds the screen's - * PlaybackConnection and the playback ID of its latest start. It gives that playback the video's - * title and channel name for the media notification once the details show, and stops it when it is - * cleared. Player commands skip intents, as ADR 0002's note says. + * PlaybackConnection and the playback ID of its latest start, or of the playback it goes on with. + * It gives that playback the video's title and channel name for the media notification once the + * details show, and releases it when it is cleared, so a minimized video plays on in the mini + * player. It holds the picture while it exists. It keeps fullscreen in its saved state, so the + * screen comes back in fullscreen after the process ends. Player commands skip intents, as ADR + * 0002's note says. */ @HiltViewModel(assistedFactory = PlayerViewModel.Factory::class) internal class PlayerViewModel @@ -43,7 +61,12 @@ constructor( private val repository: VideoDetailsRepository, /** The player, which the route reads and sends play, pause and seek to, never through state. */ internal val playback: PlaybackConnection, -) : MviViewModel(PlayerState(), PlayerReducer) { + private val savedState: SavedStateHandle, +) : + MviViewModel( + PlayerState(fullscreen = savedState[FULLSCREEN_KEY] ?: false), + PlayerReducer, + ) { /** The running request. Only the main thread touches it. */ private var detailsJob: Job? = null @@ -54,6 +77,9 @@ constructor( /** The playback ID of this screen's latest start. Only the main thread touches it. */ private var playbackId: String? = null + /** Shows the picture while this screen exists, even while it turns to landscape. */ + private val picture: PictureHold = playback.holdPicture() + init { dispatch(PlayerIntent.Load) } @@ -63,6 +89,8 @@ constructor( PlayerIntent.Load, PlayerIntent.TryAgain -> startNewRequest() is PlayerIntent.DetailsFinished -> describePlayback() + PlayerIntent.EnterFullscreen, + PlayerIntent.ExitFullscreen -> savedState[FULLSCREEN_KEY] = state.value.fullscreen } } @@ -90,6 +118,27 @@ constructor( return id } + /** + * The playback ID of the player's item if it plays this screen's video, such as one that the + * mini player shows, or null. + */ + internal fun playbackOfThisVideo(): String? = + playbackOfVideo( + playback.player.value?.currentMediaItem?.mediaId, + args.videoId, + playback::videoOf, + ) + + /** + * Goes on with [id], a playback that this ViewModel didn't start: one that already played this + * video, or this screen's own after the ViewModel was made again. It describes and releases it + * as its own. + */ + internal fun follow(id: String) { + playbackId = id + describePlayback() + } + /** * Gives the latest playback the title and channel name that the media notification shows, once * the details show. The reducer has already run, so the state holds this intent's answer. @@ -112,11 +161,13 @@ constructor( } /** - * Stops this screen's playback, unless another video started meanwhile. Navigation 3 clears the - * ViewModel only after the screen's exit animation. + * Releases this screen's playback, which plays on in the mini player while it is the player's + * item, and lets go of the picture. Navigation 3 clears the ViewModel only after the screen's + * exit animation. */ override fun onCleared() { - playbackId?.let(playback::stop) + playbackId?.let(playback::release) + picture.release() } /** Makes the ViewModel for the video in [PlayerArgs]. Hilt implements it. */ diff --git a/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/VideoArea.kt b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/VideoArea.kt index 6357efe..e742c63 100644 --- a/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/VideoArea.kt +++ b/feature/player-ui/src/main/kotlin/io/github/dewfallapp/feature/player/ui/VideoArea.kt @@ -8,6 +8,7 @@ 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.Spacer import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth @@ -15,6 +16,7 @@ import androidx.compose.foundation.layout.heightIn import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.FilledIconButton import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Slider import androidx.compose.material3.Text @@ -91,13 +93,15 @@ internal sealed interface VideoAreaContent { * * It reads the player through media3-ui-compose's state holders and [rememberPlaybackStatus], at * the rate the visible controls need, and sends play, pause and seek straight to it. [onPlay] runs - * when the user presses play while it waits, and [onTryAgain] for the failure's "Try again". + * when the user presses play while it waits, [onTryAgain] for the failure's "Try again", and + * [onFullscreen] for the fullscreen button, which shows while the player is connected. */ @Composable internal fun VideoArea( content: VideoAreaContent, onPlay: () -> Unit, onTryAgain: () -> Unit, + onFullscreen: () -> Unit, modifier: Modifier = Modifier, ) { Column( @@ -116,7 +120,7 @@ internal fun VideoArea( Picture(player = null, playing = false, loading = true) IdleControls(positionMs = null, onPlay = null) } else { - PlayerArea(player) + PlayerArea(player, onFullscreen) } } } @@ -124,7 +128,7 @@ internal fun VideoArea( } @Composable -private fun PlayerArea(player: Player) { +private fun PlayerArea(player: Player, onFullscreen: () -> Unit) { val playPause = rememberPlayPauseButtonState(player) val status = rememberPlaybackStatus(player) Column(verticalArrangement = Arrangement.spacedBy(DewfallSpacing.sm)) { @@ -144,6 +148,8 @@ private fun PlayerArea(player: Player) { text = stringResource(R.string.player_video_live), style = MaterialTheme.typography.titleSmall, ) + Spacer(Modifier.weight(1f)) + FullscreenButton(onFullscreen) } } else { SeekBar(player) @@ -158,6 +164,8 @@ private fun PlayerArea(player: Player) { onClick = playPause::onClick, ) Times(player) + Spacer(Modifier.weight(1f)) + FullscreenButton(onFullscreen) } } } @@ -218,7 +226,7 @@ private fun Modifier.cornersOver(shape: Shape, color: Color): Modifier = drawWit * letting go moves playback there. */ @Composable -private fun SeekBar(player: Player) { +internal fun SeekBar(player: Player, modifier: Modifier = Modifier) { var ticks by remember { mutableIntStateOf(1) } val progress = rememberProgressStateWithTickCount(player, ticks) LaunchedEffect(progress, ticks) { progress.updateTotalTickCount(ticks) } @@ -233,7 +241,8 @@ private fun SeekBar(player: Player) { }, enabled = progress.changingProgressEnabled, modifier = - Modifier.fillMaxWidth() + modifier + .fillMaxWidth() .onSizeChanged { ticks = it.width.coerceAtLeast(1) } .semantics { contentDescription = description }, ) @@ -241,13 +250,13 @@ private fun SeekBar(player: Player) { /** The position and the length, such as "18:24 / 1:14:02", ticking once a second. */ @Composable -private fun Times(player: Player) { +internal fun Times(player: Player) { val progress = rememberProgressStateWithTickInterval(player, TIMES_TICK_MS) TimesText(positionMs = progress.currentPositionMs, durationMs = progress.durationMs) } @Composable -private fun TimesText(positionMs: Long, durationMs: Long?) { +internal fun TimesText(positionMs: Long, durationMs: Long?) { val text = if (durationMs == null || durationMs == C.TIME_UNSET) { clockText(positionMs) @@ -296,7 +305,7 @@ private fun IdleControls(positionMs: Long?, onPlay: (() -> Unit)?) { * it offers to play it again from the start. */ @Composable -private fun PlayPauseButton( +internal fun PlayPauseButton( showPlay: Boolean, ended: Boolean, enabled: Boolean, @@ -319,7 +328,11 @@ private fun PlayPauseButton( * trying again can help. */ @Composable -private fun PlaybackFailureBanner(failure: PlaybackFailure, onTryAgain: () -> Unit) { +internal fun PlaybackFailureBanner( + failure: PlaybackFailure, + onTryAgain: () -> Unit, + modifier: Modifier = Modifier, +) { val offers = failure.offersTryAgain Banner( message = stringResource(playbackFailureText(failure)), @@ -328,5 +341,18 @@ private fun PlaybackFailureBanner(failure: PlaybackFailure, onTryAgain: () -> Un glyphTint = MaterialTheme.colorScheme.error, actionLabel = if (offers) stringResource(R.string.player_try_again) else null, onAction = if (offers) onTryAgain else null, + modifier = modifier, ) } + +/** The fullscreen button, as the "Player" frames show it at the end of the play and pause row. */ +@Composable +private fun FullscreenButton(onClick: () -> Unit) { + IconButton(onClick = onClick) { + Icon( + painter = painterResource(DesignR.drawable.ic_fullscreen), + contentDescription = stringResource(R.string.player_fullscreen), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } +} diff --git a/feature/player-ui/src/main/res/values/strings.xml b/feature/player-ui/src/main/res/values/strings.xml index 4db0937..de662cc 100644 --- a/feature/player-ui/src/main/res/values/strings.xml +++ b/feature/player-ui/src/main/res/values/strings.xml @@ -1,7 +1,7 @@ - - Close video + + Minimize player Loading video @@ -60,4 +60,19 @@ Couldn\'t play the video This video can\'t play on this phone. This video stopped playing. + + Full screen + + + Exit full screen + + Show controls + Hide controls + + + + Now playing + + Open video + Close player diff --git a/feature/player-ui/src/screenshotTest/kotlin/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshots.kt b/feature/player-ui/src/screenshotTest/kotlin/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshots.kt new file mode 100644 index 0000000..6d04a76 --- /dev/null +++ b/feature/player-ui/src/screenshotTest/kotlin/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshots.kt @@ -0,0 +1,101 @@ +package io.github.dewfallapp.feature.player.ui + +import android.content.res.Configuration +import androidx.compose.runtime.Composable +import androidx.compose.ui.tooling.preview.Preview +import androidx.compose.ui.tooling.preview.Wallpapers +import com.android.tools.screenshot.PreviewTest + +@PreviewTest +@Preview(name = "Light", heightDp = 400) +@Preview( + name = "Dark", + heightDp = 400, + uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, +) +@Preview(name = "LargeFont", heightDp = 400, fontScale = 2f) +@Preview(name = "Tablet", widthDp = 1280, heightDp = 800) +@Composable +private fun MiniPlayerPlayingScreenshot() = MiniPlayerPlayingPreview() + +@PreviewTest +@Preview(name = "DynamicLight", heightDp = 400, wallpaper = Wallpapers.BLUE_DOMINATED_EXAMPLE) +@Preview( + name = "DynamicDark", + heightDp = 400, + uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, + wallpaper = Wallpapers.BLUE_DOMINATED_EXAMPLE, +) +@Composable +private fun MiniPlayerPlayingDynamicScreenshot() = MiniPlayerPlayingDynamicPreview() + +@PreviewTest +@Preview(name = "Light", heightDp = 400) +@Preview( + name = "Dark", + heightDp = 400, + uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, +) +@Composable +private fun MiniPlayerPausedScreenshot() = MiniPlayerPausedPreview() + +@PreviewTest +@Preview(name = "Light", heightDp = 400) +@Preview( + name = "Dark", + heightDp = 400, + uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, +) +@Composable +private fun MiniPlayerNowPlayingScreenshot() = MiniPlayerNowPlayingPreview() + +@PreviewTest +@Preview(name = "Light", widthDp = 915, heightDp = 412) +@Preview( + name = "Dark", + widthDp = 915, + heightDp = 412, + uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, +) +@Preview(name = "LargeFont", widthDp = 915, heightDp = 412, fontScale = 2f) +@Preview(name = "TabletPortrait", widthDp = 800, heightDp = 1280) +@Composable +private fun FullscreenPausedScreenshot() = FullscreenPausedPreview() + +@PreviewTest +@Preview( + name = "DynamicLight", + widthDp = 915, + heightDp = 412, + wallpaper = Wallpapers.BLUE_DOMINATED_EXAMPLE, +) +@Preview( + name = "DynamicDark", + widthDp = 915, + heightDp = 412, + uiMode = Configuration.UI_MODE_NIGHT_YES or Configuration.UI_MODE_TYPE_NORMAL, + wallpaper = Wallpapers.BLUE_DOMINATED_EXAMPLE, +) +@Composable +private fun FullscreenPausedDynamicScreenshot() = FullscreenPausedDynamicPreview() + +@PreviewTest +@Preview(name = "Light", widthDp = 915, heightDp = 412) +@Composable +private fun FullscreenPlayingScreenshot() = FullscreenPlayingPreview() + +@PreviewTest +@Preview(name = "Light", widthDp = 915, heightDp = 412) +@Composable +private fun FullscreenLiveScreenshot() = FullscreenLivePreview() + +@PreviewTest +@Preview(name = "Light", widthDp = 915, heightDp = 412) +@Preview(name = "LargeFont", widthDp = 915, heightDp = 412, fontScale = 2f) +@Composable +private fun FullscreenFailureScreenshot() = FullscreenFailurePreview() + +@PreviewTest +@Preview(name = "Light", widthDp = 915, heightDp = 412) +@Composable +private fun FullscreenWaitingScreenshot() = FullscreenWaitingPreview() diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenFailureScreenshot_LargeFont_68246b84_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenFailureScreenshot_LargeFont_68246b84_0.png new file mode 100644 index 0000000..d816b58 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenFailureScreenshot_LargeFont_68246b84_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenFailureScreenshot_Light_2e0079bc_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenFailureScreenshot_Light_2e0079bc_0.png new file mode 100644 index 0000000..aa46bf1 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenFailureScreenshot_Light_2e0079bc_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenLiveScreenshot_Light_2e0079bc_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenLiveScreenshot_Light_2e0079bc_0.png new file mode 100644 index 0000000..3307ce8 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenLiveScreenshot_Light_2e0079bc_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenPausedDynamicScreenshot_DynamicDark_330cc0e7_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenPausedDynamicScreenshot_DynamicDark_330cc0e7_0.png new file mode 100644 index 0000000..5a644fc Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenPausedDynamicScreenshot_DynamicDark_330cc0e7_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenPausedDynamicScreenshot_DynamicLight_0bdea55b_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenPausedDynamicScreenshot_DynamicLight_0bdea55b_0.png new file mode 100644 index 0000000..18379da Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenPausedDynamicScreenshot_DynamicLight_0bdea55b_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenPausedScreenshot_Dark_007fb2d7_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenPausedScreenshot_Dark_007fb2d7_0.png new file mode 100644 index 0000000..a0305d9 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenPausedScreenshot_Dark_007fb2d7_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenPausedScreenshot_LargeFont_68246b84_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenPausedScreenshot_LargeFont_68246b84_0.png new file mode 100644 index 0000000..9ac4e8e Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenPausedScreenshot_LargeFont_68246b84_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenPausedScreenshot_Light_2e0079bc_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenPausedScreenshot_Light_2e0079bc_0.png new file mode 100644 index 0000000..a0305d9 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenPausedScreenshot_Light_2e0079bc_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenPausedScreenshot_TabletPortrait_0e2d2c13_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenPausedScreenshot_TabletPortrait_0e2d2c13_0.png new file mode 100644 index 0000000..cd9944e Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenPausedScreenshot_TabletPortrait_0e2d2c13_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenPlayingScreenshot_Light_2e0079bc_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenPlayingScreenshot_Light_2e0079bc_0.png new file mode 100644 index 0000000..0a4b260 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenPlayingScreenshot_Light_2e0079bc_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenWaitingScreenshot_Light_2e0079bc_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenWaitingScreenshot_Light_2e0079bc_0.png new file mode 100644 index 0000000..8e6e698 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/FullscreenWaitingScreenshot_Light_2e0079bc_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerNowPlayingScreenshot_Dark_4094ee31_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerNowPlayingScreenshot_Dark_4094ee31_0.png new file mode 100644 index 0000000..1e28b7b Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerNowPlayingScreenshot_Dark_4094ee31_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerNowPlayingScreenshot_Light_57f02e25_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerNowPlayingScreenshot_Light_57f02e25_0.png new file mode 100644 index 0000000..7ccd63b Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerNowPlayingScreenshot_Light_57f02e25_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPausedScreenshot_Dark_4094ee31_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPausedScreenshot_Dark_4094ee31_0.png new file mode 100644 index 0000000..bd6c1ae Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPausedScreenshot_Dark_4094ee31_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPausedScreenshot_Light_57f02e25_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPausedScreenshot_Light_57f02e25_0.png new file mode 100644 index 0000000..452e59b Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPausedScreenshot_Light_57f02e25_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPlayingDynamicScreenshot_DynamicDark_ef5a71c1_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPlayingDynamicScreenshot_DynamicDark_ef5a71c1_0.png new file mode 100644 index 0000000..26ed8ec Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPlayingDynamicScreenshot_DynamicDark_ef5a71c1_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPlayingDynamicScreenshot_DynamicLight_393fa0ca_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPlayingDynamicScreenshot_DynamicLight_393fa0ca_0.png new file mode 100644 index 0000000..3e2e9bc Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPlayingDynamicScreenshot_DynamicLight_393fa0ca_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPlayingScreenshot_Dark_4094ee31_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPlayingScreenshot_Dark_4094ee31_0.png new file mode 100644 index 0000000..c90abf5 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPlayingScreenshot_Dark_4094ee31_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPlayingScreenshot_LargeFont_f4e2011a_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPlayingScreenshot_LargeFont_f4e2011a_0.png new file mode 100644 index 0000000..bc17fb1 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPlayingScreenshot_LargeFont_f4e2011a_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPlayingScreenshot_Light_57f02e25_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPlayingScreenshot_Light_57f02e25_0.png new file mode 100644 index 0000000..e16c586 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPlayingScreenshot_Light_57f02e25_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPlayingScreenshot_Tablet_f32bdb34_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPlayingScreenshot_Tablet_f32bdb34_0.png new file mode 100644 index 0000000..caf7057 Binary files /dev/null and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/MiniAndFullscreenScreenshotsKt/MiniPlayerPlayingScreenshot_Tablet_f32bdb34_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/EndedScreenshot_Light_b29dc7a7_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/EndedScreenshot_Light_b29dc7a7_0.png index 24971fc..3cab6b9 100644 Binary files a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/EndedScreenshot_Light_b29dc7a7_0.png and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/EndedScreenshot_Light_b29dc7a7_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/LiveWithNoDescriptionScreenshot_Dark_d19fbf1f_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/LiveWithNoDescriptionScreenshot_Dark_d19fbf1f_0.png index 41fa0c9..879abfe 100644 Binary files a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/LiveWithNoDescriptionScreenshot_Dark_d19fbf1f_0.png and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/LiveWithNoDescriptionScreenshot_Dark_d19fbf1f_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/LiveWithNoDescriptionScreenshot_Light_b29dc7a7_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/LiveWithNoDescriptionScreenshot_Light_b29dc7a7_0.png index 18e9b77..d22c583 100644 Binary files a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/LiveWithNoDescriptionScreenshot_Light_b29dc7a7_0.png and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/LiveWithNoDescriptionScreenshot_Light_b29dc7a7_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/LoadingScreenshot_Light_b29dc7a7_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/LoadingScreenshot_Light_b29dc7a7_0.png index 0397efd..515326e 100644 Binary files a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/LoadingScreenshot_Light_b29dc7a7_0.png and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/LoadingScreenshot_Light_b29dc7a7_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PausedScreenshot_Dark_d19fbf1f_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PausedScreenshot_Dark_d19fbf1f_0.png index a9c3679..58fc0e2 100644 Binary files a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PausedScreenshot_Dark_d19fbf1f_0.png and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PausedScreenshot_Dark_d19fbf1f_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PausedScreenshot_Light_b29dc7a7_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PausedScreenshot_Light_b29dc7a7_0.png index 85ba815..44ca67a 100644 Binary files a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PausedScreenshot_Light_b29dc7a7_0.png and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PausedScreenshot_Light_b29dc7a7_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingDynamicScreenshot_DynamicDark_18383af3_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingDynamicScreenshot_DynamicDark_18383af3_0.png index d896236..a18246a 100644 Binary files a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingDynamicScreenshot_DynamicDark_18383af3_0.png and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingDynamicScreenshot_DynamicDark_18383af3_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingDynamicScreenshot_DynamicLight_4c0cf872_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingDynamicScreenshot_DynamicLight_4c0cf872_0.png index 5f84aa3..51f13ac 100644 Binary files a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingDynamicScreenshot_DynamicLight_4c0cf872_0.png and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingDynamicScreenshot_DynamicLight_4c0cf872_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_Dark_d19fbf1f_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_Dark_d19fbf1f_0.png index bee1b24..59142db 100644 Binary files a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_Dark_d19fbf1f_0.png and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_Dark_d19fbf1f_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_LargeFont_04aa6175_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_LargeFont_04aa6175_0.png index 2820360..1fb4e75 100644 Binary files a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_LargeFont_04aa6175_0.png and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_LargeFont_04aa6175_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_Light_b29dc7a7_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_Light_b29dc7a7_0.png index 61aeb91..c9b062d 100644 Binary files a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_Light_b29dc7a7_0.png and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_Light_b29dc7a7_0.png differ diff --git a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_Tablet_f32bdb34_0.png b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_Tablet_f32bdb34_0.png index a4e3715..0d1856e 100644 Binary files a/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_Tablet_f32bdb34_0.png and b/feature/player-ui/src/screenshotTestDefaultDebug/reference/io/github/dewfallapp/feature/player/ui/PlayerScreenshotsKt/PlayingScreenshot_Tablet_f32bdb34_0.png differ diff --git a/feature/player-ui/src/test/kotlin/io/github/dewfallapp/feature/player/ui/PlayerViewModelTest.kt b/feature/player-ui/src/test/kotlin/io/github/dewfallapp/feature/player/ui/PlayerViewModelTest.kt index 0c31862..7a60fb3 100644 --- a/feature/player-ui/src/test/kotlin/io/github/dewfallapp/feature/player/ui/PlayerViewModelTest.kt +++ b/feature/player-ui/src/test/kotlin/io/github/dewfallapp/feature/player/ui/PlayerViewModelTest.kt @@ -1,5 +1,6 @@ package io.github.dewfallapp.feature.player.ui +import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelStore import androidx.lifecycle.viewmodel.initializer @@ -13,9 +14,12 @@ import io.github.dewfallapp.core.model.VideoDetails import io.github.dewfallapp.core.model.VideoId import io.github.dewfallapp.core.model.YouTubeError import io.github.dewfallapp.core.model.YouTubeResult +import io.github.dewfallapp.core.playback.PictureHold import io.github.dewfallapp.core.playback.PlaybackConnection import io.github.dewfallapp.core.playback.stopsPlayback import io.github.dewfallapp.feature.player.logic.DetailsArea +import io.github.dewfallapp.feature.player.logic.PlayerIntent.EnterFullscreen +import io.github.dewfallapp.feature.player.logic.PlayerIntent.ExitFullscreen import io.github.dewfallapp.feature.player.logic.PlayerIntent.TryAgain import kotlin.test.AfterTest import kotlin.test.BeforeTest @@ -68,14 +72,18 @@ private class FakeRepository : VideoDetailsRepository { /** * A connection that records what the ViewModel asks of it. Its player's current item is the latest - * prepared one, unless a test sets it, and stopping follows the real rule, stopsPlayback. + * prepared one, unless a test sets it, and stopping follows the real rule, stopsPlayback. It counts + * the picture's holds. */ private class FakeConnection : PlaybackConnection { val prepared = mutableListOf>() val stopRequests = mutableListOf() + val releaseRequests = mutableListOf() val descriptions = mutableListOf>() + val videos = mutableMapOf() var currentItemId: String? = null var playing = false + var pictureHolds = 0 override val player: StateFlow = MutableStateFlow(null) override val failure: StateFlow = MutableStateFlow(null) @@ -83,16 +91,13 @@ private class FakeConnection : PlaybackConnection { override fun prepare(videoId: VideoId, play: Boolean, startPositionMs: Long): String { prepared += videoId to startPositionMs val id = "playback ${prepared.size}" + videos[id] = videoId currentItemId = id playing = play return id } - override fun isKnown(playbackId: String): Boolean = true - - override fun pause(playbackId: String) { - if (currentItemId == playbackId) playing = false - } + override fun videoOf(playbackId: String): VideoId? = videos[playbackId] override fun stop(playbackId: String) { stopRequests += playbackId @@ -102,11 +107,28 @@ private class FakeConnection : PlaybackConnection { } } + override fun release(playbackId: String) { + releaseRequests += playbackId + } + override fun describe(playbackId: String, title: String, channelName: String) { descriptions += Triple(playbackId, title, channelName) } - override fun setAppVisible(visible: Boolean) = Unit + override fun holdPicture(): PictureHold { + pictureHolds++ + var released = false + return PictureHold { + if (!released) { + released = true + pictureHolds-- + } + } + } + + override fun appStarted() = Unit + + override fun appStopped(changingConfigurations: Boolean) = Unit } /** A store that holds [viewModel], so the test can clear it as navigation does. */ @@ -139,9 +161,12 @@ class PlayerViewModelTest { Dispatchers.resetMain() } + private fun newViewModel(savedState: SavedStateHandle = SavedStateHandle()) = + PlayerViewModel(PlayerArgs(VIDEO), repository, connection, savedState) + @Test fun `creating the ViewModel asks once for its video, and the answer shows`() = runTest { - val viewModel = PlayerViewModel(PlayerArgs(VIDEO), repository, connection) + val viewModel = newViewModel() assertEquals(listOf(VIDEO), repository.calls.map { it.videoId }) repository.calls.single().answer.complete(YouTubeResult.Success(DETAILS)) @@ -152,7 +177,7 @@ class PlayerViewModelTest { @Test fun `trying again after NETWORK asks once more`() = runTest { - val viewModel = PlayerViewModel(PlayerArgs(VIDEO), repository, connection) + val viewModel = newViewModel() repository.calls.single().answer.complete(YouTubeResult.Failure(YouTubeError.NETWORK)) viewModel.dispatch(TryAgain) @@ -163,7 +188,7 @@ class PlayerViewModelTest { @Test fun `trying again after PRIVATE asks nothing`() = runTest { - val viewModel = PlayerViewModel(PlayerArgs(VIDEO), repository, connection) + val viewModel = newViewModel() repository.calls.single().answer.complete(YouTubeResult.Failure(YouTubeError.PRIVATE)) viewModel.dispatch(TryAgain) @@ -174,7 +199,7 @@ class PlayerViewModelTest { @Test fun `trying again while loading asks nothing`() = runTest { - val viewModel = PlayerViewModel(PlayerArgs(VIDEO), repository, connection) + val viewModel = newViewModel() viewModel.dispatch(TryAgain) @@ -182,8 +207,8 @@ class PlayerViewModelTest { } @Test - fun `closing after Try again stops the newest playback`() = runTest { - val viewModel = PlayerViewModel(PlayerArgs(VIDEO), repository, connection) + fun `closing after Try again releases the newest playback, which plays on`() = runTest { + val viewModel = newViewModel() val store = storeOf(viewModel) viewModel.startPlayback(C.TIME_UNSET) @@ -191,13 +216,14 @@ class PlayerViewModelTest { store.clear() assertEquals(listOf(VIDEO to C.TIME_UNSET, VIDEO to 61_000L), connection.prepared) - assertEquals(listOf(retried), connection.stopRequests) - assertFalse(connection.playing) + assertEquals(listOf(retried), connection.releaseRequests) + assertTrue(connection.stopRequests.isEmpty()) + assertTrue(connection.playing) } @Test fun `a video that started during the screen's exit keeps playing`() = runTest { - val viewModel = PlayerViewModel(PlayerArgs(VIDEO), repository, connection) + val viewModel = newViewModel() val store = storeOf(viewModel) viewModel.startPlayback(C.TIME_UNSET) @@ -205,14 +231,61 @@ class PlayerViewModelTest { connection.prepare(VideoId("YE7VzlLtp-4"), play = true, startPositionMs = C.TIME_UNSET) store.clear() - assertEquals(listOf("playback 1"), connection.stopRequests) + assertEquals(listOf("playback 1"), connection.releaseRequests) + assertTrue(connection.stopRequests.isEmpty()) assertTrue(connection.playing) assertEquals("playback 2", connection.currentItemId) } + @Test + fun `a followed playback gets the description and is released as the screen's own`() = runTest { + val viewModel = newViewModel() + val store = storeOf(viewModel) + + viewModel.follow("playback from the mini player") + repository.calls.single().answer.complete(YouTubeResult.Success(DETAILS)) + store.clear() + + assertEquals( + listOf(Triple("playback from the mini player", "A title", "A channel")), + connection.descriptions, + ) + assertEquals(listOf("playback from the mini player"), connection.releaseRequests) + assertTrue(connection.prepared.isEmpty()) + } + + @Test + fun `the ViewModel holds the picture until it is cleared`() = runTest { + val store = storeOf(newViewModel()) + assertEquals(1, connection.pictureHolds) + + store.clear() + + assertEquals(0, connection.pictureHolds) + } + + @Test + fun `fullscreen starts from the saved state and is written back`() = runTest { + val savedState = SavedStateHandle(mapOf("fullscreen" to true)) + val viewModel = newViewModel(savedState) + assertTrue(viewModel.state.value.fullscreen) + + viewModel.dispatch(ExitFullscreen) + assertEquals(false, savedState["fullscreen"]) + + viewModel.dispatch(EnterFullscreen) + assertEquals(true, savedState["fullscreen"]) + assertTrue(viewModel.state.value.fullscreen) + } + + @Test + fun `a new screen starts out of fullscreen`() = runTest { + assertFalse(newViewModel().state.value.fullscreen) + } + @Test fun `a failure shared by the details and playback has one Try again for both`() = runTest { - val viewModel = PlayerViewModel(PlayerArgs(VIDEO), repository, connection) + val viewModel = newViewModel() viewModel.startPlayback(C.TIME_UNSET) repository.calls.single().answer.complete(YouTubeResult.Failure(YouTubeError.NETWORK)) @@ -225,7 +298,7 @@ class PlayerViewModelTest { @Test fun `the details' Try again leaves a different playback failure alone`() = runTest { - val viewModel = PlayerViewModel(PlayerArgs(VIDEO), repository, connection) + val viewModel = newViewModel() viewModel.startPlayback(C.TIME_UNSET) repository.calls.single().answer.complete(YouTubeResult.Failure(YouTubeError.NETWORK)) @@ -238,7 +311,7 @@ class PlayerViewModelTest { @Test fun `details that arrive after the start describe that playback`() = runTest { - val viewModel = PlayerViewModel(PlayerArgs(VIDEO), repository, connection) + val viewModel = newViewModel() viewModel.startPlayback(C.TIME_UNSET) assertTrue(connection.descriptions.isEmpty()) @@ -249,7 +322,7 @@ class PlayerViewModelTest { @Test fun `a start after the details describes the new playback at once`() = runTest { - val viewModel = PlayerViewModel(PlayerArgs(VIDEO), repository, connection) + val viewModel = newViewModel() repository.calls.single().answer.complete(YouTubeResult.Success(DETAILS)) assertTrue(connection.descriptions.isEmpty()) @@ -268,7 +341,7 @@ class PlayerViewModelTest { @Test fun `details that failed describe nothing`() = runTest { - val viewModel = PlayerViewModel(PlayerArgs(VIDEO), repository, connection) + val viewModel = newViewModel() viewModel.startPlayback(C.TIME_UNSET) repository.calls.single().answer.complete(YouTubeResult.Failure(YouTubeError.NETWORK)) @@ -277,3 +350,19 @@ class PlayerViewModelTest { assertTrue(connection.descriptions.isEmpty()) } } + +class PlaybackOfVideoTest { + private val videos = mapOf("first" to VIDEO, "second" to VideoId("YE7VzlLtp-4")) + + @Test + fun `the player's item counts only when it plays the screen's video`() { + assertEquals("first", playbackOfVideo("first", VIDEO, videos::get)) + assertNull(playbackOfVideo("second", VIDEO, videos::get)) + } + + @Test + fun `no item, or an item with no video, counts as none`() { + assertNull(playbackOfVideo(null, VIDEO, videos::get)) + assertNull(playbackOfVideo("gone", VIDEO, videos::get)) + } +} diff --git a/openspec/changes/archive/2026-11-22-mini-and-fullscreen-player/.openspec.yaml b/openspec/changes/archive/2026-11-22-mini-and-fullscreen-player/.openspec.yaml new file mode 100644 index 0000000..137e8c3 --- /dev/null +++ b/openspec/changes/archive/2026-11-22-mini-and-fullscreen-player/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-21 diff --git a/openspec/changes/archive/2026-11-22-mini-and-fullscreen-player/design.md b/openspec/changes/archive/2026-11-22-mini-and-fullscreen-player/design.md new file mode 100644 index 0000000..aaa66c8 --- /dev/null +++ b/openspec/changes/archive/2026-11-22-mini-and-fullscreen-player/design.md @@ -0,0 +1,193 @@ +# Design + +## Context + +See proposal.md for why. What this change builds on, from #42 and #43 and docs/architecture.md's [The player](../../../../docs/architecture.md#the-player) and [Navigation](../../../../docs/architecture.md#navigation): + +- `:app`'s back stack holds SearchKey, then at most one PlayerKey. `openVideo` adds a PlayerKey only while SearchKey is on top. `close(key)` removes that entry's key, and `goBack` the top key while there is more than one. +- `PlayerRoute(videoId, onClose)` draws the video screen. Its top button, the keyboard_arrow_down glyph named "Close video", and the back gesture both remove the entry. Its strings file already notes that #44 makes the button minimize instead. +- PlayerViewModel keeps the playback ID of its latest start. Its `onCleared` calls `PlaybackConnection.stop(id)`, which stops the player and clears its items if the item is still that ID. Navigation 3 clears the ViewModel after the exit animation, and when the activity is destroyed for good. +- PlayerRoute keeps in its saved state whether playback started, the playback ID, the ID that has played, and the position. `startAction(started, known)` decides PLAY, WAIT_FOR_PLAY or NOTHING. At ON_STOP, `pausesOnLeave(changing, played)` pauses a playback that hasn't played yet, so its foreground service never starts from the background. +- MainActivity calls `PlaybackConnection.setAppVisible` in `onStart` and `onStop`, skipping configuration changes in an `if` that no test reaches. PlaybackService turns the video track off while the app can't be seen. +- PlaybackConnection exposes the MediaController as `player`. SessionPlayer gives the session, and so the controller, the current item's title as `title` and its channel name as `artist`, once the video screen describes the playback. PlaybackItems keeps the VideoId behind each playback ID while its item is the player's. +- The manifest keeps MainActivity in portrait. Android ignores that on large screens. Every screen draws edge to edge, and pads its content with `WindowInsets.safeDrawing`, Search YouTube included. +- `DewfallTheme(darkTheme)` already takes a darkTheme parameter "for the fullscreen player". The theme doesn't set the design system's opacity tokens yet, and architecture.md says duration-scrim comes with its first component. +- `:feature:player-ui` doesn't depend on activity-compose. `:app` does, at 1.13.0. + +### Facts checked + +Checked on November 21, 2026: + +- **Immersive mode.** [Hide system bars for immersive mode](https://developer.android.com/develop/ui/views/layout/immersive) uses `WindowCompat.getInsetsController(window, window.decorView)`, `hide(WindowInsetsCompat.Type.systemBars())` and `show(...)`. With `BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE`, a swipe from the edge shows the bars, which "overlay your app's content, might have some degree of transparency, and are automatically hidden after a short timeout". [Immersive content](https://developer.android.com/design/ui/mobile/guides/layout-and-content/immersive-content) asks for "tapping on the screen during video playback displays video playback controls and system bars", and "an overlay or scrim for overlaying text and controls". +- **Orientation.** For apps that target Android 17, as Dewfall does, `screenOrientation` and `setRequestedOrientation()` are ignored, with every portrait and landscape value, "on displays whose smallest width is greater than 600dp", in full screen and multi-window modes ([Restrictions on orientation and resizability are ignored](https://developer.android.com/about/versions/17/changes/ff-restrictions-ignored)). Android's recipe [App orientation restricted on phones but not on large screens](https://developer.android.com/develop/adaptive-apps/cookbook/orientation-restriction) sets `activity.requestedOrientation` from `LocalActivity.current` in Compose. `userLandscape`, ActivityInfo's `SCREEN_ORIENTATION_USER_LANDSCAPE`, is "Landscape orientation, but can be either normal or reverse landscape based on the device sensor and the user's preference" ([activity element](https://developer.android.com/guide/topics/manifest/activity-element#screen)), so it follows the rotation lock. +- **Back.** [Provide custom back navigation](https://developer.android.com/guide/navigation/custom-back) uses activity-compose's `BackHandler`, and "only the innermost one intercepts the back event". [Handle back gestures](https://developer.android.com/guide/navigation/navigation-event/handle-back) says handlers of the same priority run last in, first out. BackHandler in activity-compose 1.13.0 carries no deprecation, checked in its compiled classes. +- **Media3 1.11.1**, in the sources jar of the version the app uses: + - media3-ui-compose's `rememberCurrentMediaItemState(player)` holds the current `mediaItem`, its `mediaMetadata` and `isLive`, updated on position discontinuities, timeline, media metadata, metadata and command changes, and set once when it is made. Like the other state holders, it is `@UnstableApi`, so the code opts in as VideoArea does ([CurrentMediaItemState.kt at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/ui_compose/src/main/java/androidx/media3/ui/compose/state/CurrentMediaItemState.kt), [PlayerStateObserver.kt at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/ui_compose/src/main/java/androidx/media3/ui/compose/state/PlayerStateObserver.kt)). + - `PlayPauseButtonState.onClick` calls `Util.handlePlayPauseButtonAction`, whose play branch calls `prepare()` on an idle player, seeks to the default position on an ended one, then plays ([Util.java at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/common/src/main/java/androidx/media3/common/util/Util.java), `handlePlayButtonAction`). So play after a failure prepares again from the same position, as the notification's play does, and play at the end starts again. + - `ContentFrame` scales the picture with `ContentScale.Fit` by default. +- **Accessibility timeouts.** Android 10 added `AccessibilityManager.getRecommendedTimeoutMillis`, which "provides support for user-defined timeouts for interactive and non-interactive UI elements" ([Android 10 features](https://developer.android.com/about/versions/10/features), "User-defined accessibility timeouts"). Compose's `LocalAccessibilityManager` exposes it as `calculateRecommendedTimeoutMillis` ([AccessibilityManager](https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/AccessibilityManager)). + +## Goals / Non-Goals + +**Goals:** + +- The requirements in specs/player/spec.md, on Android 10 to 17, in light, dark and dynamic color, at the largest font size, and on phones, tablets and split screen. +- Playback belongs to the app, not to the video screen, so the mini player, the notification and the video screen all control one playback. +- Playback state stays out of screen state (ADR 0002). The mini player and fullscreen read the player through media3-ui-compose's state holders. + +**Non-Goals:** + +- Picture-in-picture, casting, a queue or a next video. +- A picture or thumbnail in the mini player. The design has none, and the app loads no images yet (#176). +- Gestures: swiping the mini player, double tap to seek, pinch to zoom. +- Entering fullscreen by turning the phone. The brief keeps phones in portrait except the fullscreen player, and the prototype enters it with the button. +- Restoring the mini player after Android ends the process. Nothing plays then, and #50's stored positions may bring it later. +- Screenshot tests. #45 sets them up, and whichever of #44 and #45 merges second adds them for the mini player and fullscreen. + +## Decisions + +### Playback belongs to the app + +Minimizing removes the video screen's entry from the back stack, as closing does today, but leaves playback alone. So PlayerViewModel's `onCleared` no longer stops it. It calls a new `PlaybackConnection.release(playbackId)`, which drops the ID's video only when it is neither the player's current item nor the start that waits for the connection, as the pure function `releaseDrops(waitingId, currentItemId, playbackId)` decides. A video whose links failed has no item, so minimizing it keeps nothing, as the privacy requirement's new scenario asks. + +Stopping moves to the mini player's close button, which calls the existing `stop(playbackId)` with the player's current item. Removing the app from the recent apps and dismissing the paused notification stop it as today. "Don't keep activities" no longer stops background play, because a cleared ViewModel no longer stops playback. + +Alternative: keep the video screen's entry on the back stack while minimized, under a custom Navigation 3 scene that draws it as a bar. That keeps one ViewModel, so the details aren't loaded again, but the back gesture on Search would then have to skip a hidden entry, and the mini player would belong to one entry instead of to the app. Rejected as more complex for one saved request. + +### Minimizing + +`PlayerRoute(videoId, onClose)` becomes `PlayerRoute(videoId, onMinimize)`, and its button is named "Minimize player", after the prototype. The glyph stays keyboard_arrow_down, as in the "Player" frames. `:app` calls the same `close(key)` for the button and `goBack` for the back gesture, so the double tap rule stays. BackStack.kt's KDoc says that closing an entry no longer stops playback. + +### The mini player + +`:feature:player-ui` exposes a second public composable, `MiniPlayer(onOpenVideo: (VideoId) -> Unit, modifier)`. It lives with the video screen because it shares the play and pause button, the strings and the way the screen reads the player. It isn't a screen on the back stack: it has no screen state and no ViewModel. It reads `PlaybackConnection.player`, and the controller through `rememberCurrentMediaItemState`, `rememberPlayPauseButtonState` and `rememberProgressStateWithTickCount`. Its play, pause and close are player commands, which go straight to PlaybackConnection, and its tap is an action that changes no state, which goes straight to `:app`'s navigation. "Refining the architecture rules" below says which rules this needs. + +It gets PlaybackConnection through a small Hilt entry point, `EntryPointAccessors.fromApplication`, because a composable can't take an injected constructor, and the public composable takes only plain values and actions. Passing the connection in from `:app` would make `:app` hand a player object across the feature boundary. + +- **Previews.** MiniPlayer reads the connection, so it draws through a stateless `MiniPlayerBar`, which takes the title, the channel name, whether it plays, the progress as a function, and the actions. Previews and #45's screenshot tests call MiniPlayerBar. +- **The decisions in a pure function.** `miniPlayerContent(currentItemId, title, channelName, live)`, in `:feature:player-logic`, returns null when there is no current item, so the mini player draws nothing, and otherwise the playback ID that its tap and close act on, the title or null when it is empty or blank, so the UI shows "Now playing", the channel name or null, and whether it draws the progress line, which a live stream doesn't. Its unit tests cover each case. The composable only reads the controller into it and draws the answer. +- **When it shows.** `:app` composes it only while the back stack's top isn't a PlayerKey, as the pure function `showsMiniPlayer(backStack)` in BackStack.kt decides. MiniPlayer draws nothing while the controller is null, or while `miniPlayerContent` returns null. So it shows while an item exists, whatever its state, and goes when `stop` clears the items or the session ends. +- **What it shows**, after the "Mini player on the inbox" frames and the design system's elevation table: a `surfaceContainerHigh` bar with a 2dp line at its top, `primary` for what has played on `surfaceContainerHighest`, then the title in `titleMedium` and the channel name in `bodySmall` and `onSurfaceVariant`, a 40dp FilledIconButton in `primary` with the play_arrow or filled pause glyph, then an IconButton with the close glyph in `onSurfaceVariant`. The title and channel come from the controller's `mediaMetadata.title` and `artist`. "Now playing" is the name the design gives the mini player's region. The line ticks once per pixel of its width, is drawn in the draw phase, so its ticks redraw only the line, and is hidden from screen readers. +- **Opening the video.** The title and channel form one clickable area with the click label "Open video". It looks up the VideoId of `miniPlayerContent`'s playback ID with a new `PlaybackConnection.videoOf(playbackId)`, and calls `onOpenVideo`. `:app` passes `backStack.openVideo`, which already opens only while Search YouTube is on top. +- **Minimizing before the details load** cancels their request with the ViewModel, so the mini player says "Now playing" and the notification shows no title until the video screen opens again and loads them. The spec allows it. Keeping the request alive after the screen closes would need a scope outside the screen for one title, so this is a known trade-off. +- **Insets.** `:app` puts NavDisplay and the mini player in a Column. The mini player pads its content with the system bars and the display cutout, bottom and sides, but not the keyboard, so the keyboard covers it. The box above it measures the mini player's height and passes it to `consumeWindowInsets(PaddingValues(bottom = height))`, so Search YouTube's own `safeDrawing` padding drops the navigation bar and keeps only the part of the keyboard above the mini player. In a wider window the content sits in a centered column of ReadableWidth, and the background fills the width. + +Alternatives: a Scaffold's bottom bar in `:app` would need its own inset handling for the same result. Putting the mini player inside each screen would repeat it in every feature. + +### Refining the architecture rules + +The maintainer chose this on November 21, 2026, as question 4's answer. Two rules say less than this change needs: + +- AGENTS.md's module rule, and docs/architecture.md's "Feature modules" and "Navigation", say a feature on `:app`'s back stack "exposes one public composable". `:feature:player-ui` would expose two: `PlayerRoute`, its screen, and `MiniPlayer`, a bar that `:app` places outside the back stack. Both take only plain values and actions, so features still never see each other or Navigation 3. +- AGENTS.md's MVI rule and ADR 0002's note of November 20, 2026 let "the video screen's player commands" go straight to PlaybackConnection. The mini player's play, pause and close are player commands too, from a bar with no screen state, where an intent would pass through a reducer with nothing to change. + +So this change updates AGENTS.md's module and MVI rules, docs/architecture.md's "Feature modules" and "Navigation", and adds a dated note to ADR 0002, after the maintainer approves it, as the earlier notes were. Fullscreen's two intents go through the reducer, so they need no exception. + +### Going on with a playback that already plays + +`startAction` gains a third input and a fourth answer: `startAction(started, playbackIdKnown, playsThisVideo)`, where `playsThisVideo` says that the player's current item is a playback of this screen's VideoId. A first opening that finds it answers GO_ON: the route keeps that playback ID in its saved state as if it had started it, and starts nothing. The screen shows the playback as it is: playing, paused, at its end with play again, or failed with "Try again". This covers both the mini player's tap and opening the same video from search. PlayerViewModel gains `follow(playbackId)`, which the route calls for GO_ON and for NOTHING, so a ViewModel made again after "Don't keep activities" still describes and releases the playback. + +### The leaving rule moves to the connection + +Leaving the app must not start a video that hasn't played, from the video screen or the mini player. The mini player has no saved state that knows whether the video has played, so the rule moves from PlayerRoute's ON_STOP into the connection. PlaybackConnection's `setAppVisible(visible)` becomes two calls: `appStarted()`, which MainActivity calls in `onStart`, and `appStopped(changingConfigurations)`, which it calls in `onStop` with `isChangingConfigurations`. The connection listens to its controller and keeps the playback ID that last played. + +`appStopped` acts on what the pure function `leaveDecision(changingConfigurations, waitingId, currentItemId, playedId)` returns: whether the app counts as hidden, whether to turn off the waiting start's play, and whether to pause the current item. A configuration change does none of the three. Otherwise the app is hidden, a waiting start won't play, and the current item pauses unless it is the ID that played. So the configuration-change test moves out of MainActivity's untested `if` into the function. `pausesOnLeave` and its four cases move from `:feature:player-logic` to `leaveDecision`'s tests in `:core:playback`: a configuration change, with and without a played playback, does nothing, and otherwise only a playback that hasn't played pauses. New cases add the waiting start and no item. PlayerRoute keeps saving the position at ON_STOP, and drops its saved `playedId`. + +### The picture while minimized + +The maintainer chose this on November 21, 2026, as question 2's answer. PlaybackConnection gains `holdPicture()`, which returns a handle whose `release()` lets go once, and PlaybackSessions, which is internal to `:core:playback`, keeps a count of the handles held, and the service shows the picture only while the app can be seen and the count is above zero. PlayerViewModel holds the picture from its creation until `onCleared`, so a configuration change, such as entering fullscreen on a phone, never turns it off, and minimizing turns it off once the exit animation ends. The rule builds on today's: the same track parameter, the same short load when it comes back. + +Alternative: count the composed video areas. A configuration change disposes and recomposes them, which would turn the picture off and on during the turn to landscape. Rejected. + +### Fullscreen state + +PlayerState gains `fullscreen: Boolean`, and PlayerIntent gains EnterFullscreen and ExitFullscreen, which the reducer applies. It is screen state, not a player command, so it goes through the reducer, with its tests. It lives in the ViewModel, so it survives the configuration change that turning to landscape causes. PlayerViewModel also writes it to its SavedStateHandle after each fullscreen intent, and starts from it, so it survives the end of the process too. That matters because no source says whether Android drops the activity's landscape request when the process ends. If it kept it, a screen that came back out of fullscreen would stay turned until fullscreen was entered and left again. With fullscreen saved, the screen comes back in fullscreen, waiting for play, and leaving it turns the phone back to portrait, as FullscreenWindow does. Entry ViewModels get a SavedStateHandle: the KDoc of ViewModelStoreNavEntryDecorator in lifecycle-viewmodel-navigation3 2.11.0, the version the app uses, says the saveable state decorator is required "to ensure that the NavEntry scoped ViewModels can properly provide access to SavedStateHandles", and `:app`'s NavDisplay has it first. Read in that version's sources jar on November 21, 2026. PlayerRoute shows FullscreenPlayer in place of PlayerScreen while it is on, and keeps its playback rules composed either way. + +The fullscreen button sits at the end of the play and pause row, in both the seek bar layout and the live layout, as the "Player" frames show, only while the controller is connected. + +### The fullscreen window + +A `FullscreenWindow` effect in `:feature:player-ui`, from `LocalActivity.current`: + +- On entering, it reads the bars' light or dark icons in each activity, because a recreated activity's `enableEdgeToEdge()` sets them again for the current theme. Then it sets `SCREEN_ORIENTATION_USER_LANDSCAPE`, sets `BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE`, and turns `isAppearanceLightStatusBars` and `isAppearanceLightNavigationBars` off, so a bar over the black window has light icons in light mode too. It turns them off again on every configuration change, keyed on `LocalConfiguration`, because Android 17 no longer restarts activities for several configuration changes, such as `CONFIG_KEYBOARD` ([Handle configuration changes](https://developer.android.com/guide/topics/resources/runtime-changes), "Android 17"), and in activity 1.13.0 "EdgeToEdge is now re-invoked on configuration changes" ([activity release notes](https://developer.android.com/jetpack/androidx/releases/activity), 1.13.0-alpha01), which would bring dark icons back. +- While it is composed, it shows the system bars while the controls show and hides them while they don't, with `show(systemBars())` and `hide(systemBars())`. With the behavior above, a swipe from an edge still shows hidden bars for a moment. +- On leaving, it sets `SCREEN_ORIENTATION_PORTRAIT`, the orientation that the manifest gives MainActivity and that the brief keeps phones in, restores the icons and shows the system bars, unless the activity is only changing configurations, because the new activity runs the effect again. It sets portrait rather than an orientation saved on entering, because Android 16 and 17 ignore `getRequestedOrientation()` on large screens ([Android 17's change](https://developer.android.com/about/versions/17/changes/ff-restrictions-ignored)), so a value saved on an unfolded foldable wouldn't be portrait once it folds. Large screens ignore the portrait request too, as they ignore the manifest's. If lint's SourceLockedOrientationActivity check flags the call, it gets the same justified suppression as the manifest's LockedOrientationActivity. +- PlayerContent calls `BackHandler(enabled = state.fullscreen)` unconditionally in the entry, and its handler sends ExitFullscreen. BackHandler's reference asks for exactly that: "It is important to call this composable unconditionally. Use the enabled parameter to control whether the handler is active", because conditional calls "can change the order of composition", and "the one that is composed last among all enabled handlers will be invoked" ([BackHandler](https://developer.android.com/reference/kotlin/androidx/activity/compose/BackHandler.composable), Precedence and Usage). The entry composes after NavDisplay's own handler, so while fullscreen shows, the back gesture leaves fullscreen and not the screen. + +Large screens ignore the orientation request, so fullscreen keeps the window's shape there, with black around the video. `:feature:player-ui` adds activity-compose for `LocalActivity` and `BackHandler`. `:app` already ships the same version, so the APK gains no library, and this asks no new dependency. + +Alternative: `SCREEN_ORIENTATION_SENSOR_LANDSCAPE` turns either way even with the rotation lock on. USER_LANDSCAPE respects the user's lock, as Android's guidance prefers. + +### The fullscreen layout + +After the "Player full screen" frames, inside `DewfallTheme(darkTheme = true)`: + +- The window is `scrim`, black in both schemes. The picture is ContentFrame with ContentScale.Fit, padded with `WindowInsets.displayCutout`, so no picture sits under the cutout, and showing or hiding the bars never moves it. A shown bar may lie over the picture's edge, as over the black around it. Its shutter is `surfaceContainerHighest`, as on the video screen. +- At the top start, the title in `titleMedium` and `onSurface`, and the channel name in `bodySmall` and `onSurfaceVariant`, on `surface` at the design system's duration-scrim opacity, 0.8, in a `shapes.large` box at most 480dp wide, once the details show. +- At the bottom, one row on the same background: the play and pause button, the times, the seek bar, and the exit button with the fullscreen_exit glyph. A live stream says "Live" in place of the times and the seek bar. Loading shows the spinner over the picture. A failure shows the Banner in the picture's place, with "Try again" where it helps, and the row keeps only the exit button. Waiting after the session was gone shows the play button at the saved position, as the video area does. +- Both overlays sit 16dp inside `WindowInsets.systemBarsIgnoringVisibility.union(WindowInsets.displayCutout)`. Compose's [About window insets](https://developer.android.com/develop/ui/compose/system/insets) says of the ignoring-visibility insets: "If the system bars are hidden (due to entering immersive full screen mode), then the main system bar insets will be empty, but these insets will be non-empty." So the overlays sit clear of the bars and the cutout whether the bars show or not, and never move when they do. `safeDrawing` would shrink to the cutout while the bars hide, and a bar shown again would cover the row's end in landscape with three-button navigation, against AGENTS.md's rule that no text or controls sit under the system bars. The frames draw a 16:9 video on a 20:9 phone and put the overlays 16dp inside the picture. Dewfall plays videos of any shape, and a portrait video in landscape leaves a narrow picture with little room inside it, so the overlays follow the window's safe area instead of the picture. For a 16:9 video on a 16:9 window the two are the same. +- The screen stays on while the video plays, with the same `keepScreenOn` rule. + +`:core:designsystem` gains `DewfallOpacity.DURATION_SCRIM`, 0.8, and DesignTokensTest checks it against tokens.json, so the token reaches the code with its first use, as architecture.md says. + +### Fullscreen controls that hide + +The maintainer chose this on November 21, 2026, as question 3's answer. Media3's own PlayerView does the same: it shows its controls "when playback starts, pauses, ends, or fails" (`setControllerAutoShow`, [PlayerView.java at 1.11.1](https://github.com/androidx/media/blob/1.11.1/libraries/ui/src/main/java/androidx/media3/ui/PlayerView.java)). + +- **Playing** means `Player.isPlaying`, which is false while the player is paused, waits for data, has ended or failed. Fullscreen reads it with media3-common-ktx's `Player.listen`, next to `rememberPlaybackStatus`. +- **The state.** FullscreenControls, a small class in `:feature:player-logic`, holds whether the user has the controls shown. Pure functions decide: `visible(playing, screenReader)` is true when the video isn't playing, a screen reader is on, or the user has them shown. `tapped(playing, screenReader)` toggles them only while the video plays and no screen reader is on. `playingChanged()` shows them, so pausing, the end, a failure and playing again all bring them back. `hidesAfterTimeout(playing, screenReader)` is true only while they show, the video plays and no screen reader is on. Unit tests cover each function with each input. +- **The timer.** While `hidesAfterTimeout` holds, a LaunchedEffect waits `calculateRecommendedTimeoutMillis(3000, containsIcons = true, containsText = true, containsControls = true)` milliseconds, then hides them. Every pointer event in fullscreen, seen in the initial pass without consuming it, restarts the wait, and the tap itself decides whether they show. Every key event, seen with `onPreviewKeyEvent` without consuming it, shows them and restarts the wait, so a hardware keyboard can bring them back. Fullscreen's root is focusable and takes focus, so key events reach it. +- **The tap.** The picture's tap has a click label, "Show controls" or "Hide controls", so TalkBack, Switch Access and Voice Access name it. +- **Screen readers.** While touch exploration is on, as AccessibilityManager's `isTouchExplorationEnabled` reports, they always show, because a screen reader's swipes between controls send the app no pointer events, so nothing would restart the timer. + +Touch exploration can turn on or off while fullscreen shows, so fullscreen reads it from AccessibilityManager and listens with `addTouchExplorationStateChangeListener` while it is composed. + +The system bars show and hide with the controls, as the maintainer chose on November 21, 2026, after Android's immersive content guidance: "tapping on the screen during video playback displays video playback controls and system bars". The overlays use the ignoring-visibility insets, so the bars never cover them and nothing moves. The controls appear and disappear without animation, because the design system's motion only answers a tap, and the hide answers a timeout. + +### The privacy scenario's name + +In the MODIFIED requirement "Video details stay private", the scenario keeps its living name, "After closing the video screen", while its steps now minimize the screen and close the mini player. OpenSpec refuses a MODIFIED block that drops a living scenario, and "After closing the mini player" would be a new name. + +### Strings and glyphs + +New strings in `:feature:player-ui`: "Minimize player", which replaces "Close video", "Full screen", "Exit full screen", "Open video", "Close player" and "Now playing". The fullscreen and fullscreen_exit glyphs come from Material Symbols Rounded at the same commit as the other glyphs, weight 400, grade 0, optical size 24, outlined, with the same header comment, into `:core:designsystem`, whose KDoc and architecture.md row list them. + +### Tests + +- Reducer: EnterFullscreen and ExitFullscreen, and that neither touches the details. +- `startAction`: every combination, with GO_ON only on a first opening whose video plays. +- `:core:playback`: `releaseDrops`, `leaveDecision`, with `pausesOnLeave`'s four cases and the waiting start, and the picture count in PlaybackSessions, with the app hidden, no screen, one and two screens. +- FullscreenControls: `visible`, `tapped`, `playingChanged` and `hidesAfterTimeout`, each with playing or not, a screen reader or not, and shown or not. +- PlayerViewModelTest: fullscreen starts from the SavedStateHandle and is written back after each fullscreen intent. +- `miniPlayerContent`: no current item, a title, an empty and a blank title, no channel name, and a live stream. +- `:app`: `showsMiniPlayer` with Search on top, a PlayerKey on top, and both. +- PlayerViewModelTest: `onCleared` releases instead of stopping, `follow` makes a later description reach the connection, and the ViewModel holds the picture until it is cleared. +- Hand checks on emulators with Android 10, 12L and 17, because the change touches `:core:playback`, the video area and the visibility signal. docs/testing.md's list gains the mini player, minimizing, stopping from the mini player, tapping the notification while minimized, the back gesture on Search on Android 10, which finishes the root activity there, fullscreen on a phone and a tablet, the bar icons swiped in over fullscreen in light mode, the back gesture in fullscreen, the cutout, the keyboard over the mini player, and the controls' timeout with the accessibility setting `accessibility_interactive_ui_timeout_ms`. + +### Docs + +AGENTS.md's module and MVI rules, and a dated note in ADR 0002, as "Refining the architecture rules" says. docs/architecture.md: "Feature modules" and Navigation's public composables and the Column, The theme's darkTheme sentence, `:core:designsystem`'s glyph list and DewfallOpacity, and The player: who owns playback, minimizing and the mini player, the release and leaving rules, the picture rule, fullscreen, and the corrected "Don't keep activities" and `onCleared` sentences. docs/testing.md: the hand checks, and the sentence about "Don't keep activities". The player spec's Purpose drops "Later changes add the mini and fullscreen players". AGENTS.md's "Where things are" names the mini player among feature/'s screens. + +## Questions for the maintainer + +The maintainer answered all five on November 21, 2026, each with the recommendation, and approved the change at commit ed5d4c0, which the rebases onto ca3360b, 9841b01 and ed1c0b7 carried over unchanged as def76f5, 932d1c6 and then 3105546, the plan commit on the merged branch. "The maintainer's answers" in [pull request #206](https://github.com/dewfallapp/dewfall/pull/206) records them. + +Questions 1, 2, 3 and 5 are visible to users and not covered by the roadmap, the brief or the designs. Question 4 widens an ADR's decision, which needs the maintainer's dated approval. + +1. **How does the user stop playback?** The design's mini player has no way to close it, and while the app shows, Android never stops a paused player. Recommendation: a close button at the mini player's end, named "Close player", which stops playback and removes the notification. Alternative: swipe the mini player away, with an accessibility action for screen readers. +2. **The picture while minimized.** Recommendation: turn the picture off while minimized, as in the background, which saves the data of a video-only file, at the cost of a short load when the video screen opens again. Alternative: keep fetching the picture, so reopening shows it at once. +3. **Fullscreen controls.** Recommendation: hide them 3 seconds after the last touch while the video plays, or later when the accessibility setting asks, and show them on a tap, as Android's immersive content guidance shows. Alternative: always show them. +4. **The architecture rules.** May `:feature:player-ui` expose a second public composable, the mini player, and may the mini player's play, pause and close go straight to PlaybackConnection, as the video screen's player commands do, with a dated note in ADR 0002 and the matching lines in AGENTS.md? Recommendation: yes. Alternative: give the mini player its own MVI state and ViewModel, whose intents would pass through a reducer that changes nothing. +5. **A paused, minimized video in the background.** When Android stops the player of a paused, minimized video in the background, the mini player goes away, and the position is lost until #50 stores positions. The video screen keeps its position in saved state, but the mini player has none. Recommendation: accept it for now. Alternative: keep the last minimized video and position in `:app`'s saved state and show a mini player that waits for play. + +## Risks / Trade-offs + +- [Turning to landscape recreates the activity, so the picture's SurfaceView attaches again and may flash black for a frame] → ContentFrame's shutter covers the gap, and the hand checks look for a pause in the sound. +- [The orientation saved before fullscreen may be wrong if the user enters fullscreen during another orientation request] → The video screen makes no other request, and the manifest's portrait is the only other value. +- [Moving the leaving rule changes code that #43's hand checks covered] → The same cases move with their tests, and the hand checks "Leaving early" and "Leaving from the mini player while the video loads" run again. +- [The mini player's tap loads the details again, one request to YouTube each time] → The same request as opening the video from search. No stream links are fetched again. +- [A wrong inset sum could hide the last search result behind the mini player, or leave a gap above the keyboard] → A hand check at the largest font size, with and without the keyboard, and on a phone with gesture and three-button navigation. + +## Migration Plan + +No data changes. The release has no users yet. Rolling back is a revert of the pull request. diff --git a/openspec/changes/archive/2026-11-22-mini-and-fullscreen-player/proposal.md b/openspec/changes/archive/2026-11-22-mini-and-fullscreen-player/proposal.md new file mode 100644 index 0000000..32635d2 --- /dev/null +++ b/openspec/changes/archive/2026-11-22-mini-and-fullscreen-player/proposal.md @@ -0,0 +1,36 @@ +# Proposal + +## Why + +Phase 4's task list ends the player with "Mini player and fullscreen player" ([roadmap](../../../../docs/roadmap.md#phase-4-search-and-play)), issue [#44](https://github.com/dewfallapp/dewfall/issues/44). Today the video screen's top button closes the screen and stops playback, so the user can't look for the next video while one plays, and a video can only fill a 16:9 box above its details. The design has both missing sizes: "Mini player on the inbox" and "Player full screen" in [docs/design/screens.md](../../../../docs/design/screens.md#player). + +## What Changes + +- **Minimize instead of close.** The video screen's top button becomes "Minimize player", as the "Player" frames' prototype names it. It and the system's back gesture go back to the screen the video was opened from, as that screen was, and leave playback as it is: a playing video plays on, a paused one stays paused. +- **The mini player.** While the player has a video and the video screen doesn't show, a mini player sits at the bottom of the screen, today Search YouTube, as the "Mini player on the inbox" frames show: a thin progress line, the title and channel name, and a play and pause button. Tapping its title opens the video screen for that video, which goes on playing where it is, without starting again. Phase 5's navigation bar will sit under it. +- **Stopping.** Closing the video screen no longer stops playback. The user stops it with the mini player's close button, which the maintainer chose on November 21, 2026. Removing Dewfall from the recent apps still stops it, and so does dismissing the paused notification, as today. +- **Fullscreen.** A fullscreen button joins the video screen's controls, as the "Player" frames show. Fullscreen uses the dark scheme in light mode too, hides the system bars, turns a phone to landscape, and shows the video in the whole window, with black pillars around it. The title and channel name sit at the top, and the play and pause button, the times, the seek bar and an exit button at the bottom, as the "Player full screen" frames show. The exit button and the back gesture return to the video screen in portrait. +- **One playback for the whole app.** Leaving the app still pauses a video that hasn't played yet, now for the mini player too, so a video never starts in the background. Opening, from search, the video that the mini player plays goes on with it instead of starting it again. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `player`: minimizing replaces closing; the mini player; stopping from the mini player; the fullscreen player; the leaving rule covers the mini player; the media session's title goes when the mini player closes, not when the video screen closes. + +## Impact + +- `:feature:player-ui`: the minimize button and the back gesture, the fullscreen button and the fullscreen player, and a new public composable, `MiniPlayer(onOpenVideo)`, which reads the player through its MediaController, never through screen state. `PlayerRoute(videoId, onClose)` becomes `PlayerRoute(videoId, onMinimize)`. Its ViewModel no longer stops playback when it is cleared. +- `:feature:player-logic`: PlayerState gains whether the screen is in fullscreen, with two intents and their reducer tests, the start decision gains going on with a playback that already plays the video, and the mini player's and fullscreen controls' decisions are pure functions with tests. +- `:core:playback`: PlaybackConnection gains the video of a playback ID, a release that keeps the player's own item, and the leaving rule, which moves here from the video screen. +- `:core:designsystem`: the fullscreen and fullscreen_exit glyphs from Material Symbols Rounded, under the Apache License 2.0 like the others. +- `:app`: shows the mini player under the back stack while no video screen is on top, and opens the video screen from it. +- `:feature:player-ui` adds activity-compose, for the back gesture in fullscreen and the activity. `:app` already ships it, so the APK gains no library. +- No new host, no new log line, and nothing new leaves the device. +- Rules: AGENTS.md's module and MVI rules and ADR 0002 gain the mini player, a second public composable whose player commands skip intents, which the maintainer approved on November 21, 2026 (design.md's question 4). +- Docs: docs/architecture.md's "Feature modules", "Navigation", "The theme" and "The player", docs/testing.md's hand checks, and the player spec. +- Screenshot tests of the mini player and the fullscreen player need #45's setup. If #45 merges first, this change adds them. If this change merges first, #45 adds them. diff --git a/openspec/changes/archive/2026-11-22-mini-and-fullscreen-player/specs/player/spec.md b/openspec/changes/archive/2026-11-22-mini-and-fullscreen-player/specs/player/spec.md new file mode 100644 index 0000000..9a396a4 --- /dev/null +++ b/openspec/changes/archive/2026-11-22-mini-and-fullscreen-player/specs/player/spec.md @@ -0,0 +1,401 @@ +# Spec Delta + +## ADDED Requirements + +### Requirement: Minimizing goes back +The video screen SHALL have a minimize button at the top, named for screen readers. The minimize button and the system's back gesture SHALL return to the screen the video was opened from, as that screen was, and SHALL leave playback as it is: a playing video plays on, and a paused one stays paused. + +#### Scenario: Minimizing after a search +- **WHEN** a video plays, the user opened it from search results, and taps the minimize button +- **THEN** Search YouTube shows the same text and results, sends no new search, and the video plays on in the mini player + +#### Scenario: The back gesture +- **WHEN** the user makes the system's back gesture on the video screen +- **THEN** the app goes back as the minimize button does + +#### Scenario: A double tap on minimize +- **WHEN** the user taps the minimize button twice quickly, or taps it during the back gesture +- **THEN** the app goes back once, to the screen the video was opened from, and doesn't close + +#### Scenario: Minimizing a paused video +- **WHEN** the user pauses a video and taps the minimize button +- **THEN** the video stays paused, and the mini player offers to play it + +#### Scenario: Minimizing while the video loads +- **WHEN** the user opens a video and taps the minimize button before it starts playing +- **THEN** it starts playing, and the mini player shows it + +### Requirement: The mini player shows while a video is minimized +While the player has a video and no video screen shows, the app SHALL show a mini player at the bottom of the screen. It SHALL show for a video that plays, is paused, waits for data, has ended or failed while playing. It SHALL go away when playback stops, or when Android stops the player. + +#### Scenario: A minimized video +- **WHEN** a video plays and the user minimizes it +- **THEN** the mini player shows at the bottom of Search YouTube + +#### Scenario: The video screen +- **WHEN** the video screen shows +- **THEN** no mini player shows + +#### Scenario: No video +- **WHEN** the app opens and nothing has played +- **THEN** no mini player shows + +#### Scenario: A video that couldn't start +- **WHEN** the user minimizes a video whose stream links failed to load, so the player has no video +- **THEN** no mini player shows + +#### Scenario: After the process ended +- **WHEN** the system ended the app's process while the mini player showed, and the user returns to the app +- **THEN** no mini player shows, and nothing plays + +#### Scenario: Paused and minimized in the background, back much later +- **WHEN** the user paused a minimized video, went to the home screen, and Android stopped the player before the user came back +- **THEN** no mini player shows, and opening the video again starts it from the start + +### Requirement: The mini player shows the video and how far it played +The mini player SHALL show the video's title and channel name once the video's details have loaded, and "Now playing" in the title's place until then or when they failed. The title SHALL wrap and never be cut off. A line along its top edge SHALL show how much of the video has played, hidden from screen readers. A live stream SHALL have no line. + +#### Scenario: A video with its details +- **WHEN** "How reading rooms were lit before electric lamps" by Larkspur Lectures plays in the mini player +- **THEN** the mini player shows that title and the channel name, and its line shows how much has played + +#### Scenario: Details that failed +- **WHEN** a video plays in the mini player, but its details failed to load +- **THEN** the mini player shows "Now playing", with no channel name + +#### Scenario: A long title at the largest font size +- **WHEN** the title is longer than one line and the font size is the largest +- **THEN** the title wraps onto more lines, and nothing is cut off + +#### Scenario: A live stream +- **WHEN** a live stream plays in the mini player +- **THEN** it shows no progress line + +### Requirement: The mini player plays and pauses +The mini player SHALL have a play and pause button, named for screen readers, that plays and pauses the video. At the end of a video it SHALL offer to play it again from the start. After a failure while playing, play SHALL try again from the same position. + +#### Scenario: Pausing from the mini player +- **WHEN** a video plays in the mini player and the user taps its button +- **THEN** the video pauses, and the button offers to play + +#### Scenario: The end +- **WHEN** a video in the mini player plays to its end and the user taps its button +- **THEN** it plays again from the start + +#### Scenario: After a failure +- **WHEN** the network went away while a video played in the mini player, and the user taps play with the network back +- **THEN** the video plays on from where it stopped + +#### Scenario: A failure says nothing in the mini player +- **WHEN** a video fails while it plays in the mini player +- **THEN** the mini player offers play and gives no reason, and the video screen says why once the user opens it + +### Requirement: Tapping the mini player opens the video +Tapping the mini player's title SHALL open the video screen for its video, which SHALL go on with the playback as it is, without starting it again, and SHALL load the video's details. The mini player SHALL tell screen readers that the tap opens the video. + +#### Scenario: Opening a playing video +- **WHEN** a video plays in the mini player at 18:24 and the user taps its title +- **THEN** the video screen opens and the video plays on from 18:24, and the app asks YouTube for its details once and for no new stream links + +#### Scenario: Opening a paused video +- **WHEN** the mini player's video is paused and the user taps its title +- **THEN** the video screen shows it paused at the same position + +### Requirement: Opening the video that already plays goes on with it +Opening, from search, the video that the mini player plays SHALL open its video screen and go on with that playback, as tapping the mini player does. Opening another video SHALL replace it, and start the new one from the start. + +#### Scenario: The same video from search +- **WHEN** a video plays in the mini player and the user opens the same video from search results +- **THEN** the video screen shows it playing on from where it was + +#### Scenario: Another video from search +- **WHEN** a video plays in the mini player and the user opens another video from search results +- **THEN** the first video stops, and the new one starts playing from the start + +### Requirement: The mini player fits any window +The mini player's background SHALL reach the window's bottom edge, behind the navigation bar, and its text and buttons SHALL sit above the system bars and clear of the display cutout. In a wider window its content SHALL sit in one centered column of readable width. The screen above it SHALL end at its top edge, so nothing is hidden behind it. + +#### Scenario: The end of the search results +- **WHEN** the mini player shows and the user scrolls Search YouTube's results to the end +- **THEN** the last result sits fully above the mini player + +#### Scenario: A tablet in landscape +- **WHEN** the mini player shows on a tablet in landscape +- **THEN** its background fills the window's width, and its title and buttons sit in one centered column no wider than the readable width + +#### Scenario: The keyboard +- **WHEN** the mini player shows and the user types in Search YouTube's field +- **THEN** the keyboard covers the mini player, and the search results above it end above the keyboard + +### Requirement: Closing the mini player or removing the app stops playback +The mini player SHALL have a close button, named for screen readers. Closing it SHALL stop playback, remove the media notification, and hide the mini player. Removing Dewfall from the recent apps SHALL do the same. Closing the video screen by minimizing it SHALL NOT stop playback. + +#### Scenario: Closing the mini player +- **WHEN** a video plays in the mini player and the user taps its close button +- **THEN** the sound stops, the notification goes away, the mini player goes away, and the screen under it shows as it was + +#### Scenario: Removing the app from the recent apps +- **WHEN** a video plays in the background and the user removes Dewfall from the recent apps +- **THEN** the sound stops and the notification goes away + +### Requirement: The picture turns off while minimized +While a video is minimized, the player SHALL decode no picture, and SHALL NOT fetch a picture that comes in its own file, as while the app can't be seen. Opening the video screen again SHALL bring the picture back at the current position, after a short load that may pause the sound. + +#### Scenario: Data while minimized +- **WHEN** a video whose sound and picture come in separate files plays at 1080p, and the user minimizes it +- **THEN** the player fetches only the sound until the video screen opens again + +#### Scenario: Opening it again +- **WHEN** the user opens the minimized video from the mini player +- **THEN** the picture shows again at the current position + +### Requirement: The video can play in fullscreen +The video screen's controls SHALL have a fullscreen button, named for screen readers, while the player is connected. Fullscreen SHALL show the video as large as the window allows, keeping its shape, on black. It SHALL use the dark color scheme in light mode too, and show the system bars only while its controls show, or for a moment after a swipe from the screen's edge. The screen SHALL stay on while the video plays. + +#### Scenario: Entering fullscreen +- **WHEN** a video plays on the video screen and the user taps the fullscreen button +- **THEN** the video fills the screen in dark colors and plays on without a pause, and the system bars hide when the controls do + +#### Scenario: Light mode +- **WHEN** the phone is in light mode and the user enters fullscreen +- **THEN** fullscreen uses the dark color scheme + +#### Scenario: A system bar for a moment +- **WHEN** the controls are hidden and the user swipes from the screen's edge in fullscreen +- **THEN** the system bars show for a moment over the video, and hide again + +### Requirement: A phone turns to landscape in fullscreen +On a phone, entering fullscreen SHALL turn the screen to landscape, either way round as the phone's rotation setting allows, and leaving it SHALL turn the screen back to portrait. Where Android ignores an app's orientation, such as on a tablet, an unfolded foldable or in split screen, fullscreen SHALL keep the window's shape. Turning the phone SHALL NOT enter or leave fullscreen. + +#### Scenario: A phone +- **WHEN** the user enters fullscreen on a phone held in portrait +- **THEN** the screen turns to landscape, and the video plays on without a pause + +#### Scenario: A tablet in portrait +- **WHEN** the user enters fullscreen on a tablet in portrait +- **THEN** fullscreen fills the window in portrait, with black above and below the video + +#### Scenario: Turning the phone on the video screen +- **WHEN** the user turns a phone to landscape on the video screen +- **THEN** the video screen stays in portrait, and doesn't enter fullscreen + +### Requirement: Fullscreen has its own controls +Fullscreen SHALL show the title and channel name at the top, once the details have loaded, and at the bottom the play and pause button, the position and the length, the seek bar and an exit button, each named for screen readers. A live stream SHALL say "Live" in place of the seek bar and the times. Loading and failures SHALL show as on the video screen. The title SHALL wrap and never be cut off. + +#### Scenario: Controls in fullscreen +- **WHEN** a video plays in fullscreen +- **THEN** the title and channel name show at the top, and the button, "18:24 / 1:14:02", the seek bar and the exit button at the bottom + +#### Scenario: Seeking in fullscreen +- **WHEN** the user drags the fullscreen seek bar to the middle of a video +- **THEN** playback goes on from the middle + +#### Scenario: A failure in fullscreen +- **WHEN** the network goes away in fullscreen and the player runs out of data +- **THEN** fullscreen says that YouTube can't be reached, with "Try again" and the exit button + +#### Scenario: A long title at the largest font size in fullscreen +- **WHEN** the title is long and the font size is the largest +- **THEN** the title wraps onto more lines in its box, and nothing is cut off + +### Requirement: Fullscreen keeps clear of the system bars and the display cutout +In fullscreen, no text or control SHALL sit under the system bars or the display cutout, whether the bars show or not, so showing or hiding the bars never moves the title or the controls. No picture SHALL sit under the display cutout. + +#### Scenario: A display cutout +- **WHEN** fullscreen shows in landscape on a phone with a display cutout +- **THEN** no text, control or picture sits under the cutout + +#### Scenario: The system bars over fullscreen +- **WHEN** the system bars show in fullscreen in landscape with three-button navigation, after a tap or a swipe +- **THEN** they cover none of the title and controls, the exit button can be tapped, and nothing moves + +### Requirement: Fullscreen controls hide while the video plays +While a video plays in fullscreen, the title, the controls and the system bars SHALL hide 3 seconds after the user last touched the screen or pressed a key, or later when the accessibility settings ask for more time. A tap on the video SHALL show them, and a tap while they show SHALL hide them. Whenever the video isn't playing, and while a screen reader is on, they SHALL show, even if they were hidden. When it plays again they SHALL show, and hide 3 seconds later. + +#### Scenario: Watching +- **WHEN** a video plays in fullscreen and the user doesn't touch the screen for 3 seconds +- **THEN** the title, the controls and the system bars hide, and the video plays on + +#### Scenario: Showing them again +- **WHEN** the controls are hidden and the user taps the video +- **THEN** the title, the controls and the system bars show again + +#### Scenario: Hiding them with a tap +- **WHEN** a video plays in fullscreen with the controls showing and the user taps the video +- **THEN** the title, the controls and the system bars hide + +#### Scenario: Paused +- **WHEN** the user pauses a video in fullscreen +- **THEN** the title and the controls stay, and a tap on the video doesn't hide them + +#### Scenario: Paused from elsewhere while hidden +- **WHEN** the controls are hidden and the video pauses from a headset, the notification or a phone call +- **THEN** the title, the controls and the system bars show + +#### Scenario: Waiting for data while hidden +- **WHEN** the controls are hidden and the player runs out of data +- **THEN** the title and the controls show, with the loading sign, until it plays again + +#### Scenario: The end while hidden +- **WHEN** the controls are hidden and the video plays to its end +- **THEN** the title and the controls show, and the button offers to play it again + +#### Scenario: A failure while hidden +- **WHEN** the controls are hidden and the video fails +- **THEN** the failure shows with the exit button + +#### Scenario: Playing again +- **WHEN** the user presses play in fullscreen +- **THEN** the controls stay, and hide 3 seconds after the last touch + +#### Scenario: A key press +- **WHEN** a video plays in fullscreen and the user presses a key on a hardware keyboard +- **THEN** the controls show, and the 3 seconds start again + +#### Scenario: More time to act +- **WHEN** the phone's accessibility setting for time to take action is 1 minute +- **THEN** the controls hide only after 1 minute without a touch + +#### Scenario: A screen reader +- **WHEN** TalkBack is on, or turns on, while a video plays in fullscreen +- **THEN** the title and the controls show and stay + +### Requirement: Leaving fullscreen returns to the video screen +The exit button and the system's back gesture SHALL leave fullscreen and return to the video screen, with the system bars and the screen's own colors, and playback SHALL go on without a pause. + +#### Scenario: The exit button +- **WHEN** a video plays in fullscreen and the user taps the exit button +- **THEN** the video screen shows in portrait, with the system bars, and the video plays on + +#### Scenario: The back gesture in fullscreen +- **WHEN** the user makes the system's back gesture in fullscreen +- **THEN** fullscreen ends as with the exit button, and the video screen stays open + +#### Scenario: Fullscreen after the process ended +- **WHEN** the system ended the app's process while a video showed in fullscreen on a phone, and the user returns to it +- **THEN** fullscreen shows again, waiting for play at the saved position, and leaving it turns the phone back to portrait + +## MODIFIED Requirements + +### Requirement: Video details stay private +The app SHALL never log the video's ID, title, channel name or description. It SHALL send them nowhere but YouTube, except the title and channel name, which it SHALL give only to Android's media session, for the media notification, while the video's playback lasts. The only copies kept outside the screen SHALL be the video's ID and its paused position, also user data, in the state Android saves for a process that it ends in the background, and, in memory while its playback lasts, the playing video's ID, title, channel name and stream links in the playback service, which it SHALL drop when that playback is replaced or stops. The media session SHALL identify the video only by a random playback ID, and SHALL hold no video ID. + +#### Scenario: Logs after opening a video +- **WHEN** the user opens a video, once with details showing and once with the network off +- **THEN** the app's log lines hold no ID, title, channel name or description, and the failure's line names only the call and its category + +#### Scenario: After closing the video screen +- **WHEN** the user minimizes the video screen, then closes the mini player +- **THEN** Android's media session no longer holds the video's title or channel name + +#### Scenario: After minimizing a video that couldn't start +- **WHEN** the user minimizes a video whose stream links failed to load +- **THEN** the playback service holds nothing about that video + +### Requirement: The video screen fits any window +On a phone the screen SHALL stay in portrait, except in fullscreen. In any wider window, such as a tablet, an unfolded foldable, landscape on a large screen or split screen, the screen SHALL keep its content in one centered column of readable width, and the background SHALL fill the window. No text or control SHALL sit under the system bars or the display cutout. + +#### Scenario: A tablet in landscape +- **WHEN** the screen shows a video's details on a tablet in landscape +- **THEN** the details sit in one centered column no wider than the readable width, and nothing is cut off + +### Requirement: The sound plays on in the background +Leaving the app while a video plays, such as with the home gesture or by switching apps, and turning the screen off, SHALL keep the sound playing. Coming back SHALL show the same video playing at its current position, on the video screen or in the mini player. A configuration change, such as a resized window or a theme change, SHALL NOT stop, pause or restart playback. + +#### Scenario: Going home +- **WHEN** a video plays and the user goes to the home screen +- **THEN** the sound goes on, and when the user comes back, the video plays on at its current position + +#### Scenario: The screen off +- **WHEN** a video plays and the user turns the screen off for 10 minutes +- **THEN** the sound goes on the whole time + +#### Scenario: Paused in the background, back much later +- **WHEN** the user paused a video on the video screen in the background, and Android stopped the player before the user came back +- **THEN** the video screen waits at the position where it paused, and plays on from it when the user presses play + +#### Scenario: Resizing the window +- **WHEN** a video plays in split screen and the user resizes the window +- **THEN** it keeps playing without a pause + +### Requirement: The picture turns off while the app can't be seen +While no Dewfall screen can be seen, the player SHALL decode no picture, and SHALL NOT fetch a picture that comes in its own file. When the app shows the video screen again, the picture SHALL come back at the current position, after a short load that may pause the sound. When the app shows again with the video minimized, the picture SHALL stay off until the video screen opens. A file that holds both sound and picture, and a live stream, whose segments hold both, still load the picture's bytes with the sound. + +#### Scenario: Data in the background +- **WHEN** a video whose sound and picture come in separate files plays at 1080p, and the user goes to the home screen +- **THEN** the player fetches only the sound until the user comes back + +#### Scenario: A live stream in the background +- **WHEN** a live stream plays and the user goes to the home screen +- **THEN** the sound goes on, and no picture is decoded until the user comes back + +#### Scenario: Coming back +- **WHEN** the user comes back to the video screen of a video that played on in the background +- **THEN** the picture shows again at the current position + +#### Scenario: Coming back to the mini player +- **WHEN** the user minimized a playing video, went to the home screen, and comes back +- **THEN** the mini player shows the video playing on, and the player fetches only the sound until the video screen opens + +### Requirement: A media notification shows while a video plays +While a video plays, and while it is paused until Android stops the player, the app SHALL show a media notification with a play and pause button, and the video's title and channel name once its details have loaded. It SHALL show no picture. Tapping it SHALL open the app as it was, on the video screen or on the screen under the mini player. While the video plays, the user SHALL NOT be able to dismiss it. + +#### Scenario: Playing in the background +- **WHEN** a video plays and the user goes to the home screen +- **THEN** a notification shows the video's title and channel name with a pause button, and the pause button pauses the video + +#### Scenario: Playing in the app +- **WHEN** a video plays on the video screen, or in the mini player +- **THEN** the notification shows too + +#### Scenario: Tapping the notification +- **WHEN** a video plays in the background and the user taps its notification +- **THEN** Dewfall opens as it was, on the video screen or on Search YouTube with the mini player, and the video plays on + +#### Scenario: Details that failed +- **WHEN** a video plays but its details failed to load +- **THEN** the notification shows no title or channel name, and its button still plays and pauses + +#### Scenario: Paused for a long time +- **WHEN** a video stays paused in the background for more than 10 minutes +- **THEN** the user can dismiss the notification, which stops playback, and Android may remove it + +#### Scenario: A notification left by an ended process +- **WHEN** the system ended the app's process while a paused video's notification still showed, and the user taps its play button +- **THEN** nothing plays, nothing crashes, and the notification goes away + +#### Scenario: A failure in the background +- **WHEN** a video plays in the background and the player runs out of data because the network went away +- **THEN** the notification stays with a play button, which tries again from the same position, and once the video plays again the video screen, or the mini player when the video is minimized, shows it playing, with no failure + +### Requirement: Opening a video starts playing it +Opening a video SHALL start playing it from the start, or a live stream from its live edge, without a tap, unless the mini player already plays that video, which goes on as it is. A video screen that comes back after Android stopped its player in the background SHALL wait for the user to press play, at the position where it paused. One that comes back after the system ended the app's process SHALL wait for play at the position the screen saved when the user last left the app. + +#### Scenario: Opening a video +- **WHEN** the user opens a video from search +- **THEN** the video starts playing from the start + +#### Scenario: Playback after process death +- **WHEN** the system ended the app's process while it showed a video, and the user returns to it +- **THEN** the video waits at the position it had when the user last left the app, for the user to press play, and no stream links are fetched for it until then + +### Requirement: A video that hasn't started waits +When the user leaves the app after opening a video and before it has started playing, from the video screen or with the video minimized, the video SHALL NOT start in the background. Coming back SHALL show it paused, waiting for the user to press play. + +#### Scenario: Leaving while the video loads +- **WHEN** the user opens a video and goes to the home screen before it starts playing +- **THEN** no sound plays, and when the user comes back, the video waits for play + +#### Scenario: Leaving from the mini player while the video loads +- **WHEN** the user opens a video, minimizes it and goes to the home screen before it starts playing +- **THEN** no sound plays, and when the user comes back, the mini player offers to play it + +## REMOVED Requirements + +### Requirement: Closing goes back +**Reason**: The video screen's top button minimizes the player instead of closing it, and minimizing leaves playback as it is. +**Migration**: See "Minimizing goes back", which keeps the return to the screen the video was opened from, the back gesture and the double tap. + +### Requirement: Closing the video screen or removing the app stops playback +**Reason**: Closing the video screen no longer stops playback, because the mini player goes on with it. +**Migration**: See "Closing the mini player or removing the app stops playback". diff --git a/openspec/changes/archive/2026-11-22-mini-and-fullscreen-player/tasks.md b/openspec/changes/archive/2026-11-22-mini-and-fullscreen-player/tasks.md new file mode 100644 index 0000000..edbab11 --- /dev/null +++ b/openspec/changes/archive/2026-11-22-mini-and-fullscreen-player/tasks.md @@ -0,0 +1,78 @@ +# Tasks + +## 1. Before building + +- [x] 1.1 Record the maintainer's answers to design.md's "Questions for the maintainer" in "The maintainer's answers" in the pull request's description, with their date. If an answer differs from the recommendation, change the spec, design.md and these tasks, run the maintainer subagent's plan check again, and build only after "Verdict: Build". Verify that the description quotes each answer and the approval of the change. +- [x] 1.2 If #45's screenshot test setup is on main when the build starts, rebase onto it and add a task 6.4 for the screenshot tests of the mini player and fullscreen. If not, say in the pull request that the mini player's and fullscreen's screenshot tests come with #45. Verify that the description says which. + +## 2. The playback service and connection + +- [x] 2.1 Add `PlaybackConnection.videoOf(playbackId)`, from PlaybackItems, and `release(playbackId)`, which drops the ID's video only when `releaseDrops(waitingId, currentItemId, playbackId)` says so: neither the player's current item nor the start that waits for the connection. Verify with unit tests of `releaseDrops`: the current item, the waiting start, both null, and another ID. +- [x] 2.2 Move the leaving rule into the connection, as design.md's "The leaving rule moves to the connection" describes: replace `setAppVisible(visible)` with `appStarted()` and `appStopped(changingConfigurations)`, which MainActivity calls in `onStart` and `onStop`, keep the playback ID that last played from a listener on the controller, and act on `leaveDecision(changingConfigurations, waitingId, currentItemId, playedId)`. Move `pausesOnLeave`'s four test cases from `:feature:player-logic` into `leaveDecision`'s tests in `:core:playback`, add the waiting start and no item, and remove `pausesOnLeave`, PlaybackConnection's `pause(playbackId)` and `pauseDecision`, which nothing calls once PlayerRoute drops its ON_STOP pause, with pauseDecision's test, whose waiting-start case `leaveDecision`'s tests keep. In the same task, drop PlayerRoute's call of `pausesOnLeave` and the fake's `setAppVisible` and `pause` in PlayerViewModelTest, so the build passes. Verify with `./gradlew :core:playback:testDebugUnitTest :feature:player-logic:test :app:assembleDebug`. +- [x] 2.3 As question 2's answer chose: add `PlaybackConnection.holdPicture()`, returning a handle whose `release()` lowers PlaybackSessions' count of held pictures once, and make PlaybackService show the picture only while the app can be seen and the count is above zero. Verify with unit tests of PlaybackSessions' picture state: the app hidden, no holder, one, two, and a handle released twice. +- [x] 2.4 Update docs/architecture.md's "The service and the connection", "In the background" and "Opaque playback IDs" for who owns playback, `release`, the leaving rule, the picture rule and what PlaybackItems holds after the video screen closes. Verify that the text agrees with the code. + +## 3. The video screen and minimizing + +- [x] 3.1 In `:feature:player-logic`, add `fullscreen` to PlayerState with EnterFullscreen and ExitFullscreen, and give `startAction` its third input, `playsThisVideo`, and the answer GO_ON. Verify with `./gradlew :feature:player-logic:test`: both intents, that they leave the details alone, and every combination of `startAction`'s inputs. +- [x] 3.2 In PlayerViewModel, replace `stop` in `onCleared` with `release`, add `follow(playbackId)`, hold the picture from creation until `onCleared`, take a SavedStateHandle, start `fullscreen` from it and write it back after each fullscreen intent. Give PlayerViewModelTest's fake connection `holdPicture`, `release` and `videoOf`, recording their calls. Verify with `./gradlew :feature:player-ui:testDebugUnitTest`, with the fake connection recording calls: `onCleared` releases and never stops, a followed ID gets the description once the details show, the picture is held until the ViewModel is cleared, and fullscreen starts from a SavedStateHandle that holds it and is written back. +- [x] 3.3 In PlayerRoute, rename `onClose` to `onMinimize`, name the button "Minimize player", go on with a playback of this video for GO_ON, call `follow` for GO_ON and NOTHING, drop the saved `playedId` and the ON_STOP pause, and keep saving the position. Verify with `./gradlew :feature:player-ui:assembleDebug` and the hand checks in task 6.2. +- [x] 3.4 Update docs/architecture.md's "Starting, pausing and stopping" and "Navigation" for minimizing, GO_ON and `follow`. Verify that the text agrees with the code. + +## 4. The mini player + +- [x] 4.1 Add `miniPlayerContent(currentItemId, title, channelName, live)` to `:feature:player-logic`, as design.md's "The mini player" describes. Verify with `./gradlew :feature:player-logic:test`: no current item, a title, an empty and a blank title, no channel name, and a live stream. +- [x] 4.2 Add the public `MiniPlayer(onOpenVideo, modifier)` to `:feature:player-ui`, drawing what `miniPlayerContent` returns through the stateless `MiniPlayerBar`, which the previews call, with the strings "Open video", "Close player" and "Now playing", a Hilt entry point for PlaybackConnection, and previews in light and dark: playing, paused, a long title at font scale 2, and "Now playing". Verify with `./gradlew :feature:player-ui:assembleDebug lint detekt`, and that the previews render. +- [x] 4.3 In `:app`, put NavDisplay and the mini player in a Column, with `showsMiniPlayer(backStack)` in BackStack.kt, the measured height consumed from the insets of the box above, and `openVideo` as its action. Pass `close(key)` as the video screen's `onMinimize`. Verify with BackStackTest cases for `showsMiniPlayer`, and the hand checks in task 6.2. +- [x] 4.4 Update docs/architecture.md's "Navigation", the `:app` and `:feature:player-ui` rows of the module tables, the sentence in "The video area" that says rememberPlaybackStatus stays in `:feature:player-ui` until #44 needs to share it, and add "The mini player" to "The player". Verify that the text agrees with the code. +- [x] 4.5 As question 4's answer chose: update AGENTS.md's module rule, which says a feature exposes one public composable, and its MVI rule, which lets only the video screen's player commands skip intents, docs/architecture.md's "Feature modules" and "Navigation" sentences that say the same, and add a note to ADR 0002, dated and naming the maintainer's approval, as its #41 and #42 notes do. Verify that AGENTS.md, architecture.md and ADR 0002 say the same thing, and that the note quotes the approval's date. + +## 5. Fullscreen + +- [x] 5.1 Add the fullscreen and fullscreen_exit glyphs to `:core:designsystem` from Material Symbols Rounded at commit 10ecc14790, with the same header comment as the other glyphs, and `DewfallOpacity.DURATION_SCRIM`, checked by a new case in DesignTokensTest. Verify with `./gradlew :core:designsystem:testDebugUnitTest`. +- [x] 5.2 Add the fullscreen button to the video area's play and pause rows, "Full screen", and FullscreenPlayer with the FullscreenWindow effect, and call BackHandler unconditionally in PlayerContent with `enabled = state.fullscreen`, as design.md's "The fullscreen window" and "The fullscreen layout" describe, with "Exit full screen", light bar icons while it shows, the icons the activity had restored on leaving, the system bars shown and hidden with the controls, the overlays inside the ignoring-visibility system bar insets and the cutout, and the picture inside the cutout only. `:feature:player-ui` adds activity-compose from the version catalog. Add previews in dark: playing, live, a failure, waiting, and a long title at font scale 2. Verify with `./gradlew :feature:player-ui:assembleDebug lint detekt`, and that `:app`'s release runtime classpath is unchanged, with `./gradlew :app:dependencies --configuration releaseRuntimeClasspath` before and after. +- [x] 5.3 As question 3's answer chose: add FullscreenControls to `:feature:player-logic`, with `visible`, `tapped`, `playingChanged` and `hidesAfterTimeout`, and use it in fullscreen with the recommended timeout, the touch exploration listener, pointer and key events, and the picture's click labels "Show controls" and "Hide controls", as design.md's "Fullscreen controls that hide" describes. Verify with `./gradlew :feature:player-logic:test`, each function with each input, and the hand checks in task 6.2. +- [x] 5.4 Update docs/architecture.md's "The theme" sentence about darkTheme, the `:core:designsystem` row's glyphs and DewfallOpacity, and add "Fullscreen" to "The player". Verify that the text agrees with the code. + +## 6. Checks + +- [x] 6.1 Run every check that the pull request workflow runs: `./gradlew spotlessCheck detekt lint test assembleDebug`. Verify that it passes. +- [x] 6.2 Update docs/testing.md's "Checking the player by hand": drop the sentence that "Don't keep activities" stops background play, change "Stopping" to the mini player's close button, and add checks for minimizing, the mini player, fullscreen and the picture while minimized. Run the whole list that a change to the video area asks for on emulators with Android 10 (API 29), Android 12L (API 32) and Android 17 (API 37), one emulator at a time across the sessions, plus a tablet or resizable emulator for fullscreen on a large screen and split screen. The new checks: + - Minimize a playing video: Search shows as it was, the mini player shows the title, the channel name and pause, and the sound goes on. Minimize with the back gesture, and with a double tap: the app goes back once. + - Minimize a paused video, and one that is still loading. Minimize a video whose details failed: the mini player says "Now playing". + - In the mini player, pause, play, let a short video end and play it again, and turn the network off and on, then press play. + - Tap the mini player's title: the video screen shows the video at the same position, with no new stream links in the log's call lines. Open the same video from search: the same. Open another video: it starts from the start. + - Open a video whose formats the phone can't decode, such as on the Android 17 emulator without `-feature -HardwareDecoder`, and minimize it: if the mini player shows, play fails again and gives no reason, and opening the video screen says why. + - Close the mini player: the sound stops, the notification goes away, and `adb shell dumpsys media_session` shows no title or channel name. + - Minimize a playing video, go home, and tap the notification: Search shows with the mini player, playing on, and the picture stays off until the video screen opens. On Android 10, make the back gesture on Search with the mini player, which finishes the root activity there: the sound plays on, and the notification reopens Search with the mini player. + - Minimize a video, then go home before it starts: no sound, and coming back the mini player offers play. + - While minimized, compare the received bytes of a 1080p video over one minute with the video screen open and minimized: far fewer minimized. Open it again: the picture shows at the current position. + - Scroll the search results to the end with the mini player: the last result is fully above it, at the default and the largest font size, with gesture and three-button navigation. Type in the field: the keyboard covers the mini player, and the results end above the keyboard. + - Enter fullscreen on a phone in light mode: landscape, dark colors, no system bars, no pause in the sound. The system bars show with the controls, with light icons, and hide with them. With the controls hidden, swipe from an edge: the bars show for a moment and hide again. In landscape with three-button navigation, show the bars: they cover no part of the title or the control row, the exit button works, and nothing moves. Turn the phone the other way round: it follows when auto-rotate is on. Exit with the button and with the back gesture: portrait, the bars back, still playing. + - In fullscreen, the controls hide 3 seconds after the last touch while playing, show on a tap, and stay while paused. With `adb shell settings put secure accessibility_interactive_ui_timeout_ms 60000` they hide after a minute. Put it back with `adb shell settings delete secure accessibility_interactive_ui_timeout_ms`. + - In fullscreen on an emulator with a display cutout: no text, control or picture under it. A live stream says "Live". Turn the network off: the failure shows with "Try again" and the exit button. + - Fullscreen on a tablet in portrait and in split screen: the window keeps its shape, with black around the video. + - Fullscreen at the largest font size: the title wraps in its box, and the controls are whole. + - With TalkBack on, where the emulator has it: the fullscreen controls show and stay. Without it, FullscreenControls' tests cover the rule. + - With the controls hidden, pause with `adb shell input keyevent KEYCODE_MEDIA_PAUSE`, let a short video end, and turn the network off until the player runs out of data: each time the controls show. Press play: they stay, and hide 3 seconds later. Tap while paused: they stay. + - On Android 17 in light mode, in fullscreen, connect a hardware keyboard through the emulator's settings, or change the navigation mode: the bar icons stay light. + - On a foldable or resizable emulator, enter fullscreen unfolded, fold it, and leave fullscreen: the phone is in portrait. + - In fullscreen, pause, go home, and end the process with `adb shell am kill io.github.dewfallapp`. Come back: fullscreen shows, waiting for play. Make the back gesture: fullscreen ends, the video screen stays, and the phone turns back to portrait. + - Minimize a playing video, go home, and end the process: coming back shows no mini player and plays nothing. Minimize a paused video, go home, wait over 10 minutes until the service leaves the foreground, then stop it with `adb shell am make-uid-idle io.github.dewfallapp`: coming back shows no mini player, and opening the video starts it from the start. + - Minimize and open the video again a few times, watching the screen above the mini player while Navigation 3's animation runs: nothing jumps in a way that hides text, and the last search result never sits under the mini player. + - Go home in fullscreen and come back: still fullscreen, still playing. Tap the notification in fullscreen: the same. + + Verify that every check that ran passes, restore each emulator's settings, and record the results in the pull request. The notes below say which checks ran. + +## Notes from the build + +- 1.2: #45's screenshot setup (pull request #207) wasn't on main when the build started. It merged before this pull request, so the mini player's and fullscreen's screenshot tests were added here, as the agreed rule for #44 and #45 asks: whichever merges second adds them. +- 6.2, on November 21 and 22, 2026: the hand checks ran on Android 17 (API 37) and Android 12L (API 32). They found four bugs, all fixed in the same pull request: fullscreen's text and the mini player's text drew black on dark surfaces, a key press didn't bring the fullscreen controls back, and closing the mini player left Search without the navigation bar's inset. On November 22, the rest ran on temporary emulators, created for the checks and deleted afterwards, because the machine's own Android 10 AVD was in use by the maintainer and off limits. + - Android 10 (API 29, Pixel 4). These checks passed: "Minimizing", "Playing" apart from seeking, "The mini player", "Minimized in the background", including the back gesture on Search finishing the root activity while it plays, "Stopping", with a density change in place of the theme, which this system image locks, "Live", "Networks" with the network off and "Try again", "The background" apart from its lock screen and Doze, "The picture in the background" for a 1080p video, "Leaving early", "Dismissing", "Coming back", "A notification left behind", "The end in the background", "Failures in the background" and "Buttons". "The mini player's layout" passed at the default and the largest font, with three-button and gesture navigation. Fullscreen passed: landscape, the bars and controls, taps, a key, the media keys, a network failure with "Try again", a cutout, a live stream, a long title at the largest font, going home and the notification, and the end of the process. Minimizing a video whose details failed with the network off left no mini player, because nothing played; "Now playing" showed for a video minimized before its details loaded. Not run on Android 10: "A long video", seeking, playing on mobile data only, "The background"'s lock screen and Doze, the live stream's bytes on mobile data, "Sound", "The screen", "Don't keep activities", turning the phone the other way round and an edge swipe in fullscreen, a short video's end in fullscreen, and the accessibility timeout, which ran on the tablet. TalkBack isn't on this system image. The video that can't decode and "Android 17's background audio" are checks for Android 17, and "Playing again after the foreground ended" is one for Android 12L and 17. On Android 10, `am kill` leaves the process running while the paused service is in the foreground, and `run-as io.github.dewfallapp kill -9` answered "unknown pid", so docs/testing.md now gives `kill -9` as root for that step. The checks also found that on Android 10 the video screen draws a black background, and no minimize button, while its SurfaceView shows a picture. Main at ed1c0b7 does the same, so it comes from the video screen, not from this change, and the pull request lists it as a follow-up. + - A tablet (Pixel Tablet, API 37): the mini player's layout, fullscreen in landscape, in portrait and in split screen, and resizing the split screen while it plays. In split screen Android keeps the status bar, which the app can't hide there, and nothing sits under it. The accessibility timeout of 60 seconds also passed there: the controls hid after about a minute, and the video played on without rebuffering. On November 21, on the Android 17 phone emulator, rebuffering had kept bringing the controls back before the minute ended. + - A foldable (Pixel Fold, API 37): fullscreen unfolded keeps the window's shape, folding goes on in landscape on the outer screen, and leaving fullscreen turns it to portrait. + +## Workflow follow-up + +- Run the reviewer subagent, fix its "Must fix" items, archive the change with /opsx:archive as the last commit, updating the living player spec's Purpose in the same commit, and run the reviewer again. +- Run `python3 scripts/pre_push_gate.py`, push only after PASS, and mark the pull request ready once CI is green. diff --git a/openspec/specs/player/spec.md b/openspec/specs/player/spec.md index 2864982..cbf21a7 100644 --- a/openspec/specs/player/spec.md +++ b/openspec/specs/player/spec.md @@ -2,7 +2,7 @@ ## Purpose -Lets a user open one video, see what it is, and watch it: its title, channel, publish time and description, or why they can't be shown, and the video playing above them, or why it can't play, and lets the sound play on in the background with a media notification. Later changes add the mini and fullscreen players. +Lets a user open one video, see what it is, and watch it: its title, channel, publish time and description, or why they can't be shown, and the video playing above them, or why it can't play, lets the sound play on in the background with a media notification, and lets the user minimize the video into a mini player or watch it in fullscreen. ## Requirements @@ -113,21 +113,6 @@ When YouTube can't give the details, the screen SHALL say why in words for each - **WHEN** opening a video fails, and YouTube gives no reason the app can tell apart, such as for a premiere that hasn't started - **THEN** the screen says that the video isn't available and that YouTube didn't say why, and names removal, age restriction and a start still to come as possible reasons, with no "Try again" -### Requirement: Closing goes back -The screen SHALL have a close button at the top, named for screen readers. The close button and the system's back gesture SHALL return to the screen the video was opened from, as that screen was. - -#### Scenario: Closing after a search -- **WHEN** the user opened a video from search results and taps the close button -- **THEN** Search YouTube shows the same text and results, and sends no new search - -#### Scenario: The back gesture -- **WHEN** the user makes the system's back gesture on the video screen -- **THEN** the app goes back as the close button does - -#### Scenario: A double tap on close -- **WHEN** the user taps the close button twice quickly, or taps it during the back gesture -- **THEN** the app goes back once, to the screen the video was opened from, and doesn't close - ### Requirement: The video screen survives process death After the system ends the app's process in the background while the video screen shows, the user SHALL come back to the same video's screen, which loads the details again. Going back from it SHALL show the screen it was opened from. @@ -136,7 +121,7 @@ After the system ends the app's process in the background while the video screen - **THEN** the screen says that the same video is loading, then shows its details, and the video waits for the user to press play at the position it had when the user last left the app ### Requirement: The video screen fits any window -On a phone the screen SHALL stay in portrait. In any wider window, such as a tablet, an unfolded foldable, landscape on a large screen or split screen, the screen SHALL keep its content in one centered column of readable width, and the background SHALL fill the window. No text or control SHALL sit under the system bars or the display cutout. +On a phone the screen SHALL stay in portrait, except in fullscreen. In any wider window, such as a tablet, an unfolded foldable, landscape on a large screen or split screen, the screen SHALL keep its content in one centered column of readable width, and the background SHALL fill the window. No text or control SHALL sit under the system bars or the display cutout. #### Scenario: A tablet in landscape - **WHEN** the screen shows a video's details on a tablet in landscape @@ -150,9 +135,13 @@ The app SHALL never log the video's ID, title, channel name or description. It S - **THEN** the app's log lines hold no ID, title, channel name or description, and the failure's line names only the call and its category #### Scenario: After closing the video screen -- **WHEN** the user closes the video screen +- **WHEN** the user minimizes the video screen, then closes the mini player - **THEN** Android's media session no longer holds the video's title or channel name +#### Scenario: After minimizing a video that couldn't start +- **WHEN** the user minimizes a video whose stream links failed to load +- **THEN** the playback service holds nothing about that video + ### Requirement: The video plays on the video screen The video screen SHALL show the video in a 16:9 area above the title, with a play and pause button, a seek bar, and the position and the length. Dragging the seek bar SHALL move playback to that point. While the player waits for data, the area SHALL show that it is loading. @@ -181,7 +170,7 @@ The video screen SHALL show the video in a 16:9 area above the title, with a pla - **THEN** the video pauses, and the button offers to play ### Requirement: Opening a video starts playing it -Opening a video SHALL start playing it from the start, or a live stream from its live edge, without a tap. A video screen that comes back after Android stopped its player in the background SHALL wait for the user to press play, at the position where it paused. One that comes back after the system ended the app's process SHALL wait for play at the position the screen saved when the user last left the app. +Opening a video SHALL start playing it from the start, or a live stream from its live edge, without a tap, unless the mini player already plays that video, which goes on as it is. A video screen that comes back after Android stopped its player in the background SHALL wait for the user to press play, at the position where it paused. One that comes back after the system ended the app's process SHALL wait for play at the position the screen saved when the user last left the app. #### Scenario: Opening a video - **WHEN** the user opens a video from search @@ -294,7 +283,7 @@ The player SHALL fetch video only through the YouTube layer, which SHALL send it - **THEN** the session's error message is the same constant text for every failure ### Requirement: The sound plays on in the background -Leaving the app while a video plays, such as with the home gesture or by switching apps, and turning the screen off, SHALL keep the sound playing. Coming back SHALL show the same video playing at its current position. A configuration change, such as a resized window or a theme change, SHALL NOT stop, pause or restart playback. +Leaving the app while a video plays, such as with the home gesture or by switching apps, and turning the screen off, SHALL keep the sound playing. Coming back SHALL show the same video playing at its current position, on the video screen or in the mini player. A configuration change, such as a resized window or a theme change, SHALL NOT stop, pause or restart playback. #### Scenario: Going home - **WHEN** a video plays and the user goes to the home screen @@ -305,15 +294,15 @@ Leaving the app while a video plays, such as with the home gesture or by switchi - **THEN** the sound goes on the whole time #### Scenario: Paused in the background, back much later -- **WHEN** the user paused a video in the background, and Android stopped the player before the user came back -- **THEN** the video waits at the position where it paused, and plays on from it when the user presses play +- **WHEN** the user paused a video on the video screen in the background, and Android stopped the player before the user came back +- **THEN** the video screen waits at the position where it paused, and plays on from it when the user presses play #### Scenario: Resizing the window - **WHEN** a video plays in split screen and the user resizes the window - **THEN** it keeps playing without a pause ### Requirement: The picture turns off while the app can't be seen -While no Dewfall screen can be seen, the player SHALL decode no picture, and SHALL NOT fetch a picture that comes in its own file. When the app shows again, the picture SHALL come back at the current position, after a short load that may pause the sound. A file that holds both sound and picture, and a live stream, whose segments hold both, still load the picture's bytes with the sound. +While no Dewfall screen can be seen, the player SHALL decode no picture, and SHALL NOT fetch a picture that comes in its own file. When the app shows the video screen again, the picture SHALL come back at the current position, after a short load that may pause the sound. When the app shows again with the video minimized, the picture SHALL stay off until the video screen opens. A file that holds both sound and picture, and a live stream, whose segments hold both, still load the picture's bytes with the sound. #### Scenario: Data in the background - **WHEN** a video whose sound and picture come in separate files plays at 1080p, and the user goes to the home screen @@ -324,41 +313,38 @@ While no Dewfall screen can be seen, the player SHALL decode no picture, and SHA - **THEN** the sound goes on, and no picture is decoded until the user comes back #### Scenario: Coming back -- **WHEN** the user comes back to a video that played on in the background +- **WHEN** the user comes back to the video screen of a video that played on in the background - **THEN** the picture shows again at the current position +#### Scenario: Coming back to the mini player +- **WHEN** the user minimized a playing video, went to the home screen, and comes back +- **THEN** the mini player shows the video playing on, and the player fetches only the sound until the video screen opens + ### Requirement: A video that hasn't started waits -When the user leaves the app after opening a video and before it has started playing, the video SHALL NOT start in the background. Coming back SHALL show it paused, waiting for the user to press play. +When the user leaves the app after opening a video and before it has started playing, from the video screen or with the video minimized, the video SHALL NOT start in the background. Coming back SHALL show it paused, waiting for the user to press play. #### Scenario: Leaving while the video loads - **WHEN** the user opens a video and goes to the home screen before it starts playing - **THEN** no sound plays, and when the user comes back, the video waits for play -### Requirement: Closing the video screen or removing the app stops playback -Closing the video screen SHALL stop playback and remove the media notification. Removing Dewfall from the recent apps SHALL do the same. - -#### Scenario: Closing the video screen -- **WHEN** a video plays and the user closes its screen -- **THEN** the sound stops, the notification goes away, and search shows as it was - -#### Scenario: Removing the app from the recent apps -- **WHEN** a video plays in the background and the user removes Dewfall from the recent apps -- **THEN** the sound stops and the notification goes away +#### Scenario: Leaving from the mini player while the video loads +- **WHEN** the user opens a video, minimizes it and goes to the home screen before it starts playing +- **THEN** no sound plays, and when the user comes back, the mini player offers to play it ### Requirement: A media notification shows while a video plays -While a video plays, and while it is paused until Android stops the player, the app SHALL show a media notification with a play and pause button, and the video's title and channel name once its details have loaded. It SHALL show no picture. Tapping it SHALL open the app as it was. While the video plays, the user SHALL NOT be able to dismiss it. +While a video plays, and while it is paused until Android stops the player, the app SHALL show a media notification with a play and pause button, and the video's title and channel name once its details have loaded. It SHALL show no picture. Tapping it SHALL open the app as it was, on the video screen or on the screen under the mini player. While the video plays, the user SHALL NOT be able to dismiss it. #### Scenario: Playing in the background - **WHEN** a video plays and the user goes to the home screen - **THEN** a notification shows the video's title and channel name with a pause button, and the pause button pauses the video #### Scenario: Playing in the app -- **WHEN** a video plays on the video screen +- **WHEN** a video plays on the video screen, or in the mini player - **THEN** the notification shows too #### Scenario: Tapping the notification - **WHEN** a video plays in the background and the user taps its notification -- **THEN** Dewfall opens on the video screen as it was, and the video plays on +- **THEN** Dewfall opens as it was, on the video screen or on Search YouTube with the mini player, and the video plays on #### Scenario: Details that failed - **WHEN** a video plays but its details failed to load @@ -374,7 +360,7 @@ While a video plays, and while it is paused until Android stops the player, the #### Scenario: A failure in the background - **WHEN** a video plays in the background and the player runs out of data because the network went away -- **THEN** the notification stays with a play button, which tries again from the same position, and once the video plays again the video screen shows it playing, with no failure +- **THEN** the notification stays with a play button, which tries again from the same position, and once the video plays again the video screen, or the mini player when the video is minimized, shows it playing, with no failure ### Requirement: Headset and Bluetooth buttons play and pause While Dewfall's player runs, the play and pause buttons of a headset, a Bluetooth device and the notification SHALL play and pause the video. Next, previous, fast forward and rewind SHALL do nothing. After Android stopped the player, or ended the app's process, a media button SHALL NOT start the app or play anything. @@ -409,3 +395,276 @@ Besides Dewfall itself, only Android's own components that may control media, su #### Scenario: An app asks for another item - **WHEN** an app with notification access asks the player to play another item - **THEN** the player refuses, and the video plays on + +### Requirement: Minimizing goes back +The video screen SHALL have a minimize button at the top, named for screen readers. The minimize button and the system's back gesture SHALL return to the screen the video was opened from, as that screen was, and SHALL leave playback as it is: a playing video plays on, and a paused one stays paused. + +#### Scenario: Minimizing after a search +- **WHEN** a video plays, the user opened it from search results, and taps the minimize button +- **THEN** Search YouTube shows the same text and results, sends no new search, and the video plays on in the mini player + +#### Scenario: The back gesture +- **WHEN** the user makes the system's back gesture on the video screen +- **THEN** the app goes back as the minimize button does + +#### Scenario: A double tap on minimize +- **WHEN** the user taps the minimize button twice quickly, or taps it during the back gesture +- **THEN** the app goes back once, to the screen the video was opened from, and doesn't close + +#### Scenario: Minimizing a paused video +- **WHEN** the user pauses a video and taps the minimize button +- **THEN** the video stays paused, and the mini player offers to play it + +#### Scenario: Minimizing while the video loads +- **WHEN** the user opens a video and taps the minimize button before it starts playing +- **THEN** it starts playing, and the mini player shows it + +### Requirement: The mini player shows while a video is minimized +While the player has a video and no video screen shows, the app SHALL show a mini player at the bottom of the screen. It SHALL show for a video that plays, is paused, waits for data, has ended or failed while playing. It SHALL go away when playback stops, or when Android stops the player. + +#### Scenario: A minimized video +- **WHEN** a video plays and the user minimizes it +- **THEN** the mini player shows at the bottom of Search YouTube + +#### Scenario: The video screen +- **WHEN** the video screen shows +- **THEN** no mini player shows + +#### Scenario: No video +- **WHEN** the app opens and nothing has played +- **THEN** no mini player shows + +#### Scenario: A video that couldn't start +- **WHEN** the user minimizes a video whose stream links failed to load, so the player has no video +- **THEN** no mini player shows + +#### Scenario: After the process ended +- **WHEN** the system ended the app's process while the mini player showed, and the user returns to the app +- **THEN** no mini player shows, and nothing plays + +#### Scenario: Paused and minimized in the background, back much later +- **WHEN** the user paused a minimized video, went to the home screen, and Android stopped the player before the user came back +- **THEN** no mini player shows, and opening the video again starts it from the start + +### Requirement: The mini player shows the video and how far it played +The mini player SHALL show the video's title and channel name once the video's details have loaded, and "Now playing" in the title's place until then or when they failed. The title SHALL wrap and never be cut off. A line along its top edge SHALL show how much of the video has played, hidden from screen readers. A live stream SHALL have no line. + +#### Scenario: A video with its details +- **WHEN** "How reading rooms were lit before electric lamps" by Larkspur Lectures plays in the mini player +- **THEN** the mini player shows that title and the channel name, and its line shows how much has played + +#### Scenario: Details that failed +- **WHEN** a video plays in the mini player, but its details failed to load +- **THEN** the mini player shows "Now playing", with no channel name + +#### Scenario: A long title at the largest font size +- **WHEN** the title is longer than one line and the font size is the largest +- **THEN** the title wraps onto more lines, and nothing is cut off + +#### Scenario: A live stream +- **WHEN** a live stream plays in the mini player +- **THEN** it shows no progress line + +### Requirement: The mini player plays and pauses +The mini player SHALL have a play and pause button, named for screen readers, that plays and pauses the video. At the end of a video it SHALL offer to play it again from the start. After a failure while playing, play SHALL try again from the same position. + +#### Scenario: Pausing from the mini player +- **WHEN** a video plays in the mini player and the user taps its button +- **THEN** the video pauses, and the button offers to play + +#### Scenario: The end +- **WHEN** a video in the mini player plays to its end and the user taps its button +- **THEN** it plays again from the start + +#### Scenario: After a failure +- **WHEN** the network went away while a video played in the mini player, and the user taps play with the network back +- **THEN** the video plays on from where it stopped + +#### Scenario: A failure says nothing in the mini player +- **WHEN** a video fails while it plays in the mini player +- **THEN** the mini player offers play and gives no reason, and the video screen says why once the user opens it + +### Requirement: Tapping the mini player opens the video +Tapping the mini player's title SHALL open the video screen for its video, which SHALL go on with the playback as it is, without starting it again, and SHALL load the video's details. The mini player SHALL tell screen readers that the tap opens the video. + +#### Scenario: Opening a playing video +- **WHEN** a video plays in the mini player at 18:24 and the user taps its title +- **THEN** the video screen opens and the video plays on from 18:24, and the app asks YouTube for its details once and for no new stream links + +#### Scenario: Opening a paused video +- **WHEN** the mini player's video is paused and the user taps its title +- **THEN** the video screen shows it paused at the same position + +### Requirement: Opening the video that already plays goes on with it +Opening, from search, the video that the mini player plays SHALL open its video screen and go on with that playback, as tapping the mini player does. Opening another video SHALL replace it, and start the new one from the start. + +#### Scenario: The same video from search +- **WHEN** a video plays in the mini player and the user opens the same video from search results +- **THEN** the video screen shows it playing on from where it was + +#### Scenario: Another video from search +- **WHEN** a video plays in the mini player and the user opens another video from search results +- **THEN** the first video stops, and the new one starts playing from the start + +### Requirement: The mini player fits any window +The mini player's background SHALL reach the window's bottom edge, behind the navigation bar, and its text and buttons SHALL sit above the system bars and clear of the display cutout. In a wider window its content SHALL sit in one centered column of readable width. The screen above it SHALL end at its top edge, so nothing is hidden behind it. + +#### Scenario: The end of the search results +- **WHEN** the mini player shows and the user scrolls Search YouTube's results to the end +- **THEN** the last result sits fully above the mini player + +#### Scenario: A tablet in landscape +- **WHEN** the mini player shows on a tablet in landscape +- **THEN** its background fills the window's width, and its title and buttons sit in one centered column no wider than the readable width + +#### Scenario: The keyboard +- **WHEN** the mini player shows and the user types in Search YouTube's field +- **THEN** the keyboard covers the mini player, and the search results above it end above the keyboard + +### Requirement: Closing the mini player or removing the app stops playback +The mini player SHALL have a close button, named for screen readers. Closing it SHALL stop playback, remove the media notification, and hide the mini player. Removing Dewfall from the recent apps SHALL do the same. Closing the video screen by minimizing it SHALL NOT stop playback. + +#### Scenario: Closing the mini player +- **WHEN** a video plays in the mini player and the user taps its close button +- **THEN** the sound stops, the notification goes away, the mini player goes away, and the screen under it shows as it was + +#### Scenario: Removing the app from the recent apps +- **WHEN** a video plays in the background and the user removes Dewfall from the recent apps +- **THEN** the sound stops and the notification goes away + +### Requirement: The picture turns off while minimized +While a video is minimized, the player SHALL decode no picture, and SHALL NOT fetch a picture that comes in its own file, as while the app can't be seen. Opening the video screen again SHALL bring the picture back at the current position, after a short load that may pause the sound. + +#### Scenario: Data while minimized +- **WHEN** a video whose sound and picture come in separate files plays at 1080p, and the user minimizes it +- **THEN** the player fetches only the sound until the video screen opens again + +#### Scenario: Opening it again +- **WHEN** the user opens the minimized video from the mini player +- **THEN** the picture shows again at the current position + +### Requirement: The video can play in fullscreen +The video screen's controls SHALL have a fullscreen button, named for screen readers, while the player is connected. Fullscreen SHALL show the video as large as the window allows, keeping its shape, on black. It SHALL use the dark color scheme in light mode too, and show the system bars only while its controls show, or for a moment after a swipe from the screen's edge. The screen SHALL stay on while the video plays. + +#### Scenario: Entering fullscreen +- **WHEN** a video plays on the video screen and the user taps the fullscreen button +- **THEN** the video fills the screen in dark colors and plays on without a pause, and the system bars hide when the controls do + +#### Scenario: Light mode +- **WHEN** the phone is in light mode and the user enters fullscreen +- **THEN** fullscreen uses the dark color scheme + +#### Scenario: A system bar for a moment +- **WHEN** the controls are hidden and the user swipes from the screen's edge in fullscreen +- **THEN** the system bars show for a moment over the video, and hide again + +### Requirement: A phone turns to landscape in fullscreen +On a phone, entering fullscreen SHALL turn the screen to landscape, either way round as the phone's rotation setting allows, and leaving it SHALL turn the screen back to portrait. Where Android ignores an app's orientation, such as on a tablet, an unfolded foldable or in split screen, fullscreen SHALL keep the window's shape. Turning the phone SHALL NOT enter or leave fullscreen. + +#### Scenario: A phone +- **WHEN** the user enters fullscreen on a phone held in portrait +- **THEN** the screen turns to landscape, and the video plays on without a pause + +#### Scenario: A tablet in portrait +- **WHEN** the user enters fullscreen on a tablet in portrait +- **THEN** fullscreen fills the window in portrait, with black above and below the video + +#### Scenario: Turning the phone on the video screen +- **WHEN** the user turns a phone to landscape on the video screen +- **THEN** the video screen stays in portrait, and doesn't enter fullscreen + +### Requirement: Fullscreen has its own controls +Fullscreen SHALL show the title and channel name at the top, once the details have loaded, and at the bottom the play and pause button, the position and the length, the seek bar and an exit button, each named for screen readers. A live stream SHALL say "Live" in place of the seek bar and the times. Loading and failures SHALL show as on the video screen. The title SHALL wrap and never be cut off. + +#### Scenario: Controls in fullscreen +- **WHEN** a video plays in fullscreen +- **THEN** the title and channel name show at the top, and the button, "18:24 / 1:14:02", the seek bar and the exit button at the bottom + +#### Scenario: Seeking in fullscreen +- **WHEN** the user drags the fullscreen seek bar to the middle of a video +- **THEN** playback goes on from the middle + +#### Scenario: A failure in fullscreen +- **WHEN** the network goes away in fullscreen and the player runs out of data +- **THEN** fullscreen says that YouTube can't be reached, with "Try again" and the exit button + +#### Scenario: A long title at the largest font size in fullscreen +- **WHEN** the title is long and the font size is the largest +- **THEN** the title wraps onto more lines in its box, and nothing is cut off + +### Requirement: Fullscreen keeps clear of the system bars and the display cutout +In fullscreen, no text or control SHALL sit under the system bars or the display cutout, whether the bars show or not, so showing or hiding the bars never moves the title or the controls. No picture SHALL sit under the display cutout. + +#### Scenario: A display cutout +- **WHEN** fullscreen shows in landscape on a phone with a display cutout +- **THEN** no text, control or picture sits under the cutout + +#### Scenario: The system bars over fullscreen +- **WHEN** the system bars show in fullscreen in landscape with three-button navigation, after a tap or a swipe +- **THEN** they cover none of the title and controls, the exit button can be tapped, and nothing moves + +### Requirement: Fullscreen controls hide while the video plays +While a video plays in fullscreen, the title, the controls and the system bars SHALL hide 3 seconds after the user last touched the screen or pressed a key, or later when the accessibility settings ask for more time. A tap on the video SHALL show them, and a tap while they show SHALL hide them. Whenever the video isn't playing, and while a screen reader is on, they SHALL show, even if they were hidden. When it plays again they SHALL show, and hide 3 seconds later. + +#### Scenario: Watching +- **WHEN** a video plays in fullscreen and the user doesn't touch the screen for 3 seconds +- **THEN** the title, the controls and the system bars hide, and the video plays on + +#### Scenario: Showing them again +- **WHEN** the controls are hidden and the user taps the video +- **THEN** the title, the controls and the system bars show again + +#### Scenario: Hiding them with a tap +- **WHEN** a video plays in fullscreen with the controls showing and the user taps the video +- **THEN** the title, the controls and the system bars hide + +#### Scenario: Paused +- **WHEN** the user pauses a video in fullscreen +- **THEN** the title and the controls stay, and a tap on the video doesn't hide them + +#### Scenario: Paused from elsewhere while hidden +- **WHEN** the controls are hidden and the video pauses from a headset, the notification or a phone call +- **THEN** the title, the controls and the system bars show + +#### Scenario: Waiting for data while hidden +- **WHEN** the controls are hidden and the player runs out of data +- **THEN** the title and the controls show, with the loading sign, until it plays again + +#### Scenario: The end while hidden +- **WHEN** the controls are hidden and the video plays to its end +- **THEN** the title and the controls show, and the button offers to play it again + +#### Scenario: A failure while hidden +- **WHEN** the controls are hidden and the video fails +- **THEN** the failure shows with the exit button + +#### Scenario: Playing again +- **WHEN** the user presses play in fullscreen +- **THEN** the controls stay, and hide 3 seconds after the last touch + +#### Scenario: A key press +- **WHEN** a video plays in fullscreen and the user presses a key on a hardware keyboard +- **THEN** the controls show, and the 3 seconds start again + +#### Scenario: More time to act +- **WHEN** the phone's accessibility setting for time to take action is 1 minute +- **THEN** the controls hide only after 1 minute without a touch + +#### Scenario: A screen reader +- **WHEN** TalkBack is on, or turns on, while a video plays in fullscreen +- **THEN** the title and the controls show and stay + +### Requirement: Leaving fullscreen returns to the video screen +The exit button and the system's back gesture SHALL leave fullscreen and return to the video screen, with the system bars and the screen's own colors, and playback SHALL go on without a pause. + +#### Scenario: The exit button +- **WHEN** a video plays in fullscreen and the user taps the exit button +- **THEN** the video screen shows in portrait, with the system bars, and the video plays on + +#### Scenario: The back gesture in fullscreen +- **WHEN** the user makes the system's back gesture in fullscreen +- **THEN** fullscreen ends as with the exit button, and the video screen stays open + +#### Scenario: Fullscreen after the process ended +- **WHEN** the system ended the app's process while a video showed in fullscreen on a phone, and the user returns to it +- **THEN** fullscreen shows again, waiting for play at the saved position, and leaving it turns the phone back to portrait