Skip to content

基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。

feat(player): redesign episode selection

Prediditacb28d30ac86
diff --git a/assets/images/playing.gif b/assets/images/playing.gif
deleted file mode 100644
index 20e7d6ce..00000000
Binary files a/assets/images/playing.gif and /dev/null differ
diff --git a/lib/pages/video/episode_selection_panel.dart b/lib/pages/video/episode_selection_panel.dart
new file mode 100644
index 00000000..a1acd8a9
--- /dev/null
+++ b/lib/pages/video/episode_selection_panel.dart
@@ -0,0 +1,669 @@
+import 'dart:math' as math;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/physics.dart';
+import 'package:scrollview_observer/scrollview_observer.dart';
+
+import 'package:kazumi/bean/widget/empty_state_widget.dart';
+import 'package:kazumi/modules/download/download_module.dart';
+import 'package:kazumi/modules/roads/road_module.dart';
+
+class EpisodeSelectionPanel extends StatefulWidget {
+ const EpisodeSelectionPanel({
+ super.key,
+ required this.title,
+ required this.roads,
+ required this.selectedRoad,
+ required this.selectedEpisode,
+ required this.onEpisodeSelected,
+ required this.downloads,
+ this.onDownload,
+ this.isOffline = false,
+ this.isPlaying = false,
+ this.disableAnimations = false,
+ });
+
+ final String title;
+ final List<Road> roads;
+ final int selectedRoad;
+ final int selectedEpisode;
+ final void Function(int episode, int road) onEpisodeSelected;
+ final ValueChanged<int>? onDownload;
+ final Map<String, DownloadEpisode> downloads;
+ final bool isOffline;
+ final bool isPlaying;
+ final bool disableAnimations;
+
+ @override
+ EpisodeSelectionPanelState createState() => EpisodeSelectionPanelState();
+}
+
+class EpisodeSelectionPanelState extends State<EpisodeSelectionPanel> {
+ final _scrollController = ScrollController();
+ late final _observerController =
+ ListObserverController(controller: _scrollController)
+ ..cacheJumpIndexOffset = false;
+ late int _visibleRoad = widget.selectedRoad;
+
+ bool get _canLocate =>
+ widget.selectedRoad >= 0 &&
+ widget.selectedRoad < widget.roads.length &&
+ widget.selectedEpisode > 0 &&
+ widget.selectedEpisode <= widget.roads[widget.selectedRoad].data.length;
+
+ double get _toolbarHeight =>
+ math.max(56, MediaQuery.textScalerOf(context).scale(20) + 8);
+
+ void _selectRoad(int road) {
+ if (_visibleRoad == road) return;
+ setState(() => _visibleRoad = road);
+ if (_scrollController.hasClients) _scrollController.jumpTo(0);
+ }
+
+ Future<void> revealCurrentEpisode() async {
+ if (!_canLocate) return;
+ setState(() => _visibleRoad = widget.selectedRoad);
+ // Wait for the observer to bind the new road's sliver after layout.
+ await WidgetsBinding.instance.endOfFrame;
+ if (!mounted ||
+ !_scrollController.hasClients ||
+ !_canLocate ||
+ _visibleRoad != widget.selectedRoad) {
+ return;
+ }
+
+ final index = widget.selectedEpisode - 1;
+ final toolbarHeight = _toolbarHeight;
+ final item = _observerController.observeItem(index: index);
+ if (item != null) {
+ final top = item.renderObject
+ .localToGlobal(Offset.zero, ancestor: item.viewport)
+ .dy;
+ if (top >= toolbarHeight &&
+ top + item.renderObject.size.height <= item.viewport.size.height) {
+ return;
+ }
+ }
+ await _observerController.jumpTo(
+ index: index,
+ offset: (_) => toolbarHeight,
+ );
+ }
+
+ @override
+ void dispose() {
+ _scrollController.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ final colors = theme.colorScheme;
+ final road = _visibleRoad >= 0 && _visibleRoad < widget.roads.length
+ ? widget.roads[_visibleRoad]
+ : null;
+ final count = road?.data.length ?? 0;
+
+ return LayoutBuilder(builder: (context, constraints) {
+ final textScaler = MediaQuery.textScalerOf(context);
+ return ListViewObserver(
+ controller: _observerController,
+ child: Scrollbar(
+ controller: _scrollController,
+ child: CustomScrollView(
+ controller: _scrollController,
+ slivers: [
+ SliverToBoxAdapter(
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(16, 20, 16, 4),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Semantics(
+ header: true,
+ child: Text(
+ widget.title.isEmpty ? '剧集列表' : widget.title,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: theme.textTheme.titleLarge?.copyWith(
+ fontWeight: FontWeight.w700,
+ color: colors.onSurface,
+ ),
+ ),
+ ),
+ const SizedBox(height: 16),
+ _RoadSelector(
+ roads: widget.roads,
+ visibleRoad: _visibleRoad,
+ isOffline: widget.isOffline,
+ onChanged: _selectRoad,
+ disableAnimations: widget.disableAnimations,
+ ),
+ ],
+ ),
+ ),
+ ),
+ SliverPersistentHeader(
+ pinned: true,
+ delegate: _EpisodeToolbar(
+ height: _toolbarHeight,
+ color: colors.surface,
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(16, 4, 8, 4),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ textScaler.scale(14) > 21 ||
+ constraints.maxWidth < 320
+ ? '$count 集'
+ : widget.isOffline
+ ? '已缓存 · $count 集'
+ : '全部剧集 · $count 集',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: theme.textTheme.labelLarge?.copyWith(
+ color: colors.onSurfaceVariant,
+ ),
+ ),
+ ),
+ IconButton(
+ tooltip: '定位当前集',
+ onPressed: _canLocate ? revealCurrentEpisode : null,
+ icon: const Icon(Icons.my_location_rounded, size: 20),
+ ),
+ if (!widget.isOffline)
+ IconButton.filledTonal(
+ tooltip: '缓存剧集',
+ onPressed: count > 0 && widget.onDownload != null
+ ? () => widget.onDownload!(_visibleRoad)
+ : null,
+ icon: const Icon(Icons.download_rounded, size: 20),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ if (count == 0)
+ const SliverFillRemaining(
+ hasScrollBody: false,
+ child: Padding(
+ padding: EdgeInsets.all(24),
+ child: Center(
+ child: GeneralEmptyState(
+ icon: Icons.video_library_outlined,
+ title: '这条线路暂无剧集',
+ ),
+ ),
+ ),
+ )
+ else
+ SliverPadding(
+ padding: EdgeInsets.fromLTRB(
+ 16,
+ 0,
+ 16,
+ 16 + MediaQuery.paddingOf(context).bottom,
+ ),
+ sliver: SliverList.builder(
+ itemCount: count,
+ itemBuilder: (context, index) {
+ final episode = index + 1;
+ final name = index < road!.identifier.length &&
+ road.identifier[index].trim().isNotEmpty
+ ? road.identifier[index]
+ : '第$episode集';
+ return _EpisodeRow(
+ key: ValueKey('$_visibleRoad:$episode'),
+ name: name,
+ first: index == 0,
+ last: index == count - 1,
+ selected: _visibleRoad == widget.selectedRoad &&
+ episode == widget.selectedEpisode,
+ isPlaying: widget.isPlaying,
+ isOffline: widget.isOffline,
+ download: widget.downloads[road.data[index]],
+ disableAnimations: widget.disableAnimations,
+ onTap: () =>
+ widget.onEpisodeSelected(episode, _visibleRoad),
+ );
+ },
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ });
+ }
+}
+
+class _EpisodeToolbar extends SliverPersistentHeaderDelegate {
+ const _EpisodeToolbar({
+ required this.height,
+ required this.color,
+ required this.child,
+ });
+
+ final double height;
+ final Color color;
+ final Widget child;
+
+ @override
+ double get minExtent => height;
+
+ @override
+ double get maxExtent => minExtent;
+
+ @override
+ Widget build(
+ BuildContext context, double shrinkOffset, bool overlapsContent) =>
+ // Fill minExtent even when desktop controls use a smaller touch target.
+ SizedBox.expand(child: ColoredBox(color: color, child: child));
+
+ @override
+ bool shouldRebuild(covariant _EpisodeToolbar oldDelegate) =>
+ height != oldDelegate.height ||
+ color != oldDelegate.color ||
+ child != oldDelegate.child;
+}
+
+class _RoadSelector extends StatefulWidget {
+ const _RoadSelector({
+ required this.roads,
+ required this.visibleRoad,
+ required this.isOffline,
+ required this.onChanged,
+ required this.disableAnimations,
+ });
+
+ final List<Road> roads;
+ final int visibleRoad;
+ final bool isOffline;
+ final ValueChanged<int> onChanged;
+ final bool disableAnimations;
+
+ @override
+ State<_RoadSelector> createState() => _RoadSelectorState();
+}
+
+class _RoadSelectorState extends State<_RoadSelector> {
+ final _focusNode = FocusNode(debugLabel: 'Playback road selector');
+ bool _open = false;
+
+ String _name(int index) => index >= 0 && index < widget.roads.length
+ ? (widget.roads[index].name.trim().isEmpty
+ ? '播放线路 ${index + 1}'
+ : widget.roads[index].name)
+ : '暂无线路';
+
+ void _setOpen(bool value) {
+ if (mounted) setState(() => _open = value);
+ }
+
+ @override
+ void dispose() {
+ _focusNode.dispose();
+ super.dispose();
+ }
+
+ Widget _buildMenuItem(int index, double width) {
+ final theme = Theme.of(context);
+ final colors = theme.colorScheme;
+ final road = widget.roads[index];
+ final selected = index == widget.visibleRoad;
+ final last = index == widget.roads.length - 1;
+ return Padding(
+ padding: EdgeInsets.only(bottom: last ? 0 : 2),
+ child: Semantics(
+ selected: selected,
+ inMutuallyExclusiveGroup: true,
+ child: MenuItemButton(
+ key: ValueKey('road-option-$index'),
+ onPressed: () => widget.onChanged(index),
+ style: ButtonStyle(
+ minimumSize: WidgetStatePropertyAll(Size(width, 56)),
+ padding: const WidgetStatePropertyAll(
+ EdgeInsets.symmetric(horizontal: 16, vertical: 12)),
+ visualDensity: VisualDensity.standard,
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ backgroundColor: WidgetStatePropertyAll(
+ selected ? colors.secondaryContainer : colors.surfaceContainerLow,
+ ),
+ foregroundColor: WidgetStatePropertyAll(
+ selected ? colors.onSecondaryContainer : colors.onSurface,
+ ),
+ textStyle: WidgetStatePropertyAll(
+ theme.textTheme.labelLarge?.copyWith(
+ fontWeight: selected ? FontWeight.w700 : FontWeight.w500,
+ ),
+ ),
+ shape: WidgetStatePropertyAll(RoundedRectangleBorder(
+ borderRadius: selected
+ ? BorderRadius.circular(20)
+ : BorderRadius.vertical(
+ top: Radius.circular(index == 0 ? 20 : 4),
+ bottom: Radius.circular(last ? 20 : 4),
+ ),
+ )),
+ ),
+ trailingIcon:
+ selected ? const Icon(Icons.check_rounded, size: 20) : null,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(_name(index), maxLines: 2, overflow: TextOverflow.ellipsis),
+ const SizedBox(height: 4),
+ Text(
+ '${road.data.length} 集',
+ style: theme.textTheme.bodySmall?.copyWith(
+ color: selected
+ ? colors.onSecondaryContainer
+ : colors.onSurfaceVariant,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ final colors = theme.colorScheme;
+ final canSwitch = widget.roads.length > 1;
+ final reduceMotion =
+ widget.disableAnimations || MediaQuery.disableAnimationsOf(context);
+ final duration =
+ reduceMotion ? Duration.zero : const Duration(milliseconds: 200);
+ final foreground = _open ? colors.onSecondaryContainer : colors.onSurface;
+
+ return LayoutBuilder(builder: (context, constraints) {
+ final width =
+ math.min(constraints.maxWidth, MediaQuery.sizeOf(context).width - 32);
+ return MenuAnchor(
+ childFocusNode: _focusNode,
+ crossAxisUnconstrained: false,
+ consumeOutsideTap: true,
+ animated: !reduceMotion,
+ onOpen: () => _setOpen(true),
+ onClose: () => _setOpen(false),
+ alignmentOffset: const Offset(0, 8),
+ style: MenuStyle(
+ alignment: AlignmentDirectional.bottomStart,
+ backgroundColor: WidgetStatePropertyAll(colors.surfaceContainer),
+ surfaceTintColor: const WidgetStatePropertyAll(Colors.transparent),
+ elevation: const WidgetStatePropertyAll(3),
+ padding: const WidgetStatePropertyAll(EdgeInsets.all(8)),
+ shape: WidgetStatePropertyAll(RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(28),
+ )),
+ minimumSize: WidgetStatePropertyAll(Size(width, 0)),
+ maximumSize: WidgetStatePropertyAll(Size(
+ width, math.min(400, MediaQuery.sizeOf(context).height - 32))),
+ visualDensity: VisualDensity.standard,
+ ),
+ menuChildren: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(12, 8, 12, 12),
+ child: Text(
+ '选择播放线路',
+ style: theme.textTheme.labelLarge?.copyWith(
+ color: colors.onSurfaceVariant,
+ ),
+ ),
+ ),
+ for (var i = 0; i < widget.roads.length; i++)
+ _buildMenuItem(i, width - 16),
+ ],
+ builder: (context, controller, child) => Semantics(
+ button: canSwitch,
+ expanded: canSwitch ? _open : null,
+ label: canSwitch ? '切换播放线路' : null,
+ child: Material(
+ animationDuration: duration,
+ color:
+ _open ? colors.secondaryContainer : colors.surfaceContainerLow,
+ borderRadius: BorderRadius.circular(_open ? 16 : 20),
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ focusNode: _focusNode,
+ onTap: canSwitch
+ ? () =>
+ controller.isOpen ? controller.close() : controller.open()
+ : null,
+ child: Padding(
+ padding:
+ const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
+ child: Row(
+ children: [
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ widget.isOffline ? '离线观看' : '播放线路',
+ style: theme.textTheme.labelMedium
+ ?.copyWith(color: foreground),
+ ),
+ const SizedBox(height: 2),
+ Text(
+ _name(widget.visibleRoad),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: theme.textTheme.titleSmall?.copyWith(
+ fontWeight: FontWeight.w700,
+ color: foreground,
+ ),
+ ),
+ ],
+ ),
+ ),
+ if (canSwitch) ...[
+ const SizedBox(width: 8),
+ AnimatedRotation(
+ turns: _open ? 0.5 : 0,
+ duration: duration,
+ curve: Curves.easeOutCubic,
+ child: Icon(Icons.keyboard_arrow_down_rounded,
+ color: foreground),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ });
+ }
+}
+
+class _EpisodeRow extends StatefulWidget {
+ const _EpisodeRow({
+ super.key,
+ required this.name,
+ required this.first,
+ required this.last,
+ required this.selected,
+ required this.isPlaying,
+ required this.isOffline,
+ required this.disableAnimations,
+ required this.onTap,
+ this.download,
+ });
+
+ final String name;
+ final bool first;
+ final bool last;
+ final bool selected;
+ final bool isPlaying;
+ final bool isOffline;
+ final bool disableAnimations;
+ final VoidCallback onTap;
+ final DownloadEpisode? download;
+
+ @override
+ State<_EpisodeRow> createState() => _EpisodeRowState();
+}
+
+class _EpisodeRowState extends State<_EpisodeRow>
+ with SingleTickerProviderStateMixin {
+ late final _press = AnimationController.unbounded(vsync: this);
+
+ bool get _reduceMotion =>
+ widget.disableAnimations || MediaQuery.disableAnimationsOf(context);
+
+ void _setPressed(bool pressed) {
+ final target = pressed ? 1.0 : 0.0;
+ if (_reduceMotion) {
+ _press.value = target;
+ return;
+ }
+ _press.animateWith(SpringSimulation(
+ SpringDescription.withDampingRatio(
+ mass: 1,
+ stiffness: 500,
+ ratio: 0.8,
+ ),
+ _press.value,
+ target,
+ _press.velocity,
+ ));
+ }
+
+ @override
+ void dispose() {
+ _press.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ final colors = theme.colorScheme;
+ final foreground = widget.selected ? colors.onPrimary : colors.onSurface;
+ final status =
+ widget.isOffline ? DownloadStatus.completed : widget.download?.status;
+ final downloadLabel = switch (status) {
+ DownloadStatus.completed => '已缓存',
+ DownloadStatus.downloading => '正在缓存',
+ DownloadStatus.failed => '缓存失败',
+ DownloadStatus.paused => '缓存已暂停',
+ DownloadStatus.pending => '等待缓存',
+ DownloadStatus.resolving => '正在解析',
+ _ => null,
+ };
+ final playbackLabel =
+ widget.selected ? (widget.isPlaying ? '正在播放' : '当前选集') : '播放';
+
+ final supportingText = [
+ if (widget.selected) playbackLabel,
+ if (!widget.isOffline && downloadLabel != null)
+ status == DownloadStatus.downloading
+ ? '缓存 ${(widget.download!.progressPercent.clamp(0, 1) * 100).round()}%'
+ : downloadLabel,
+ ].join(' · ');
+
+ return Semantics(
+ button: true,
+ onTap: widget.onTap,
+ selected: widget.selected,
+ inMutuallyExclusiveGroup: true,
+ label: '${widget.name},$playbackLabel'
+ '${downloadLabel == null ? '' : ',$downloadLabel'}',
+ child: Tooltip(
+ message: '${widget.name} · $playbackLabel'
+ '${downloadLabel == null ? '' : ' · $downloadLabel'}',
+ excludeFromSemantics: true,
+ child: AnimatedBuilder(
+ animation: _press,
+ builder: (context, child) {
+ final restShape = widget.selected
+ ? BorderRadius.circular(20)
+ : BorderRadius.vertical(
+ top: Radius.circular(widget.first ? 20 : 4),
+ bottom: Radius.circular(widget.last ? 20 : 4),
+ );
+ final press = _press.value.clamp(0.0, 1.0);
+ return Padding(
+ padding: EdgeInsets.only(bottom: widget.last ? 0 : 2),
+ child: Material(
+ animationDuration: _reduceMotion
+ ? Duration.zero
+ : const Duration(milliseconds: 200),
+ color: widget.selected
+ ? colors.primary
+ : colors.surfaceContainerLow,
+ borderRadius: BorderRadius.lerp(
+ restShape, BorderRadius.circular(12), press),
+ clipBehavior: Clip.antiAlias,
+ child: child,
+ ),
+ );
+ },
+ child: InkWell(
+ onTap: widget.onTap,
+ onHighlightChanged: _setPressed,
+ excludeFromSemantics: true,
+ overlayColor: WidgetStateProperty.resolveWith((states) {
+ if (states.contains(WidgetState.pressed) ||
+ states.contains(WidgetState.focused)) {
+ return foreground.withValues(alpha: 0.1);
+ }
+ if (states.contains(WidgetState.hovered)) {
+ return foreground.withValues(alpha: 0.08);
+ }
+ return null;
+ }),
+ child: ExcludeSemantics(
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(minHeight: 56),
+ child: Padding(
+ padding:
+ const EdgeInsets.symmetric(horizontal: 20, vertical: 16),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ widget.name,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: theme.textTheme.bodyLarge?.copyWith(
+ color: foreground,
+ fontWeight: widget.selected
+ ? FontWeight.w700
+ : FontWeight.w500,
+ ),
+ ),
+ if (supportingText.isNotEmpty) ...[
+ const SizedBox(height: 4),
+ Text(
+ supportingText,
+ style: theme.textTheme.bodySmall?.copyWith(
+ color: widget.selected
+ ? foreground
+ : status == DownloadStatus.failed
+ ? colors.error
+ : colors.onSurfaceVariant,
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/pages/video/player_content_tabs.dart b/lib/pages/video/player_content_tabs.dart
new file mode 100644
index 00000000..6039875d
--- /dev/null
+++ b/lib/pages/video/player_content_tabs.dart
@@ -0,0 +1,59 @@
+import 'package:flutter/material.dart';
+
+class PlayerContentTabs extends StatelessWidget {
+ const PlayerContentTabs({
+ super.key,
+ required this.controller,
+ required this.onEpisodesSelected,
+ this.trailing,
+ });
+
+ final TabController controller;
+ final VoidCallback onEpisodesSelected;
+ final Widget? trailing;
+
+ @override
+ Widget build(BuildContext context) {
+ final theme = Theme.of(context);
+ final colors = theme.colorScheme;
+ final height = (MediaQuery.textScalerOf(context).scale(14) * 1.5 + 16)
+ .clamp(48.0, double.infinity);
+
+ return Material(
+ color: colors.surface,
+ child: Row(
+ children: [
+ Expanded(
+ child: TabBar(
+ controller: controller,
+ padding: EdgeInsets.zero,
+ dividerHeight: 0,
+ splashBorderRadius: BorderRadius.zero,
+ indicatorSize: TabBarIndicatorSize.label,
+ indicatorWeight: 4,
+ labelColor: colors.primary,
+ unselectedLabelColor: colors.onSurfaceVariant,
+ labelStyle: theme.textTheme.titleSmall?.copyWith(
+ fontWeight: FontWeight.w700,
+ ),
+ unselectedLabelStyle: theme.textTheme.titleSmall,
+ labelPadding: const EdgeInsets.symmetric(horizontal: 4),
+ onTap: (index) {
+ if (index == 0) onEpisodesSelected();
+ },
+ tabs: [
+ Tab(text: '选集', height: height),
+ Tab(text: '评论', height: height),
+ ],
+ ),
+ ),
+ if (trailing != null)
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8),
+ child: trailing,
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/lib/pages/video/video_page.dart b/lib/pages/video/video_page.dart
index 49df8ba1..0268d168 100644
--- a/lib/pages/video/video_page.dart
+++ b/lib/pages/video/video_page.dart
@@ -6,7 +6,6 @@ import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:mobx/mobx.dart' as mobx;
import 'package:screen_brightness_platform_interface/screen_brightness_platform_interface.dart';
-import 'package:scrollview_observer/scrollview_observer.dart';
import 'package:window_manager/window_manager.dart';
import 'package:kazumi/bean/appbar/drag_to_move_bar.dart' as dtb;
@@ -23,9 +22,10 @@ import 'package:kazumi/pages/player/player_controller.dart';
import 'package:kazumi/pages/player/player_item.dart';
import 'package:kazumi/pages/video/danmaku_destination_sheet.dart';
import 'package:kazumi/pages/video/danmaku_send_sheet.dart';
+import 'package:kazumi/pages/video/episode_selection_panel.dart';
+import 'package:kazumi/pages/video/player_content_tabs.dart';
import 'package:kazumi/pages/video/video_controller.dart';
import 'package:kazumi/pages/video/video_playback_args.dart';
-import 'package:kazumi/services/logging/logger.dart';
import 'package:kazumi/services/platform/display_mode_service.dart';
import 'package:kazumi/services/player/pip_utils.dart';
import 'package:kazumi/services/player/timed_shutdown_service.dart';
@@ -67,14 +67,12 @@ class _VideoPageState extends State<VideoPage>
final FocusNode keyboardFocus =
FocusNode(debugLabel: 'Video player shortcut scope');
- ScrollController scrollController = ScrollController();
- late GridObserverController observerController;
+ final _episodePanelKey = GlobalKey<EpisodeSelectionPanelState>();
late AnimationController animation;
late Animation<Offset> _rightOffsetAnimation;
late Animation<double> _maskOpacityAnimation;
late TabController tabController;
- int visibleRoad = 0;
bool _tabBodyTargetVisible = true;
int _tabBodyAnimationRun = 0;
@@ -94,7 +92,6 @@ class _VideoPageState extends State<VideoPage>
videoPageController.isDesktopFullscreen();
tabController = TabController(length: 2, vsync: this);
- observerController = GridObserverController(controller: scrollController);
animation = AnimationController(
duration: _sideTabAnimationDuration,
vsync: this,
@@ -155,9 +152,9 @@ class _VideoPageState extends State<VideoPage>
void _initializePlayback() {
if (videoPageController.isOfflineMode) {
- _initOfflineMode(playerController);
+ _initOfflineMode();
} else {
- _initOnlineMode(playerController);
+ _initOnlineMode();
}
_syncChatSubscription =
@@ -182,12 +179,11 @@ class _VideoPageState extends State<VideoPage>
});
}
- void _initOfflineMode(PlayerController playerController) {
+ void _initOfflineMode() {
final identity = videoPageController.currentHistoryIdentity;
videoPageController.historyOffset = identity == null
? 0
: videoPageController.getHistoryOffsetFor(identity);
- visibleRoad = videoPageController.selectedEpisode.road;
_showTabBodyImmediately();
WidgetsBinding.instance.addPostFrameCallback((_) async {
@@ -204,7 +200,7 @@ class _VideoPageState extends State<VideoPage>
});
}
- void _initOnlineMode(PlayerController playerController) {
+ void _initOnlineMode() {
videoPageController.historyOffset = 0;
var progress = historyController.lastWatching(
@@ -224,7 +220,6 @@ class _VideoPageState extends State<VideoPage>
}
}
}
- visibleRoad = videoPageController.selectedEpisode.road;
_showTabBodyImmediately();
_logSubscription = videoPageController.logStream.listen((log) {
@@ -253,9 +248,6 @@ class _VideoPageState extends State<VideoPage>
try {
windowManager.removeListener(this);
} catch (_) {}
- try {
- scrollController.dispose();
- } catch (_) {}
try {
animation.dispose();
} catch (_) {}
@@ -290,12 +282,6 @@ class _VideoPageState extends State<VideoPage>
videoPageController.handleOnExitFullScreen();
}
- void showDebugConsole() {
- setState(() {
- showDebugLog = true;
- });
- }
-
void hideDebugConsole() {
setState(() {
showDebugLog = false;
@@ -327,18 +313,9 @@ class _VideoPageState extends State<VideoPage>
playerController: playerController);
}
- void menuJumpToCurrentEpisode() {
- WidgetsBinding.instance.addPostFrameCallback((_) async {
- // Wait for GridViewObserver to bind its sliver in the post-frame callback.
- await Future<void>.delayed(Duration.zero);
- if (!mounted || !scrollController.hasClients) {
- return;
- }
- final int index = videoPageController.selectedEpisode.episode - 1;
- await observerController.jumpTo(
- index: index < 0 ? 0 : index,
- isFixedHeight: true,
- );
+ void _revealCurrentEpisode() {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _episodePanelKey.currentState?.revealCurrentEpisode();
});
}
@@ -349,7 +326,7 @@ class _VideoPageState extends State<VideoPage>
void _openTabBodyAnimated() {
_setTabBodyVisible(true, animated: true);
- menuJumpToCurrentEpisode();
+ _revealCurrentEpisode();
}
void _closeTabBodyAnimated() {
@@ -367,7 +344,7 @@ class _VideoPageState extends State<VideoPage>
void _showTabBodyImmediately() {
_setTabBodyVisible(true, animated: false);
- menuJumpToCurrentEpisode();
+ _revealCurrentEpisode();
}
void _hideTabBodyImmediately() {
@@ -442,7 +419,7 @@ class _VideoPageState extends State<VideoPage>
return;
}
if (videoPageController.isFullscreen && !isTablet()) {
- menuJumpToCurrentEpisode();
+ _revealCurrentEpisode();
await DisplayModeService.exitFullScreen();
_hideTabBodyImmediately();
videoPageController.isFullscreen = false;
@@ -626,19 +603,14 @@ class _VideoPageState extends State<VideoPage>
: (MediaQuery.sizeOf(context).width / 3 > 420
? 420
: MediaQuery.sizeOf(context).width / 3),
- child: Container(
- color: Theme.of(context).canvasColor,
- child: (isDesktop() || isTablet())
- ? tabBody
- : GridViewObserver(
- controller: observerController,
- child: Column(
- children: [
- menuBar,
- menuBody,
- ],
- ),
- ),
+ child: Material(
+ color: Theme.of(context).colorScheme.surface,
+ borderRadius: const BorderRadiusDirectional.only(
+ topStart: Radius.circular(28),
+ bottomStart: Radius.circular(28),
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: (isDesktop() || isTablet()) ? tabBody : episodePanel,
),
);
}
@@ -824,368 +796,104 @@ class _VideoPageState extends State<VideoPage>
);
}
- Widget get menuBar {
- return Padding(
- padding: const EdgeInsets.all(8),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: [
- const Text(' 合集 '),
- Expanded(
- child: Text(
- videoPageController.title,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: 12,
- color: Theme.of(context).colorScheme.outline,
- ),
- ),
- ),
- const SizedBox(width: 10),
- MenuAnchor(
- consumeOutsideTap: true,
- builder: (_, MenuController controller, __) {
- return SizedBox(
- height: 34,
- child: TextButton(
- style: ButtonStyle(
- padding: WidgetStateProperty.all(EdgeInsets.zero),
- ),
- onPressed: () {
- if (controller.isOpen) {
- controller.close();
- } else {
- controller.open();
- }
- },
- child: Text(
- visibleRoad >= 0 &&
- visibleRoad < videoPageController.roadList.length
- ? '${videoPageController.roadList[visibleRoad].name} '
- : '播放线路${visibleRoad + 1} ',
- style: const TextStyle(fontSize: 13),
- ),
- ),
- );
- },
- menuChildren: List<MenuItemButton>.generate(
- videoPageController.roadList.length,
- (int i) => MenuItemButton(
- onPressed: () {
- setState(() {
- visibleRoad = i;
- });
- },
- child: Container(
- height: 48,
- constraints: BoxConstraints(minWidth: 112),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Text(
- videoPageController.roadList[i].name,
- style: TextStyle(
- color: i == visibleRoad
- ? Theme.of(context).colorScheme.primary
- : null,
- ),
- ),
- ),
- ),
- ),
- ),
- ),
- ],
- ),
- );
- }
-
- DownloadEpisode? _getEpisodeFromRecords(
- int episodeNumber, String episodePageUrl) {
- final bangumiId = videoPageController.bangumiItem.id;
- final pluginName = videoPageController.currentPlugin.name;
-
- for (final record in downloadController.records) {
- if (record.bangumiId == bangumiId && record.pluginName == pluginName) {
- if (episodePageUrl.isNotEmpty) {
- for (final episode in record.episodes.values) {
- if (episode.episodePageUrl == episodePageUrl) {
- return episode;
+ Widget get episodePanel => Observer(builder: (context) {
+ final downloads = <String, DownloadEpisode>{};
+ if (!videoPageController.isOfflineMode) {
+ for (final record in downloadController.records) {
+ if (record.bangumiId != videoPageController.bangumiItem.id ||
+ record.pluginName != videoPageController.currentPlugin.name) {
+ continue;
+ }
+ for (final episode in record.episodes.values) {
+ if (episode.episodePageUrl.isNotEmpty) {
+ downloads[episode.episodePageUrl] = episode;
+ } else if (episode.road >= 0 &&
+ episode.road < videoPageController.roadList.length) {
+ // Older records have no URL; only match within their own road.
+ final urls = videoPageController.roadList[episode.road].data;
+ if (episode.episodeNumber > 0 &&
+ episode.episodeNumber <= urls.length) {
+ downloads[urls[episode.episodeNumber - 1]] = episode;
+ }
+ }
}
}
}
- return record.episodes[episodeNumber];
- }
- }
- return null;
- }
-
- Widget _buildDownloadStatusIcon(int episodeNumber, String episodePageUrl) {
- if (videoPageController.isOfflineMode) return const SizedBox.shrink();
- final episode = _getEpisodeFromRecords(episodeNumber, episodePageUrl);
- if (episode == null) return const SizedBox.shrink();
- switch (episode.status) {
- case DownloadStatus.completed:
- return Icon(Icons.offline_pin,
- size: 16, color: Theme.of(context).colorScheme.primary);
- case DownloadStatus.downloading:
- return SizedBox(
- width: 16,
- height: 16,
- child: CircularProgressIndicator(
- value: episode.progressPercent,
- strokeWidth: 2,
- ),
- );
- case DownloadStatus.failed:
- return Icon(Icons.error_outline,
- size: 16, color: Theme.of(context).colorScheme.error);
- case DownloadStatus.paused:
- return Icon(Icons.pause_circle_outline,
- size: 16, color: Theme.of(context).colorScheme.outline);
- case DownloadStatus.pending:
- case DownloadStatus.resolving:
- return SizedBox(
- width: 16,
- height: 16,
- child: LoadingIndicator(),
- );
- default:
- return const SizedBox.shrink();
- }
- }
-
- Widget get menuBody {
- return Observer(
- builder: (context) {
- var cardList = <Widget>[];
- if (visibleRoad >= 0 &&
- visibleRoad < videoPageController.roadList.length) {
- final road = videoPageController.roadList[visibleRoad];
- int count = 1;
- for (var urlItem in road.data) {
- int count0 = count;
- final episodeName = count0 - 1 < road.identifier.length
- ? road.identifier[count0 - 1]
- : '第$count0集';
- cardList.add(Container(
- margin: const EdgeInsets.only(bottom: 4),
- child: Material(
- color: Theme.of(context).colorScheme.onInverseSurface,
- borderRadius: BorderRadius.circular(6),
- clipBehavior: Clip.hardEdge,
- child: InkWell(
- onTap: () async {
- if (count0 == videoPageController.selectedEpisode.episode &&
- videoPageController.selectedEpisode.road ==
- visibleRoad) {
- return;
- }
- KazumiLogger()
- .i('VideoPageController: video URL is $urlItem');
- _closeTabBodyAnimated();
- changeEpisode(count0, currentRoad: visibleRoad);
- },
- child: Padding(
- padding:
- const EdgeInsets.symmetric(vertical: 8, horizontal: 10),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: <Widget>[
- Row(
- children: [
- if (count0 ==
- (videoPageController
- .selectedEpisode.episode) &&
- visibleRoad ==
- videoPageController
- .selectedEpisode.road) ...<Widget>[
- Image.asset(
- 'assets/images/playing.gif',
- color: Theme.of(context).colorScheme.primary,
- height: 12,
- ),
- const SizedBox(width: 6)
- ],
- Expanded(
- child: Text(
- episodeName,
- maxLines: 2,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: 13,
- color: (count0 ==
- videoPageController
- .selectedEpisode.episode &&
- visibleRoad ==
- videoPageController
- .selectedEpisode.road)
- ? Theme.of(context).colorScheme.primary
- : Theme.of(context)
- .colorScheme
- .onSurface),
- )),
- _buildDownloadStatusIcon(count0, urlItem),
- const SizedBox(width: 2),
- ],
- ),
- const SizedBox(height: 3),
- ],
- ),
- ),
- ),
- ),
- ));
- count++;
- }
- }
- return Expanded(
- child: Padding(
- padding: const EdgeInsets.only(top: 0, right: 8, left: 8),
- child: GridView.builder(
- scrollDirection: Axis.vertical,
- controller: scrollController,
- gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
- crossAxisCount: 3,
- crossAxisSpacing: 10,
- mainAxisSpacing: 5,
- mainAxisExtent: 70,
- ),
- itemCount: cardList.length,
- itemBuilder: (context, index) {
- return cardList[index];
- },
+ return EpisodeSelectionPanel(
+ key: _episodePanelKey,
+ title: videoPageController.title,
+ roads: videoPageController.roadList,
+ selectedRoad: videoPageController.selectedEpisode.road,
+ selectedEpisode: videoPageController.selectedEpisode.episode,
+ downloads: downloads,
+ isOffline: videoPageController.isOfflineMode,
+ isPlaying: playerController.playback.playing &&
+ !playerController.playback.loading &&
+ !videoPageController.loading,
+ disableAnimations: disableAnimations,
+ onEpisodeSelected: (episode, road) {
+ if (episode == videoPageController.selectedEpisode.episode &&
+ road == videoPageController.selectedEpisode.road) {
+ return;
+ }
+ _closeTabBodyAnimated();
+ changeEpisode(episode, currentRoad: road);
+ },
+ onDownload: (road) => showAdaptiveBottomSheet<void>(
+ context: context,
+ builder: (context) => DownloadEpisodeSheet(
+ road: road,
+ videoPageController: videoPageController,
),
),
);
- },
- );
- }
+ });
Widget get tabBody {
+ final colors = Theme.of(context).colorScheme;
final bool danmakuOn = playerController.danmaku.danmakuOn;
final int episodeNum = videoPageController.commentsEpisode;
- return Container(
- color: Theme.of(context).canvasColor,
- child: DefaultTabController(
- length: 2,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Row(
+ return ColoredBox(
+ color: colors.surface,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ PlayerContentTabs(
+ controller: tabController,
+ onEpisodesSelected: _revealCurrentEpisode,
+ trailing: !_windowIsLandscape
+ ? IconButton.filledTonal(
+ tooltip: danmakuOn ? '发送弹幕' : '弹幕已关闭',
+ onPressed: () {
+ if (danmakuOn && !videoPageController.loading) {
+ showMobileDanmakuInput();
+ } else if (videoPageController.loading) {
+ KazumiDialog.showToast(message: '请等待视频加载完成');
+ } else {
+ KazumiDialog.showToast(message: '请先打开弹幕');
+ }
+ },
+ icon: Icon(danmakuOn
+ ? Icons.edit_note_rounded
+ : Icons.comments_disabled_outlined),
+ )
+ : null,
+ ),
+ Expanded(
+ child: TabBarView(
+ controller: tabController,
children: [
- TabBar(
- controller: tabController,
- dividerHeight: 0,
- isScrollable: true,
- tabAlignment: TabAlignment.start,
- labelPadding:
- const EdgeInsetsDirectional.only(start: 30, end: 30),
- onTap: (index) {
- if (index == 0) {
- menuJumpToCurrentEpisode();
- }
- },
- tabs: const [
- Tab(text: '选集'),
- Tab(text: '评论'),
- ],
+ episodePanel,
+ EpisodeCommentsSheet(
+ episode: episodeNum,
+ selection: videoPageController.selectedEpisode,
+ videoPageController: videoPageController,
),
- if (MediaQuery.sizeOf(context).width <=
- MediaQuery.sizeOf(context).height) ...[
- const Spacer(),
- Container(
- padding: EdgeInsets.symmetric(horizontal: 5, vertical: 2),
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(25),
- border: Border.all(
- color: danmakuOn
- ? Theme.of(context).hintColor
- : Theme.of(context).disabledColor,
- width: 0.5,
- ),
- ),
- child: GestureDetector(
- onTap: () {
- if (danmakuOn && !videoPageController.loading) {
- showMobileDanmakuInput();
- } else if (videoPageController.loading) {
- KazumiDialog.showToast(message: '请等待视频加载完成');
- } else {
- KazumiDialog.showToast(message: '请先打开弹幕');
- }
- },
- child: Row(
- children: [
- Text(
- danmakuOn ? ' 点我发弹幕 ' : ' 已关闭弹幕 ',
- softWrap: false,
- overflow: TextOverflow.clip,
- style: TextStyle(
- color: danmakuOn
- ? Theme.of(context).hintColor
- : Theme.of(context).disabledColor,
- ),
- ),
- if (danmakuOn)
- Icon(
- Icons.send_rounded,
- size: 20,
- color: Theme.of(context).hintColor,
- ),
- ],
- ),
- ),
- ),
- ],
- const SizedBox(width: 8),
],
),
- Divider(height: isDesktop() ? 0.5 : 0.2),
- Expanded(
- child: TabBarView(
- controller: tabController,
- children: [
- Stack(
- children: [
- GridViewObserver(
- controller: observerController,
- child: Column(
- children: [
- menuBar,
- menuBody,
- ],
- ),
- ),
- if (!videoPageController.isOfflineMode)
- Positioned(
- right: 16,
- bottom: 16,
- child: FloatingActionButton(
- child: const Icon(Icons.download_rounded),
- onPressed: () {
- showAdaptiveBottomSheet<void>(
- context: context,
- builder: (context) => DownloadEpisodeSheet(
- road: visibleRoad,
- videoPageController: videoPageController,
- ),
- );
- },
- ),
- ),
- ],
- ),
- EpisodeCommentsSheet(
- episode: episodeNum,
- selection: videoPageController.selectedEpisode,
- videoPageController: videoPageController,
- ),
- ],
- ),
- ),
- ],
- ),
+ ),
+ ],
),
);
}