Skip to content

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

feat(player): add screenshot selection and cross platform export

Prediditb41f98d6bc9c
diff --git a/lib/pages/player/controller/player_playback_controller.dart b/lib/pages/player/controller/player_playback_controller.dart
index d6ba9cc4..004e6cf2 100644
--- a/lib/pages/player/controller/player_playback_controller.dart
+++ b/lib/pages/player/controller/player_playback_controller.dart
@@ -14,7 +14,6 @@ import 'package:kazumi/services/network/proxy_utils.dart';
import 'package:kazumi/services/network/system_proxy_service.dart';
import 'package:kazumi/services/player/playback_cache_policy.dart';
import 'package:kazumi/services/player/player_error_mapper.dart';
-import 'package:kazumi/services/player/player_screenshot_service.dart';
import 'package:kazumi/services/storage/storage.dart';
import 'package:kazumi/services/video_source/video_source_format.dart';
import 'package:kazumi/utils/async_serial_queue.dart';
@@ -68,8 +67,6 @@ abstract class _PlayerPlaybackController with Store {
final PlayerDebugController debug;
final String Function() videoUrl;
final bool Function() isLocalPlayback;
- final PlayerScreenshotService screenshotService =
- const PlayerScreenshotService();
late final PlaybackCachePolicy cachePolicy = PlaybackCachePolicy(
isLocalPlayback: isLocalPlayback,
currentPlayer: () => mediaPlayer,
@@ -632,15 +629,12 @@ abstract class _PlayerPlaybackController with Store {
]);
}
- Future<Uint8List?> screenshot({String format = 'image/jpeg'}) async {
- return await mediaPlayer!.screenshot(format: format);
- }
-
Future<Uint8List?> screenshotPng() async {
final player = mediaPlayer;
if (player == null) {
return null;
}
- return await screenshotService.capturePng(player);
+ // Encode the captured frame natively; PlayerState dimensions may be stale.
+ return player.safeScreenshot(format: 'image/png');
}
}
diff --git a/lib/pages/player/controller/player_screenshot_controller.dart b/lib/pages/player/controller/player_screenshot_controller.dart
new file mode 100644
index 00000000..97952cf1
--- /dev/null
+++ b/lib/pages/player/controller/player_screenshot_controller.dart
@@ -0,0 +1,177 @@
+// ignore_for_file: library_private_types_in_public_api
+
+import 'dart:collection';
+import 'dart:typed_data';
+
+import 'package:kazumi/services/player/screenshot_candidate.dart';
+import 'package:mobx/mobx.dart';
+
+part 'player_screenshot_controller.g.dart';
+
+class PlayerScreenshotController = _PlayerScreenshotController
+ with _$PlayerScreenshotController;
+
+/// Candidates are append-only and live until the playback page is disposed.
+abstract class _PlayerScreenshotController with Store {
+ static const _maxCandidates = 24;
+ static const _maxBytes = 96 << 20;
+ final _candidates = ObservableList<ScreenshotCandidate>();
+ final _selected = ObservableSet<String>();
+ final _saved = ObservableSet<String>();
+ late final List<ScreenshotCandidate> candidates = UnmodifiableListView(
+ _candidates,
+ );
+ bool _disposed = false;
+ int _sequence = 0;
+ int _byteCount = 0;
+
+ @readonly
+ bool _capturing = false;
+
+ @readonly
+ bool _saving = false;
+
+ @readonly
+ int _saveCompleted = 0;
+
+ @readonly
+ int _saveTotal = 0;
+
+ @readonly
+ String? _message;
+
+ @readonly
+ bool _hasError = false;
+
+ @computed
+ bool get busy => _capturing || _saving;
+
+ @computed
+ int get selectedCount => _selected.length;
+
+ bool isSelected(ScreenshotCandidate item) => _selected.contains(item.id);
+ bool isSaved(ScreenshotCandidate item) => _saved.contains(item.id);
+
+ void _report(String message, {bool error = false}) {
+ if (_disposed) return;
+ _message = message;
+ _hasError = error;
+ }
+
+ @action
+ Future<bool> capture({
+ required Future<Uint8List?> Function() capturePng,
+ required String title,
+ required String episode,
+ required Duration position,
+ required bool Function() isCurrent,
+ }) async {
+ if (_disposed || busy) return false;
+ if (_candidates.length >= _maxCandidates || _byteCount >= _maxBytes) {
+ _report('本次播放的截图候选已满,请挑选需要保存的截图', error: true);
+ return false;
+ }
+ _capturing = true;
+ _message = null;
+ _hasError = false;
+ final capturedAt = DateTime.now();
+ try {
+ final bytes = await capturePng();
+ if (_disposed) return false;
+ if (!isCurrent()) {
+ _report('视频已切换,请重新截图', error: true);
+ return false;
+ }
+ if (bytes == null || bytes.isEmpty) {
+ _report('暂未获取到画面,请等视频显示后重试', error: true);
+ return false;
+ }
+ if (_byteCount + bytes.lengthInBytes > _maxBytes) {
+ _report('截图候选已达到内存上限,请挑选需要保存的截图', error: true);
+ return false;
+ }
+ final item = ScreenshotCandidate(
+ id: '${capturedAt.microsecondsSinceEpoch}_${_sequence++}',
+ bytes: bytes,
+ title: title,
+ episode: episode,
+ position: position,
+ );
+ _candidates.add(item);
+ _byteCount += bytes.lengthInBytes;
+ return true;
+ } catch (_) {
+ _report('截图失败,请稍后重试', error: true);
+ return false;
+ } finally {
+ if (!_disposed) _capturing = false;
+ }
+ }
+
+ @action
+ void toggle(ScreenshotCandidate item) {
+ if (_disposed || _saving || isSaved(item) || !_candidates.contains(item)) {
+ return;
+ }
+ if (!_selected.remove(item.id)) _selected.add(item.id);
+ }
+
+ @action
+ Future<void> save({
+ required Future<String?> Function() chooseDestination,
+ required Future<void> Function(ScreenshotCandidate, String) write,
+ required String destinationLabel,
+ }) async {
+ if (_disposed || busy || selectedCount == 0) return;
+ final batch = _candidates.where(isSelected).toList();
+ _saving = true;
+ _saveCompleted = 0;
+ _saveTotal = batch.length;
+ _message = null;
+ _hasError = false;
+ var successes = 0;
+ var failures = 0;
+ try {
+ final destination = await chooseDestination();
+ if (_disposed) return;
+ if (destination == null) {
+ _report('已取消保存,候选截图仍保留');
+ return;
+ }
+ for (final item in batch) {
+ try {
+ await write(item, destination);
+ if (_disposed) return;
+ // Commit each success so retries only write failed items.
+ _saved.add(item.id);
+ _selected.remove(item.id);
+ successes++;
+ } catch (_) {
+ if (_disposed) return;
+ failures++;
+ }
+ _saveCompleted++;
+ }
+ if (failures > 0) {
+ _report('已保存 $successes 张,$failures 张失败;未保存的截图仍已选中,请重试', error: true);
+ } else {
+ _report('已保存 $successes 张到$destinationLabel');
+ }
+ } catch (_) {
+ _report('无法打开保存位置,请检查权限后重试', error: true);
+ } finally {
+ if (!_disposed) _saving = false;
+ }
+ }
+
+ @action
+ void dispose() {
+ if (_disposed) return;
+ _disposed = true;
+ _capturing = false;
+ _saving = false;
+ _candidates.clear();
+ _selected.clear();
+ _saved.clear();
+ }
+}
diff --git a/lib/pages/player/controller/player_screenshot_controller.g.dart b/lib/pages/player/controller/player_screenshot_controller.g.dart
new file mode 100644
index 00000000..42952641
--- /dev/null
+++ b/lib/pages/player/controller/player_screenshot_controller.g.dart
@@ -0,0 +1,225 @@
+// GENERATED CODE - DO NOT MODIFY BY HAND
+
+part of 'player_screenshot_controller.dart';
+
+// **************************************************************************
+// StoreGenerator
+// **************************************************************************
+
+// ignore_for_file: non_constant_identifier_names, unnecessary_brace_in_string_interps, unnecessary_lambdas, prefer_expression_function_bodies, lines_longer_than_80_chars, avoid_as, avoid_annotating_with_dynamic, no_leading_underscores_for_local_identifiers
+
+mixin _$PlayerScreenshotController on _PlayerScreenshotController, Store {
+ Computed<bool>? _$busyComputed;
+
+ @override
+ bool get busy => (_$busyComputed ??= Computed<bool>(
+ () => super.busy,
+ name: '_PlayerScreenshotController.busy',
+ )).value;
+ Computed<int>? _$selectedCountComputed;
+
+ @override
+ int get selectedCount => (_$selectedCountComputed ??= Computed<int>(
+ () => super.selectedCount,
+ name: '_PlayerScreenshotController.selectedCount',
+ )).value;
+
+ late final _$_capturingAtom = Atom(
+ name: '_PlayerScreenshotController._capturing',
+ context: context,
+ );
+
+ bool get capturing {
+ _$_capturingAtom.reportRead();
+ return super._capturing;
+ }
+
+ @override
+ bool get _capturing => capturing;
+
+ @override
+ set _capturing(bool value) {
+ _$_capturingAtom.reportWrite(value, super._capturing, () {
+ super._capturing = value;
+ });
+ }
+
+ late final _$_savingAtom = Atom(
+ name: '_PlayerScreenshotController._saving',
+ context: context,
+ );
+
+ bool get saving {
+ _$_savingAtom.reportRead();
+ return super._saving;
+ }
+
+ @override
+ bool get _saving => saving;
+
+ @override
+ set _saving(bool value) {
+ _$_savingAtom.reportWrite(value, super._saving, () {
+ super._saving = value;
+ });
+ }
+
+ late final _$_saveCompletedAtom = Atom(
+ name: '_PlayerScreenshotController._saveCompleted',
+ context: context,
+ );
+
+ int get saveCompleted {
+ _$_saveCompletedAtom.reportRead();
+ return super._saveCompleted;
+ }
+
+ @override
+ int get _saveCompleted => saveCompleted;
+
+ @override
+ set _saveCompleted(int value) {
+ _$_saveCompletedAtom.reportWrite(value, super._saveCompleted, () {
+ super._saveCompleted = value;
+ });
+ }
+
+ late final _$_saveTotalAtom = Atom(
+ name: '_PlayerScreenshotController._saveTotal',
+ context: context,
+ );
+
+ int get saveTotal {
+ _$_saveTotalAtom.reportRead();
+ return super._saveTotal;
+ }
+
+ @override
+ int get _saveTotal => saveTotal;
+
+ @override
+ set _saveTotal(int value) {
+ _$_saveTotalAtom.reportWrite(value, super._saveTotal, () {
+ super._saveTotal = value;
+ });
+ }
+
+ late final _$_messageAtom = Atom(
+ name: '_PlayerScreenshotController._message',
+ context: context,
+ );
+
+ String? get message {
+ _$_messageAtom.reportRead();
+ return super._message;
+ }
+
+ @override
+ String? get _message => message;
+
+ @override
+ set _message(String? value) {
+ _$_messageAtom.reportWrite(value, super._message, () {
+ super._message = value;
+ });
+ }
+
+ late final _$_hasErrorAtom = Atom(
+ name: '_PlayerScreenshotController._hasError',
+ context: context,
+ );
+
+ bool get hasError {
+ _$_hasErrorAtom.reportRead();
+ return super._hasError;
+ }
+
+ @override
+ bool get _hasError => hasError;
+
+ @override
+ set _hasError(bool value) {
+ _$_hasErrorAtom.reportWrite(value, super._hasError, () {
+ super._hasError = value;
+ });
+ }
+
+ late final _$captureAsyncAction = AsyncAction(
+ '_PlayerScreenshotController.capture',
+ context: context,
+ );
+
+ @override
+ Future<bool> capture({
+ required Future<Uint8List?> Function() capturePng,
+ required String title,
+ required String episode,
+ required Duration position,
+ required bool Function() isCurrent,
+ }) {
+ return _$captureAsyncAction.run(
+ () => super.capture(
+ capturePng: capturePng,
+ title: title,
+ episode: episode,
+ position: position,
+ isCurrent: isCurrent,
+ ),
+ );
+ }
+
+ late final _$saveAsyncAction = AsyncAction(
+ '_PlayerScreenshotController.save',
+ context: context,
+ );
+
+ @override
+ Future<void> save({
+ required Future<String?> Function() chooseDestination,
+ required Future<void> Function(ScreenshotCandidate, String) write,
+ required String destinationLabel,
+ }) {
+ return _$saveAsyncAction.run(
+ () => super.save(
+ chooseDestination: chooseDestination,
+ write: write,
+ destinationLabel: destinationLabel,
+ ),
+ );
+ }
+
+ late final _$_PlayerScreenshotControllerActionController = ActionController(
+ name: '_PlayerScreenshotController',
+ context: context,
+ );
+
+ @override
+ void toggle(ScreenshotCandidate item) {
+ final _$actionInfo = _$_PlayerScreenshotControllerActionController
+ .startAction(name: '_PlayerScreenshotController.toggle');
+ try {
+ return super.toggle(item);
+ } finally {
+ _$_PlayerScreenshotControllerActionController.endAction(_$actionInfo);
+ }
+ }
+
+ @override
+ void dispose() {
+ final _$actionInfo = _$_PlayerScreenshotControllerActionController
+ .startAction(name: '_PlayerScreenshotController.dispose');
+ try {
+ return super.dispose();
+ } finally {
+ _$_PlayerScreenshotControllerActionController.endAction(_$actionInfo);
+ }
+ }
+
+ @override
+ String toString() {
+ return '''
+busy: ${busy},
+selectedCount: ${selectedCount}
+ ''';
+ }
+}
diff --git a/lib/pages/player/player_controller.dart b/lib/pages/player/player_controller.dart
index 232902d9..26c6b204 100644
--- a/lib/pages/player/player_controller.dart
+++ b/lib/pages/player/player_controller.dart
@@ -14,6 +14,7 @@ import 'package:kazumi/pages/player/controller/player_panel_controller.dart';
import 'package:kazumi/pages/player/controller/player_playback_controller.dart';
import 'package:kazumi/pages/player/controller/player_super_resolution.dart';
import 'package:kazumi/pages/player/controller/player_syncplay_controller.dart';
+import 'package:kazumi/pages/player/controller/player_screenshot_controller.dart';
import 'package:kazumi/services/storage/storage.dart';
import 'package:kazumi/services/logging/logger.dart';
import 'package:kazumi/services/shaders/shader_asset_service.dart';
@@ -41,6 +42,7 @@ class PlayerController implements Disposable {
final AsyncSessionOwner _initializations = AsyncSessionOwner();
Future<void>? _shutdownFuture;
final PlayerPanelController panel = PlayerPanelController();
+ final PlayerScreenshotController screenshots = PlayerScreenshotController();
final PlayerDebugController debug = PlayerDebugController();
late final PlayerDanmakuController danmaku;
@@ -385,6 +387,7 @@ class PlayerController implements Disposable {
if (_shutdownFuture != null) {
return;
}
+ screenshots.dispose();
final shutdown = _shutdownResources();
_shutdownFuture = shutdown;
unawaited(
@@ -433,13 +436,7 @@ class PlayerController implements Disposable {
await _releasePlaybackResources();
}
- Future<Uint8List?> screenshot({String format = 'image/jpeg'}) async {
- return await playback.screenshot(format: format);
- }
-
- Future<Uint8List?> screenshotPng() async {
- return await playback.screenshotPng();
- }
+ Future<Uint8List?> screenshotPng() => playback.screenshotPng();
void setButtonForwardTime(int time) {
playback.buttonSkipTime = time;
diff --git a/lib/pages/player/player_item.dart b/lib/pages/player/player_item.dart
index 131964cc..5cb8788f 100644
--- a/lib/pages/player/player_item.dart
+++ b/lib/pages/player/player_item.dart
@@ -7,12 +7,13 @@ import 'package:kazumi/pages/player/player_panel_hold.dart';
import 'package:kazumi/pages/player/player_pointer_interaction.dart';
import 'package:kazumi/pages/player/player_gesture_detector.dart';
import 'package:kazumi/pages/player/player_screenshot_feedback_overlay.dart';
+import 'package:kazumi/pages/player/player_screenshot_sheet.dart';
+import 'package:kazumi/pages/player/controller/player_screenshot_controller.dart';
import 'package:kazumi/pages/player/syncplay_sheet.dart';
import 'package:kazumi/utils/constants.dart';
import 'package:kazumi/services/logging/logger.dart';
import 'package:kazumi/services/player/pip_utils.dart';
import 'package:kazumi/services/sync/webdav.dart';
-import 'package:flutter/services.dart';
import 'package:flutter/gestures.dart';
import 'package:kazumi/pages/player/player_controller.dart';
import 'package:flutter/material.dart';
@@ -32,8 +33,8 @@ import 'package:kazumi/pages/player/danmaku_source_sheet.dart';
import 'package:kazumi/pages/player/player_item_surface.dart';
import 'package:mobx/mobx.dart' as mobx;
import 'package:kazumi/pages/my/my_controller.dart';
-import 'package:saver_gallery/saver_gallery.dart';
import 'package:kazumi/services/player/audio_controller.dart';
+import 'package:kazumi/services/player/timed_shutdown_service.dart';
import 'package:kazumi/utils/device.dart';
import 'package:kazumi/services/platform/player_menu_service.dart';
@@ -130,6 +131,9 @@ class _PlayerItemState extends State<PlayerItem>
late final AnimationController _panelVisibilityController;
late final AnimationController _screenshotFeedbackController;
late final Animation<double> _screenshotFeedbackAnimation;
+ late final PlayerScreenshotController _screenshots =
+ playerController.screenshots;
+ bool _screenshotSheetOpen = false;
double lastPlayerSpeed = 1.0;
late double longPressPlaySpeed;
@@ -733,36 +737,90 @@ class _PlayerItemState extends State<PlayerItem>
}
Future<void> handleScreenshot() async {
- _playScreenshotFeedback();
-
- if (isDesktop()) {
- KazumiDialog.showToast(message: '桌面端暂未支持保存截图');
+ if (!mounted || _screenshots.busy || _screenshotSheetOpen) return;
+ final episode = videoPageController.playbackEpisode;
+ final source = videoPageController.src;
+ final player = playerController.playback.mediaPlayer;
+ if (videoPageController.loading || player == null) {
+ KazumiDialog.showToast(message: '暂未获取到画面,请等视频显示后重试');
return;
}
-
- try {
- Uint8List? screenshot = await playerController.screenshotPng();
-
- if (screenshot == null) {
- KazumiDialog.showToast(message: '截图失败:未获取到图像');
- return;
+ final added = await _screenshots.capture(
+ capturePng: playerController.screenshotPng,
+ title: videoPageController.title,
+ episode:
+ videoPageController.resolveEpisode(episode)?.displayTitle ??
+ '第 ${episode.episode} 集',
+ position: player.state.position,
+ isCurrent: () =>
+ mounted &&
+ !videoPageController.loading &&
+ videoPageController.playbackEpisode == episode &&
+ videoPageController.src == source &&
+ identical(playerController.playback.mediaPlayer, player),
+ );
+ if (!mounted) return;
+ if (added) _playScreenshotFeedback();
+ if (!_screenshotSheetOpen) {
+ showVideoController();
+ if (!added || _screenshots.candidates.length == 1) {
+ KazumiDialog.showToast(
+ message: added
+ ? '已截取画面,点击右侧图库挑选保存'
+ : _screenshots.message ?? '截图失败,请重试',
+ showActionButton: _screenshots.candidates.isNotEmpty,
+ actionLabel: '挑选截图',
+ onActionPressed: showScreenshotCandidates,
+ );
}
+ }
+ }
- final result = await SaverGallery.saveImage(
- screenshot,
- fileName: DateTime.timestamp().millisecondsSinceEpoch.toString(),
- skipIfExists: false,
- );
- if (!result.isSuccess) {
- KazumiDialog.showToast(message: '截图保存失败:${result.errorMessage}');
+ Future<void> showScreenshotCandidates() async {
+ if (!mounted || _screenshotSheetOpen || _screenshots.busy) return;
+ _screenshotSheetOpen = true;
+ final hold = acquirePlayerPanelHold();
+ final player = playerController.playback.mediaPlayer;
+ final episode = videoPageController.playbackEpisode;
+ final source = videoPageController.src;
+ final resume =
+ playerController.playback.playing &&
+ !playerController.syncplay.hasSession;
+ final sleepRemaining = TimedShutdownService().remainingSecondsNotifier.value;
+ final sleepDeadline = sleepRemaining > 0
+ ? DateTime.now().add(Duration(seconds: sleepRemaining))
+ : null;
+ try {
+ if (resume) await playerController.pause(enableSync: false);
+ if (!mounted) return;
+ await showPlayerScreenshotSheet(context, controller: _screenshots);
+ } finally {
+ _screenshotSheetOpen = false;
+ if (mounted) {
+ hold.release();
+ widget.keyboardFocus.requestFocus();
+ // Resume only the same local playback, respecting the sleep timer.
+ if (resume &&
+ identical(player, playerController.playback.mediaPlayer) &&
+ videoPageController.playbackEpisode == episode &&
+ videoPageController.src == source &&
+ !videoPageController.loading &&
+ !playerController.syncplay.hasSession &&
+ (sleepDeadline == null || DateTime.now().isBefore(sleepDeadline)) &&
+ WidgetsBinding.instance.lifecycleState == AppLifecycleState.resumed &&
+ (ModalRoute.of(context)?.isCurrent ?? false)) {
+ await playerController.play(enableSync: false);
+ }
+ } else {
+ hold.releaseSilently();
}
- } catch (e) {
- KazumiDialog.showToast(message: '截图失败:$e');
}
}
void _playScreenshotFeedback() {
- if (!mounted) {
+ if (!mounted ||
+ widget.disableAnimations ||
+ MediaQuery.disableAnimationsOf(context)) {
return;
}
_screenshotFeedbackController.forward(from: 0);
@@ -1464,6 +1522,7 @@ class _PlayerItemState extends State<PlayerItem>
pauseForTimedShutdown: widget.pauseForTimedShutdown,
disableAnimations: widget.disableAnimations,
handleScreenShot: handleScreenshot,
+ showScreenshotCandidates: showScreenshotCandidates,
skipOP: skipOP,
),
Positioned.fill(
diff --git a/lib/pages/player/player_item_panel.dart b/lib/pages/player/player_item_panel.dart
index 182c0614..b6138fd7 100644
--- a/lib/pages/player/player_item_panel.dart
+++ b/lib/pages/player/player_item_panel.dart
@@ -25,6 +25,7 @@ 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';
class PlayerItemPanel extends StatefulWidget {
const PlayerItemPanel({
@@ -38,6 +39,7 @@ class PlayerItemPanel extends StatefulWidget {
required this.handleFullscreen,
required this.enterAndroidPictureInPicture,
required this.handleScreenShot,
+ required this.showScreenshotCandidates,
required this.onNextEpisode,
required this.handleProgressBarDragStart,
required this.handleProgressBarSeek,
@@ -65,6 +67,7 @@ class PlayerItemPanel extends StatefulWidget {
final VoidCallback handleFullscreen;
final Future<void> Function() enterAndroidPictureInPicture;
final VoidCallback handleScreenShot;
+ final VoidCallback showScreenshotCandidates;
final VoidCallback handleProgressBarDragStart;
final Future<void> Function(Duration duration) handleProgressBarSeek;
final Future<void> Function(SuperResolutionMode mode)
@@ -448,27 +451,28 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
);
}),
),
- if (!_desktop)
- Positioned(
- right: 0,
- top: 0,
- bottom: 0,
- child: Observer(builder: (context) {
- if ((compact || !widget.fillsWindow) &&
- !playerController.panel.lockPanel) {
- return const SizedBox.shrink();
- }
- return Visibility(
- visible: widget.disableAnimations
- ? playerController.panel.showVideoController
- : true,
- child: widget.disableAnimations
- ? _rightControls
- : SlideTransition(
- position: _rightOffsetAnimation, child: _rightControls),
- );
- }),
- ),
+ Positioned(
+ right: 0,
+ top: 0,
+ bottom: 0,
+ child: Observer(builder: (context) {
+ if (!_desktop &&
+ (compact || !widget.fillsWindow) &&
+ !playerController.panel.lockPanel) {
+ return const SizedBox.shrink();
+ }
+ return Visibility(
+ visible: widget.disableAnimations
+ ? playerController.panel.showVideoController
+ : true,
+ child: widget.disableAnimations
+ ? _rightControls
+ : SlideTransition(
+ position: _rightOffsetAnimation,
+ child: _rightControls),
+ );
+ }),
+ ),
Positioned(
top: 0,
left: 0,
@@ -856,6 +860,16 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
);
},
menuChildren: [
+ MenuItemButton(
+ leadingIcon: const Icon(Icons.photo_camera_outlined),
+ onPressed: widget.handleScreenShot,
+ child: _menuLabel('截取当前画面'),
+ ),
+ MenuItemButton(
+ leadingIcon: const Icon(Icons.photo_library_outlined),
+ onPressed: widget.showScreenshotCandidates,
+ child: _menuLabel('挑选截图'),
+ ),
if (compact) ...[
SubmenuButton(
menuChildren: _aspectRatioItems,
@@ -959,33 +973,35 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
bottom: false,
left: widget.fillsWindow,
right: widget.fillsWindow,
- child: Column(
- children: [
- const Spacer(),
- if (!playerController.panel.lockPanel)
- IconButton(
- icon: const Icon(
- Icons.photo_camera_outlined,
- color: Colors.white,
+ child: PlayerPanelHoldMouseRegion(
+ acquirePlayerPanelHold: widget.acquirePlayerPanelHold,
+ cursor: SystemMouseCursors.basic,
+ child: Column(
+ children: [
+ const Spacer(),
+ if (!playerController.panel.lockPanel)
+ PlayerScreenshotControls(
+ controller: playerController.screenshots,
+ onCapture: widget.handleScreenShot,
+ onReview: widget.showScreenshotCandidates,
),
- tooltip: '截图',
- onPressed: widget.handleScreenShot,
- ),
- IconButton(
- icon: Icon(
- playerController.panel.lockPanel
- ? Icons.lock_outline
- : Icons.lock_open,
- color: Colors.white,
- ),
- tooltip: playerController.panel.lockPanel ? '解锁面板' : '锁定面板',
- onPressed: () {
- playerController.panel.lockPanel =
- !playerController.panel.lockPanel;
- },
- ),
- const Spacer(),
- ],
+ if (!_desktop)
+ IconButton(
+ icon: Icon(
+ playerController.panel.lockPanel
+ ? Icons.lock_outline
+ : Icons.lock_open,
+ color: Colors.white,
+ ),
+ tooltip: playerController.panel.lockPanel ? '解锁面板' : '锁定面板',
+ onPressed: () {
+ playerController.panel.lockPanel =
+ !playerController.panel.lockPanel;
+ },
+ ),
+ const Spacer(),
+ ],
+ ),
),
);
}
diff --git a/lib/pages/player/player_screenshot_controls.dart b/lib/pages/player/player_screenshot_controls.dart
new file mode 100644
index 00000000..9530cc67
--- /dev/null
+++ b/lib/pages/player/player_screenshot_controls.dart
@@ -0,0 +1,54 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_mobx/flutter_mobx.dart';
+import 'package:kazumi/pages/player/controller/player_screenshot_controller.dart';
+
+class PlayerScreenshotControls extends StatelessWidget {
+ const PlayerScreenshotControls({
+ super.key,
+ required this.controller,
+ required this.onCapture,
+ required this.onReview,
+ });
+ final PlayerScreenshotController controller;
+ final VoidCallback onCapture;
+ final VoidCallback onReview;
+
+ @override
+ Widget build(BuildContext context) => Observer(
+ builder: (context) => Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ IconButton(
+ tooltip: '截取当前画面',
+ style: IconButton.styleFrom(
+ foregroundColor: Colors.white,
+ minimumSize: const Size(48, 48),
+ ),
+ onPressed: controller.busy ? null : onCapture,
+ icon: controller.capturing
+ ? const SizedBox.square(
+ dimension: 20,
+ child: CircularProgressIndicator(
+ strokeWidth: 2,
+ color: Colors.white,
+ ),
+ )
+ : const Icon(Icons.photo_camera_outlined),
+ ),
+ if (controller.candidates.isNotEmpty)
+ IconButton(
+ tooltip: '挑选截图 · ${controller.candidates.length} 张',
+ style: IconButton.styleFrom(
+ foregroundColor: Colors.white,
+ minimumSize: const Size(48, 48),
+ ),
+ onPressed: controller.saving ? null : onReview,
+ icon: Badge.count(
+ count: controller.candidates.length,
+ child: const Icon(Icons.photo_library_outlined),
+ ),
+ ),
+ ],
+ ),
+ );
+}
diff --git a/lib/pages/player/player_screenshot_image.dart b/lib/pages/player/player_screenshot_image.dart
new file mode 100644
index 00000000..a4e3ce88
--- /dev/null
+++ b/lib/pages/player/player_screenshot_image.dart
@@ -0,0 +1,47 @@
+import 'dart:typed_data';
+
+import 'package:flutter/material.dart';
+
+class PlayerScreenshotImage extends StatelessWidget {
+ const PlayerScreenshotImage({
+ super.key,
+ required this.bytes,
+ this.fit = BoxFit.contain,
+ this.cacheWidth,
+ this.semanticLabel,
+ });
+
+ final Uint8List bytes;
+ final BoxFit fit;
+ final int? cacheWidth;
+ final String? semanticLabel;
+
+ @override
+ Widget build(BuildContext context) => Image.memory(
+ bytes,
+ fit: fit,
+ width: double.infinity,
+ height: double.infinity,
+ cacheWidth: cacheWidth,
+ gaplessPlayback: true,
+ semanticLabel: semanticLabel,
+ excludeFromSemantics: semanticLabel == null,
+ frameBuilder: (context, child, frame, synchronouslyLoaded) {
+ if (synchronouslyLoaded || MediaQuery.disableAnimationsOf(context)) {
+ return child;
+ }
+ return AnimatedOpacity(
+ opacity: frame == null ? 0 : 1,
+ duration: const Duration(milliseconds: 120),
+ curve: Curves.easeOut,
+ child: child,
+ );
+ },
+ errorBuilder: (context, error, stack) => Center(
+ child: Icon(
+ Icons.broken_image_outlined,
+ color: Theme.of(context).colorScheme.onSurfaceVariant,
+ ),
+ ),
+ );
+}
diff --git a/lib/pages/player/player_screenshot_sheet.dart b/lib/pages/player/player_screenshot_sheet.dart
new file mode 100644
index 00000000..7a97ae73
--- /dev/null
+++ b/lib/pages/player/player_screenshot_sheet.dart
@@ -0,0 +1,956 @@
+import 'dart:async';
+import 'dart:math' as math;
+import 'dart:ui' as ui;
+
+import 'package:flutter/gestures.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_mobx/flutter_mobx.dart';
+import 'package:kazumi/pages/player/controller/player_screenshot_controller.dart';
+import 'package:kazumi/pages/player/player_screenshot_image.dart';
+import 'package:kazumi/services/player/screenshot_candidate.dart';
+import 'package:kazumi/services/player/screenshot_export_service.dart';
+
+Future<void> showPlayerScreenshotSheet(
+ BuildContext context, {
+ required PlayerScreenshotController controller,
+}) => showDialog<void>(
+ context: context,
+ barrierDismissible: true,
+ builder: (context) => LayoutBuilder(
+ builder: (context, constraints) {
+ final inset = constraints.maxWidth < 700 || constraints.maxHeight < 500
+ ? 16.0
+ : 24.0;
+ return Dialog(
+ clipBehavior: Clip.antiAlias,
+ backgroundColor: Theme.of(context).colorScheme.surfaceContainerHigh,
+ insetPadding: EdgeInsets.all(inset),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(28)),
+ child: SizedBox(
+ width: 1120,
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight: math.min(840, constraints.maxHeight - inset * 2),
+ ),
+ child: _PlayerScreenshotSheet(controller: controller),
+ ),
+ ),
+ );
+ },
+ ),
+);
+
+class _PlayerScreenshotSheet extends StatefulWidget {
+ const _PlayerScreenshotSheet({required this.controller});
+ final PlayerScreenshotController controller;
+
+ @override
+ State<_PlayerScreenshotSheet> createState() => _PlayerScreenshotSheetState();
+}
+
+class _PlayerScreenshotSheetState extends State<_PlayerScreenshotSheet> {
+ static const _exportService = ScreenshotExportService();
+ late final PageController _pages;
+ final FocusNode _focus = FocusNode(debugLabel: 'Screenshot review');
+ final TransformationController _transform = TransformationController();
+ // Preserve paging and zoom state when rotation moves the preview.
+ final GlobalKey _previewKey = GlobalKey();
+ final Map<String, double?> _aspectRatios = {};
+ int _index = 0;
+ bool _zoomed = false;
+ bool _showResult = false;
+ String? _notice;
+ bool _noticeError = false;
+ Timer? _noticeTimer;
+
+ PlayerScreenshotController get collection => widget.controller;
+ ScreenshotCandidate? get current =>
+ collection.candidates.isEmpty ? null : collection.candidates[_index];
+ double get _aspectRatio => _aspectRatios[current?.id] ?? 16 / 9;
+ Duration get _motion => MediaQuery.disableAnimationsOf(context)
+ ? Duration.zero
+ : const Duration(milliseconds: 220);
+
+ @override
+ void initState() {
+ super.initState();
+ _index = math.max(0, collection.candidates.length - 1);
+ _pages = PageController(initialPage: _index);
+ }
+
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ _warmNeighbors();
+ }
+
+ void _warmNeighbors() {
+ for (
+ var i = math.max(0, _index - 1);
+ i <= math.min(collection.candidates.length - 1, _index + 1);
+ i++
+ ) {
+ final item = collection.candidates[i];
+ if (_aspectRatios.containsKey(item.id)) continue;
+ _aspectRatios[item.id] = null;
+ unawaited(_readAspectRatio(item));
+ unawaited(
+ precacheImage(MemoryImage(item.bytes), context, onError: (_, _) {}),
+ );
+ }
+ }
+
+ Future<void> _readAspectRatio(ScreenshotCandidate item) async {
+ ui.ImmutableBuffer? buffer;
+ ui.ImageDescriptor? descriptor;
+ try {
+ buffer = await ui.ImmutableBuffer.fromUint8List(item.bytes);
+ descriptor = await ui.ImageDescriptor.encoded(buffer);
+ if (!mounted) return;
+ final ratio = descriptor.width / descriptor.height;
+ final resize = current?.id == item.id && ratio != _aspectRatio;
+ _aspectRatios[item.id] = ratio;
+ if (resize) setState(() {});
+ } catch (_) {
+ // The image widget handles invalid image data.
+ } finally {
+ descriptor?.dispose();
+ buffer?.dispose();
+ }
+ }
+
+ @override
+ void dispose() {
+ _pages.dispose();
+ _focus.dispose();
+ _transform.dispose();
+ _noticeTimer?.cancel();
+ super.dispose();
+ }
+
+ void _goTo(int index) {
+ if (index < 0 || index >= collection.candidates.length || index == _index) {
+ return;
+ }
+ _pages.jumpToPage(index);
+ }
+
+ void _step(int delta) => _goTo(_index + delta);
+
+ void _toggleZoom() {
+ final size = _previewKey.currentContext?.size;
+ if (size == null || size.isEmpty) return;
+ setState(() {
+ _zoomed = !_zoomed;
+ _transform.value = _zoomed
+ ? (Matrix4.identity()
+ ..translateByDouble(-size.width * 0.5, -size.height * 0.5, 0, 1)
+ ..scaleByDouble(2, 2, 1, 1))
+ : Matrix4.identity();
+ });
+ }
+
+ void _toggle() {
+ final item = current;
+ if (item != null) collection.toggle(item);
+ }
+
+ void _close() {
+ if (!collection.saving) Navigator.maybePop(context);
+ }
+
+ Future<void> _save() async {
+ _noticeTimer?.cancel();
+ setState(() {
+ _showResult = true;
+ _notice = null;
+ });
+ await collection.save(
+ chooseDestination: _exportService.chooseDestination,
+ write: _exportService.write,
+ destinationLabel: _exportService.destinationLabel,
+ );
+ if (mounted) {
+ _focus.requestFocus();
+ setState(() {
+ _notice = collection.message;
+ _noticeError = collection.hasError;
+ });
+ _noticeTimer = Timer(const Duration(seconds: 5), () {
+ if (mounted) setState(() => _notice = null);
+ });
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) => Observer.withBuiltChild(
+ builder: (context, child) =>
+ PopScope(canPop: !collection.saving, child: child),
+ child: CallbackShortcuts(
+ bindings: {
+ const SingleActivator(LogicalKeyboardKey.arrowLeft): () => _step(-1),
+ const SingleActivator(LogicalKeyboardKey.arrowRight): () => _step(1),
+ const SingleActivator(LogicalKeyboardKey.space): _toggle,
+ const SingleActivator(LogicalKeyboardKey.escape): _close,
+ },
+ child: Focus(
+ focusNode: _focus,
+ autofocus: true,
+ child: IconButtonTheme(
+ data: const IconButtonThemeData(
+ style: ButtonStyle(
+ minimumSize: WidgetStatePropertyAll(Size(48, 48)),
+ ),
+ ),
+ child: Material(
+ color: Theme.of(context).colorScheme.surfaceContainerHigh,
+ child: LayoutBuilder(
+ builder: (context, constraints) => Observer(
+ builder: (context) {
+ final compact = constraints.maxHeight < 500;
+ final wide = constraints.maxWidth >= 700;
+ final landscape =
+ compact &&
+ constraints.maxWidth >= 480 &&
+ constraints.maxWidth > constraints.maxHeight;
+ final padding = compact || !wide ? 16.0 : 24.0;
+ if (current != null && landscape) {
+ return _landscape(context, constraints);
+ }
+ return Column(
+ mainAxisSize: wide ? MainAxisSize.max : MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ _header(context, compact: compact, padding: padding),
+ if (current == null)
+ Expanded(child: _empty(context))
+ else ...[
+ Flexible(
+ fit: wide ? FlexFit.tight : FlexFit.loose,
+ child: Padding(
+ padding: EdgeInsets.symmetric(horizontal: padding),
+ child: wide
+ ? Center(child: _preview())
+ : _preview(),
+ ),
+ ),
+ Padding(
+ padding: EdgeInsets.fromLTRB(
+ padding,
+ compact ? 8 : 16,
+ padding,
+ 0,
+ ),
+ child: Material(
+ color: Theme.of(
+ context,
+ ).colorScheme.surfaceContainerLow,
+ borderRadius: BorderRadius.circular(20),
+ clipBehavior: Clip.antiAlias,
+ child: Column(
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ 16,
+ 8,
+ 16,
+ 0,
+ ),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ '${current!.episode} · ${current!.timeLabel}',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: Theme.of(context)
+ .textTheme
+ .labelMedium
+ ?.copyWith(
+ color: Theme.of(
+ context,
+ ).colorScheme.onSurfaceVariant,
+ ),
+ ),
+ ),
+ _navigation(),
+ ],
+ ),
+ ),
+ _thumbnails(compact: compact),
+ ],
+ ),
+ ),
+ ),
+ _footer(
+ context,
+ compact: compact,
+ padding: padding,
+ showReturn: wide,
+ ),
+ ],
+ ],
+ );
+ },
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+
+ Widget _landscape(BuildContext context, BoxConstraints constraints) {
+ final panelWidth = math.min(
+ constraints.maxWidth * 0.4,
+ math.max(208.0, MediaQuery.textScalerOf(context).scale(160)),
+ );
+ return Padding(
+ padding: const EdgeInsets.all(12),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Expanded(
+ child: Column(
+ children: [
+ Expanded(child: Center(child: _preview())),
+ const SizedBox(height: 8),
+ Material(
+ color: Theme.of(context).colorScheme.surfaceContainerLow,
+ borderRadius: BorderRadius.circular(16),
+ clipBehavior: Clip.antiAlias,
+ child: _thumbnails(compact: true),
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(width: 16),
+ SizedBox(
+ width: panelWidth,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ _header(context, compact: true, padding: 0),
+ Expanded(
+ child: SingleChildScrollView(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ current!.title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: Theme.of(context).textTheme.titleSmall,
+ ),
+ const SizedBox(height: 4),
+ Text(
+ '${current!.episode} · ${current!.timeLabel}',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: Theme.of(context).textTheme.bodySmall,
+ ),
+ ],
+ ),
+ ),
+ ),
+ Center(child: _navigation()),
+ _footer(context, compact: true, padding: 0, stackActions: true),
+ ],
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ Widget _preview() => AspectRatio(
+ key: _previewKey,
+ aspectRatio: _aspectRatio,
+ child: ClipRRect(borderRadius: BorderRadius.circular(16), child: _stage()),
+ );
+
+ Widget _navigation() => Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ IconButton(
+ tooltip: '上一张',
+ onPressed: _index > 0 ? () => _step(-1) : null,
+ icon: const Icon(Icons.chevron_left_rounded),
+ ),
+ Text(
+ '${_index + 1} / ${collection.candidates.length}',
+ style: Theme.of(context).textTheme.labelMedium,
+ ),
+ IconButton(
+ tooltip: '下一张',
+ onPressed: _index < collection.candidates.length - 1
+ ? () => _step(1)
+ : null,
+ icon: const Icon(Icons.chevron_right_rounded),
+ ),
+ ],
+ );
+
+ Widget _header(
+ BuildContext context, {
+ required bool compact,
+ required double padding,
+ }) => Padding(
+ padding: EdgeInsets.fromLTRB(
+ padding,
+ compact ? 4 : 16,
+ math.max(0, padding - 8),
+ compact ? 4 : 16,
+ ),
+ child: Row(
+ children: [
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ '挑选截图',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: compact
+ ? Theme.of(context).textTheme.titleLarge
+ : Theme.of(context).textTheme.headlineSmall,
+ ),
+ if (!compact && current != null)
+ Text(
+ current!.title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: Theme.of(context).textTheme.bodyMedium?.copyWith(
+ color: Theme.of(context).colorScheme.onSurfaceVariant,
+ ),
+ ),
+ ],
+ ),
+ ),
+ if (current != null)
+ IconButton(
+ tooltip: _zoomed ? '还原大小' : '放大查看',
+ onPressed: _toggleZoom,
+ icon: Icon(
+ _zoomed ? Icons.zoom_out_rounded : Icons.zoom_in_rounded,
+ ),
+ ),
+ Observer(
+ builder: (context) => IconButton(
+ tooltip: '返回播放',
+ onPressed: collection.saving ? null : _close,
+ icon: const Icon(Icons.close_rounded),
+ ),
+ ),
+ ],
+ ),
+ );
+
+ Widget _stage() => ColoredBox(
+ color: const Color(0xff101114),
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ PageView.builder(
+ controller: _pages,
+ physics: _zoomed
+ ? const NeverScrollableScrollPhysics()
+ : const ClampingScrollPhysics(),
+ onPageChanged: (index) {
+ _transform.value = Matrix4.identity();
+ setState(() {
+ _index = index;
+ _zoomed = false;
+ });
+ _warmNeighbors();
+ },
+ itemCount: collection.candidates.length,
+ itemBuilder: (context, index) => GestureDetector(
+ key: ValueKey(collection.candidates[index].id),
+ onDoubleTap: index == _index ? _toggleZoom : null,
+ child: InteractiveViewer(
+ transformationController: index == _index ? _transform : null,
+ minScale: 1,
+ maxScale: 4,
+ panEnabled: index == _index && _zoomed,
+ onInteractionEnd: (_) {
+ if (index == _index) {
+ setState(() {
+ _zoomed = _transform.value.getMaxScaleOnAxis() > 1.01;
+ });
+ }
+ },
+ child: PlayerScreenshotImage(
+ bytes: collection.candidates[index].bytes,
+ semanticLabel:
+ '${collection.candidates[index].episode} '
+ '${collection.candidates[index].timeLabel} 截图',
+ ),
+ ),
+ ),
+ ),
+ Positioned(
+ left: 8,
+ right: 8,
+ bottom: 8,
+ child: Align(
+ alignment: Alignment.bottomCenter,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 520),
+ child: AnimatedSwitcher(
+ duration: _motion,
+ transitionBuilder: (child, animation) => FadeTransition(
+ opacity: animation,
+ child: SlideTransition(
+ position: Tween<Offset>(
+ begin: const Offset(0, 0.15),
+ end: Offset.zero,
+ ).animate(animation),
+ child: child,
+ ),
+ ),
+ child: _notice == null
+ ? const SizedBox.shrink()
+ : _noticeView(),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+
+ Widget _pickButton(ScreenshotCandidate item) => Observer(
+ builder: (context) {
+ final selected = collection.isSelected(item);
+ final saved = collection.isSaved(item);
+ return Semantics(
+ selected: selected,
+ child: FilledButton.tonalIcon(
+ style: _actionStyle(selected: selected).copyWith(
+ backgroundColor: WidgetStatePropertyAll(
+ selected
+ ? Theme.of(context).colorScheme.secondaryContainer
+ : Theme.of(context).colorScheme.surfaceContainerHighest,
+ ),
+ ),
+ onPressed: saved || collection.saving ? null : _toggle,
+ icon: Icon(
+ saved
+ ? Icons.download_done_rounded
+ : selected
+ ? Icons.check_circle_rounded
+ : Icons.radio_button_unchecked_rounded,
+ size: 20,
+ ),
+ label: Text(
+ saved
+ ? '已保存'
+ : selected
+ ? '已选中'
+ : '选择这张',
+ ),
+ ),
+ );
+ },
+ );
+
+ Widget _thumbnails({required bool compact}) => _ScreenshotFilmstrip(
+ controller: collection,
+ activeIndex: _index,
+ compact: compact,
+ duration: _motion,
+ onBrowse: _goTo,
+ );
+
+ Widget _noticeView() {
+ final colors = Theme.of(context).colorScheme;
+ return Semantics(
+ key: ValueKey(_notice),
+ liveRegion: true,
+ child: Material(
+ color: colors.inverseSurface,
+ elevation: 6,
+ borderRadius: BorderRadius.circular(12),
+ child: Padding(
+ padding: const EdgeInsets.only(left: 16, top: 4, bottom: 4),
+ child: Row(
+ children: [
+ Icon(
+ _noticeError
+ ? Icons.error_outline_rounded
+ : Icons.info_outline_rounded,
+ size: 20,
+ color: colors.onInverseSurface,
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Text(
+ _notice!,
+ maxLines: 3,
+ overflow: TextOverflow.ellipsis,
+ style: Theme.of(context).textTheme.bodyMedium?.copyWith(
+ color: colors.onInverseSurface,
+ ),
+ ),
+ ),
+ IconButton(
+ tooltip: '关闭提示',
+ color: colors.onInverseSurface,
+ onPressed: () => setState(() => _notice = null),
+ icon: const Icon(Icons.close_rounded, size: 20),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _footer(
+ BuildContext context, {
+ required bool compact,
+ required double padding,
+ bool showReturn = false,
+ bool stackActions = false,
+ }) {
+ final scaler = MediaQuery.textScalerOf(context);
+ final buttonHeight = math.max(48.0, scaler.scale(20) + 24);
+ final saveWidth = math.max(148.0, scaler.scale(100) + 48);
+ final save = SizedBox(
+ height: buttonHeight,
+ child: Observer(
+ builder: (context) {
+ final finished =
+ _showResult &&
+ !collection.saving &&
+ !collection.hasError &&
+ collection.saveCompleted > 0 &&
+ collection.selectedCount == 0;
+ return FilledButton.icon(
+ style: _actionStyle(),
+ onPressed: finished
+ ? _close
+ : !collection.busy && collection.selectedCount > 0
+ ? _save
+ : null,
+ icon: collection.saving
+ ? const SizedBox.square(
+ dimension: 18,
+ child: CircularProgressIndicator(strokeWidth: 2),
+ )
+ : Icon(
+ finished ? Icons.check_rounded : Icons.save_alt_rounded,
+ size: 20,
+ ),
+ label: Text(
+ collection.saving
+ ? '${collection.saveCompleted}/${collection.saveTotal}'
+ : finished
+ ? '完成'
+ : '保存${collection.selectedCount > 0 ? ' ${collection.selectedCount} 张' : '所选'}',
+ maxLines: 1,
+ ),
+ );
+ },
+ ),
+ );
+ return Padding(
+ padding: EdgeInsets.fromLTRB(
+ padding,
+ compact ? 8 : 16,
+ padding,
+ compact ? 8 : 24,
+ ),
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ // Keep action bounds stable across save results and text scales.
+ final stacked =
+ stackActions ||
+ constraints.maxWidth < saveWidth + scaler.scale(96) + 48;
+ final pick = SizedBox(
+ height: buttonHeight,
+ child: _pickButton(current!),
+ );
+ if (stacked) {
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [pick, const SizedBox(height: 8), save],
+ );
+ }
+ return Row(
+ children: [
+ pick,
+ const Spacer(),
+ if (showReturn) ...[
+ Observer(
+ builder: (context) => TextButton(
+ onPressed: collection.saving ? null : _close,
+ child: const Text('返回播放'),
+ ),
+ ),
+ const SizedBox(width: 8),
+ ],
+ SizedBox(width: saveWidth, child: save),
+ ],
+ );
+ },
+ ),
+ );
+ }
+
+ ButtonStyle _actionStyle({bool selected = false}) => ButtonStyle(
+ minimumSize: const WidgetStatePropertyAll(Size(48, 48)),
+ padding: const WidgetStatePropertyAll(
+ EdgeInsets.symmetric(horizontal: 20, vertical: 12),
+ ),
+ animationDuration: _motion,
+ shape: WidgetStateProperty.resolveWith(
+ (states) => RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(
+ states.contains(WidgetState.pressed)
+ ? 12
+ : selected
+ ? 16
+ : 24,
+ ),
+ ),
+ ),
+ );
+
+ Widget _empty(BuildContext context) => Center(
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.all(24),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(
+ Icons.photo_camera_outlined,
+ size: 40,
+ color: Theme.of(context).colorScheme.primary,
+ ),
+ const SizedBox(height: 20),
+ Text('还没有截图', style: Theme.of(context).textTheme.titleLarge),
+ const SizedBox(height: 8),
+ const Text(
+ '返回视频,点击相机收集喜欢的画面。\n截图会暂存在本次播放中。',
+ textAlign: TextAlign.center,
+ ),
+ const SizedBox(height: 24),
+ FilledButton.tonal(onPressed: _close, child: const Text('返回视频截图')),
+ ],
+ ),
+ ),
+ );
+}
+
+class _ScreenshotFilmstrip extends StatefulWidget {
+ const _ScreenshotFilmstrip({
+ required this.controller,
+ required this.activeIndex,
+ required this.compact,
+ required this.duration,
+ required this.onBrowse,
+ });
+
+ final PlayerScreenshotController controller;
+ final int activeIndex;
+ final bool compact;
+ final Duration duration;
+ final ValueChanged<int> onBrowse;
+
+ @override
+ State<_ScreenshotFilmstrip> createState() => _ScreenshotFilmstripState();
+}
+
+class _ScreenshotFilmstripState extends State<_ScreenshotFilmstrip> {
+ final ScrollController _scroll = ScrollController();
+ double? _target;
+ bool _positioned = false;
+
+ @override
+ void dispose() {
+ _scroll.dispose();
+ super.dispose();
+ }
+
+ void _centerActive() {
+ if (!mounted || !_scroll.hasClients) return;
+ final offset = _target!.clamp(0.0, _scroll.position.maxScrollExtent);
+ if (!_positioned || widget.duration == Duration.zero) {
+ _scroll.jumpTo(offset);
+ if (!_positioned) setState(() => _positioned = true);
+ } else {
+ _scroll.animateTo(
+ offset,
+ duration: widget.duration,
+ curve: Curves.easeOutCubic,
+ );
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) => LayoutBuilder(
+ builder: (context, constraints) => Observer(
+ builder: (context) {
+ final items = widget.controller.candidates;
+ final height = widget.compact ? 52.0 : 72.0;
+ final extent = widget.compact ? 80.0 : 108.0;
+ final padding = math.max(
+ 12.0,
+ (constraints.maxWidth - items.length * extent) / 2,
+ );
+ final target =
+ padding +
+ (widget.activeIndex + 0.5) * extent -
+ constraints.maxWidth / 2;
+ if (_target != target) {
+ _target = target;
+ WidgetsBinding.instance.addPostFrameCallback((_) => _centerActive());
+ }
+ return SizedBox(
+ height: height + (widget.compact ? 4 : 16),
+ child: ScrollConfiguration(
+ behavior: ScrollConfiguration.of(context).copyWith(
+ dragDevices: {
+ PointerDeviceKind.touch,
+ PointerDeviceKind.mouse,
+ PointerDeviceKind.trackpad,
+ },
+ ),
+ child: AnimatedOpacity(
+ opacity: _positioned ? 1 : 0,
+ duration: widget.duration == Duration.zero
+ ? Duration.zero
+ : const Duration(milliseconds: 120),
+ child: ListView.builder(
+ controller: _scroll,
+ scrollDirection: Axis.horizontal,
+ padding: EdgeInsets.symmetric(
+ horizontal: padding,
+ vertical: widget.compact ? 2 : 8,
+ ),
+ itemExtent: extent,
+ itemCount: items.length,
+ itemBuilder: (context, index) {
+ final item = items[index];
+ return Observer(
+ builder: (context) => _FrameThumbnail(
+ item: item,
+ index: index,
+ active: index == widget.activeIndex,
+ selected: widget.controller.isSelected(item),
+ saved: widget.controller.isSaved(item),
+ duration: widget.duration,
+ onTap: () => widget.onBrowse(index),
+ ),
+ );
+ },
+ ),
+ ),
+ ),
+ );
+ },
+ ),
+ );
+}
+
+class _FrameThumbnail extends StatelessWidget {
+ const _FrameThumbnail({
+ required this.item,
+ required this.index,
+ required this.active,
+ required this.selected,
+ required this.saved,
+ required this.duration,
+ required this.onTap,
+ });
+ final ScreenshotCandidate item;
+ final int index;
+ final bool active;
+ final bool selected;
+ final bool saved;
+ final Duration duration;
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ final colors = Theme.of(context).colorScheme;
+ return Semantics(
+ button: true,
+ selected: active,
+ label:
+ '查看第 ${index + 1} 张,${item.episode} ${item.timeLabel}${saved
+ ? ',已保存'
+ : selected
+ ? ',已选中'
+ : ''}',
+ child: Material(
+ color: Colors.transparent,
+ child: InkWell(
+ borderRadius: BorderRadius.circular(12),
+ onTap: onTap,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 4),
+ child: AnimatedContainer(
+ duration: duration,
+ curve: Curves.easeInOutCubicEmphasized,
+ padding: const EdgeInsets.all(3),
+ decoration: BoxDecoration(
+ border: Border.all(
+ color: active ? colors.primary : Colors.transparent,
+ width: 2,
+ ),
+ borderRadius: BorderRadius.circular(active ? 12 : 8),
+ ),
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(6),
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ PlayerScreenshotImage(
+ bytes: item.bytes,
+ fit: BoxFit.cover,
+ cacheWidth: 240,
+ ),
+ if (selected || saved)
+ Positioned(
+ right: 3,
+ bottom: 3,
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ color: selected
+ ? colors.primary
+ : colors.inverseSurface,
+ shape: BoxShape.circle,
+ border: Border.all(
+ color: colors.surface,
+ width: 1.5,
+ ),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.all(2),
+ child: Icon(
+ saved
+ ? Icons.done_all_rounded
+ : Icons.check_rounded,
+ size: 14,
+ color: selected
+ ? colors.onPrimary
+ : colors.onInverseSurface,
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/lib/services/player/player_screenshot_service.dart b/lib/services/player/player_screenshot_service.dart
deleted file mode 100644
index c2aefcfd..00000000
--- a/lib/services/player/player_screenshot_service.dart
+++ /dev/null
@@ -1,143 +0,0 @@
-import 'dart:isolate';
-import 'dart:typed_data';
-
-import 'package:image/image.dart' as image;
-import 'package:media_kit/media_kit.dart';
-
-class PlayerScreenshotService {
- const PlayerScreenshotService();
-
- Future<Uint8List?> capturePng(Player player) async {
- final raw = await player.safeScreenshot(format: null);
- if (raw == null || raw.isEmpty) {
- return null;
- }
-
- final geometry = _ScreenshotGeometry.resolve(
- rawLength: raw.lengthInBytes,
- state: player.state,
- );
- if (geometry == null) {
- return null;
- }
-
- final request = _ScreenshotEncodeRequest(
- raw: TransferableTypedData.fromList([raw]),
- width: geometry.width,
- height: geometry.height,
- rowStride: geometry.rowStride,
- );
- final encoded = await Isolate.run(
- () => _encodeBgraToPng(request),
- );
-
- return encoded.materialize().asUint8List();
- }
-}
-
-class _ScreenshotGeometry {
- const _ScreenshotGeometry({
- required this.width,
- required this.height,
- required this.rowStride,
- });
-
- final int width;
- final int height;
- final int rowStride;
-
- static _ScreenshotGeometry? resolve({
- required int rawLength,
- required PlayerState state,
- }) {
- for (final candidate in _dimensionCandidates(state)) {
- final width = candidate.width;
- final height = candidate.height;
- if (width <= 0 || height <= 0) {
- continue;
- }
- if (rawLength % height != 0) {
- continue;
- }
- final rowStride = rawLength ~/ height;
- if (rowStride < width * 4) {
- continue;
- }
- return _ScreenshotGeometry(
- width: width,
- height: height,
- rowStride: rowStride,
- );
- }
- return null;
- }
-
- static Iterable<_ScreenshotDimensions> _dimensionCandidates(
- PlayerState state,
- ) sync* {
- final seen = <String>{};
-
- _ScreenshotDimensions? unique(int? width, int? height) {
- if (width == null || height == null || width <= 0 || height <= 0) {
- return null;
- }
- final key = '$width:$height';
- if (!seen.add(key)) {
- return null;
- }
- return _ScreenshotDimensions(width, height);
- }
-
- final params = state.videoParams;
- final rotate = params.rotate ?? 0;
- final rotated = rotate == 90 || rotate == 270;
-
- for (final candidate in [
- unique(state.width, state.height),
- unique(params.dw, params.dh),
- if (rotated) unique(params.dh, params.dw),
- unique(params.w, params.h),
- if (rotated) unique(params.h, params.w),
- ]) {
- if (candidate != null) {
- yield candidate;
- }
- }
- }
-}
-
-class _ScreenshotDimensions {
- const _ScreenshotDimensions(this.width, this.height);
-
- final int width;
- final int height;
-}
-
-class _ScreenshotEncodeRequest {
- const _ScreenshotEncodeRequest({
- required this.raw,
- required this.width,
- required this.height,
- required this.rowStride,
- });
-
- final TransferableTypedData raw;
- final int width;
- final int height;
- final int rowStride;
-}
-
-TransferableTypedData _encodeBgraToPng(_ScreenshotEncodeRequest request) {
- final raw = request.raw.materialize().asUint8List();
- final frame = image.Image.fromBytes(
- width: request.width,
- height: request.height,
- bytes: raw.buffer,
- bytesOffset: raw.offsetInBytes,
- numChannels: 4,
- rowStride: request.rowStride,
- order: image.ChannelOrder.bgra,
- );
- final png = Uint8List.fromList(image.encodePng(frame));
- return TransferableTypedData.fromList([png]);
-}
diff --git a/lib/services/player/screenshot_candidate.dart b/lib/services/player/screenshot_candidate.dart
new file mode 100644
index 00000000..001d5c4d
--- /dev/null
+++ b/lib/services/player/screenshot_candidate.dart
@@ -0,0 +1,24 @@
+import 'dart:typed_data';
+
+class ScreenshotCandidate {
+ const ScreenshotCandidate({
+ required this.id,
+ required this.bytes,
+ required this.title,
+ required this.episode,
+ required this.position,
+ });
+
+ final String id;
+ final Uint8List bytes;
+ final String title;
+ final String episode;
+ final Duration position;
+
+ String get timeLabel {
+ String pad(int value) => value.toString().padLeft(2, '0');
+ final hours = position.inHours;
+ return '${hours > 0 ? '${pad(hours)}:' : ''}'
+ '${pad(position.inMinutes % 60)}:${pad(position.inSeconds % 60)}';
+ }
+}
diff --git a/lib/services/player/screenshot_export_service.dart b/lib/services/player/screenshot_export_service.dart
new file mode 100644
index 00000000..0c90344f
--- /dev/null
+++ b/lib/services/player/screenshot_export_service.dart
@@ -0,0 +1,79 @@
+import 'dart:io';
+
+import 'package:file_picker/file_picker.dart';
+import 'package:kazumi/services/player/screenshot_candidate.dart';
+import 'package:path/path.dart' as path;
+import 'package:saver_gallery/saver_gallery.dart';
+
+enum _ScreenshotDestination {
+ gallery('相册'),
+ directory('所选位置');
+
+ const _ScreenshotDestination(this.label);
+ final String label;
+}
+
+class ScreenshotExportService {
+ const ScreenshotExportService();
+
+ _ScreenshotDestination get _destination =>
+ Platform.isAndroid || Platform.isIOS || Platform.operatingSystem == 'ohos'
+ ? _ScreenshotDestination.gallery
+ : _ScreenshotDestination.directory;
+
+ String get destinationLabel => _destination.label;
+
+ Future<String?> chooseDestination() async {
+ if (_destination == _ScreenshotDestination.directory) {
+ return FilePicker.platform.getDirectoryPath(
+ dialogTitle: '选择截图保存文件夹',
+ lockParentWindow: true,
+ );
+ }
+ return _destination.name;
+ }
+
+ Future<void> write(ScreenshotCandidate item, String location) async {
+ final name = _fileName(item);
+ switch (_destination) {
+ case _ScreenshotDestination.gallery:
+ final result = await SaverGallery.saveImage(
+ item.bytes,
+ fileName: name,
+ extension: 'png',
+ androidRelativePath: 'Pictures/Kazumi',
+ skipIfExists: false,
+ );
+ if (!result.isSuccess) {
+ throw StateError(result.errorMessage ?? 'Gallery save failed');
+ }
+ return;
+ case _ScreenshotDestination.directory:
+ var file = File(path.join(location, name));
+ var suffix = 1;
+ while (await file.exists()) {
+ file = File(
+ path.join(
+ location,
+ '${path.basenameWithoutExtension(name)}_${suffix++}.png',
+ ),
+ );
+ }
+ await file.writeAsBytes(item.bytes, flush: true);
+ }
+ }
+
+ static String _fileName(ScreenshotCandidate item) {
+ String clean(String value) {
+ final safe = value
+ .replaceAll(RegExp(r'[<>:"/\\|?*\x00-\x1f]'), '_')
+ .trim()
+ .replaceAll(RegExp(r'[. ]+$'), '');
+ // Leave room for the ID within common 255-byte filename limits.
+ return String.fromCharCodes(safe.runes.take(24));
+ }
+
+ return 'Kazumi_${clean(item.title)}_${clean(item.episode)}_'
+ '${item.timeLabel.replaceAll(':', '-')}_${item.id}.png';
+ }
+}