基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。
feat(player): add hover and drag time preview to the progress bar (#2722)
Ru00ydfcf9629a524
diff --git a/lib/pages/player/player_item.dart b/lib/pages/player/player_item.dartindex 4ffa5579..8a9b202f 100644--- a/lib/pages/player/player_item.dart+++ b/lib/pages/player/player_item.dart@@ -684,12 +684,8 @@ class _PlayerItemState extends State<PlayerItem>_progressBarDragHold = acquirePlayerPanelHold();}- Future<void> handleProgressBarSeek(Duration duration) async {- if (!playerController.seeking.updateInteractiveSeek(duration)) {- await playerController.seek(duration);- return;- }- await _finishInteractiveSeek();+ void handleProgressBarDragEnd(bool cancelled) {+ unawaited(_finishInteractiveSeek(cancelled: cancelled));}void _beginInteractiveSeek() {@@ -1538,7 +1534,7 @@ class _PlayerItemState extends State<PlayerItem>enterAndroidPictureInPicture,handleProgressBarDragStart:handleProgressBarDragStart,- handleProgressBarSeek: handleProgressBarSeek,+ handleProgressBarDragEnd: handleProgressBarDragEnd,handleSuperResolutionChange:handleSuperResolutionChange,onNextEpisode: () => handlePreNextEpisode('next'),diff --git a/lib/pages/player/player_item_panel.dart b/lib/pages/player/player_item_panel.dartindex 6a5b336c..be7a0fd3 100644--- a/lib/pages/player/player_item_panel.dart+++ b/lib/pages/player/player_item_panel.dart@@ -24,11 +24,11 @@ import 'package:kazumi/bean/appbar/drag_to_move_bar.dart' as dtb;import 'package:kazumi/pages/settings/danmaku/danmaku_settings_sheet.dart';import 'package:kazumi/utils/constants.dart';import 'package:kazumi/utils/device.dart';-import 'package:audio_video_progress_bar/audio_video_progress_bar.dart';import 'package:kazumi/services/player/timed_shutdown_service.dart';import 'package:kazumi/utils/format.dart';import 'package:kazumi/pages/player/player_transport_bar.dart';import 'package:kazumi/pages/player/player_screenshot_controls.dart';+import 'package:kazumi/pages/player/player_progress_bar.dart';class PlayerItemPanel extends StatefulWidget {const PlayerItemPanel({@@ -45,7 +45,7 @@ class PlayerItemPanel extends StatefulWidget {required this.showScreenshotCandidates,required this.onNextEpisode,required this.handleProgressBarDragStart,- required this.handleProgressBarSeek,+ required this.handleProgressBarDragEnd,required this.handleSuperResolutionChange,required this.panelVisibilityController,this.onToggleSidePanel,@@ -72,7 +72,7 @@ class PlayerItemPanel extends StatefulWidget {final VoidCallback handleScreenShot;final VoidCallback showScreenshotCandidates;final VoidCallback handleProgressBarDragStart;- final Future<void> Function(Duration duration) handleProgressBarSeek;+ final void Function(bool cancelled) handleProgressBarDragEnd;final Future<void> Function(SuperResolutionMode mode)handleSuperResolutionChange;final AnimationController panelVisibilityController;@@ -758,23 +758,17 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {onPressed: widget.onNextEpisode,),// Playback ticks only rebuild the progress bar and its time labels.- progressBuilder: (location) => Observer(- builder: (context) => ProgressBar(- thumbRadius: 8,- thumbGlowRadius: 18,- timeLabelLocation: location,- timeLabelTextStyle: const TextStyle(- color: Colors.white,- fontSize: 12,- fontFeatures: [FontFeature.tabularFigures()],- ),+ progressBuilder: ({required sideLabels}) => Observer(+ builder: (context) => PlayerProgressBar(+ sideLabels: sideLabels,progress: playerController.playback.currentPosition,buffered: playerController.playback.buffer,total: playerController.playback.duration,- onSeek: widget.handleProgressBarSeek,- onDragStart: (_) => widget.handleProgressBarDragStart(),- onDragUpdate: (details) => playerController.seeking- .updateInteractiveSeek(details.timeStamp),+ onDragStart: widget.handleProgressBarDragStart,+ onDragUpdate: (position) => playerController.seeking+ .updateInteractiveSeek(position),+ onDragEnd: widget.handleProgressBarDragEnd,+ onSeek: playerController.seek,)),timeLabel: Observer(builder: (context) => Text(diff --git a/lib/pages/player/player_progress_bar.dart b/lib/pages/player/player_progress_bar.dartnew file mode 100644index 00000000..02d242dc--- /dev/null+++ b/lib/pages/player/player_progress_bar.dart@@ -0,0 +1,370 @@+import 'dart:async';+import 'dart:math' as math;++import 'package:flutter/gestures.dart';+import 'package:flutter/material.dart';+import 'package:kazumi/utils/format.dart';++// Metrics follow the defaults of the former audio_video_progress_bar.+const double _thumbRadius = 8;+const double _thumbGlowRadius = 18;+const double _barHeight = 5;+const double _labelGap = _thumbRadius + 5;+const double _semanticStep = 0.05;+const _labelStyle = TextStyle(+ color: Colors.white,+ fontSize: 12,+ fontFeatures: [FontFeature.tabularFigures()],+);++/// Every [onDragStart] is followed by exactly one [onDragEnd], also when the+/// bar is removed mid-drag.+class PlayerProgressBar extends StatefulWidget {+ const PlayerProgressBar({+ super.key,+ required this.progress,+ required this.buffered,+ required this.total,+ required this.sideLabels,+ required this.onDragStart,+ required this.onDragUpdate,+ required this.onDragEnd,+ required this.onSeek,+ });++ final Duration progress;+ final Duration buffered;+ final Duration total;+ final bool sideLabels;+ final VoidCallback onDragStart;+ final ValueChanged<Duration> onDragUpdate;+ final void Function(bool cancelled) onDragEnd;++ /// Seeks from accessibility actions, outside of any drag.+ final ValueChanged<Duration> onSeek;++ @override+ State<PlayerProgressBar> createState() => _PlayerProgressBarState();+}++class _PlayerProgressBarState extends State<PlayerProgressBar> {+ final _preview = OverlayPortalController();+ double? _dragFraction;+ bool _mouseDrag = false;+ double? _hoverFraction;++ bool get _seekable => widget.total > Duration.zero;++ double? get _previewFraction {+ if (_dragFraction == null) return _hoverFraction;+ return _mouseDrag ? _dragFraction : null;+ }++ double _fractionOf(Duration value) => _seekable+ ? (value.inMilliseconds / widget.total.inMilliseconds).clamp(0.0, 1.0)+ : 0;++ Duration _timeAt(double fraction) => Duration(+ milliseconds:+ (widget.total.inMilliseconds * fraction.clamp(0.0, 1.0)).round());++ @override+ void dispose() {+ // The recognizer goes away without reporting an end, and disposal runs+ // inside a frame, so the drag is closed right after it.+ if (_dragFraction != null) {+ final onDragEnd = widget.onDragEnd;+ scheduleMicrotask(() => onDragEnd(true));+ }+ super.dispose();+ }++ void _syncPreview() {+ final visible = _previewFraction != null;+ if (visible == _preview.isShowing) return;+ if (visible) {+ _preview.show();+ } else {+ _preview.hide();+ }+ }++ void _handleHover(PointerEvent event, _Track track) {+ if (event.kind != PointerDeviceKind.mouse || _dragFraction != null) return;+ final dx = event.localPosition.dx;+ _setHover(_seekable && track.covers(dx) ? track.fractionAt(dx) : null);+ }++ void _setHover(double? fraction) {+ if (fraction == _hoverFraction) return;+ setState(() => _hoverFraction = fraction);+ _syncPreview();+ }++ void _handleDragStart(DragStartDetails details, _Track track) {+ if (!_seekable || track.isEmpty) return;+ final fraction = track.fractionAt(details.localPosition.dx);+ setState(() {+ _dragFraction = fraction;+ _mouseDrag = details.kind == PointerDeviceKind.mouse;+ _hoverFraction = null;+ });+ _syncPreview();+ widget.onDragStart();+ widget.onDragUpdate(_timeAt(fraction));+ }++ void _handleDragUpdate(DragUpdateDetails details, _Track track) {+ if (_dragFraction == null) return;+ final fraction = track.fractionAt(details.localPosition.dx);+ setState(() => _dragFraction = fraction);+ widget.onDragUpdate(_timeAt(fraction));+ }++ void _handleDragEnd({required bool cancelled}) {+ if (_dragFraction == null) return;+ setState(() => _dragFraction = null);+ _syncPreview();+ widget.onDragEnd(cancelled || !_seekable);+ }++ static String _percent(double fraction) =>+ '${(fraction.clamp(0.0, 1.0) * 100).round()}%';++ @override+ Widget build(BuildContext context) {+ final textScaler = MediaQuery.textScalerOf(context);+ final color = Theme.of(context).colorScheme.primary;+ // Both labels take the width of the total time, the longest one, so the+ // track stays put while the position label changes.+ final labelSize = widget.sideLabels+ ? _measureLabel(durationToString(widget.total), textScaler)+ : null;+ final inset = labelSize == null ? 0.0 : labelSize.width + _labelGap;+ final height = math.max(2 * _thumbRadius, labelSize?.height ?? 0);+ final dragFraction = _dragFraction;+ final current = dragFraction ?? _fractionOf(widget.progress);+ final position =+ dragFraction == null ? widget.progress : _timeAt(dragFraction);+ return LayoutBuilder(builder: (context, constraints) {+ final track = _Track(width: constraints.maxWidth, inset: inset);+ return OverlayPortal.overlayChildLayoutBuilder(+ controller: _preview,+ overlayChildBuilder: (context, info) =>+ _buildPreview(context, info, track),+ child: Semantics(+ slider: true,+ label: '播放进度',+ value: _percent(current),+ increasedValue: _percent(current + _semanticStep),+ decreasedValue: _percent(current - _semanticStep),+ onIncrease: _seekable+ ? () => widget.onSeek(_timeAt(current + _semanticStep))+ : null,+ onDecrease: _seekable+ ? () => widget.onSeek(_timeAt(current - _semanticStep))+ : null,+ child: MouseRegion(+ onEnter: (event) => _handleHover(event, track),+ onHover: (event) => _handleHover(event, track),+ onExit: (_) => _setHover(null),+ child: RawGestureDetector(+ behavior: HitTestBehavior.opaque,+ gestures: {+ _ProgressDragRecognizer: GestureRecognizerFactoryWithHandlers<+ _ProgressDragRecognizer>(_ProgressDragRecognizer.new,+ (recognizer) {+ recognizer.onStart =+ (details) => _handleDragStart(details, track);+ recognizer.onUpdate =+ (details) => _handleDragUpdate(details, track);+ recognizer.onEnd =+ (_) => _handleDragEnd(cancelled: recognizer.cancelled);+ }),+ },+ child: SizedBox(+ width: track.width,+ height: height,+ child: RepaintBoundary(+ child: CustomPaint(+ painter: _ProgressPainter(+ inset: inset,+ current: current,+ buffered: _fractionOf(widget.buffered),+ dragging: dragFraction != null,+ color: color,+ textScaler: textScaler,+ labels: labelSize == null+ ? null+ : (+ position: durationToString(position),+ total: durationToString(widget.total),+ ),+ ),+ ),+ ),+ ),+ ),+ ),+ ),+ );+ });+ }++ Widget _buildPreview(+ BuildContext context, OverlayChildLayoutInfo info, _Track track) {+ final fraction = _previewFraction;+ if (fraction == null || !_seekable || track.isEmpty) {+ return const SizedBox.shrink();+ }+ final text = durationToString(_timeAt(fraction));+ final textSize = _measureLabel(text, MediaQuery.textScalerOf(context));+ final width = textSize.width + 20;+ final height = textSize.height + 12;+ Offset toOverlay(double x) =>+ MatrixUtils.transformPoint(info.childPaintTransform, Offset(x, 0));+ final anchor = toOverlay(track.xAt(fraction));+ final minLeft = toOverlay(0).dx;+ final maxLeft = math.max(minLeft, toOverlay(track.width).dx - width);+ return Positioned(+ left: (anchor.dx - width / 2).clamp(minLeft, maxLeft),+ top: math.max(4.0, anchor.dy - height - 8),+ child: IgnorePointer(+ child: ExcludeSemantics(+ child: Container(+ width: width,+ height: height,+ alignment: Alignment.center,+ decoration: BoxDecoration(+ color: Colors.black.withValues(alpha: 0.85),+ borderRadius: BorderRadius.circular(8),+ ),+ child: Text(text, style: _labelStyle),+ ),+ ),+ ),+ );+ }+}++TextPainter _layoutLabel(String text, TextScaler textScaler) => TextPainter(+ text: TextSpan(text: text, style: _labelStyle),+ textDirection: TextDirection.ltr,+ textScaler: textScaler,+ )..layout();++Size _measureLabel(String text, TextScaler textScaler) {+ final painter = _layoutLabel(text, textScaler);+ final size = painter.size;+ painter.dispose();+ return size;+}++class _Track {+ const _Track({required this.width, required this.inset});++ final double width;+ final double inset;++ // A round cap reaches half the bar height past each end of the line.+ double get start => inset + _barHeight / 2;+ double get end => width - inset - _barHeight / 2;+ bool get isEmpty => end <= start;++ double xAt(double fraction) => start + (end - start) * fraction;++ double fractionAt(double dx) =>+ isEmpty ? 0 : ((dx - start) / (end - start)).clamp(0.0, 1.0);++ bool covers(double dx) => !isEmpty && dx >= inset && dx <= width - inset;+}++// Accepts on contact so a press seeks at once. A cancelled pointer still ends+// in onEnd, so the flag tells the two apart.+class _ProgressDragRecognizer extends HorizontalDragGestureRecognizer {+ bool cancelled = false;++ @override+ void addAllowedPointer(PointerDownEvent event) {+ cancelled = false;+ super.addAllowedPointer(event);+ resolve(GestureDisposition.accepted);+ }++ @override+ void handleEvent(PointerEvent event) {+ if (event is PointerCancelEvent) cancelled = true;+ super.handleEvent(event);+ }++ @override+ String get debugDescription => 'progress drag';+}++class _ProgressPainter extends CustomPainter {+ const _ProgressPainter({+ required this.inset,+ required this.current,+ required this.buffered,+ required this.dragging,+ required this.color,+ required this.textScaler,+ required this.labels,+ });++ final double inset;+ final double current;+ final double buffered;+ final bool dragging;+ final Color color;+ final TextScaler textScaler;+ final ({String position, String total})? labels;++ @override+ void paint(Canvas canvas, Size size) {+ final track = _Track(width: size.width, inset: inset);+ final centerY = size.height / 2;+ if (!track.isEmpty) {+ final bar = Paint()+ ..strokeCap = StrokeCap.round+ ..strokeWidth = _barHeight;+ void drawBar(double fraction, Color barColor) => canvas.drawLine(+ Offset(track.start, centerY),+ Offset(track.xAt(fraction), centerY),+ bar..color = barColor);+ final faded = color.withValues(alpha: 0.24);+ drawBar(1, faded);+ drawBar(buffered, faded);+ drawBar(current, color);+ final thumb = Offset(track.xAt(current), centerY);+ if (dragging) {+ canvas.drawCircle(thumb, _thumbGlowRadius,+ Paint()..color = color.withValues(alpha: 80 / 255));+ }+ canvas.drawCircle(thumb, _thumbRadius, Paint()..color = color);+ }+ final labels = this.labels;+ if (labels != null) {+ _paintLabel(canvas, labels.position, 0, centerY);+ _paintLabel(canvas, labels.total, size.width, centerY, alignEnd: true);+ }+ }++ void _paintLabel(Canvas canvas, String text, double x, double centerY,+ {bool alignEnd = false}) {+ final painter = _layoutLabel(text, textScaler);+ painter.paint(canvas,+ Offset(alignEnd ? x - painter.width : x, centerY - painter.height / 2));+ painter.dispose();+ }++ @override+ bool shouldRepaint(_ProgressPainter oldDelegate) =>+ oldDelegate.inset != inset ||+ oldDelegate.current != current ||+ oldDelegate.buffered != buffered ||+ oldDelegate.dragging != dragging ||+ oldDelegate.color != color ||+ oldDelegate.textScaler != textScaler ||+ oldDelegate.labels != labels;+}diff --git a/lib/pages/player/player_transport_bar.dart b/lib/pages/player/player_transport_bar.dartindex 20d214f7..210ac16f 100644--- a/lib/pages/player/player_transport_bar.dart+++ b/lib/pages/player/player_transport_bar.dart@@ -1,4 +1,3 @@-import 'package:audio_video_progress_bar/audio_video_progress_bar.dart';import 'package:flutter/material.dart';enum PlayerTimeLabelPlacement {@@ -31,7 +30,7 @@ class PlayerTransportBar extends StatelessWidget {final bool compact;final Widget playPause;final Widget nextEpisode;- final Widget Function(TimeLabelLocation location) progressBuilder;+ final Widget Function({required bool sideLabels}) progressBuilder;final Widget timeLabel;final PlayerTimeLabelPlacement timePlacement;final Widget controls;@@ -41,7 +40,7 @@ class PlayerTransportBar extends StatelessWidget {Widget build(BuildContext context) => compact? Row(children: [playPause,- Expanded(child: progressBuilder(TimeLabelLocation.none)),+ Expanded(child: progressBuilder(sideLabels: false)),timeLabel,fullscreen,])@@ -57,9 +56,8 @@ class PlayerTransportBar extends StatelessWidget {Padding(padding: const EdgeInsets.symmetric(horizontal: 10),child: progressBuilder(- timePlacement == PlayerTimeLabelPlacement.besideProgress- ? TimeLabelLocation.sides- : TimeLabelLocation.none,+ sideLabels:+ timePlacement == PlayerTimeLabelPlacement.besideProgress,),),Padding(diff --git a/pubspec.lock b/pubspec.lockindex 534f64f3..1e244a0f 100644--- a/pubspec.lock+++ b/pubspec.lock@@ -107,14 +107,6 @@ packages:url: "https://pub.dev"source: hostedversion: "0.2.3"- audio_video_progress_bar:- dependency: "direct main"- description:- name: audio_video_progress_bar- sha256: "552b1f73c56c4c88407999e0a8507176f60c56de3e6d63bc20a0eab48467d4c9"- url: "https://pub.dev"- source: hosted- version: "2.0.3"auto_injector:dependency: transitivedescription:diff --git a/pubspec.yaml b/pubspec.yamlindex f29687e7..383e7a4d 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -32,7 +32,6 @@ dependencies:file_picker: ^10.3.7flutter_volume_controller: ^2.0.1- audio_video_progress_bar: ^2.0.2audio_service: ^0.18.15audio_service_mpris:git: