Skip to content

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

refactor(player): scope playback state to the video route and batch mobx updates

Predidit9fa4b9d63c46
diff --git a/lib/bean/card/bangumi_history_card.dart b/lib/bean/card/bangumi_history_card.dart
index e975f74c..6beb91d7 100644
--- a/lib/bean/card/bangumi_history_card.dart
+++ b/lib/bean/card/bangumi_history_card.dart
@@ -8,9 +8,11 @@ import 'package:kazumi/modules/download/download_module.dart';
import 'package:kazumi/modules/history/history_module.dart';
import 'package:kazumi/pages/collect/collect_controller.dart';
import 'package:kazumi/pages/download/download_controller.dart';
-import 'package:kazumi/pages/video/video_controller.dart';
+import 'package:kazumi/pages/video/video_playback_args.dart';
import 'package:kazumi/plugins/plugins.dart';
import 'package:kazumi/plugins/plugins_controller.dart';
+import 'package:kazumi/services/plugin/rule_engine_models.dart'
+ show RuleCancelToken;
import 'package:kazumi/services/logging/logger.dart';
import 'package:kazumi/utils/device.dart';
import 'package:kazumi/utils/date_time.dart';
@@ -21,37 +23,36 @@ String historySourceText(String entryKind) {
: '在线';
}
-Future<HistoryPlaybackOpenResult> openHistoryPlaybackForEntry({
+Future<_HistoryPlaybackOpenResult> _openHistoryPlaybackForEntry({
required String entryKind,
- required Future<bool> Function() openOnlinePlayback,
- required Future<bool> Function() openOfflinePlayback,
+ required Future<VideoPlaybackArgs?> Function() openOnlinePlayback,
+ required Future<VideoPlaybackArgs?> Function() openOfflinePlayback,
}) async {
if (HistoryEntryKind.normalize(entryKind) == HistoryEntryKind.offline) {
- final opened = await openOfflinePlayback();
- return HistoryPlaybackOpenResult(
- opened: opened,
- failureMessage: opened ? null : '未找到可用缓存',
+ final args = await openOfflinePlayback();
+ return _HistoryPlaybackOpenResult(
+ args: args,
+ failureMessage: args != null ? null : '未找到可用缓存',
);
}
- final opened = await openOnlinePlayback();
- return HistoryPlaybackOpenResult(
- opened: opened,
- failureMessage: opened ? null : '在线源不可用,请重新选择播放源',
+ final args = await openOnlinePlayback();
+ return _HistoryPlaybackOpenResult(
+ args: args,
+ failureMessage: args != null ? null : '在线源不可用,请重新选择播放源',
);
}
-class HistoryPlaybackOpenResult {
- const HistoryPlaybackOpenResult({
- required this.opened,
+class _HistoryPlaybackOpenResult {
+ const _HistoryPlaybackOpenResult({
+ required this.args,
required this.failureMessage,
});
- final bool opened;
+ final VideoPlaybackArgs? args;
final String? failureMessage;
}
-// 视频历史记录卡片 - 水平布局
class BangumiHistoryCardV extends StatefulWidget {
const BangumiHistoryCardV({
super.key,
@@ -69,11 +70,18 @@ class BangumiHistoryCardV extends StatefulWidget {
}
class _BangumiHistoryCardVState extends State<BangumiHistoryCardV> {
- final VideoPageController videoPageController = inject<VideoPageController>();
final PluginsController pluginsController = inject<PluginsController>();
final CollectController collectController = inject<CollectController>();
final DownloadController downloadController = inject<DownloadController>();
+ RuleCancelToken? _queryRoadsCancelToken;
+
+ @override
+ void dispose() {
+ _queryRoadsCancelToken?.cancel();
+ super.dispose();
+ }
+
Future<void> _onTap() async {
if (widget.showDelete) {
KazumiDialog.showToast(message: '编辑模式');
@@ -83,26 +91,27 @@ class _BangumiHistoryCardVState extends State<BangumiHistoryCardV> {
msg: '获取中',
barrierDismissible: isDesktop(),
onDismiss: () {
- videoPageController.cancelQueryRoads();
+ _queryRoadsCancelToken?.cancel();
},
);
- final result = await openHistoryPlaybackForEntry(
+ final result = await _openHistoryPlaybackForEntry(
entryKind: widget.historyItem.entryKind,
openOnlinePlayback: _openOnlinePlayback,
openOfflinePlayback: _openOfflinePlayback,
);
KazumiDialog.dismiss();
if (!mounted) return;
- if (result.opened) {
- context.pushNamed('/video/');
+ final args = result.args;
+ if (args != null) {
+ context.pushNamed('/video/', arguments: args);
return;
}
KazumiDialog.showToast(message: result.failureMessage ?? '未找到可用播放入口');
}
- Future<bool> _openOnlinePlayback() async {
+ Future<VideoPlaybackArgs?> _openOnlinePlayback() async {
if (widget.historyItem.lastSrc.isEmpty) {
- return false;
+ return null;
}
Plugin? targetPlugin;
for (Plugin plugin in pluginsController.pluginList) {
@@ -112,33 +121,40 @@ class _BangumiHistoryCardVState extends State<BangumiHistoryCardV> {
}
}
if (targetPlugin == null) {
- return false;
+ return null;
}
- videoPageController.bangumiItem = widget.historyItem.bangumiItem;
- videoPageController.currentPlugin = targetPlugin;
- videoPageController.title = widget.historyItem.bangumiItem.nameCn == ''
- ? widget.historyItem.bangumiItem.name
- : widget.historyItem.bangumiItem.nameCn;
- videoPageController.src = widget.historyItem.lastSrc;
try {
- await videoPageController.queryRoads(
+ _queryRoadsCancelToken?.cancel();
+ _queryRoadsCancelToken = RuleCancelToken();
+ final roads = await targetPlugin.queryChapterRoads(
widget.historyItem.lastSrc,
- targetPlugin.name,
+ cancelToken: _queryRoadsCancelToken,
+ );
+ if (roads.isEmpty) {
+ return null;
+ }
+ return OnlineVideoPlaybackArgs(
+ bangumiItem: widget.historyItem.bangumiItem,
+ plugin: targetPlugin,
+ title: widget.historyItem.bangumiItem.nameCn == ''
+ ? widget.historyItem.bangumiItem.name
+ : widget.historyItem.bangumiItem.nameCn,
+ src: widget.historyItem.lastSrc,
+ roads: roads,
);
- return true;
} catch (_) {
KazumiLogger().w("QueryManager: failed to query roads");
- return false;
+ return null;
}
}
- Future<bool> _openOfflinePlayback() async {
+ Future<VideoPlaybackArgs?> _openOfflinePlayback() async {
final downloadedEpisodes = downloadController.getCompletedEpisodes(
widget.historyItem.bangumiItem.id,
widget.historyItem.adapterName,
);
if (downloadedEpisodes.isEmpty) {
- return false;
+ return null;
}
DownloadEpisode? targetEpisode;
@@ -155,7 +171,7 @@ class _BangumiHistoryCardVState extends State<BangumiHistoryCardV> {
widget.historyItem.lastWatchEpisode,
);
if (targetEpisode == null) {
- return false;
+ return null;
}
final localPath = downloadController.getLocalVideoPath(
@@ -164,17 +180,16 @@ class _BangumiHistoryCardVState extends State<BangumiHistoryCardV> {
targetEpisode.episodeNumber,
);
if (localPath == null) {
- return false;
+ return null;
}
- videoPageController.initForOfflinePlayback(
+ return OfflineVideoPlaybackArgs(
bangumiItem: widget.historyItem.bangumiItem,
pluginName: widget.historyItem.adapterName,
episodeNumber: targetEpisode.episodeNumber,
road: targetEpisode.road,
downloadedEpisodes: downloadedEpisodes,
);
- return true;
}
DownloadEpisode? _episodeByNumber(
diff --git a/lib/core_module.dart b/lib/core_module.dart
index ef137dfb..264d2679 100644
--- a/lib/core_module.dart
+++ b/lib/core_module.dart
@@ -3,7 +3,6 @@ import 'package:kazumi/pages/collect/collect_controller.dart';
import 'package:kazumi/pages/download/download_controller.dart';
import 'package:kazumi/pages/history/history_controller.dart';
import 'package:kazumi/pages/my/my_controller.dart';
-import 'package:kazumi/pages/video/video_controller.dart';
import 'package:kazumi/plugins/plugins_controller.dart';
import 'package:kazumi/repositories/collect_crud_repository.dart';
import 'package:kazumi/repositories/collect_repository.dart';
@@ -37,7 +36,6 @@ final coreModule = createModule(
..addSingleton<CollectController>(CollectController.new)
..addSingleton<HistoryController>(HistoryController.new)
..addSingleton<MyController>(MyController.new)
- ..addSingleton<DownloadController>(DownloadController.new)
- ..addSingleton<VideoPageController>(VideoPageController.new);
+ ..addSingleton<DownloadController>(DownloadController.new);
},
);
diff --git a/lib/modules/history/history_module.g.dart b/lib/modules/history/history_module.g.dart
index f2a98336..b4a25b44 100644
--- a/lib/modules/history/history_module.g.dart
+++ b/lib/modules/history/history_module.g.dart
@@ -23,9 +23,7 @@ class HistoryAdapter extends TypeAdapter<History> {
fields[4] as DateTime,
fields[5] as String,
fields[6] == null ? '' : fields[6] as String,
- entryKind: fields[7] == null
- ? HistoryEntryKind.online
- : fields[7] as String,
+ entryKind: fields[7] == null ? 'online' : fields[7] as String,
episodePageUrl: fields[8] == null ? '' : fields[8] as String,
)..progresses = (fields[0] as Map).cast<int, Progress>();
}
diff --git a/lib/pages/download/download_episode_sheet.dart b/lib/pages/download/download_episode_sheet.dart
index ea8461d0..a28aac72 100644
--- a/lib/pages/download/download_episode_sheet.dart
+++ b/lib/pages/download/download_episode_sheet.dart
@@ -8,15 +8,20 @@ import 'package:kazumi/pages/video/video_controller.dart';
class DownloadEpisodeSheet extends StatefulWidget {
final int road;
+ final VideoPageController videoPageController;
- const DownloadEpisodeSheet({super.key, required this.road});
+ const DownloadEpisodeSheet({
+ super.key,
+ required this.road,
+ required this.videoPageController,
+ });
@override
State<DownloadEpisodeSheet> createState() => _DownloadEpisodeSheetState();
}
class _DownloadEpisodeSheetState extends State<DownloadEpisodeSheet> {
- final VideoPageController videoPageController = inject<VideoPageController>();
+ VideoPageController get videoPageController => widget.videoPageController;
final DownloadController downloadController = inject<DownloadController>();
final Set<int> _selectedEpisodes = {};
@@ -51,7 +56,6 @@ class _DownloadEpisodeSheetState extends State<DownloadEpisodeSheet> {
builder: (context, scrollController) {
return Column(
children: [
- // Header
Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
child: Row(
@@ -71,7 +75,6 @@ class _DownloadEpisodeSheetState extends State<DownloadEpisodeSheet> {
],
),
),
- // Select all / deselect all
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row(
diff --git a/lib/pages/download/download_page.dart b/lib/pages/download/download_page.dart
index 1461fc42..9d4f3061 100644
--- a/lib/pages/download/download_page.dart
+++ b/lib/pages/download/download_page.dart
@@ -6,7 +6,7 @@ import 'package:kazumi/bean/dialog/dialog_helper.dart';
import 'package:kazumi/modules/download/download_module.dart';
import 'package:kazumi/modules/bangumi/bangumi_item.dart';
import 'package:kazumi/pages/download/download_controller.dart';
-import 'package:kazumi/pages/video/video_controller.dart';
+import 'package:kazumi/pages/video/video_playback_args.dart';
import 'package:kazumi/utils/format.dart';
class DownloadPage extends StatefulWidget {
@@ -373,16 +373,16 @@ class _DownloadPageState extends State<DownloadPage> {
record.pluginName,
);
- final videoPageController = inject<VideoPageController>();
- videoPageController.initForOfflinePlayback(
- bangumiItem: bangumiItem,
- pluginName: record.pluginName,
- episodeNumber: episode.episodeNumber,
- road: episode.road,
- downloadedEpisodes: downloadedEpisodes,
+ context.pushNamed(
+ '/video/',
+ arguments: OfflineVideoPlaybackArgs(
+ bangumiItem: bangumiItem,
+ pluginName: record.pluginName,
+ episodeNumber: episode.episodeNumber,
+ road: episode.road,
+ downloadedEpisodes: downloadedEpisodes,
+ ),
);
-
- context.pushNamed('/video/');
}
void _confirmDeleteEpisode(DownloadRecord record, DownloadEpisode episode) {
diff --git a/lib/pages/info/info_module.dart b/lib/pages/info/info_module.dart
index 2794b4f7..94062d81 100644
--- a/lib/pages/info/info_module.dart
+++ b/lib/pages/info/info_module.dart
@@ -3,7 +3,6 @@ import 'package:kazumi/modules/bangumi/bangumi_item.dart';
import 'package:kazumi/pages/info/info_controller.dart';
import 'package:kazumi/pages/info/info_page.dart';
import 'package:kazumi/pages/route_error_page.dart';
-import 'package:kazumi/pages/video/video_controller.dart';
import 'package:kazumi/plugins/plugins_controller.dart';
final infoModule = createModule(
@@ -20,7 +19,6 @@ final infoModule = createModule(
return InfoPage(
inputBangumiItem: bangumiItem,
infoController: context.read<InfoController>(),
- videoPageController: inject<VideoPageController>(),
pluginsController: inject<PluginsController>(),
);
},
diff --git a/lib/pages/info/info_page.dart b/lib/pages/info/info_page.dart
index 870f36fd..0faea409 100644
--- a/lib/pages/info/info_page.dart
+++ b/lib/pages/info/info_page.dart
@@ -12,7 +12,6 @@ import 'package:kazumi/pages/info/info_controller.dart';
import 'package:kazumi/bean/card/bangumi_info_card.dart';
import 'package:kazumi/pages/info/source_sheet.dart';
import 'package:kazumi/plugins/plugins_controller.dart';
-import 'package:kazumi/pages/video/video_controller.dart';
import 'package:kazumi/bean/card/network_img_layer.dart';
import 'package:kazumi/services/logging/logger.dart';
import 'package:kazumi/pages/info/info_tabview.dart';
@@ -28,13 +27,11 @@ class InfoPage extends StatefulWidget {
super.key,
required this.inputBangumiItem,
required this.infoController,
- required this.videoPageController,
required this.pluginsController,
});
final BangumiItem inputBangumiItem;
final InfoController infoController;
- final VideoPageController videoPageController;
final PluginsController pluginsController;
@override
@@ -54,7 +51,6 @@ class _InfoPageState extends State<InfoPage> with TickerProviderStateMixin {
Duration(milliseconds: 600);
InfoController get infoController => widget.infoController;
- VideoPageController get videoPageController => widget.videoPageController;
PluginsController get pluginsController => widget.pluginsController;
late TabController sourceTabController;
late TabController infoTabController;
@@ -210,7 +206,6 @@ class _InfoPageState extends State<InfoPage> with TickerProviderStateMixin {
infoController.clearComments();
infoController.staffList.clear();
infoController.pluginSearchResponseList.clear();
- videoPageController.resetEpisodeState();
// Search results can miss rating distribution or summaries, so fill those
// fields without replacing image URLs that are already rendered.
if (_needsBangumiInfoRefresh(infoController.bangumiItem)) {
@@ -295,7 +290,6 @@ class _InfoPageState extends State<InfoPage> with TickerProviderStateMixin {
infoController.clearComments();
infoController.staffList.clear();
infoController.pluginSearchResponseList.clear();
- videoPageController.resetEpisodeState();
sourceTabController.dispose();
infoTabController.dispose();
super.dispose();
diff --git a/lib/pages/info/source_sheet.dart b/lib/pages/info/source_sheet.dart
index 0c20b993..554fc626 100644
--- a/lib/pages/info/source_sheet.dart
+++ b/lib/pages/info/source_sheet.dart
@@ -6,7 +6,9 @@ import 'package:kazumi/services/logging/logger.dart';
import 'package:kazumi/bean/dialog/dialog_helper.dart';
import 'package:kazumi/plugins/plugins_controller.dart';
import 'package:kazumi/plugins/plugins.dart';
-import 'package:kazumi/pages/video/video_controller.dart';
+import 'package:kazumi/pages/video/video_playback_args.dart';
+import 'package:kazumi/services/plugin/rule_engine_models.dart'
+ show RuleCancelToken;
import 'package:url_launcher/url_launcher.dart';
import 'package:kazumi/services/plugin/plugin_search_service.dart';
import 'package:kazumi/pages/collect/collect_controller.dart';
@@ -33,7 +35,6 @@ class SourceSheet extends StatefulWidget {
class _SourceSheetState extends State<SourceSheet>
with SingleTickerProviderStateMixin {
- final VideoPageController videoPageController = inject<VideoPageController>();
final CollectController collectController = inject<CollectController>();
final PluginsController pluginsController = inject<PluginsController>();
late String keyword;
@@ -71,7 +72,6 @@ class _SourceSheetState extends State<SourceSheet>
super.dispose();
}
- /// 根据插件的验证类型分发到对应的验证对话框
void showAntiCrawlerDialog(Plugin plugin) {
switch (plugin.antiCrawlerConfig.captchaType) {
case CaptchaType.customJavaScript:
@@ -345,7 +345,8 @@ class _SourceSheetState extends State<SourceSheet>
);
}
- /// 构建结果列表底部补充检索入口,便于已有结果不准确时换用别名或手动检索关键词
+ /// Fallback search entry under the result list, for when the default
+ /// keyword produced inaccurate matches.
Widget showSupplementarySearchEntry(String pluginName) {
return SafeArea(
top: false,
@@ -575,24 +576,34 @@ class _SourceSheetState extends State<SourceSheet>
child: InkWell(
borderRadius: BorderRadius.circular(12),
onTap: () async {
+ final cancelToken = RuleCancelToken();
KazumiDialog.showLoading(
msg: '获取中',
barrierDismissible: isDesktop(),
- onDismiss: () {
- videoPageController.cancelQueryRoads();
- },
+ onDismiss: cancelToken.cancel,
);
- videoPageController.bangumiItem =
- widget.infoController.bangumiItem;
- videoPageController.currentPlugin = plugin;
- videoPageController.title = searchItem.name;
- videoPageController.src = searchItem.src;
try {
- await videoPageController.queryRoads(
- searchItem.src, plugin.name);
+ final roads =
+ await plugin.queryChapterRoads(
+ searchItem.src,
+ cancelToken: cancelToken,
+ );
+ if (roads.isEmpty) {
+ throw ChapterErrorException(plugin.name);
+ }
KazumiDialog.dismiss();
if (!mounted) return;
- this.context.pushNamed('/video/');
+ this.context.pushNamed(
+ '/video/',
+ arguments: OnlineVideoPlaybackArgs(
+ bangumiItem: widget
+ .infoController.bangumiItem,
+ plugin: plugin,
+ title: searchItem.name,
+ src: searchItem.src,
+ roads: roads,
+ ),
+ );
} catch (_) {
KazumiLogger().w(
"PluginSearchService: failed to query video playlist");
diff --git a/lib/pages/player/player_item.dart b/lib/pages/player/player_item.dart
index 1f8d0e20..aa334d9f 100644
--- a/lib/pages/player/player_item.dart
+++ b/lib/pages/player/player_item.dart
@@ -23,7 +23,6 @@ import 'package:kazumi/bean/dialog/adaptive_bottom_sheet.dart';
import 'package:kazumi/bean/dialog/dialog_helper.dart';
import 'package:screen_brightness_platform_interface/screen_brightness_platform_interface.dart';
import 'package:kazumi/pages/history/history_controller.dart';
-import 'package:kazumi/pages/collect/collect_controller.dart';
import 'package:kazumi/services/storage/storage.dart';
import 'package:kazumi/request/apis/danmaku_api.dart';
import 'package:kazumi/modules/danmaku/danmaku_search_response.dart';
@@ -43,6 +42,7 @@ class PlayerItem extends StatefulWidget {
const PlayerItem({
super.key,
required this.playerController,
+ required this.videoPageController,
required this.toggleMenu,
required this.showMenuImmediately,
required this.hideMenuImmediately,
@@ -56,6 +56,7 @@ class PlayerItem extends StatefulWidget {
});
final PlayerController playerController;
+ final VideoPageController videoPageController;
final VoidCallback toggleMenu;
final VoidCallback showMenuImmediately;
final VoidCallback hideMenuImmediately;
@@ -75,25 +76,18 @@ class PlayerItem extends StatefulWidget {
class _PlayerItemState extends State<PlayerItem>
with WindowListener, WidgetsBindingObserver, TickerProviderStateMixin {
late final PlayerController playerController;
- final VideoPageController videoPageController = inject<VideoPageController>();
+ late final VideoPageController videoPageController =
+ widget.videoPageController;
final HistoryController historyController = inject<HistoryController>();
- final CollectController collectController = inject<CollectController>();
final MyController myController = inject<MyController>();
AudioController get _audioController => playerController.audioController;
late Map<String, List<String>> keyboardShortcuts;
late List<String> keyboardActionsNeedLongPress;
late Map<String, void Function()> keyboardActions;
- // 1. 在看
- // 2. 想看
- // 3. 搁置
- // 4. 看过
- // 5. 抛弃
- late int collectType;
late bool webDavEnable;
late bool webDavEnableHistory;
- // 弹幕
final _danmuKey = GlobalKey();
late bool _border;
late double _opacity;
@@ -113,13 +107,12 @@ class _PlayerItemState extends State<PlayerItem>
late bool _danmakuUseSystemFont;
late double _danmakuBorderSize;
- // 硬件解码
late bool haEnable;
late bool autoPlayNext;
late bool backgroundPlayback;
late bool brightnessVolumeGesture;
- // 播放器控制面板无交互后自动隐藏所需时间 (单位:毫秒)
+ /// Idle timeout before the player panel auto-hides, in milliseconds.
late int playerControllerLayerDisappearTime;
Timer? hideTimer;
@@ -137,14 +130,14 @@ class _PlayerItemState extends State<PlayerItem>
double lastPlayerSpeed = 1.0;
late double longPressPlaySpeed;
- int episodeNum = 0;
bool? _lastPipPlaying;
bool? _lastPipDanmakuEnabled;
late mobx.ReactionDisposer _playerSizeListener;
late mobx.ReactionDisposer _fullscreenListener;
- /// 处理 Android/iOS 应用后台或熄屏
+ /// Pauses playback when the app is backgrounded on Android/iOS, unless
+ /// background playback is enabled.
@override
void didChangeAppLifecycleState(AppLifecycleState state) async {
super.didChangeAppLifecycleState(state);
@@ -244,9 +237,7 @@ class _PlayerItemState extends State<PlayerItem>
}
void _initKeyboardActions() {
- //需要实现长按的功能列表。
keyboardActionsNeedLongPress = ["forward"];
- //快捷键功能对应表
keyboardActions = {
'playorpause': () => playerController.playOrPause(),
'forward': () async => handleShortcutForwardDown(),
@@ -266,24 +257,21 @@ class _PlayerItemState extends State<PlayerItem>
'speed3': () async => setPlaybackSpeed(3.0),
'speedup': () async => handleSpeedChange('up'),
'speeddown': () async => handleSpeedChange('down'),
- // 开始对应长按功能
- // 如需对应长按功能,例如对功能'func'对应长按,请分别添加'funcRepeat'和'funcUp'。
+ // Long-press support for action 'func' requires paired entries named
+ // 'funcRepeat' and 'funcUp'.
'forwardRepeat': () async => handleShortcutForwardRepeat(),
'forwardUp': () async => handleShortcutForwardUp(),
};
}
- //初始化播放器菜单
void _initPlayerMenu() {
PlayerMenuService.initialize(keyboardActions);
}
- //销毁播放器菜单
void _disposePlayerMenu() {
PlayerMenuService.dispose();
}
- //快捷键按下
bool handleShortcutDown(String keyLabel) {
for (final entry in keyboardShortcuts.entries) {
final func = entry.key;
@@ -299,7 +287,6 @@ class _PlayerItemState extends State<PlayerItem>
return false;
}
- // 快捷键长按
bool handleShortcutLongPress(String keyLabel, String mode) {
for (final func in keyboardActionsNeedLongPress) {
final keys = keyboardShortcuts[func];
@@ -314,7 +301,6 @@ class _PlayerItemState extends State<PlayerItem>
return false;
}
- //上一集下一集动作
Future<void> handlePreNextEpisode(String direction) async {
if (videoPageController.loading) return;
final selection = videoPageController.selectedEpisode;
@@ -342,12 +328,12 @@ class _PlayerItemState extends State<PlayerItem>
episode: targetEpisode,
road: currentRoad,
);
+ // Resolution failures surface through the controller's failed state;
+ // the toast here is progress feedback only.
final targetRef = videoPageController.resolveEpisode(targetSelection);
- if (targetRef == null) {
- KazumiDialog.showToast(message: '集数解析失败');
- return;
+ if (targetRef != null) {
+ KazumiDialog.showToast(message: '正在加载${targetRef.displayTitle}');
}
- KazumiDialog.showToast(message: '正在加载${targetRef.displayTitle}');
widget.changeEpisode(targetEpisode, currentRoad: currentRoad);
}
@@ -394,12 +380,10 @@ class _PlayerItemState extends State<PlayerItem>
}
}
- //全屏快捷键动作
void handleShortcutFullscreen() {
if (!videoPageController.isPip) handleFullscreen();
}
- //退出全屏快捷键动作
void handleShortcutExitFullscreen() {
if (videoPageController.isFullscreen && !isTablet()) {
try {
@@ -672,7 +656,6 @@ class _PlayerItemState extends State<PlayerItem>
}
}
- //截图
Future<void> handleScreenshot() async {
_playScreenshotFeedback();
@@ -712,7 +695,7 @@ class _PlayerItemState extends State<PlayerItem>
Future<void> handleSuperResolutionChange(SuperResolutionMode mode) async {
if (!mounted) return;
- // mediacodec_embed 不支持超分辨率
+ // The mediacodec_embed renderer cannot apply super-resolution shaders.
if (Platform.isAndroid && mode != SuperResolutionMode.off) {
final String androidVideoRenderer =
GStorage.getSetting(SettingsKeys.androidVideoRenderer);
@@ -1033,14 +1016,12 @@ class _PlayerItemState extends State<PlayerItem>
unawaited(_updateAndroidPIPActions());
_syncAudioServiceState();
_emitDanmakusForCurrentPosition();
- // 音量相关
if (!playerController.panel.volumeSeeking) {
if (isDesktop()) {
playerController.playback
.applyExternalVolume(playerController.playback.playerVolume);
}
}
- // 亮度相关
if (!Platform.isWindows &&
!Platform.isMacOS &&
!Platform.isLinux &&
@@ -1050,7 +1031,6 @@ class _PlayerItemState extends State<PlayerItem>
playerController.panel.brightness = value;
});
}
- // 历史记录相关
final historyIdentity = videoPageController.currentHistoryIdentity;
if (playerController.playback.playerPlaying &&
!videoPageController.loading &&
@@ -1061,7 +1041,6 @@ class _PlayerItemState extends State<PlayerItem>
playerController.playback.playerPosition,
);
}
- // 自动播放下一集
final playingSelection = videoPageController.playbackEpisode;
final playingRoadData =
videoPageController.roadList[playingSelection.road];
@@ -1073,18 +1052,18 @@ class _PlayerItemState extends State<PlayerItem>
episode: playingSelection.episode + 1,
road: playingSelection.road,
);
+ // Resolution failures surface through the controller's failed state
+ // instead of silently retrying here every second.
final nextRef = videoPageController.resolveEpisode(nextSelection);
- if (nextRef == null) {
- return;
+ if (nextRef != null) {
+ KazumiDialog.showToast(message: '正在加载${nextRef.displayTitle}');
}
- KazumiDialog.showToast(message: '正在加载${nextRef.displayTitle}');
try {
playerTimer!.cancel();
} catch (_) {}
widget.changeEpisode(playingSelection.episode + 1,
currentRoad: playingSelection.road);
}
- // 一起去看相关
playerController.setSyncPlayCurrentPosition();
});
}
@@ -1183,7 +1162,6 @@ class _PlayerItemState extends State<PlayerItem>
});
}
- // 弹幕查询
void showDanmakuSwitch() {
String searchKeyword = videoPageController.title;
KazumiDialog.show(
@@ -1770,8 +1748,6 @@ class _PlayerItemState extends State<PlayerItem>
@override
Widget build(BuildContext context) {
- collectType =
- collectController.getCollectType(videoPageController.bangumiItem);
return Observer(
builder: (context) {
return ClipRect(
@@ -1901,7 +1877,6 @@ class _PlayerItemState extends State<PlayerItem>
height: double.infinity,
),
),
- // 弹幕面板
Positioned(
top: 0,
left: 0,
@@ -1942,10 +1917,10 @@ class _PlayerItemState extends State<PlayerItem>
animation: _screenshotFeedbackAnimation,
),
),
- // 播放器控制面板
(needFullPanel(context))
? PlayerItemPanel(
playerController: playerController,
+ videoPageController: videoPageController,
onBackPressed: widget.onBackPressed,
setPlaybackSpeed: setPlaybackSpeed,
showDanmakuSwitch: showDanmakuSwitch,
@@ -1978,6 +1953,7 @@ class _PlayerItemState extends State<PlayerItem>
)
: SmallestPlayerItemPanel(
playerController: playerController,
+ videoPageController: videoPageController,
onBackPressed: widget.onBackPressed,
setPlaybackSpeed: setPlaybackSpeed,
showDanmakuSwitch: showDanmakuSwitch,
@@ -2001,7 +1977,6 @@ class _PlayerItemState extends State<PlayerItem>
disableAnimations: widget.disableAnimations,
skipOP: skipOP,
),
- // 播放器手势控制
Positioned.fill(
left: 16,
top: 25,
@@ -2056,7 +2031,7 @@ class _PlayerItemState extends State<PlayerItem>
final double delta = details.delta.dy;
if (tapPosition < sectionWidth) {
- // 左边区域
+ // Left half adjusts brightness.
playerController.panel.brightnessSeeking =
true;
_showBrightnessAdjustmentHud();
@@ -2069,7 +2044,7 @@ class _PlayerItemState extends State<PlayerItem>
setBrightness(result);
playerController.panel.brightness = result;
} else {
- // 右边区域
+ // Right half adjusts volume.
_showVolumeAdjustmentHud();
if (!playerController.panel.volumeSeeking) {
playerController.panel.volumeSeeking = true;
diff --git a/lib/pages/player/player_item_panel.dart b/lib/pages/player/player_item_panel.dart
index 538211df..b5439d1f 100644
--- a/lib/pages/player/player_item_panel.dart
+++ b/lib/pages/player/player_item_panel.dart
@@ -19,7 +19,6 @@ import 'package:kazumi/services/player/remote.dart';
import 'package:kazumi/bean/appbar/drag_to_move_bar.dart' as dtb;
import 'package:kazumi/pages/settings/danmaku/danmaku_settings_sheet.dart';
import 'package:kazumi/utils/constants.dart';
-import 'package:kazumi/services/storage/storage.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';
@@ -30,6 +29,7 @@ class PlayerItemPanel extends StatefulWidget {
const PlayerItemPanel({
super.key,
required this.playerController,
+ required this.videoPageController,
required this.onBackPressed,
required this.setPlaybackSpeed,
required this.showDanmakuSwitch,
@@ -56,6 +56,7 @@ class PlayerItemPanel extends StatefulWidget {
});
final PlayerController playerController;
+ final VideoPageController videoPageController;
final void Function(BuildContext) onBackPressed;
final Future<void> Function(double) setPlaybackSpeed;
final void Function() showDanmakuSwitch;
@@ -86,18 +87,17 @@ class PlayerItemPanel extends StatefulWidget {
}
class _PlayerItemPanelState extends State<PlayerItemPanel> {
- late bool haEnable;
late Animation<Offset> topOffsetAnimation;
late Animation<Offset> bottomOffsetAnimation;
late Animation<Offset> leftOffsetAnimation;
- final VideoPageController videoPageController = inject<VideoPageController>();
+ 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;
- // SVG Caches
String? cachedSvgString;
Widget? cachedDanmakuOnIcon;
Widget? cachedDanmakuOffIcon;
@@ -210,7 +210,6 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
});
}
- // 选择倍速
void showSetSpeedSheet() {
final double currentSpeed = playerController.playback.playerSpeed;
KazumiDialog.show(builder: (context) {
@@ -272,11 +271,10 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
builder: (BuildContext context, StateSetter setState) {
return TextField(
inputFormatters: [
- FilteringTextInputFormatter.digitsOnly, // 只允许输入数字
+ FilteringTextInputFormatter.digitsOnly,
],
decoration: InputDecoration(
- floatingLabelBehavior:
- FloatingLabelBehavior.never, // 控制label的显示方式
+ floatingLabelBehavior: FloatingLabelBehavior.never,
labelText: playerController.playback.buttonSkipTime.toString(),
),
onChanged: (value) {
@@ -333,7 +331,6 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
parent: widget.panelVisibilityController,
curve: Curves.easeInOut,
));
- haEnable = GStorage.getSetting(SettingsKeys.hAenable);
cacheSvgIcons();
}
@@ -515,11 +512,19 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
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: playerController.panel.showSeekTime,
- currentPosition: playerController.playback.currentPosition,
- playerPosition: playerController.playback.playerPosition,
- duration: playerController.playback.duration,
+ 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,
);
@@ -625,43 +630,50 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
+ // Position reads stay inside these narrow Observers so the 1s
+ // progress tick rebuilds only the bar and time text, not the
+ // whole bottom bar.
if (!isDesktop() && !isTablet())
Container(
padding: const EdgeInsets.only(left: 10.0, bottom: 10),
- child: Text(
- "${durationToString(playerController.playback.currentPosition)} / ${durationToString(playerController.playback.duration)}",
- style: const TextStyle(
+ 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(),
+ ],
+ ),
+ );
+ }),
+ ),
+ 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(),
],
),
- ),
- ),
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: 10),
- child: 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),
- ),
+ 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),
@@ -675,7 +687,6 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
playing: playerController.playback.playing,
),
),
- // 更换选集
if (videoPageController.isFullscreen ||
isTablet() ||
isDesktop())
@@ -688,16 +699,18 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
if (isDesktop())
Container(
padding: const EdgeInsets.only(left: 10.0),
- child: Text(
- "${durationToString(playerController.playback.currentPosition)} / ${durationToString(playerController.playback.duration)}",
- style: const TextStyle(
- color: Colors.white,
- fontSize: 16.0,
- fontFeatures: [
- FontFeature.tabularFigures(),
- ],
- ),
- ),
+ 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(
@@ -767,7 +780,6 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
],
if (!playerController.danmaku.danmakuOn) const Spacer(),
],
- // 超分辨率
PlayerPanelHoldMenuAnchor(
acquirePlayerPanelHold: widget.acquirePlayerPanelHold,
consumeOutsideTap: true,
@@ -812,7 +824,6 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
),
],
),
- // 倍速播放
PlayerPanelHoldMenuAnchor(
acquirePlayerPanelHold: widget.acquirePlayerPanelHold,
consumeOutsideTap: true,
@@ -967,7 +978,6 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
widget.onBackPressed(context);
},
),
- // 拖动条
Expanded(
child: dtb.DragToMoveArea(
child: Text(
@@ -981,7 +991,6 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
),
),
),
- // 跳过
forwardIcon(),
if ((isDesktop() && !videoPageController.isFullscreen) ||
Platform.isAndroid)
@@ -1025,7 +1034,6 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
color: Colors.white,
),
),
- // 追番
PlayerPanelHoldCollectButton(
acquirePlayerPanelHold: widget.acquirePlayerPanelHold,
bangumiItem: videoPageController.bangumiItem,
@@ -1112,7 +1120,6 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
),
),
),
- // 定时关闭
SubmenuButton(
menuChildren: [
MenuItemButton(
diff --git a/lib/pages/player/smallest_player_item_panel.dart b/lib/pages/player/smallest_player_item_panel.dart
index 1946a661..09ce406f 100644
--- a/lib/pages/player/smallest_player_item_panel.dart
+++ b/lib/pages/player/smallest_player_item_panel.dart
@@ -1,7 +1,6 @@
import 'dart:io';
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';
@@ -16,7 +15,6 @@ 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/services/storage/storage.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';
@@ -28,6 +26,7 @@ class SmallestPlayerItemPanel extends StatefulWidget {
const SmallestPlayerItemPanel({
super.key,
required this.playerController,
+ required this.videoPageController,
required this.onBackPressed,
required this.setPlaybackSpeed,
required this.showDanmakuSwitch,
@@ -48,6 +47,7 @@ class SmallestPlayerItemPanel extends StatefulWidget {
});
final PlayerController playerController;
+ final VideoPageController videoPageController;
final void Function(BuildContext) onBackPressed;
final Future<void> Function(double) setPlaybackSpeed;
final void Function() showDanmakuSwitch;
@@ -73,15 +73,12 @@ class SmallestPlayerItemPanel extends StatefulWidget {
}
class _SmallestPlayerItemPanelState extends State<SmallestPlayerItemPanel> {
- late bool haEnable;
late Animation<Offset> topOffsetAnimation;
late Animation<Offset> bottomOffsetAnimation;
- late Animation<Offset> leftOffsetAnimation;
- final VideoPageController videoPageController = inject<VideoPageController>();
+ late final VideoPageController videoPageController =
+ widget.videoPageController;
late final PlayerController playerController;
- final TextEditingController textController = TextEditingController();
- // SVG Caches
String? cachedSvgString;
Widget? cachedDanmakuOnIcon;
Widget? cachedDanmakuOffIcon;
@@ -89,12 +86,6 @@ class _SmallestPlayerItemPanelState extends State<SmallestPlayerItemPanel> {
static const double _danmakuIconSize = 24.0;
static const double _loadingIndicatorStrokeWidth = 2.0;
- @override
- void dispose() {
- textController.dispose();
- super.dispose();
- }
-
void showForwardChange() {
KazumiDialog.show(builder: (context) {
String input = "";
@@ -104,11 +95,10 @@ class _SmallestPlayerItemPanelState extends State<SmallestPlayerItemPanel> {
builder: (BuildContext context, StateSetter setState) {
return TextField(
inputFormatters: [
- FilteringTextInputFormatter.digitsOnly, // 只允许输入数字
+ FilteringTextInputFormatter.digitsOnly,
],
decoration: InputDecoration(
- floatingLabelBehavior:
- FloatingLabelBehavior.never, // 控制label的显示方式
+ floatingLabelBehavior: FloatingLabelBehavior.never,
labelText: playerController.playback.buttonSkipTime.toString(),
),
onChanged: (value) {
@@ -158,14 +148,6 @@ class _SmallestPlayerItemPanelState extends State<SmallestPlayerItemPanel> {
parent: widget.panelVisibilityController,
curve: Curves.easeInOut,
));
- 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,
- ));
- haEnable = GStorage.getSetting(SettingsKeys.hAenable);
cacheSvgIcons();
}
@@ -340,11 +322,19 @@ class _SmallestPlayerItemPanelState extends State<SmallestPlayerItemPanel> {
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: playerController.panel.showSeekTime,
- currentPosition: playerController.playback.currentPosition,
- playerPosition: playerController.playback.playerPosition,
- duration: playerController.playback.duration,
+ 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,
);
@@ -429,30 +419,36 @@ class _SmallestPlayerItemPanelState extends State<SmallestPlayerItemPanel> {
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: 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),
- ),
- ),
- Text(
- " ${durationToString(playerController.playback.currentPosition)} / ${durationToString(playerController.playback.duration)}",
- style: const TextStyle(
- color: Colors.white,
- fontSize: 12.0,
- fontFeatures: [
- FontFeature.tabularFigures(),
- ],
- ),
+ 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,
@@ -481,11 +477,9 @@ class _SmallestPlayerItemPanelState extends State<SmallestPlayerItemPanel> {
widget.onBackPressed(context);
},
),
- // 拖动条
const Expanded(
child: dtb.DragToMoveArea(child: SizedBox(height: 40)),
),
- // 跳过
forwardIcon(),
if (isDesktop() || Platform.isAndroid)
IconButton(
@@ -494,7 +488,8 @@ class _SmallestPlayerItemPanelState extends State<SmallestPlayerItemPanel> {
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,
@@ -525,9 +520,7 @@ class _SmallestPlayerItemPanelState extends State<SmallestPlayerItemPanel> {
tooltip: '画中画',
icon:
const Icon(Icons.picture_in_picture, color: Colors.white)),
- // 弹幕开关
_buildDanmakuToggleButton(context),
- // 追番
PlayerPanelHoldCollectButton(
acquirePlayerPanelHold: widget.acquirePlayerPanelHold,
bangumiItem: videoPageController.bangumiItem,
@@ -807,7 +800,6 @@ class _SmallestPlayerItemPanelState extends State<SmallestPlayerItemPanel> {
),
),
),
- // 定时关闭
SubmenuButton(
menuChildren: [
MenuItemButton(
diff --git a/lib/pages/popular/popular_controller.dart b/lib/pages/popular/popular_controller.dart
index 01aabb26..8bb3971a 100644
--- a/lib/pages/popular/popular_controller.dart
+++ b/lib/pages/popular/popular_controller.dart
@@ -37,6 +37,9 @@ abstract class _PopularController with Store {
bangumiList.clear();
}
+ // Async actions commit each segment between awaits as one transaction,
+ // batching the completion writes into a single notification.
+ @action
Future<void> queryBangumiByTrend({String type = 'add'}) async {
if (type == 'init') {
trendList.clear();
@@ -51,6 +54,7 @@ abstract class _PopularController with Store {
isTimeOut = trendList.isEmpty;
}
+ @action
Future<void> queryBangumiByTag({String type = 'add'}) async {
if (type == 'init') {
bangumiList.clear();
diff --git a/lib/pages/popular/popular_controller.g.dart b/lib/pages/popular/popular_controller.g.dart
index 5810c2e7..06613d91 100644
--- a/lib/pages/popular/popular_controller.g.dart
+++ b/lib/pages/popular/popular_controller.g.dart
@@ -89,6 +89,24 @@ mixin _$PopularController on _PopularController, Store {
});
}
+ late final _$queryBangumiByTrendAsyncAction =
+ AsyncAction('_PopularController.queryBangumiByTrend', context: context);
+
+ @override
+ Future<void> queryBangumiByTrend({String type = 'add'}) {
+ return _$queryBangumiByTrendAsyncAction
+ .run(() => super.queryBangumiByTrend(type: type));
+ }
+
+ late final _$queryBangumiByTagAsyncAction =
+ AsyncAction('_PopularController.queryBangumiByTag', context: context);
+
+ @override
+ Future<void> queryBangumiByTag({String type = 'add'}) {
+ return _$queryBangumiByTagAsyncAction
+ .run(() => super.queryBangumiByTag(type: type));
+ }
+
@override
String toString() {
return '''
diff --git a/lib/pages/timeline/timeline_controller.dart b/lib/pages/timeline/timeline_controller.dart
index 923d7c84..8173b640 100644
--- a/lib/pages/timeline/timeline_controller.dart
+++ b/lib/pages/timeline/timeline_controller.dart
@@ -40,19 +40,24 @@ abstract class _TimelineController with Store {
late bool onlyShowWatchingBangumis =
_collectRepository.getTimelineOnlyShowWatchingBangumis();
- int sortType = 3;
+ int _sortType = 3;
+ int get sortType => _sortType;
- late DateTime selectedDate;
+ late DateTime _selectedDate;
+ DateTime get selectedDate => _selectedDate;
bool get _bangumiMirrorEnabled =>
GStorage.getSetting(SettingsKeys.enableBangumiProxy);
void init() {
- selectedDate = DateTime.now();
- seasonString = AnimeSeason(selectedDate).toString();
+ _selectedDate = DateTime.now();
+ seasonString = AnimeSeason(_selectedDate).toString();
getSchedules();
}
+ // Async actions commit each segment between awaits as one transaction, so
+ // clear+addAll never shows observers an intermediate empty list.
+ @action
Future<void> getSchedules() async {
isLoading = true;
isTimeOut = false;
@@ -65,6 +70,7 @@ abstract class _TimelineController with Store {
isTimeOut = bangumiCalendar.isEmpty;
}
+ @action
Future<void> getSchedulesBySeason() async {
if (_bangumiMirrorEnabled) {
isLoading = true;
@@ -83,7 +89,6 @@ abstract class _TimelineController with Store {
return;
}
- // 4次获取,每次最多20部
isLoading = true;
isTimeOut = false;
bangumiCalendar.clear();
@@ -113,22 +118,20 @@ abstract class _TimelineController with Store {
}
void tryEnterSeason(DateTime date) {
- selectedDate = date;
+ _selectedDate = date;
seasonString = "加载中 ٩(◦`꒳´◦)۶";
}
- /// 排序方式
- /// 1. default
- /// 2. score
- /// 3. heat
+ /// Sort type: 1 = default (id), 2 = score, 3 = heat (votes).
+ @action
void changeSortType(int type) {
if (type < 1 || type > 3) {
return;
}
- sortType = type;
+ _sortType = type;
var resBangumiCalendar = bangumiCalendar.toList();
for (var dayList in resBangumiCalendar) {
- switch (sortType) {
+ switch (_sortType) {
case 1:
dayList.sort((a, b) => a.id.compareTo(b.id));
break;
diff --git a/lib/pages/timeline/timeline_controller.g.dart b/lib/pages/timeline/timeline_controller.g.dart
index 4e506af2..ee3e2e88 100644
--- a/lib/pages/timeline/timeline_controller.g.dart
+++ b/lib/pages/timeline/timeline_controller.g.dart
@@ -142,6 +142,23 @@ mixin _$TimelineController on _TimelineController, Store {
});
}
+ late final _$getSchedulesAsyncAction =
+ AsyncAction('_TimelineController.getSchedules', context: context);
+
+ @override
+ Future<void> getSchedules() {
+ return _$getSchedulesAsyncAction.run(() => super.getSchedules());
+ }
+
+ late final _$getSchedulesBySeasonAsyncAction =
+ AsyncAction('_TimelineController.getSchedulesBySeason', context: context);
+
+ @override
+ Future<void> getSchedulesBySeason() {
+ return _$getSchedulesBySeasonAsyncAction
+ .run(() => super.getSchedulesBySeason());
+ }
+
late final _$setNotShowAbandonedBangumisAsyncAction = AsyncAction(
'_TimelineController.setNotShowAbandonedBangumis',
context: context);
@@ -172,6 +189,20 @@ mixin _$TimelineController on _TimelineController, Store {
.run(() => super.setOnlyShowWatchingBangumis(value));
}
+ late final _$_TimelineControllerActionController =
+ ActionController(name: '_TimelineController', context: context);
+
+ @override
+ void changeSortType(int type) {
+ final _$actionInfo = _$_TimelineControllerActionController.startAction(
+ name: '_TimelineController.changeSortType');
+ try {
+ return super.changeSortType(type);
+ } finally {
+ _$_TimelineControllerActionController.endAction(_$actionInfo);
+ }
+ }
+
@override
String toString() {
return '''
diff --git a/lib/pages/video/video_controller.dart b/lib/pages/video/video_controller.dart
index 99d6bc22..2fafa01f 100644
--- a/lib/pages/video/video_controller.dart
+++ b/lib/pages/video/video_controller.dart
@@ -1,6 +1,7 @@
import 'dart:async';
+import 'package:flutter_modular/flutter_modular.dart';
import 'package:kazumi/modules/roads/road_module.dart';
-import 'package:kazumi/plugins/plugins_controller.dart';
+import 'package:kazumi/pages/video/video_playback_args.dart';
import 'package:kazumi/plugins/plugins.dart';
import 'package:kazumi/pages/history/history_controller.dart';
import 'package:kazumi/pages/player/player_controller.dart';
@@ -18,7 +19,6 @@ 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:dio/dio.dart';
import 'package:kazumi/services/storage/storage.dart';
import 'package:kazumi/utils/device.dart';
import 'package:kazumi/utils/episode_url.dart';
@@ -56,9 +56,8 @@ class VideoEpisodeSelection {
}
}
-abstract class _VideoPageController with Store {
+abstract class _VideoPageController with Store implements Disposable {
_VideoPageController(
- this.pluginsController,
this.historyController,
this.downloadRepository,
this.downloadManager,
@@ -70,11 +69,14 @@ abstract class _VideoPageController with Store {
@observable
var episodeCommentsList = ObservableList<EpisodeCommentItem>();
- @observable
- bool loading = true;
+ // Resolution state machine: [_beginEpisodeSwitch] enters the loading state;
+ // [_finishLoading] and [_failLoading] are the only terminal transitions.
+ // [_errorMessage] is non-null only in the failed state.
+ @readonly
+ bool _loading = true;
- @observable
- String? errorMessage;
+ @readonly
+ String? _errorMessage;
@observable
VideoEpisodeSelection selectedEpisode =
@@ -86,6 +88,7 @@ abstract class _VideoPageController with Store {
@observable
int commentsEpisode = 1;
+ @action
void resetEpisodeState({int episode = 1, int road = 0}) {
final selection = VideoEpisodeSelection(episode: episode, road: road);
selectedEpisode = selection;
@@ -126,7 +129,7 @@ abstract class _VideoPageController with Store {
final Map<int, int> _offlineDisplayRoadToOriginalRoad = {};
final Map<int, int> _offlineOriginalRoadToDisplayRoad = {};
- /// 和 bangumiItem 中的标题不同,此标题来自于视频源
+ /// Title reported by the video source; may differ from [bangumiItem]'s.
String title = '';
String src = '';
@@ -138,9 +141,6 @@ abstract class _VideoPageController with Store {
String _offlinePluginName = '';
- CancelToken? _queryRoadsCancelToken;
-
- final PluginsController pluginsController;
final HistoryController historyController;
final IDownloadRepository downloadRepository;
final IDownloadManager downloadManager;
@@ -154,7 +154,30 @@ abstract class _VideoPageController with Store {
StreamSubscription<String>? _logSubscription;
- void initForOfflinePlayback({
+ /// Applies the route arguments exactly once, from [VideoPage.initState].
+ @action
+ void applyPlaybackArgs(VideoPlaybackArgs args) {
+ switch (args) {
+ case OnlineVideoPlaybackArgs():
+ bangumiItem = args.bangumiItem;
+ currentPlugin = args.plugin;
+ title = args.title;
+ src = args.src;
+ roadList.clear();
+ roadList.addAll(args.roads);
+ case OfflineVideoPlaybackArgs():
+ _initForOfflinePlayback(
+ bangumiItem: args.bangumiItem,
+ pluginName: args.pluginName,
+ episodeNumber: args.episodeNumber,
+ road: args.road,
+ downloadedEpisodes: args.downloadedEpisodes,
+ );
+ }
+ }
+
+ @action
+ void _initForOfflinePlayback({
required BangumiItem bangumiItem,
required String pluginName,
required int episodeNumber,
@@ -166,7 +189,7 @@ abstract class _VideoPageController with Store {
title =
bangumiItem.nameCn.isNotEmpty ? bangumiItem.nameCn : bangumiItem.name;
isOfflineMode = true;
- loading = false;
+ _loading = false;
_buildOfflineRoadList(downloadedEpisodes);
@@ -208,15 +231,6 @@ abstract class _VideoPageController with Store {
.addAll(snapshot.originalRoadToDisplayRoad);
}
- void resetOfflineMode() {
- isOfflineMode = false;
- _offlinePluginName = '';
- _offlineEpisodesByNumber.clear();
- _offlineDisplayRoadToOriginalRoad.clear();
- _offlineOriginalRoadToDisplayRoad.clear();
- _playbackHistoryIdentity = null;
- }
-
String get offlinePluginName => _offlinePluginName;
PlaybackHistoryIdentity? get currentHistoryIdentity =>
@@ -364,6 +378,38 @@ abstract class _VideoPageController with Store {
return resolvedEpisode?.danmakuEpisodeNumber ?? selection.episode;
}
+ /// Resets pre-switch state as a single transaction so observers see one
+ /// notification instead of one per field.
+ @action
+ void _beginEpisodeSwitch(VideoEpisodeSelection selection) {
+ selectedEpisode = selection;
+ playingEpisode = null;
+ commentsEpisode = commentEpisodeForSelection(selection);
+ _resetEpisodeComments();
+ _loading = true;
+ _errorMessage = null;
+ }
+
+ @action
+ void _applyResolvedSelection(EpisodeRef resolvedEpisode) {
+ selectedEpisode = VideoEpisodeSelection(
+ episode: resolvedEpisode.listIndex,
+ road: resolvedEpisode.roadIndex,
+ );
+ commentsEpisode = commentEpisodeForSelection(selectedEpisode);
+ }
+
+ @action
+ void _finishLoading() {
+ _loading = false;
+ }
+
+ @action
+ void _failLoading(String message) {
+ _loading = false;
+ _errorMessage = message;
+ }
+
Future<void> changeEpisode(
int episode, {
int currentRoad = 0,
@@ -375,15 +421,10 @@ abstract class _VideoPageController with Store {
episode: episode,
road: currentRoad,
);
- selectedEpisode = selection;
- playingEpisode = null;
- commentsEpisode = commentEpisodeForSelection(selection);
- resetEpisodeComments();
+ _beginEpisodeSwitch(selection);
_danmakuSessions.cancel();
playerController.danmaku.finishDanmakuLoad();
_videoSourceService?.cancel();
- loading = true;
- errorMessage = null;
await playerController.stop();
if (session.isStale) {
@@ -402,18 +443,13 @@ abstract class _VideoPageController with Store {
final resolvedEpisode = _resolveOnlineEpisode(episode, road: currentRoad);
if (resolvedEpisode == null) {
- loading = false;
KazumiLogger().e(
'VideoPageController: failed to resolve online episode. road=$currentRoad, episode=$episode');
- KazumiDialog.showToast(message: '集数解析失败');
+ _failLoading('集数解析失败');
return;
}
- selectedEpisode = VideoEpisodeSelection(
- episode: resolvedEpisode.listIndex,
- road: resolvedEpisode.roadIndex,
- );
- commentsEpisode = commentEpisodeForSelection(selectedEpisode);
+ _applyResolvedSelection(resolvedEpisode);
_setOnlineHistoryIdentity(resolvedEpisode);
KazumiLogger()
@@ -441,10 +477,9 @@ abstract class _VideoPageController with Store {
final resolvedEpisode =
_resolveOfflineEpisode(selection.episode, road: selection.road);
if (resolvedEpisode == null) {
- loading = false;
KazumiLogger().e(
'VideoPageController: failed to resolve offline episode. road=${selection.road}, episode=${selection.episode}');
- KazumiDialog.showToast(message: '集数解析失败');
+ _failLoading('集数解析失败');
return;
}
@@ -454,20 +489,15 @@ abstract class _VideoPageController with Store {
resolvedEpisode.historyEpisodeNumber,
);
if (localPath == null) {
- loading = false;
- KazumiDialog.showToast(message: '该集数未下载');
+ _failLoading('该集数未下载');
return;
}
- selectedEpisode = VideoEpisodeSelection(
- episode: resolvedEpisode.listIndex,
- road: resolvedEpisode.roadIndex,
- );
- commentsEpisode = commentEpisodeForSelection(selectedEpisode);
+ _applyResolvedSelection(resolvedEpisode);
_setOfflineHistoryIdentity(resolvedEpisode);
if (session.isStale) {
return;
}
- loading = false;
+ _finishLoading();
final resolvedOffset =
offset > 0 ? offset : getHistoryOffsetFor(_playbackHistoryIdentity!);
@@ -503,10 +533,6 @@ abstract class _VideoPageController with Store {
}
}
- int _danmakuEpisodeForPlayback(PlaybackInitParams params) {
- return params.danmakuEpisodeNumber;
- }
-
Future<void> _loadPlaybackDanmaku(
PlayerController playerController,
PlaybackInitParams params,
@@ -518,7 +544,7 @@ abstract class _VideoPageController with Store {
final result = await playerController.danmaku.fetchDanmaku(
params.bangumiId,
params.pluginName,
- _danmakuEpisodeForPlayback(params),
+ params.danmakuEpisodeNumber,
);
if (session.isActive && danmakuSession.isActive) {
if (result.hasDanmakus) {
@@ -581,7 +607,7 @@ abstract class _VideoPageController with Store {
if (session.isStale) {
return;
}
- loading = false;
+ _finishLoading();
KazumiLogger()
.i('VideoPageController: resolved video URL: ${source.url}');
@@ -629,35 +655,18 @@ abstract class _VideoPageController with Store {
if (session.isStale) {
return;
}
- loading = false;
- errorMessage = '视频解析超时,请重试';
+ _failLoading('视频解析超时,请重试');
} on VideoSourceCancelledException {
KazumiLogger().i('VideoPageController: video URL resolution cancelled');
} catch (e) {
if (session.isStale) {
return;
}
- loading = false;
- errorMessage = '视频解析失败:${e.toString()}';
+ _failLoading('视频解析失败:${e.toString()}');
}
}
- void cancelVideoSourceResolution() {
- _playbackSessions.cancel();
- _danmakuSessions.cancel();
- _logSubscription?.cancel();
- _logSubscription = null;
- if (!_logStreamController.isClosed) {
- _logStreamController.close();
- }
- final videoSourceService = _videoSourceService;
- _videoSourceService = null;
- if (videoSourceService != null) {
- unawaited(videoSourceService.dispose());
- }
- }
-
- void resetEpisodeComments() {
+ void _resetEpisodeComments() {
_commentSessions.cancel();
episodeInfo.reset();
episodeCommentsList.clear();
@@ -690,8 +699,6 @@ abstract class _VideoPageController with Store {
if (session.isStale) {
return false;
}
- commentsEpisode = episode;
- episodeInfo = latestEpisodeInfo;
final commentsList = value.commentList;
if (!isCommentsAscending) {
commentsList
@@ -700,40 +707,24 @@ abstract class _VideoPageController with Store {
commentsList
.sort((a, b) => a.comment.createdAt.compareTo(b.comment.createdAt));
}
- episodeCommentsList = ObservableList.of(commentsList);
+ _applyEpisodeComments(episode, latestEpisodeInfo, commentsList);
KazumiLogger().i(
'VideoPageController: loaded comments list length ${episodeCommentsList.length}');
return true;
}
- Future<void> queryRoads(String url, String pluginName,
- {CancelToken? cancelToken}) async {
- if (cancelToken != null) {
- _queryRoadsCancelToken?.cancel();
- _queryRoadsCancelToken = cancelToken;
- } else {
- _queryRoadsCancelToken?.cancel();
- _queryRoadsCancelToken = CancelToken();
- cancelToken = _queryRoadsCancelToken;
- }
-
- roadList.clear();
- for (Plugin plugin in pluginsController.pluginList) {
- if (plugin.name == pluginName) {
- roadList.addAll(
- await plugin.queryChapterRoads(url, cancelToken: cancelToken));
- }
- }
- KazumiLogger()
- .i('VideoPageController: road list length ${roadList.length}');
- if (roadList.isEmpty) {
- throw ChapterErrorException(pluginName);
- }
- KazumiLogger().i(
- 'VideoPageController: first road episode count ${roadList.first.data.length}',
- );
+ @action
+ void _applyEpisodeComments(
+ int episode,
+ EpisodeInfo info,
+ List<EpisodeCommentItem> comments,
+ ) {
+ commentsEpisode = episode;
+ episodeInfo = info;
+ episodeCommentsList = ObservableList.of(comments);
}
+ @action
void toggleSortOrder() {
isCommentsAscending = !isCommentsAscending;
episodeCommentsList.sort(
@@ -743,11 +734,21 @@ abstract class _VideoPageController with Store {
);
}
- void cancelQueryRoads() {
- if (_queryRoadsCancelToken != null) {
- if (!_queryRoadsCancelToken!.isCancelled) {
- _queryRoadsCancelToken!.cancel();
- }
+ /// Called by Modular when the '/video' route scope is disposed.
+ @override
+ void dispose() {
+ _playbackSessions.cancel();
+ _danmakuSessions.cancel();
+ _commentSessions.cancel();
+ _logSubscription?.cancel();
+ _logSubscription = null;
+ if (!_logStreamController.isClosed) {
+ _logStreamController.close();
+ }
+ final videoSourceService = _videoSourceService;
+ _videoSourceService = null;
+ if (videoSourceService != null) {
+ unawaited(videoSourceService.dispose());
}
}
@@ -849,9 +850,10 @@ class EpisodeRef {
final String displayTitle;
final String pageUrl;
- /// 集数排序号。
- /// - 在线:从 [displayTitle] 解析([extractEpisodeNumber]),无法解析时为 null。
- /// - 离线:恒等于下载数据的 episodeNumber。
+ /// Episode sort number.
+ /// - Online: parsed from [displayTitle] via [extractEpisodeNumber];
+ /// null when unparsable.
+ /// - Offline: always the download record's episodeNumber.
final int? sortNumber;
final int historyEpisodeNumber;
final int danmakuEpisodeNumber;
diff --git a/lib/pages/video/video_controller.g.dart b/lib/pages/video/video_controller.g.dart
index 92b35695..9dddc5c1 100644
--- a/lib/pages/video/video_controller.g.dart
+++ b/lib/pages/video/video_controller.g.dart
@@ -25,35 +25,39 @@ mixin _$VideoPageController on _VideoPageController, Store {
});
}
- late final _$loadingAtom =
- Atom(name: '_VideoPageController.loading', context: context);
+ late final _$_loadingAtom =
+ Atom(name: '_VideoPageController._loading', context: context);
- @override
bool get loading {
- _$loadingAtom.reportRead();
- return super.loading;
+ _$_loadingAtom.reportRead();
+ return super._loading;
}
@override
- set loading(bool value) {
- _$loadingAtom.reportWrite(value, super.loading, () {
- super.loading = value;
+ bool get _loading => loading;
+
+ @override
+ set _loading(bool value) {
+ _$_loadingAtom.reportWrite(value, super._loading, () {
+ super._loading = value;
});
}
- late final _$errorMessageAtom =
- Atom(name: '_VideoPageController.errorMessage', context: context);
+ late final _$_errorMessageAtom =
+ Atom(name: '_VideoPageController._errorMessage', context: context);
- @override
String? get errorMessage {
- _$errorMessageAtom.reportRead();
- return super.errorMessage;
+ _$_errorMessageAtom.reportRead();
+ return super._errorMessage;
}
@override
- set errorMessage(String? value) {
- _$errorMessageAtom.reportWrite(value, super.errorMessage, () {
- super.errorMessage = value;
+ String? get _errorMessage => errorMessage;
+
+ @override
+ set _errorMessage(String? value) {
+ _$_errorMessageAtom.reportWrite(value, super._errorMessage, () {
+ super._errorMessage = value;
});
}
@@ -217,12 +221,123 @@ mixin _$VideoPageController on _VideoPageController, Store {
});
}
+ late final _$_VideoPageControllerActionController =
+ ActionController(name: '_VideoPageController', context: context);
+
+ @override
+ void resetEpisodeState({int episode = 1, int road = 0}) {
+ final _$actionInfo = _$_VideoPageControllerActionController.startAction(
+ name: '_VideoPageController.resetEpisodeState');
+ try {
+ return super.resetEpisodeState(episode: episode, road: road);
+ } finally {
+ _$_VideoPageControllerActionController.endAction(_$actionInfo);
+ }
+ }
+
+ @override
+ void applyPlaybackArgs(VideoPlaybackArgs args) {
+ final _$actionInfo = _$_VideoPageControllerActionController.startAction(
+ name: '_VideoPageController.applyPlaybackArgs');
+ try {
+ return super.applyPlaybackArgs(args);
+ } finally {
+ _$_VideoPageControllerActionController.endAction(_$actionInfo);
+ }
+ }
+
+ @override
+ void _initForOfflinePlayback(
+ {required BangumiItem bangumiItem,
+ required String pluginName,
+ required int episodeNumber,
+ required int road,
+ required List<DownloadEpisode> downloadedEpisodes}) {
+ final _$actionInfo = _$_VideoPageControllerActionController.startAction(
+ name: '_VideoPageController._initForOfflinePlayback');
+ try {
+ return super._initForOfflinePlayback(
+ bangumiItem: bangumiItem,
+ pluginName: pluginName,
+ episodeNumber: episodeNumber,
+ road: road,
+ downloadedEpisodes: downloadedEpisodes);
+ } finally {
+ _$_VideoPageControllerActionController.endAction(_$actionInfo);
+ }
+ }
+
+ @override
+ void _beginEpisodeSwitch(VideoEpisodeSelection selection) {
+ final _$actionInfo = _$_VideoPageControllerActionController.startAction(
+ name: '_VideoPageController._beginEpisodeSwitch');
+ try {
+ return super._beginEpisodeSwitch(selection);
+ } finally {
+ _$_VideoPageControllerActionController.endAction(_$actionInfo);
+ }
+ }
+
+ @override
+ void _applyResolvedSelection(EpisodeRef resolvedEpisode) {
+ final _$actionInfo = _$_VideoPageControllerActionController.startAction(
+ name: '_VideoPageController._applyResolvedSelection');
+ try {
+ return super._applyResolvedSelection(resolvedEpisode);
+ } finally {
+ _$_VideoPageControllerActionController.endAction(_$actionInfo);
+ }
+ }
+
+ @override
+ void _finishLoading() {
+ final _$actionInfo = _$_VideoPageControllerActionController.startAction(
+ name: '_VideoPageController._finishLoading');
+ try {
+ return super._finishLoading();
+ } finally {
+ _$_VideoPageControllerActionController.endAction(_$actionInfo);
+ }
+ }
+
+ @override
+ void _failLoading(String message) {
+ final _$actionInfo = _$_VideoPageControllerActionController.startAction(
+ name: '_VideoPageController._failLoading');
+ try {
+ return super._failLoading(message);
+ } finally {
+ _$_VideoPageControllerActionController.endAction(_$actionInfo);
+ }
+ }
+
+ @override
+ void _applyEpisodeComments(
+ int episode, EpisodeInfo info, List<EpisodeCommentItem> comments) {
+ final _$actionInfo = _$_VideoPageControllerActionController.startAction(
+ name: '_VideoPageController._applyEpisodeComments');
+ try {
+ return super._applyEpisodeComments(episode, info, comments);
+ } finally {
+ _$_VideoPageControllerActionController.endAction(_$actionInfo);
+ }
+ }
+
+ @override
+ void toggleSortOrder() {
+ final _$actionInfo = _$_VideoPageControllerActionController.startAction(
+ name: '_VideoPageController.toggleSortOrder');
+ try {
+ return super.toggleSortOrder();
+ } finally {
+ _$_VideoPageControllerActionController.endAction(_$actionInfo);
+ }
+ }
+
@override
String toString() {
return '''
episodeCommentsList: ${episodeCommentsList},
-loading: ${loading},
-errorMessage: ${errorMessage},
selectedEpisode: ${selectedEpisode},
playingEpisode: ${playingEpisode},
commentsEpisode: ${commentsEpisode},
diff --git a/lib/pages/video/video_module.dart b/lib/pages/video/video_module.dart
index d5b500e8..e1539eec 100644
--- a/lib/pages/video/video_module.dart
+++ b/lib/pages/video/video_module.dart
@@ -1,22 +1,33 @@
import 'package:flutter_modular/flutter_modular.dart';
+import 'package:kazumi/pages/download/download_controller.dart';
+import 'package:kazumi/pages/history/history_controller.dart';
import 'package:kazumi/pages/player/player_controller.dart';
-import 'package:kazumi/pages/video/video_page.dart';
+import 'package:kazumi/pages/route_error_page.dart';
import 'package:kazumi/pages/video/video_controller.dart';
-import 'package:kazumi/pages/history/history_controller.dart';
-import 'package:kazumi/pages/download/download_controller.dart';
+import 'package:kazumi/pages/video/video_page.dart';
+import 'package:kazumi/pages/video/video_playback_args.dart';
final videoModule = createModule(
path: '/video',
register: (c) {
c.route(
'/',
- provide: (s) => s.add<PlayerController>(PlayerController.new),
- child: (context, state) => VideoPage(
- playerController: context.read<PlayerController>(),
- videoPageController: inject<VideoPageController>(),
- historyController: inject<HistoryController>(),
- downloadController: inject<DownloadController>(),
- ),
+ provide: (s) => s
+ ..add<VideoPageController>(VideoPageController.new)
+ ..add<PlayerController>(PlayerController.new),
+ child: (context, state) {
+ final args = state.arguments;
+ if (args is! VideoPlaybackArgs) {
+ return const RouteErrorPage(message: '播放参数无效,请返回后重试。');
+ }
+ return VideoPage(
+ args: args,
+ playerController: context.read<PlayerController>(),
+ videoPageController: context.read<VideoPageController>(),
+ historyController: inject<HistoryController>(),
+ downloadController: inject<DownloadController>(),
+ );
+ },
);
},
);
diff --git a/lib/pages/video/video_page.dart b/lib/pages/video/video_page.dart
index 83b68ee5..92203dce 100644
--- a/lib/pages/video/video_page.dart
+++ b/lib/pages/video/video_page.dart
@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:kazumi/pages/player/player_controller.dart';
import 'package:kazumi/pages/video/video_controller.dart';
+import 'package:kazumi/pages/video/video_playback_args.dart';
import 'package:kazumi/pages/history/history_controller.dart';
import 'package:kazumi/services/logging/logger.dart';
import 'package:kazumi/pages/player/player_item.dart';
@@ -28,12 +29,14 @@ import 'package:kazumi/services/platform/display_mode_service.dart';
class VideoPage extends StatefulWidget {
const VideoPage({
super.key,
+ required this.args,
required this.playerController,
required this.videoPageController,
required this.historyController,
required this.downloadController,
});
+ final VideoPlaybackArgs args;
final PlayerController playerController;
final VideoPageController videoPageController;
final HistoryController historyController;
@@ -78,6 +81,7 @@ class _VideoPageState extends State<VideoPage>
@override
void initState() {
super.initState();
+ videoPageController.applyPlaybackArgs(widget.args);
windowManager.addListener(this);
// Window fullscreen can be changed outside this page through system chrome.
videoPageController.isDesktopFullscreen();
@@ -169,7 +173,6 @@ class _VideoPageState extends State<VideoPage>
}
void _initOnlineMode(PlayerController playerController) {
- videoPageController.resetEpisodeState();
videoPageController.historyOffset = 0;
_showTabBodyImmediately(locateEpisode: false);
@@ -230,14 +233,13 @@ class _VideoPageState extends State<VideoPage>
try {
_logSubscription?.cancel();
} catch (_) {}
- videoPageController.cancelVideoSourceResolution();
+ // Cancellation and log-stream teardown happen in VideoPageController's
+ // own dispose when Modular releases the route scope.
if (!isDesktop()) {
try {
ScreenBrightnessPlatform.instance.resetApplicationScreenBrightness();
} catch (_) {}
}
- videoPageController.resetEpisodeComments();
- videoPageController.resetOfflineMode();
DisplayModeService.unlockScreenRotation();
keyboardFocus.dispose();
tabController.dispose();
@@ -870,6 +872,7 @@ class _VideoPageState extends State<VideoPage>
? Container()
: PlayerItem(
playerController: playerController,
+ videoPageController: videoPageController,
toggleMenu: _toggleTabBodyAnimated,
showMenuImmediately: _showTabBodyImmediately,
hideMenuImmediately: _hideTabBodyImmediately,
@@ -983,7 +986,6 @@ class _VideoPageState extends State<VideoPage>
}
Widget _buildDownloadStatusIcon(int episodeNumber, String episodePageUrl) {
- // 离线模式下不显示下载状态图标
if (videoPageController.isOfflineMode) return const SizedBox.shrink();
final episode = _getEpisodeFromRecords(episodeNumber, episodePageUrl);
if (episode == null) return const SizedBox.shrink();
@@ -1231,7 +1233,10 @@ class _VideoPageState extends State<VideoPage>
showAdaptiveBottomSheet<void>(
context: context,
builder: (context) =>
- DownloadEpisodeSheet(road: visibleRoad),
+ DownloadEpisodeSheet(
+ road: visibleRoad,
+ videoPageController: videoPageController,
+ ),
);
},
),
diff --git a/lib/pages/video/video_playback_args.dart b/lib/pages/video/video_playback_args.dart
new file mode 100644
index 00000000..d28b9f1c
--- /dev/null
+++ b/lib/pages/video/video_playback_args.dart
@@ -0,0 +1,43 @@
+import 'package:kazumi/modules/bangumi/bangumi_item.dart';
+import 'package:kazumi/modules/download/download_module.dart';
+import 'package:kazumi/modules/roads/road_module.dart';
+import 'package:kazumi/plugins/plugins.dart';
+
+/// Route arguments for '/video/'. Entry points hand playback context over
+/// through the route instead of pre-filling a shared controller, which lets
+/// [VideoPageController] live and die with the route.
+sealed class VideoPlaybackArgs {
+ const VideoPlaybackArgs({required this.bangumiItem});
+
+ final BangumiItem bangumiItem;
+}
+
+class OnlineVideoPlaybackArgs extends VideoPlaybackArgs {
+ const OnlineVideoPlaybackArgs({
+ required super.bangumiItem,
+ required this.plugin,
+ required this.title,
+ required this.src,
+ required this.roads,
+ });
+
+ final Plugin plugin;
+ final String title;
+ final String src;
+ final List<Road> roads;
+}
+
+class OfflineVideoPlaybackArgs extends VideoPlaybackArgs {
+ const OfflineVideoPlaybackArgs({
+ required super.bangumiItem,
+ required this.pluginName,
+ required this.episodeNumber,
+ required this.road,
+ required this.downloadedEpisodes,
+ });
+
+ final String pluginName;
+ final int episodeNumber;
+ final int road;
+ final List<DownloadEpisode> downloadedEpisodes;
+}