diff --git a/.gitignore b/.gitignore index beae9ac..91d7ba2 100644 --- a/.gitignore +++ b/.gitignore @@ -50,3 +50,4 @@ app.*.map.json !ios/Podfile.lock # Widget Preview related .widget_preview/ +.claude/ diff --git a/CLAUDE.md b/CLAUDE.md index 56d7d61..8d2d14d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -57,13 +57,13 @@ lib/ **GraphQL types (codegen).** The documents live in `lib/core/api/documents/*.graphql`; graphql_codegen (`build.yaml`) checks them against `stash_schema.graphql` and generates `Query$…`/`Mutation$…`/`Fragment$…` classes, `Options$…` and `Variables$…`, plus `Input$…`/`Enum$…` for the whole schema. The generated files are committed (like `lib/l10n/gen`), excluded from analysis and marked generated in `.gitattributes`. Models have factories from the generated fragments (`Scene.fromFields`, `Studio.fromRef`, …) instead of `fromJson`; shared selections are fragments in `refs.graphql`. Keep `addTypename: true`: the generated parsers resolve fragments by `__typename`. The client caches nothing (`stashGraphQLPolicies`, `FetchPolicy.noCache` for queries and mutations): `networkOnly` still wrote every response into the normalized cache, which grew with every page, filter and random seed and was never read; `repository_graphql_test.dart` checks the cache stays empty. Filters and edit changes are still built as maps (`SceneQuery.toSceneFilter`, the forms' `_diff`); `StashRepository._input` turns them into the input types and asserts in debug/tests that every key is in the schema (`fitsInput`), and `convertSavedSceneFilter` drops saved criteria that don't fit `Input$SceneFilterType`. Tests build models and fake responses with `test/fixtures.dart` (complete results with `__typename`s); `test/data/repository_graphql_test.dart` runs the repository through a real client and cache. The schema is the newest Stash's, so compatibility with older servers is not checked at build time. -**Paginated lists.** `sceneListProvider`, `performerListProvider` and `studioListProvider` are auto-dispose family `PagedNotifier`s keyed by query objects (`SceneQuery`, `PerformerQuery`, `StudioQuery`). These query objects must keep value equality. UI code reads paged lists through `.current` (`PagedValue` extension), not `.value`. On a server switch the lists rebuild (`isReloading`), and `.value` would keep showing the previous server's items, or would hide a failed load behind them. A reload of the same list (pull-to-refresh, the connection banner's `reloadLists`) that fails with a network error keeps the loaded items as data with `PagedState.refreshError` (STATE-1; the banner explains it), but only when `PagedState.origin` (server and paging mode) still matches, so after a server switch the error shows instead; server-reported errors still replace the list by an `ErrorView`. The random sort uses a `random_` sort field so pages stay stable, and the seed is 0 for every other sort. To get an infinite, refreshable list with sort chips, use `SceneFeedView`, or compose `RefreshIndicator`, `LoadMoreListener`, `CustomScrollView` and `PagedSliver` yourself. After a failed page, scrolling doesn't retry; `PagedSliver`'s `onLoadMore` (its "try again" button) passes `loadMore(retry: true)`. `pagingModeProvider` (settings) switches all paged lists to numbered pages: `loadMore` then does nothing, `PagedSliver` shows a `PageBar` driving `PagedNotifier.goToPage` (pass `onGoToPage`), and changing the mode rebuilds the lists. The first page loads as skeletons (`widgets/skeleton.dart`, `PagedSliver(skeletonBuilder:)`), not a spinner. `SceneFeedView(pinChips: true)` pins the filter, sort and saved-filter chips under the home app bar (shelves go into `belowChipsSlivers`); `unfilteredEmptyView` replaces the empty message only without filters or search term (home: "scan your library" with a button to the server tasks). `EmptyView` takes an optional action. +**Paginated lists.** `sceneListProvider`, `performerListProvider` and `studioListProvider` are auto-dispose family `PagedNotifier`s keyed by query objects (`SceneQuery`, `PerformerQuery`, `StudioQuery`). These query objects must keep value equality. UI code reads paged lists through `.current` (`PagedValue` extension), not `.value`. On a server switch the lists rebuild (`isReloading`), and `.value` would keep showing the previous server's items, or would hide a failed load behind them. A reload of the same list (pull-to-refresh, the connection banner's `reloadLists`) that fails with a network error keeps the loaded items as data with `PagedState.refreshError` (STATE-1; the banner explains it), but only when `PagedState.origin` (server and paging mode) still matches, so after a server switch the error shows instead; server-reported errors still replace the list by an `ErrorView`. The random sort uses a `random_` sort field so pages stay stable, and the seed is 0 for every other sort. To get an infinite, refreshable list with sort chips, use `SceneFeedView`, or compose `RefreshIndicator`, `LoadMoreListener`, `CustomScrollView` and `PagedSliver` yourself. After a failed page, scrolling doesn't retry; `PagedSliver`'s `onLoadMore` (its "try again" button) passes `loadMore(retry: true)`. `pagingModeProvider` (settings) switches all paged lists to numbered pages: `loadMore` then does nothing, `PagedSliver` shows a `PageBar` driving `PagedNotifier.goToPage` (pass `onGoToPage`), and changing the mode rebuilds the lists. The first page loads as skeletons (`widgets/skeleton.dart`, `PagedSliver(skeletonBuilder:)`), not a spinner. `SceneFeedView` pins the filter, sort and saved-filter chips (`pinChips`, on by default; under the home app bar, below a channel's tab bar; shelves go into `belowChipsSlivers`), and the other lists pin their chip row with `PinnedBar` (`widgets/chip_bar.dart`); `unfilteredEmptyView` replaces the empty message only without filters or search term (home: "scan your library" with a button to the server tasks). `EmptyView` takes an optional action. `LoadMoreListener` also wraps its list in `ScrollToTop` (`widgets/scroll_to_top.dart`): a "Back to top" pill at the bottom center once the list is 1.5 screens down, switched off in Settings → Appearance (`scrollToTopProvider`) or per list (`scrollToTop: false`, sheets). The tag page passes `SceneQuery.tagId` (added to the filter sheet's tags, so the filter can't remove it) and is `filterable`. -**Shell and navigation.** `AppShell` holds an `IndexedStack` with one nested `Navigator` per `AppTab`, with the player's `SlidingPanel` on top. The bottom `NavigationBar` collapses as the player expands, driven by `miniplayerHeightProvider`. `IndexedStack` keeps hidden tabs ticking, so `_TabTickers` turns `TickerMode` off for every tab but the shown one, and for that one too while the player is fully open (animated images and shimmers pause). `ShellLayout` (`features/shell/shell_layout.dart`, NAV-4) picks the navigation by width (`ShellNavigation.forWidth`): the bar below `kWideLayoutBreakpoint`, from there a `NavigationRail` on the left (also on phones in landscape; labels clamped to 1.3× text), extended with labels beside the icons from `kExtendedRailBreakpoint` (1240). The content sits right of the rail (which takes the side's safe area), the collapsed miniplayer at the bottom of the content above the home indicator; while expanding, the panel's left edge slides over the rail (its `MediaQuery` width is the space it has), so the expanded player covers the rail and the content never resizes. The shorts' fullscreen hides the rail like the bar. The bar shows only the tabs in `navBarConfigProvider` (`features/shell/nav_bar_config.dart`, configured in the settings, stored for all servers); `currentTabProvider` starts on the first one and falls back to it when its tab is hidden. Each `LibrarySection` (`features/library/library_page.dart`) is an `AppTab` of its own (`AppTab.section`, shown by `LibrarySectionPage`); only `LibrarySection.media` (scenes, images, galleries) are the library's text-only sub-tabs, the others are on the "You" page. A new `AppTab` needs a root page in `AppShell.rootPage` and should be hidden in `NavBarConfig.standard` (home, shorts, search, library, you). `AppTab.you` (`YouPage`, `features/you/`: shelves for history, watch later, groups and markers with "See all", then stats, performers, studios, tags, the views not in the bar, server tasks and settings; picked views open inside that tab) is `NavBarConfig.alwaysShown` and last by default; it replaced the former `all` tab, and a stored `all` becomes `you` at its place. The bar has at most `NavBarConfig.maxVisible` (5) tabs and stored bars with more are `fitted()`. The tab pages' app bars end with `ServerAvatarButton` (`features/auth/server_avatar.dart`, the active server's initial), which opens the account sheet: switch server, server tasks and settings. The settings are not a tab but a `showCupertinoSheet` over the whole app (`openSettings` in `settings_button.dart`, from the account sheet and the "You" page): closed with its X or by swiping down, with its own nested navigator, so its sub-pages push with `Navigator.of(context)`, not `openPage`. `settingsOpenProvider` tells the shorts to pause while it is open. Re-selecting the current tab (`reselectTab`) pops back to its root, or there scrolls to the top: each tab root gets its own `PrimaryScrollController` (`tabScrollControllersProvider`), so its lists must not bring a controller of their own if they should follow. To navigate, use `openPage`, `openPerformer`, `openStudio` or `openSearch` from `features/shell/navigation.dart`. They push onto the current tab's navigator and collapse the player, and they also work from inside the player, which sits outside the tab navigators. Settings open on a page of categories (`settings_page.dart`) whose sub-pages live in `settings_categories.dart`; "Remove this server" is only on the server page. `openSettings(context, ref, initialPage:)` opens the sheet with a sub-page already pushed (home's empty state opens the server tasks that way). Settings picked from a menu use `SettingsDropdownTile`, which moves the menu under the title when it would take more than half the row (large text). `test/features/text_scale_test.dart` pumps the main pages and the shell's bar/rail at 1.0×, 1.5× and 2.0× text on a 360×780 phone (plus 320×640 and a 1024×768 tablet) and fails on layout errors (A11Y-3); its `_knownOverflows` lists the ones not fixed yet. Optional tab `AppTab.subscriptions`, labelled "Favorites" (`features/subscriptions/`): only performers with Stash's `favorite` flag (ratings play no part). Their avatars (dot = new since the last visit) are a selector, "All" first: a tap shows only that performer's scenes (newest first, with "View channel"; tapping it again goes back to all), a long press opens the channel; "All" is `SceneQuery.newFromFavorites` (shared with home's shelf). The feed is keyed by the selection, so it starts at the top. `LastVisitNotifier` (`last_visit:`) is the baseline for home's "N new videos since your last visit" banner (`SceneQuery.createdAfter`); `JobFinishedListener` reports server jobs the user started once they end. Home's dice plays a random scene. Scenes are added to groups through `showAddToGroupSheet` (scene menu, player's More sheet). External links go through `openExternalUrl` (`core/utils/external_links.dart`, url_launcher; never with the API key); the description sheet has "Open in Stash" (not for the demo). +**Shell and navigation.** `AppShell` holds an `IndexedStack` with one nested `Navigator` per `AppTab`, with the player's `SlidingPanel` on top. The bottom `NavigationBar` collapses as the player expands, driven by `miniplayerHeightProvider`. `IndexedStack` keeps hidden tabs ticking, so `_TabTickers` turns `TickerMode` off for every tab but the shown one, and for that one too while the player is fully open (animated images and shimmers pause). `ShellLayout` (`features/shell/shell_layout.dart`, NAV-4) picks the navigation by width (`ShellNavigation.forWidth`): the bar below `kWideLayoutBreakpoint`, from there a `NavigationRail` on the left (also on phones in landscape; labels clamped to 1.3× text), extended with labels beside the icons from `kExtendedRailBreakpoint` (1240). The content sits right of the rail (which takes the side's safe area), the collapsed miniplayer at the bottom of the content above the home indicator; while expanding, the panel's left edge slides over the rail (its `MediaQuery` width is the space it has), so the expanded player covers the rail and the content never resizes. The shorts' fullscreen hides the rail like the bar. The bar shows only the tabs in `navBarConfigProvider` (`features/shell/nav_bar_config.dart`, configured in the settings, stored for all servers); `currentTabProvider` starts on the first one and falls back to it when its tab is hidden. Each `LibrarySection` (`features/library/library_page.dart`) is an `AppTab` of its own (`AppTab.section`, shown by `LibrarySectionPage`); only `LibrarySection.media` (scenes, images, galleries) are the library's text-only sub-tabs, the others are on the "You" page. A new `AppTab` needs a root page in `AppShell.rootPage` and should be hidden in `NavBarConfig.standard` (home, shorts, search, library, you). `AppTab.you` (`YouPage`, `features/you/`: shelves for history, watch later, groups and markers with "See all", then stats, performers, studios, tags, the views not in the bar, server tasks and settings; picked views open inside that tab) is `NavBarConfig.alwaysShown` and last by default (a double tap on it in the bar or rail opens the server switcher, `TabDoubleTap`); it replaced the former `all` tab, and a stored `all` becomes `you` at its place. The bar has at most `NavBarConfig.maxVisible` (5) tabs and stored bars with more are `fitted()`. The tab pages' app bars end with `ServerAvatarButton` (`features/auth/server_avatar.dart`, the active server's initial), which opens the account sheet: switch server, server tasks and settings. The settings are not a tab but a `showCupertinoSheet` over the whole app (`openSettings` in `settings_button.dart`, from the account sheet and the "You" page): closed with its X or by swiping down, with its own nested navigator, so its sub-pages push with `Navigator.of(context)`, not `openPage`. `settingsOpenProvider` tells the shorts to pause while it is open. Re-selecting the current tab (`reselectTab`) pops back to its root, or there scrolls to the top: each tab root gets its own `PrimaryScrollController` (`tabScrollControllersProvider`), so its lists must not bring a controller of their own if they should follow. To navigate, use `openPage`, `openPerformer`, `openStudio` or `openSearch` from `features/shell/navigation.dart`. They push onto the current tab's navigator and collapse the player, and they also work from inside the player, which sits outside the tab navigators. Settings open on a page of categories (`settings_page.dart`) whose sub-pages live in `settings_categories.dart`; "Remove this server" is only on the server page. `openSettings(context, ref, initialPage:)` opens the sheet with a sub-page already pushed (home's empty state opens the server tasks that way). Settings picked from a menu use `SettingsDropdownTile`, which moves the menu under the title when it would take more than half the row (large text). `test/features/text_scale_test.dart` pumps the main pages and the shell's bar/rail at 1.0×, 1.5× and 2.0× text on a 360×780 phone (plus 320×640 and a 1024×768 tablet) and fails on layout errors (A11Y-3); its `_knownOverflows` lists the ones not fixed yet. Optional tab `AppTab.subscriptions`, labelled "Favorites" (`features/subscriptions/`): only performers with Stash's `favorite` flag (ratings play no part). Their avatars (dot = new since the last visit) are a selector, "All" first: a tap shows only that performer's scenes (newest first, with "View channel"; tapping it again goes back to all), a double tap or long press opens the channel; "All" is `SceneQuery.newFromFavorites` (shared with home's shelf); a double tap on it, or "Show all" in the header, opens all favorite performers (`openAllFavorites`, `PerformersPage(initialSort: PerformerSort.favorites)`). The feed is keyed by the selection, so it starts at the top. `LastVisitNotifier` (`last_visit:`) is the baseline for home's "N new videos since your last visit" banner (`SceneQuery.createdAfter`); `JobFinishedListener` reports server jobs the user started once they end. Home's dice plays a random scene. Scenes are added to groups through `showAddToGroupSheet` (scene menu, player's More sheet). External links go through `openExternalUrl` (`core/utils/external_links.dart`, url_launcher; never with the API key); the description sheet has "Open in Stash" (not for the demo). **Player.** There is a single media_kit `Player` in `playerProvider`. `nowPlayingProvider.play(scene)` opens the stream with the auth headers, starting at the resume position, and expands the panel. `PlayerPanel` is a single layout that `PlayerTransition` interpolates between the mini bar and the expanded page (video, details, "Up next") based on the panel height. The one `PlayerVideo` instance stays in place, so it is never rebuilt mid-transition. The details are built while the panel rests (collapsed or open, never mid-animation) and then kept (hidden with `Visibility(maintainState:)` while collapsed), laid out at their expanded height and reused as one widget while only the height changes, so expanding and collapsing doesn't rebuild, relayout or reload "Up next" every frame. The video area follows the video's aspect ratio (`PlayerTransition.videoAspect`; portrait videos up to `maxVideoShare` of the panel). From `PlayerTransition.splitBreakpoint` (840 dp) the expanded video takes `splitShare` (half) of the width (`columnWidth`, `expandedWidth`), with `PlayerDetails(part: info)` below it and `part: list` ("Up next" or the queue) on the right; the right `Positioned` is always in the stack so the video never moves in the tree. Phones stay portrait everywhere, the player too (4.28): `AppOrientation` (`widgets/app_orientation.dart`; `AppOrientationScope` in `MaterialApp.builder` tells it whether the window is a phone's) allows only portrait on phones, all on tablets, and the fullscreen sets its orientations through `AppOrientation.turnTo`, which waits until the window has turned (never call `SystemChrome.setPreferredOrientations` elsewhere). On a phone `PlayerVideo` listens to `heldOrientationProvider` (`held_orientation.dart`, the `stash/device_orientation` event channel: Android's `OrientationEventListener` in `MainActivity`, iOS' UIDevice orientation in `DeviceOrientationStream`; `portrait`/`turnedLeft`/`turnedRight`, physical, both respect the system's rotation lock) for as long as it lives, not only while expanded: the panel isn't expanded for a moment while the screen turns, and listening anew reported the sideways hold at once, so leaving fullscreen by its button jumped right back in. A report counts once it held for 250 ms (held at an angle, the reports flip back and forth), and not while the app is locked or away (coming back reported turns that each opened another fullscreen; `enterPlayerFullscreen` also opens only one route, `playerFullscreenOpen`). Sideways in the open player with a wide video enters fullscreen (`fullscreenByRotation`), upright leaves it, and after leaving it while sideways a new turn counts only once the phone was upright. Tablets don't enter fullscreen by turning. Fullscreen goes through `enterPlayerFullscreen`/`exitPlayerFullscreen`/`togglePlayerFullscreen` (`fullscreen_route.dart`, a copy of media_kit's route without its own transition) and `FullscreenMorph` (`fullscreen_morph.dart`, in `MaterialApp.builder`): a second `Video` of the controller moves from the player's place (`inlineVideoRect`) to the fullscreen pose, turned by `HeldOrientation.uprightAngle` in a portrait window, while the app goes black; the screen then turns underneath (both landscape sides allowed, so the system picks the held one), where the pose already matches, and the morph goes. By default (`FullscreenMorph.curtainOnly`, both platforms) the app only fades to black (`cover`/`uncover`), turns underneath and fades back in, both ways: on iOS the morph's turn still showed, and the plain fade read best. The morph (kept, tested with `curtainOnlyOverride = false`) needs a turn without the system's rotation animation, which would turn the already turned picture once more: iOS' `RunnerViewController` disables it, Android's `MainActivity` sets `ROTATION_ANIMATION_JUMPCUT` on phones (no system animation on top of the app's fade; the old frame it stretches for a moment is black). Leaving, `_onExitFullscreen` shows the pose at once (also after the system's back), turns back and moves the video home. They need a context below the `Video`, so `PlayerVideo` keeps the controls' contexts (inline and fullscreen). A portrait video's extra height covers a spacer at the top of the details and shrinks as they scroll (`PlayerTransition.extraVideoHeight`). Pinch zoom (`video_zoom.dart`, 4.22/4.31) is a Flutter transform: `ZoomedVideo` (around the inline and the fullscreen `Video`) draws the video scaled 1–4× and panned, clipped to its box, and `ZoomCounter` (around the controls inside the `Video`) applies the inverse so the controls keep their size. mpv's `video-zoom` was dropped: it stays inside the video's rectangle, so the box's black bars never went. The scale grows continuously and sticks (±7 %) to 1× (the video's width or height fills the box) and to the scale where the video covers the box (`VideoZoom.coverScale`, `fill`: recomputed for every box, so it holds in fullscreen and when turning); the pan sticks to the center and the edges (`VideoZoom.panSnap`, both axes); each new snap gives a light tick (`VideoZoom.snaps`), and `ZoomSnapFeedback` (in the controls' stack, always there) shows it while pinching: the scale pill reads "Original"/"Fill" in the accent with a small pop when the scale sticks, thin guide lines (`VideoZoom.guideX`/`guideY`) where the pan sticks; no pop or fade with reduced motion; `NowPlayingNotifier.play` resets the pinch zoom for a new scene but keeps a fill. Both widgets always build the same tree (an identity transform at no zoom), so the `Video` is never remounted. Subtitles (4.32, `captions.dart`): `SceneDetails.captions` (`captions` and `paths.caption` of `FindSceneDetails`, url `…?lang=&type=`), the top bar's subtitle button opens `showCaptionSheet`, `selectCaption` adds the file with mpv's `sub-add` (`SubtitleTrack.uri`) and `preferredCaptionProvider` (stored language) switches them on for later scenes as soon as the file's duration is known; the demo serves generated WebVTT under `/demo/caption/` (en, de). The double-tap seek feedback is a half disc (`_SeekFeedback`, `_HalfDiscClipper`) over the outer 30 % of the tapped side, its text toward the edge; it fades in with the first tap and out after the sequence (`_feedbackFading` keeps it mounted meanwhile). On iOS, `RunnerViewController` (Main.storyboard) turns without UIKit's rotation animation, which stretched the video. Keep the panel's widget tree structurally stable and toggle behavior with flags. Don't pass media_kit's `NoVideoControls` to `Video`: since media_kit_video 2 it is `null`, which `Video` ignores on update, so the old controls would stay; `PlayerVideo` uses an empty builder instead. With `showControls`, `PlayerVideo` (`player_controls.dart`) wraps media_kit's `MaterialVideoControls` on both platforms, with double-tap seeking, the collapse button and the quality sheet. `sceneDetailsProvider` loads `sceneStreams`, scene markers and the file infos (`SceneFile`, shown by `FileInfoCard`) lazily per scene. Chapters appear as gaps in the controls' `PreviewSeekBar` and in `ChapterList`; there is deliberately no progress line under the expanded video. `preferredStreamProvider` stores the chosen stream label (from the HD button, or ` p` from the settings), `pickPreferredStream` matches it by format and height (the `resolution` URL parameter), and `play` only waits for the stream list when a preference is set. Playback errors: `playbackErrorProvider` counts mpv's `stream.error` only when playback hasn't moved on for 2 s (mpv also reports errors it recovers from); `_PlaybackErrorOverlay` and the mini bar offer `retry()` (`NowPlayingNotifier.reopen`) and the quality sheet. Failed casts go through `castFailureProvider` to a snack bar. Under the video, `PlayerDetails` shows title and meta (a tap opens the description sheet, `scene_description.dart`: description, tags, file info, edit scene), the channel row, one action bar (`SceneActions`: rating pill with `showRatingSheet`, O-counter pill with `showOCounterSheet` (−/+, no undo snack bar), watch later, marker, More with `showSceneMoreSheet`), performers, one line of tags (`SceneTagsRow`: as many as fit, then "+N" opening the description sheet), chapters, then Up next; sheet actions pop first and then act through the root navigator. Markers can be ranges on newer Stash (`end_seconds`): the end times come from the optional `SceneMarkerEnds`/`MarkerEnds` queries merged into the markers (a server error means unsupported and stops asking); ranges show as a tinted segment in the seek bar, "0:40–1:10" in the marker list and grid, and the add-marker sheet offers an end only when supported (`SceneDetails.markerRanges`). The list under the video is titled "Markers" (Stash has no chapters). A long press on a chapter or a markers-grid tile opens `showMarkerMenu` (`scene_actions.dart`; the grid adds play and play as loop): edit reuses `AddMarkerSheet(marker:)` and sends only changes (`StashRepository.updateMarker`, a map like the other forms; `end_seconds: null` removes the end), delete asks first (`confirmDeleteMarker`, `deleteMarker`); both reload the scene details and the marker lists. `SceneMarker`/`Marker` carry `ownTitle` and the primary `tag` for that. -**Player gestures.** The panel is our own `SlidingPanel` (`sliding_panel.dart`, replaced the unmaintained `miniplayer` package): collapsed, a tap expands it and a vertical drag follows the finger, snapping on release (`SlidingPanel.snapAfterDrag`) or dismissing below the bar; expanded, it takes no gestures, so taps belong to the video controls without a guard. media_kit's controls and the details list both claim vertical drags, so `DragToMinimize` reads raw pointer events and drives the panel through `SlidingPanelController.jumpTo`/`expand`/`collapse` (`miniplayerControllerProvider`; calls while no panel is mounted do nothing). Back while the player is open collapses it (`AppShell`'s `PopScope`). An expanded panel stays expanded when the window's height changes. That's also why the player's details have no pull-to-refresh. The player uses its own `StashVideoControls` instead of media_kit's, because media_kit's hide timer removed our seek bar mid-scrub. The controls take the fullscreen state and a toggle callback from media_kit's `VideoState`; buttons sit above the tap/double-tap gesture layer so they react without waiting for a double tap. Holding the video (`HoldDetector`, 250 ms) plays at 2× until released, and the speed button opens `showSpeedSheet` (mpv keeps the speed across files). mpv reports the position every frame, so `PreviewSeekBar` repaints its `SeekBarPainter` through a `ValueNotifier` (`progress`) and rebuilds only once a second (the spoken value). Their `PreviewSeekBar` shows sprite thumbnails (`scrubThumbnailsProvider`, parsed from Stash's WebVTT) while scrubbing. They load lazily: the controls stay mounted while hidden, so the bar reads the provider only once it is `visible` or touched, then precaches the sprite. `sceneDetailsProvider` and `scrubThumbnailsProvider` stay cached for 5 minutes without listeners (`Ref.cacheFor`), so collapsing and expanding the player doesn't refetch. On first use the controls show one-time gesture tips (`gesture_hints.dart`, `gesture_tips_seen`, resettable in Settings → Playback). In fullscreen a lock button (`TouchLockLayer`, `touch_lock.dart`) ignores all touches until its pill is held for 1 s; leaving fullscreen or a playback error unlocks. Chapters show the marker's screenshot (sprite frame as stand-in). The channel row has a favorite heart (performers; studios from Stash 0.25 through the optional `StudioFavorite` query). Channel pages put `ChannelFavoriteButton` (`FavoriteButton`, `StudioFavoriteButton`) and `ChannelRatingButton` (`features/channel/channel_rating.dart`) under the name: stars are saved through `channelRatingsProvider` (optimistic, `:`), a studio's come from the optional `StudioRating` query, and the picker is `showStarsSheet`, shared with the scenes' `showRatingSheet`. Double-tap seeking is a sequence like YouTube's: a double tap on the left/right third starts it and every further tap on that side within 700 ms extends it (5, 10, 20, 30, 40 s; `seekSequenceTotal`), counted from raw pointers so extending taps react at once; it also works while casting (tap areas over `CastingControls`) and not while locked. A tap on the other side starts a new sequence from one step; for 2 s after a seek (`_seekSettling`) a new sequence counts from the last target, since mpv (and a TV) still report the old position. Double-tap seeking is configurable per device (`seekSettingsProvider`, `seek_settings.dart`; Settings → Playback): on/off (off = single taps react without the double-tap delay), step 5/10/15/30 s, and cumulative (`SeekSettings.total`: step, then 2×step×(n−1), i.e. 5, 10, 20, 30, 40 s) or linear (one step per tap). +**Player gestures.** The panel is our own `SlidingPanel` (`sliding_panel.dart`, replaced the unmaintained `miniplayer` package): collapsed, a tap expands it and a vertical drag follows the finger, snapping on release (`SlidingPanel.snapAfterDrag`) or dismissing below the bar; expanded, it takes no gestures, so taps belong to the video controls without a guard. media_kit's controls and the details list both claim vertical drags, so `DragToMinimize` reads raw pointer events and drives the panel through `SlidingPanelController.jumpTo`/`expand`/`collapse` (`miniplayerControllerProvider`; calls while no panel is mounted do nothing). Back while the player is open collapses it (`AppShell`'s `PopScope`). An expanded panel stays expanded when the window's height changes. That's also why the player's details have no pull-to-refresh. The player uses its own `StashVideoControls` instead of media_kit's, because media_kit's hide timer removed our seek bar mid-scrub. The controls take the fullscreen state and a toggle callback from media_kit's `VideoState`; buttons sit above the tap/double-tap gesture layer so they react without waiting for a double tap. Holding the video (`HoldDetector`, 250 ms) plays at 2× until released, and the speed button opens `showSpeedSheet` (mpv keeps the speed across files). mpv reports the position every frame, so `PreviewSeekBar` repaints its `SeekBarPainter` through a `ValueNotifier` (`progress`) and rebuilds only once a second (the spoken value). Their `PreviewSeekBar` shows sprite thumbnails (`scrubThumbnailsProvider`, parsed from Stash's WebVTT) while scrubbing. They load lazily: the controls stay mounted while hidden, so the bar reads the provider only once it is `visible` or touched, then precaches the sprite. `sceneDetailsProvider` and `scrubThumbnailsProvider` stay cached for 5 minutes without listeners (`Ref.cacheFor`), so collapsing and expanding the player doesn't refetch. On first use the controls show one-time gesture tips (`gesture_hints.dart`, `gesture_tips_seen`, resettable in Settings → Playback). In fullscreen a lock button (`TouchLockLayer`, `touch_lock.dart`) ignores all touches until its pill is held for 1 s; leaving fullscreen or a playback error unlocks. Chapters show the marker's screenshot (sprite frame as stand-in). The channel row has a favorite heart (performers; studios from Stash 0.25 through the optional `StudioFavorite` query). Channel pages put `ChannelFavoriteButton` (`FavoriteButton`, `StudioFavoriteButton`) and `ChannelRatingButton` (`features/channel/channel_rating.dart`) under the name: stars are saved through `channelRatingsProvider` (optimistic, `:`), a studio's come from the optional `StudioRating` query, and the picker is `showStarsSheet`, shared with the scenes' `showRatingSheet`. Double-tap seeking is a sequence like YouTube's: a double tap on the left/right third starts it and every further tap on that side within 700 ms extends it (5, 10, 20, 30, 40 s; `seekSequenceTotal`), counted from raw pointers so extending taps react at once; it also works while casting (tap areas over `CastingControls`) and not while locked. A tap on the other side only ends the sequence: switching sides always takes a new double tap, which starts from one step; for 2 s after a seek (`_seekSettling`) a new sequence counts from the last target, since mpv (and a TV) still report the old position. Double-tap seeking is configurable per device (`seekSettingsProvider`, `seek_settings.dart`; Settings → Playback): on/off (off = single taps react without the double-tap delay), step 5/10/15/30 s, and cumulative (`SeekSettings.total`: step, then 2×step×(n−1), i.e. 5, 10, 20, 30, 40 s) or linear (one step per tap). **Queue and autoplay.** `playQueueProvider` holds the playing list (watch later, a group). `NowPlayingNotifier.playQueue` starts it, `playNext` runs when `playerCompletedProvider` fires, and `play()` of a scene outside the queue ends the queue. Watch later is a list of scene ids stored on the device (`watchLaterProvider`), loaded with `findScenesByIds`. With a queue the video controls show previous/next (`playPrevious` restarts the scene after 3 s). A scene picked while the panel is open pushes the one it replaces, with its position, onto `playerHistoryProvider` (`PlayerHistory.back`/`forward`, at most 20 each, each scene once; `play(remember: false)` for queue moves and history moves); `NowPlayingNotifier.goBack`/`goForward` move through it like a browser (a newly picked scene drops the way forward), from `AppShell`'s back and the ←/→ that `_QueueButtons` shows beside play when there is no queue, and back collapses the player only once there is nothing to go back to. `close()` clears it. @@ -77,11 +77,11 @@ lib/ **Watch progress and play count.** `playbackTrackerProvider` feeds the player streams into `PlaybackTracker`. That class has no widget or media_kit dependencies and is unit-tested. It calls `sceneSaveActivity` and `sceneAddPlay` through the `PlaybackActivityApi` interface that `StashRepository` implements. Saved positions also go into `resumeTimesProvider`, so thumbnails show current progress without refetching. Read a scene's position with `effectiveResumeTime`. -**Library.** The `library` tab (`features/library/`) has a sub-tab per `LibrarySection.media`; the other sections open from the "You" page or as tabs of their own. The markers section (`markers_tab.dart`, `markerListProvider`/`MarkerQuery`, `StashRepository.findMarkers`) lists the scene markers of all scenes; a tile plays its scene from the marker via `NowPlayingNotifier.play(scene, at:)`. All scenes uses `SceneFeedView` with `SceneFeedLayout.grid`. Images and galleries share `ImageGridView`, which takes an `ImageQuery` (optionally with a `galleryId`); tapping an image opens `ImageViewerPage` on the root navigator, so it covers the shell and the player. The stats section (`libraryStatsProvider` plus the optional `activityStatsProvider`, which returns null on Stash versions without those fields). The viewer's info button opens `showImageInfoSheet` (`image_info.dart`), loading `imageDetailsProvider` (`FindImageDetails`, cached 2 min) only then; tapping a studio, performer, tag or gallery there closes the sheet and the viewer and opens the page in the current tab. The viewer opens through `ImageViewerPage.route()` (a non-opaque fade route) so that swiping an unzoomed image down closes it with the page showing through. +**Library.** The `library` tab (`features/library/`) has a sub-tab per `LibrarySection.media`; the other sections open from the "You" page or as tabs of their own. The markers section (`markers_tab.dart`, `markerListProvider`/`MarkerQuery`, `StashRepository.findMarkers`) lists the scene markers of all scenes; a tile plays its scene from the marker via `NowPlayingNotifier.play(scene, at:)`. All scenes uses `SceneFeedView` with `SceneFeedLayout.grid`. Images and galleries share `ImageGridView`, which takes an `ImageQuery` (optionally with a `galleryId`); tapping an image opens `ImageViewerPage` on the root navigator, so it covers the shell and the player. A video file among the images (`visual_files` with a `VideoFile`, `ImageItem.isVideo`; a gallery library with videos off, #64) gets a `VideoBadge` in the grid and plays in the viewer through a media_kit player of its own (`image_video.dart`: looping, `ImageVideoBar` with play/pause, slider, mute; pauses the main player). `ImageVideoPage` has the player's gestures: pinch zoom (`InteractiveViewer`, up to 4×), a double tap on the left/right third skips one `SeekSettings.step` (middle: play/pause), holding plays at 2×. A wide clip lets a phone turn sideways while it shows (`AppOrientation.turnTo` with `shellLayoutHold`, `AppOrientation.isPhone`). The clips of an image grid play as shorts (`openImageClipsAsShorts`, from the grid's count row and the viewer's top bar): `ShortsSource.images(ImageQuery, startPage:)` loads the grid's pages and keeps only the videos (`imageShortsStart`), each a `Short.image`, whose `scene` is only a stand-in (`image:`): `ShortsPage` hides the scene actions and counts no play for it, and `PreviewSeekBar(sceneId: null)` shows only the time. The stats section (`libraryStatsProvider` plus the optional `activityStatsProvider`, which returns null on Stash versions without those fields). The viewer's info button opens `showImageInfoSheet` (`image_info.dart`), loading `imageDetailsProvider` (`FindImageDetails`, cached 2 min) only then; tapping a studio, performer, tag or gallery there closes the sheet and the viewer and opens the page in the current tab. The viewer opens through `ImageViewerPage.route()` (a non-opaque fade route) so that swiping an unzoomed image down closes it with the page showing through; swiping up opens the info sheet. **Login (session).** Instead of an API key a server can have a username and password (`ServerConfig.usesSession`: credentials and no API key). `StashSessionNotifier` (`data/repositories/stash_session.dart`) signs in through `POST /login` for Stash's `session` cookie, renews it shortly before it expires, and `StashSessionClient` (the `stashHttpClientProvider` used by GraphQL and the repository) sends it and signs in again on a 401, repeating the request. `authHeadersProvider` (images, streams) adds the cookie; the repository deliberately doesn't watch it, so a renewed cookie doesn't reload everything. `stashLogin` reads only the headers and gives up after `stashLoginTimeout` (20 s) as unreachable. Cast devices can't send cookies, so casting still needs an API key. The login is two steps: URL and optional name first (`findServer` without credentials, through `serverVerifierProvider` for tests); only when the server answers 401/403 does it ask for an API key or username and password (`SegmentedButton`). Editing a server shows one form. -**Demo (App Store review).** `features/demo/`. The login's "Try the demo" button starts `DemoServer`, a Stash look-alike on `ServerConfig.demoUrl` (`http://127.0.0.1:47999`, loopback only), and saves it as the server "Demo"; `main()` starts it again when a saved server has that URL (`ServerProfilesNotifier.hasDemo`), and it rebinds on resume (iOS can take the socket away). The rest of the app talks to it like to any Stash. `DemoHandler` (no sockets, so tests call it directly) answers `POST /graphql` through `DemoGraphql`, a small executor that runs the app's own documents (fragments, aliases, variables) against `DemoLibrary`'s object graph of maps with `__typename`s, and serves `assets/demo/` with byte ranges plus generated sprite WebVTT. `DemoLibrary` keeps the sample data in memory (edits last until the app restarts) and implements the criteria, sorts (`random_`) and paging the app sends; a field it lacks resolves to null, so a new field in a document needs a value there too (`test/features/demo_test.dart` runs every repository call against it). The media are clips from Big Buck Bunny (CC BY 3.0, credited in `registerAppLicenses`) built by `tool/demo/make_demo_assets.sh`, which also writes `assets/demo/manifest.json` (durations, sizes); keep them small, they ship in every build. Casting doesn't work with the demo (the TV can't reach the phone's loopback). +**Demo (App Store review).** `features/demo/`. The login's "Try the demo" button starts `DemoServer`, a Stash look-alike on `ServerConfig.demoUrl` (`http://127.0.0.1:47999`, loopback only), and saves it as the server "Demo"; `main()` starts it again when a saved server has that URL (`ServerProfilesNotifier.hasDemo`), and it rebinds on resume (iOS can take the socket away). The rest of the app talks to it like to any Stash. `DemoHandler` (no sockets, so tests call it directly) answers `POST /graphql` through `DemoGraphql`, a small executor that runs the app's own documents (fragments, aliases, variables) against `DemoLibrary`'s object graph of maps with `__typename`s, and serves `assets/demo/` with byte ranges plus generated sprite WebVTT. `DemoLibrary` keeps the sample data in memory (edits last until the app restarts) and implements the criteria, sorts (`random_`) and paging the app sends; a field it lacks resolves to null, so a new field in a document needs a value there too (`test/features/demo_test.dart` runs every repository call against it). The media are clips from Big Buck Bunny (CC BY 3.0, credited in `registerAppLicenses`) built by `tool/demo/make_demo_assets.sh`, which also writes `assets/demo/manifest.json` (durations, sizes); keep them small, they ship in every build. Casting doesn't work with the demo (the TV can't reach the phone's loopback). Its gallery "Clips" holds three of the shorts' clips as images (`_Image.clip`: a `VideoFile` in `visual_files`, the image path serves the MP4), for the viewer's video playback (#64); one is wide. **Errors.** `StashRepository._run` maps failures to `StashApiException` (a response that doesn't parse into the generated types too). Stash answers invalid queries with HTTP 422 plus GraphQL errors, which gql_http_link raises as `HttpLinkServerException`; these count as query errors (`isNetworkError == false`), and 401/403 become "check the API key" (Stash's 401 has no JSON body, a `HttpLinkParserException`). Other non-JSON error pages (a proxy's) report their HTTP status and are retried only for 5xx. Fields that only newer Stash versions have should go into a separate, optional query (see `activityStats`). `_run` also reports reachability to `connectionStatusProvider` (`data/connection_status.dart`, per server): network errors mark the server unreachable, any success reachable. `ConnectionBannerScope` (in `AppShell`, under the player) then shows a banner with retry and switch server and reloads the lists once the server answers again (`reloadLists`). `ErrorView` shows an icon, headline and one sentence per kind (`errorHeadline`/`errorExplanation` in `l10n/errors.dart`) with the technical text behind "Details". On iOS a LAN host failing with "No route to host"/errno 65 is `StashErrorKind.localNetworkDenied` (the Local Network permission was refused), with its own message in the login and the error views. diff --git a/devtools_options.yaml b/devtools_options.yaml index fa0b357..ff5a421 100644 --- a/devtools_options.yaml +++ b/devtools_options.yaml @@ -1,3 +1,4 @@ description: This file stores settings for Dart & Flutter DevTools. documentation: https://docs.flutter.dev/tools/devtools/extensions#configure-extension-enablement-states extensions: + - hive_ce: true \ No newline at end of file diff --git a/docs/RELEASE_NOTES_next.md b/docs/RELEASE_NOTES_next.md index c5be84d..aa10c4b 100644 --- a/docs/RELEASE_NOTES_next.md +++ b/docs/RELEASE_NOTES_next.md @@ -1,28 +1,21 @@ -# StashTube 1.0.0-beta.9 +# StashTube 1.0.0-beta.10 -Pre-release. The pipeline picks the version (next beta after `v1.0.0-beta.8`). +Pre-release. The pipeline picks the version (next beta after `v1.0.0-beta.9`). ## What's new -- **Back where you were** – lists keep their place when you turn the phone for fullscreen and come back to them. -- **Favorites** – the avatars at the top pick "All" or one performer (a long press opens the channel), with a header and "View channel". -- **Zoom snap feedback** – "Original" and "Fill" show when the pinch zoom snaps, and guide lines where the picture snaps to the center or an edge. -- **PIN with biometrics** – changing the PIN or turning the app lock off also accepts Face ID or the fingerprint, so a forgotten PIN can be replaced. -- **Proxy warning** – a banner names both addresses when the server hands out media URLs on another address than the one StashTube connects to (a reverse proxy without `Host` / `X-Forwarded-Proto`), and how to fix it. +- **Videos in galleries** (#64) – video files that Stash lists as images (a library with only images on) play in the image viewer: looping, with play/pause, a position slider and mute, pinch zoom, double tap on the left or right to skip and hold for 2×. Wide clips let the phone turn sideways. The grid marks them with a play badge and their length. +- **Clips as shorts** – "Play as shorts" in an image grid with clips, or in the viewer, plays the grid's videos one after another in the shorts. +- **Sticky filters** – the filter and sort bars stay at the top of every list, like on home. +- **Back to top** – long lists show a button that jumps back up (Settings → Appearance turns it off). +- **Tag filters** – tag pages have the filter button; the page's tag always applies. +- **Shortcuts** – double tap "You" in the tab bar to switch servers; swipe an image up for its info. +- **Favorites** – double tap "All" (or "Show all") for all favorite performers, double tap a performer for their channel. -## Security +## Changes -- The API key and the session cookie only go to the server's own address (scheme, host and port): never to media URLs pointing elsewhere, and not along a redirect that leaves the server. -- The PIN is stored as PBKDF2-HMAC-SHA256. PINs of earlier versions keep working and are converted after the next correct entry. -- If the PIN can't be read (e.g. after restoring a backup), the app stays locked instead of opening: biometrics lead to a new PIN, otherwise the app can be reset. -- A password in a server address (`https://user:pass@host`) is kept in the secure storage instead of the settings; existing servers move on the first start. - -## Fixes and internals - -- GraphQL responses are no longer written into a cache that was never read. -- The preview check stops after the status instead of downloading whole files from servers that ignore `Range`. -- The password login gives up after 20 s instead of waiting forever. +- Double tap to skip: a tap on the other side only ends the running skip; skipping there takes a new double tap. ## Not tested on a device yet -Proxy warning on a misconfigured server, the lost-PIN screen, and upgrading a PIN set by beta.8 or earlier. +Gallery videos in the viewer (zoom, gestures, turning sideways) and as shorts, the sticky bars on channel pages, the Back to top button. diff --git a/lib/core/api/documents/images.graphql b/lib/core/api/documents/images.graphql index 7d658c8..d9cf274 100644 --- a/lib/core/api/documents/images.graphql +++ b/lib/core/api/documents/images.graphql @@ -7,6 +7,11 @@ query FindImages($filter: FindFilterType, $image_filter: ImageFilterType) { date rating100 paths { thumbnail image } + # A video file in a gallery (a library with only images on) is an image + # too; the viewer plays it (#64). + visual_files { + ... on VideoFile { duration width height } + } studio { ...StudioRef } performers { ...PerformerRef } } diff --git a/lib/core/api/documents/images.graphql.dart b/lib/core/api/documents/images.graphql.dart index b19825b..a9f8fe8 100644 --- a/lib/core/api/documents/images.graphql.dart +++ b/lib/core/api/documents/images.graphql.dart @@ -273,6 +273,64 @@ const documentNodeQueryFindImages = DocumentNode( ], ), ), + FieldNode( + name: NameNode(value: 'visual_files'), + alias: null, + arguments: [], + directives: [], + selectionSet: SelectionSetNode( + selections: [ + InlineFragmentNode( + typeCondition: TypeConditionNode( + on: NamedTypeNode( + name: NameNode(value: 'VideoFile'), + isNonNull: false, + ), + ), + directives: [], + selectionSet: SelectionSetNode( + selections: [ + FieldNode( + name: NameNode(value: 'duration'), + alias: null, + arguments: [], + directives: [], + selectionSet: null, + ), + FieldNode( + name: NameNode(value: 'width'), + alias: null, + arguments: [], + directives: [], + selectionSet: null, + ), + FieldNode( + name: NameNode(value: 'height'), + alias: null, + arguments: [], + directives: [], + selectionSet: null, + ), + FieldNode( + name: NameNode(value: '__typename'), + alias: null, + arguments: [], + directives: [], + selectionSet: null, + ), + ], + ), + ), + FieldNode( + name: NameNode(value: '__typename'), + alias: null, + arguments: [], + directives: [], + selectionSet: null, + ), + ], + ), + ), FieldNode( name: NameNode(value: 'studio'), alias: null, @@ -576,6 +634,7 @@ class Query$FindImages$findImages$images { this.date, this.rating100, required this.paths, + required this.visual_files, this.studio, required this.performers, this.$__typename = 'Image', @@ -589,6 +648,7 @@ class Query$FindImages$findImages$images { final l$date = json['date']; final l$rating100 = json['rating100']; final l$paths = json['paths']; + final l$visual_files = json['visual_files']; final l$studio = json['studio']; final l$performers = json['performers']; final l$$__typename = json['__typename']; @@ -600,6 +660,13 @@ class Query$FindImages$findImages$images { paths: Query$FindImages$findImages$images$paths.fromJson( (l$paths as Map), ), + visual_files: (l$visual_files as List) + .map( + (e) => Query$FindImages$findImages$images$visual_files.fromJson( + (e as Map), + ), + ) + .toList(), studio: l$studio == null ? null : Fragment$StudioRef.fromJson((l$studio as Map)), @@ -622,6 +689,8 @@ class Query$FindImages$findImages$images { final Query$FindImages$findImages$images$paths paths; + final List visual_files; + final Fragment$StudioRef? studio; final List performers; @@ -640,6 +709,10 @@ class Query$FindImages$findImages$images { _resultData['rating100'] = l$rating100; final l$paths = paths; _resultData['paths'] = l$paths.toJson(); + final l$visual_files = visual_files; + _resultData['visual_files'] = l$visual_files + .map((e) => e.toJson()) + .toList(); final l$studio = studio; _resultData['studio'] = l$studio?.toJson(); final l$performers = performers; @@ -656,6 +729,7 @@ class Query$FindImages$findImages$images { final l$date = date; final l$rating100 = rating100; final l$paths = paths; + final l$visual_files = visual_files; final l$studio = studio; final l$performers = performers; final l$$__typename = $__typename; @@ -665,6 +739,7 @@ class Query$FindImages$findImages$images { l$date, l$rating100, l$paths, + Object.hashAll(l$visual_files.map((v) => v)), l$studio, Object.hashAll(l$performers.map((v) => v)), l$$__typename, @@ -705,6 +780,18 @@ class Query$FindImages$findImages$images { if (l$paths != lOther$paths) { return false; } + final l$visual_files = visual_files; + final lOther$visual_files = other.visual_files; + if (l$visual_files.length != lOther$visual_files.length) { + return false; + } + for (int i = 0; i < l$visual_files.length; i++) { + final l$visual_files$entry = l$visual_files[i]; + final lOther$visual_files$entry = lOther$visual_files[i]; + if (l$visual_files$entry != lOther$visual_files$entry) { + return false; + } + } final l$studio = studio; final lOther$studio = other.studio; if (l$studio != lOther$studio) { @@ -804,6 +891,260 @@ class Query$FindImages$findImages$images$paths { } } +class Query$FindImages$findImages$images$visual_files { + Query$FindImages$findImages$images$visual_files({required this.$__typename}); + + factory Query$FindImages$findImages$images$visual_files.fromJson( + Map json, + ) { + switch (json["__typename"] as String) { + case "VideoFile": + return Query$FindImages$findImages$images$visual_files$$VideoFile.fromJson( + json, + ); + + case "ImageFile": + return Query$FindImages$findImages$images$visual_files$$ImageFile.fromJson( + json, + ); + + default: + final l$$__typename = json['__typename']; + return Query$FindImages$findImages$images$visual_files( + $__typename: (l$$__typename as String), + ); + } + } + + final String $__typename; + + Map toJson() { + final _resultData = {}; + final l$$__typename = $__typename; + _resultData['__typename'] = l$$__typename; + return _resultData; + } + + @override + int get hashCode { + final l$$__typename = $__typename; + return Object.hashAll([l$$__typename]); + } + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + if (other is! Query$FindImages$findImages$images$visual_files || + runtimeType != other.runtimeType) { + return false; + } + final l$$__typename = $__typename; + final lOther$$__typename = other.$__typename; + if (l$$__typename != lOther$$__typename) { + return false; + } + return true; + } +} + +extension UtilityExtension$Query$FindImages$findImages$images$visual_files + on Query$FindImages$findImages$images$visual_files { + _T when<_T>({ + required _T Function( + Query$FindImages$findImages$images$visual_files$$VideoFile, + ) + videoFile, + required _T Function( + Query$FindImages$findImages$images$visual_files$$ImageFile, + ) + imageFile, + required _T Function() orElse, + }) { + switch ($__typename) { + case "VideoFile": + return videoFile( + this as Query$FindImages$findImages$images$visual_files$$VideoFile, + ); + + case "ImageFile": + return imageFile( + this as Query$FindImages$findImages$images$visual_files$$ImageFile, + ); + + default: + return orElse(); + } + } + + _T maybeWhen<_T>({ + _T Function(Query$FindImages$findImages$images$visual_files$$VideoFile)? + videoFile, + _T Function(Query$FindImages$findImages$images$visual_files$$ImageFile)? + imageFile, + required _T Function() orElse, + }) { + switch ($__typename) { + case "VideoFile": + if (videoFile != null) { + return videoFile( + this as Query$FindImages$findImages$images$visual_files$$VideoFile, + ); + } else { + return orElse(); + } + + case "ImageFile": + if (imageFile != null) { + return imageFile( + this as Query$FindImages$findImages$images$visual_files$$ImageFile, + ); + } else { + return orElse(); + } + + default: + return orElse(); + } + } +} + +class Query$FindImages$findImages$images$visual_files$$VideoFile + implements Query$FindImages$findImages$images$visual_files { + Query$FindImages$findImages$images$visual_files$$VideoFile({ + required this.duration, + required this.width, + required this.height, + this.$__typename = 'VideoFile', + }); + + factory Query$FindImages$findImages$images$visual_files$$VideoFile.fromJson( + Map json, + ) { + final l$duration = json['duration']; + final l$width = json['width']; + final l$height = json['height']; + final l$$__typename = json['__typename']; + return Query$FindImages$findImages$images$visual_files$$VideoFile( + duration: (l$duration as num).toDouble(), + width: (l$width as int), + height: (l$height as int), + $__typename: (l$$__typename as String), + ); + } + + final double duration; + + final int width; + + final int height; + + final String $__typename; + + Map toJson() { + final _resultData = {}; + final l$duration = duration; + _resultData['duration'] = l$duration; + final l$width = width; + _resultData['width'] = l$width; + final l$height = height; + _resultData['height'] = l$height; + final l$$__typename = $__typename; + _resultData['__typename'] = l$$__typename; + return _resultData; + } + + @override + int get hashCode { + final l$duration = duration; + final l$width = width; + final l$height = height; + final l$$__typename = $__typename; + return Object.hashAll([l$duration, l$width, l$height, l$$__typename]); + } + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + if (other is! Query$FindImages$findImages$images$visual_files$$VideoFile || + runtimeType != other.runtimeType) { + return false; + } + final l$duration = duration; + final lOther$duration = other.duration; + if (l$duration != lOther$duration) { + return false; + } + final l$width = width; + final lOther$width = other.width; + if (l$width != lOther$width) { + return false; + } + final l$height = height; + final lOther$height = other.height; + if (l$height != lOther$height) { + return false; + } + final l$$__typename = $__typename; + final lOther$$__typename = other.$__typename; + if (l$$__typename != lOther$$__typename) { + return false; + } + return true; + } +} + +class Query$FindImages$findImages$images$visual_files$$ImageFile + implements Query$FindImages$findImages$images$visual_files { + Query$FindImages$findImages$images$visual_files$$ImageFile({ + this.$__typename = 'ImageFile', + }); + + factory Query$FindImages$findImages$images$visual_files$$ImageFile.fromJson( + Map json, + ) { + final l$$__typename = json['__typename']; + return Query$FindImages$findImages$images$visual_files$$ImageFile( + $__typename: (l$$__typename as String), + ); + } + + final String $__typename; + + Map toJson() { + final _resultData = {}; + final l$$__typename = $__typename; + _resultData['__typename'] = l$$__typename; + return _resultData; + } + + @override + int get hashCode { + final l$$__typename = $__typename; + return Object.hashAll([l$$__typename]); + } + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + if (other is! Query$FindImages$findImages$images$visual_files$$ImageFile || + runtimeType != other.runtimeType) { + return false; + } + final l$$__typename = $__typename; + final lOther$$__typename = other.$__typename; + if (l$$__typename != lOther$$__typename) { + return false; + } + return true; + } +} + class Variables$Query$FindImageDetails { factory Variables$Query$FindImageDetails({required String id}) => Variables$Query$FindImageDetails._({r'id': id}); diff --git a/lib/data/models/image_item.dart b/lib/data/models/image_item.dart index 392d51c..10867c0 100644 --- a/lib/data/models/image_item.dart +++ b/lib/data/models/image_item.dart @@ -14,6 +14,9 @@ class ImageItem { this.imageUrl, this.studio, this.performers = const [], + this.videoDuration, + this.width, + this.height, }); final String id; @@ -27,8 +30,25 @@ class ImageItem { final Studio? studio; final List performers; + /// Set for a video file shown as an image (a gallery's clip, #64): its + /// length in seconds. [imageUrl] then serves the video. + final double? videoDuration; + + bool get isVideo => videoDuration != null; + + /// The video's size, when [isVideo]. + final int? width; + final int? height; + + /// The video's width / height; null when unknown or not a video. + double? get aspect { + final w = width, h = height; + return w == null || h == null || w <= 0 || h <= 0 ? null : w / h; + } + factory ImageItem.fromGraphql(Query$FindImages$findImages$images i) { final studio = i.studio; + final video = i.visual_files.whereType().firstOrNull; return ImageItem( id: i.id, title: nonEmpty(i.title) ?? 'Image', @@ -38,6 +58,9 @@ class ImageItem { imageUrl: nonEmpty(i.paths.image), studio: studio == null ? null : Studio.fromRef(studio), performers: [for (final p in i.performers) Performer.fromRef(p)], + videoDuration: video?.duration, + width: video?.width, + height: video?.height, ); } } diff --git a/lib/data/models/list_queries.dart b/lib/data/models/list_queries.dart index 58a9dca..6d0f27f 100644 --- a/lib/data/models/list_queries.dart +++ b/lib/data/models/list_queries.dart @@ -98,6 +98,7 @@ class SceneQuery { this.groupId, this.playedOnly = false, this.createdAfter, + this.tagId, int? seed, }) : seed = seed ?? (sort == SceneSort.random ? newRandomSeed() : 0); @@ -136,6 +137,10 @@ class SceneQuery { /// visit", NOTIF-1). final DateTime? createdAfter; + /// Only scenes with this tag (the tag page), on top of [filter]'s tags, + /// so the filter sheet can't remove it. + final String? tagId; + /// Seed for [SceneSort.random] so that pages are stable while scrolling. /// Always 0 for other sorts, so equal queries map to the same provider. final int seed; @@ -162,9 +167,35 @@ class SceneQuery { if (playedOnly) 'play_count': {'value': 0, 'modifier': 'GREATER_THAN'}, if (createdAfter case final after?) 'created_at': {'value': stashTimestamp(after), 'modifier': 'GREATER_THAN'}, }; + if (tagId case final tag?) _addTag(criteria, tag); return criteria.isEmpty ? null : criteria; } + /// Adds [tag] as a required tag: into the filter's "all of" tags, or, if + /// the tags criterion means something else (any of, a saved filter's + /// excludes), as a criterion of its own under `AND`. + static void _addTag(Map criteria, String tag) { + final existing = criteria['tags']; + if (existing == null) { + criteria['tags'] = {'value': [tag], 'modifier': 'INCLUDES_ALL', 'depth': 0}; + return; + } + if (existing is Map && existing['modifier'] == 'INCLUDES_ALL' && existing['value'] is List) { + criteria['tags'] = { + ...existing, + 'value': {...(existing['value'] as List), tag}.toList(), + }; + return; + } + var target = criteria; + while (target['AND'] is Map) { + target = target['AND'] as Map; + } + target['AND'] = { + 'tags': {'value': [tag], 'modifier': 'INCLUDES_ALL', 'depth': 0}, + }; + } + SceneQuery copyWith({SceneSort? sort, SceneFilter? filter, String? search, bool clearSearch = false}) => SceneQuery( sort: sort ?? this.sort, search: clearSearch ? null : (search ?? this.search), @@ -178,6 +209,7 @@ class SceneQuery { groupId: groupId, playedOnly: playedOnly, createdAfter: createdAfter, + tagId: tagId, // Picking a sort again (e.g. "Shuffle") starts a fresh shuffle. seed: sort == null ? seed : null, ); @@ -197,6 +229,7 @@ class SceneQuery { other.groupId == groupId && other.playedOnly == playedOnly && other.createdAfter == createdAfter && + other.tagId == tagId && other.seed == seed; @override @@ -213,6 +246,7 @@ class SceneQuery { groupId, playedOnly, createdAfter, + tagId, seed, ); } diff --git a/lib/features/channel/channel_tabs.dart b/lib/features/channel/channel_tabs.dart index bf9e04c..b34bac9 100644 --- a/lib/features/channel/channel_tabs.dart +++ b/lib/features/channel/channel_tabs.dart @@ -487,7 +487,7 @@ class _ChannelGalleryGridState extends ConsumerState { physics: const AlwaysScrollableScrollPhysics(), slivers: [ ...widget.headerSlivers, - SliverToBoxAdapter( + PinnedBar( child: ChipBar( values: GallerySort.values, selected: _query.sort, diff --git a/lib/features/demo/demo_library.dart b/lib/features/demo/demo_library.dart index 079597f..fc2b887 100644 --- a/lib/features/demo/demo_library.dart +++ b/lib/features/demo/demo_library.dart @@ -235,8 +235,53 @@ class DemoLibrary { ); } _galleries.add( - _Gallery('1', 'Stills', studioId: '2', performerIds: ['1'], details: _credit, cover: media.images.firstOrNull), + _Gallery( + '1', + 'Stills', + studioId: '2', + performerIds: ['1'], + details: _credit, + cover: media.images.firstOrNull == null ? null : 'images/${media.images.first}.jpg', + ), ); + + // Video files in a gallery, as Stash shows them from a library with only + // images on (#64): images whose file is a video. + final clips = [ + // A wide one too, which the viewer lets a phone turn sideways for. + ('riverside', 'Riverside clip'), + ('short-stretch', 'Stretch clip'), + ('short-butterfly', 'Butterfly clip'), + ]; + for (final (i, (file, title)) in clips.indexed) { + final clip = media.clips[file]; + if (clip == null) continue; + _images.add( + _Image( + '${_images.length + 1}', + file, + title: title, + studioId: '2', + galleryIds: ['2'], + performerIds: const ['1'], + tagIds: [tag('Animation'), tag('Short')], + createdAt: _now.subtract(Duration(minutes: 30 * (i + 1))), + clip: clip, + ), + ); + } + if (_images.any((i) => i.clip != null)) { + _galleries.add( + _Gallery( + '2', + 'Clips', + studioId: '2', + performerIds: ['1'], + details: _credit, + cover: 'covers/${clips.first.$1}.jpg', + ), + ); + } } String _newId() => '${_nextId++}'; @@ -462,7 +507,7 @@ class DemoLibrary { 'details': g.details, 'urls': g.urls, 'image_count': (Map _) => _images.where((i) => i.galleryIds.contains(g.id)).length, - 'paths': {'__typename': 'GalleryPathsType', 'cover': g.cover == null ? '' : _media('images/${g.cover}.jpg')}, + 'paths': {'__typename': 'GalleryPathsType', 'cover': g.cover == null ? '' : _media(g.cover!)}, 'files': const [], 'folder': null, 'studio': (Map _) => _studios.where((s) => s.id == g.studioId).map(_studioObject).firstOrNull, @@ -486,15 +531,27 @@ class DemoLibrary { 'updated_at': i.createdAt.toUtc().toIso8601String(), // The stills are 640 × 360 JPEGs (tool/demo/make_demo_assets.sh). 'visual_files': [ - { - '__typename': 'ImageFile', - 'path': '/demo/images/${i.file}.jpg', - 'basename': '${i.file}.jpg', - 'size': _imageSize, - 'format': 'jpeg', - 'width': 640, - 'height': 360, - }, + if (i.clip case final clip?) + { + '__typename': 'VideoFile', + 'path': '/demo/scenes/${i.file}.mp4', + 'basename': '${i.file}.mp4', + 'size': clip.size, + 'format': 'mp4', + 'width': clip.width, + 'height': clip.height, + 'duration': clip.duration, + } + else + { + '__typename': 'ImageFile', + 'path': '/demo/images/${i.file}.jpg', + 'basename': '${i.file}.jpg', + 'size': _imageSize, + 'format': 'jpeg', + 'width': 640, + 'height': 360, + }, ], 'tags': (Map _) => [ for (final id in i.tagIds) ..._tags.where((t) => t.id == id).map(_tagObject), @@ -504,8 +561,8 @@ class DemoLibrary { ], 'paths': { '__typename': 'ImagePathsType', - 'thumbnail': _media('images/${i.file}.jpg'), - 'image': _media('images/${i.file}.jpg'), + 'thumbnail': _media(i.clip == null ? 'images/${i.file}.jpg' : 'covers/${i.file}.jpg'), + 'image': _media(i.clip == null ? 'images/${i.file}.jpg' : 'scenes/${i.file}.mp4'), }, 'studio': (Map _) => _studios.where((s) => s.id == i.studioId).map(_studioObject).firstOrNull, 'performers': (Map _) => [ @@ -1226,10 +1283,14 @@ class _Image { this.rating100, this.performerIds = const [], this.tagIds = const [], + this.clip, }); final String id; final String file; + + /// Set for a video file shown as an image (#64): `scenes/.mp4`. + final DemoClip? clip; final List performerIds; final List tagIds; final String title; diff --git a/lib/features/library/add_to_group.dart b/lib/features/library/add_to_group.dart index 480a1d5..9c53fd2 100644 --- a/lib/features/library/add_to_group.dart +++ b/lib/features/library/add_to_group.dart @@ -176,6 +176,7 @@ class _AddToGroupSheetState extends ConsumerState { child: Scaffold( backgroundColor: Colors.transparent, body: LoadMoreListener( + scrollToTop: false, onLoadMore: () => ref.read(provider.notifier).loadMore(), child: CustomScrollView( controller: scrollController, diff --git a/lib/features/library/galleries_tab.dart b/lib/features/library/galleries_tab.dart index cb385f2..3478b94 100644 --- a/lib/features/library/galleries_tab.dart +++ b/lib/features/library/galleries_tab.dart @@ -66,7 +66,7 @@ class _GalleryGridViewState extends ConsumerState { child: CustomScrollView( physics: const AlwaysScrollableScrollPhysics(), slivers: [ - SliverToBoxAdapter( + PinnedBar( child: ChipBar( values: GallerySort.values, selected: _query.sort, diff --git a/lib/features/library/image_video.dart b/lib/features/library/image_video.dart new file mode 100644 index 0000000..7f9cd84 --- /dev/null +++ b/lib/features/library/image_video.dart @@ -0,0 +1,367 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:media_kit/media_kit.dart'; +import 'package:media_kit_video/media_kit_video.dart'; + +import '../../core/config/haptics.dart'; +import '../../core/config/theme.dart'; +import '../../core/pagination/paged_notifier.dart'; +import '../../core/pagination/paging_mode.dart'; +import '../../data/models/list_queries.dart'; +import '../../core/utils/format.dart'; +import '../../data/models/image_item.dart'; +import '../../l10n/l10n.dart'; +import '../../widgets/hold_detector.dart'; +import '../../widgets/play_pause_icon.dart'; +import '../player/seek_settings.dart'; +import '../../widgets/stash_image.dart'; +import '../shell/navigation.dart'; +import '../shorts/shorts_feed.dart'; +import '../shorts/shorts_page.dart'; + +/// Opens the video files of an image grid ([query], loaded as [state]) as +/// shorts, at [at] or the first one (#64). +void openImageClipsAsShorts(WidgetRef ref, ImageQuery query, PagedState state, {ImageItem? at, String? title}) { + Haptics.light(); + final index = at == null ? -1 : state.items.indexOf(at); + final numbered = ref.read(pagingModeProvider) == PagingMode.pages; + final start = index < 0 + ? (startPage: numbered ? state.page : 1, initialIndex: 0) + : imageShortsStart(state.items, index, page: numbered ? state.page : null, perPage: state.perPage); + openPage( + ref, + ShortsPage( + source: ShortsSource.images(query, startPage: start.startPage, title: title), + initialIndex: start.initialIndex, + ), + ); +} + +/// A gallery's video file (#64) on its page in the image viewer: the +/// thumbnail, and over it the video once [controller] plays it (only the +/// current page gets one; the viewer owns the player). Like the player: +/// pinch to zoom (up to 4×), double tap on the left or right third to skip +/// a step back or on ([seekSettingsProvider]), hold for 2× speed. +class ImageVideoPage extends ConsumerStatefulWidget { + const ImageVideoPage({ + super.key, + required this.image, + this.controller, + required this.onTap, + required this.onZoomChanged, + }); + + final ImageItem image; + final VideoController? controller; + + /// A single tap: the viewer toggles its overlay. + final VoidCallback onTap; + + /// Zoomed in, horizontal and vertical drags pan instead of paging or + /// closing. + final ValueChanged onZoomChanged; + + @override + ConsumerState createState() => _ImageVideoPageState(); +} + +class _ImageVideoPageState extends ConsumerState { + final _transform = TransformationController(); + Offset _doubleTapAt = Offset.zero; + + /// The feedback of the last double tap: -1 back, 1 on; 0 none. + int _skipped = 0; + int _skipTick = 0; + Timer? _skipTimer; + + /// The speed before holding for 2×; null while not holding. + double? _rateBeforeHold; + + @override + void dispose() { + _skipTimer?.cancel(); + _transform.dispose(); + final rate = _rateBeforeHold; + if (rate != null) widget.controller?.player.setRate(rate); + super.dispose(); + } + + bool get _isZoomed => _transform.value.getMaxScaleOnAxis() > 1.01; + + void _onDoubleTap() { + final player = widget.controller?.player; + final width = context.size?.width ?? 0; + if (player == null || width <= 0) return; + final x = _doubleTapAt.dx; + final direction = x < width / 3 ? -1 : (x > width * 2 / 3 ? 1 : 0); + if (direction == 0) { + Haptics.light(); + unawaited(player.playOrPause()); + return; + } + final step = ref.read(seekSettingsProvider).step; + final state = player.state; + var target = state.position + step * direction; + if (target < Duration.zero) target = Duration.zero; + if (state.duration > Duration.zero && target > state.duration) target = state.duration; + unawaited(player.seek(target)); + Haptics.selection(); + _skipTimer?.cancel(); + _skipTimer = Timer(const Duration(milliseconds: 700), () { + if (mounted) setState(() => _skipped = 0); + }); + setState(() { + _skipped = direction; + _skipTick++; + }); + } + + void _startHold() { + final player = widget.controller?.player; + if (player == null || _rateBeforeHold != null) return; + Haptics.light(); + setState(() => _rateBeforeHold = player.state.rate); + unawaited(player.setRate(2)); + } + + void _endHold() { + final rate = _rateBeforeHold; + if (rate == null) return; + unawaited(widget.controller?.player.setRate(rate)); + setState(() => _rateBeforeHold = null); + } + + @override + Widget build(BuildContext context) { + final l = context.l10n; + final controller = widget.controller; + final step = ref.watch(seekSettingsProvider.select((s) => s.step)).inSeconds; + return Stack( + fit: StackFit.expand, + children: [ + HoldDetector( + onHoldStart: _startHold, + onHoldEnd: _endHold, + child: GestureDetector( + onTap: widget.onTap, + onDoubleTapDown: (details) => _doubleTapAt = details.localPosition, + onDoubleTap: controller == null ? null : _onDoubleTap, + child: InteractiveViewer( + transformationController: _transform, + maxScale: 4, + onInteractionEnd: (_) => widget.onZoomChanged(_isZoomed), + child: Stack( + fit: StackFit.expand, + children: [ + Center( + child: StashImage(widget.image.thumbnailUrl, fit: BoxFit.contain, fallbackIcon: Icons.movie_outlined), + ), + if (controller != null) + Video(controller: controller, fit: BoxFit.contain, fill: Colors.transparent, controls: _noControls) + else + const Center(child: Icon(Icons.play_circle_outline, color: Colors.white70, size: 64)), + ], + ), + ), + ), + ), + if (_skipped != 0) + IgnorePointer( + child: Align( + alignment: _skipped < 0 ? const Alignment(-0.7, 0) : const Alignment(0.7, 0), + child: _SkipLabel( + key: ValueKey(_skipTick), + text: _skipped < 0 ? l.seekBackSeconds(step) : l.seekForwardSeconds(step), + icon: _skipped < 0 ? Icons.fast_rewind : Icons.fast_forward, + ), + ), + ), + if (_rateBeforeHold != null) + IgnorePointer( + child: Align( + alignment: const Alignment(0, -0.75), + child: _Pill(child: Text(l.fastForward2x, style: const TextStyle(color: Colors.white))), + ), + ), + ], + ); + } +} + +class _SkipLabel extends StatelessWidget { + const _SkipLabel({super.key, required this.text, required this.icon}); + + final String text; + final IconData icon; + + @override + Widget build(BuildContext context) => TweenAnimationBuilder( + tween: Tween(begin: MediaQuery.disableAnimationsOf(context) ? 1 : 0.85, end: 1), + duration: const Duration(milliseconds: 150), + builder: (_, scale, child) => Transform.scale(scale: scale, child: child), + child: _Pill( + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, color: Colors.white, size: 18), + const SizedBox(width: AppSpacing.xs), + Text(text, style: const TextStyle(color: Colors.white)), + ], + ), + ), + ); +} + +class _Pill extends StatelessWidget { + const _Pill({required this.child}); + + final Widget child; + + @override + Widget build(BuildContext context) => DecoratedBox( + decoration: BoxDecoration(color: AppColors.of(context).videoScrimSoft, borderRadius: AppRadius.pillBorder), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: AppSpacing.m, vertical: AppSpacing.xs), + child: child, + ), + ); +} + +/// media_kit's `NoVideoControls` is `null`, which `Video` ignores. +Widget _noControls(VideoState state) => const SizedBox.shrink(); + +/// Play/pause, the position as a slider, the times and mute, for the video +/// in the image viewer's bottom overlay. +class ImageVideoBar extends StatefulWidget { + const ImageVideoBar({super.key, required this.player}); + + final Player player; + + @override + State createState() => _ImageVideoBarState(); +} + +class _ImageVideoBarState extends State { + final _subscriptions = >[]; + late bool _playing; + late Duration _position; + late Duration _duration; + late double _volume; + + /// The slider's value while it is dragged, in seconds. + double? _dragging; + + @override + void initState() { + super.initState(); + _listen(); + } + + @override + void didUpdateWidget(ImageVideoBar oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.player != widget.player) { + _cancel(); + _listen(); + } + } + + void _listen() { + final player = widget.player; + final state = player.state; + _playing = state.playing; + _position = state.position; + _duration = state.duration; + _volume = state.volume; + void update(VoidCallback change) { + if (mounted) setState(change); + } + + _subscriptions.addAll([ + player.stream.playing.listen((v) => update(() => _playing = v)), + player.stream.position.listen((v) => update(() => _position = v)), + player.stream.duration.listen((v) => update(() => _duration = v)), + player.stream.volume.listen((v) => update(() => _volume = v)), + ]); + } + + void _cancel() { + for (final s in _subscriptions) { + unawaited(s.cancel()); + } + _subscriptions.clear(); + } + + @override + void dispose() { + _cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final l = context.l10n; + final player = widget.player; + final total = _duration.inMilliseconds / 1000; + final position = (_dragging ?? _position.inMilliseconds / 1000).clamp(0.0, total > 0 ? total : 0.0); + final muted = _volume == 0; + const text = TextStyle(color: Colors.white, fontFeatures: [FontFeature.tabularFigures()]); + return Row( + children: [ + IconButton( + tooltip: _playing ? l.imageVideoPause : l.imageVideoPlay, + onPressed: () => unawaited(player.playOrPause()), + icon: PlayPauseIcon(playing: _playing, color: Colors.white), + ), + Text(formatDuration(position), style: text), + Expanded( + child: Slider( + value: position, + max: total > 0 ? total : 1, + onChanged: total > 0 ? (v) => setState(() => _dragging = v) : null, + onChangeEnd: (v) { + unawaited(player.seek(Duration(milliseconds: (v * 1000).round()))); + setState(() => _dragging = null); + }, + semanticFormatterCallback: (v) => formatDuration(v), + ), + ), + Text(formatDuration(total), style: text), + const SizedBox(width: AppSpacing.xs), + IconButton( + tooltip: muted ? l.imageVideoUnmute : l.imageVideoMute, + onPressed: () => unawaited(player.setVolume(muted ? 100 : 0)), + icon: Icon(muted ? Icons.volume_off : Icons.volume_up, color: Colors.white), + ), + ], + ); + } +} + +/// The play symbol and length on a video's grid tile. +class VideoBadge extends StatelessWidget { + const VideoBadge({super.key, required this.seconds}); + + final double seconds; + + @override + Widget build(BuildContext context) { + final colors = AppColors.of(context); + return Container( + padding: const EdgeInsets.symmetric(horizontal: AppSpacing.xs, vertical: 1), + decoration: BoxDecoration(color: colors.badgeBackground, borderRadius: AppRadius.badgeBorder), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.play_arrow, size: 14, color: colors.onBadge), + Text( + formatDuration(seconds), + style: TextStyle(color: colors.onBadge, fontSize: AppTextSize.overlayLabel, fontWeight: FontWeight.w500), + ), + ], + ), + ); + } +} diff --git a/lib/features/library/image_viewer_page.dart b/lib/features/library/image_viewer_page.dart index 340bbd5..5e03f36 100644 --- a/lib/features/library/image_viewer_page.dart +++ b/lib/features/library/image_viewer_page.dart @@ -1,6 +1,10 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:media_kit/media_kit.dart'; +import 'package:media_kit_video/media_kit_video.dart'; import '../../core/config/theme.dart'; import '../../core/utils/format.dart'; @@ -8,15 +12,22 @@ import '../../data/models/image_item.dart'; import '../../data/models/list_queries.dart'; import '../../l10n/l10n.dart'; import '../../data/providers.dart'; +import '../../data/repositories/stash_session.dart'; +import '../../widgets/app_orientation.dart'; +import '../../widgets/layout_freeze.dart'; +import '../player/player_providers.dart'; import '../shell/navigation.dart'; import 'gallery_page.dart'; import 'image_info.dart'; +import 'image_video.dart'; import '../../widgets/stash_image.dart'; /// Fullscreen image viewer: swipe between images, pinch or double tap to /// zoom, tap to toggle the info overlay (with the performers), "i" for the -/// image's details, swipe down (not zoomed in) to close. Loads more images -/// when nearing the end. +/// image's details (or swipe up), swipe down (not zoomed in) to close. Loads more images +/// when nearing the end. A video file among the images (#64) plays on its +/// page, looping, with play/pause, a position slider and mute in the +/// overlay. class ImageViewerPage extends ConsumerStatefulWidget { const ImageViewerPage({super.key, required this.query, required this.initialIndex}); @@ -49,6 +60,39 @@ class _ImageViewerPageState extends ConsumerState with SingleTi /// A swipe this far down (of the height), or a fling, closes the viewer. static const _closeFraction = 0.15; + /// A swipe up this far (after the resistance), or a fling up, opens the + /// image's info. + static const _infoDistance = 30.0; + + /// Plays the current page's video, if it is one; created for the first. + Player? _videoPlayer; + VideoController? _videoController; + + /// The image [_videoPlayer] plays; null: none (stopped). + String? _videoId; + + /// A phone may turn sideways while a wide video shows (else the app + /// stays portrait there); the lists behind keep their layout meanwhile. + bool _turnable = false; + + static const _anyOrientation = [ + DeviceOrientation.portraitUp, + DeviceOrientation.landscapeLeft, + DeviceOrientation.landscapeRight, + ]; + + void _setTurnable(bool turnable) { + if (turnable == _turnable || !AppOrientation.isPhone) return; + _turnable = turnable; + if (turnable) { + shellLayoutHold.hold(); + unawaited(AppOrientation.turnTo(_anyOrientation)); + } else { + // Upright again first, then the lists may lay out anew. + unawaited(AppOrientation.turnTo(null).whenComplete(() => shellLayoutHold.releaseLater(const Duration(seconds: 1)))); + } + } + @override void initState() { super.initState(); @@ -58,6 +102,8 @@ class _ImageViewerPageState extends ConsumerState with SingleTi @override void dispose() { SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge); + _setTurnable(false); + _videoPlayer?.dispose(); _dismiss.dispose(); _pageController.dispose(); super.dispose(); @@ -90,7 +136,7 @@ class _ImageViewerPageState extends ConsumerState with SingleTi return; } final dy = details.primaryDelta ?? 0; - // Up only with resistance; only down closes. + // Up only with resistance (it opens the info); only down closes. _dismiss.value += _dismiss.value < 0 || (_dismiss.value == 0 && dy < 0) ? dy * 0.25 : dy; } @@ -99,6 +145,13 @@ class _ImageViewerPageState extends ConsumerState with SingleTi _dismissing = false; final height = MediaQuery.sizeOf(context).height; final velocity = details.primaryVelocity ?? 0; + if (_dismiss.value < 0 && (velocity < -500 || _dismiss.value < -_infoDistance)) { + // Swiped up: the image's details. + _springBack(); + final items = ref.read(imageListProvider(widget.query)).current?.items ?? const []; + if (_index < items.length) _showInfo(items[_index]); + return; + } final close = velocity > 700 || (_dismiss.value > height * _closeFraction && velocity > -300); close ? _close(height) : _springBack(); } @@ -151,10 +204,41 @@ class _ImageViewerPageState extends ConsumerState with SingleTi Navigator.of(context).pop(); } + /// Plays [current] if it is a video, else stops the player. + void _syncVideo(ImageItem? current) { + final url = current?.imageUrl; + final id = current != null && current.isVideo && url != null ? current.id : null; + _setTurnable(id != null && (current!.aspect ?? 0) > 1.05); + if (id == _videoId) return; + _videoId = id; + if (id == null || url == null) { + _videoPlayer?.stop(); + return; + } + final player = _videoPlayer ??= Player(); + _videoController ??= VideoController(player); + // Not over the main player's sound. + if (ref.read(nowPlayingProvider) != null) ref.read(playerProvider).pause(); + player + ..setPlaylistMode(PlaylistMode.single) + ..open(Media(url, httpHeaders: ref.read(authHeadersProvider).forUrl(url))).ignore(); + } + + /// The list's clips as shorts, from [clip]; in the current tab, behind the + /// viewer, which closes. + void _playAsShorts(ImageItem clip) { + final state = ref.read(imageListProvider(widget.query)).current; + if (state == null) return; + _videoPlayer?.pause(); + openImageClipsAsShorts(ref, widget.query, state, at: clip, title: context.l10n.imagesClips); + Navigator.of(context).pop(); + } + @override Widget build(BuildContext context) { final items = ref.watch(imageListProvider(widget.query)).current?.items ?? const []; final current = _index < items.length ? items[_index] : null; + _syncVideo(current); final pages = PageView.builder( controller: _pageController, @@ -162,15 +246,25 @@ class _ImageViewerPageState extends ConsumerState with SingleTi physics: _zoomed ? const NeverScrollableScrollPhysics() : null, itemCount: items.length, onPageChanged: _onPageChanged, - itemBuilder: (_, i) => GestureDetector( - onTap: () => setState(() => _showOverlay = !_showOverlay), - child: _ZoomableImage( - image: items[i], - onZoomChanged: (zoomed) { - if (zoomed != _zoomed) setState(() => _zoomed = zoomed); - }, - ), - ), + itemBuilder: (_, i) => items[i].isVideo + // Its own taps: double taps skip instead of zooming. + ? ImageVideoPage( + image: items[i], + controller: items[i].id == _videoId ? _videoController : null, + onTap: () => setState(() => _showOverlay = !_showOverlay), + onZoomChanged: (zoomed) { + if (zoomed != _zoomed) setState(() => _zoomed = zoomed); + }, + ) + : GestureDetector( + onTap: () => setState(() => _showOverlay = !_showOverlay), + child: _ZoomableImage( + image: items[i], + onZoomChanged: (zoomed) { + if (zoomed != _zoomed) setState(() => _zoomed = zoomed); + }, + ), + ), ); final overlay = AnimatedOpacity( opacity: _showOverlay ? 1 : 0, @@ -181,7 +275,9 @@ class _ImageViewerPageState extends ConsumerState with SingleTi image: current, position: _index + 1, total: items.length, + video: current != null && current.id == _videoId ? _videoPlayer : null, onInfo: current == null ? null : () => _showInfo(current), + onPlayAsShorts: current == null || !current.isVideo ? null : () => _playAsShorts(current), ), ), ); @@ -334,11 +430,24 @@ class _ZoomableImageState extends State<_ZoomableImage> with SingleTickerProvide } class _Overlay extends ConsumerWidget { - const _Overlay({required this.image, required this.position, required this.total, this.onInfo}); + const _Overlay({ + required this.image, + required this.position, + required this.total, + this.video, + this.onInfo, + this.onPlayAsShorts, + }); final ImageItem? image; final int position; final int total; + + /// The current page's video player, if it is a video. + final Player? video; + + /// For a video: the list's clips as shorts. + final VoidCallback? onPlayAsShorts; final VoidCallback? onInfo; @override @@ -373,6 +482,12 @@ class _Overlay extends ConsumerWidget { style: const TextStyle(color: Colors.white), ), ), + if (onPlayAsShorts != null) + IconButton( + icon: const Icon(Icons.slow_motion_video, color: Colors.white), + tooltip: l.imagesPlayAsShorts, + onPressed: onPlayAsShorts, + ), if (onInfo != null) IconButton( icon: const Icon(Icons.info_outline, color: Colors.white), @@ -403,6 +518,7 @@ class _Overlay extends ConsumerWidget { crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ + if (video case final player?) ImageVideoBar(player: player), Text( image.title, maxLines: 2, diff --git a/lib/features/library/images_tab.dart b/lib/features/library/images_tab.dart index aa06593..3b4a6bb 100644 --- a/lib/features/library/images_tab.dart +++ b/lib/features/library/images_tab.dart @@ -10,7 +10,10 @@ import '../../widgets/chip_bar.dart'; import '../../widgets/paged_sliver.dart'; import '../../widgets/scene_filter_sheet.dart'; import '../../widgets/stash_image.dart'; +import 'image_video.dart'; import 'image_viewer_page.dart'; +import '../../core/config/theme.dart'; +import '../../widgets/scene_card.dart' show spokenDuration; import '../../l10n/l10n.dart'; /// All images, newest first. @@ -142,7 +145,7 @@ class _ImageGridViewState extends ConsumerState { ), ), ), - SliverToBoxAdapter( + PinnedBar( child: Row( children: [ Padding( @@ -171,10 +174,23 @@ class _ImageGridViewState extends ConsumerState { if (value.current case final state?) SliverToBoxAdapter( child: Padding( - padding: const EdgeInsets.fromLTRB(16, 4, 16, 8), - child: Text( - context.l10n.imagesCount(state.totalCount), - style: theme.textTheme.bodySmall?.copyWith(color: theme.colorScheme.onSurfaceVariant), + padding: const EdgeInsets.fromLTRB(16, 0, 8, 4), + child: Row( + children: [ + Expanded( + child: Text( + context.l10n.imagesCount(state.totalCount), + style: theme.textTheme.bodySmall?.copyWith(color: theme.colorScheme.onSurfaceVariant), + ), + ), + // Video files among the images (a gallery's clips, #64). + if (state.items.any((i) => i.isVideo && i.imageUrl != null)) + TextButton.icon( + onPressed: () => openImageClipsAsShorts(ref, _query, state, title: context.l10n.imagesClips), + icon: const Icon(Icons.slow_motion_video), + label: Text(context.l10n.imagesPlayAsShorts), + ), + ], ), ), ), @@ -200,9 +216,19 @@ class _ImageGridViewState extends ConsumerState { .push(ImageViewerPage.route(query: _query, initialIndex: items.indexOf(image))); }, child: Semantics( - label: image.title, + label: image.videoDuration == null + ? image.title + : context.l10n.imageVideoLabel(image.title, spokenDuration(context.l10n, image.videoDuration!)), button: true, - child: StashImage(image.thumbnailUrl, fallbackIcon: Icons.image_outlined), + excludeSemantics: true, + child: Stack( + fit: StackFit.expand, + children: [ + StashImage(image.thumbnailUrl, fallbackIcon: Icons.image_outlined), + if (image.videoDuration case final seconds?) + Positioned(right: AppSpacing.xs, bottom: AppSpacing.xs, child: VideoBadge(seconds: seconds)), + ], + ), ), ), ), diff --git a/lib/features/library/markers_tab.dart b/lib/features/library/markers_tab.dart index 5008907..a04ade4 100644 --- a/lib/features/library/markers_tab.dart +++ b/lib/features/library/markers_tab.dart @@ -100,7 +100,7 @@ class _MarkerGridViewState extends ConsumerState { physics: const AlwaysScrollableScrollPhysics(), slivers: [ ...widget.headerSlivers, - SliverToBoxAdapter( + PinnedBar( child: ChipBar( values: MarkerSort.values, selected: _query.sort, diff --git a/lib/features/performers/performers_page.dart b/lib/features/performers/performers_page.dart index 74c63db..e825257 100644 --- a/lib/features/performers/performers_page.dart +++ b/lib/features/performers/performers_page.dart @@ -14,14 +14,18 @@ import '../../l10n/l10n.dart'; import '../auth/server_avatar.dart'; class PerformersPage extends ConsumerStatefulWidget { - const PerformersPage({super.key}); + const PerformersPage({super.key, this.initialSort = PerformerSort.name}); + + /// The sort chip selected at first; [PerformerSort.favorites] lists only + /// the favorites. + final PerformerSort initialSort; @override ConsumerState createState() => _PerformersPageState(); } class _PerformersPageState extends ConsumerState { - var _query = PerformerQuery(); + late var _query = PerformerQuery(sort: widget.initialSort); @override Widget build(BuildContext context) { @@ -54,7 +58,7 @@ class _PerformersPageState extends ConsumerState { child: CustomScrollView( physics: const AlwaysScrollableScrollPhysics(), slivers: [ - SliverToBoxAdapter( + PinnedBar( child: ChipBar( values: PerformerSort.values, selected: _query.sort, diff --git a/lib/features/player/preview_seek_bar.dart b/lib/features/player/preview_seek_bar.dart index 0f7a7ad..aff02ee 100644 --- a/lib/features/player/preview_seek_bar.dart +++ b/lib/features/player/preview_seek_bar.dart @@ -49,7 +49,9 @@ class PreviewSeekBar extends ConsumerStatefulWidget { this.windowRelative = false, }); - final String sceneId; + /// The scene whose sprite previews and markers the bar shows; null for a + /// video that is no scene (a gallery's clip): only the time. + final String? sceneId; /// The part of the video the bar covers; null for the whole video. final SeekWindow? window; @@ -251,7 +253,8 @@ class _PreviewSeekBarState extends ConsumerState { // The duration or the window may have changed since the last position. if (remote == null) _played.value = _fractionOf(_position); final auth = ref.watch(authHeadersProvider); - final thumbs = _loadThumbnails ? ref.watch(scrubThumbnailsProvider(widget.sceneId)).value : null; + final sceneId = widget.sceneId; + final thumbs = _loadThumbnails && sceneId != null ? ref.watch(scrubThumbnailsProvider(sceneId)).value : null; final headers = thumbs == null ? const {} : auth.forUrl(thumbs.spriteUrl); if (thumbs != null && thumbs.spriteUrl != _precachedSprite) { _precachedSprite = thumbs.spriteUrl; @@ -260,7 +263,7 @@ class _PreviewSeekBarState extends ConsumerState { onError: (_, _) {})); } // Like the thumbnails, only once the bar is shown or touched. - final details = _loadThumbnails ? ref.watch(sceneDetailsProvider(widget.sceneId)).value : null; + final details = _loadThumbnails && sceneId != null ? ref.watch(sceneDetailsProvider(sceneId)).value : null; // With a window, only the markers inside it (ranges cut to it), and not // the one the window starts at: that is the clip itself. final windowed = widget.window != null; diff --git a/lib/features/player/video_controls.dart b/lib/features/player/video_controls.dart index a2c6456..eea9022 100644 --- a/lib/features/player/video_controls.dart +++ b/lib/features/player/video_controls.dart @@ -335,21 +335,20 @@ class _StashVideoControlsState extends ConsumerState { } /// Double tap on a side starts a seek sequence; while it runs, every - /// single tap on that side extends it, a tap on the other side starts a - /// new one there, and a tap in the middle ends it (and toggles the - /// controls as usual). + /// single tap on that side extends it. A tap in the middle ends it (and + /// toggles the controls as usual); a tap on the other side ends it too and + /// counts as the first tap of a new double tap there, so switching sides + /// always takes a double tap. void _onSeekTap(int side, Offset position) { if (_locked || _tipsShowing || !ref.read(seekSettingsProvider).enabled) return; if (_seekDirection != 0) { _clearLastTap(); - if (side == 0) { - _endSeekSequence(); - } else if (side == _seekDirection) { + if (side == _seekDirection) { _extendSeekSequence(); - } else { - _startSeekSequence(side); + return; } - return; + _endSeekSequence(); + if (side == 0) return; } final last = _lastTap; if (side != 0 && last != null && last.side == side && (position - last.position).distance <= kDoubleTapSlop) { diff --git a/lib/features/settings/settings_categories.dart b/lib/features/settings/settings_categories.dart index 7b55b5e..7c6366d 100644 --- a/lib/features/settings/settings_categories.dart +++ b/lib/features/settings/settings_categories.dart @@ -29,6 +29,7 @@ import 'about.dart'; import 'appearance_picker.dart'; import 'nav_bar_settings_page.dart'; import 'scene_card_config.dart'; +import '../../widgets/scroll_to_top.dart'; /// The sub-pages of the settings (SET-1), pushed inside the settings sheet's /// own navigator, so their app bars show a back button instead of the X. @@ -266,6 +267,13 @@ class AppearanceSettingsPage extends ConsumerWidget { }, ), ), + SwitchListTile( + secondary: const Icon(Icons.vertical_align_top), + title: Text(l.scrollToTopSetting), + subtitle: Text(l.scrollToTopSettingSubtitle), + value: ref.watch(scrollToTopProvider), + onChanged: withHaptic((v) => ref.read(scrollToTopProvider.notifier).set(v)), + ), SettingsDropdownTile( leading: const Icon(Icons.vibration), title: Text(l.haptics), diff --git a/lib/features/shell/app_shell.dart b/lib/features/shell/app_shell.dart index dfb21b0..0f87a3a 100644 --- a/lib/features/shell/app_shell.dart +++ b/lib/features/shell/app_shell.dart @@ -7,6 +7,7 @@ import '../../core/config/haptics.dart'; import '../../l10n/l10n.dart'; import '../../widgets/connection_banner.dart'; import '../../widgets/layout_freeze.dart'; +import '../auth/server_switcher.dart'; import '../home/home_page.dart'; import '../library/library_page.dart'; import '../performers/performers_page.dart'; @@ -95,6 +96,11 @@ class _AppShellBody extends ConsumerWidget { final selected = tabs.indexOf(currentTab).clamp(0, tabs.length - 1); void selectTab(AppTab tab) { + if (ref.read(tabDoubleTapProvider).tap(tab, DateTime.now()) && tab == AppTab.you) { + Haptics.selection(); + showServerSwitcher(context); + return; + } if (tab == currentTab) { reselectTab(navigatorKeys[tab]!.currentState, scrollControllers[tab]!); Haptics.selection(); diff --git a/lib/features/shell/navigation.dart b/lib/features/shell/navigation.dart index 4a20d3e..fdc7254 100644 --- a/lib/features/shell/navigation.dart +++ b/lib/features/shell/navigation.dart @@ -1,3 +1,4 @@ +import 'package:flutter/gestures.dart' show kDoubleTapTimeout; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -141,3 +142,22 @@ void openSearch(WidgetRef ref, {SearchScope scope = SearchScope.scenes}) => void openTag(WidgetRef ref, String id) => openPage(ref, TagPage(tagId: id)); void openTags(WidgetRef ref) => openPage(ref, const TagsPage()); + +/// Notices a double tap on a tab of the bar or rail (two taps on the same +/// tab within [kDoubleTapTimeout]); the "You" tab's opens the server +/// switcher. +class TabDoubleTap { + AppTab? _tab; + DateTime? _at; + + /// Records a tap on [tab]; true when it completes a double tap. + bool tap(AppTab tab, DateTime now) { + final at = _at; + final double = tab == _tab && at != null && now.difference(at) <= kDoubleTapTimeout; + _tab = double ? null : tab; + _at = double ? null : now; + return double; + } +} + +final tabDoubleTapProvider = Provider((ref) => TabDoubleTap()); diff --git a/lib/features/shorts/short.dart b/lib/features/shorts/short.dart index 2dc092d..298e58b 100644 --- a/lib/features/shorts/short.dart +++ b/lib/features/shorts/short.dart @@ -4,6 +4,7 @@ import 'package:flutter/widgets.dart'; import '../../core/utils/picture_fit.dart'; +import '../../data/models/image_item.dart'; import '../../data/models/marker.dart'; import '../../data/models/scene.dart'; @@ -11,9 +12,31 @@ import '../../data/models/scene.dart'; /// from its scene's stream (original resolution) between [start] and [end]. @immutable class Short { - const Short.video(this.scene) : marker = null; - - Short.marker(Marker this.marker) : scene = marker.scene; + const Short.video(this.scene) + : marker = null, + image = null; + + Short.marker(Marker this.marker) + : scene = marker.scene, + image = null; + + /// A video file shown as an image (a gallery's clip, #64). [scene] only + /// stands in for display (title, thumbnail, file, performers): it is no + /// Stash scene, so the scene actions (rating, O-counter, plays, watch + /// later, full video) don't apply ([isImage]). + Short.image(ImageItem this.image) + : marker = null, + scene = Scene( + id: 'image:${image.id}', + title: image.title, + duration: image.videoDuration ?? 0, + width: image.width, + height: image.height, + screenshotUrl: image.thumbnailUrl, + streamUrl: image.imageUrl, + studio: image.studio, + performers: image.performers, + ); /// Length of a marker clip without an end time; Stash's marker previews /// are as long. @@ -21,9 +44,12 @@ class Short { final Scene scene; final Marker? marker; + final ImageItem? image; bool get isMarker => marker != null; + bool get isImage => image != null; + /// Unique in a feed: a scene can be a short and have markers in it. String get key => marker == null ? scene.id : 'marker:${marker!.id}'; diff --git a/lib/features/shorts/shorts_feed.dart b/lib/features/shorts/shorts_feed.dart index 1b96625..4232faf 100644 --- a/lib/features/shorts/shorts_feed.dart +++ b/lib/features/shorts/shorts_feed.dart @@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../core/pagination/paged_notifier.dart'; +import '../../data/models/image_item.dart'; import '../../data/models/list_queries.dart'; import '../../data/models/marker.dart'; import '../../data/models/page_result.dart'; @@ -98,6 +99,7 @@ class ShortsSource { title = null, lane = null, markers = null, + images = null, loops = false, startPage = 1; @@ -109,6 +111,7 @@ class ShortsSource { title = null, lane = null, markers = null, + images = null, loops = true, startPage = 1; @@ -116,6 +119,7 @@ class ShortsSource { : studioId = null, lane = null, markers = null, + images = null, loops = false, startPage = 1; @@ -124,6 +128,7 @@ class ShortsSource { : performerId = null, lane = null, markers = null, + images = null, loops = false, startPage = 1; @@ -134,6 +139,7 @@ class ShortsSource { studioId = null, title = null, markers = null, + images = null, loops = false, startPage = 1; @@ -144,6 +150,16 @@ class ShortsSource { : performerId = null, studioId = null, lane = null, + images = null, + loops = false; + + /// The video files of an image grid (a gallery's clips, #64), in its + /// order, from its page [startPage] on; its pictures are left out. + const ShortsSource.images(ImageQuery this.images, {this.startPage = 1, this.title}) + : performerId = null, + studioId = null, + lane = null, + markers = null, loops = false; final String? performerId; @@ -155,6 +171,9 @@ class ShortsSource { /// The markers grid's query, for [ShortsSource.markers]. final MarkerQuery? markers; + /// The image grid's query, for [ShortsSource.images]. + final ImageQuery? images; + /// [ShortsSource.loops]. final bool loops; @@ -169,7 +188,7 @@ class ShortsSource { /// The shorts tab's own feed (videos or loops), which the shorts/loops /// switch changes. - bool get isFeed => performerId == null && studioId == null && lane == null && markers == null; + bool get isFeed => performerId == null && studioId == null && lane == null && markers == null && images == null; /// A channel's videos that fit the shorts settings' [filter] (length and /// orientation); null for the mixed feeds. @@ -188,11 +207,12 @@ class ShortsSource { other.studioId == studioId && other.lane == lane && other.markers == markers && + other.images == images && other.loops == loops && other.startPage == startPage; @override - int get hashCode => Object.hash(performerId, studioId, lane, markers, loops, startPage); + int get hashCode => Object.hash(performerId, studioId, lane, markers, images, loops, startPage); } /// Where a tapped marker is in the shorts of [ShortsSource.markers]: the @@ -214,6 +234,23 @@ class ShortsSource { return (startPage: startPage, initialIndex: initialIndex); } +/// Where a tapped clip is in the shorts of [ShortsSource.images]: like +/// [markerShortsStart], counting only the grid's videos. +({int startPage, int initialIndex}) imageShortsStart( + List items, + int index, { + int? page, + int perPage = PagedNotifier.pageSize, +}) { + final startPage = page ?? index ~/ perPage + 1; + final first = page == null ? (startPage - 1) * perPage : 0; + var initialIndex = 0; + for (var i = first; i < index && i < items.length; i++) { + if (items[i].isVideo && items[i].imageUrl != null) initialIndex++; + } + return (startPage: startPage, initialIndex: initialIndex); +} + /// Endless, shuffled feed of shorts built from [shortsSettingsProvider]: /// the length and orientation always apply, the preferred tags only to the /// tab's feeds. [ShortsSource.loops] plays scene markers instead of videos. @@ -240,6 +277,11 @@ class ShortsFeedNotifier extends Notifier { /// Whether the next short is a video (else a marker), while both last. bool _videoTurn = true; + /// [ShortsSource.images]: the grid's videos, in its order. + final _clips = Queue(); + bool _clipsDone = true; + int _clipsPage = 0; + /// Bumped on every build, so loads of a previous build are dropped. int _generation = 0; bool _loading = false; @@ -247,13 +289,18 @@ class ShortsFeedNotifier extends Notifier { @override ShortsFeedState build() { ref.watch(stashRepositoryProvider); - // A markers grid's markers: no settings apply. - final settings = source.markers == null ? ref.watch(shortsSettingsProvider) : const ShortsSettings(); + // A markers or image grid's items: no settings apply. + final settings = + source.markers == null && source.images == null ? ref.watch(shortsSettingsProvider) : const ShortsSettings(); final channelQuery = source.channelQuery(settings.baseFilter); if (source.markers case final markers?) { _preferredQuery = null; _othersQuery = null; _markerQuery = markers; + } else if (source.images != null) { + _preferredQuery = null; + _othersQuery = null; + _markerQuery = null; } else if (channelQuery != null) { _preferredQuery = null; _othersQuery = channelQuery; @@ -275,6 +322,9 @@ class ShortsFeedNotifier extends Notifier { _markersDone = _markerQuery == null; _markersPage = source.startPage - 1; _videoTurn = true; + _clips.clear(); + _clipsDone = source.images == null; + _clipsPage = source.startPage - 1; _loading = false; final generation = ++_generation; Future.microtask(() { @@ -287,7 +337,9 @@ class ShortsFeedNotifier extends Notifier { bool get _needsMarkers => !_markersDone && _markers.length < 2; - bool get _isExhausted => _mixer.isExhausted && _markersDone && _markers.isEmpty; + bool get _needsClips => !_clipsDone && _clips.length < 2; + + bool get _isExhausted => _mixer.isExhausted && _markersDone && _markers.isEmpty && _clipsDone && _clips.isEmpty; Future loadMore() async { final generation = _generation; @@ -302,10 +354,11 @@ class ShortsFeedNotifier extends Notifier { if (_mixer.needsPreferred) _load(preferred: true), if (_mixer.needsOthers) _load(preferred: false), if (_needsMarkers) _loadMarkers(), + if (_needsClips) _loadClips(), ]); if (!ref.mounted || generation != _generation) return; final taken = _take(_pageSize - added.length); - if (taken.isEmpty && !_mixer.needsPreferred && !_mixer.needsOthers && !_needsMarkers) break; + if (taken.isEmpty && !_mixer.needsPreferred && !_mixer.needsOthers && !_needsMarkers && !_needsClips) break; added.addAll(taken); } state = ShortsFeedState(items: [...state.items, ...added], hasMore: !_isExhausted); @@ -321,6 +374,13 @@ class ShortsFeedNotifier extends Notifier { /// the source whose turn it is waits for its next page. List _take(int count) { final result = []; + // An image grid's clips: only those, in order. + if (source.images != null) { + while (result.length < count && _clips.isNotEmpty) { + result.add(_clips.removeFirst()); + } + return result; + } while (result.length < count) { final videosLeft = !_mixer.isExhausted; final markersLeft = !_markersDone || _markers.isNotEmpty; @@ -358,6 +418,16 @@ class ShortsFeedNotifier extends Notifier { } } + Future _loadClips() async { + final generation = _generation; + final page = _clipsPage + 1; + final result = await ref.read(stashRepositoryProvider).findImages(source.images!, page: page, perPage: _pageSize); + if (!ref.mounted || generation != _generation) return; + _clipsPage = page; + _clips.addAll([for (final i in result.items) if (i.isVideo && i.imageUrl != null) Short.image(i)]); + _clipsDone = result.items.isEmpty || page * _pageSize >= result.totalCount; + } + Future _loadMarkers() async { final generation = _generation; final page = _markersPage + 1; diff --git a/lib/features/shorts/shorts_page.dart b/lib/features/shorts/shorts_page.dart index d35f7df..d07a1e3 100644 --- a/lib/features/shorts/shorts_page.dart +++ b/lib/features/shorts/shorts_page.dart @@ -306,7 +306,8 @@ class _ShortsPageState extends ConsumerState { _positionSub?.cancel(); final scene = short.scene; final player = _players?[_slot(_index)]; - if (player == null || _counted.contains(scene.id)) return; + // A gallery's clip is no scene: nothing to count. + if (player == null || short.isImage || _counted.contains(scene.id)) return; // Positions run from 0 for a marker's clip too (Short.playbackUrl). final threshold = Duration(milliseconds: (short.duration * 500).round().clamp(1000, 15000)); _positionSub = player.stream.position.listen((position) { @@ -870,6 +871,8 @@ class _ShortViewState extends ConsumerState<_ShortView> { // less of the video; pausing shows the rest. Screen readers get all. final showAll = widget.paused || MediaQuery.accessibleNavigationOf(context); final showInfo = showAll || _infoShown; + // A gallery's clip: no scene to rate, count, save or open. + final sceneActions = !short.isImage; return Stack( fit: StackFit.expand, @@ -982,7 +985,7 @@ class _ShortViewState extends ConsumerState<_ShortView> { const SizedBox(height: 4), Text( [ - l.playsCount(scene.playCount), + if (sceneActions) l.playsCount(scene.playCount), // A ranged marker with its place in the scene. if (marker?.endSeconds case final end?) markerTimeLabel(l, marker!.seconds, end, withLength: true) @@ -1011,6 +1014,7 @@ class _ShortViewState extends ConsumerState<_ShortView> { child: ChannelAvatar(name: performer.name, imageUrl: performer.imageUrl, radius: 22), ), ), + if (sceneActions) ...[ Row( mainAxisSize: MainAxisSize.min, children: [ @@ -1065,6 +1069,7 @@ class _ShortViewState extends ConsumerState<_ShortView> { ], ), ), + ], ], ), ), @@ -1085,7 +1090,7 @@ class _ShortViewState extends ConsumerState<_ShortView> { opacity: showBar ? 1 : 0, duration: const Duration(milliseconds: 250), child: PreviewSeekBar( - sceneId: scene.id, + sceneId: short.isImage ? null : scene.id, player: controller.player, // A marker's bar covers only its clip. window: short.isMarker ? (start: short.start!, end: short.end!) : null, diff --git a/lib/features/subscriptions/subscriptions_page.dart b/lib/features/subscriptions/subscriptions_page.dart index 7009e88..aab9753 100644 --- a/lib/features/subscriptions/subscriptions_page.dart +++ b/lib/features/subscriptions/subscriptions_page.dart @@ -23,7 +23,7 @@ import 'last_visit.dart'; /// filter: "All" (the default) lists the newest scenes of all favorites /// ([SceneQuery.newFromFavorites], shared with home's shelf), one avatar /// only that performer's scenes, newest first, with "View channel". The -/// avatars open the channel only on a long press, so a tap never leaves the +/// avatars open the channel only on a double tap or a long press, so a tap never leaves the /// page. A dot marks performers with scenes added since the last visit. An /// optional tab, a tile on the "You" page and home's "New from favorites" /// "See all". @@ -116,6 +116,7 @@ class _SubscriptionsPageState extends ConsumerState { child: FavoritePerformersRow( selectedId: selected?.id, onSelected: _select, + onShowAll: () => openAllFavorites(ref), controller: _avatarScroll, ), ), @@ -126,6 +127,13 @@ class _SubscriptionsPageState extends ConsumerState { } } +/// All favorite performers as a grid ([PerformersPage] on its favorites +/// sort): a double tap on "All" or "Show all" in the header. +void openAllFavorites(WidgetRef ref) { + Haptics.selection(); + openPage(ref, const PerformersPage(initialSort: PerformerSort.favorites)); +} + /// What the feed below shows: all favorites, or one performer with a way /// to their channel. class _SelectionHeader extends ConsumerWidget { @@ -159,6 +167,12 @@ class _SelectionHeader extends ConsumerWidget { Haptics.selection(); openPerformer(ref, performer.id); }, + ) + else + TextButton.icon( + icon: const Icon(Icons.people_outline), + label: Text(l.subscriptionsShowAll), + onPressed: () => openAllFavorites(ref), ), ], ), @@ -168,13 +182,15 @@ class _SelectionHeader extends ConsumerWidget { /// The favorite performers' avatars in a horizontal row. With [onSelected] /// it starts with "All", and a tap selects ([onSelected] with null for -/// "All") while a long press opens the channel; without, a tap opens the -/// channel. Loads further pages as it scrolls. +/// "All") while a double tap or a long press opens the channel; without, a +/// tap opens the channel. A double tap on "All" calls [onShowAll]. Loads further pages as +/// it scrolls. class FavoritePerformersRow extends ConsumerWidget { - const FavoritePerformersRow({super.key, this.selectedId, this.onSelected, this.controller}); + const FavoritePerformersRow({super.key, this.selectedId, this.onSelected, this.onShowAll, this.controller}); final String? selectedId; final ValueChanged? onSelected; + final VoidCallback? onShowAll; final ScrollController? controller; static const _avatarRadius = 30.0; @@ -212,6 +228,7 @@ class FavoritePerformersRow extends ConsumerWidget { width: _itemWidth, radius: _avatarRadius, onTap: () => onSelected(null), + onDoubleTap: onShowAll, ); } final i = index - lead; @@ -265,12 +282,19 @@ class _SelectionRing extends StatelessWidget { double _innerRadius(double radius) => radius - _SelectionRing.width - _SelectionRing.gap; class _AllAvatar extends StatelessWidget { - const _AllAvatar({required this.selected, required this.width, required this.radius, required this.onTap}); + const _AllAvatar({ + required this.selected, + required this.width, + required this.radius, + required this.onTap, + this.onDoubleTap, + }); final bool selected; final double width; final double radius; final VoidCallback onTap; + final VoidCallback? onDoubleTap; @override Widget build(BuildContext context) { @@ -286,6 +310,7 @@ class _AllAvatar extends StatelessWidget { key: const ValueKey('favorites-all'), borderRadius: AppRadius.cardBorder, onTap: onTap, + onDoubleTap: onDoubleTap, child: SizedBox( width: width, child: Column( @@ -358,6 +383,7 @@ class _Avatar extends ConsumerWidget { child: InkWell( borderRadius: AppRadius.cardBorder, onTap: select ?? openChannel, + onDoubleTap: select == null ? null : openChannel, onLongPress: select == null ? null : openChannel, child: SizedBox( width: width, diff --git a/lib/features/tags/tag_page.dart b/lib/features/tags/tag_page.dart index a66bc11..9c062c4 100644 --- a/lib/features/tags/tag_page.dart +++ b/lib/features/tags/tag_page.dart @@ -2,8 +2,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../data/models/list_queries.dart'; -import '../../data/models/scene_filter.dart'; -import '../../data/models/tag.dart'; import '../../data/providers.dart'; import '../../widgets/channel_header.dart'; import '../../widgets/scene_feed.dart'; @@ -35,12 +33,9 @@ class TagPage extends ConsumerWidget { ), ], body: SceneFeedView( - initialQuery: SceneQuery( - sort: SceneSort.newest, - // The filter compares tags by id only. - filter: SceneFilter(tags: [Tag(id: tagId, name: '')]), - ), + initialQuery: SceneQuery(sort: SceneSort.newest, tagId: tagId), sorts: _sorts, + filterable: true, headerSlivers: [ SliverToBoxAdapter( child: tag.when( diff --git a/lib/features/tags/tags_page.dart b/lib/features/tags/tags_page.dart index 95ebc18..db9fdba 100644 --- a/lib/features/tags/tags_page.dart +++ b/lib/features/tags/tags_page.dart @@ -44,7 +44,7 @@ class _TagsPageState extends ConsumerState { child: CustomScrollView( physics: const AlwaysScrollableScrollPhysics(), slivers: [ - SliverToBoxAdapter( + PinnedBar( child: ChipBar( values: TagSort.values, selected: _query.sort, diff --git a/lib/features/whats_new/whats_new.dart b/lib/features/whats_new/whats_new.dart index 5c2f356..4a82ef2 100644 --- a/lib/features/whats_new/whats_new.dart +++ b/lib/features/whats_new/whats_new.dart @@ -18,6 +18,22 @@ typedef ChangelogItem = ({IconData icon, String text}); /// its texts in both ARB files, one change per line, the most relevant /// first, and an icon per line. List changelog(AppLocalizations l) => [ + ( + id: 4, + title: l.whatsNew4Title, + items: _items(l.whatsNew4, const [ + Icons.movie_outlined, // gallery videos + Icons.slow_motion_video, // clips as shorts + Icons.vertical_align_top, // sticky bars, back to top + Icons.touch_app_outlined, // double tap You, swipe up + Icons.favorite_border, // favorites + Icons.tune, // tag filters + ]), + more: _items(l.whatsNew4More, const [ + Icons.fast_forward_outlined, // double tap sides + Icons.settings_outlined, // back to top setting + ]), + ), ( id: 3, title: l.whatsNew3Title, diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index f485f85..7e0dd7e 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -200,6 +200,10 @@ "subscriptionsAll": "Alle", "subscriptionsAllLabel": "Alle Favoriten", "subscriptionsLatest": "Neueste Videos deiner Favoriten", + "scrollToTop": "Nach oben", + "scrollToTopSetting": "„Nach oben“-Button", + "scrollToTopSettingSubtitle": "Zeigt in langen Listen eine Taste, um zum Anfang zurückzuspringen", + "subscriptionsShowAll": "Alle zeigen", "subscriptionsViewChannel": "Kanal ansehen", "subscriptionsPerformerEmpty": "Noch keine Videos mit {name}", "subscriptionsSelectHint": "Tippen zeigt nur ihre Videos, Halten öffnet den Kanal", @@ -500,6 +504,13 @@ "fileFrameRate": "Bildrate", "fileBitRate": "Bitrate", "fileModified": "Geändert", + "imageVideoLabel": "Video: {title}, {duration}", + "imageVideoMute": "Stumm", + "imageVideoUnmute": "Ton an", + "imageVideoPlay": "Abspielen", + "imageVideoPause": "Pause", + "imagesPlayAsShorts": "Als Shorts abspielen", + "imagesClips": "Clips", "imageInfo": "Bildinfo", "imagePhotographer": "Fotograf", "imageDimensions": "Abmessungen", @@ -756,6 +767,9 @@ "whatsNewTitle": "Neu in StashTube", "whatsNewDone": "Verstanden", "whatsNewSubtitle": "Was die letzten Updates gebracht haben", + "whatsNew4Title": "Videos in Galerien, feste Filterleisten und schnellere Gesten", + "whatsNew4": "Videodateien in Galerien laufen im Bildbetrachter, mit Zoom, Doppeltipp zum Spulen und Halten für 2×; breite Clips drehen sich mit dem Handy.\nDie Clips einer Galerie als Shorts abspielen, aus dem Raster oder dem Bildbetrachter.\nFilter- und Sortierleisten bleiben in jeder Liste oben, und ein „Nach oben“-Button springt in langen Listen zurück.\nDoppeltipp auf „Du“ in der Tab-Leiste wechselt den Server; ein Bild nach oben wischen zeigt seine Infos.\nFavoriten: Doppeltipp auf „Alle“ zeigt alle Lieblingsdarsteller, auf einen Darsteller seinen Kanal.\nTag-Seiten haben Filter.", + "whatsNew4More": "Doppeltipp zum Spulen: Beim Seitenwechsel braucht es einen neuen Doppeltipp.\nDer „Nach oben“-Button lässt sich unter Einstellungen → Darstellung ausschalten.", "whatsNew3Title": "Zurück an derselben Stelle, Favoriten und eine sicherere App-Sperre", "whatsNew3": "Listen behalten ihre Position, wenn du das Handy für den Vollbildmodus drehst und zurückkommst.\nFavoriten: Oben „Alle“ oder einen Darsteller wählen; langes Drücken öffnet seinen Kanal.\nBeim Zoomen erscheinen „Original“ und „Füllen“, wenn es einrastet, und Hilfslinien, wo das Bild einrastet.\nPIN ändern oder die App-Sperre ausschalten geht mit Face ID oder Fingerabdruck, auch wenn du die PIN vergessen hast.\nDein API-Key und Login gehen nur an deinen Server, und eine Warnung erscheint, wenn ein Proxy falsche Medienadressen herausgibt.", "whatsNew3More": "Die PIN wird mit einem viel langsameren Hash gespeichert; deine PIN bleibt dieselbe.\nLässt sich die PIN nach einer Wiederherstellung nicht lesen, bleibt die App gesperrt und bietet per Biometrie eine neue PIN oder das Zurücksetzen an.\nEin Passwort in einer Server-Adresse liegt im sicheren Speicher des Geräts.\nWeniger Anfragen: Listen sammeln sich nicht mehr in einem Cache, und die Vorschauprüfung lädt keine ganzen Dateien mehr.", diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 779ce47..af999d5 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -511,6 +511,10 @@ "subscriptionsAll": "All", "subscriptionsAllLabel": "All favorites", "subscriptionsLatest": "Newest from your favorites", + "scrollToTop": "Back to top", + "scrollToTopSetting": "\"Back to top\" button", + "scrollToTopSettingSubtitle": "Shows a button to jump back to the top of long lists", + "subscriptionsShowAll": "Show all", "subscriptionsViewChannel": "View channel", "subscriptionsPerformerEmpty": "No videos with {name} yet", "@subscriptionsPerformerEmpty": { @@ -1115,6 +1119,23 @@ "fileFrameRate": "Frame rate", "fileBitRate": "Bit rate", "fileModified": "Modified", + "imageVideoLabel": "Video: {title}, {duration}", + "@imageVideoLabel": { + "placeholders": { + "title": { + "type": "String" + }, + "duration": { + "type": "String" + } + } + }, + "imageVideoMute": "Mute", + "imageVideoUnmute": "Unmute", + "imageVideoPlay": "Play", + "imageVideoPause": "Pause", + "imagesPlayAsShorts": "Play as shorts", + "imagesClips": "Clips", "imageInfo": "Image info", "@imageInfo": { "description": "Tooltip of the image viewer's info button and title of its sheet." @@ -1553,6 +1574,9 @@ "whatsNewTitle": "What's new", "whatsNewDone": "Got it", "whatsNewSubtitle": "What the latest updates brought", + "whatsNew4Title": "Videos in galleries, sticky filters and quicker taps", + "whatsNew4": "Video files in galleries play in the image viewer, with zoom, double tap to skip and hold for 2×; wide clips turn with the phone.\nPlay a gallery's clips as shorts, from the grid or the viewer.\nFilter and sort bars stay at the top of every list, and a Back to top button jumps up long lists.\nDouble tap You in the tab bar to switch servers; swipe an image up for its info.\nFavorites: double tap All for all favorite performers, or a performer for their channel.\nTag pages have filters.", + "whatsNew4More": "Double tap to skip: switching sides takes a new double tap.\nThe Back to top button can be turned off in Settings → Appearance.", "whatsNew3Title": "Back where you were, favorites and a safer app lock", "whatsNew3": "Lists keep their place when you turn the phone for fullscreen and come back.\nFavorites: pick All or one performer at the top; a long press opens their channel.\nZooming shows Original and Fill when it snaps, and guide lines where the picture snaps.\nChange the PIN or turn the app lock off with Face ID or your fingerprint, also when you forgot the PIN.\nYour API key and login only go to your server, and a warning shows when a proxy hands out wrong media addresses.", "whatsNew3More": "The PIN is stored with a much slower hash; your PIN stays the same.\nIf the PIN can't be read after a restore, the app stays locked and offers a new PIN with biometrics, or a reset.\nA password in a server address is kept in the device's secure storage.\nFewer requests: lists no longer pile up in a cache, and the preview check no longer downloads whole files.", diff --git a/lib/l10n/gen/app_localizations.dart b/lib/l10n/gen/app_localizations.dart index f24814c..f7453f0 100644 --- a/lib/l10n/gen/app_localizations.dart +++ b/lib/l10n/gen/app_localizations.dart @@ -1238,6 +1238,30 @@ abstract class AppLocalizations { /// **'Newest from your favorites'** String get subscriptionsLatest; + /// No description provided for @scrollToTop. + /// + /// In en, this message translates to: + /// **'Back to top'** + String get scrollToTop; + + /// No description provided for @scrollToTopSetting. + /// + /// In en, this message translates to: + /// **'\"Back to top\" button'** + String get scrollToTopSetting; + + /// No description provided for @scrollToTopSettingSubtitle. + /// + /// In en, this message translates to: + /// **'Shows a button to jump back to the top of long lists'** + String get scrollToTopSettingSubtitle; + + /// No description provided for @subscriptionsShowAll. + /// + /// In en, this message translates to: + /// **'Show all'** + String get subscriptionsShowAll; + /// No description provided for @subscriptionsViewChannel. /// /// In en, this message translates to: @@ -2918,6 +2942,48 @@ abstract class AppLocalizations { /// **'Modified'** String get fileModified; + /// No description provided for @imageVideoLabel. + /// + /// In en, this message translates to: + /// **'Video: {title}, {duration}'** + String imageVideoLabel(String title, String duration); + + /// No description provided for @imageVideoMute. + /// + /// In en, this message translates to: + /// **'Mute'** + String get imageVideoMute; + + /// No description provided for @imageVideoUnmute. + /// + /// In en, this message translates to: + /// **'Unmute'** + String get imageVideoUnmute; + + /// No description provided for @imageVideoPlay. + /// + /// In en, this message translates to: + /// **'Play'** + String get imageVideoPlay; + + /// No description provided for @imageVideoPause. + /// + /// In en, this message translates to: + /// **'Pause'** + String get imageVideoPause; + + /// No description provided for @imagesPlayAsShorts. + /// + /// In en, this message translates to: + /// **'Play as shorts'** + String get imagesPlayAsShorts; + + /// No description provided for @imagesClips. + /// + /// In en, this message translates to: + /// **'Clips'** + String get imagesClips; + /// Tooltip of the image viewer's info button and title of its sheet. /// /// In en, this message translates to: @@ -4424,6 +4490,24 @@ abstract class AppLocalizations { /// **'What the latest updates brought'** String get whatsNewSubtitle; + /// No description provided for @whatsNew4Title. + /// + /// In en, this message translates to: + /// **'Videos in galleries, sticky filters and quicker taps'** + String get whatsNew4Title; + + /// No description provided for @whatsNew4. + /// + /// In en, this message translates to: + /// **'Video files in galleries play in the image viewer, with zoom, double tap to skip and hold for 2×; wide clips turn with the phone.\nPlay a gallery\'s clips as shorts, from the grid or the viewer.\nFilter and sort bars stay at the top of every list, and a Back to top button jumps up long lists.\nDouble tap You in the tab bar to switch servers; swipe an image up for its info.\nFavorites: double tap All for all favorite performers, or a performer for their channel.\nTag pages have filters.'** + String get whatsNew4; + + /// No description provided for @whatsNew4More. + /// + /// In en, this message translates to: + /// **'Double tap to skip: switching sides takes a new double tap.\nThe Back to top button can be turned off in Settings → Appearance.'** + String get whatsNew4More; + /// No description provided for @whatsNew3Title. /// /// In en, this message translates to: diff --git a/lib/l10n/gen/app_localizations_de.dart b/lib/l10n/gen/app_localizations_de.dart index c141f9b..d8a8113 100644 --- a/lib/l10n/gen/app_localizations_de.dart +++ b/lib/l10n/gen/app_localizations_de.dart @@ -816,6 +816,19 @@ class AppLocalizationsDe extends AppLocalizations { @override String get subscriptionsLatest => 'Neueste Videos deiner Favoriten'; + @override + String get scrollToTop => 'Nach oben'; + + @override + String get scrollToTopSetting => '„Nach oben“-Button'; + + @override + String get scrollToTopSettingSubtitle => + 'Zeigt in langen Listen eine Taste, um zum Anfang zurückzuspringen'; + + @override + String get subscriptionsShowAll => 'Alle zeigen'; + @override String get subscriptionsViewChannel => 'Kanal ansehen'; @@ -1812,6 +1825,29 @@ class AppLocalizationsDe extends AppLocalizations { @override String get fileModified => 'Geändert'; + @override + String imageVideoLabel(String title, String duration) { + return 'Video: $title, $duration'; + } + + @override + String get imageVideoMute => 'Stumm'; + + @override + String get imageVideoUnmute => 'Ton an'; + + @override + String get imageVideoPlay => 'Abspielen'; + + @override + String get imageVideoPause => 'Pause'; + + @override + String get imagesPlayAsShorts => 'Als Shorts abspielen'; + + @override + String get imagesClips => 'Clips'; + @override String get imageInfo => 'Bildinfo'; @@ -2678,6 +2714,18 @@ class AppLocalizationsDe extends AppLocalizations { @override String get whatsNewSubtitle => 'Was die letzten Updates gebracht haben'; + @override + String get whatsNew4Title => + 'Videos in Galerien, feste Filterleisten und schnellere Gesten'; + + @override + String get whatsNew4 => + 'Videodateien in Galerien laufen im Bildbetrachter, mit Zoom, Doppeltipp zum Spulen und Halten für 2×; breite Clips drehen sich mit dem Handy.\nDie Clips einer Galerie als Shorts abspielen, aus dem Raster oder dem Bildbetrachter.\nFilter- und Sortierleisten bleiben in jeder Liste oben, und ein „Nach oben“-Button springt in langen Listen zurück.\nDoppeltipp auf „Du“ in der Tab-Leiste wechselt den Server; ein Bild nach oben wischen zeigt seine Infos.\nFavoriten: Doppeltipp auf „Alle“ zeigt alle Lieblingsdarsteller, auf einen Darsteller seinen Kanal.\nTag-Seiten haben Filter.'; + + @override + String get whatsNew4More => + 'Doppeltipp zum Spulen: Beim Seitenwechsel braucht es einen neuen Doppeltipp.\nDer „Nach oben“-Button lässt sich unter Einstellungen → Darstellung ausschalten.'; + @override String get whatsNew3Title => 'Zurück an derselben Stelle, Favoriten und eine sicherere App-Sperre'; diff --git a/lib/l10n/gen/app_localizations_en.dart b/lib/l10n/gen/app_localizations_en.dart index 9476fb4..50080ab 100644 --- a/lib/l10n/gen/app_localizations_en.dart +++ b/lib/l10n/gen/app_localizations_en.dart @@ -814,6 +814,19 @@ class AppLocalizationsEn extends AppLocalizations { @override String get subscriptionsLatest => 'Newest from your favorites'; + @override + String get scrollToTop => 'Back to top'; + + @override + String get scrollToTopSetting => '\"Back to top\" button'; + + @override + String get scrollToTopSettingSubtitle => + 'Shows a button to jump back to the top of long lists'; + + @override + String get subscriptionsShowAll => 'Show all'; + @override String get subscriptionsViewChannel => 'View channel'; @@ -1805,6 +1818,29 @@ class AppLocalizationsEn extends AppLocalizations { @override String get fileModified => 'Modified'; + @override + String imageVideoLabel(String title, String duration) { + return 'Video: $title, $duration'; + } + + @override + String get imageVideoMute => 'Mute'; + + @override + String get imageVideoUnmute => 'Unmute'; + + @override + String get imageVideoPlay => 'Play'; + + @override + String get imageVideoPause => 'Pause'; + + @override + String get imagesPlayAsShorts => 'Play as shorts'; + + @override + String get imagesClips => 'Clips'; + @override String get imageInfo => 'Image info'; @@ -2667,6 +2703,18 @@ class AppLocalizationsEn extends AppLocalizations { @override String get whatsNewSubtitle => 'What the latest updates brought'; + @override + String get whatsNew4Title => + 'Videos in galleries, sticky filters and quicker taps'; + + @override + String get whatsNew4 => + 'Video files in galleries play in the image viewer, with zoom, double tap to skip and hold for 2×; wide clips turn with the phone.\nPlay a gallery\'s clips as shorts, from the grid or the viewer.\nFilter and sort bars stay at the top of every list, and a Back to top button jumps up long lists.\nDouble tap You in the tab bar to switch servers; swipe an image up for its info.\nFavorites: double tap All for all favorite performers, or a performer for their channel.\nTag pages have filters.'; + + @override + String get whatsNew4More => + 'Double tap to skip: switching sides takes a new double tap.\nThe Back to top button can be turned off in Settings → Appearance.'; + @override String get whatsNew3Title => 'Back where you were, favorites and a safer app lock'; diff --git a/lib/widgets/app_orientation.dart b/lib/widgets/app_orientation.dart index 067663c..15b944d 100644 --- a/lib/widgets/app_orientation.dart +++ b/lib/widgets/app_orientation.dart @@ -26,6 +26,9 @@ abstract final class AppOrientation { static List get allowed => _override ?? (_phone ? const [DeviceOrientation.portraitUp] : const []); + /// Whether the window is a phone's, which stays portrait. + static bool get isPhone => _phone; + /// Whether the window is a phone's (its shortest side below /// [kWideLayoutBreakpoint]). static Future setPhone(bool phone) { diff --git a/lib/widgets/chip_bar.dart b/lib/widgets/chip_bar.dart index 4686269..71b7279 100644 --- a/lib/widgets/chip_bar.dart +++ b/lib/widgets/chip_bar.dart @@ -44,3 +44,59 @@ class ChipBar extends StatelessWidget { ); } } + +/// The pinned chips: [topSpace] above them scrolls away down to [inset]; +/// the chips get the surface color and a hairline once content passes +/// beneath them. +class PinnedBarDelegate extends SliverPersistentHeaderDelegate { + PinnedBarDelegate({required this.topSpace, required this.inset, required this.height, required this.child}); + + final double topSpace; + final double inset; + final double height; + final Widget child; + + @override + double get maxExtent => topSpace + height; + + @override + double get minExtent => inset + height; + + @override + Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) { + final colors = Theme.of(context).colorScheme; + final pinned = shrinkOffset > 0 && shrinkOffset >= maxExtent - minExtent - 0.5; + return Align( + alignment: Alignment.bottomCenter, + child: DecoratedBox( + decoration: BoxDecoration( + color: colors.surface, + border: Border( + bottom: BorderSide(color: pinned ? colors.outlineVariant : colors.surface.withValues(alpha: 0), width: 0.5), + ), + ), + child: SizedBox(height: height, child: child), + ), + ); + } + + @override + bool shouldRebuild(PinnedBarDelegate old) => + old.topSpace != topSpace || old.inset != inset || old.height != height || old.child != child; +} + +/// A bar of chips (sort, filter button) that stays at the top of its list +/// while the content scrolls beneath it, like home's; below other pinned +/// headers (a channel's tab bar) when there are some. +class PinnedBar extends StatelessWidget { + const PinnedBar({super.key, required this.child, this.height = ChipBar.height}); + + final Widget child; + final double height; + + @override + Widget build(BuildContext context) => SliverPersistentHeader( + pinned: true, + delegate: PinnedBarDelegate(topSpace: 0, inset: 0, height: height, child: child), + ); +} diff --git a/lib/widgets/paged_sliver.dart b/lib/widgets/paged_sliver.dart index 4c4d161..da7f18f 100644 --- a/lib/widgets/paged_sliver.dart +++ b/lib/widgets/paged_sliver.dart @@ -10,22 +10,30 @@ import 'skeleton.dart'; import 'sliver_columns.dart'; import 'status_views.dart'; import '../l10n/l10n.dart'; +import 'scroll_to_top.dart'; /// Calls [onLoadMore] when the user scrolls near the end of the wrapped scroll view. class LoadMoreListener extends StatelessWidget { - const LoadMoreListener({super.key, required this.onLoadMore, required this.child}); + const LoadMoreListener({super.key, required this.onLoadMore, required this.child, this.scrollToTop = true}); final VoidCallback onLoadMore; final Widget child; + /// Shows the "Back to top" button ([ScrollToTop]) once the list is + /// scrolled down; off for lists inside sheets. + final bool scrollToTop; + @override - Widget build(BuildContext context) => NotificationListener( - onNotification: (n) { - if (n.metrics.axis == Axis.vertical && n.metrics.extentAfter < 800) onLoadMore(); - return false; - }, - child: child, - ); + Widget build(BuildContext context) { + final list = NotificationListener( + onNotification: (n) { + if (n.metrics.axis == Axis.vertical && n.metrics.extentAfter < 800) onLoadMore(); + return false; + }, + child: child, + ); + return scrollToTop ? ScrollToTop(child: list) : list; + } } /// For `RefreshIndicator.onRefresh`: reloads [future] (e.g. `provider(arg).future`). diff --git a/lib/widgets/scene_feed.dart b/lib/widgets/scene_feed.dart index 6b72f8e..cdb58d4 100644 --- a/lib/widgets/scene_feed.dart +++ b/lib/widgets/scene_feed.dart @@ -47,7 +47,7 @@ class SceneFeedView extends ConsumerStatefulWidget { this.emptyHint, this.onRefresh, this.belowChipsSlivers = const [], - this.pinChips = false, + this.pinChips = true, this.chipsTopSpace = 0, this.keepChipsTopSpace = false, this.unfilteredEmptyView, @@ -86,7 +86,8 @@ class SceneFeedView extends ConsumerStatefulWidget { final List belowChipsSlivers; /// Keeps the filter button, sort chips and saved filters at the top while - /// the content scrolls beneath them (HOME-1). + /// the content scrolls beneath them (HOME-1); on by default, like every + /// list's chip bar ([PinnedBar]). final bool pinChips; /// With [pinChips]: space above the chips, e.g. for an app bar laid over @@ -201,13 +202,14 @@ class _SceneFeedViewState extends ConsumerState { ], ); final height = (hasSortRow ? ChipBar.height : 0.0) + (saved ? _SavedFilterChips.height : 0.0); + if (height == 0 && widget.chipsTopSpace == 0) return const SliverToBoxAdapter(); return TweenAnimationBuilder( tween: Tween(end: widget.keepChipsTopSpace ? widget.chipsTopSpace : 0.0), duration: MediaQuery.disableAnimationsOf(context) ? Duration.zero : const Duration(milliseconds: 200), curve: Curves.easeOut, builder: (context, inset, _) => SliverPersistentHeader( pinned: true, - delegate: _PinnedChipsDelegate( + delegate: PinnedBarDelegate( topSpace: widget.chipsTopSpace, inset: inset.clamp(0.0, widget.chipsTopSpace), height: height, @@ -338,42 +340,3 @@ class _SavedFilterChips extends ConsumerWidget { } } -/// The pinned chips: [topSpace] above them scrolls away down to [inset]; -/// the chips get the surface color and a hairline once content passes -/// beneath them. -class _PinnedChipsDelegate extends SliverPersistentHeaderDelegate { - _PinnedChipsDelegate({required this.topSpace, required this.inset, required this.height, required this.child}); - - final double topSpace; - final double inset; - final double height; - final Widget child; - - @override - double get maxExtent => topSpace + height; - - @override - double get minExtent => inset + height; - - @override - Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) { - final colors = Theme.of(context).colorScheme; - final pinned = shrinkOffset > 0 && shrinkOffset >= maxExtent - minExtent - 0.5; - return Align( - alignment: Alignment.bottomCenter, - child: DecoratedBox( - decoration: BoxDecoration( - color: colors.surface, - border: Border( - bottom: BorderSide(color: pinned ? colors.outlineVariant : colors.surface.withValues(alpha: 0), width: 0.5), - ), - ), - child: SizedBox(height: height, child: child), - ), - ); - } - - @override - bool shouldRebuild(_PinnedChipsDelegate old) => - old.topSpace != topSpace || old.inset != inset || old.height != height || old.child != child; -} diff --git a/lib/widgets/scroll_to_top.dart b/lib/widgets/scroll_to_top.dart new file mode 100644 index 0000000..30b4a76 --- /dev/null +++ b/lib/widgets/scroll_to_top.dart @@ -0,0 +1,124 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../core/config/haptics.dart'; +import '../core/config/server_config.dart'; +import '../core/config/theme.dart'; +import '../l10n/l10n.dart'; + +/// Whether long lists show the "Back to top" button (Settings → Appearance); +/// on by default, stored for all servers. +class ScrollToTopNotifier extends Notifier { + static const _key = 'scroll_to_top_button'; + + @override + bool build() { + final SharedPreferences prefs; + try { + prefs = ref.watch(sharedPreferencesProvider); + } catch (_) { + // Tests of single lists don't provide preferences. + return true; + } + return prefs.getBool(_key) ?? true; + } + + Future set(bool value) async { + state = value; + await ref.read(sharedPreferencesProvider).setBool(_key, value); + } +} + +final scrollToTopProvider = NotifierProvider(ScrollToTopNotifier.new); + +/// Around a vertical list: once it is scrolled down further than +/// [ScrollToTop.threshold] screens, a "Back to top" pill floats at the bottom +/// center (clear of the FABs on the right) and scrolls the list back up. +/// Listens only to its child's outermost scrollable, not to rows inside it. +class ScrollToTop extends ConsumerStatefulWidget { + const ScrollToTop({super.key, required this.child}); + + final Widget child; + + /// In screen heights. + static const threshold = 1.5; + + /// Further than this many screens, the list first jumps closer, so the + /// way up doesn't build every item on the way. + static const jumpBeyond = 6.0; + + @override + ConsumerState createState() => _ScrollToTopState(); +} + +class _ScrollToTopState extends ConsumerState { + ScrollPosition? _position; + bool _shown = false; + + bool _onScroll(ScrollNotification n) { + if (n.depth != 0 || n.metrics.axis != Axis.vertical) return false; + final context = n.context; + if (context != null) _position = Scrollable.maybeOf(context)?.position; + final viewport = n.metrics.viewportDimension; + final shown = viewport > 0 && n.metrics.pixels > viewport * ScrollToTop.threshold; + if (shown != _shown) setState(() => _shown = shown); + return false; + } + + void _toTop() { + final position = _position; + if (position == null || !position.hasPixels) return; + Haptics.selection(); + final viewport = position.viewportDimension; + if (position.pixels > viewport * ScrollToTop.jumpBeyond) position.jumpTo(viewport * 2); + if (MediaQuery.disableAnimationsOf(context)) { + position.jumpTo(0); + } else { + position.animateTo(0, duration: const Duration(milliseconds: 400), curve: Curves.easeOutCubic); + } + } + + @override + Widget build(BuildContext context) { + final enabled = ref.watch(scrollToTopProvider); + final list = NotificationListener(onNotification: _onScroll, child: widget.child); + if (!enabled) return list; + final shown = _shown; + final animate = !MediaQuery.disableAnimationsOf(context); + return Stack( + children: [ + list, + Positioned( + left: 0, + right: 0, + bottom: AppSpacing.l, + child: Center( + child: IgnorePointer( + ignoring: !shown, + child: ExcludeSemantics( + excluding: !shown, + child: AnimatedSlide( + offset: shown ? Offset.zero : const Offset(0, 0.5), + duration: animate ? const Duration(milliseconds: 200) : Duration.zero, + curve: Curves.easeOut, + child: AnimatedOpacity( + opacity: shown ? 1 : 0, + duration: animate ? const Duration(milliseconds: 200) : Duration.zero, + child: FilledButton.tonalIcon( + key: const ValueKey('scroll-to-top'), + onPressed: _toTop, + icon: const Icon(Icons.arrow_upward), + label: Text(context.l10n.scrollToTop), + style: FilledButton.styleFrom(elevation: 3, shadowColor: Theme.of(context).colorScheme.shadow), + ), + ), + ), + ), + ), + ), + ), + ], + ); + } +} diff --git a/test/data/tag_query_test.dart b/test/data/tag_query_test.dart new file mode 100644 index 0000000..fb5d820 --- /dev/null +++ b/test/data/tag_query_test.dart @@ -0,0 +1,59 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:stash_app_mobile/data/models/list_queries.dart'; +import 'package:stash_app_mobile/data/models/scene_filter.dart'; +import 'package:stash_app_mobile/data/models/tag.dart'; + +import '../fixtures.dart'; + +void main() { + group('SceneQuery.tagId (the tag page)', () { + test('requires the tag', () { + expect(SceneQuery(tagId: 't1').toSceneFilter(), { + 'tags': {'value': ['t1'], 'modifier': 'INCLUDES_ALL', 'depth': 0}, + }); + }); + + test('adds it to the filter sheet\'s tags, which then can\'t remove it', () { + final query = SceneQuery(tagId: 't1', filter: const SceneFilter(tags: [Tag(id: 't2', name: 'B')], minStars: 3)); + final criteria = query.toSceneFilter()!; + expect(criteria['tags'], {'value': ['t2', 't1'], 'modifier': 'INCLUDES_ALL', 'depth': 0}); + expect(criteria['rating100'], isNotNull); + }); + + test('with "any of" tags it goes under AND, so both hold', () { + final query = SceneQuery( + tagId: 't1', + filter: const SceneFilter(tags: [Tag(id: 't2', name: 'B'), Tag(id: 't3', name: 'C')], anyTag: true), + ); + final criteria = query.toSceneFilter()!; + expect((criteria['tags'] as Map)['modifier'], 'INCLUDES'); + expect(criteria['AND'], { + 'tags': {'value': ['t1'], 'modifier': 'INCLUDES_ALL', 'depth': 0}, + }); + }); + + test('is part of the equality', () { + expect(SceneQuery(tagId: 't1'), SceneQuery(tagId: 't1')); + expect(SceneQuery(tagId: 't1') == SceneQuery(tagId: 't2'), isFalse); + expect(SceneQuery(tagId: 't1').copyWith(sort: SceneSort.newest).tagId, 't1'); + }); + }); + + test('a video file among the images is a video (#64)', () { + expect(imageFrom().isVideo, isFalse); + final clip = imageFrom({ + 'visual_files': [ + {'__typename': 'VideoFile', 'duration': 12.5, 'width': 1920, 'height': 1080}, + ], + }); + expect(clip.isVideo, isTrue); + expect(clip.videoDuration, 12.5); + expect(clip.aspect, 1920 / 1080); + final still = imageFrom({ + 'visual_files': [ + {'__typename': 'ImageFile'}, + ], + }); + expect(still.isVideo, isFalse); + }); +} diff --git a/test/features/demo_test.dart b/test/features/demo_test.dart index 5b01bdb..320d1fc 100644 --- a/test/features/demo_test.dart +++ b/test/features/demo_test.dart @@ -226,7 +226,9 @@ void main() { expect(group.sceneCount, 8); expect((await repo.findGroups(const GroupQuery())).items.single.name, group.name); - final gallery = (await repo.findGalleries(GalleryQuery())).items.single; + final galleries = (await repo.findGalleries(GalleryQuery())).items; + expect(galleries.map((g) => g.title), containsAll(['Stills', 'Clips'])); + final gallery = galleries.firstWhere((g) => g.title == 'Stills'); expect(gallery.imageCount, media.images.length); expect((await repo.findGallery(gallery.id)).title, 'Stills'); final images = await repo.findImages(ImageQuery(galleryId: gallery.id, sort: ImageSort.path)); @@ -244,6 +246,18 @@ void main() { expect(image.performers.single.id, '1'); expect(image.tags.single.name, 'Animation'); expect(image.galleries.single.title, 'Stills'); + expect(images.items.any((i) => i.isVideo), isFalse); + + // Video files in a gallery (#64): the image URL serves the video. + final clips = await repo.findImages(ImageQuery(galleryId: galleries.firstWhere((g) => g.title == 'Clips').id)); + expect(clips.items, isNotEmpty); + final clip = clips.items.first; + expect(clip.isVideo, isTrue); + expect(clip.videoDuration, isPositive); + expect(clip.imageUrl, endsWith('.mp4')); + expect(clip.thumbnailUrl, endsWith('.jpg')); + final clipDetails = await repo.findImageDetails(clip.id); + expect(clipDetails.file!.name, endsWith('.mp4')); final stats = await repo.libraryStats(); expect(stats.sceneCount, 12); @@ -259,28 +273,30 @@ void main() { }); test('channel tabs: profile, counts and media by performer or studio (CH-2)', () async { + // The stills and the clips gallery (#64) are Big Buck Bunny's, of studio 2. + const clips = 3; final profile = await repo.performerProfile('1'); expect(profile.aliases, ['Bunny']); expect(profile.heightCm, 180); expect(profile.career, isNotNull); - expect(profile.counts.images, media.images.length); - expect(profile.counts.galleries, 1); + expect(profile.counts.images, media.images.length + clips); + expect(profile.counts.galleries, 2); expect((await repo.performerProfile('2')).counts.galleries, 0); - expect((await repo.findImages(ImageQuery(performerId: '1'))).totalCount, media.images.length); + expect((await repo.findImages(ImageQuery(performerId: '1'))).totalCount, media.images.length + clips); expect((await repo.findImages(ImageQuery(performerId: '2'))).totalCount, 0); - expect((await repo.findGalleries(GalleryQuery(performerId: '1'))).items.single.title, 'Stills'); + expect((await repo.findGalleries(GalleryQuery(performerId: '1'))).items.map((g) => g.title), containsAll(['Stills', 'Clips'])); expect((await repo.findGalleries(GalleryQuery(performerId: '3'))).items, isEmpty); // The stills belong to the sub-studio "Peach Open Movie" of Blender Studio. final network = await repo.studioMediaCounts('1'); - expect(network.images, media.images.length); - expect(network.galleries, 1); + expect(network.images, media.images.length + clips); + expect(network.galleries, 2); expect((await repo.studioMediaCounts('3')).images, 0); expect((await repo.findGalleries(GalleryQuery(studioId: '1'))).items, isEmpty); - expect((await repo.findGalleries(GalleryQuery(studioId: '1', includeSubStudios: true))).items, hasLength(1)); - expect((await repo.findImages(ImageQuery(studioId: '2'))).totalCount, media.images.length); - expect((await repo.findImages(ImageQuery(studioId: '1', includeSubStudios: true))).totalCount, media.images.length); + expect((await repo.findGalleries(GalleryQuery(studioId: '1', includeSubStudios: true))).items, hasLength(2)); + expect((await repo.findImages(ImageQuery(studioId: '2'))).totalCount, media.images.length + clips); + expect((await repo.findImages(ImageQuery(studioId: '1', includeSubStudios: true))).totalCount, media.images.length + clips); }); test('edits last while the app runs', () async { diff --git a/test/features/home_page_test.dart b/test/features/home_page_test.dart index 4127254..d1e4fd0 100644 --- a/test/features/home_page_test.dart +++ b/test/features/home_page_test.dart @@ -77,7 +77,13 @@ void main() { container = ProviderScope.containerOf(tester.element(find.byWidget(home))); } - double barOffset(WidgetTester tester) => tester.widget(find.byType(AnimatedSlide)).offset.dy; + // The app bar's slide, not the "Back to top" button's. + double barOffset(WidgetTester tester) => tester + .widget(find.byWidgetPredicate( + (w) => w is AnimatedSlide && find.descendant(of: find.byWidget(w), matching: find.byKey(const ValueKey('scroll-to-top'))).evaluate().isEmpty, + )) + .offset + .dy; testWidgets('the app bar hides while scrolling down and comes back when scrolling up', (tester) async { await pumpHome(tester); diff --git a/test/features/library/image_viewer_dismiss_test.dart b/test/features/library/image_viewer_dismiss_test.dart index 4ae4f8c..4e2aaaa 100644 --- a/test/features/library/image_viewer_dismiss_test.dart +++ b/test/features/library/image_viewer_dismiss_test.dart @@ -7,6 +7,7 @@ import 'package:stash_app_mobile/data/models/image_item.dart'; import 'package:stash_app_mobile/data/models/list_queries.dart'; import 'package:stash_app_mobile/data/models/page_result.dart'; import 'package:stash_app_mobile/data/repositories/stash_repository.dart'; +import 'package:stash_app_mobile/features/library/image_info.dart'; import 'package:stash_app_mobile/features/library/image_viewer_page.dart'; import '../../fixtures.dart'; @@ -23,7 +24,7 @@ class _Repo implements StashRepository { ); @override - dynamic noSuchMethod(Invocation invocation) => throw UnimplementedError('${invocation.memberName}'); + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } /// Swiping the image viewer down closes it (LIB, image viewer). @@ -100,11 +101,19 @@ void main() { expect(find.byType(ImageViewerPage), findsNothing); }); - testWidgets('swiping up does not close', (tester) async { + testWidgets('swiping up opens the image info instead of closing', (tester) async { await pumpViewer(tester); await tester.fling(find.byType(PageView), const Offset(0, -300), 1500); await tester.pumpAndSettle(); expect(find.byType(ImageViewerPage), findsOneWidget); + expect(find.byType(ImageInfoSheet), findsOneWidget); + }); + + testWidgets('a small nudge up only springs back', (tester) async { + await pumpViewer(tester); + await tester.timedDrag(find.byType(PageView), const Offset(0, -60), const Duration(seconds: 1)); + await tester.pumpAndSettle(); + expect(find.byType(ImageInfoSheet), findsNothing); }); testWidgets('horizontal swipes still page between the images', (tester) async { diff --git a/test/features/player/seek_sequence_test.dart b/test/features/player/seek_sequence_test.dart index 8f41929..3d3efa4 100644 --- a/test/features/player/seek_sequence_test.dart +++ b/test/features/player/seek_sequence_test.dart @@ -201,13 +201,15 @@ void main() { expect(find.text('5 seconds'), findsOneWidget); }); - testWidgets('a tap on the other side starts a new sequence there', (tester) async { + testWidgets('the other side takes a double tap again', (tester) async { await pump(tester); await tap(tester, right(tester)); await tap(tester, right(tester)); await tap(tester, right(tester)); expect(seconds(player.seeks), [35, 40]); await tap(tester, left(tester)); + expect(seconds(player.seeks), [35, 40], reason: 'one tap on the other side only ends the sequence'); + await tap(tester, left(tester)); expect(seconds(player.seeks), [35, 40, 35], reason: '5 s back from where it is'); expect(find.text('5 seconds'), findsOneWidget); expect(find.text('10 seconds'), findsNothing); @@ -224,6 +226,7 @@ void main() { await tap(tester, left(tester)); expect(seconds(player.seeks), [25, 20]); await tap(tester, right(tester)); + await tap(tester, right(tester)); expect(seconds(player.seeks).last, 25, reason: '5 s on from 0:20, not from the stale 0:30'); expect(find.text('5 seconds'), findsOneWidget); await tap(tester, right(tester)); diff --git a/test/features/shorts_markers_ui_test.dart b/test/features/shorts_markers_ui_test.dart index 6f421f4..380349c 100644 --- a/test/features/shorts_markers_ui_test.dart +++ b/test/features/shorts_markers_ui_test.dart @@ -56,6 +56,26 @@ class _TagRepository implements StashRepository { } void main() { + testWidgets('a clip that is no scene (#64): the bar shows only the time', (tester) async { + final player = FakePlayer(position: const Duration(seconds: 3), duration: const Duration(seconds: 12)); + await tester.pumpWidget(ProviderScope( + overrides: [ + playerProvider.overrideWithValue(player), + authHeadersProvider.overrideWithValue(AuthHeaders.none), + ], + child: MaterialApp( + home: Scaffold( + body: Center(child: SizedBox(width: 400, child: PreviewSeekBar(sceneId: null, player: player))), + ), + ), + )); + await tester.pump(); + // Touching it would load the sprites and markers of a scene; there is none. + await tester.drag(find.byType(PreviewSeekBar), const Offset(100, 0)); + await tester.pump(); + expect(tester.takeException(), isNull); + }); + group('seek bar with a window (marker shorts)', () { late FakePlayer player; diff --git a/test/features/shorts_test.dart b/test/features/shorts_test.dart index 03892d7..1a048db 100644 --- a/test/features/shorts_test.dart +++ b/test/features/shorts_test.dart @@ -2,6 +2,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:stash_app_mobile/core/config/server_config.dart'; +import 'package:stash_app_mobile/data/models/image_item.dart'; import 'package:stash_app_mobile/data/models/list_queries.dart'; import 'package:stash_app_mobile/data/models/marker.dart'; import 'package:stash_app_mobile/data/models/page_result.dart'; @@ -35,11 +36,17 @@ Marker _marker(String id, {double seconds = 30, double? end, double duration = 6 /// Tagged scenes are `t`, all others `o`, markers `marker:m`; /// pages of [perPage]. class _ShortsRepository implements StashRepository { - _ShortsRepository({this.tagged = 10, this.others = 10, this.markers = 0}); + _ShortsRepository({this.tagged = 10, this.others = 10, this.markers = 0, this.images = 0}); final int tagged; final int others; final int markers; + + /// Images `i`; every third (`i0`, `i3`, ...) is a picture, the others + /// video files (#64). + final int images; + final imageQueries = []; + final imagePages = []; final queries = []; final markerQueries = []; final pages = []; @@ -71,10 +78,28 @@ class _ShortsRepository implements StashRepository { return PageResult(items: all.skip((page - 1) * perPage).take(perPage).toList(), totalCount: all.length); } + @override + Future> findImages(ImageQuery query, {int page = 1, int perPage = 24}) async { + imageQueries.add(query); + imagePages.add(page); + final all = [for (var i = 0; i < images; i++) _image(i)]; + return PageResult(items: all.skip((page - 1) * perPage).take(perPage).toList(), totalCount: all.length); + } + @override dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); } +ImageItem _image(int i) => ImageItem( + id: 'i$i', + title: 'Image $i', + thumbnailUrl: 'http://s/i$i.jpg', + imageUrl: 'http://s/i$i', + videoDuration: i % 3 == 0 ? null : 12, + width: 720, + height: 1280, + ); + Future _container(_ShortsRepository repo, [ShortsSettings? settings]) async { SharedPreferences.setMockInitialValues({}); final prefs = await SharedPreferences.getInstance(); @@ -465,4 +490,36 @@ void main() { expect(markerShortsStart(items.sublist(0, 10), 4, page: 3), (startPage: 3, initialIndex: 4)); }); }); + + group('an image grid\'s clips as shorts (#64)', () { + test('plays only its video files, in order, as image shorts', () async { + final repo = _ShortsRepository(images: 40); + final c = await _container(repo, const ShortsSettings(tags: [beach])); + final grid = ImageQuery(galleryId: 'g1', sort: ImageSort.path); + final feed = await _loaded(c, ShortsSource.images(grid)); + final videos = [for (var i = 0; i < 40; i++) if (i % 3 != 0) 'image:i$i']; + expect(feed.items.map((s) => s.key), videos.take(24)); + expect(feed.items.every((s) => s.isImage), isTrue); + expect(repo.queries, isEmpty, reason: 'no scenes'); + expect(repo.imageQueries.first, same(grid)); + + final clip = feed.items.first; + expect(clip.playbackUrl, 'http://s/i1'); + expect(clip.duration, 12); + expect(clip.aspect, 720 / 1280); + }); + + test('the tapped clip\'s place counts only videos', () { + final items = [for (var i = 0; i < 30; i++) _image(i)]; + expect(imageShortsStart(items, 4), (startPage: 1, initialIndex: 2), reason: 'i1 and i2 before it'); + expect(imageShortsStart(items, 26), (startPage: 2, initialIndex: 1), reason: 'i24 is a picture, i25 a clip'); + }); + + test('sources are equal by their query', () { + final query = ImageQuery(galleryId: 'g1'); + expect(ShortsSource.images(query, title: 'a'), ShortsSource.images(ImageQuery(galleryId: 'g1'))); + expect(ShortsSource.images(query), isNot(ShortsSource.images(query, startPage: 2))); + expect(ShortsSource.images(query).isFeed, isFalse); + }); + }); } diff --git a/test/features/subscriptions_test.dart b/test/features/subscriptions_test.dart index 00db174..34534e3 100644 --- a/test/features/subscriptions_test.dart +++ b/test/features/subscriptions_test.dart @@ -10,6 +10,8 @@ import 'package:stash_app_mobile/data/models/saved_filter.dart'; import 'package:stash_app_mobile/data/models/scene.dart'; import 'package:stash_app_mobile/data/repositories/stash_repository.dart'; import 'package:stash_app_mobile/features/shell/nav_bar_config.dart'; +import 'package:stash_app_mobile/features/performers/performer_page.dart'; +import 'package:stash_app_mobile/features/performers/performers_page.dart'; import 'package:stash_app_mobile/features/shell/navigation.dart'; import 'package:stash_app_mobile/features/subscriptions/subscriptions_page.dart'; @@ -126,6 +128,66 @@ void main() { expect(find.text('Newest from your favorites'), findsOneWidget); }); + testWidgets('a double tap on "All" (or "Show all") lists all favorites, on a performer opens the channel', (tester) async { + final prefs = (await tester.runAsync(() async { + SharedPreferences.setMockInitialValues({}); + return SharedPreferences.getInstance(); + }))!; + final container = ProviderContainer(overrides: [ + ...testServer, + sharedPreferencesProvider.overrideWithValue(prefs), + stashRepositoryProvider.overrideWithValue(_Repo()), + ]); + addTearDown(container.dispose); + await tester.pumpWidget(UncontrolledProviderScope( + container: container, + child: MaterialApp( + home: Navigator( + key: container.read(tabNavigatorKeysProvider)[container.read(currentTabProvider)], + onGenerateRoute: (_) => MaterialPageRoute(builder: (_) => const SubscriptionsPage()), + ), + ), + )); + for (var i = 0; i < 5; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + + final all = find.byKey(const ValueKey('favorites-all')); + await tester.tap(all); + await tester.pump(const Duration(milliseconds: 50)); + await tester.tap(all); + for (var i = 0; i < 6; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + expect(find.byType(PerformersPage), findsOneWidget); + expect(find.text('Newest from your favorites'), findsNothing); + + await tester.pageBack(); + for (var i = 0; i < 6; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + expect(find.byType(PerformersPage), findsNothing); + await tester.tap(find.text('Show all')); + for (var i = 0; i < 6; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + expect(find.byType(PerformersPage), findsOneWidget); + + // A double tap on a performer opens the channel. + await tester.pageBack(); + for (var i = 0; i < 6; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + final anna = find.text('Anna').first; + await tester.tap(anna); + await tester.pump(const Duration(milliseconds: 50)); + await tester.tap(anna); + for (var i = 0; i < 6; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + expect(find.byType(PerformerPage), findsOneWidget); + }); + testWidgets('no dots on the first visit', (tester) async { await pumpPage(tester, _Repo()); expect(find.text('New with Anna'), findsOneWidget); diff --git a/test/features/tab_double_tap_test.dart b/test/features/tab_double_tap_test.dart new file mode 100644 index 0000000..988f4da --- /dev/null +++ b/test/features/tab_double_tap_test.dart @@ -0,0 +1,14 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:stash_app_mobile/features/shell/navigation.dart'; + +void main() { + test('two taps on the same tab in time are a double tap', () { + final taps = TabDoubleTap(); + final t = DateTime(2026); + expect(taps.tap(AppTab.you, t), isFalse); + expect(taps.tap(AppTab.you, t.add(const Duration(milliseconds: 200))), isTrue); + expect(taps.tap(AppTab.you, t.add(const Duration(milliseconds: 300))), isFalse, reason: 'a third tap starts anew'); + expect(taps.tap(AppTab.you, t.add(const Duration(seconds: 2))), isFalse, reason: 'too late'); + expect(taps.tap(AppTab.home, t.add(const Duration(milliseconds: 2100))), isFalse, reason: 'another tab'); + }); +} diff --git a/test/features/whats_new_test.dart b/test/features/whats_new_test.dart index 8a52e80..3cb6f75 100644 --- a/test/features/whats_new_test.dart +++ b/test/features/whats_new_test.dart @@ -61,16 +61,16 @@ void main() { testWidgets('after an update: shown once', (tester) async { final c = await pump(tester); expect(find.text(l.whatsNewTitle), findsOneWidget); - expect(find.text(l.whatsNew3Title), findsOneWidget, reason: 'the newest first'); + expect(find.text(l.whatsNew4Title), findsOneWidget, reason: 'the newest first'); expect(find.byIcon(Icons.auto_awesome), findsNothing); - expect(find.byIcon(Icons.fingerprint), findsOneWidget, reason: 'the biometrics item has its icon'); + expect(find.byIcon(Icons.slow_motion_video), findsOneWidget, reason: 'the clips item has its icon'); final entry = changelog(l).first; - expect(entry.more, hasLength(4)); + expect(entry.more, hasLength(2)); final more = entry.more.first.text; expect(find.text(more, skipOffstage: false), findsNothing, reason: 'the rest waits behind "show more"'); - await tester.ensureVisible(find.text(l.whatsNewShowMore(4))); + await tester.ensureVisible(find.text(l.whatsNewShowMore(2))); await tester.pumpAndSettle(); - await tester.tap(find.text(l.whatsNewShowMore(4))); + await tester.tap(find.text(l.whatsNewShowMore(2))); await tester.pumpAndSettle(); expect(find.text(more, skipOffstage: false), findsOneWidget); expect(c.read(whatsNewSeenProvider), latestChangelogId(l)); diff --git a/test/fixtures.dart b/test/fixtures.dart index 1ac9b76..b77efd5 100644 --- a/test/fixtures.dart +++ b/test/fixtures.dart @@ -153,6 +153,7 @@ Json imageJson([Json fields = const {}]) => typed('Image', { 'date': null, 'rating100': null, 'paths': const {'thumbnail': null, 'image': null}, + 'visual_files': const [], 'studio': null, 'performers': const [], ...fields, diff --git a/test/widgets/scroll_to_top_test.dart b/test/widgets/scroll_to_top_test.dart new file mode 100644 index 0000000..044d4aa --- /dev/null +++ b/test/widgets/scroll_to_top_test.dart @@ -0,0 +1,69 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:stash_app_mobile/core/config/server_config.dart'; +import 'package:stash_app_mobile/widgets/scroll_to_top.dart'; + +void main() { + Future pump(WidgetTester tester, {Map stored = const {}}) async { + final prefs = (await tester.runAsync(() async { + SharedPreferences.setMockInitialValues(stored); + return SharedPreferences.getInstance(); + }))!; + final controller = ScrollController(); + addTearDown(controller.dispose); + await tester.pumpWidget(ProviderScope( + overrides: [sharedPreferencesProvider.overrideWithValue(prefs)], + child: MaterialApp( + home: Scaffold( + body: ScrollToTop( + child: ListView.builder( + controller: controller, + itemCount: 500, + itemBuilder: (_, i) => SizedBox( + height: 100, + // A row that scrolls sideways doesn't count. + child: i == 0 + ? ListView(scrollDirection: Axis.horizontal, children: const [SizedBox(width: 2000)]) + : Text('Item $i'), + ), + ), + ), + ), + ), + )); + return controller; + } + + bool shown(WidgetTester tester) => + tester.widget( + find.ancestor(of: find.byKey(const ValueKey('scroll-to-top')), matching: find.byType(IgnorePointer)).first, + ).ignoring == + false; + + testWidgets('shows once scrolled down and scrolls back to the top', (tester) async { + final controller = await pump(tester); + expect(shown(tester), isFalse); + + await tester.drag(find.text('Item 3'), const Offset(0, -300)); + await tester.pumpAndSettle(); + expect(shown(tester), isFalse, reason: 'not yet 1.5 screens down'); + + controller.jumpTo(20000); + await tester.pumpAndSettle(); + expect(shown(tester), isTrue); + + await tester.tap(find.byKey(const ValueKey('scroll-to-top'))); + await tester.pumpAndSettle(); + expect(controller.offset, 0); + expect(shown(tester), isFalse); + }); + + testWidgets('can be switched off in the settings', (tester) async { + final controller = await pump(tester, stored: {'scroll_to_top_button': false}); + controller.jumpTo(20000); + await tester.pumpAndSettle(); + expect(find.byKey(const ValueKey('scroll-to-top')), findsNothing); + }); +}