基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。
refactor(player): unify fullscreen behavior and layout ownership
Prediditc2c21b5f25f3
diff --git a/android/app/src/main/kotlin/com/example/kazumi/MainActivity.kt b/android/app/src/main/kotlin/com/example/kazumi/MainActivity.ktindex 4d1512ad..e098691a 100644--- a/android/app/src/main/kotlin/com/example/kazumi/MainActivity.kt+++ b/android/app/src/main/kotlin/com/example/kazumi/MainActivity.kt@@ -46,7 +46,7 @@ class MainActivity: AudioServiceActivity() {private var pipAspectHeight = 9private var pipSourceRect: Rect? = nullprivate var inPipMode = false- private var androidFullscreen = false+ private var systemBarsHidden = falseprivate var originalWindowBackground: Drawable? = nullprivate var windowBackgroundOverridden = false@@ -83,7 +83,7 @@ class MainActivity: AudioServiceActivity() {override fun onWindowFocusChanged(hasFocus: Boolean) {super.onWindowFocusChanged(hasFocus)- if (hasFocus && androidFullscreen) {+ if (hasFocus) {applySystemBarsState()}}@@ -112,17 +112,12 @@ class MainActivity: AudioServiceActivity() {} else {result.error("INVALID_ARGUMENT", "URL and MIME type required", null)}- } else if (call.method == "checkIfInMultiWindowMode") {- val isInMultiWindow = checkIfInMultiWindowMode()- result.success(isInMultiWindow)} else if (call.method == "getAndroidSdkVersion") {val sdkVersion = getAndroidSdkVersion()result.success(sdkVersion)- } else if (call.method == "enterFullscreen") {- enterAndroidFullscreen()- result.success(null)- } else if (call.method == "exitFullscreen") {- exitAndroidFullscreen()+ } else if (call.method == "setSystemBarsHidden") {+ systemBarsHidden = call.arguments as? Boolean ?: false+ applySystemBarsState()result.success(null)} else {result.notImplemented()@@ -181,28 +176,10 @@ class MainActivity: AudioServiceActivity() {startActivity(intent)}- private fun checkIfInMultiWindowMode(): Boolean {- return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {- this.isInMultiWindowMode- } else {- false- }- }-private fun getAndroidSdkVersion(): Int {return Build.VERSION.SDK_INT}- private fun enterAndroidFullscreen() {- androidFullscreen = true- applySystemBarsState()- }-- private fun exitAndroidFullscreen() {- androidFullscreen = false- applySystemBarsState()- }-// System bars belong to the full size window; replayed on leaving PiP.private fun applySystemBarsState() {if (inPipMode) {@@ -210,7 +187,7 @@ class MainActivity: AudioServiceActivity() {}WindowCompat.setDecorFitsSystemWindows(window, false)val controller = WindowCompat.getInsetsController(window, window.decorView)- if (androidFullscreen) {+ if (systemBarsHidden) {controller.systemBarsBehavior =WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPEcontroller.hide(WindowInsetsCompat.Type.systemBars())@@ -219,24 +196,18 @@ class MainActivity: AudioServiceActivity() {}}- // Single entry point: the mode callback and the configuration change both- // route here, whichever the OEM delivers first.+ // Either PiP callback may arrive first, depending on the device.private fun syncPictureInPictureMode() {val current = isInPictureInPictureMode- if (current == inPipMode) {- return- }- inPipMode = current- pipChannel?.invokeMethod("onModeChanged", mapOf("isInPipMode" to current))- refreshWindowBackground()- if (!current) {- applySystemBarsState()+ if (current != inPipMode) {+ inPipMode = current+ pipChannel?.invokeMethod("onModeChanged", mapOf("isInPipMode" to current))+ refreshWindowBackground()}+ applySystemBarsState()}- // The window background shows through the Flutter surface while a resized- // surface has no frame yet, so the light theme would paint the picture in- // picture transition white.+ // Cover the surface with black until Flutter renders the resized frame.private fun refreshWindowBackground() {val blackBackground = inPipMode || pipInPlayerPageif (blackBackground == windowBackgroundOverridden) {diff --git a/lib/bean/card/bangumi_card.dart b/lib/bean/card/bangumi_card.dartindex 91f9c953..a57648f2 100644--- a/lib/bean/card/bangumi_card.dart+++ b/lib/bean/card/bangumi_card.dart@@ -3,7 +3,6 @@ import 'package:flutter_modular/flutter_modular.dart';import 'package:kazumi/bean/card/network_img_layer.dart';import 'package:kazumi/bean/dialog/dialog_helper.dart';import 'package:kazumi/modules/bangumi/bangumi_item.dart';-import 'package:kazumi/utils/device.dart';// 视频卡片 - 垂直布局class BangumiCardV extends StatelessWidget {@@ -76,34 +75,37 @@ class BangumiContent extends StatelessWidget {final BangumiItem bangumiItem;- static int maxTextLinesFor(BuildContext context) {- return isDesktop()- ? 3- : (isTablet() &&- MediaQuery.of(context).orientation == Orientation.landscape)- ? 3- : 2;- }-@overrideWidget build(BuildContext context) {final ts = MediaQuery.textScalerOf(context);- final int maxTextLines = maxTextLinesFor(context);return Expanded(child: Padding(padding: const EdgeInsets.fromLTRB(5, 3, 5, 1),- child: Text(- bangumiItem.nameCn,- textAlign: TextAlign.start,- style: const TextStyle(- fontWeight: FontWeight.w500,- letterSpacing: 0.3,- ),- textScaler: ts.clamp(maxScaleFactor: 1.1),- maxLines: maxTextLines,- overflow: TextOverflow.ellipsis,- ),+ child: LayoutBuilder(builder: (context, constraints) {+ final style = DefaultTextStyle.of(context).style.copyWith(+ fontWeight: FontWeight.w500,+ letterSpacing: 0.3,+ );+ final textScaler = ts.clamp(maxScaleFactor: 1.1);+ final painter = TextPainter(+ text: TextSpan(text: bangumiItem.nameCn, style: style),+ textDirection: Directionality.of(context),+ textScaler: textScaler,+ );+ final lines = (constraints.maxHeight / painter.preferredLineHeight)+ .floor()+ .clamp(1, 3);+ painter.dispose();+ return Text(+ bangumiItem.nameCn,+ textAlign: TextAlign.start,+ style: style,+ textScaler: textScaler,+ maxLines: lines,+ overflow: TextOverflow.ellipsis,+ );+ }),),);}diff --git a/lib/bean/dialog/adaptive_bottom_sheet.dart b/lib/bean/dialog/adaptive_bottom_sheet.dartindex babb3464..10d2246c 100644--- a/lib/bean/dialog/adaptive_bottom_sheet.dart+++ b/lib/bean/dialog/adaptive_bottom_sheet.dart@@ -5,8 +5,6 @@ import 'dart:math' as math;import 'package:flutter/material.dart';import 'package:flutter/physics.dart';-import 'package:kazumi/utils/device.dart';-BoxConstraints _adaptiveBottomSheetConstraints(BuildContext context, {required double maxHeightFactor,@@ -14,12 +12,10 @@ BoxConstraints _adaptiveBottomSheetConstraints(}) {final size = MediaQuery.sizeOf(context);final isLandscape = size.width > size.height;- final isLargeScreen = size.shortestSide >= 600;final useFullWidth = !isLandscape && size.width < 600;final maxWidth =useFullWidth ? size.width : math.min(size.width * 0.72, 640.0);- final useExpandedLandscapeHeight =- isLandscape && !isDesktop() && !isLargeScreen;+ final useExpandedLandscapeHeight = isLandscape && size.height < 600;final maxHeight = size.height *(useExpandedLandscapeHeight? compactLandscapeMaxHeightFactordiff --git a/lib/pages/player/player_item.dart b/lib/pages/player/player_item.dartindex 228630e9..0bcedfb9 100644--- a/lib/pages/player/player_item.dart+++ b/lib/pages/player/player_item.dart@@ -6,7 +6,6 @@ import 'package:kazumi/pages/player/controller/player_super_resolution.dart';import 'package:kazumi/pages/player/player_panel_hold.dart';import 'package:kazumi/pages/player/player_pointer_interaction.dart';import 'package:kazumi/pages/player/player_screenshot_feedback_overlay.dart';-import 'package:kazumi/pages/player/smallest_player_item_panel.dart';import 'package:kazumi/pages/player/syncplay_sheet.dart';import 'package:kazumi/utils/constants.dart';import 'package:kazumi/services/logging/logger.dart';@@ -37,7 +36,6 @@ 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/utils/device.dart';-import 'package:kazumi/services/platform/display_mode_service.dart';import 'package:kazumi/services/platform/player_menu_service.dart';class PlayerItem extends StatefulWidget {@@ -45,9 +43,8 @@ class PlayerItem extends StatefulWidget {super.key,required this.playerController,required this.videoPageController,- required this.toggleMenu,- required this.showMenuImmediately,- required this.hideMenuImmediately,+ required this.fillsWindow,+ this.onToggleSidePanel,required this.changeEpisode,required this.onBackPressed,required this.keyboardFocus,@@ -57,12 +54,11 @@ class PlayerItem extends StatefulWidget {final PlayerController playerController;final VideoPageController videoPageController;- final VoidCallback toggleMenu;- final VoidCallback showMenuImmediately;- final VoidCallback hideMenuImmediately;+ final bool fillsWindow;+ final VoidCallback? onToggleSidePanel;final Future<void> Function(int episode, {int currentRoad, int offset})changeEpisode;- final void Function(BuildContext) onBackPressed;+ final VoidCallback onBackPressed;final FocusNode keyboardFocus;final bool disableAnimations;final VoidCallback pauseForTimedShutdown;@@ -94,7 +90,12 @@ class _PlayerItemState extends State<PlayerItem>final _videoSurfaceKey = GlobalKey();late bool _border;late double _opacity;- late double _fontSize;+ double get _fontSize => GStorage.getSetting(+ SettingsKeys.danmakuFontSize,+ context: SettingContext(+ compactLayout: MediaQuery.sizeOf(context).shortestSide < 600,+ ),+ );late double _danmakuArea;late bool _hideTop;late bool _hideBottom;@@ -245,7 +246,7 @@ class _PlayerItemState extends State<PlayerItem>if (size.isEmpty) {return null;}- Rect rect = renderObject.localToGlobal(Offset.zero) & size;+ Rect rect = Offset.zero & size;final int videoWidth = playerController.debug.playerWidth;final int videoHeight = playerController.debug.playerHeight;if (videoWidth > 0 && videoHeight > 0) {@@ -259,6 +260,8 @@ class _PlayerItemState extends State<PlayerItem>height: videoHeight * scale,);}+ // Convert the fitted video rectangle to window coordinates for native PiP.+ rect = MatrixUtils.transformRect(renderObject.getTransformTo(null), rect);final double ratio = MediaQuery.devicePixelRatioOf(context);return Rect.fromLTRB(rect.left * ratio,@@ -465,13 +468,9 @@ class _PlayerItemState extends State<PlayerItem>}void handleShortcutExitFullscreen() {- if (videoPageController.isFullscreen && !isTablet()) {- try {- playerController.danmaku.canvasController.clear();- } catch (_) {}- DisplayModeService.exitFullScreen();- videoPageController.isFullscreen = !videoPageController.isFullscreen;- } else if (!Platform.isMacOS) {+ if (videoPageController.isFullscreen) {+ unawaited(videoPageController.fullscreen.setFullscreen(false));+ } else if (isDesktop() && !Platform.isMacOS) {playerController.pause();windowManager.hide();}@@ -666,7 +665,7 @@ class _PlayerItemState extends State<PlayerItem>}}- void _handleFullscreenChange(BuildContext context) async {+ void _handleFullscreenChange() async {playerController.panel.lockPanel = false;_releasePlayerPanelHolds();playerController.danmaku.canvasController.clear();@@ -872,17 +871,9 @@ class _PlayerItemState extends State<PlayerItem>}void handleFullscreen() {- _handleFullscreenChange(context);- if (videoPageController.isFullscreen) {- DisplayModeService.exitFullScreen();- if (!isDesktop()) {- widget.showMenuImmediately();- }- } else {- DisplayModeService.enterFullScreen();- widget.hideMenuImmediately();+ if (!videoPageController.isPip) {+ unawaited(videoPageController.fullscreen.toggle());}- videoPageController.isFullscreen = !videoPageController.isFullscreen;}bool get _canHidePlayerPanel =>@@ -1266,22 +1257,6 @@ class _PlayerItemState extends State<PlayerItem>);}- bool _needsFullPanel(BuildContext context) {- final size = MediaQuery.sizeOf(context);- if (size.width < LayoutBreakpoint.compact['width']!) {- return false;- }- if (videoPageController.isPip) {- return false;- }- if (!isDesktop() &&- size.height > LayoutBreakpoint.compact['height']! &&- size.width < LayoutBreakpoint.medium['width']!) {- return false;- }- return true;- }-@overridevoid onWindowRestore() {playerController.danmaku.canvasController.clear();@@ -1296,7 +1271,7 @@ class _PlayerItemState extends State<PlayerItem>_fullscreenListener = mobx.reaction<bool>((_) => videoPageController.isFullscreen,(_) {- _handleFullscreenChange(context);+ _handleFullscreenChange();},);_playerSizeListener = mobx.reaction<String>(@@ -1354,10 +1329,6 @@ class _PlayerItemState extends State<PlayerItem>);_border = GStorage.getSetting(SettingsKeys.danmakuBorder);_opacity = GStorage.getSetting(SettingsKeys.danmakuOpacity);- _fontSize = GStorage.getSetting(- SettingsKeys.danmakuFontSize,- context: SettingContext(compactLayout: isCompact()),- );_danmakuArea = GStorage.getSetting(SettingsKeys.danmakuArea);_hideTop = !GStorage.getSetting(SettingsKeys.danmakuTop);_hideBottom = !GStorage.getSetting(SettingsKeys.danmakuBottom);@@ -1448,12 +1419,7 @@ class _PlayerItemState extends State<PlayerItem>playerController.setVolume(volume);}},- child: SizedBox(- height: videoPageController.isFullscreen ||- videoPageController.isPip- ? (MediaQuery.of(context).size.height)- : (MediaQuery.of(context).size.width * 9.0 / (16.0)),- width: MediaQuery.of(context).size.width,+ child: SizedBox.expand(child: Stack(alignment: Alignment.center, children: [PlayerKeyboardShortcuts(focusScopeNode: widget.keyboardFocus,@@ -1526,14 +1492,7 @@ class _PlayerItemState extends State<PlayerItem>height: double.infinity,),),- Positioned(- top: 0,- left: 0,- right: 0,- height: videoPageController.isFullscreen ||- videoPageController.isPip- ? MediaQuery.sizeOf(context).height- : (MediaQuery.sizeOf(context).width * 9 / 16),+ Positioned.fill(child: DanmakuScreen(key: _danmuKey,createdController: (DanmakuController e) {@@ -1569,65 +1528,37 @@ class _PlayerItemState extends State<PlayerItem>(Platform.isAndroid &&(videoPageController.isPip || _pipEnterRequested))? const SizedBox.shrink()- : (_needsFullPanel(context))- ? PlayerItemPanel(- playerController: playerController,- videoPageController: videoPageController,- onBackPressed: widget.onBackPressed,- setPlaybackSpeed: setPlaybackSpeed,- showDanmakuSwitch: showDanmakuSwitch,- toggleMenu: widget.toggleMenu,- handleFullscreen: handleFullscreen,- enterAndroidPictureInPicture:- enterAndroidPictureInPicture,- handleProgressBarDragStart:- handleProgressBarDragStart,- handleProgressBarSeek: handleProgressBarSeek,- handleSuperResolutionChange:- handleSuperResolutionChange,- handlePreNextEpisode: handlePreNextEpisode,- panelVisibilityController:- _panelVisibilityController,- keyboardFocus: widget.keyboardFocus,- acquirePlayerPanelHold: acquirePlayerPanelHold,- onMenuVisibilityChanged:- _handlePlayerMenuVisibilityChanged,- handleDanmaku: handleDanmaku,- showVideoInfo: showVideoInfo,- showSyncPlayPanel: showSyncPlayPanel,- pauseForTimedShutdown:- widget.pauseForTimedShutdown,- disableAnimations: widget.disableAnimations,- handleScreenShot: handleScreenshot,- skipOP: skipOP,- )- : SmallestPlayerItemPanel(- playerController: playerController,- videoPageController: videoPageController,- onBackPressed: widget.onBackPressed,- setPlaybackSpeed: setPlaybackSpeed,- showDanmakuSwitch: showDanmakuSwitch,- handleFullscreen: handleFullscreen,- enterAndroidPictureInPicture:- enterAndroidPictureInPicture,- handleProgressBarDragStart:- handleProgressBarDragStart,- handleProgressBarSeek: handleProgressBarSeek,- handleSuperResolutionChange:- handleSuperResolutionChange,- panelVisibilityController:- _panelVisibilityController,- acquirePlayerPanelHold: acquirePlayerPanelHold,- onMenuVisibilityChanged:- _handlePlayerMenuVisibilityChanged,- handleDanmaku: handleDanmaku,- showVideoInfo: showVideoInfo,- showSyncPlayPanel: showSyncPlayPanel,- pauseForTimedShutdown:- widget.pauseForTimedShutdown,- disableAnimations: widget.disableAnimations,- skipOP: skipOP,- ),+ : PlayerItemPanel(+ fillsWindow: widget.fillsWindow,+ playerController: playerController,+ videoPageController: videoPageController,+ onBackPressed: widget.onBackPressed,+ setPlaybackSpeed: setPlaybackSpeed,+ showDanmakuSwitch: showDanmakuSwitch,+ onToggleSidePanel: widget.onToggleSidePanel,+ handleFullscreen: handleFullscreen,+ enterAndroidPictureInPicture:+ enterAndroidPictureInPicture,+ handleProgressBarDragStart:+ handleProgressBarDragStart,+ handleProgressBarSeek: handleProgressBarSeek,+ handleSuperResolutionChange:+ handleSuperResolutionChange,+ onNextEpisode: () => handlePreNextEpisode('next'),+ panelVisibilityController:+ _panelVisibilityController,+ keyboardFocus: widget.keyboardFocus,+ acquirePlayerPanelHold: acquirePlayerPanelHold,+ onMenuVisibilityChanged:+ _handlePlayerMenuVisibilityChanged,+ handleDanmaku: handleDanmaku,+ showVideoInfo: showVideoInfo,+ showSyncPlayPanel: showSyncPlayPanel,+ pauseForTimedShutdown: widget.pauseForTimedShutdown,+ disableAnimations: widget.disableAnimations,+ handleScreenShot: handleScreenshot,+ skipOP: skipOP,+ ),Positioned.fill(left: 16,top: 25,diff --git a/lib/pages/player/player_item_panel.dart b/lib/pages/player/player_item_panel.dartindex ec39878d..71c27158 100644--- a/lib/pages/player/player_item_panel.dart+++ b/lib/pages/player/player_item_panel.dart@@ -1,9 +1,9 @@import 'dart:async';-import 'dart:io';++import 'package:flutter/foundation.dart';import 'package:canvas_danmaku/models/danmaku_content_item.dart';import 'package:flutter/material.dart';import 'package:flutter_mobx/flutter_mobx.dart';-import 'package:flutter_modular/flutter_modular.dart';import 'package:flutter_svg/flutter_svg.dart';import 'package:kazumi/bean/widget/play_pause_icon.dart';import 'package:kazumi/pages/player/player_adjustment_hud.dart';@@ -23,27 +23,27 @@ import 'package:kazumi/pages/settings/danmaku/danmaku_settings_sheet.dart';import 'package:kazumi/utils/constants.dart';import 'package:audio_video_progress_bar/audio_video_progress_bar.dart';import 'package:kazumi/services/player/timed_shutdown_service.dart';-import 'package:kazumi/pages/download/download_controller.dart';-import 'package:kazumi/utils/device.dart';import 'package:kazumi/utils/format.dart';+import 'package:kazumi/pages/player/player_transport_bar.dart';class PlayerItemPanel extends StatefulWidget {const PlayerItemPanel({super.key,required this.playerController,required this.videoPageController,+ required this.fillsWindow,required this.onBackPressed,required this.setPlaybackSpeed,required this.showDanmakuSwitch,required this.handleFullscreen,required this.enterAndroidPictureInPicture,required this.handleScreenShot,- required this.handlePreNextEpisode,+ required this.onNextEpisode,required this.handleProgressBarDragStart,required this.handleProgressBarSeek,required this.handleSuperResolutionChange,required this.panelVisibilityController,- required this.toggleMenu,+ this.onToggleSidePanel,required this.keyboardFocus,required this.acquirePlayerPanelHold,required this.onMenuVisibilityChanged,@@ -57,13 +57,14 @@ class PlayerItemPanel extends StatefulWidget {final PlayerController playerController;final VideoPageController videoPageController;- final void Function(BuildContext) onBackPressed;+ final bool fillsWindow;+ final VoidCallback onBackPressed;final Future<void> Function(double) setPlaybackSpeed;- final void Function() showDanmakuSwitch;- final void Function() toggleMenu;- final void Function() handleFullscreen;+ final VoidCallback showDanmakuSwitch;+ final VoidCallback? onToggleSidePanel;+ final VoidCallback handleFullscreen;final Future<void> Function() enterAndroidPictureInPicture;- final void Function() handleScreenShot;+ final VoidCallback handleScreenShot;final VoidCallback handleProgressBarDragStart;final Future<void> Function(Duration duration) handleProgressBarSeek;final Future<void> Function(SuperResolutionMode mode)@@ -72,11 +73,11 @@ class PlayerItemPanel extends StatefulWidget {final FocusNode keyboardFocus;final PlayerPanelHold Function() acquirePlayerPanelHold;final ValueChanged<bool> onMenuVisibilityChanged;- final void Function() handleDanmaku;- final void Function(String direction) handlePreNextEpisode;- final void Function() skipOP;- final void Function() showVideoInfo;- final void Function() showSyncPlayPanel;+ final VoidCallback handleDanmaku;+ final VoidCallback onNextEpisode;+ final VoidCallback skipOP;+ final VoidCallback showVideoInfo;+ final VoidCallback showSyncPlayPanel;final VoidCallback pauseForTimedShutdown;final bool disableAnimations;@@ -85,48 +86,40 @@ class PlayerItemPanel extends StatefulWidget {}class _PlayerItemPanelState extends State<PlayerItemPanel> {- late Animation<Offset> topOffsetAnimation;- late Animation<Offset> bottomOffsetAnimation;- late Animation<Offset> leftOffsetAnimation;+ late final Animation<Offset> _topOffsetAnimation;+ late final Animation<Offset> _bottomOffsetAnimation;+ late final Animation<Offset> _rightOffsetAnimation;late final VideoPageController videoPageController =widget.videoPageController;late final PlayerController playerController;- final DownloadController downloadController = inject<DownloadController>();final TextEditingController textController = TextEditingController();final FocusNode textFieldFocus = FocusNode();- PlayerPanelHold? _danmakuTextFieldHold;- String? cachedSvgString;- Widget? cachedDanmakuOnIcon;- Widget? cachedDanmakuOffIcon;- Widget? cachedDanmakuSettingIcon;+ String? _cachedDanmakuColorHex;+ late Widget _cachedDanmakuOnIcon;+ late final Widget _cachedDanmakuOffIcon;+ late final Widget _cachedDanmakuSettingsIcon;++ bool get _desktop => switch (defaultTargetPlatform) {+ TargetPlatform.windows ||+ TargetPlatform.linux ||+ TargetPlatform.macOS =>+ true,+ _ => false,+ };static const double _danmakuIconSize = 24.0;static const double _loadingIndicatorStrokeWidth = 2.0;@overridevoid dispose() {- _releaseDanmakuTextFieldPanel();textController.dispose();textFieldFocus.dispose();super.dispose();}- void _holdDanmakuTextFieldPanel() {- if (_danmakuTextFieldHold?.isReleased == false) {- return;- }- _danmakuTextFieldHold = widget.acquirePlayerPanelHold();- }-- void _releaseDanmakuTextFieldPanel() {- _danmakuTextFieldHold?.release();- _danmakuTextFieldHold = null;- }-Future<void> _submitDanmakuText(String message) async {textFieldFocus.unfocus();- _releaseDanmakuTextFieldPanel();if (message.trim().isEmpty) {KazumiDialog.showToast(message: '弹幕内容为空');@@ -174,97 +167,93 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {textController.clear();}- Widget get danmakuTextField {+ Widget get _danmakuTextField {return Observer(builder: (context) {- return Container(- constraints: isDesktop()- ? const BoxConstraints(maxWidth: 500, maxHeight: 33)- : const BoxConstraints(maxHeight: 33),- padding: const EdgeInsets.symmetric(horizontal: 8),- child: TextField(- focusNode: textFieldFocus,- style:- TextStyle(fontSize: isDesktop() ? 15 : 13, color: Colors.white),- controller: textController,- textAlignVertical: TextAlignVertical.center,- decoration: InputDecoration(- enabled: playerController.danmaku.danmakuOn,- filled: true,- fillColor: Colors.white38,- floatingLabelBehavior: FloatingLabelBehavior.never,- hintText:- playerController.danmaku.danmakuOn ? '发个友善的弹幕见证当下' : '已关闭弹幕',- hintStyle: TextStyle(- fontSize: isDesktop() ? 15 : 13, color: Colors.white60),- alignLabelWithHint: true,- contentPadding: EdgeInsets.symmetric(- vertical: 8, horizontal: isDesktop() ? 8 : 12),- border: OutlineInputBorder(- borderSide: BorderSide.none,- borderRadius:- BorderRadius.all(Radius.circular(isDesktop() ? 8 : 20)),- ),- suffixIconConstraints: const BoxConstraints(minWidth: 0),- suffixIcon: Row(- mainAxisSize: MainAxisSize.min,- children: [- TextButton(- onPressed: () {- unawaited(_submitDanmakuText(textController.text));- },- style: TextButton.styleFrom(- foregroundColor: playerController.danmaku.danmakuOn- ? Theme.of(context).colorScheme.onPrimaryContainer- : Colors.white60,- backgroundColor: playerController.danmaku.danmakuOn- ? Theme.of(context).colorScheme.primaryContainer- : Theme.of(context).disabledColor,- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(isDesktop() ? 8 : 20),+ return PlayerPanelHoldFocusRegion(+ acquirePlayerPanelHold: widget.acquirePlayerPanelHold,+ child: Container(+ constraints: _desktop+ ? const BoxConstraints(maxWidth: 500, maxHeight: 33)+ : const BoxConstraints(maxHeight: 33),+ padding: const EdgeInsets.symmetric(horizontal: 8),+ child: TextField(+ focusNode: textFieldFocus,+ style:+ TextStyle(fontSize: _desktop ? 15 : 13, color: Colors.white),+ controller: textController,+ textAlignVertical: TextAlignVertical.center,+ decoration: InputDecoration(+ enabled: playerController.danmaku.danmakuOn,+ filled: true,+ fillColor: Colors.white38,+ floatingLabelBehavior: FloatingLabelBehavior.never,+ hintText: playerController.danmaku.danmakuOn+ ? '发个友善的弹幕见证当下'+ : '已关闭弹幕',+ hintStyle: TextStyle(+ fontSize: _desktop ? 15 : 13, color: Colors.white60),+ alignLabelWithHint: true,+ contentPadding: EdgeInsets.symmetric(+ vertical: 8, horizontal: _desktop ? 8 : 12),+ border: OutlineInputBorder(+ borderSide: BorderSide.none,+ borderRadius:+ BorderRadius.all(Radius.circular(_desktop ? 8 : 20)),+ ),+ suffixIconConstraints: const BoxConstraints(minWidth: 0),+ suffixIcon: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ TextButton(+ onPressed: () {+ unawaited(_submitDanmakuText(textController.text));+ },+ style: TextButton.styleFrom(+ foregroundColor: playerController.danmaku.danmakuOn+ ? Theme.of(context).colorScheme.onPrimaryContainer+ : Colors.white60,+ backgroundColor: playerController.danmaku.danmakuOn+ ? Theme.of(context).colorScheme.primaryContainer+ : Theme.of(context).disabledColor,+ shape: RoundedRectangleBorder(+ borderRadius:+ BorderRadius.circular(_desktop ? 8 : 20),+ ),+ ),+ child: const Text('发送'),),- ),- child: const Text('发送'),+ ],),- ],+ ),+ onSubmitted: (msg) {+ unawaited(_submitDanmakuText(msg));+ },+ onTapOutside: (_) {+ textFieldFocus.unfocus();+ widget.keyboardFocus.requestFocus();+ },),- ),- onTapAlwaysCalled: true,- onTap: () {- _holdDanmakuTextFieldPanel();- },- onSubmitted: (msg) {- unawaited(_submitDanmakuText(msg));- },- onTapOutside: (_) {- _releaseDanmakuTextFieldPanel();- textFieldFocus.unfocus();- widget.keyboardFocus.requestFocus();- },- ),- );+ ));});}- void showForwardChange() {+ void _showForwardChange() {KazumiDialog.show(builder: (context) {- String input = "";+ var input = '';return AlertDialog(title: const Text('跳过秒数'),- content: StatefulBuilder(- builder: (BuildContext context, StateSetter setState) {- return TextField(- inputFormatters: [- FilteringTextInputFormatter.digitsOnly,- ],- decoration: InputDecoration(- floatingLabelBehavior: FloatingLabelBehavior.never,- labelText: playerController.playback.buttonSkipTime.toString(),- ),- onChanged: (value) {- input = value;- },- );- }),+ content: TextField(+ inputFormatters: [+ FilteringTextInputFormatter.digitsOnly,+ ],+ decoration: InputDecoration(+ floatingLabelBehavior: FloatingLabelBehavior.never,+ labelText: playerController.playback.buttonSkipTime.toString(),+ ),+ onChanged: (value) {+ input = value;+ },+ ),actions: <Widget>[TextButton(onPressed: () => KazumiDialog.dismiss(),@@ -274,13 +263,11 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {),),TextButton(- onPressed: () async {- if (input != "") {+ onPressed: () {+ if (input.isNotEmpty) {playerController.setButtonForwardTime(int.parse(input));- KazumiDialog.dismiss();- } else {- KazumiDialog.dismiss();}+ KazumiDialog.dismiss();},child: const Text('确定'),),@@ -293,39 +280,28 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {void initState() {super.initState();playerController = widget.playerController;- topOffsetAnimation = Tween<Offset>(- begin: const Offset(0.0, -1.0),- end: const Offset(0.0, 0.0),- ).animate(CurvedAnimation(- parent: widget.panelVisibilityController,- curve: Curves.easeInOut,+ final visibility = widget.panelVisibilityController+ .drive(CurveTween(curve: Curves.easeInOut));+ _topOffsetAnimation = visibility.drive(Tween<Offset>(+ begin: const Offset(0, -1),+ end: Offset.zero,));- bottomOffsetAnimation = Tween<Offset>(- begin: const Offset(0.0, 1.0),- end: const Offset(0.0, 0.0),- ).animate(CurvedAnimation(- parent: widget.panelVisibilityController,- curve: Curves.easeInOut,+ _bottomOffsetAnimation = visibility.drive(Tween<Offset>(+ begin: const Offset(0, 1),+ end: Offset.zero,));- leftOffsetAnimation = Tween<Offset>(- begin: const Offset(1.0, 0.0),- end: const Offset(0.0, 0.0),- ).animate(CurvedAnimation(- parent: widget.panelVisibilityController,- curve: Curves.easeInOut,+ _rightOffsetAnimation = visibility.drive(Tween<Offset>(+ begin: const Offset(1, 0),+ end: Offset.zero,));- cacheSvgIcons();- }-- void cacheSvgIcons() {- cachedDanmakuOffIcon = RepaintBoundary(+ _cachedDanmakuOffIcon = RepaintBoundary(child: SvgPicture.asset('assets/images/danmaku_off.svg',height: _danmakuIconSize,),);- cachedDanmakuSettingIcon = RepaintBoundary(+ _cachedDanmakuSettingsIcon = RepaintBoundary(child: SvgPicture.asset('assets/images/danmaku_setting.svg',height: _danmakuIconSize,@@ -333,7 +309,7 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {);}- Widget danmakuOnIcon(BuildContext context) {+ Widget _danmakuOnIcon(BuildContext context) {final colorHex = Theme.of(context).colorScheme.primary@@ -341,10 +317,10 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {.toRadixString(16).substring(2);- if (cachedSvgString != colorHex) {- cachedSvgString = colorHex;+ if (_cachedDanmakuColorHex != colorHex) {+ _cachedDanmakuColorHex = colorHex;final svgString = danmakuOnSvg.replaceFirst('00AEEC', colorHex);- cachedDanmakuOnIcon = RepaintBoundary(+ _cachedDanmakuOnIcon = RepaintBoundary(child: SvgPicture.string(svgString,height: _danmakuIconSize,@@ -352,7 +328,7 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {);}- return cachedDanmakuOnIcon!;+ return _cachedDanmakuOnIcon;}Widget _buildDanmakuToggleButton(BuildContext context) {@@ -369,128 +345,60 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {strokeWidth: _loadingIndicatorStrokeWidth,),)- : (danmakuOn ? danmakuOnIcon(context) : cachedDanmakuOffIcon!),- onPressed: danmakuLoading- ? null- : () {- widget.handleDanmaku();- },+ : (danmakuOn ? _danmakuOnIcon(context) : _cachedDanmakuOffIcon),+ onPressed: danmakuLoading ? null : widget.handleDanmaku,tooltip: danmakuLoading ? '弹幕加载中...' : (danmakuOn ? '关闭弹幕' : '打开弹幕'),);});}- Widget forwardIcon() {+ Widget _forwardButton() {return Tooltip(message: '快进${playerController.playback.buttonSkipTime}秒,长按修改时间',child: GestureDetector(- onLongPress: () => showForwardChange(),+ onLongPress: _showForwardChange,child: IconButton(icon: Image.asset('assets/images/forward_80.png',color: Colors.white,height: 24,),- onPressed: () {- widget.skipOP();- },+ onPressed: widget.skipOP,),),);}@override- Widget build(BuildContext context) {+ Widget build(BuildContext context) => LayoutBuilder(+ builder: (context, constraints) => _buildPanel(+ constraints.maxWidth < MediaQuery.textScalerOf(context).scale(600),+ ),+ );++ Widget _buildPanel(bool compact) {return Stack(alignment: Alignment.center,children: [- AnimatedPositioned(- duration: const Duration(seconds: 1),+ Positioned(top: 0,left: 0,right: 0,- child: Observer(builder: (context) {- return Visibility(- visible: !playerController.panel.lockPanel &&- (widget.disableAnimations- ? playerController.panel.showVideoController- : true),- child: widget.disableAnimations- ? Container(- height: 50,- decoration: const BoxDecoration(- gradient: LinearGradient(- begin: Alignment.topCenter,- end: Alignment.bottomCenter,- colors: [- Colors.black45,- Colors.transparent,- ],- ),- ),- )- : SlideTransition(- position: topOffsetAnimation,- child: Container(- height: 50,- decoration: const BoxDecoration(- gradient: LinearGradient(- begin: Alignment.topCenter,- end: Alignment.bottomCenter,- colors: [- Colors.black45,- Colors.transparent,- ],- ),- ),- ),- ),- );- }),+ child: _buildScrim(+ height: 50,+ colors: const [Colors.black45, Colors.transparent],+ offset: _topOffsetAnimation,+ ),),- AnimatedPositioned(- duration: const Duration(seconds: 1),+ Positioned(bottom: 0,left: 0,right: 0,- child: Observer(builder: (context) {- return Visibility(- visible: !playerController.panel.lockPanel &&- (widget.disableAnimations- ? playerController.panel.showVideoController- : true),- child: widget.disableAnimations- ? Container(- height: 100,- decoration: const BoxDecoration(- gradient: LinearGradient(- begin: Alignment.topCenter,- end: Alignment.bottomCenter,- colors: [- Colors.transparent,- Colors.black45,- ],- ),- ),- )- : SlideTransition(- position: bottomOffsetAnimation,- child: Container(- height: 100,- decoration: const BoxDecoration(- gradient: LinearGradient(- begin: Alignment.topCenter,- end: Alignment.bottomCenter,- colors: [- Colors.transparent,- Colors.black45,- ],- ),- ),- ),- ),- );- }),+ child: _buildScrim(+ height: 100,+ colors: const [Colors.transparent, Colors.black45],+ offset: _bottomOffsetAnimation,+ ),),Positioned(top: 25,@@ -539,25 +447,27 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {);}),),- (isDesktop() || !videoPageController.isFullscreen)- ? Container()- : Positioned(- right: 0,- top: 0,- bottom: 0,- child: Observer(builder: (context) {- return Visibility(- visible: widget.disableAnimations- ? playerController.panel.showVideoController- : true,- child: widget.disableAnimations- ? leftControlWidget- : SlideTransition(- position: leftOffsetAnimation,- child: leftControlWidget),- );- }),- ),+ 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(top: 0,left: 0,@@ -569,9 +479,10 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {? playerController.panel.showVideoController: true),child: widget.disableAnimations- ? topControlWidget+ ? _buildTopControls(compact): SlideTransition(- position: topOffsetAnimation, child: topControlWidget),+ position: _topOffsetAnimation,+ child: _buildTopControls(compact)),);}),),@@ -586,10 +497,10 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {? playerController.panel.showVideoController: true),child: widget.disableAnimations- ? bottomControlWidget+ ? _buildBottomControls(compact): SlideTransition(- position: bottomOffsetAnimation,- child: bottomControlWidget),+ position: _bottomOffsetAnimation,+ child: _buildBottomControls(compact)),);}),),@@ -597,353 +508,269 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {);}- Widget get bottomControlWidget {- return SafeArea(- top: false,- bottom: videoPageController.isFullscreen,- left: videoPageController.isFullscreen,- right: videoPageController.isFullscreen,- child: PlayerPanelHoldMouseRegion(+ Widget _buildScrim({+ required double height,+ required List<Color> colors,+ required Animation<Offset> offset,+ }) =>+ Observer(builder: (context) {+ final scrim = Container(+ height: height,+ decoration: BoxDecoration(+ gradient: LinearGradient(+ begin: Alignment.topCenter,+ end: Alignment.bottomCenter,+ colors: colors,+ ),+ ),+ );+ return Visibility(+ visible: !playerController.panel.lockPanel &&+ (!widget.disableAnimations ||+ playerController.panel.showVideoController),+ child: widget.disableAnimations+ ? scrim+ : SlideTransition(position: offset, child: scrim),+ );+ });++ void _showDanmakuSettings() {+ showDanmakuSettingsSheet(+ context: context,+ danmakuController: playerController.danmaku.canvasController,+ onUpdateDanmakuSpeed: playerController.updateDanmakuSpeed,+ onTimelineOffsetChanged:+ playerController.danmaku.clearAndInvalidateScheduledDanmakus,+ );+ }++ List<Widget> _choiceItems<T>(+ Iterable<T> values, {+ required String Function(T) label,+ required bool Function(T) selected,+ required void Function(T) onSelected,+ }) =>+ [+ for (final value in values)+ MenuItemButton(+ onPressed: () => onSelected(value),+ child: _menuLabel(label(value), selected: selected(value)),+ ),+ ];++ List<Widget> get _aspectRatioItems => _choiceItems(+ PlayerAspectRatio.values,+ label: (value) => value.label,+ selected: (value) => value == playerController.panel.aspectRatioMode,+ onSelected: (value) => playerController.panel.aspectRatioMode = value,+ );++ List<Widget> get _speedItems => _choiceItems(+ defaultPlaySpeedList,+ label: (value) => '${value}x',+ selected: (value) => value == playerController.playback.playerSpeed,+ onSelected: widget.setPlaybackSpeed,+ );++ List<Widget> get _superResolutionItems => _choiceItems(+ SuperResolutionMode.values,+ label: (value) => value.label,+ selected: (value) =>+ value == playerController.playback.superResolutionMode,+ onSelected: widget.handleSuperResolutionChange,+ );++ Widget _menuButton(+ {required Widget child,+ required List<Widget> items,+ String? tooltip}) =>+ PlayerPanelHoldMenuAnchor(acquirePlayerPanelHold: widget.acquirePlayerPanelHold,- cursor: (videoPageController.isFullscreen &&- !playerController.panel.showVideoController)- ? SystemMouseCursors.none- : SystemMouseCursors.basic,- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- // Keep playback ticks inside the progress and time observers.- if (!isDesktop() && !isTablet())- Container(- padding: const EdgeInsets.only(left: 10.0, bottom: 10),- child: Observer(builder: (context) {- return Text(- "${durationToString(playerController.playback.currentPosition)} / ${durationToString(playerController.playback.duration)}",- style: const TextStyle(- color: Colors.white,- fontSize: 12.0,- fontFeatures: [- FontFeature.tabularFigures(),- ],- ),- );- }),+ onVisibilityChanged: widget.onMenuVisibilityChanged,+ consumeOutsideTap: true,+ builder: (context, controller, menuChild) {+ void toggle() =>+ controller.isOpen ? controller.close() : controller.open();+ return tooltip == null+ ? TextButton(onPressed: toggle, child: child)+ : IconButton(onPressed: toggle, icon: child, tooltip: tooltip);+ },+ menuChildren: items,+ );++ Widget get _danmakuSettingsButton => IconButton(+ onPressed: _showDanmakuSettings,+ color: Colors.white,+ icon: _cachedDanmakuSettingsIcon,+ tooltip: '弹幕设置',+ );++ Widget get _desktopDanmakuControls => LayoutBuilder(+ builder: (context, constraints) => Center(+ child: Row(+ mainAxisAlignment: MainAxisAlignment.center,+ children: [+ _buildDanmakuToggleButton(context),+ _danmakuSettingsButton,+ if (constraints.maxWidth > 600) _danmakuTextField,+ ],+ ),+ ),+ );++ Widget get _syncPlayMenuItem => MenuItemButton(+ onPressed: widget.showSyncPlayPanel,+ child: _menuLabel('一起看'),+ );++ Widget get _danmakuSettingsMenuItem => MenuItemButton(+ onPressed: _showDanmakuSettings,+ child: _menuLabel('弹幕设置'),+ );++ Widget _menuLabel(String label, {bool selected = false}) => Container(+ height: 48,+ constraints: const BoxConstraints(minWidth: 112),+ alignment: Alignment.centerLeft,+ child: Text(label,+ style: selected+ ? TextStyle(color: Theme.of(context).colorScheme.primary)+ : null),+ );++ Widget get _wideControls => Row(children: [+ if (_desktop) Expanded(child: _desktopDanmakuControls),+ if (!_desktop) ...[+ IconButton(+ color: Colors.white,+ icon: playerController.danmaku.danmakuOn+ ? _danmakuOnIcon(context)+ : _cachedDanmakuOffIcon,+ onPressed: widget.handleDanmaku,+ tooltip: playerController.danmaku.danmakuOn ? '关闭弹幕' : '打开弹幕',+ ),+ if (playerController.danmaku.danmakuOn) ...[+ _danmakuSettingsButton,+ Expanded(child: _danmakuTextField),+ ] else+ const Spacer(),+ ],+ _menuButton(+ child: const Text('超分辨率', style: TextStyle(color: Colors.white)),+ items: _superResolutionItems,+ ),+ _menuButton(+ child: Text(+ playerController.playback.playerSpeed == 1+ ? '倍速'+ : '${playerController.playback.playerSpeed}x',+ style: const TextStyle(color: Colors.white)),+ items: _speedItems,+ ),+ _menuButton(+ child: const Icon(Icons.aspect_ratio_rounded, color: Colors.white),+ tooltip: '视频比例',+ items: _aspectRatioItems,+ ),+ if (widget.onToggleSidePanel != null)+ IconButton(+ color: Colors.white,+ icon: const Icon(Icons.menu_open_rounded),+ tooltip: '选集面板',+ onPressed: widget.onToggleSidePanel,+ ),+ ]);++ Widget _buildBottomControls(bool compact) => SafeArea(+ top: false,+ bottom: !compact && widget.fillsWindow,+ left: !compact && widget.fillsWindow,+ right: !compact && widget.fillsWindow,+ child: PlayerPanelHoldMouseRegion(+ acquirePlayerPanelHold: widget.acquirePlayerPanelHold,+ cursor: (videoPageController.isFullscreen &&+ !playerController.panel.showVideoController)+ ? SystemMouseCursors.none+ : SystemMouseCursors.basic,+ child: PlayerTransportBar(+ compact: compact,+ timePlacement: PlayerTimeLabelPlacement.forViewport(+ MediaQuery.sizeOf(context),+ desktop: _desktop,+ ),+ playPause: IconButton(+ tooltip: playerController.playback.playing ? '暂停' : '播放',+ onPressed: () => playerController.playOrPause(),+ icon: PlayPauseIcon(+ iconColor: Colors.white,+ playing: playerController.playback.playing,),- Padding(- padding: const EdgeInsets.symmetric(horizontal: 10),- child: Observer(builder: (context) {- return ProgressBar(- thumbRadius: 8,- thumbGlowRadius: 18,- timeLabelLocation: isTablet()- ? TimeLabelLocation.sides- : TimeLabelLocation.none,- timeLabelTextStyle: const TextStyle(- color: Colors.white,- fontSize: 12.0,- fontFeatures: [- FontFeature.tabularFigures(),- ],- ),- 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),- );- }),),- Padding(- padding: const EdgeInsets.symmetric(horizontal: 10),- child: Row(- children: [- IconButton(- tooltip: playerController.playback.playing ? '暂停' : '播放',- onPressed: () => playerController.playOrPause(),- icon: PlayPauseIcon(- iconColor: Colors.white,- playing: playerController.playback.playing,- ),- ),- if (videoPageController.isFullscreen ||- isTablet() ||- isDesktop())- IconButton(- color: Colors.white,- icon: const Icon(Icons.skip_next_rounded),- tooltip: '下一集',- onPressed: () => widget.handlePreNextEpisode('next'),- ),- if (isDesktop())- Container(- padding: const EdgeInsets.only(left: 10.0),- child: Observer(builder: (context) {- return Text(- "${durationToString(playerController.playback.currentPosition)} / ${durationToString(playerController.playback.duration)}",- style: const TextStyle(- color: Colors.white,- fontSize: 16.0,- fontFeatures: [- FontFeature.tabularFigures(),- ],- ),- );- }),- ),- if (isDesktop())- Expanded(- child: LayoutBuilder(- builder: (context, constraints) {- bool isSpaceEnough = constraints.maxWidth > 600;- return Center(- child: Row(- mainAxisAlignment: MainAxisAlignment.center,- children: [- _buildDanmakuToggleButton(context),- IconButton(- onPressed: () {- showDanmakuSettingsSheet(- context: context,- danmakuController: playerController- .danmaku.canvasController,- onUpdateDanmakuSpeed:- playerController.updateDanmakuSpeed,- onTimelineOffsetChanged: playerController- .danmaku- .clearAndInvalidateScheduledDanmakus,- );- },- color: Colors.white,- icon: cachedDanmakuSettingIcon!,- tooltip: '弹幕设置',- ),- if (isSpaceEnough) danmakuTextField,- ],- ),- );- },+ nextEpisode: IconButton(+ color: Colors.white,+ icon: const Icon(Icons.skip_next_rounded),+ tooltip: '下一集',+ 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()],),- ),- if (!isDesktop()) ...[- IconButton(- color: Colors.white,- icon: playerController.danmaku.danmakuOn- ? danmakuOnIcon(context)- : cachedDanmakuOffIcon!,- onPressed: () {- widget.handleDanmaku();- },- tooltip:- playerController.danmaku.danmakuOn ? '关闭弹幕' : '打开弹幕',- ),- if (playerController.danmaku.danmakuOn) ...[- IconButton(- onPressed: () {- showDanmakuSettingsSheet(- context: context,- danmakuController:- playerController.danmaku.canvasController,- onUpdateDanmakuSpeed:- playerController.updateDanmakuSpeed,- onTimelineOffsetChanged: playerController- .danmaku.clearAndInvalidateScheduledDanmakus,- );- },+ 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),+ )),+ timeLabel: Observer(+ builder: (context) => Text(+ '${compact ? ' ' : ''}${durationToString(playerController.playback.currentPosition)} / ${durationToString(playerController.playback.duration)}',+ style: TextStyle(color: Colors.white,- icon: cachedDanmakuSettingIcon!,- tooltip: '弹幕设置',+ fontSize: !compact && _desktop ? 16 : 12,+ fontFeatures: [FontFeature.tabularFigures()],),- Expanded(child: danmakuTextField),- ],- if (!playerController.danmaku.danmakuOn) const Spacer(),- ],- PlayerPanelHoldMenuAnchor(- acquirePlayerPanelHold: widget.acquirePlayerPanelHold,- onVisibilityChanged: widget.onMenuVisibilityChanged,- consumeOutsideTap: true,- builder: (BuildContext context, MenuController controller,- Widget? child) {- return TextButton(- onPressed: () {- if (controller.isOpen) {- controller.close();- } else {- controller.open();- }- },- child: const Text(- '超分辨率',- style: TextStyle(color: Colors.white),- ),- );- },- menuChildren: [- for (final mode in SuperResolutionMode.values)- MenuItemButton(- onPressed: () =>- widget.handleSuperResolutionChange(mode),- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text(- mode.label,- style: TextStyle(- color: playerController- .playback.superResolutionMode ==- mode- ? Theme.of(context).colorScheme.primary- : null,- ),- ),- ),- ),- ),- ],- ),- PlayerPanelHoldMenuAnchor(- acquirePlayerPanelHold: widget.acquirePlayerPanelHold,- onVisibilityChanged: widget.onMenuVisibilityChanged,- consumeOutsideTap: true,- builder: (BuildContext context, MenuController controller,- Widget? child) {- return TextButton(- onPressed: () {- if (controller.isOpen) {- controller.close();- } else {- controller.open();- }- },- child: Text(- playerController.playback.playerSpeed == 1.0- ? '倍速'- : '${playerController.playback.playerSpeed}x',- style: const TextStyle(color: Colors.white),- ),- );- },- menuChildren: [- for (final double i- in defaultPlaySpeedList) ...<MenuItemButton>[- MenuItemButton(- onPressed: () async {- await widget.setPlaybackSpeed(i);- },- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text(- '${i}x',- style: TextStyle(- color: i ==- playerController.playback.playerSpeed- ? Theme.of(context).colorScheme.primary- : null,- ),- ),- ),- ),- ),- ],- ],- ),- PlayerPanelHoldMenuAnchor(- acquirePlayerPanelHold: widget.acquirePlayerPanelHold,- onVisibilityChanged: widget.onMenuVisibilityChanged,- consumeOutsideTap: true,- builder: (BuildContext context, MenuController controller,- Widget? child) {- return IconButton(- onPressed: () {- if (controller.isOpen) {- controller.close();- } else {- controller.open();- }- },- icon: const Icon(- Icons.aspect_ratio_rounded,- color: Colors.white,- ),- tooltip: '视频比例',- );- },- menuChildren: [- for (final aspectRatioMode in PlayerAspectRatio.values)- MenuItemButton(- onPressed: () => playerController- .panel.aspectRatioMode = aspectRatioMode,- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text(- aspectRatioMode.label,- style: TextStyle(- color: aspectRatioMode ==- playerController.panel.aspectRatioMode- ? Theme.of(context).colorScheme.primary- : null,- ),- ),- ),- ),- ),- ],- ),- (!videoPageController.isFullscreen &&- !isTablet() &&- !isDesktop())- ? Container()- : IconButton(- color: Colors.white,- icon: const Icon(Icons.menu_open_rounded),- tooltip: '选集面板',- onPressed: () {- widget.toggleMenu();- },- ),- (isTablet() &&- videoPageController.isFullscreen &&- MediaQuery.of(context).size.height <- MediaQuery.of(context).size.width)- ? Container()- : IconButton(- color: Colors.white,- icon: Icon(videoPageController.isFullscreen- ? Icons.fullscreen_exit_rounded- : Icons.fullscreen_rounded),- tooltip:- videoPageController.isFullscreen ? '退出全屏' : '全屏',- onPressed: () {- widget.handleFullscreen();- },- ),- ],- ),- ),- if (isTablet() || isDesktop()) const SizedBox(height: 6),- ],+ )),+ controls: compact ? const SizedBox.shrink() : _wideControls,+ fullscreen: _buildFullscreenButton(compact),+ ),),- ),+ );++ Widget _buildFullscreenButton(bool compact) {+ if (videoPageController.isPip) {+ return compact ? const Text(' ') : const SizedBox.shrink();+ }+ if (!_desktop && widget.fillsWindow && !videoPageController.isFullscreen) {+ return const SizedBox.shrink();+ }+ return IconButton(+ color: Colors.white,+ icon: Icon(videoPageController.isFullscreen+ ? Icons.fullscreen_exit_rounded+ : Icons.fullscreen_rounded),+ tooltip: videoPageController.isFullscreen ? '退出全屏' : '全屏',+ onPressed: widget.handleFullscreen,);}- Widget get topControlWidget {+ Widget _buildTopControls(bool compact) {return EmbeddedNativeControlArea(- requireOffset: !videoPageController.isFullscreen,+ requireOffset: compact || !videoPageController.isFullscreen,child: SafeArea(top: false,bottom: false,- left: videoPageController.isFullscreen,- right: videoPageController.isFullscreen,+ left: !compact && widget.fillsWindow,+ right: !compact && widget.fillsWindow,child: PlayerPanelHoldMouseRegion(acquirePlayerPanelHold: widget.acquirePlayerPanelHold,cursor: (videoPageController.isFullscreen &&@@ -956,29 +783,32 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {color: Colors.white,icon: const Icon(Icons.arrow_back_rounded),tooltip: '返回',- onPressed: () {- widget.onBackPressed(context);- },+ onPressed: widget.onBackPressed,),Expanded(child: dtb.DragToMoveArea(- child: Text(- ' ${videoPageController.title} [${videoPageController.roadList[videoPageController.selectedEpisode.road].identifier[videoPageController.selectedEpisode.episode - 1]}]',- style: TextStyle(- color: Colors.white,- fontSize:- Theme.of(context).textTheme.titleMedium!.fontSize,- overflow: TextOverflow.ellipsis,- ),- ),+ child: compact+ ? const SizedBox(height: 40)+ : Text(+ ' ${videoPageController.title} [${videoPageController.roadList[videoPageController.selectedEpisode.road].identifier[videoPageController.selectedEpisode.episode - 1]}]',+ style: TextStyle(+ color: Colors.white,+ fontSize: Theme.of(context)+ .textTheme+ .titleMedium!+ .fontSize,+ overflow: TextOverflow.ellipsis,+ ),+ ),),),- forwardIcon(),- if ((isDesktop() && !videoPageController.isFullscreen) ||- Platform.isAndroid)+ _forwardButton(),+ if ((_desktop &&+ (compact || !videoPageController.isFullscreen)) ||+ (defaultTargetPlatform == TargetPlatform.android))IconButton(onPressed: () async {- if (isDesktop()) {+ if (_desktop) {if (videoPageController.isPip) {await PipUtils.exitDesktopPIPWindow();} else {@@ -998,6 +828,7 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {color: Colors.white,),),+ if (compact) _buildDanmakuToggleButton(context),PlayerPanelHoldCollectButton(acquirePlayerPanelHold: widget.acquirePlayerPanelHold,bangumiItem: videoPageController.bangumiItem,@@ -1024,35 +855,29 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {);},menuChildren: [+ if (compact) ...[+ SubmenuButton(+ menuChildren: _aspectRatioItems,+ child: _menuLabel('视频比例')),+ SubmenuButton(+ menuChildren: _speedItems, child: _menuLabel('倍速')),+ SubmenuButton(+ menuChildren: _superResolutionItems,+ child: _menuLabel('超分辨率')),+ _syncPlayMenuItem,+ ],MenuItemButton(- onPressed: () {- widget.showDanmakuSwitch();- },- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text("弹幕切换"),- ),- ),+ onPressed: widget.showDanmakuSwitch,+ child: _menuLabel('弹幕切换'),),+ if (compact) _danmakuSettingsMenuItem,MenuItemButton(- onPressed: () {- widget.showVideoInfo();- },- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text("视频详情"),- ),- ),+ onPressed: widget.showVideoInfo,+ child: _menuLabel('视频详情'),),MenuItemButton(onPressed: () {- bool needRestart = playerController.playback.playing;+ final needRestart = playerController.playback.playing;playerController.pause();RemotePlay().castVideo(playerController.videoUrl,@@ -1063,49 +888,18 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {}});},- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text("远程投屏"),- ),- ),+ child: _menuLabel('远程投屏'),),MenuItemButton(- onPressed: () {- playerController.launchExternalPlayer();- },- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text("外部播放"),- ),- ),+ onPressed: playerController.launchExternalPlayer,+ child: _menuLabel('外部播放'),),SubmenuButton(menuChildren: [MenuItemButton(- onPressed: () {- TimedShutdownService().cancel();- },- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text(- "不开启",- style: TextStyle(- color: !TimedShutdownService().isActive- ? Theme.of(context).colorScheme.primary- : null,- ),- ),- ),- ),+ onPressed: TimedShutdownService().cancel,+ child: _menuLabel('不开启',+ selected: !TimedShutdownService().isActive),),for (final int minutes in [15, 30, 60])MenuItemButton(@@ -1116,22 +910,9 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {message:'已设置 ${TimedShutdownService().formatMinutesToDisplay(minutes)} 后定时关闭');},- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text(- "$minutes 分钟",- style: TextStyle(- color: TimedShutdownService().setMinutes ==- minutes- ? Theme.of(context).colorScheme.primary- : null,- ),- ),- ),- ),+ child: _menuLabel('$minutes 分钟',+ selected:+ TimedShutdownService().setMinutes == minutes),),MenuItemButton(onPressed: () {@@ -1139,14 +920,7 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {onExpired: widget.pauseForTimedShutdown,);},- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text("自定义"),- ),- ),+ child: _menuLabel('自定义'),),],child: Container(@@ -1168,19 +942,7 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {),),),- MenuItemButton(- onPressed: () {- widget.showSyncPlayPanel();- },- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text("一起看"),- ),- ),- ),+ if (!compact) _syncPlayMenuItem,],),],@@ -1190,27 +952,24 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {);}- Widget get leftControlWidget {+ Widget get _rightControls {return SafeArea(top: false,bottom: false,- left: videoPageController.isFullscreen,- right: videoPageController.isFullscreen,+ left: widget.fillsWindow,+ right: widget.fillsWindow,child: Column(children: [const Spacer(),- (playerController.panel.lockPanel)- ? Container()- : IconButton(- icon: const Icon(- Icons.photo_camera_outlined,- color: Colors.white,- ),- tooltip: '截图',- onPressed: () {- widget.handleScreenShot();- },- ),+ if (!playerController.panel.lockPanel)+ IconButton(+ icon: const Icon(+ Icons.photo_camera_outlined,+ color: Colors.white,+ ),+ tooltip: '截图',+ onPressed: widget.handleScreenShot,+ ),IconButton(icon: Icon(playerController.panel.lockPaneldiff --git a/lib/pages/player/player_panel_hold.dart b/lib/pages/player/player_panel_hold.dartindex f65e97cc..fd571130 100644--- a/lib/pages/player/player_panel_hold.dart+++ b/lib/pages/player/player_panel_hold.dart@@ -24,8 +24,50 @@ class PlayerPanelHold {}}-/// Binds a hover/menu widget lifecycle to a panel hold so callers do not manage-/// counters or menu identities by hand.+/// Release focus holds when resizing removes the input but preserves its panel.+class PlayerPanelHoldFocusRegion extends StatefulWidget {+ const PlayerPanelHoldFocusRegion({+ super.key,+ required this.acquirePlayerPanelHold,+ required this.child,+ });++ final PlayerPanelHold Function() acquirePlayerPanelHold;+ final Widget child;++ @override+ State<PlayerPanelHoldFocusRegion> createState() =>+ _PlayerPanelHoldFocusRegionState();+}++class _PlayerPanelHoldFocusRegionState+ extends State<PlayerPanelHoldFocusRegion> {+ PlayerPanelHold? _hold;++ void _onFocusChange(bool focused) {+ if (focused) {+ _hold ??= widget.acquirePlayerPanelHold();+ } else {+ _hold?.release();+ _hold = null;+ }+ }++ @override+ void dispose() {+ _hold?.release();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) => Focus(+ canRequestFocus: false,+ onFocusChange: _onFocusChange,+ child: widget.child,+ );+}++/// Release hover holds when their controls unmount.class PlayerPanelHoldMouseRegion extends StatefulWidget {const PlayerPanelHoldMouseRegion({super.key,diff --git a/lib/pages/player/player_transport_bar.dart b/lib/pages/player/player_transport_bar.dartnew file mode 100644index 00000000..20d214f7--- /dev/null+++ b/lib/pages/player/player_transport_bar.dart@@ -0,0 +1,82 @@+import 'package:audio_video_progress_bar/audio_video_progress_bar.dart';+import 'package:flutter/material.dart';++enum PlayerTimeLabelPlacement {+ aboveProgress,+ besideProgress,+ afterPlaybackButtons;++ static PlayerTimeLabelPlacement forViewport(Size viewport,+ {required bool desktop}) {+ if (desktop) return afterPlaybackButtons;+ final hasRoomForSideLabels = viewport.shortestSide >= 600 &&+ viewport.shortestSide / viewport.longestSide >= 9 / 16;+ return hasRoomForSideLabels ? besideProgress : aboveProgress;+ }+}++class PlayerTransportBar extends StatelessWidget {+ const PlayerTransportBar({+ super.key,+ required this.compact,+ required this.playPause,+ required this.nextEpisode,+ required this.progressBuilder,+ required this.timeLabel,+ required this.timePlacement,+ required this.controls,+ required this.fullscreen,+ });++ final bool compact;+ final Widget playPause;+ final Widget nextEpisode;+ final Widget Function(TimeLabelLocation location) progressBuilder;+ final Widget timeLabel;+ final PlayerTimeLabelPlacement timePlacement;+ final Widget controls;+ final Widget fullscreen;++ @override+ Widget build(BuildContext context) => compact+ ? Row(children: [+ playPause,+ Expanded(child: progressBuilder(TimeLabelLocation.none)),+ timeLabel,+ fullscreen,+ ])+ : Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ mainAxisSize: MainAxisSize.min,+ children: [+ if (timePlacement == PlayerTimeLabelPlacement.aboveProgress)+ Padding(+ padding: const EdgeInsets.only(left: 10, bottom: 10),+ child: timeLabel,+ ),+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 10),+ child: progressBuilder(+ timePlacement == PlayerTimeLabelPlacement.besideProgress+ ? TimeLabelLocation.sides+ : TimeLabelLocation.none,+ ),+ ),+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 10),+ child: Row(children: [+ playPause,+ nextEpisode,+ if (timePlacement ==+ PlayerTimeLabelPlacement.afterPlaybackButtons)+ Padding(+ padding: const EdgeInsets.only(left: 10),+ child: timeLabel),+ Expanded(child: controls),+ fullscreen,+ ])),+ if (timePlacement != PlayerTimeLabelPlacement.aboveProgress)+ const SizedBox(height: 6),+ ],+ );+}diff --git a/lib/pages/player/smallest_player_item_panel.dart b/lib/pages/player/smallest_player_item_panel.dartdeleted file mode 100644index 49c21937..00000000--- a/lib/pages/player/smallest_player_item_panel.dart+++ /dev/null@@ -1,816 +0,0 @@-import 'dart:io';-import 'package:flutter/material.dart';-import 'package:flutter_mobx/flutter_mobx.dart';-import 'package:flutter_svg/flutter_svg.dart';-import 'package:kazumi/bean/widget/play_pause_icon.dart';-import 'package:kazumi/pages/player/player_adjustment_hud.dart';-import 'package:kazumi/pages/player/controller/player_aspect_ratio.dart';-import 'package:kazumi/pages/player/controller/player_super_resolution.dart';-import 'package:kazumi/pages/player/player_panel_hold.dart';-import 'package:kazumi/services/player/pip_utils.dart';-import 'package:kazumi/pages/video/video_controller.dart';-import 'package:kazumi/bean/dialog/dialog_helper.dart';-import 'package:kazumi/pages/player/player_controller.dart';-import 'package:flutter/services.dart';-import 'package:kazumi/services/player/remote.dart';-import 'package:kazumi/pages/settings/danmaku/danmaku_settings_sheet.dart';-import 'package:kazumi/utils/constants.dart';-import 'package:kazumi/bean/appbar/drag_to_move_bar.dart' as dtb;-import 'package:audio_video_progress_bar/audio_video_progress_bar.dart';-import 'package:kazumi/bean/widget/embedded_native_control_area.dart';-import 'package:kazumi/services/player/timed_shutdown_service.dart';-import 'package:kazumi/utils/device.dart';-import 'package:kazumi/utils/format.dart';--class SmallestPlayerItemPanel extends StatefulWidget {- const SmallestPlayerItemPanel({- super.key,- required this.playerController,- required this.videoPageController,- required this.onBackPressed,- required this.setPlaybackSpeed,- required this.showDanmakuSwitch,- required this.handleFullscreen,- required this.enterAndroidPictureInPicture,- required this.handleProgressBarDragStart,- required this.handleProgressBarSeek,- required this.handleSuperResolutionChange,- required this.panelVisibilityController,- required this.acquirePlayerPanelHold,- required this.onMenuVisibilityChanged,- required this.handleDanmaku,- required this.skipOP,- required this.showVideoInfo,- required this.showSyncPlayPanel,- required this.pauseForTimedShutdown,- this.disableAnimations = false,- });-- final PlayerController playerController;- final VideoPageController videoPageController;- final void Function(BuildContext) onBackPressed;- final Future<void> Function(double) setPlaybackSpeed;- final void Function() showDanmakuSwitch;- final void Function() handleDanmaku;- final void Function() skipOP;- final void Function() handleFullscreen;- final Future<void> Function() enterAndroidPictureInPicture;- final VoidCallback handleProgressBarDragStart;- final Future<void> Function(Duration duration) handleProgressBarSeek;- final Future<void> Function(SuperResolutionMode mode)- handleSuperResolutionChange;- final AnimationController panelVisibilityController;- final PlayerPanelHold Function() acquirePlayerPanelHold;- final ValueChanged<bool> onMenuVisibilityChanged;- final void Function() showVideoInfo;- final void Function() showSyncPlayPanel;- final VoidCallback pauseForTimedShutdown;- final bool disableAnimations;-- @override- State<SmallestPlayerItemPanel> createState() =>- _SmallestPlayerItemPanelState();-}--class _SmallestPlayerItemPanelState extends State<SmallestPlayerItemPanel> {- late Animation<Offset> topOffsetAnimation;- late Animation<Offset> bottomOffsetAnimation;- late final VideoPageController videoPageController =- widget.videoPageController;- late final PlayerController playerController;-- String? cachedSvgString;- Widget? cachedDanmakuOnIcon;- Widget? cachedDanmakuOffIcon;-- static const double _danmakuIconSize = 24.0;- static const double _loadingIndicatorStrokeWidth = 2.0;-- void showForwardChange() {- KazumiDialog.show(builder: (context) {- String input = "";- return AlertDialog(- title: const Text('跳过秒数'),- content: StatefulBuilder(- builder: (BuildContext context, StateSetter setState) {- return TextField(- inputFormatters: [- FilteringTextInputFormatter.digitsOnly,- ],- decoration: InputDecoration(- floatingLabelBehavior: FloatingLabelBehavior.never,- labelText: playerController.playback.buttonSkipTime.toString(),- ),- onChanged: (value) {- input = value;- },- );- }),- actions: <Widget>[- TextButton(- onPressed: () => KazumiDialog.dismiss(),- child: Text(- '取消',- style: TextStyle(color: Theme.of(context).colorScheme.outline),- ),- ),- TextButton(- onPressed: () async {- if (input != "") {- playerController.setButtonForwardTime(int.parse(input));- KazumiDialog.dismiss();- } else {- KazumiDialog.dismiss();- }- },- child: const Text('确定'),- ),- ],- );- });- }-- @override- void initState() {- super.initState();- playerController = widget.playerController;- topOffsetAnimation = Tween<Offset>(- begin: const Offset(0.0, -1.0),- end: const Offset(0.0, 0.0),- ).animate(CurvedAnimation(- parent: widget.panelVisibilityController,- curve: Curves.easeInOut,- ));- bottomOffsetAnimation = Tween<Offset>(- begin: const Offset(0.0, 1.0),- end: const Offset(0.0, 0.0),- ).animate(CurvedAnimation(- parent: widget.panelVisibilityController,- curve: Curves.easeInOut,- ));- cacheSvgIcons();- }-- void cacheSvgIcons() {- cachedDanmakuOffIcon = RepaintBoundary(- child: SvgPicture.asset(- 'assets/images/danmaku_off.svg',- height: _danmakuIconSize,- ),- );- }-- Widget danmakuOnIcon(BuildContext context) {- final colorHex = Theme.of(context)- .colorScheme- .primary- .toARGB32()- .toRadixString(16)- .substring(2);-- if (cachedSvgString != colorHex) {- cachedSvgString = colorHex;- final svgString = danmakuOnSvg.replaceFirst('00AEEC', colorHex);- cachedDanmakuOnIcon = RepaintBoundary(- child: SvgPicture.string(- svgString,- height: _danmakuIconSize,- ),- );- }-- return cachedDanmakuOnIcon!;- }-- Widget _buildDanmakuToggleButton(BuildContext context) {- return Observer(builder: (context) {- final danmakuLoading = playerController.danmaku.danmakuLoading;- final danmakuOn = playerController.danmaku.danmakuOn;- return IconButton(- color: Colors.white,- icon: danmakuLoading- ? SizedBox(- width: _danmakuIconSize,- height: _danmakuIconSize,- child: CircularProgressIndicator(- strokeWidth: _loadingIndicatorStrokeWidth,- ),- )- : (danmakuOn ? danmakuOnIcon(context) : cachedDanmakuOffIcon!),- onPressed: danmakuLoading- ? null- : () {- widget.handleDanmaku();- },- tooltip: danmakuLoading ? '弹幕加载中...' : (danmakuOn ? '关闭弹幕' : '打开弹幕'),- );- });- }-- Widget forwardIcon() {- return Tooltip(- message: '快进${playerController.playback.buttonSkipTime}秒,长按修改时间',- child: GestureDetector(- onLongPress: () => showForwardChange(),- child: IconButton(- icon: Image.asset(- 'assets/images/forward_80.png',- color: Colors.white,- height: 24,- ),- onPressed: () {- widget.skipOP();- },- ),- ),- );- }-- @override- Widget build(BuildContext context) {- return Stack(- alignment: Alignment.center,- children: [- AnimatedPositioned(- duration: const Duration(seconds: 1),- top: 0,- left: 0,- right: 0,- child: Observer(builder: (context) {- return Visibility(- visible: !playerController.panel.lockPanel &&- (widget.disableAnimations- ? playerController.panel.showVideoController- : true),- child: widget.disableAnimations- ? Container(- height: 50,- decoration: const BoxDecoration(- gradient: LinearGradient(- begin: Alignment.topCenter,- end: Alignment.bottomCenter,- colors: [- Colors.black45,- Colors.transparent,- ],- ),- ),- )- : SlideTransition(- position: topOffsetAnimation,- child: Container(- height: 50,- decoration: const BoxDecoration(- gradient: LinearGradient(- begin: Alignment.topCenter,- end: Alignment.bottomCenter,- colors: [- Colors.black45,- Colors.transparent,- ],- ),- ),- ),- ),- );- }),- ),- AnimatedPositioned(- duration: const Duration(seconds: 1),- bottom: 0,- left: 0,- right: 0,- child: Observer(builder: (context) {- return Visibility(- visible: !playerController.panel.lockPanel &&- (widget.disableAnimations- ? playerController.panel.showVideoController- : true),- child: widget.disableAnimations- ? Container(- height: 100,- decoration: const BoxDecoration(- gradient: LinearGradient(- begin: Alignment.topCenter,- end: Alignment.bottomCenter,- colors: [- Colors.transparent,- Colors.black45,- ],- ),- ),- )- : SlideTransition(- position: bottomOffsetAnimation,- child: Container(- height: 100,- decoration: const BoxDecoration(- gradient: LinearGradient(- begin: Alignment.topCenter,- end: Alignment.bottomCenter,- colors: [- Colors.transparent,- Colors.black45,- ],- ),- ),- ),- ),- );- }),- ),- Positioned(- top: 25,- child: Observer(builder: (context) {- // PlayerSeekHud latches values only while visible, so skipping the- // position reads when hidden keeps the 1s tick from rebuilding this.- final visible = playerController.panel.showSeekTime;- return PlayerSeekHud(- visible: visible,- currentPosition: visible- ? playerController.playback.currentPosition- : Duration.zero,- playerPosition: visible- ? playerController.playback.playerPosition- : Duration.zero,- duration:- visible ? playerController.playback.duration : Duration.zero,- direction: playerController.panel.seekDirection,- disableAnimations: widget.disableAnimations,- );- }),- ),- Positioned(- top: 25,- child: Observer(builder: (context) {- return PlayerSpeedHud(- visible: playerController.panel.showPlaySpeed,- speed: playerController.playback.playerSpeed,- disableAnimations: widget.disableAnimations,- );- }),- ),- Positioned(- top: 25,- child: Observer(builder: (context) {- final showVolume = playerController.panel.showVolume;- final showBrightness = playerController.panel.showBrightness;- return PlayerAdjustmentHud(- visible: showVolume || showBrightness,- type: showVolume- ? PlayerAdjustmentHudType.volume- : PlayerAdjustmentHudType.brightness,- value: showVolume- ? playerController.playback.volume- : playerController.panel.brightness,- disableAnimations: widget.disableAnimations,- );- }),- ),- Positioned(- top: 0,- left: 0,- right: 0,- child: Observer(builder: (context) {- return Visibility(- visible: !playerController.panel.lockPanel &&- (widget.disableAnimations- ? playerController.panel.showVideoController- : true),- child: widget.disableAnimations- ? topControlWidget- : SlideTransition(- position: topOffsetAnimation, child: topControlWidget),- );- }),- ),- Positioned(- bottom: 0,- left: 0,- right: 0,- child: Observer(builder: (context) {- return Visibility(- visible: !playerController.panel.lockPanel &&- (widget.disableAnimations- ? playerController.panel.showVideoController- : true),- child: widget.disableAnimations- ? bottomControlWidget- : SlideTransition(- position: bottomOffsetAnimation,- child: bottomControlWidget),- );- }),- ),- ],- );- }-- Widget get bottomControlWidget {- return Row(- children: [- IconButton(- icon: PlayPauseIcon(- iconColor: Colors.white,- playing: playerController.playback.playing,- ),- tooltip: playerController.playback.playing ? '暂停' : '播放',- onPressed: () {- playerController.playOrPause();- },- ),- // Position reads stay inside these narrow Observers so the 1s progress- // tick rebuilds only the bar and time text, not the whole bottom bar.- Expanded(- child: Observer(builder: (context) {- return ProgressBar(- thumbRadius: 8,- thumbGlowRadius: 18,- timeLabelLocation: TimeLabelLocation.none,- 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),- );- }),- ),- Observer(builder: (context) {- return Text(- " ${durationToString(playerController.playback.currentPosition)} / ${durationToString(playerController.playback.duration)}",- style: const TextStyle(- color: Colors.white,- fontSize: 12.0,- fontFeatures: [- FontFeature.tabularFigures(),- ],- ),- );- }),- (!videoPageController.isPip)- ? IconButton(- color: Colors.white,- icon: Icon(videoPageController.isFullscreen- ? Icons.fullscreen_exit_rounded- : Icons.fullscreen_rounded),- tooltip: videoPageController.isFullscreen ? '退出全屏' : '全屏',- onPressed: () {- widget.handleFullscreen();- },- )- : const Text(' '),- ],- );- }-- Widget get topControlWidget {- return EmbeddedNativeControlArea(- child: Row(- children: [- IconButton(- color: Colors.white,- icon: const Icon(Icons.arrow_back_rounded),- tooltip: '返回',- onPressed: () {- widget.onBackPressed(context);- },- ),- const Expanded(- child: dtb.DragToMoveArea(child: SizedBox(height: 40)),- ),- forwardIcon(),- if (isDesktop() || Platform.isAndroid)- IconButton(- onPressed: () async {- if (isDesktop()) {- if (videoPageController.isPip) {- await PipUtils.exitDesktopPIPWindow();- } else {- // Size the PiP window to the video aspect ratio to- // avoid letterboxing.- await PipUtils.enterDesktopPIPWindow(- width: playerController.debug.playerWidth,- height: playerController.debug.playerHeight,- );- }- videoPageController.isPip = !videoPageController.isPip;- return;- }- await widget.enterAndroidPictureInPicture();- },- tooltip: '画中画',- icon:- const Icon(Icons.picture_in_picture, color: Colors.white)),- _buildDanmakuToggleButton(context),- PlayerPanelHoldCollectButton(- acquirePlayerPanelHold: widget.acquirePlayerPanelHold,- bangumiItem: videoPageController.bangumiItem,- ),- PlayerPanelHoldMenuAnchor(- acquirePlayerPanelHold: widget.acquirePlayerPanelHold,- onVisibilityChanged: widget.onMenuVisibilityChanged,- consumeOutsideTap: true,- builder: (BuildContext context, MenuController controller,- Widget? child) {- return IconButton(- onPressed: () {- if (controller.isOpen) {- controller.close();- } else {- controller.open();- }- },- tooltip: '更多选项',- icon: const Icon(- Icons.more_vert,- color: Colors.white,- ),- );- },- menuChildren: [- SubmenuButton(- menuChildren: [- for (final aspectRatioMode in PlayerAspectRatio.values)- MenuItemButton(- onPressed: () => playerController.panel.aspectRatioMode =- aspectRatioMode,- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text(- aspectRatioMode.label,- style: TextStyle(- color: aspectRatioMode ==- playerController.panel.aspectRatioMode- ? Theme.of(context).colorScheme.primary- : null),- ),- ),- ),- ),- ],- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text("视频比例"),- ),- ),- ),- SubmenuButton(- menuChildren: [- for (final double i- in defaultPlaySpeedList) ...<MenuItemButton>[- MenuItemButton(- onPressed: () async {- await widget.setPlaybackSpeed(i);- },- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text(- '${i}x',- style: TextStyle(- color:- i == playerController.playback.playerSpeed- ? Theme.of(context).colorScheme.primary- : null),- ),- ),- ),- ),- ],- ],- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text("倍速"),- ),- ),- ),- SubmenuButton(- menuChildren: [- for (final mode in SuperResolutionMode.values)- MenuItemButton(- onPressed: () => widget.handleSuperResolutionChange(mode),- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text(- mode.label,- style: TextStyle(- color: playerController- .playback.superResolutionMode ==- mode- ? Theme.of(context).colorScheme.primary- : null,- ),- ),- ),- ),- ),- ],- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text("超分辨率"),- ),- ),- ),- MenuItemButton(- onPressed: () {- widget.showSyncPlayPanel();- },- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text("一起看"),- ),- ),- ),- MenuItemButton(- onPressed: () {- widget.showDanmakuSwitch();- },- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text("弹幕切换"),- ),- ),- ),- MenuItemButton(- onPressed: () {- showDanmakuSettingsSheet(- context: context,- danmakuController:- playerController.danmaku.canvasController,- onUpdateDanmakuSpeed: playerController.updateDanmakuSpeed,- onTimelineOffsetChanged: playerController- .danmaku.clearAndInvalidateScheduledDanmakus,- );- },- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text("弹幕设置"),- ),- ),- ),- MenuItemButton(- onPressed: () {- widget.showVideoInfo();- },- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text("视频详情"),- ),- ),- ),- MenuItemButton(- onPressed: () {- bool needRestart = playerController.playback.playing;- playerController.pause();- RemotePlay()- .castVideo(playerController.videoUrl,- videoPageController.currentPlugin.referer)- .whenComplete(() {- if (mounted && needRestart) {- playerController.play();- }- });- },- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text("远程投屏"),- ),- ),- ),- MenuItemButton(- onPressed: () {- playerController.launchExternalPlayer();- },- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text("外部播放"),- ),- ),- ),- SubmenuButton(- menuChildren: [- MenuItemButton(- onPressed: () {- TimedShutdownService().cancel();- },- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text(- "不开启",- style: TextStyle(- color: !TimedShutdownService().isActive- ? Theme.of(context).colorScheme.primary- : null,- ),- ),- ),- ),- ),- for (final int minutes in [15, 30, 60])- MenuItemButton(- onPressed: () {- TimedShutdownService().start(minutes,- onExpired: widget.pauseForTimedShutdown);- KazumiDialog.showToast(- message:- '已设置 ${TimedShutdownService().formatMinutesToDisplay(minutes)} 后定时关闭');- },- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text(- "$minutes 分钟",- style: TextStyle(- color:- TimedShutdownService().setMinutes == minutes- ? Theme.of(context).colorScheme.primary- : null,- ),- ),- ),- ),- ),- MenuItemButton(- onPressed: () {- TimedShutdownService.showCustomTimerDialog(- onExpired: widget.pauseForTimedShutdown,- );- },- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: Text("自定义"),- ),- ),- ),- ],- child: Container(- height: 48,- constraints: BoxConstraints(minWidth: 112),- child: Align(- alignment: Alignment.centerLeft,- child: ValueListenableBuilder<int>(- valueListenable:- TimedShutdownService().remainingSecondsNotifier,- builder: (context, remainingSeconds, child) {- return Text(- remainingSeconds > 0- ? "定时关闭 (${TimedShutdownService().formatRemainingTime()})"- : "定时关闭",- );- },- ),- ),- ),- ),- ],- ),- ],- ),- );- }-}diff --git a/lib/pages/settings/danmaku/danmaku_settings.dart b/lib/pages/settings/danmaku/danmaku_settings.dartindex 4bd222e1..968ae312 100644--- a/lib/pages/settings/danmaku/danmaku_settings.dart+++ b/lib/pages/settings/danmaku/danmaku_settings.dart@@ -4,7 +4,6 @@ import 'package:kazumi/services/storage/storage.dart';import 'package:kazumi/bean/dialog/dialog_helper.dart';import 'package:kazumi/bean/settings/settings_detail_scaffold.dart';import 'package:kazumi/bean/settings/settings_list.dart';-import 'package:kazumi/utils/device.dart';class DanmakuSettingsPage extends StatefulWidget {const DanmakuSettingsPage({super.key});@@ -14,7 +13,6 @@ class DanmakuSettingsPage extends StatefulWidget {}class _DanmakuSettingsPageState extends State<DanmakuSettingsPage> {- late final bool compactLayout;late double defaultDanmakuArea;late double defaultDanmakuOpacity;late double defaultDanmakuFontSize;@@ -35,14 +33,15 @@ class _DanmakuSettingsPageState extends State<DanmakuSettingsPage> {late bool danmakuFollowSpeed;@override- void initState() {- super.initState();- compactLayout = isCompact();+ void didChangeDependencies() {+ super.didChangeDependencies();_loadSettingsFromStorage();}void _loadSettingsFromStorage() {- final settingContext = SettingContext(compactLayout: compactLayout);+ final settingContext = SettingContext(+ compactLayout: MediaQuery.sizeOf(context).shortestSide < 600,+ );defaultDanmakuArea = GStorage.getSetting(SettingsKeys.danmakuArea);defaultDanmakuOpacity = GStorage.getSetting(SettingsKeys.danmakuOpacity);defaultDanmakuFontSize = GStorage.getSetting<double>(@@ -352,7 +351,7 @@ class _DanmakuSettingsPageState extends State<DanmakuSettingsPage> {title: Text('字体大小'),value: defaultDanmakuFontSize,min: 10,- max: isCompact() ? 32 : 48,+ max: 48,valueLabel: '${defaultDanmakuFontSize.floor()}',onChanged: (value) =>updateDanmakuFontSize(value.floorToDouble()),diff --git a/lib/pages/settings/danmaku/danmaku_settings_sheet.dart b/lib/pages/settings/danmaku/danmaku_settings_sheet.dartindex 930b94b4..b9a07cd4 100644--- a/lib/pages/settings/danmaku/danmaku_settings_sheet.dart+++ b/lib/pages/settings/danmaku/danmaku_settings_sheet.dart@@ -9,7 +9,6 @@ import 'package:kazumi/bean/widget/content_section.dart';import 'package:kazumi/pages/settings/danmaku/danmaku_shield_settings_sheet.dart';import 'package:kazumi/pages/settings/danmaku/danmaku_time_offset_sheet.dart';import 'package:kazumi/services/storage/storage.dart';-import 'package:kazumi/utils/device.dart';enum _DanmakuSettingsDestination {timeOffset,@@ -97,7 +96,7 @@ class _DanmakuSettingsSheetState extends State<_DanmakuSettingsSheet> {title: Text('字体大小'),value: _option.fontSize,min: 10,- max: isCompact() ? 32 : 48,+ max: 48,valueLabel: '${_option.fontSize.floor()}',onChanged: (value) {final fontSize = value.floorToDouble();diff --git a/lib/pages/video/video_controller.dart b/lib/pages/video/video_controller.dartindex 182ae777..08b310b1 100644--- a/lib/pages/video/video_controller.dart+++ b/lib/pages/video/video_controller.dart@@ -14,18 +14,17 @@ import 'package:kazumi/services/video_source/services.dart';import 'package:kazumi/bean/dialog/dialog_helper.dart';import 'package:mobx/mobx.dart';import 'package:kazumi/services/logging/logger.dart';-import 'package:window_manager/window_manager.dart';import 'package:kazumi/modules/bangumi/episode_item.dart';import 'package:kazumi/modules/comments/comment_item.dart';import 'package:kazumi/modules/comments/comment_response.dart';import 'package:kazumi/request/apis/bangumi_api.dart';import 'package:kazumi/services/storage/storage.dart';-import 'package:kazumi/utils/device.dart';import 'package:kazumi/utils/episode_url.dart';import 'package:kazumi/utils/http_headers.dart';import 'package:kazumi/utils/media.dart';import 'package:kazumi/utils/async_session.dart';import 'package:kazumi/services/platform/display_mode_service.dart';+import 'package:kazumi/pages/video/video_fullscreen_controller.dart';part 'video_controller.g.dart';@@ -99,8 +98,11 @@ abstract class _VideoPageController with Store implements Disposable {VideoEpisodeSelection get playbackEpisode =>playingEpisode ?? selectedEpisode;- @observable- bool isFullscreen = false;+ final fullscreen = VideoFullscreenController(+ applyFullscreen: DisplayModeService.applyVideoFullscreen,+ );++ bool get isFullscreen => fullscreen.isFullscreen;@observablebool isCommentsAscending = false;@@ -115,9 +117,6 @@ abstract class _VideoPageController with Store implements Disposable {@observablebool isPip = false;- @observable- bool showTabBody = true;-@observableint historyOffset = 0;@@ -744,6 +743,7 @@ abstract class _VideoPageController with Store implements Disposable {/// Called by Modular when the '/video' route scope is disposed.@overridevoid dispose() {+ unawaited(fullscreen.close());_playbackSessions.cancel();_danmakuSessions.cancel();_commentSessions.cancel();@@ -758,30 +758,6 @@ abstract class _VideoPageController with Store implements Disposable {unawaited(videoSourceService.dispose());}}-- void enterFullScreen() {- isFullscreen = true;- DisplayModeService.enterFullScreen(lockOrientation: false);- }-- void exitFullScreen() {- isFullscreen = false;- DisplayModeService.exitFullScreen();- }-- void isDesktopFullscreen() async {- if (isDesktop()) {- isFullscreen = await windowManager.isFullScreen();- }- }-- void handleOnEnterFullScreen() async {- isFullscreen = true;- }-- void handleOnExitFullScreen() async {- isFullscreen = false;- }}class OfflineRoadListSnapshot {diff --git a/lib/pages/video/video_controller.g.dart b/lib/pages/video/video_controller.g.dartindex 9dddc5c1..5dafe32f 100644--- a/lib/pages/video/video_controller.g.dart+++ b/lib/pages/video/video_controller.g.dart@@ -109,22 +109,6 @@ mixin _$VideoPageController on _VideoPageController, Store {});}- late final _$isFullscreenAtom =- Atom(name: '_VideoPageController.isFullscreen', context: context);-- @override- bool get isFullscreen {- _$isFullscreenAtom.reportRead();- return super.isFullscreen;- }-- @override- set isFullscreen(bool value) {- _$isFullscreenAtom.reportWrite(value, super.isFullscreen, () {- super.isFullscreen = value;- });- }-late final _$isCommentsAscendingAtom =Atom(name: '_VideoPageController.isCommentsAscending', context: context);@@ -157,22 +141,6 @@ mixin _$VideoPageController on _VideoPageController, Store {});}- late final _$showTabBodyAtom =- Atom(name: '_VideoPageController.showTabBody', context: context);-- @override- bool get showTabBody {- _$showTabBodyAtom.reportRead();- return super.showTabBody;- }-- @override- set showTabBody(bool value) {- _$showTabBodyAtom.reportWrite(value, super.showTabBody, () {- super.showTabBody = value;- });- }-late final _$historyOffsetAtom =Atom(name: '_VideoPageController.historyOffset', context: context);@@ -341,10 +309,8 @@ episodeCommentsList: ${episodeCommentsList},selectedEpisode: ${selectedEpisode},playingEpisode: ${playingEpisode},commentsEpisode: ${commentsEpisode},-isFullscreen: ${isFullscreen},isCommentsAscending: ${isCommentsAscending},isPip: ${isPip},-showTabBody: ${showTabBody},historyOffset: ${historyOffset},isOfflineMode: ${isOfflineMode},roadList: ${roadList}diff --git a/lib/pages/video/video_fullscreen_controller.dart b/lib/pages/video/video_fullscreen_controller.dartnew file mode 100644index 00000000..71ef1f90--- /dev/null+++ b/lib/pages/video/video_fullscreen_controller.dart@@ -0,0 +1,94 @@+import 'dart:async';++import 'package:flutter/widgets.dart';+import 'package:mobx/mobx.dart';++/// Explicit fullscreen owns a local history entry; rotation does not.+class VideoFullscreenController {+ VideoFullscreenController({+ required Future<void> Function(bool fullscreen) applyFullscreen,+ }) : _applyFullscreen = applyFullscreen;++ final Future<void> Function(bool fullscreen) _applyFullscreen;+ final Observable<LocalHistoryEntry?> _entry = Observable(null);+ ModalRoute<dynamic>? _route;+ int _revision = 0;+ int _pendingRequests = 0;+ Future<void> _lastRequest = Future.value();+ Future<void>? _closeFuture;++ bool get isFullscreen => _entry.value != null;++ void attach(ModalRoute<dynamic> route) {+ assert(_route == null || identical(_route, route));+ _route = route;+ }++ Future<void> toggle() => setFullscreen(!isFullscreen);++ Future<void> setFullscreen(bool fullscreen) =>+ _setFullscreen(fullscreen, updatePlatform: true);++ Future<void> _setFullscreen(bool fullscreen, {required bool updatePlatform}) {+ if (_closeFuture != null || fullscreen == isFullscreen) return _lastRequest;+ final route = _route;+ if (route == null) {+ throw StateError('Attach the video route before entering fullscreen.');+ }+ _revision++;+ if (fullscreen) {+ late final LocalHistoryEntry entry;+ entry = LocalHistoryEntry(+ impliesAppBarDismissal: false,+ onRemove: () {+ if (!identical(_entry.value, entry)) return;+ _revision++;+ _setEntry(null);+ unawaited(_requestFullscreen(false));+ },+ );+ route.addLocalHistoryEntry(entry);+ _setEntry(entry);+ } else {+ _removeEntry();+ }+ return updatePlatform ? _requestFullscreen(fullscreen) : Future.value();+ }++ void _setEntry(LocalHistoryEntry? entry) {+ runInAction(() => _entry.value = entry);+ }++ void _removeEntry() {+ final entry = _entry.value;+ _setEntry(null);+ entry?.remove();+ }++ void onDesktopFullscreenChanged(bool fullscreen) {+ // Ignore acknowledgements of commands still in flight.+ if (_pendingRequests != 0) return;+ unawaited(_setFullscreen(fullscreen, updatePlatform: false));+ }++ Future<void> initializeDesktop(Future<bool> Function() readFullscreen) async {+ final revision = _revision;+ final fullscreen = await readFullscreen();+ if (revision == _revision) onDesktopFullscreenChanged(fullscreen);+ }++ Future<void> _requestFullscreen(bool fullscreen) {+ _pendingRequests++;+ return _lastRequest = _applyFullscreen(fullscreen).whenComplete(() {+ _pendingRequests--;+ });+ }++ Future<void> close() {+ if (_closeFuture != null) return _closeFuture!;+ _revision++;+ _removeEntry();+ _route = null;+ return _closeFuture = _requestFullscreen(false);+ }+}diff --git a/lib/pages/video/video_page.dart b/lib/pages/video/video_page.dartindex b1e134db..b0e2b947 100644--- a/lib/pages/video/video_page.dart+++ b/lib/pages/video/video_page.dart@@ -3,14 +3,12 @@ import 'dart:async';import 'package:canvas_danmaku/models/danmaku_content_item.dart';import 'package:flutter/material.dart';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:window_manager/window_manager.dart';import 'package:kazumi/bean/appbar/drag_to_move_bar.dart' as dtb;import 'package:kazumi/bean/dialog/adaptive_bottom_sheet.dart';-import 'package:kazumi/bean/dialog/dialog_helper.dart';import 'package:kazumi/bean/widget/embedded_native_control_area.dart';import 'package:kazumi/bean/widget/loading_indicator.dart';import 'package:kazumi/bean/widget/media_error_widget.dart';@@ -25,7 +23,9 @@ 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/platform/display_mode_service.dart';+import 'package:kazumi/pages/video/video_page_layout.dart';+import 'package:kazumi/pages/video/video_side_panel.dart';+import 'package:kazumi/pages/video/video_system_bars.dart';import 'package:kazumi/services/player/pip_utils.dart';import 'package:kazumi/services/player/timed_shutdown_service.dart';import 'package:kazumi/services/storage/storage.dart';@@ -52,11 +52,10 @@ class VideoPage extends StatefulWidget {}class _VideoPageState extends State<VideoPage>- with TickerProviderStateMixin, WindowListener {+ with SingleTickerProviderStateMixin, WindowListener {PlayerController get playerController => widget.playerController;VideoPageController get videoPageController => widget.videoPageController;bool _didInitializePlayback = false;- bool _isClosing = false;HistoryController get historyController => widget.historyController;DownloadController get downloadController => widget.downloadController;late bool playResume;@@ -67,21 +66,16 @@ class _VideoPageState extends State<VideoPage>FocusNode(debugLabel: 'Video player shortcut scope');final _episodePanelKey = GlobalKey<EpisodeSelectionPanelState>();- late AnimationController animation;- late Animation<Offset> _rightOffsetAnimation;- late Animation<double> _maskOpacityAnimation;+ final _sidePanelKey = GlobalKey<VideoSidePanelState>();late TabController tabController;- bool _tabBodyTargetVisible = true;- int _tabBodyAnimationRun = 0;-late final bool disableAnimations;StreamSubscription<SyncPlayChatMessage>? _syncChatSubscription;late final mobx.ReactionDisposer _pipModeListener;+ LocalHistoryEntry? _desktopPipEntry;static const Duration _offlinePlayerInitDelay = Duration(milliseconds: 400);- static const Duration _sideTabAnimationDuration = Duration(milliseconds: 120);@overridevoid initState() {@@ -89,56 +83,17 @@ class _VideoPageState extends State<VideoPage>videoPageController.applyPlaybackArgs(widget.args);windowManager.addListener(this);- videoPageController.isDesktopFullscreen();tabController = TabController(length: 2, vsync: this);- animation = AnimationController(- duration: _sideTabAnimationDuration,- vsync: this,- );- _rightOffsetAnimation = Tween<Offset>(- begin: const Offset(1.0, 0.0),- end: const Offset(0.0, 0.0),- ).animate(CurvedAnimation(- parent: animation,- curve: Curves.easeOut,- ));- _maskOpacityAnimation = Tween<double>(- begin: 0.0,- end: 1.0,- ).animate(CurvedAnimation(- parent: animation,- curve: Curves.easeIn,- ));playResume = GStorage.getSetting(SettingsKeys.playResume);disableAnimations =GStorage.getSetting(SettingsKeys.playerDisableAnimations);_pipModeListener = mobx.reaction<bool>((_) => videoPageController.isPip,- (_) => _syncFullscreenWithWindowShape(),+ _syncDesktopPipHistory,);}- bool get _windowIsLandscape {- final Size window = MediaQuery.sizeOf(context);- return window.width > window.height;- }-- // Fullscreen and picture-in-picture events can arrive in either order.- void _syncFullscreenWithWindowShape() {- if (isDesktop() || videoPageController.isPip) {- return;- }- final bool landscape = _windowIsLandscape;- if (landscape && !videoPageController.isFullscreen) {- _hideTabBodyImmediately();- videoPageController.enterFullScreen();- } else if (!landscape && videoPageController.isFullscreen) {- videoPageController.exitFullScreen();- _showTabBodyImmediately();- }- }-@overridevoid didChangeDependencies() {super.didChangeDependencies();@@ -146,6 +101,11 @@ class _VideoPageState extends State<VideoPage>return;}_didInitializePlayback = true;+ videoPageController.fullscreen.attach(ModalRoute.of(context)!);+ if (isDesktop()) {+ unawaited(videoPageController.fullscreen+ .initializeDesktop(windowManager.isFullScreen));+ }_initializePlayback();}@@ -183,7 +143,7 @@ class _VideoPageState extends State<VideoPage>videoPageController.historyOffset = identity == null? 0: videoPageController.getHistoryOffsetFor(identity);- _showTabBodyImmediately();+ _revealCurrentEpisode();WidgetsBinding.instance.addPostFrameCallback((_) async {await Future.delayed(_offlinePlayerInitDelay);@@ -219,7 +179,7 @@ class _VideoPageState extends State<VideoPage>}}}- _showTabBodyImmediately();+ _revealCurrentEpisode();_logSubscription = videoPageController.logStream.listen((log) {if (mounted) {@@ -247,9 +207,6 @@ class _VideoPageState extends State<VideoPage>try {windowManager.removeListener(this);} catch (_) {}- try {- animation.dispose();- } catch (_) {}try {_syncChatSubscription?.cancel();} catch (_) {}@@ -257,13 +214,14 @@ class _VideoPageState extends State<VideoPage>_logSubscription?.cancel();} catch (_) {}_pipModeListener();- // Modular disposes the controller and its log subscription with the route.+ _desktopPipEntry?.remove();+ _desktopPipEntry = null;if (!isDesktop()) {try {ScreenBrightnessPlatform.instance.resetApplicationScreenBrightness();} catch (_) {}}- DisplayModeService.unlockScreenRotation();+ unawaited(videoPageController.fullscreen.close());keyboardFocus.dispose();tabController.dispose();TimedShutdownService().cancel();@@ -272,40 +230,29 @@ class _VideoPageState extends State<VideoPage>@overridevoid onWindowEnterFullScreen() {- _hideTabBodyImmediately();- videoPageController.handleOnEnterFullScreen();+ videoPageController.fullscreen.onDesktopFullscreenChanged(true);}@overridevoid onWindowLeaveFullScreen() {- videoPageController.handleOnExitFullScreen();+ videoPageController.fullscreen.onDesktopFullscreenChanged(false);}- void hideDebugConsole() {- setState(() {- showDebugLog = false;- });- }-- void switchDebugConsole() {+ void _toggleDebugConsole() {setState(() {showDebugLog = !showDebugLog;});}- void clearWebviewLog() {- setState(() {- webviewLogLines.clear();- });- }-Future<void> changeEpisode(int episode,{int currentRoad = 0, int offset = 0}) async {if (!mounted) {return;}- clearWebviewLog();- hideDebugConsole();+ setState(() {+ webviewLogLines.clear();+ showDebugLog = false;+ });await videoPageController.changeEpisode(episode,currentRoad: currentRoad,offset: offset,@@ -318,125 +265,33 @@ class _VideoPageState extends State<VideoPage>});}- bool get _isSideTabLayout => _windowIsLandscape;-- bool get _canAnimateSideTab =>- mounted && _isSideTabLayout && !disableAnimations;-- void _openTabBodyAnimated() {- _setTabBodyVisible(true, animated: true);- _revealCurrentEpisode();- }-- void _closeTabBodyAnimated() {- _setTabBodyVisible(false, animated: true);- keyboardFocus.requestFocus();- }-- void _toggleTabBodyAnimated() {- if (_tabBodyTargetVisible) {- _closeTabBodyAnimated();- } else {- _openTabBodyAnimated();- }- }-- void _showTabBodyImmediately() {- _setTabBodyVisible(true, animated: false);- _revealCurrentEpisode();- }-- void _hideTabBodyImmediately() {- _setTabBodyVisible(false, animated: false);- }-- void _setTabBodyVisible(bool visible, {required bool animated}) {- _tabBodyTargetVisible = visible;- final int animationRun = ++_tabBodyAnimationRun;-- if (visible) {- if (!videoPageController.showTabBody) {- animation.value = 0.0;- videoPageController.showTabBody = true;- }- if (_canAnimateSideTab && animated) {- animation.forward(from: animation.value);- } else {- animation.value = 1.0;- }- return;- }-- if (!videoPageController.showTabBody) {- animation.value = 0.0;- return;- }-- if (_canAnimateSideTab && animated && animation.value > 0.0) {- animation.reverse().whenComplete(() {- if (!mounted || animationRun != _tabBodyAnimationRun) {- return;- }- videoPageController.showTabBody = false;- animation.value = 0.0;- });- return;- }-- videoPageController.showTabBody = false;- animation.value = 0.0;- }-- void _syncTabBodyAnimationAfterLayout() {- if (!_tabBodyTargetVisible) {- if (!videoPageController.showTabBody) {- animation.value = 0.0;- }- return;- }- if (!videoPageController.showTabBody) {- animation.value = 0.0;- return;- }- if (!_isSideTabLayout || disableAnimations) {- animation.value = 1.0;- return;- }- if (animation.value == 0.0 && animation.status != AnimationStatus.reverse) {- animation.forward();+ void _toggleSidePanel() => _sidePanelKey.currentState?.toggle();++ void _closeSidePanel() => _sidePanelKey.currentState?.close();++ // Only desktop PiP participates in local navigation.+ void _syncDesktopPipHistory(bool isPip) {+ if (!isDesktop()) return;+ if (isPip && _desktopPipEntry == null) {+ _desktopPipEntry = LocalHistoryEntry(+ impliesAppBarDismissal: false,+ onRemove: () {+ _desktopPipEntry = null;+ if (videoPageController.isPip) {+ videoPageController.isPip = false;+ unawaited(PipUtils.exitDesktopPIPWindow());+ }+ },+ );+ ModalRoute.of(context)!.addLocalHistoryEntry(_desktopPipEntry!);+ } else if (!isPip) {+ _desktopPipEntry?.remove();+ _desktopPipEntry = null;}}- void onBackPressed(BuildContext context) async {- if (KazumiDialog.observer.hasKazumiDialog) {- KazumiDialog.dismiss();- return;- }- if (videoPageController.isPip && isDesktop()) {- PipUtils.exitDesktopPIPWindow();- videoPageController.isPip = false;- return;- }- if (videoPageController.isFullscreen && !isTablet()) {- _revealCurrentEpisode();- await DisplayModeService.exitFullScreen();- _hideTabBodyImmediately();- videoPageController.isFullscreen = false;- return;- }- if (videoPageController.isFullscreen) {- await DisplayModeService.exitFullScreen();- videoPageController.isFullscreen = false;- }- if (_isClosing) {- return;- }- _isClosing = true;- playerController.beginShutdown();- if (!context.mounted) {- return;- }- context.pop();+ void _onBackPressed() {+ unawaited(Navigator.of(context).maybePop());}void pauseForTimedShutdown() {@@ -447,120 +302,44 @@ class _VideoPageState extends State<VideoPage>@overrideWidget build(BuildContext context) {- final bool isLandscape = _windowIsLandscape;- _syncFullscreenWithWindowShape();- WidgetsBinding.instance.addPostFrameCallback((_) {- if (!mounted) {- return;- }- _syncTabBodyAnimationAfterLayout();- });return PopScope(- canPop: false,onPopInvokedWithResult: (bool didPop, Object? result) {- if (didPop) {- return;- }- onBackPressed(context);+ if (didPop) playerController.beginShutdown();},child: Observer(builder: (context) {final bool isPip = videoPageController.isPip;- final bool videoFillsWindow = isLandscape || isPip;- return Scaffold(- appBar: null,- body: SafeArea(- top: !videoPageController.isFullscreen && !isPip,- bottom: false,- left: !videoPageController.isFullscreen && !isPip,- right: !videoPageController.isFullscreen && !isPip,- child: Stack(- alignment: Alignment.centerRight,- children: [- Column(- children: [- Flexible(- flex: videoFillsWindow ? 1 : 0,- child: Container(- color: Colors.black,- height: videoFillsWindow- ? MediaQuery.sizeOf(context).height- : MediaQuery.sizeOf(context).width * 9 / 16,- width: MediaQuery.sizeOf(context).width,- child: Focus(- focusNode: keyboardFocus,- autofocus: true,- child: playerBody,- ),- ),- ),- if (!videoFillsWindow) Expanded(child: tabBody),- ],- ),- if (isLandscape &&- videoPageController.showTabBody &&- !isPip) ...[- if (disableAnimations) ...[- sideTabMask,- sideTabBody,- ] else ...[- FadeTransition(- opacity: _maskOpacityAnimation,- child: sideTabMask,- ),- SlideTransition(- position: _rightOffsetAnimation,- child: sideTabBody,- ),- ],- ],- ],- )),+ return VideoSystemBars(+ fullscreen: videoPageController.isFullscreen,+ isPip: isPip,+ child: Scaffold(+ body: VideoPageLayout(+ fullscreen: videoPageController.isFullscreen,+ isPip: isPip,+ playerBuilder: (context, layout) => ColoredBox(+ color: Colors.black,+ child: Focus(+ focusNode: keyboardFocus,+ autofocus: true,+ child: Observer(builder: (_) => _buildPlayerBody(layout)),+ ),+ ),+ tabs: tabBody,+ sidePanel: VideoSidePanel(+ key: _sidePanelKey,+ fullscreen: videoPageController.isFullscreen,+ disableAnimations: disableAnimations,+ onOpened: _revealCurrentEpisode,+ onClosed: keyboardFocus.requestFocus,+ child: tabBody,+ ),+ ),+ ),);}),);}- Widget get sideTabBody {- return SizedBox(- height: MediaQuery.sizeOf(context).height,- width: (!isDesktop() && !isTablet())- ? MediaQuery.sizeOf(context).height- : (MediaQuery.sizeOf(context).width / 3 > 420- ? 420- : MediaQuery.sizeOf(context).width / 3),- 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,- ),- );- }-- Widget get sideTabMask {- return GestureDetector(- onTap: _closeTabBodyAnimated,- child: Container(- decoration: BoxDecoration(- gradient: LinearGradient(- begin: Alignment.centerLeft,- end: Alignment.centerRight,- colors: [- Colors.black.withValues(alpha: 0.5),- Colors.transparent,- ],- ),- ),- width: double.infinity,- height: double.infinity,- ),- );- }-- Widget get playerBody {+ Widget _buildPlayerBody(VideoPlayerLayout layout) {final bool playerLoading = playerController.playback.loading;return Stack(children: [@@ -613,7 +392,7 @@ class _VideoPageState extends State<VideoPage>itemCount: webviewLogLines.length,itemBuilder: (context, index) {return Text(- webviewLogLines.isEmpty ? '' : webviewLogLines[index],+ webviewLogLines[index],style: const TextStyle(color: Colors.white,),@@ -637,7 +416,7 @@ class _VideoPageState extends State<VideoPage>IconButton(icon: const Icon(Icons.arrow_back,color: Colors.white),- onPressed: () => onBackPressed(context),+ onPressed: _onBackPressed,),const Expanded(child: dtb.DragToMoveArea(@@ -652,30 +431,21 @@ class _VideoPageState extends State<VideoPage>videoPageController.selectedEpisode.road);},),- Visibility(- visible: MediaQuery.sizeOf(context).width >- MediaQuery.sizeOf(context).height,- child: IconButton(- onPressed: () {- _toggleTabBodyAnimated();- },- icon: Icon(- _tabBodyTargetVisible- ? Icons.menu_open- : Icons.menu_open_outlined,+ if (layout.hasSidePanel)+ IconButton(+ onPressed: _toggleSidePanel,+ icon: const Icon(+ Icons.menu_open_rounded,color: Colors.white,),),- ),IconButton(icon: Icon(showDebugLog? Icons.bug_report: Icons.bug_report_outlined,color: Colors.white),- onPressed: () {- switchDebugConsole();- },+ onPressed: _toggleDebugConsole,),],),@@ -687,16 +457,16 @@ class _VideoPageState extends State<VideoPage>),),Positioned.fill(- child: playerController.playback.loading- ? Container()+ child: playerLoading+ ? const SizedBox.shrink(): PlayerItem(+ fillsWindow: layout.fillsWindow,playerController: playerController,videoPageController: videoPageController,- toggleMenu: _toggleTabBodyAnimated,- showMenuImmediately: _showTabBodyImmediately,- hideMenuImmediately: _hideTabBodyImmediately,+ onToggleSidePanel:+ layout.hasSidePanel ? _toggleSidePanel : null,changeEpisode: changeEpisode,- onBackPressed: onBackPressed,+ onBackPressed: _onBackPressed,keyboardFocus: keyboardFocus,disableAnimations: disableAnimations,pauseForTimedShutdown: pauseForTimedShutdown,@@ -746,7 +516,7 @@ class _VideoPageState extends State<VideoPage>road == videoPageController.selectedEpisode.road) {return;}- _closeTabBodyAnimated();+ _closeSidePanel();changeEpisode(episode, currentRoad: road);},onDownload: (road) => showAdaptiveBottomSheet<void>(diff --git a/lib/pages/video/video_page_layout.dart b/lib/pages/video/video_page_layout.dartnew file mode 100644index 00000000..f467cb58--- /dev/null+++ b/lib/pages/video/video_page_layout.dart@@ -0,0 +1,63 @@+import 'package:flutter/material.dart';++typedef VideoPlayerLayout = ({bool fillsWindow, bool hasSidePanel});++/// Fullscreen fills the available window; rotation belongs to the OS.+class VideoPageLayout extends StatelessWidget {+ const VideoPageLayout({+ super.key,+ required this.fullscreen,+ required this.isPip,+ required this.playerBuilder,+ required this.tabs,+ this.sidePanel,+ });++ final bool fullscreen;+ final bool isPip;+ final Widget Function(BuildContext context, VideoPlayerLayout layout)+ playerBuilder;+ final Widget tabs;+ final Widget? sidePanel;++ @override+ Widget build(BuildContext context) {+ return LayoutBuilder(builder: (context, constraints) {+ final fillsWindow =+ fullscreen || isPip || constraints.maxWidth > constraints.maxHeight;+ final hasSidePanel = fillsWindow && !isPip && sidePanel != null;+ return SafeArea(+ top: !fillsWindow,+ bottom: !fillsWindow,+ left: !fillsWindow,+ right: !fillsWindow,+ child: Stack(+ alignment: Alignment.centerRight,+ children: [+ Column(+ children: [+ Flexible(+ flex: fillsWindow ? 1 : 0,+ child: SizedBox(+ height: fillsWindow ? double.infinity : null,+ width: double.infinity,+ child: AspectRatio(+ aspectRatio: 16 / 9,+ child: Builder(+ builder: (context) => playerBuilder(context, (+ fillsWindow: fillsWindow,+ hasSidePanel: hasSidePanel+ ))),+ ),+ ),+ ),+ if (!fillsWindow) Expanded(child: tabs),+ ],+ ),+ if (hasSidePanel) sidePanel!,+ ],+ ),+ );+ });+ }+}diff --git a/lib/pages/video/video_side_panel.dart b/lib/pages/video/video_side_panel.dartnew file mode 100644index 00000000..ad7919c8--- /dev/null+++ b/lib/pages/video/video_side_panel.dart@@ -0,0 +1,132 @@+import 'dart:math' as math;++import 'package:flutter/material.dart';++class VideoSidePanel extends StatefulWidget {+ const VideoSidePanel({+ super.key,+ required this.fullscreen,+ required this.child,+ this.disableAnimations = false,+ this.onOpened,+ this.onClosed,+ });++ final bool fullscreen;+ final bool disableAnimations;+ final Widget child;+ final VoidCallback? onOpened;+ final VoidCallback? onClosed;++ @override+ State<VideoSidePanel> createState() => VideoSidePanelState();+}++class VideoSidePanelState extends State<VideoSidePanel>+ with SingleTickerProviderStateMixin {+ late final AnimationController _animation = AnimationController(+ vsync: this,+ duration: const Duration(milliseconds: 120),+ );+ late final Animation<Offset> _offset = Tween<Offset>(+ begin: const Offset(1, 0),+ end: Offset.zero,+ ).animate(_animation.drive(CurveTween(curve: Curves.easeOut)));+ late final Animation<double> _opacity =+ _animation.drive(CurveTween(curve: Curves.easeIn));++ bool get _isOpening =>+ _animation.status == AnimationStatus.forward ||+ _animation.status == AnimationStatus.completed;++ void toggle() {+ if (_isOpening) {+ close();+ } else {+ if (widget.disableAnimations) {+ _animation.value = 1;+ } else {+ _animation.forward();+ }+ widget.onOpened?.call();+ }+ }++ void close() {+ if (widget.disableAnimations) {+ _animation.value = 0;+ } else {+ _animation.reverse();+ }+ widget.onClosed?.call();+ }++ @override+ void didUpdateWidget(VideoSidePanel oldWidget) {+ super.didUpdateWidget(oldWidget);+ // Reset before rendering the new mode to avoid a sidebar flash.+ if (oldWidget.fullscreen != widget.fullscreen) _animation.value = 0;+ }++ @override+ void dispose() {+ _animation.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) => LayoutBuilder(+ builder: (context, constraints) => AnimatedBuilder(+ animation: _animation,+ builder: (context, child) {+ if (_animation.isDismissed) return const SizedBox.shrink();+ return Stack(+ alignment: Alignment.centerRight,+ children: [+ FadeTransition(+ opacity: _opacity,+ child: GestureDetector(+ onTap: close,+ child: SizedBox.expand(+ child: DecoratedBox(+ decoration: BoxDecoration(+ gradient: LinearGradient(+ begin: Alignment.centerLeft,+ end: Alignment.centerRight,+ colors: [+ Colors.black.withValues(alpha: 0.5),+ Colors.transparent,+ ],+ ),+ ),+ ),+ ),+ ),+ ),+ SlideTransition(position: _offset, child: child),+ ],+ );+ },+ child: SizedBox(+ // Keep space outside the panel for dismissal.+ width: math.min(constraints.maxWidth * 0.9,+ (constraints.maxWidth / 3).clamp(320.0, 420.0)),+ height: constraints.maxHeight,+ child: Material(+ color: Theme.of(context).colorScheme.surface,+ borderRadius: const BorderRadiusDirectional.only(+ topStart: Radius.circular(28),+ bottomStart: Radius.circular(28),+ ),+ clipBehavior: Clip.antiAlias,+ // Consume the hidden status-bar inset for the entire overlay.+ child: MediaQuery.removePadding(+ context: context,+ removeTop: true,+ child: SafeArea(child: widget.child),+ ),+ ),+ ),+ ),+ );+}diff --git a/lib/pages/video/video_system_bars.dart b/lib/pages/video/video_system_bars.dartnew file mode 100644index 00000000..606992dc--- /dev/null+++ b/lib/pages/video/video_system_bars.dart@@ -0,0 +1,84 @@+import 'dart:async';++import 'package:flutter/widgets.dart';+import 'package:kazumi/navigation.dart';+import 'package:kazumi/services/platform/display_mode_service.dart';++/// Place above Scaffold to measure the window without keyboard insets.+class VideoSystemBars extends StatefulWidget {+ const VideoSystemBars({+ super.key,+ required this.fullscreen,+ required this.isPip,+ required this.child,+ });++ final bool fullscreen;+ final bool isPip;+ final Widget child;++ @override+ State<VideoSystemBars> createState() => _VideoSystemBarsState();+}++class _VideoSystemBarsState extends State<VideoSystemBars> with RouteAware {+ PageRoute<void>? _route;+ bool _visible = true;++ @override+ void didChangeDependencies() {+ super.didChangeDependencies();+ final route = ModalRoute.of(context);+ if (route is PageRoute<void> && !identical(route, _route)) {+ rootRouteObserver.unsubscribe(this);+ _route = route;+ _visible = route.isCurrent;+ rootRouteObserver.subscribe(this, route);+ }+ _sync();+ }++ @override+ void didUpdateWidget(covariant VideoSystemBars oldWidget) {+ super.didUpdateWidget(oldWidget);+ _sync();+ }++ @override+ void didPushNext() => _setVisible(false);++ @override+ void didPopNext() => _setVisible(true);++ @override+ void didPop() => _setVisible(false);++ void _setVisible(bool visible) {+ _visible = visible;+ _sync();+ }++ void _sync() {+ if (!_visible || _route?.isActive == false) {+ unawaited(DisplayModeService.releaseSystemBars(this));+ } else if (!widget.isPip) {+ // PiP keeps the full-window preference until its original metrics return.+ final landscape =+ MediaQuery.orientationOf(context) == Orientation.landscape;+ unawaited(DisplayModeService.setSystemBarsHidden(+ owner: this,+ hidden: widget.fullscreen || landscape,+ ));+ }+ }++ @override+ void dispose() {+ rootRouteObserver.unsubscribe(this);+ unawaited(DisplayModeService.releaseSystemBars(this));+ super.dispose();+ }++ @override+ Widget build(BuildContext context) => widget.child;+}diff --git a/lib/services/platform/display_mode_service.dart b/lib/services/platform/display_mode_service.dartindex 942a7607..d4967268 100644--- a/lib/services/platform/display_mode_service.dart+++ b/lib/services/platform/display_mode_service.dart@@ -1,94 +1,87 @@-import 'dart:io';-import 'package:flutter/foundation.dart';import 'package:flutter/services.dart';import 'package:kazumi/services/logging/logger.dart';-import 'package:kazumi/services/platform/platform_environment_service.dart';-import 'package:kazumi/utils/device.dart';import 'package:window_manager/window_manager.dart';class DisplayModeService {DisplayModeService._();static const _intentChannel = MethodChannel('com.predidit.kazumi/intent');+ static Future<void> _pendingFullscreen = Future.value();+ static Future<void>? _pendingSystemBars;+ static Object? _systemBarsOwner;+ static bool _systemBarsHidden = false;- static Future<void> enterFullScreen({bool lockOrientation = true}) async {- if (Platform.isLinux || Platform.isMacOS || Platform.isWindows) {- await windowManager.setFullScreen(true);- return;- }- if (Platform.isAndroid) {- await _intentChannel.invokeMethod('enterFullscreen');- } else {- await SystemChrome.setEnabledSystemUIMode(SystemUiMode.immersiveSticky);- }- if (!lockOrientation) {- return;- }- if (Platform.isAndroid &&- await PlatformEnvironmentService.isInMultiWindowMode()) {- return;- }- await landscape();+ static Future<void> applyVideoFullscreen(bool fullscreen) {+ return _pendingFullscreen = _pendingFullscreen.then((_) async {+ if (defaultTargetPlatform == TargetPlatform.linux ||+ defaultTargetPlatform == TargetPlatform.macOS ||+ defaultTargetPlatform == TargetPlatform.windows) {+ await _attempt(() => windowManager.setFullScreen(fullscreen));+ return;+ }++ // Restore system orientation on exit, including an existing landscape.+ await _attempt(() => SystemChrome.setPreferredOrientations(+ fullscreen+ ? [+ DeviceOrientation.landscapeLeft,+ DeviceOrientation.landscapeRight+ ]+ : [],+ ));+ });}- static Future<void> exitFullScreen({bool lockOrientation = true}) async {- if (Platform.isLinux || Platform.isMacOS || Platform.isWindows) {- await windowManager.setFullScreen(false);- }- try {- if (Platform.isAndroid || Platform.isIOS) {- if (Platform.isAndroid) {- await _intentChannel.invokeMethod('exitFullscreen');- } else {- await SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge);- }- if (isCompact() && lockOrientation) {- if (Platform.isAndroid &&- await PlatformEnvironmentService.isInMultiWindowMode()) {- return;- }- await verticalScreen();- }- }- } catch (exception, stacktrace) {- KazumiLogger().e(- 'Display: failed to exit full screen',- error: exception,- stackTrace: stacktrace,- );- }+ /// Outgoing pages cannot release chrome owned by the next visible page.+ static Future<void> setSystemBarsHidden({+ required Object owner,+ required bool hidden,+ }) {+ _systemBarsOwner = owner;+ return _setSystemBarsHidden(hidden);}- static Future<void> landscape() async {- dynamic document;- try {- if (kIsWeb) {- await document.documentElement?.requestFullscreen();- } else if (Platform.isAndroid || Platform.isIOS) {- await SystemChrome.setPreferredOrientations(- [- DeviceOrientation.landscapeLeft,- DeviceOrientation.landscapeRight,- ],- );- }- } catch (exception, stacktrace) {- KazumiLogger().e(- 'Display: failed to enter landscape mode',- error: exception,- stackTrace: stacktrace,- );+ static Future<void> releaseSystemBars(Object owner) {+ if (!identical(_systemBarsOwner, owner)) {+ return _pendingSystemBars ?? Future.value();}+ _systemBarsOwner = null;+ return _setSystemBarsHidden(false);}- static Future<void> verticalScreen() async {- await SystemChrome.setPreferredOrientations([- DeviceOrientation.portraitUp,- ]);+ static Future<void> _setSystemBarsHidden(bool hidden) {+ if (_systemBarsHidden == hidden) {+ return _pendingSystemBars ?? Future.value();+ }+ _systemBarsHidden = hidden;+ // Rotation acknowledgements must not delay immersion or route cleanup.+ late final Future<void> request;+ request = (_pendingSystemBars ?? Future<void>.value())+ .then((_) => _attempt(() async {+ if (defaultTargetPlatform == TargetPlatform.android) {+ await _intentChannel.invokeMethod(+ 'setSystemBarsHidden', hidden);+ } else if (defaultTargetPlatform == TargetPlatform.iOS) {+ await SystemChrome.setEnabledSystemUIMode(+ hidden+ ? SystemUiMode.immersiveSticky+ : SystemUiMode.edgeToEdge,+ );+ }+ }))+ .whenComplete(() {+ if (identical(_pendingSystemBars, request)) _pendingSystemBars = null;+ });+ return _pendingSystemBars = request;}- static Future<void> unlockScreenRotation() async {- await SystemChrome.setPreferredOrientations([]);+ static Future<void> _attempt(Future<void> Function() operation) async {+ try {+ await operation();+ } catch (error, stackTrace) {+ KazumiLogger().e('Display: failed to apply video display mode',+ error: error, stackTrace: stackTrace);+ }}}diff --git a/lib/services/platform/platform_environment_service.dart b/lib/services/platform/platform_environment_service.dartindex f6989c9d..25cb5179 100644--- a/lib/services/platform/platform_environment_service.dart+++ b/lib/services/platform/platform_environment_service.dart@@ -8,18 +8,6 @@ class PlatformEnvironmentService {static const _intentChannel = MethodChannel('com.predidit.kazumi/intent');- static Future<bool> isInMultiWindowMode() async {- if (!Platform.isAndroid) {- return false;- }- try {- return await _intentChannel.invokeMethod('checkIfInMultiWindowMode');- } on PlatformException catch (e) {- KazumiLogger().e("Failed to check multi window mode: '${e.message}'.");- return false;- }- }-static Future<bool> isRunningOnX11() async {if (!Platform.isLinux) {return false;diff --git a/lib/services/storage/settings_keys.dart b/lib/services/storage/settings_keys.dartindex 68d7e2eb..b0e497c6 100644--- a/lib/services/storage/settings_keys.dart+++ b/lib/services/storage/settings_keys.dart@@ -268,11 +268,6 @@ class SettingsKeys {'/tab/popular/',group: SettingGroup.interface,);- static const isWideScreen = SettingKey<bool>(- _SettingBoxKey.isWideScreen,- false,- group: SettingGroup.interface,- );static const webDavEnable = SettingKey<bool>(_SettingBoxKey.webDavEnable,false,@@ -574,7 +569,6 @@ class SettingsKeys {enableBangumiProxy,enableSystemProxy,defaultStartupPage,- isWideScreen,webDavEnable,webDavEnableHistory,webDavEnableCollect,@@ -686,9 +680,6 @@ class _SettingBoxKey {enableBangumiProxy = 'enableBangumiProxy',enableSystemProxy = 'enableSystemProxy',defaultStartupPage = 'defaultStartupPage',-- /// Deprecated- isWideScreen = 'isWideScreen',webDavEnable = 'webDavEnable',webDavEnableHistory = 'webDavEnableHistory',webDavEnableCollect = 'webDavEnableCollect',diff --git a/lib/utils/device.dart b/lib/utils/device.dartindex 2a51b6c2..12b43f4b 100644--- a/lib/utils/device.dart+++ b/lib/utils/device.dart@@ -26,19 +26,3 @@ Future<Map<String, double>> getScreenInfo() async {bool isDesktop() {return Platform.isWindows || Platform.isMacOS || Platform.isLinux;}--bool isWideScreen() {- final mediaQuery = MediaQueryData.fromView(- WidgetsBinding.instance.platformDispatcher.views.first,- );- return mediaQuery.size.shortestSide >= 600 &&- mediaQuery.size.shortestSide / mediaQuery.size.longestSide >= 9 / 16;-}--bool isTablet() {- return isWideScreen() && !isDesktop();-}--bool isCompact() {- return !isDesktop() && !isWideScreen();-}