Skip to content

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

fix(android): rework pip entry

Predidit281ee9cc589e
diff --git a/android/app/src/main/kotlin/com/example/kazumi/MainActivity.kt b/android/app/src/main/kotlin/com/example/kazumi/MainActivity.kt
index d572011c..b697339e 100644
--- a/android/app/src/main/kotlin/com/example/kazumi/MainActivity.kt
+++ b/android/app/src/main/kotlin/com/example/kazumi/MainActivity.kt
@@ -5,7 +5,12 @@ import android.content.Intent
import android.content.IntentFilter
import android.content.BroadcastReceiver
import android.content.pm.PackageManager
+import android.content.res.Configuration
import android.app.RemoteAction
+import android.graphics.Color
+import android.graphics.Rect
+import android.graphics.drawable.ColorDrawable
+import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.os.StatFs
@@ -13,12 +18,14 @@ import android.net.Uri
import android.app.PictureInPictureParams
import android.graphics.drawable.Icon
import android.util.Rational
+import android.view.View
import androidx.annotation.NonNull
import androidx.core.content.ContextCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import io.flutter.embedding.engine.FlutterEngine
+import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import com.ryanheise.audioservice.AudioServiceActivity
@@ -36,12 +43,19 @@ class MainActivity: AudioServiceActivity() {
private var pipInPlayerPage = false
private var pipAspectWidth = 16
private var pipAspectHeight = 9
+ private var pipSourceRect: Rect? = null
+ private var inPipMode = false
private var androidFullscreen = false
+ private var originalWindowBackground: Drawable? = null
+ private var windowBackgroundOverridden = false
private val actionPipPlayPause = "com.predidit.kazumi.pip.PLAY_PAUSE"
private val actionPipForward = "com.predidit.kazumi.pip.FORWARD"
private val actionPipToggleDanmaku = "com.predidit.kazumi.pip.TOGGLE_DANMAKU"
+ // Ratios outside [1:2.39, 2.39:1] make enterPictureInPictureMode throw.
+ private val maxPipAspectRatio = 2.39f
+
private val pipActionReceiver = object : BroadcastReceiver() {
override fun onReceive(context: android.content.Context?, intent: Intent?) {
val action = intent?.action ?: return
@@ -66,10 +80,21 @@ class MainActivity: AudioServiceActivity() {
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
if (hasFocus && androidFullscreen) {
- applyAndroidFullscreen()
+ applySystemBarsState()
}
}
+ override fun onConfigurationChanged(newConfig: Configuration) {
+ super.onConfigurationChanged(newConfig)
+ syncPictureInPictureMode()
+ }
+
+ @Suppress("DEPRECATION")
+ override fun onPictureInPictureModeChanged(isInPictureInPictureMode: Boolean) {
+ super.onPictureInPictureModeChanged(isInPictureInPictureMode)
+ syncPictureInPictureMode()
+ }
+
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
intentChannel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL)
@@ -124,6 +149,7 @@ class MainActivity: AudioServiceActivity() {
val danmakuEnabled = call.argument<Boolean>("danmakuEnabled") ?: false
pipAspectWidth = call.argument<Int>("width") ?: pipAspectWidth
pipAspectHeight = call.argument<Int>("height") ?: pipAspectHeight
+ updatePipSourceRect(call)
updatePictureInPictureActions(playing, danmakuEnabled)
result.success(true)
} else if (call.method == "setAndroidAutoEnterPIPEnabled") {
@@ -132,6 +158,10 @@ class MainActivity: AudioServiceActivity() {
result.success(true)
} else if (call.method == "setAndroidPIPInPlayerPage") {
pipInPlayerPage = call.argument<Boolean>("inPlayerPage") ?: false
+ if (!pipInPlayerPage) {
+ pipSourceRect = null
+ }
+ refreshWindowBackground()
refreshPictureInPictureParamsIfNeeded()
result.success(true)
} else {
@@ -161,23 +191,61 @@ class MainActivity: AudioServiceActivity() {
private fun enterAndroidFullscreen() {
androidFullscreen = true
- applyAndroidFullscreen()
+ applySystemBarsState()
}
- private fun applyAndroidFullscreen() {
+ private fun exitAndroidFullscreen() {
+ androidFullscreen = false
+ applySystemBarsState()
+ }
+
+ // System bars belong to the full size window; replayed on leaving PiP.
+ private fun applySystemBarsState() {
+ if (inPipMode) {
+ return
+ }
WindowCompat.setDecorFitsSystemWindows(window, false)
- WindowCompat.getInsetsController(window, window.decorView).apply {
- systemBarsBehavior =
+ val controller = WindowCompat.getInsetsController(window, window.decorView)
+ if (androidFullscreen) {
+ controller.systemBarsBehavior =
WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
- hide(WindowInsetsCompat.Type.systemBars())
+ controller.hide(WindowInsetsCompat.Type.systemBars())
+ } else {
+ controller.show(WindowInsetsCompat.Type.systemBars())
}
}
- private fun exitAndroidFullscreen() {
- androidFullscreen = false
- WindowCompat.setDecorFitsSystemWindows(window, false)
- WindowCompat.getInsetsController(window, window.decorView)
- .show(WindowInsetsCompat.Type.systemBars())
+ // Single entry point: the mode callback and the configuration change both
+ // route here, whichever the OEM delivers first.
+ private fun syncPictureInPictureMode() {
+ val current = isInPictureInPictureMode
+ if (current == inPipMode) {
+ return
+ }
+ inPipMode = current
+ pipChannel?.invokeMethod("onModeChanged", mapOf("isInPipMode" to current))
+ refreshWindowBackground()
+ if (!current) {
+ 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.
+ private fun refreshWindowBackground() {
+ val blackBackground = inPipMode || pipInPlayerPage
+ if (blackBackground == windowBackgroundOverridden) {
+ return
+ }
+ if (blackBackground) {
+ originalWindowBackground = window.decorView.background
+ window.setBackgroundDrawable(ColorDrawable(Color.BLACK))
+ } else {
+ window.setBackgroundDrawable(originalWindowBackground)
+ originalWindowBackground = null
+ }
+ windowBackgroundOverridden = blackBackground
}
private fun isPictureInPictureSupported(): Boolean {
@@ -194,7 +262,11 @@ class MainActivity: AudioServiceActivity() {
if (isInPictureInPictureMode) {
return true
}
- return enterPictureInPictureMode(buildPictureInPictureParams())
+ return try {
+ enterPictureInPictureMode(buildPictureInPictureParams())
+ } catch (e: Exception) {
+ false
+ }
}
private fun updatePictureInPictureActions(
@@ -209,13 +281,58 @@ class MainActivity: AudioServiceActivity() {
refreshPictureInPictureParamsIfNeeded()
}
+ // In picture in picture the rect would describe the small window, so the
+ // pre-PiP one is kept as the expand back target.
+ private fun updatePipSourceRect(call: MethodCall) {
+ if (inPipMode) {
+ return
+ }
+ val left = call.argument<Int>("sourceLeft") ?: return
+ val top = call.argument<Int>("sourceTop") ?: return
+ val right = call.argument<Int>("sourceRight") ?: return
+ val bottom = call.argument<Int>("sourceBottom") ?: return
+ if (right <= left || bottom <= top) {
+ return
+ }
+ pipSourceRect = Rect(left, top, right, bottom)
+ }
+
+ private fun buildPipSourceRectHint(): Rect? {
+ val rect = pipSourceRect ?: return null
+ val contentView = window.decorView.findViewById<View>(android.R.id.content) ?: return null
+ val contentBounds = Rect()
+ if (!contentView.getGlobalVisibleRect(contentBounds)) {
+ return null
+ }
+ val hint = Rect(rect)
+ hint.offset(contentBounds.left, contentBounds.top)
+ if (!hint.intersect(contentBounds) || hint.isEmpty) {
+ return null
+ }
+ return hint
+ }
+
+ private fun buildPipAspectRatio(): Rational {
+ val width = if (pipAspectWidth > 0) pipAspectWidth else 16
+ val height = if (pipAspectHeight > 0) pipAspectHeight else 9
+ val ratio = width.toFloat() / height.toFloat()
+ return when {
+ ratio > maxPipAspectRatio -> Rational(239, 100)
+ ratio < 1f / maxPipAspectRatio -> Rational(100, 239)
+ else -> Rational(width, height)
+ }
+ }
+
private fun buildPictureInPictureParams(): PictureInPictureParams {
val actions = buildPipActions()
val builder = PictureInPictureParams.Builder()
- .setAspectRatio(Rational(pipAspectWidth, pipAspectHeight))
+ .setAspectRatio(buildPipAspectRatio())
+ buildPipSourceRectHint()?.let { builder.setSourceRectHint(it) }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
builder.setAutoEnterEnabled(autoEnterPipOnHomeGesture && pipInPlayerPage)
- builder.setSeamlessResizeEnabled(false)
+ // The crossfade alternative is driven by a window snapshot, which
+ // holds no video surface and fades through an empty window.
+ builder.setSeamlessResizeEnabled(true)
}
if (actions.isNotEmpty()) {
builder.setActions(actions)
@@ -228,7 +345,11 @@ class MainActivity: AudioServiceActivity() {
return
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- setPictureInPictureParams(buildPictureInPictureParams())
+ try {
+ setPictureInPictureParams(buildPictureInPictureParams())
+ } catch (e: Exception) {
+ // The activity can reject params while it is not resumed.
+ }
}
}
diff --git a/lib/pages/player/player_item.dart b/lib/pages/player/player_item.dart
index 48bc1696..8534f85a 100644
--- a/lib/pages/player/player_item.dart
+++ b/lib/pages/player/player_item.dart
@@ -91,6 +91,7 @@ class _PlayerItemState extends State<PlayerItem>
late bool webDavEnableHistory;
final _danmuKey = GlobalKey();
+ final _videoSurfaceKey = GlobalKey();
late bool _border;
late double _opacity;
late double _fontSize;
@@ -135,10 +136,19 @@ class _PlayerItemState extends State<PlayerItem>
late double longPressPlaySpeed;
bool? _lastPipPlaying;
bool? _lastPipDanmakuEnabled;
+ Rect? _lastPipSourceRect;
+ bool _pipSourceRectSyncScheduled = false;
+ bool _pipEnterRequested = false;
late mobx.ReactionDisposer _playerSizeListener;
late mobx.ReactionDisposer _fullscreenListener;
+ @override
+ void didChangeMetrics() {
+ super.didChangeMetrics();
+ _scheduleAndroidPIPSourceRectSync();
+ }
+
/// Pauses playback when the app is backgrounded on Android/iOS, unless
/// background playback is enabled.
@override
@@ -196,20 +206,129 @@ class _PlayerItemState extends State<PlayerItem>
}
final bool playing = playerController.playback.playing;
final bool danmakuEnabled = playerController.danmaku.danmakuOn;
+ // In picture in picture the measured rect is the small window itself.
+ final Rect? sourceRect = videoPageController.isPip
+ ? _lastPipSourceRect
+ : _androidPIPSourceRect();
if (!force &&
_lastPipPlaying == playing &&
- _lastPipDanmakuEnabled == danmakuEnabled) {
+ _lastPipDanmakuEnabled == danmakuEnabled &&
+ _lastPipSourceRect == sourceRect) {
return;
}
_lastPipPlaying = playing;
_lastPipDanmakuEnabled = danmakuEnabled;
+ _lastPipSourceRect = sourceRect;
await PipUtils.updateAndroidPIPActions(
playing: playing,
danmakuEnabled: danmakuEnabled,
width: playerController.debug.playerWidth,
height: playerController.debug.playerHeight,
+ sourceRect: sourceRect,
+ );
+ }
+
+ /// The letterboxed video image in physical pixels, relative to the Flutter
+ /// view. Android animates the picture in picture window out of this rect
+ /// instead of shrinking the whole window.
+ Rect? _androidPIPSourceRect() {
+ if (!mounted) {
+ return null;
+ }
+ final renderObject = _videoSurfaceKey.currentContext?.findRenderObject();
+ if (renderObject is! RenderBox || !renderObject.hasSize) {
+ return null;
+ }
+ final Size size = renderObject.size;
+ if (size.isEmpty) {
+ return null;
+ }
+ Rect rect = renderObject.localToGlobal(Offset.zero) & size;
+ final int videoWidth = playerController.debug.playerWidth;
+ final int videoHeight = playerController.debug.playerHeight;
+ if (videoWidth > 0 && videoHeight > 0) {
+ final double scale =
+ (rect.width / videoWidth) < (rect.height / videoHeight)
+ ? rect.width / videoWidth
+ : rect.height / videoHeight;
+ rect = Rect.fromCenter(
+ center: rect.center,
+ width: videoWidth * scale,
+ height: videoHeight * scale,
+ );
+ }
+ final double ratio = MediaQuery.devicePixelRatioOf(context);
+ return Rect.fromLTRB(
+ rect.left * ratio,
+ rect.top * ratio,
+ rect.right * ratio,
+ rect.bottom * ratio,
+ );
+ }
+
+ /// The panel is dropped before the request, not from the mode callback:
+ /// tearing it down while the window animates steals the frames the resized
+ /// surface needs.
+ Future<void> enterAndroidPictureInPicture() async {
+ if (!Platform.isAndroid || !mounted) {
+ return;
+ }
+ final bool supported = await PipUtils.isAndroidPIPSupported();
+ if (!mounted) {
+ return;
+ }
+ if (!supported) {
+ KazumiDialog.showToast(message: '当前设备不支持画中画');
+ return;
+ }
+ setState(() {
+ _pipEnterRequested = true;
+ });
+ await WidgetsBinding.instance.endOfFrame;
+ if (!mounted) {
+ return;
+ }
+ await _updateAndroidPIPActions(force: true);
+ final bool entered = await PipUtils.enterAndroidPIPWindow(
+ width: playerController.debug.playerWidth,
+ height: playerController.debug.playerHeight,
);
+ if (entered || !mounted) {
+ return;
+ }
+ KazumiDialog.showToast(message: '进入画中画失败');
+ setState(() {
+ _pipEnterRequested = false;
+ });
+ }
+
+ void _handleAndroidPIPModeChanged(bool inPipMode) {
+ if (!mounted || videoPageController.isPip == inPipMode) {
+ return;
+ }
+ setState(() {
+ videoPageController.isPip = inPipMode;
+ });
+ if (!inPipMode) {
+ _pipEnterRequested = false;
+ _scheduleAndroidPIPSourceRectSync();
+ }
+ }
+
+ /// Gesture triggered entry uses the rect last handed to the platform.
+ void _scheduleAndroidPIPSourceRectSync() {
+ if (!Platform.isAndroid || _pipSourceRectSyncScheduled) {
+ return;
+ }
+ _pipSourceRectSyncScheduled = true;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ _pipSourceRectSyncScheduled = false;
+ if (!mounted) {
+ return;
+ }
+ unawaited(_updateAndroidPIPActions());
+ });
}
Future<void> _syncPIPAspectWhenVideoSizeReady() async {
@@ -559,6 +678,7 @@ class _PlayerItemState extends State<PlayerItem>
playerController.panel.lockPanel = false;
_releasePlayerPanelHolds();
playerController.danmaku.canvasController.clear();
+ _scheduleAndroidPIPSourceRectSync();
await _syncHistoryWithWebDav();
}
@@ -1268,10 +1388,12 @@ class _PlayerItemState extends State<PlayerItem>
await _updateAndroidPIPActions(force: true);
},
+ onModeChanged: _handleAndroidPIPModeChanged,
);
unawaited(_syncAndroidAutoEnterPIPSetting());
unawaited(_syncAndroidPIPPlayerPageState(true));
unawaited(_updateAndroidPIPActions(force: true));
+ _scheduleAndroidPIPSourceRectSync();
}
WidgetsBinding.instance.addObserver(this);
_panelVisibilityController = AnimationController(
@@ -1404,6 +1526,7 @@ class _PlayerItemState extends State<PlayerItem>
isBlocked: () => _openPlayerMenuCount > 0,
),
Center(
+ key: _videoSurfaceKey,
child: PlayerItemSurface(
playerController: playerController,
),
@@ -1507,63 +1630,72 @@ class _PlayerItemState extends State<PlayerItem>
animation: _screenshotFeedbackAnimation,
),
),
- (needFullPanel(context))
- ? PlayerItemPanel(
- playerController: playerController,
- videoPageController: videoPageController,
- onBackPressed: widget.onBackPressed,
- setPlaybackSpeed: setPlaybackSpeed,
- showDanmakuSwitch: showDanmakuSwitch,
- changeEpisode: widget.changeEpisode,
- toggleMenu: widget.toggleMenu,
- handleFullscreen: handleFullscreen,
- handleProgressBarDragStart:
- handleProgressBarDragStart,
- handleProgressBarSeek: handleProgressBarSeek,
- handleSuperResolutionChange:
- handleSuperResolutionChange,
- handlePreNextEpisode: handlePreNextEpisode,
- panelVisibilityController:
- _panelVisibilityController,
- keyboardFocus: widget.keyboardFocus,
- sendDanmaku: widget.sendDanmaku,
- acquirePlayerPanelHold: acquirePlayerPanelHold,
- onMenuVisibilityChanged:
- _handlePlayerMenuVisibilityChanged,
- handleDanmaku: handleDanmaku,
- showVideoInfo: showVideoInfo,
- showSyncPlayPanel: showSyncPlayPanel,
- showDanmakuDestinationPickerAndSend:
- widget.showDanmakuDestinationPickerAndSend,
- pauseForTimedShutdown: widget.pauseForTimedShutdown,
- disableAnimations: widget.disableAnimations,
- handleScreenShot: handleScreenshot,
- skipOP: skipOP,
- )
- : SmallestPlayerItemPanel(
- playerController: playerController,
- videoPageController: videoPageController,
- onBackPressed: widget.onBackPressed,
- setPlaybackSpeed: setPlaybackSpeed,
- showDanmakuSwitch: showDanmakuSwitch,
- handleFullscreen: handleFullscreen,
- 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,
- ),
+ (Platform.isAndroid &&
+ (videoPageController.isPip || _pipEnterRequested))
+ ? const SizedBox.shrink()
+ : (needFullPanel(context))
+ ? PlayerItemPanel(
+ playerController: playerController,
+ videoPageController: videoPageController,
+ onBackPressed: widget.onBackPressed,
+ setPlaybackSpeed: setPlaybackSpeed,
+ showDanmakuSwitch: showDanmakuSwitch,
+ changeEpisode: widget.changeEpisode,
+ toggleMenu: widget.toggleMenu,
+ handleFullscreen: handleFullscreen,
+ enterAndroidPictureInPicture:
+ enterAndroidPictureInPicture,
+ handleProgressBarDragStart:
+ handleProgressBarDragStart,
+ handleProgressBarSeek: handleProgressBarSeek,
+ handleSuperResolutionChange:
+ handleSuperResolutionChange,
+ handlePreNextEpisode: handlePreNextEpisode,
+ panelVisibilityController:
+ _panelVisibilityController,
+ keyboardFocus: widget.keyboardFocus,
+ sendDanmaku: widget.sendDanmaku,
+ acquirePlayerPanelHold: acquirePlayerPanelHold,
+ onMenuVisibilityChanged:
+ _handlePlayerMenuVisibilityChanged,
+ handleDanmaku: handleDanmaku,
+ showVideoInfo: showVideoInfo,
+ showSyncPlayPanel: showSyncPlayPanel,
+ showDanmakuDestinationPickerAndSend:
+ widget.showDanmakuDestinationPickerAndSend,
+ 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,
+ ),
Positioned.fill(
left: 16,
top: 25,
diff --git a/lib/pages/player/player_item_panel.dart b/lib/pages/player/player_item_panel.dart
index 5542bfb2..6003f1c1 100644
--- a/lib/pages/player/player_item_panel.dart
+++ b/lib/pages/player/player_item_panel.dart
@@ -35,6 +35,7 @@ class PlayerItemPanel extends StatefulWidget {
required this.showDanmakuSwitch,
required this.changeEpisode,
required this.handleFullscreen,
+ required this.enterAndroidPictureInPicture,
required this.handleScreenShot,
required this.handlePreNextEpisode,
required this.handleProgressBarDragStart,
@@ -63,6 +64,7 @@ class PlayerItemPanel extends StatefulWidget {
final Future<void> Function(int, {int currentRoad, int offset}) changeEpisode;
final void Function() toggleMenu;
final void Function() handleFullscreen;
+ final Future<void> Function() enterAndroidPictureInPicture;
final void Function() handleScreenShot;
final VoidCallback handleProgressBarDragStart;
final Future<void> Function(Duration duration) handleProgressBarSeek;
@@ -1010,25 +1012,7 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
videoPageController.isPip = !videoPageController.isPip;
return;
}
- final bool supported =
- await PipUtils.isAndroidPIPSupported();
- if (!supported) {
- KazumiDialog.showToast(message: '当前设备不支持画中画');
- return;
- }
- await PipUtils.updateAndroidPIPActions(
- playing: playerController.playback.playing,
- danmakuEnabled: playerController.danmaku.danmakuOn,
- width: playerController.debug.playerWidth,
- height: playerController.debug.playerHeight,
- );
- final bool entered = await PipUtils.enterAndroidPIPWindow(
- width: playerController.debug.playerWidth,
- height: playerController.debug.playerHeight,
- );
- if (!entered) {
- KazumiDialog.showToast(message: '进入画中画失败');
- }
+ await widget.enterAndroidPictureInPicture();
},
tooltip: '画中画',
icon: const Icon(
diff --git a/lib/pages/player/smallest_player_item_panel.dart b/lib/pages/player/smallest_player_item_panel.dart
index 0e905954..49c21937 100644
--- a/lib/pages/player/smallest_player_item_panel.dart
+++ b/lib/pages/player/smallest_player_item_panel.dart
@@ -31,6 +31,7 @@ class SmallestPlayerItemPanel extends StatefulWidget {
required this.setPlaybackSpeed,
required this.showDanmakuSwitch,
required this.handleFullscreen,
+ required this.enterAndroidPictureInPicture,
required this.handleProgressBarDragStart,
required this.handleProgressBarSeek,
required this.handleSuperResolutionChange,
@@ -53,6 +54,7 @@ class SmallestPlayerItemPanel extends StatefulWidget {
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)
@@ -496,24 +498,7 @@ class _SmallestPlayerItemPanelState extends State<SmallestPlayerItemPanel> {
videoPageController.isPip = !videoPageController.isPip;
return;
}
- final bool supported = await PipUtils.isAndroidPIPSupported();
- if (!supported) {
- KazumiDialog.showToast(message: '当前设备不支持画中画');
- return;
- }
- await PipUtils.updateAndroidPIPActions(
- playing: playerController.playback.playing,
- danmakuEnabled: playerController.danmaku.danmakuOn,
- width: playerController.debug.playerWidth,
- height: playerController.debug.playerHeight,
- );
- final bool entered = await PipUtils.enterAndroidPIPWindow(
- width: playerController.debug.playerWidth,
- height: playerController.debug.playerHeight,
- );
- if (!entered) {
- KazumiDialog.showToast(message: '进入画中画失败');
- }
+ await widget.enterAndroidPictureInPicture();
},
tooltip: '画中画',
icon:
diff --git a/lib/pages/video/video_page.dart b/lib/pages/video/video_page.dart
index b11fd23a..f37c85d1 100644
--- a/lib/pages/video/video_page.dart
+++ b/lib/pages/video/video_page.dart
@@ -27,6 +27,7 @@ import 'package:kazumi/modules/download/download_module.dart';
import 'package:kazumi/services/player/timed_shutdown_service.dart';
import 'package:kazumi/utils/device.dart';
import 'package:kazumi/services/platform/display_mode_service.dart';
+import 'package:mobx/mobx.dart' as mobx;
class VideoPage extends StatefulWidget {
const VideoPage({
@@ -77,6 +78,7 @@ class _VideoPageState extends State<VideoPage>
late final bool disableAnimations;
StreamSubscription<SyncPlayChatMessage>? _syncChatSubscription;
+ late final mobx.ReactionDisposer _pipModeListener;
static const Duration _offlinePlayerInitDelay = Duration(milliseconds: 400);
static const Duration _sideTabAnimationDuration = Duration(milliseconds: 120);
@@ -112,6 +114,32 @@ class _VideoPageState extends State<VideoPage>
playResume = GStorage.getSetting(SettingsKeys.playResume);
disableAnimations =
GStorage.getSetting(SettingsKeys.playerDisableAnimations);
+ _pipModeListener = mobx.reaction<bool>(
+ (_) => videoPageController.isPip,
+ (_) => _syncFullscreenWithWindowShape(),
+ );
+ }
+
+ bool get _windowIsLandscape {
+ final Size window = MediaQuery.sizeOf(context);
+ return window.width > window.height;
+ }
+
+ /// The fullscreen switch has two inputs, the window shape and the picture in
+ /// picture state, and they arrive over different channels in either order, so
+ /// it settles on both. A picture in picture window is not an orientation.
+ 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();
+ }
}
@override
@@ -236,6 +264,7 @@ class _VideoPageState extends State<VideoPage>
try {
_logSubscription?.cancel();
} catch (_) {}
+ _pipModeListener();
// Cancellation and log-stream teardown happen in VideoPageController's
// own dispose when Modular releases the route scope.
if (!isDesktop()) {
@@ -314,8 +343,7 @@ class _VideoPageState extends State<VideoPage>
});
}
- bool get _isSideTabLayout =>
- MediaQuery.sizeOf(context).width > MediaQuery.sizeOf(context).height;
+ bool get _isSideTabLayout => _windowIsLandscape;
bool get _canAnimateSideTab =>
mounted && _isSideTabLayout && !disableAnimations;
@@ -564,8 +592,8 @@ class _VideoPageState extends State<VideoPage>
@override
Widget build(BuildContext context) {
- final bool isLandscape =
- MediaQuery.sizeOf(context).width > MediaQuery.sizeOf(context).height;
+ final bool isLandscape = _windowIsLandscape;
+ _syncFullscreenWithWindowShape();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) {
return;
@@ -580,69 +608,60 @@ class _VideoPageState extends State<VideoPage>
}
onBackPressed(context);
},
- child: OrientationBuilder(builder: (context, orientation) {
- if (!isDesktop()) {
- if (orientation == Orientation.landscape &&
- !videoPageController.isFullscreen) {
- _hideTabBodyImmediately();
- videoPageController.enterFullScreen();
- } else if (orientation == Orientation.portrait &&
- videoPageController.isFullscreen) {
- videoPageController.exitFullScreen();
- _showTabBodyImmediately();
- }
- }
- return Observer(builder: (context) {
- return Scaffold(
- appBar: null,
- body: SafeArea(
- top: !videoPageController.isFullscreen,
- // set iOS and Android navigation bar to immersive
- bottom: false,
- left: !videoPageController.isFullscreen,
- right: !videoPageController.isFullscreen,
- child: Stack(
- alignment: Alignment.centerRight,
- children: [
- Column(
- children: [
- Flexible(
- flex: isLandscape ? 1 : 0,
- child: Container(
- color: Colors.black,
- height: isLandscape
- ? MediaQuery.sizeOf(context).height
- : MediaQuery.sizeOf(context).width * 9 / 16,
- width: MediaQuery.sizeOf(context).width,
- child: Focus(
- focusNode: keyboardFocus,
- autofocus: true,
- child: playerBody,
- ),
+ child: Observer(builder: (context) {
+ final bool isPip = videoPageController.isPip;
+ final bool videoFillsWindow = isLandscape || isPip;
+ return Scaffold(
+ appBar: null,
+ body: SafeArea(
+ top: !videoPageController.isFullscreen && !isPip,
+ // set iOS and Android navigation bar to immersive
+ 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 (!isLandscape) Expanded(child: tabBody),
- ],
- ),
- if (isLandscape && videoPageController.showTabBody) ...[
- if (disableAnimations) ...[
- sideTabMask,
- sideTabBody,
- ] else ...[
- FadeTransition(
- opacity: _maskOpacityAnimation,
- child: sideTabMask,
- ),
- SlideTransition(
- position: _rightOffsetAnimation,
- child: sideTabBody,
- ),
- ],
+ ),
+ 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,
+ ),
],
],
- )),
- );
- });
+ ],
+ )),
+ );
}),
);
}
diff --git a/lib/services/player/pip_utils.dart b/lib/services/player/pip_utils.dart
index 196c5e56..9a1a0426 100644
--- a/lib/services/player/pip_utils.dart
+++ b/lib/services/player/pip_utils.dart
@@ -57,6 +57,7 @@ class PipUtils {
required bool danmakuEnabled,
int width = 16,
int height = 9,
+ Rect? sourceRect,
}) async {
if (!Platform.isAndroid) {
return;
@@ -69,6 +70,12 @@ class PipUtils {
'danmakuEnabled': danmakuEnabled,
'width': aspectSize.width.toInt(),
'height': aspectSize.height.toInt(),
+ if (sourceRect != null) ...{
+ 'sourceLeft': sourceRect.left.round(),
+ 'sourceTop': sourceRect.top.round(),
+ 'sourceRight': sourceRect.right.round(),
+ 'sourceBottom': sourceRect.bottom.round(),
+ },
});
} on PlatformException catch (e) {
KazumiLogger().e("Failed to update Android PIP actions: '${e.message}'.");
@@ -127,21 +134,31 @@ class PipUtils {
static void initPipHandler({
required Future<void> Function(String action) onAction,
+ required void Function(bool inPipMode) onModeChanged,
}) {
const MethodChannel pipChannel = MethodChannel('com.predidit.kazumi/pip');
if (androidPIPInited) return;
androidPIPInited = true;
pipChannel.setMethodCallHandler((call) async {
- if (!Platform.isAndroid || call.method != 'onAction') {
+ if (!Platform.isAndroid) {
return;
}
- final args = call.arguments;
- final String? action = (args is Map) ? args['action'] as String? : null;
+ final Object? args = call.arguments;
+ final Map? arguments = (args is Map) ? args : null;
- if (action != null) {
- await onAction(action);
+ switch (call.method) {
+ case 'onModeChanged':
+ final bool? inPipMode = arguments?['isInPipMode'] as bool?;
+ if (inPipMode != null) {
+ onModeChanged(inPipMode);
+ }
+ case 'onAction':
+ final String? action = arguments?['action'] as String?;
+ if (action != null) {
+ await onAction(action);
+ }
}
});
}