Skip to content

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

refactor(dialog): centralize workflows

Predidit31e0db7f502e
diff --git a/lib/bean/dialog/dialog.dart b/lib/bean/dialog/dialog.dart
new file mode 100644
index 00000000..bd6a5646
--- /dev/null
+++ b/lib/bean/dialog/dialog.dart
@@ -0,0 +1,232 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/scheduler.dart';
+
+import 'package:kazumi/navigation.dart';
+import 'package:kazumi/utils/constants.dart';
+
+/// Single-use ownership of a route, including before its first frame.
+class KazumiDialogHandle<T> {
+ Route<T>? _route;
+ bool _used = false;
+ bool _dismissed = false;
+
+ bool get isActive => !_dismissed && (_route?.isActive ?? false);
+
+ void dismiss({T? popWith}) {
+ if (_dismissed) return;
+ _dismissed = true;
+ final route = _route;
+ if (route != null) KazumiDialog._dismissRoute(route, popWith);
+ }
+
+ void _attach(Route<T> route) {
+ _used = true;
+ _route = route;
+ }
+
+ void _finish() {
+ _dismissed = true;
+ _route = null;
+ }
+}
+
+class KazumiDialog {
+ static final KazumiDialogObserver observer = KazumiDialogObserver();
+ static int _toastRevision = 0;
+
+ KazumiDialog._internal();
+
+ static Future<T?> show<T>({
+ BuildContext? context,
+ KazumiDialogHandle<T>? handle,
+ bool clickMaskDismiss = true,
+ FutureOr<void> Function()? onDismiss,
+ required WidgetBuilder builder,
+ }) async {
+ final dialog = handle ?? KazumiDialogHandle<T>();
+ if (dialog._used) {
+ throw StateError('A dialog handle can only be used once.');
+ }
+ try {
+ final ctx = context ??
+ rootNavigatorKey.currentContext ??
+ observer.navigator?.context;
+ if (ctx == null || !ctx.mounted || dialog._dismissed) return null;
+ final navigator = Navigator.of(ctx, rootNavigator: true);
+ final route = DialogRoute<T>(
+ context: ctx,
+ builder: builder,
+ themes: InheritedTheme.capture(from: ctx, to: navigator.context),
+ barrierColor: DialogTheme.of(ctx).barrierColor ??
+ Theme.of(ctx).dialogTheme.barrierColor ??
+ Colors.black54,
+ barrierDismissible: clickMaskDismiss,
+ traversalEdgeBehavior: TraversalEdgeBehavior.closedLoop,
+ settings: const RouteSettings(name: 'KazumiDialog'),
+ );
+ dialog._attach(route);
+ return await navigator.push<T>(route);
+ } catch (e) {
+ debugPrint('Kazumi Dialog Error: Failed to show dialog: $e');
+ return null;
+ } finally {
+ dialog._finish();
+ await onDismiss?.call();
+ }
+ }
+
+ static void showToast({
+ required String message,
+ BuildContext? context,
+ bool showActionButton = false,
+ String? actionLabel,
+ VoidCallback? onActionPressed,
+ Duration duration = const Duration(seconds: 2),
+ }) {
+ final messenger = _resolveScaffoldMessenger(context);
+ if (messenger != null && messenger.mounted) {
+ final toastContext =
+ context != null && context.mounted ? context : messenger.context;
+ try {
+ _toastRevision++;
+ messenger
+ ..removeCurrentSnackBar()
+ ..showSnackBar(
+ SnackBar(
+ content: Text(message),
+ behavior: SnackBarBehavior.floating,
+ width: MediaQuery.sizeOf(toastContext).width >
+ LayoutBreakpoint.medium['width']!
+ ? 600
+ : null,
+ duration: duration,
+ persist: false,
+ action: showActionButton
+ ? SnackBarAction(
+ label: actionLabel ?? 'Dismiss',
+ onPressed: () {
+ // Let SnackBarAction close the old toast before replacing it.
+ if (onActionPressed != null) {
+ scheduleMicrotask(onActionPressed);
+ }
+ },
+ )
+ : null,
+ ),
+ );
+ } catch (e) {
+ debugPrint('Kazumi Dialog Error: Failed to show toast: $e');
+ }
+ } else {
+ debugPrint(
+ 'Kazumi Dialog Error: No ScaffoldMessenger available to show Toast');
+ }
+ }
+
+ static void dismiss<T>({BuildContext? context, T? popWith}) {
+ if (context != null && !context.mounted) return;
+ final route =
+ context == null ? observer._lastDialogRoute : ModalRoute.of(context);
+ if (route != null && route.settings.name == 'KazumiDialog') {
+ _dismissRoute(route, popWith);
+ }
+ }
+
+ static void _dismissRoute<T>(Route<T> route, T? result) {
+ if (!route.isActive) return;
+ // Owners may be disposed while Navigator is reconciling its routes.
+ if (SchedulerBinding.instance.schedulerPhase ==
+ SchedulerPhase.persistentCallbacks) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ _dismissRoute(route, result);
+ });
+ return;
+ }
+ final navigator = route.navigator;
+ if (navigator == null || !navigator.mounted) return;
+ if (route.isCurrent) {
+ navigator.pop<T>(result);
+ } else {
+ navigator.removeRoute<T>(route, result);
+ }
+ }
+
+ static ScaffoldMessengerState? _resolveScaffoldMessenger(
+ BuildContext? context,
+ ) {
+ if (context != null && context.mounted) {
+ final scopedMessenger = ScaffoldMessenger.maybeOf(context);
+ if (scopedMessenger != null) {
+ return scopedMessenger;
+ }
+ }
+ return rootScaffoldMessengerKey.currentState;
+ }
+}
+
+class KazumiDialogObserver extends NavigatorObserver {
+ final List<Route<dynamic>> _kazumiDialogRoutes = [];
+ bool _snackBarClearScheduled = false;
+
+ bool get hasKazumiDialog => _kazumiDialogRoutes.isNotEmpty;
+
+ Route<dynamic>? get _lastDialogRoute =>
+ _kazumiDialogRoutes.isEmpty ? null : _kazumiDialogRoutes.last;
+
+ @override
+ void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
+ super.didPush(route, previousRoute);
+ if (_isKazumiDialogRoute(route)) {
+ _kazumiDialogRoutes.add(route);
+ }
+ }
+
+ @override
+ void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
+ super.didPop(route, previousRoute);
+ if (route is PageRoute) _scheduleSnackBarClear();
+ if (_isKazumiDialogRoute(route)) {
+ _kazumiDialogRoutes.remove(route);
+ }
+ }
+
+ @override
+ void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
+ super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
+ if (oldRoute is PageRoute) _scheduleSnackBarClear();
+ if (_isKazumiDialogRoute(oldRoute)) {
+ _kazumiDialogRoutes.remove(oldRoute);
+ }
+ if (newRoute != null && _isKazumiDialogRoute(newRoute)) {
+ _kazumiDialogRoutes.add(newRoute);
+ }
+ }
+
+ @override
+ void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
+ super.didRemove(route, previousRoute);
+ if (route is PageRoute) _scheduleSnackBarClear();
+
+ if (_isKazumiDialogRoute(route)) {
+ _kazumiDialogRoutes.remove(route);
+ }
+ }
+
+ bool _isKazumiDialogRoute(Route<dynamic>? route) =>
+ route?.settings.name == 'KazumiDialog';
+
+ void _scheduleSnackBarClear() {
+ if (_snackBarClearScheduled) return;
+ _snackBarClearScheduled = true;
+ final revision = KazumiDialog._toastRevision;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ _snackBarClearScheduled = false;
+ // Only clear the old page's toast, never one posted after navigation.
+ if (revision == KazumiDialog._toastRevision) {
+ rootScaffoldMessengerKey.currentState?.removeCurrentSnackBar();
+ }
+ });
+ }
+}
diff --git a/lib/bean/dialog/dialog_helper.dart b/lib/bean/dialog/dialog_helper.dart
index 50594eb4..45e20077 100644
--- a/lib/bean/dialog/dialog_helper.dart
+++ b/lib/bean/dialog/dialog_helper.dart
@@ -1,261 +1,2 @@
-import 'package:flutter/material.dart';
-
-import 'package:kazumi/bean/widget/loading_indicator.dart';
-import 'package:kazumi/navigation.dart';
-import 'package:kazumi/utils/constants.dart';
-
-class KazumiDialog {
- static final KazumiDialogObserver observer = KazumiDialogObserver();
-
- KazumiDialog._internal();
-
- static Future<T?> show<T>({
- BuildContext? context,
- bool? clickMaskDismiss,
- VoidCallback? onDismiss,
- required WidgetBuilder builder,
- }) async {
- final ctx =
- context ?? rootNavigatorKey.currentContext ?? observer.currentContext;
- if (ctx != null && ctx.mounted) {
- try {
- final result = await showDialog<T>(
- context: ctx,
- useRootNavigator: true,
- barrierDismissible: clickMaskDismiss ?? true,
- builder: builder,
- routeSettings: const RouteSettings(name: 'KazumiDialog'),
- );
- onDismiss?.call();
- return result;
- } catch (e) {
- debugPrint('Kazumi Dialog Error: Failed to show dialog: $e');
- return null;
- }
- } else {
- debugPrint(
- 'Kazumi Dialog Error: No context available to show the dialog');
- return null;
- }
- }
-
- static void showToast({
- required String message,
- BuildContext? context,
- bool showActionButton = false,
- String? actionLabel,
- Function()? onActionPressed,
- Duration duration = const Duration(seconds: 2),
- }) {
- final messenger = _resolveScaffoldMessenger(context);
- final toastContext = _resolveToastContext(context);
- if (messenger != null && toastContext != null && toastContext.mounted) {
- try {
- messenger
- ..removeCurrentSnackBar()
- ..showSnackBar(
- SnackBar(
- content: Text(message),
- behavior: SnackBarBehavior.floating,
- width: MediaQuery.sizeOf(toastContext).width >
- LayoutBreakpoint.medium['width']!
- ? 600
- : null,
- duration: duration,
- persist: false,
- action: showActionButton
- ? SnackBarAction(
- label: actionLabel ?? 'Dismiss',
- onPressed: () {
- onActionPressed?.call();
- messenger.hideCurrentSnackBar();
- },
- )
- : null,
- ),
- );
- } catch (e) {
- debugPrint('Kazumi Dialog Error: Failed to show toast: $e');
- }
- } else {
- debugPrint(
- 'Kazumi Dialog Error: No ScaffoldMessenger available to show Toast');
- }
- }
-
- static Future<void> showLoading({
- BuildContext? context,
- String? msg,
- bool barrierDismissible = false,
- Function()? onDismiss,
- }) async {
- final ctx =
- context ?? rootNavigatorKey.currentContext ?? observer.currentContext;
- if (ctx != null && ctx.mounted) {
- try {
- await showDialog(
- context: ctx,
- useRootNavigator: true,
- barrierDismissible: barrierDismissible,
- builder: (BuildContext context) {
- return Center(
- child: Card(
- elevation: 8.0,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(12)),
- child: Padding(
- padding: const EdgeInsets.all(24.0),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- const LoadingIndicator(),
- const SizedBox(height: 16),
- Text(
- msg ?? 'Loading...',
- style: const TextStyle(fontSize: 16),
- ),
- ],
- ),
- ),
- ),
- );
- },
- routeSettings: const RouteSettings(name: 'KazumiDialog'),
- );
- onDismiss?.call();
- } catch (e) {
- debugPrint('Kazumi Dialog Error: Failed to show loading dialog: $e');
- }
- } else {
- debugPrint(
- 'Kazumi Dialog Error: No context available to show the loading dialog');
- }
- }
-
- static void dismiss<T>({T? popWith}) {
- if (observer.hasKazumiDialog && observer.kazumiDialogContext != null) {
- try {
- Navigator.of(observer.kazumiDialogContext!).pop(popWith);
- } catch (e) {
- debugPrint('Kazumi Dialog Error: Failed to dismiss dialog: $e');
- }
- } else {
- debugPrint('Kazumi Dialog Debug: No active KazumiDialog to dismiss');
- }
- }
-
- static ScaffoldMessengerState? _resolveScaffoldMessenger(
- BuildContext? context,
- ) {
- if (context != null && context.mounted) {
- final scopedMessenger = ScaffoldMessenger.maybeOf(context);
- if (scopedMessenger != null) {
- return scopedMessenger;
- }
- }
- return rootScaffoldMessengerKey.currentState;
- }
-
- static BuildContext? _resolveToastContext(BuildContext? context) {
- if (context != null && context.mounted) {
- return context;
- }
- final messengerContext = rootScaffoldMessengerKey.currentContext;
- if (messengerContext != null && messengerContext.mounted) {
- return messengerContext;
- }
- return observer.scaffoldContext;
- }
-}
-
-class KazumiDialogObserver extends NavigatorObserver {
- final List<Route<dynamic>> _kazumiDialogRoutes = [];
- bool _snackBarClearScheduled = false;
-
- BuildContext? _currentContext;
-
- BuildContext? _scaffoldContext;
-
- BuildContext? get currentContext => _currentContext;
-
- BuildContext? get scaffoldContext => _scaffoldContext ?? _currentContext;
-
- bool get hasKazumiDialog => _kazumiDialogRoutes.isNotEmpty;
-
- BuildContext? get kazumiDialogContext => _kazumiDialogRoutes.isNotEmpty
- ? _kazumiDialogRoutes.last.navigator?.context
- : null;
-
- @override
- void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
- super.didPush(route, previousRoute);
- if (_isKazumiDialogRoute(route)) {
- _kazumiDialogRoutes.add(route);
- }
- if (route.navigator?.context != null) {
- _updateContexts(route.navigator!.context);
- }
- }
-
- @override
- void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
- super.didPop(route, previousRoute);
- _scheduleSnackBarClear();
- if (_isKazumiDialogRoute(route)) {
- _kazumiDialogRoutes.remove(route);
- }
- if (previousRoute?.navigator?.context != null) {
- _updateContexts(previousRoute!.navigator!.context);
- }
- }
-
- @override
- void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) {
- super.didReplace(newRoute: newRoute, oldRoute: oldRoute);
- _scheduleSnackBarClear();
- if (_isKazumiDialogRoute(oldRoute)) {
- _kazumiDialogRoutes.remove(oldRoute);
- }
- if (newRoute != null && _isKazumiDialogRoute(newRoute)) {
- _kazumiDialogRoutes.add(newRoute);
- }
- final context = newRoute?.navigator?.context;
- if (context != null) {
- _updateContexts(context);
- }
- }
-
- @override
- void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) {
- super.didRemove(route, previousRoute);
- _scheduleSnackBarClear();
-
- if (_isKazumiDialogRoute(route)) {
- _kazumiDialogRoutes.remove(route);
- }
-
- if (previousRoute?.navigator?.context != null) {
- _updateContexts(previousRoute!.navigator!.context);
- }
- }
-
- void _updateContexts(BuildContext context) {
- _currentContext = context;
- if (Scaffold.maybeOf(context) != null) {
- _scaffoldContext = context;
- }
- }
-
- bool _isKazumiDialogRoute(Route<dynamic>? route) =>
- route?.settings.name == 'KazumiDialog';
-
- void _scheduleSnackBarClear() {
- if (_snackBarClearScheduled) return;
- _snackBarClearScheduled = true;
- WidgetsBinding.instance.addPostFrameCallback((_) {
- _snackBarClearScheduled = false;
- // Defer snackbar removal until Navigator finishes reconciling routes.
- rootScaffoldMessengerKey.currentState?.removeCurrentSnackBar();
- });
- }
-}
+export 'dialog.dart';
+export 'dialog_task.dart';
diff --git a/lib/bean/dialog/dialog_task.dart b/lib/bean/dialog/dialog_task.dart
new file mode 100644
index 00000000..5abef090
--- /dev/null
+++ b/lib/bean/dialog/dialog_task.dart
@@ -0,0 +1,236 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/scheduler.dart';
+import 'package:kazumi/bean/dialog/dialog.dart'
+ show KazumiDialog, KazumiDialogHandle;
+import 'package:kazumi/bean/widget/loading_indicator.dart';
+
+mixin KazumiDialogOwner<T extends StatefulWidget> on State<T> {
+ late final dialogs = KazumiDialogController(context: () => context)
+ ..addListener(_refreshDialogState);
+
+ void _refreshDialogState() {
+ if (SchedulerBinding.instance.schedulerPhase ==
+ SchedulerPhase.persistentCallbacks) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) setState(() {});
+ });
+ } else if (mounted) {
+ setState(() {});
+ }
+ }
+
+ @override
+ void dispose() {
+ dialogs.removeListener(_refreshDialogState);
+ dialogs.dispose();
+ super.dispose();
+ }
+}
+
+class KazumiDialogController extends ChangeNotifier {
+ KazumiDialogController({BuildContext Function()? context})
+ : _context = context;
+
+ final BuildContext Function()? _context;
+ KazumiDialogTask? _current;
+ bool _disposed = false;
+
+ bool get isRunning => _current?._isActive ?? false;
+
+ /// Await steps through the task to stop on cancellation. Replacing or disposing
+ /// the owner skips [onCancelled]; user cancellation calls it after cleanup.
+ Future<void> run(
+ Future<void> Function(KazumiDialogTask task) action, {
+ String? errorMessage,
+ void Function(Object error, StackTrace stackTrace)? onError,
+ VoidCallback? onCancelled,
+ }) async {
+ if (_disposed || !(_context?.call().mounted ?? true)) return;
+ cancel();
+ final task = _current = KazumiDialogTask._(this);
+ notifyListeners();
+ try {
+ await action(task);
+ } on _DialogTaskCancelled {
+ if (!_disposed && identical(_current, task)) onCancelled?.call();
+ } catch (error, stackTrace) {
+ if (!task._isActive) return;
+ if (onError != null) {
+ onError(error, stackTrace);
+ } else if (errorMessage != null) {
+ KazumiDialog.showToast(message: errorMessage);
+ } else {
+ rethrow;
+ }
+ } finally {
+ task._dialog?.dismiss();
+ if (identical(_current, task)) {
+ _current = null;
+ if (!_disposed) notifyListeners();
+ }
+ }
+ }
+
+ void cancel() {
+ _current?.cancel();
+ }
+
+ void _notifyCancellation() {
+ if (!_disposed) notifyListeners();
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ cancel();
+ super.dispose();
+ }
+}
+
+class KazumiDialogTask {
+ KazumiDialogTask._(this._owner);
+
+ final KazumiDialogController _owner;
+ final _cancelled = Completer<void>();
+ KazumiDialogHandle<dynamic>? _dialog;
+ FutureOr<void> Function()? _onCancel;
+ Future<void>? _cancelCleanup;
+
+ bool get _isActive =>
+ !_cancelled.isCompleted &&
+ !_owner._disposed &&
+ identical(_owner._current, this) &&
+ (_owner._context?.call().mounted ?? true);
+
+ void withContext(void Function(BuildContext context) action) {
+ _checkActive();
+ final context = _owner._context?.call();
+ if (context == null) {
+ throw StateError('This dialog task has no widget owner.');
+ }
+ action(context);
+ }
+
+ void _checkActive() {
+ if (!_isActive) throw const _DialogTaskCancelled();
+ }
+
+ void cancel() {
+ if (_cancelled.isCompleted) return;
+ _cancelled.complete();
+ _owner._notifyCancellation();
+ _dialog?.dismiss();
+ final onCancel = _onCancel;
+ if (onCancel != null) {
+ _cancelCleanup = Future<void>.sync(onCancel).catchError((Object error) {
+ debugPrint('Kazumi Dialog Error: Task cancellation failed: $error');
+ });
+ }
+ }
+
+ /// Stops waiting, not the operation itself; late errors are still consumed.
+ Future<T> wait<T>(Future<T> future) async {
+ final result = await Future.any<T>([
+ future,
+ _cancelled.future.then<T>((_) => throw const _DialogTaskCancelled()),
+ ]);
+ _checkActive();
+ return result;
+ }
+
+ Future<T> loading<T>({
+ required Future<T> Function() action,
+ String? message,
+ bool barrierDismissible = false,
+ FutureOr<void> Function()? onCancel,
+ WidgetBuilder? builder,
+ }) async {
+ _checkActive();
+ final dialog = KazumiDialogHandle<void>();
+ _dialog = dialog;
+ _onCancel = onCancel;
+ final closed = KazumiDialog.show<void>(
+ context: _owner._context?.call(),
+ handle: dialog,
+ clickMaskDismiss: barrierDismissible,
+ builder: builder ?? (_) => _LoadingDialog(message: message),
+ );
+ unawaited(closed.then((_) {
+ if (identical(_dialog, dialog)) cancel();
+ }));
+ late T result;
+ try {
+ if (!dialog.isActive) cancel();
+ _checkActive();
+ result = await wait(action());
+ } finally {
+ // A system pop can precede completion of the dialog's Future.
+ if (!dialog.isActive) cancel();
+ _dialog = null;
+ _onCancel = null;
+ dialog.dismiss();
+ await _cancelCleanup;
+ _checkActive();
+ }
+ return result;
+ }
+
+ /// A dismissed choice cancels the workflow; an explicit false remains a result.
+ Future<T> show<T extends Object>({
+ required WidgetBuilder builder,
+ bool clickMaskDismiss = true,
+ }) async {
+ _checkActive();
+ final dialog = KazumiDialogHandle<T>();
+ _dialog = dialog;
+ try {
+ final result = await wait(KazumiDialog.show<T>(
+ context: _owner._context?.call(),
+ handle: dialog,
+ clickMaskDismiss: clickMaskDismiss,
+ builder: builder,
+ ));
+ if (result == null) {
+ cancel();
+ throw const _DialogTaskCancelled();
+ }
+ return result;
+ } finally {
+ _dialog = null;
+ dialog.dismiss();
+ }
+ }
+}
+
+class _DialogTaskCancelled implements Exception {
+ const _DialogTaskCancelled();
+}
+
+class _LoadingDialog extends StatelessWidget {
+ const _LoadingDialog({this.message});
+
+ final String? message;
+
+ @override
+ Widget build(BuildContext context) => Center(
+ child: Card(
+ elevation: 8,
+ shape:
+ RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
+ child: Padding(
+ padding: const EdgeInsets.all(24),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ const LoadingIndicator(),
+ const SizedBox(height: 16),
+ Text(message ?? 'Loading...',
+ style: const TextStyle(fontSize: 16)),
+ ],
+ ),
+ ),
+ ),
+ );
+}
diff --git a/lib/pages/about/about_widgets.dart b/lib/pages/about/about_widgets.dart
index 2c4d1266..639880c4 100644
--- a/lib/pages/about/about_widgets.dart
+++ b/lib/pages/about/about_widgets.dart
@@ -2,13 +2,12 @@ import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:url_launcher/url_launcher.dart';
+import 'package:kazumi/bean/dialog/dialog_helper.dart';
import 'package:kazumi/bean/widget/split_list_row.dart';
import 'package:kazumi/bean/widget/state_presentation.dart';
void _showMessage(BuildContext context, String message) {
- ScaffoldMessenger.of(context)
- ..hideCurrentSnackBar()
- ..showSnackBar(SnackBar(content: Text(message)));
+ KazumiDialog.showToast(context: context, message: message);
}
Future<void> openAboutLink(BuildContext context, String url) async {
diff --git a/lib/pages/bangumi/bangumi_setting.dart b/lib/pages/bangumi/bangumi_setting.dart
index c00892c6..e9678d8c 100644
--- a/lib/pages/bangumi/bangumi_setting.dart
+++ b/lib/pages/bangumi/bangumi_setting.dart
@@ -16,13 +16,13 @@ class BangumiEditorPage extends StatefulWidget {
State<BangumiEditorPage> createState() => _BangumiEditorPageState();
}
-class _BangumiEditorPageState extends State<BangumiEditorPage> {
+class _BangumiEditorPageState extends State<BangumiEditorPage>
+ with KazumiDialogOwner {
final TextEditingController bangumiTokenController = TextEditingController();
bool passwordVisible = false;
bool isVerifying = false;
late bool bangumiImmediateSyncToastEnable;
late int syncPriority;
- bool syncCollectiblesing = false;
final MenuController syncPriorityMenuController = MenuController();
@override
@@ -50,6 +50,7 @@ class _BangumiEditorPageState extends State<BangumiEditorPage> {
}
Future<void> syncWithProgress() async {
+ if (dialogs.isRunning) return;
final syncEnable = GStorage.getSetting(SettingsKeys.bangumiSyncEnable);
if (!syncEnable) {
KazumiDialog.showToast(message: '请先开启 Bangumi 同步');
@@ -57,46 +58,32 @@ class _BangumiEditorPageState extends State<BangumiEditorPage> {
}
final progressDialogKey = GlobalKey<_BangumiSyncProgressDialogState>();
-
- try {
- setState(() {
- syncCollectiblesing = true;
- });
-
- KazumiDialog.show(
- clickMaskDismiss: false,
+ await dialogs.run((task) async {
+ await task.loading(
builder: (context) =>
_BangumiSyncProgressDialog(key: progressDialogKey),
- );
-
- final bangumi = BangumiSyncService();
- await bangumi.ping();
- await bangumi.syncCollectibles(
- onProgress: (message, current, total) {
- progressDialogKey.currentState?.update(
- total > 0 ? '$message ($current/$total)' : message,
- total > 0 ? (current / total).clamp(0.0, 1.0).toDouble() : null,
+ action: () async {
+ final bangumi = BangumiSyncService();
+ await bangumi.ping();
+ await bangumi.syncCollectibles(
+ onProgress: (message, current, total) {
+ progressDialogKey.currentState?.update(
+ total > 0 ? '$message ($current/$total)' : message,
+ total > 0 ? (current / total).clamp(0.0, 1.0).toDouble() : null,
+ );
+ },
);
},
);
- } catch (e) {
+ }, onError: (e, _) {
KazumiDialog.showToast(message: 'Bangumi同步失败 $e');
- } finally {
- if (KazumiDialog.observer.hasKazumiDialog) {
- KazumiDialog.dismiss();
- }
- if (mounted) {
- setState(() {
- syncCollectiblesing = false;
- });
- }
- }
+ });
}
@override
Widget build(BuildContext context) {
return PopScope(
- canPop: !syncCollectiblesing,
+ canPop: !dialogs.isRunning,
child: Scaffold(
appBar: const SysAppBar(title: Text('Bangumi 配置')),
body: SingleChildScrollView(
@@ -190,7 +177,7 @@ class _BangumiEditorPageState extends State<BangumiEditorPage> {
),
SettingsTile(
leading: Icons.cloud_sync_rounded,
- trailing: syncCollectiblesing
+ trailing: dialogs.isRunning
? const SizedBox(
width: 20,
height: 20,
diff --git a/lib/pages/collect/collect_page.dart b/lib/pages/collect/collect_page.dart
index b4320c03..b136c14d 100644
--- a/lib/pages/collect/collect_page.dart
+++ b/lib/pages/collect/collect_page.dart
@@ -26,84 +26,73 @@ class CollectPage extends StatefulWidget {
State<CollectPage> createState() => _CollectPageState();
}
-class _CollectPageState extends State<CollectPage> {
+class _CollectPageState extends State<CollectPage> with KazumiDialogOwner {
CollectController get collectController => widget.controller;
- bool _syncing = false;
+ bool get _syncing => dialogs.isRunning;
final Set<int> _pendingIds = {};
Future<void> _runFullSync({
required CollectSyncPlan plan,
- }) async {
- final progressDialogKey = GlobalKey<_FullSyncProgressDialogState>();
-
- unawaited(KazumiDialog.show(
- context: context,
- clickMaskDismiss: false,
- builder: (context) => _FullSyncProgressDialog(key: progressDialogKey),
- ));
- await WidgetsBinding.instance.endOfFrame;
- bool webDavSynced = false;
- bool bangumiSynced = false;
- bool webDavUploaded = false;
-
- try {
- if (plan.shouldSyncWebDavCollectibles) {
- progressDialogKey.currentState?.update('正在同步 WebDav 收藏...', null);
- webDavSynced =
- await collectController.syncCollectibles(showSuccessToast: false);
- }
-
- if (plan.shouldSyncBangumi) {
- progressDialogKey.currentState?.update('准备同步 Bangumi 收藏...', null);
- bangumiSynced = await collectController.syncCollectiblesBangumi(
- showSuccessToast: false,
- onProgress: (message, current, total) {
- progressDialogKey.currentState?.update(
- total > 0 ? '$message ($current/$total)' : message,
- total > 0 ? (current / total).clamp(0.0, 1.0).toDouble() : null,
- );
+ }) =>
+ dialogs.run((task) async {
+ final progressDialogKey = GlobalKey<_FullSyncProgressDialogState>();
+ bool webDavSynced = false;
+ bool bangumiSynced = false;
+ bool webDavUploaded = false;
+
+ await task.loading(
+ builder: (context) => _FullSyncProgressDialog(key: progressDialogKey),
+ action: () async {
+ await WidgetsBinding.instance.endOfFrame;
+ if (plan.shouldSyncWebDavCollectibles) {
+ progressDialogKey.currentState?.update('正在同步 WebDav 收藏...', null);
+ webDavSynced = await collectController.syncCollectibles(
+ showSuccessToast: false);
+ }
+
+ if (plan.shouldSyncBangumi) {
+ progressDialogKey.currentState
+ ?.update('准备同步 Bangumi 收藏...', null);
+ bangumiSynced = await collectController.syncCollectiblesBangumi(
+ showSuccessToast: false,
+ onProgress: (message, current, total) {
+ progressDialogKey.currentState?.update(
+ total > 0 ? '$message ($current/$total)' : message,
+ total > 0
+ ? (current / total).clamp(0.0, 1.0).toDouble()
+ : null,
+ );
+ },
+ );
+ }
+
+ if (plan.shouldUploadWebDavAfterBangumi(
+ webDavSynced: webDavSynced,
+ bangumiSynced: bangumiSynced,
+ )) {
+ progressDialogKey.currentState
+ ?.update('正在回传最新收藏到 WebDav...', null);
+ webDavUploaded =
+ await collectController.uploadCollectiblesToWebDav(
+ showSuccessToast: false,
+ );
+ }
},
);
- }
-
- if (plan.shouldUploadWebDavAfterBangumi(
- webDavSynced: webDavSynced,
- bangumiSynced: bangumiSynced,
- )) {
- progressDialogKey.currentState?.update('正在回传最新收藏到 WebDav...', null);
- webDavUploaded = await collectController.uploadCollectiblesToWebDav(
- showSuccessToast: false,
- );
- }
- } finally {
- final dialogContext = progressDialogKey.currentContext;
- if (dialogContext != null && dialogContext.mounted) {
- final route = ModalRoute.of(dialogContext);
- if (route != null) {
- final navigator = Navigator.of(dialogContext);
- if (route.isCurrent) {
- navigator.pop();
- } else {
- navigator.removeRoute(route);
- }
- // The route observer clears stale snackbars at the end of the frame.
- await WidgetsBinding.instance.endOfFrame;
- }
- }
- }
- final states = [
- if (plan.shouldSyncWebDavCollectibles)
- webDavSynced ? 'WebDav 已同步' : 'WebDav 未完成',
- if (plan.shouldSyncBangumi) bangumiSynced ? 'Bangumi 已同步' : 'Bangumi 未完成',
- if (plan.shouldUploadWebDavAfterBangumi(
- webDavSynced: webDavSynced,
- bangumiSynced: bangumiSynced,
- ))
- webDavUploaded ? 'WebDav 已回传最新数据' : 'WebDav 未回传最新数据',
- ];
- KazumiDialog.showToast(message: states.join(','));
- }
+ final states = [
+ if (plan.shouldSyncWebDavCollectibles)
+ webDavSynced ? 'WebDav 已同步' : 'WebDav 未完成',
+ if (plan.shouldSyncBangumi)
+ bangumiSynced ? 'Bangumi 已同步' : 'Bangumi 未完成',
+ if (plan.shouldUploadWebDavAfterBangumi(
+ webDavSynced: webDavSynced,
+ bangumiSynced: bangumiSynced,
+ ))
+ webDavUploaded ? 'WebDav 已回传最新数据' : 'WebDav 未回传最新数据',
+ ];
+ KazumiDialog.showToast(message: states.join(','));
+ }, errorMessage: '同步未完成,请稍后重试');
@override
void initState() {
@@ -135,14 +124,7 @@ class _CollectPageState extends State<CollectPage> {
KazumiDialog.showToast(message: '同步功能不可用,请至少开启一个同步功能');
return;
}
- setState(() => _syncing = true);
- try {
- await _runFullSync(plan: plan);
- } catch (_) {
- KazumiDialog.showToast(message: '同步未完成,请稍后重试');
- } finally {
- if (mounted) setState(() => _syncing = false);
- }
+ await _runFullSync(plan: plan);
}
@override
diff --git a/lib/pages/history/history_page.dart b/lib/pages/history/history_page.dart
index 14127e0d..f2ab5e29 100644
--- a/lib/pages/history/history_page.dart
+++ b/lib/pages/history/history_page.dart
@@ -175,50 +175,31 @@ class _HistoryCard extends StatefulWidget {
State<_HistoryCard> createState() => _HistoryCardState();
}
-class _HistoryCardState extends State<_HistoryCard> {
+class _HistoryCardState extends State<_HistoryCard> with KazumiDialogOwner {
final CollectController _collectController = inject<CollectController>();
final HistoryPlaybackService _playbackService =
inject<HistoryPlaybackService>();
- RuleCancelToken? _playbackCancelToken;
- bool _opening = false;
bool _updatingCollect = false;
- @override
- void dispose() {
- _playbackCancelToken?.cancel();
- super.dispose();
- }
-
Future<void> _play() async {
- if (widget.editing || widget.busy || _opening) return;
- setState(() => _opening = true);
- final cancelToken = RuleCancelToken();
- _playbackCancelToken = cancelToken;
- KazumiDialog.showLoading(
- msg: '获取中',
- barrierDismissible: isDesktop(),
- onDismiss: cancelToken.cancel,
- );
- try {
- final result = await _playbackService.open(
- widget.history,
- cancelToken: cancelToken,
+ if (widget.editing || widget.busy || dialogs.isRunning) return;
+ await dialogs.run((task) async {
+ final cancelToken = RuleCancelToken();
+ final result = await task.loading(
+ message: '获取中',
+ barrierDismissible: isDesktop(),
+ onCancel: cancelToken.cancel,
+ action: () =>
+ _playbackService.open(widget.history, cancelToken: cancelToken),
);
- if (!mounted || cancelToken.isCancelled) return;
- KazumiDialog.dismiss();
switch (result) {
case HistoryPlaybackReady(:final args):
- context.pushNamed('/video/', arguments: args);
+ task.withContext(
+ (context) => context.pushNamed('/video/', arguments: args));
case HistoryPlaybackUnavailable(:final reason):
KazumiDialog.showToast(message: reason);
}
- } catch (_) {
- if (!mounted || cancelToken.isCancelled) return;
- KazumiDialog.dismiss();
- KazumiDialog.showToast(message: '暂时无法继续播放,请稍后重试');
- } finally {
- if (mounted) setState(() => _opening = false);
- }
+ }, errorMessage: '暂时无法继续播放,请稍后重试');
}
Future<void> _changeCollect(CollectType type) async {
@@ -243,7 +224,7 @@ class _HistoryCardState extends State<_HistoryCard> {
history: widget.history,
borderRadius: widget.borderRadius,
editing: widget.editing,
- busy: widget.busy || _opening,
+ busy: widget.busy || dialogs.isRunning,
onPlay: _play,
onDelete: widget.onDelete,
onDetails: () =>
diff --git a/lib/pages/info/rating_review_dialog.dart b/lib/pages/info/rating_review_dialog.dart
index 5caccbdc..157f10c7 100644
--- a/lib/pages/info/rating_review_dialog.dart
+++ b/lib/pages/info/rating_review_dialog.dart
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
+import 'package:kazumi/bean/dialog/dialog_helper.dart';
import 'package:kazumi/bean/widget/loading_indicator.dart';
import 'package:kazumi/modules/bangumi/bangumi_item.dart';
import 'package:kazumi/modules/bangumi/bangumi_tag.dart';
@@ -164,7 +165,7 @@ class _RatingReviewDialogState extends State<RatingReviewDialog> {
try {
final submitted = await widget.onSubmit?.call(result) ?? true;
if (submitted && mounted) {
- Navigator.of(context).pop();
+ KazumiDialog.dismiss(context: context);
return;
}
} catch (e, stackTrace) {
diff --git a/lib/pages/info/source_captcha_flow.dart b/lib/pages/info/source_captcha_flow.dart
index f2f10941..2f76c350 100644
--- a/lib/pages/info/source_captcha_flow.dart
+++ b/lib/pages/info/source_captcha_flow.dart
@@ -4,156 +4,98 @@ class _SourceCaptchaFlow {
_SourceCaptchaFlow({required this.onVerified, required this.onCancelled});
final void Function(Plugin plugin, String pageHtml) onVerified;
-
final void Function(Plugin plugin) onCancelled;
+ final _dialogs = KazumiDialogController();
- CaptchaVerificationService? _service;
- Timer? _timer;
-
- void start(Plugin plugin, String keyword) {
- final searchUrl = plugin.searchURL
- .replaceAll('@keyword', Uri.encodeQueryComponent(keyword));
- switch (plugin.antiCrawlerConfig.captchaType) {
- case CaptchaType.customJavaScript:
- _startAutomated(
- plugin,
- startVerification: (service, onVerified) =>
- service.loadForCustomScript(
- url: searchUrl,
- script: plugin.antiCrawlerConfig.captchaScript,
- pluginName: plugin.name,
- onVerified: onVerified,
- ),
- );
- case CaptchaType.autoClickButton:
- _startAutomated(
- plugin,
- startVerification: (service, onVerified) =>
- service.loadForButtonClick(
- url: searchUrl,
- buttonXpath: plugin.antiCrawlerConfig.captchaButton,
- pluginName: plugin.name,
- onVerified: onVerified,
- ),
- );
- default:
- _startCaptchaInput(plugin, searchUrl);
- }
- }
-
- void dispose() {
- _service?.dispose();
- _service = null;
- _timer?.cancel();
- _timer = null;
- }
+ void dispose() => _dialogs.dispose();
void showSuccess(String pluginName, {required VoidCallback onComplete}) {
- KazumiDialog.show<bool>(
- clickMaskDismiss: false,
- builder: (_) => _VerificationCompleteDialog(pluginName: pluginName),
- ).then((completed) {
- if (completed == true) onComplete();
- });
- }
-
- void _startCaptchaInput(Plugin plugin, String searchUrl) {
- bool verified = false;
- bool finalizing = false;
-
- _service?.dispose();
- final service = _service = CaptchaVerificationService();
-
- Future<void> submitCaptcha(String captchaCode) async {
- await _service?.submitCaptcha(
- captchaCode: captchaCode,
- inputXpath: plugin.antiCrawlerConfig.captchaInput,
- buttonXpath: plugin.antiCrawlerConfig.captchaButton,
- pluginName: plugin.name,
- onFinalizing: () {
- finalizing = true;
- _timer?.cancel();
- _timer = null;
- },
- onVerified: (pageHtml) {
- verified = true;
- KazumiDialog.dismiss();
- onVerified(plugin, pageHtml);
- },
+ unawaited(_dialogs.run((task) async {
+ await task.show<bool>(
+ clickMaskDismiss: false,
+ builder: (_) => _VerificationCompleteDialog(pluginName: pluginName),
);
- // Submission finishes on the JS click, before verification completes.
- if (!finalizing) {
- _timer?.cancel();
- _timer = Timer(const Duration(seconds: 8), () {
- if (!finalizing) {
- KazumiDialog.dismiss();
- }
- });
- }
- }
-
- KazumiDialog.show(
- onDismiss: () async {
- _timer?.cancel();
- _timer = null;
- // Capture the service before awaiting so a replacement cannot be disposed.
- final captchaService = _service;
- _service = null;
- if (verified) {
- captchaService?.dispose();
- } else {
- await captchaService?.cancelAndSave(plugin.name);
- captchaService?.dispose();
- onCancelled(plugin);
- }
- },
- builder: (context) => _CaptchaDialog(
- pluginName: plugin.name,
- captchaImageStream: service.onCaptchaImageUrl,
- onReload: () => service.loadForCaptcha(
- searchUrl,
- plugin.antiCrawlerConfig.captchaImage,
- inputXpath: plugin.antiCrawlerConfig.captchaInput,
- ),
- onSubmit: submitCaptcha,
- ),
- );
+ onComplete();
+ }));
}
- void _startAutomated(
- Plugin plugin, {
- required Future<void> Function(
- CaptchaVerificationService service,
- void Function(String pageHtml) onVerified,
- ) startVerification,
- }) {
- bool verified = false;
-
- _service?.dispose();
- final service = _service = CaptchaVerificationService();
+ void start(Plugin plugin, String keyword) {
+ unawaited(_dialogs.run((task) async {
+ final service = CaptchaVerificationService();
+ final verified = Completer<String>();
+ final config = plugin.antiCrawlerConfig;
+ final searchUrl = plugin.searchURL
+ .replaceAll('@keyword', Uri.encodeQueryComponent(keyword));
+ Timer? timeout;
+ bool finalizing = false;
+
+ Future<void> submitCaptcha(String code) async {
+ await task.wait(service.submitCaptcha(
+ captchaCode: code,
+ inputXpath: config.captchaInput,
+ buttonXpath: config.captchaButton,
+ pluginName: plugin.name,
+ onFinalizing: () {
+ finalizing = true;
+ timeout?.cancel();
+ },
+ onVerified: verified.complete,
+ ));
+ // Submission returns after the JS click, before verification completes.
+ if (!finalizing) {
+ timeout?.cancel();
+ timeout = Timer(const Duration(seconds: 8), task.cancel);
+ }
+ }
- unawaited(startVerification(service, (pageHtml) {
- verified = true;
- KazumiDialog.dismiss();
+ final String pageHtml;
+ try {
+ pageHtml = await task.loading(
+ barrierDismissible: true,
+ onCancel: () => service.cancelAndSave(plugin.name),
+ builder: (_) => switch (config.captchaType) {
+ CaptchaType.customJavaScript ||
+ CaptchaType.autoClickButton =>
+ _AutomatedVerifyDialog(pluginName: plugin.name),
+ _ => _CaptchaDialog(
+ pluginName: plugin.name,
+ captchaImageStream: service.onCaptchaImageUrl,
+ onReload: () => service.loadForCaptcha(
+ searchUrl,
+ config.captchaImage,
+ inputXpath: config.captchaInput,
+ ),
+ onSubmit: submitCaptcha,
+ ),
+ },
+ action: () async {
+ switch (config.captchaType) {
+ case CaptchaType.customJavaScript:
+ await service.loadForCustomScript(
+ url: searchUrl,
+ script: config.captchaScript,
+ pluginName: plugin.name,
+ onVerified: verified.complete,
+ );
+ case CaptchaType.autoClickButton:
+ await service.loadForButtonClick(
+ url: searchUrl,
+ buttonXpath: config.captchaButton,
+ pluginName: plugin.name,
+ onVerified: verified.complete,
+ );
+ default:
+ break;
+ }
+ return verified.future;
+ },
+ );
+ } finally {
+ timeout?.cancel();
+ service.dispose();
+ }
onVerified(plugin, pageHtml);
- }));
-
- KazumiDialog.show(
- onDismiss: () async {
- final captchaService = _service;
- _service = null;
- if (verified) {
- captchaService?.dispose();
- } else {
- await captchaService?.cancelAndSave(plugin.name);
- captchaService?.dispose();
- onCancelled(plugin);
- }
- },
- builder: (context) => _AutomatedVerifyDialog(
- pluginName: plugin.name,
- ),
- );
+ }, onCancelled: () => onCancelled(plugin), errorMessage: '验证失败,请稍后重试'));
}
}
@@ -344,7 +286,7 @@ class _CaptchaDialogState extends State<_CaptchaDialog> {
actions: [
TextButton(
style: TextButton.styleFrom(minimumSize: const Size(72, 48)),
- onPressed: KazumiDialog.dismiss,
+ onPressed: () => KazumiDialog.dismiss(context: context),
child: const Text('返回来源'),
),
FilledButton(
@@ -463,7 +405,7 @@ class _AutomatedVerifyDialog extends StatelessWidget {
actions: [
TextButton(
style: TextButton.styleFrom(minimumSize: const Size(72, 48)),
- onPressed: KazumiDialog.dismiss,
+ onPressed: () => KazumiDialog.dismiss(context: context),
child: const Text('返回来源'),
),
],
@@ -476,7 +418,9 @@ class _AutomatedVerifyDialog extends StatelessWidget {
}
class _VerificationCompleteDialog extends StatefulWidget {
- const _VerificationCompleteDialog({required this.pluginName});
+ const _VerificationCompleteDialog({
+ required this.pluginName,
+ });
final String pluginName;
@@ -492,8 +436,9 @@ class _VerificationCompleteDialogState
@override
void initState() {
super.initState();
- _closeTimer = Timer(
- const Duration(seconds: 3), () => Navigator.of(context).pop(true));
+ _closeTimer = Timer(const Duration(seconds: 3), () {
+ KazumiDialog.dismiss(context: context, popWith: true);
+ });
}
@override
@@ -505,20 +450,23 @@ class _VerificationCompleteDialogState
@override
Widget build(BuildContext context) {
final colors = Theme.of(context).colorScheme;
- return _VerifyDialogFrame(
- pluginName: widget.pluginName,
- title: '验证通过',
- description: '即将自动继续检索。',
- child: Center(
- child: Container(
- width: 64,
- height: 64,
- decoration: BoxDecoration(
- color: colors.primaryContainer,
- shape: BoxShape.circle,
+ return PopScope(
+ canPop: false,
+ child: _VerifyDialogFrame(
+ pluginName: widget.pluginName,
+ title: '验证通过',
+ description: '即将自动继续检索。',
+ child: Center(
+ child: Container(
+ width: 64,
+ height: 64,
+ decoration: BoxDecoration(
+ color: colors.primaryContainer,
+ shape: BoxShape.circle,
+ ),
+ child: Icon(Icons.check_rounded,
+ color: colors.onPrimaryContainer, size: 32),
),
- child: Icon(Icons.check_rounded,
- color: colors.onPrimaryContainer, size: 32),
),
),
);
diff --git a/lib/pages/info/source_sheet.dart b/lib/pages/info/source_sheet.dart
index 9dad3a24..10f1fcd5 100644
--- a/lib/pages/info/source_sheet.dart
+++ b/lib/pages/info/source_sheet.dart
@@ -40,7 +40,7 @@ class SourceSheet extends StatefulWidget {
State<SourceSheet> createState() => _SourceSheetState();
}
-class _SourceSheetState extends State<SourceSheet> {
+class _SourceSheetState extends State<SourceSheet> with KazumiDialogOwner {
final CollectController _collectController = inject<CollectController>();
final PluginsController _pluginsController = inject<PluginsController>();
final Map<String, String> _sourceKeywords = {};
@@ -48,7 +48,6 @@ class _SourceSheetState extends State<SourceSheet> {
late final String _keyword;
late final PluginSearchService _searchService;
late final _SourceCaptchaFlow _captchaFlow;
- RuleCancelToken? _chapterCancelToken;
@override
void initState() {
@@ -68,7 +67,6 @@ class _SourceSheetState extends State<SourceSheet> {
@override
void dispose() {
- _chapterCancelToken?.cancel();
_searchService.cancel();
_captchaFlow.dispose();
super.dispose();
@@ -120,40 +118,32 @@ class _SourceSheetState extends State<SourceSheet> {
}
Future<void> _openSearchItem(String name, SearchItem searchItem) async {
- if (_chapterCancelToken != null) return;
+ if (dialogs.isRunning) return;
final plugin = _pluginFor(name);
- final cancelToken = _chapterCancelToken = RuleCancelToken();
- KazumiDialog.showLoading(
- msg: '正在获取播放列表',
- barrierDismissible: isDesktop(),
- onDismiss: cancelToken.cancel,
- );
- try {
- final roads = await plugin.queryChapterRoads(
- searchItem.src,
- cancelToken: cancelToken,
+ await dialogs.run((task) async {
+ final cancelToken = RuleCancelToken();
+ final roads = await task.loading(
+ message: '正在获取播放列表',
+ barrierDismissible: isDesktop(),
+ onCancel: cancelToken.cancel,
+ action: () =>
+ plugin.queryChapterRoads(searchItem.src, cancelToken: cancelToken),
);
- if (!mounted || cancelToken.isCancelled) return;
if (roads.isEmpty) throw ChapterErrorException(plugin.name);
- KazumiDialog.dismiss();
- context.pushNamed(
- '/video/',
- arguments: OnlineVideoPlaybackArgs(
- bangumiItem: widget.infoController.bangumiItem,
- plugin: plugin,
- title: searchItem.name,
- src: searchItem.src,
- roads: roads,
- ),
- );
- } catch (error) {
- if (!mounted || cancelToken.isCancelled) return;
+ task.withContext((context) => context.pushNamed(
+ '/video/',
+ arguments: OnlineVideoPlaybackArgs(
+ bangumiItem: widget.infoController.bangumiItem,
+ plugin: plugin,
+ title: searchItem.name,
+ src: searchItem.src,
+ roads: roads,
+ ),
+ ));
+ }, onError: (error, stackTrace) {
KazumiLogger().w('SourceSheet: failed to query playlist', error: error);
- KazumiDialog.dismiss();
KazumiDialog.showToast(message: '未能获取播放列表,请重试或选择其他结果');
- } finally {
- _chapterCancelToken = null;
- }
+ });
}
void _showAliasPicker(String pluginName) {
diff --git a/lib/pages/my/recent_watch_card.dart b/lib/pages/my/recent_watch_card.dart
index 81c860a3..eaf6f8bd 100644
--- a/lib/pages/my/recent_watch_card.dart
+++ b/lib/pages/my/recent_watch_card.dart
@@ -9,7 +9,6 @@ import 'package:kazumi/services/plugin/rule_engine_models.dart'
import 'package:kazumi/utils/date_time.dart';
import 'package:kazumi/utils/device.dart';
-/// Continue-watching card: opens playback, nothing else.
class RecentWatchCard extends StatefulWidget {
const RecentWatchCard({super.key, required this.item});
@@ -19,43 +18,31 @@ class RecentWatchCard extends StatefulWidget {
State<RecentWatchCard> createState() => _RecentWatchCardState();
}
-class _RecentWatchCardState extends State<RecentWatchCard> {
+class _RecentWatchCardState extends State<RecentWatchCard>
+ with KazumiDialogOwner {
static const double _coverWidth = 78;
static const double _coverHeight = 104;
final HistoryPlaybackService _playbackService =
inject<HistoryPlaybackService>();
- RuleCancelToken? _cancelToken;
-
- @override
- void dispose() {
- _cancelToken?.cancel();
- super.dispose();
- }
-
- Future<void> _play() async {
- _cancelToken?.cancel();
- final cancelToken = RuleCancelToken();
- _cancelToken = cancelToken;
- KazumiDialog.showLoading(
- msg: '获取中',
- barrierDismissible: isDesktop(),
- onDismiss: cancelToken.cancel,
- );
- final result = await _playbackService.open(
- widget.item.history,
- cancelToken: cancelToken,
- );
- KazumiDialog.dismiss();
- if (!mounted) return;
- switch (result) {
- case HistoryPlaybackReady(:final args):
- context.pushNamed('/video/', arguments: args);
- case HistoryPlaybackUnavailable(:final reason):
- KazumiDialog.showToast(message: reason);
- }
- }
+ Future<void> _play() => dialogs.run((task) async {
+ final cancelToken = RuleCancelToken();
+ final result = await task.loading(
+ message: '获取中',
+ barrierDismissible: isDesktop(),
+ onCancel: cancelToken.cancel,
+ action: () => _playbackService.open(widget.item.history,
+ cancelToken: cancelToken),
+ );
+ switch (result) {
+ case HistoryPlaybackReady(:final args):
+ task.withContext(
+ (context) => context.pushNamed('/video/', arguments: args));
+ case HistoryPlaybackUnavailable(:final reason):
+ KazumiDialog.showToast(message: reason);
+ }
+ }, errorMessage: '暂时无法继续播放,请稍后重试');
@override
Widget build(BuildContext context) {
@@ -81,8 +68,6 @@ class _RecentWatchCardState extends State<RecentWatchCard> {
height: _coverHeight,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
- // Titles run one or two lines; splitting the slack keeps
- // both cases balanced against the cover height.
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
@@ -184,10 +169,8 @@ class _RecentWatchCardState extends State<RecentWatchCard> {
),
child: Text(
label,
- style: Theme.of(context)
- .textTheme
- .labelSmall
- ?.copyWith(color: foreground),
+ style:
+ Theme.of(context).textTheme.labelSmall?.copyWith(color: foreground),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
diff --git a/lib/pages/player/episode_comments_sheet.dart b/lib/pages/player/episode_comments_sheet.dart
index 291de231..42e97ecf 100644
--- a/lib/pages/player/episode_comments_sheet.dart
+++ b/lib/pages/player/episode_comments_sheet.dart
@@ -25,12 +25,12 @@ class EpisodeCommentsSheet extends StatefulWidget {
State<EpisodeCommentsSheet> createState() => _EpisodeCommentsSheetState();
}
-class _EpisodeCommentsSheetState extends State<EpisodeCommentsSheet> {
+class _EpisodeCommentsSheetState extends State<EpisodeCommentsSheet>
+ with KazumiDialogOwner {
VideoPageController get _controller => widget.videoPageController;
late int _selectedEpisode;
bool _isLoading = false;
bool _hasError = false;
- bool _isSelectingEpisode = false;
int _requestVersion = 0;
final Map<int, EpisodeInfo> _episodeInfoByIndex = {};
@@ -57,6 +57,7 @@ class _EpisodeCommentsSheetState extends State<EpisodeCommentsSheet> {
}
void _resetAndScheduleRefresh() {
+ dialogs.cancel();
final version = ++_requestVersion;
_selectedEpisode = widget.episode;
_hasError = false;
@@ -106,20 +107,14 @@ class _EpisodeCommentsSheetState extends State<EpisodeCommentsSheet> {
}
Future<void> _showEpisodeSelection() async {
- if (_isSelectingEpisode) return;
- _isSelectingEpisode = true;
+ if (dialogs.isRunning) return;
final controller = _controller;
- final selection = widget.selection;
- KazumiDialog.showLoading(msg: '分集列表加载中');
- try {
- final episodes =
- await BangumiApi.getBangumiEpisodesByID(controller.bangumiItem.id);
- KazumiDialog.dismiss();
- if (!mounted ||
- controller != _controller ||
- selection != widget.selection) {
- return;
- }
+ await dialogs.run((task) async {
+ final episodes = await task.loading(
+ message: '分集列表加载中',
+ action: () =>
+ BangumiApi.getBangumiEpisodesByID(controller.bangumiItem.id),
+ );
if (episodes.isEmpty) {
KazumiDialog.showToast(message: '未找到分集列表');
return;
@@ -127,25 +122,16 @@ class _EpisodeCommentsSheetState extends State<EpisodeCommentsSheet> {
for (var index = 0; index < episodes.length; index++) {
_rememberEpisodeInfo(index + 1, episodes[index]);
}
- final selected = await KazumiDialog.show<int>(
- context: context,
+ final selected = await task.show<int>(
builder: (context) => EpisodeCommentsPicker(
episodes: episodes,
selectedEpisode: _selectedEpisode,
),
);
- if (!mounted ||
- controller != _controller ||
- selection != widget.selection ||
- selected == null ||
- selected == _selectedEpisode) {
- return;
- }
+ if (selected == _selectedEpisode) return;
_selectedEpisode = selected;
unawaited(_loadComments());
- } finally {
- _isSelectingEpisode = false;
- }
+ }, errorMessage: '分集列表加载失败,请稍后重试');
}
@override
diff --git a/lib/pages/player/player_item.dart b/lib/pages/player/player_item.dart
index 3dc2f911..228630e9 100644
--- a/lib/pages/player/player_item.dart
+++ b/lib/pages/player/player_item.dart
@@ -72,7 +72,11 @@ class PlayerItem extends StatefulWidget {
}
class _PlayerItemState extends State<PlayerItem>
- with WindowListener, WidgetsBindingObserver, TickerProviderStateMixin {
+ with
+ WindowListener,
+ WidgetsBindingObserver,
+ TickerProviderStateMixin,
+ KazumiDialogOwner {
late final PlayerController playerController;
late final VideoPageController videoPageController =
widget.videoPageController;
@@ -782,7 +786,7 @@ class _PlayerItemState extends State<PlayerItem>
actions: [
TextButton(
onPressed: () {
- KazumiDialog.dismiss();
+ KazumiDialog.dismiss(context: context);
},
child: const Text('确定'),
),
@@ -835,7 +839,8 @@ class _PlayerItemState extends State<PlayerItem>
true,
);
}
- KazumiDialog.dismiss();
+ if (!context.mounted) return;
+ KazumiDialog.dismiss(context: context);
},
child: const Text('取消'),
),
@@ -848,7 +853,8 @@ class _PlayerItemState extends State<PlayerItem>
true,
);
}
- KazumiDialog.dismiss();
+ if (!context.mounted) return;
+ KazumiDialog.dismiss(context: context);
},
child: const Text('确认'),
),
@@ -857,7 +863,7 @@ class _PlayerItemState extends State<PlayerItem>
});
});
- if (confirmed) {
+ if (confirmed && mounted) {
playerController.setShader(mode);
}
} else {
@@ -1146,157 +1152,107 @@ class _PlayerItemState extends State<PlayerItem>
});
}
- void showDanmakuSearchDialog(String keyword) async {
- KazumiDialog.dismiss();
- KazumiDialog.showLoading(msg: '弹幕检索中');
- DanmakuSearchResponse danmakuSearchResponse;
- try {
- danmakuSearchResponse = await DanmakuApi.searchAnimes(keyword);
- } catch (e) {
- KazumiDialog.dismiss();
- KazumiDialog.showToast(message: '弹幕检索错误: ${e.toString()}');
- return;
- }
- KazumiDialog.dismiss();
- if (danmakuSearchResponse.animes.isEmpty) {
- KazumiDialog.showToast(message: '未找到匹配结果');
- return;
- }
- await KazumiDialog.show(builder: (context) {
- return Dialog(
- child: ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: 560),
- child: ListView(
- shrinkWrap: true,
- children: [
- if (danmakuSearchResponse.hasMore)
- Padding(
- padding: const EdgeInsets.fromLTRB(24, 16, 24, 8),
- child: Text(
- '结果较多,仅显示部分条目,可补充更完整的番剧名缩小范围',
- style: Theme.of(context).textTheme.bodySmall?.copyWith(
- color: Theme.of(context).colorScheme.outline,
- ),
- ),
- ),
- ...danmakuSearchResponse.animes.map((danmakuInfo) {
- return ListTile(
- title: Text(danmakuInfo.animeTitle),
- subtitle: danmakuInfo.typeDescription.isEmpty
- ? null
- : Text(danmakuInfo.typeDescription),
- onTap: () async {
- KazumiDialog.dismiss();
- KazumiDialog.showLoading(msg: '弹幕检索中');
- final DanmakuEpisodeResponse danmakuEpisodeResponse;
- try {
- danmakuEpisodeResponse =
- await DanmakuApi.getDanDanEpisodesByDanDanBangumiID(
- danmakuInfo.animeId);
- } catch (e) {
- KazumiDialog.dismiss();
- KazumiDialog.showToast(
- message: '弹幕检索错误: ${e.toString()}');
- return;
- }
- KazumiDialog.dismiss();
- if (danmakuEpisodeResponse.episodes.isEmpty) {
- KazumiDialog.showToast(message: '未找到匹配结果');
- return;
- }
- KazumiDialog.show(builder: (context) {
- return Dialog(
- child: ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: 560),
- child: ListView.builder(
- shrinkWrap: true,
- itemCount: danmakuEpisodeResponse.episodes.length,
- itemBuilder: (context, index) {
- final episode =
- danmakuEpisodeResponse.episodes[index];
- return ListTile(
- title: Text(episode.episodeTitle),
- onTap: () async {
- KazumiDialog.dismiss();
- try {
- videoPageController
- .cancelAutomaticDanmakuLoad();
- final hasDanmakus = await playerController
- .danmaku
- .getDanDanmakuByEpisodeID(
- episode.episodeId);
- if (!mounted) {
- return;
- }
- if (hasDanmakus) {
- playerController.danmaku
- .setDanmakuEnabled(true);
- KazumiDialog.showToast(message: '弹幕切换成功');
- } else {
- playerController.danmaku
- .setDanmakuEnabled(false);
- KazumiDialog.showToast(
- message: '未找到弹幕内容');
- }
- } catch (e) {
- KazumiDialog.showToast(message: '弹幕切换失败');
- }
- },
- );
- },
- ),
- ),
- );
- });
- },
- );
- }),
- ],
- ),
- ),
- );
- });
- }
-
- void showDanmakuSwitch() {
- String searchKeyword = videoPageController.title;
- KazumiDialog.show(
- builder: (context) {
- return AlertDialog(
- title: const Text('弹幕检索'),
- content: TextFormField(
- initialValue: searchKeyword,
- decoration: const InputDecoration(
- hintText: '番剧名',
+ Future<void> showDanmakuSwitch() => dialogs.run((task) async {
+ String keyword = videoPageController.title;
+ final query = await task.show<String>(
+ builder: (context) => AlertDialog(
+ title: const Text('弹幕检索'),
+ content: TextFormField(
+ initialValue: keyword,
+ decoration: const InputDecoration(hintText: '番剧名'),
+ onChanged: (value) => keyword = value,
+ onFieldSubmitted: (value) =>
+ KazumiDialog.dismiss(context: context, popWith: value),
),
- onChanged: (value) => searchKeyword = value,
- onFieldSubmitted: (keyword) {
- showDanmakuSearchDialog(keyword);
- },
+ actions: [
+ TextButton(
+ onPressed: () => KazumiDialog.dismiss(context: context),
+ child: const Text('取消'),
+ ),
+ TextButton(
+ onPressed: () =>
+ KazumiDialog.dismiss(context: context, popWith: keyword),
+ child: const Text('提交'),
+ ),
+ ],
),
- actions: [
- TextButton(
- onPressed: () {
- KazumiDialog.dismiss();
- },
- child: Text(
- '取消',
- style: TextStyle(color: Theme.of(context).colorScheme.outline),
+ );
+ final response = await task.loading(
+ message: '弹幕检索中',
+ action: () => DanmakuApi.searchAnimes(query),
+ );
+ if (response.animes.isEmpty) {
+ KazumiDialog.showToast(message: '未找到匹配结果');
+ return;
+ }
+ final anime = await task.show<DanmakuSearchAnime>(
+ builder: (context) => Dialog(
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 560),
+ child: ListView(
+ shrinkWrap: true,
+ children: [
+ if (response.hasMore)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(24, 16, 24, 8),
+ child: Text(
+ '结果较多,仅显示部分条目,可补充更完整的番剧名缩小范围',
+ style: Theme.of(context).textTheme.bodySmall?.copyWith(
+ color: Theme.of(context).colorScheme.outline,
+ ),
+ ),
+ ),
+ for (final anime in response.animes)
+ ListTile(
+ title: Text(anime.animeTitle),
+ subtitle: anime.typeDescription.isEmpty
+ ? null
+ : Text(anime.typeDescription),
+ onTap: () => KazumiDialog.dismiss(
+ context: context, popWith: anime),
+ ),
+ ],
),
),
- TextButton(
- onPressed: () {
- showDanmakuSearchDialog(searchKeyword);
- },
- child: const Text(
- '提交',
+ ),
+ );
+ final episodeResponse = await task.loading(
+ message: '弹幕检索中',
+ action: () =>
+ DanmakuApi.getDanDanEpisodesByDanDanBangumiID(anime.animeId),
+ );
+ if (episodeResponse.episodes.isEmpty) {
+ KazumiDialog.showToast(message: '未找到匹配结果');
+ return;
+ }
+ final episode = await task.show<DanmakuEpisode>(
+ builder: (context) => Dialog(
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 560),
+ child: ListView.builder(
+ shrinkWrap: true,
+ itemCount: episodeResponse.episodes.length,
+ itemBuilder: (context, index) {
+ final episode = episodeResponse.episodes[index];
+ return ListTile(
+ title: Text(episode.episodeTitle),
+ onTap: () => KazumiDialog.dismiss(
+ context: context, popWith: episode),
+ );
+ },
),
),
- ],
+ ),
);
- },
- );
- }
+ videoPageController.cancelAutomaticDanmakuLoad();
+ final hasDanmakus = await task.wait(
+ playerController.danmaku.getDanDanmakuByEpisodeID(episode.episodeId),
+ );
+ playerController.danmaku.setDanmakuEnabled(hasDanmakus);
+ KazumiDialog.showToast(message: hasDanmakus ? '弹幕切换成功' : '未找到弹幕内容');
+ }, onError: (error, stackTrace) {
+ KazumiDialog.showToast(message: '弹幕检索错误: $error');
+ });
void showVideoInfo() {
showVideoDetailsSheet(context, playerController: playerController);
diff --git a/lib/pages/plugin_editor/rule_dialogs.dart b/lib/pages/plugin_editor/rule_dialogs.dart
index d4e20e7f..9d42c566 100644
--- a/lib/pages/plugin_editor/rule_dialogs.dart
+++ b/lib/pages/plugin_editor/rule_dialogs.dart
@@ -159,7 +159,7 @@ Future<void> showRuleShareDialog(BuildContext context, Plugin plugin) async {
try {
await Clipboard.setData(ClipboardData(text: link));
if (!context.mounted) return;
- Navigator.of(context).pop();
+ KazumiDialog.dismiss(context: context);
KazumiDialog.showToast(message: '规则链接已复制');
} catch (_) {
if (context.mounted) {
@@ -222,7 +222,7 @@ class _RuleImportDialogState extends State<_RuleImportDialog> {
try {
await widget.controller.updatePlugins(result.plugins);
if (!mounted) return;
- Navigator.of(context).pop();
+ KazumiDialog.dismiss(context: context);
KazumiDialog.showToast(
message: '已导入 ${result.plugins.length} 条规则'
',跳过重复 ${result.duplicateCount} 条,失败 ${result.failureCount} 条');
diff --git a/lib/pages/search/image_search_page.dart b/lib/pages/search/image_search_page.dart
index c56745dc..cfea8ce1 100644
--- a/lib/pages/search/image_search_page.dart
+++ b/lib/pages/search/image_search_page.dart
@@ -11,6 +11,7 @@ import 'package:path/path.dart' as path;
import 'package:url_launcher/url_launcher.dart';
import 'package:kazumi/bean/appbar/sys_app_bar.dart';
+import 'package:kazumi/bean/dialog/dialog_helper.dart';
import 'package:kazumi/bean/widget/empty_state_widget.dart';
import 'package:kazumi/bean/widget/error_widget.dart';
import 'package:kazumi/bean/widget/loading_indicator.dart';
@@ -200,13 +201,11 @@ class _ImageSearchPageState extends State<ImageSearchPage> {
// Fall through to the shared error message.
}
if (!mounted) return;
- ScaffoldMessenger.of(context).showSnackBar(
- const SnackBar(content: Text('暂时无法打开链接,请稍后再试')),
- );
+ KazumiDialog.showToast(context: context, message: '暂时无法打开链接,请稍后再试');
}
void _showHelp() {
- showDialog<void>(
+ KazumiDialog.show<void>(
context: context,
builder: (context) => AlertDialog(
icon: const Icon(Icons.image_search_rounded),
diff --git a/lib/pages/settings/danmaku/danmaku_settings.dart b/lib/pages/settings/danmaku/danmaku_settings.dart
index 498b3f2f..4bd222e1 100644
--- a/lib/pages/settings/danmaku/danmaku_settings.dart
+++ b/lib/pages/settings/danmaku/danmaku_settings.dart
@@ -99,13 +99,6 @@ class _DanmakuSettingsPageState extends State<DanmakuSettingsPage> {
KazumiDialog.showToast(message: '已恢复默认弹幕设置');
}
- void onBackPressed(BuildContext context) {
- if (KazumiDialog.observer.hasKazumiDialog) {
- KazumiDialog.dismiss();
- return;
- }
- }
-
void updateDanmakuArea(double i) async {
await GStorage.putSetting<double>(SettingsKeys.danmakuArea, i);
setState(() {
@@ -157,253 +150,246 @@ class _DanmakuSettingsPageState extends State<DanmakuSettingsPage> {
@override
Widget build(BuildContext context) {
- return PopScope(
- canPop: true,
- onPopInvokedWithResult: (bool didPop, Object? result) {
- onBackPressed(context);
- },
- child: SettingsDetailScaffold(
- title: const Text('弹幕设置'),
- body: SettingsList(
- sections: [
- SettingsSection(
- title: Text('弹幕来源'),
- tiles: [
- SettingsTile.switchTile(
- leading: Icons.live_tv_rounded,
- onToggle: (value) async {
- danmakuBiliBiliSource = value ?? !danmakuBiliBiliSource;
- await GStorage.putSetting<bool>(
- SettingsKeys.danmakuBiliBiliSource,
- danmakuBiliBiliSource);
- setState(() {});
- },
- title: Text('BiliBili'),
- initialValue: danmakuBiliBiliSource,
- ),
- SettingsTile.switchTile(
- leading: Icons.sports_esports_rounded,
- onToggle: (value) async {
- danmakuGamerSource = value ?? !danmakuGamerSource;
- await GStorage.putSetting<bool>(
- SettingsKeys.danmakuGamerSource, danmakuGamerSource);
- setState(() {});
- },
- title: Text('Gamer'),
- initialValue: danmakuGamerSource,
- ),
- SettingsTile.switchTile(
- leading: Icons.forum_rounded,
- onToggle: (value) async {
- danmakuDanDanSource = value ?? !danmakuDanDanSource;
- await GStorage.putSetting<bool>(
- SettingsKeys.danmakuDanDanSource, danmakuDanDanSource);
- setState(() {});
- },
- title: Text('弹弹play'),
- initialValue: danmakuDanDanSource,
- ),
- ],
- ),
- SettingsSection(
- title: Text('弹幕屏蔽'),
- tiles: [
- SettingsTile(
- leading: Icons.block_rounded,
- onPressed: (_) {
- context.pushNamed('/settings/danmaku/shield');
- },
- title: Text('关键词屏蔽'),
- ),
- ],
- ),
- SettingsSection(
- title: Text('弹幕显示'),
- tiles: [
- SettingsSliderTile(
- leading: Icons.crop_free_rounded,
- title: Text('弹幕区域'),
- value: defaultDanmakuArea,
- min: 0,
- max: 1,
- divisions: 8,
- valueLabel: '${(defaultDanmakuArea * 100).round()}%',
- onChanged: updateDanmakuArea,
- ),
- SettingsSliderTile(
- leading: Icons.timer_rounded,
- title: Text('弹幕持续时间'),
- value: defaultDanmakuDuration,
- min: 2,
- max: 16,
- divisions: 14,
- valueLabel: '${defaultDanmakuDuration.round()} 秒',
- onChanged: (value) =>
- updateDanmakuDuration(value.roundToDouble()),
- ),
- SettingsSliderTile(
- leading: Icons.format_line_spacing_rounded,
- title: Text('弹幕行高'),
- value: defaultDanmakuLineHeight,
- min: 0,
- max: 3,
- divisions: 30,
- valueLabel: defaultDanmakuLineHeight.toStringAsFixed(1),
- onChanged: (value) => updateDanmakuLineHeight(
- double.parse(value.toStringAsFixed(1))),
- ),
- SettingsTile.switchTile(
- leading: Icons.speed_rounded,
- onToggle: (value) async {
- danmakuFollowSpeed = value ?? !danmakuFollowSpeed;
- await GStorage.putSetting<bool>(
- SettingsKeys.danmakuFollowSpeed, danmakuFollowSpeed);
- setState(() {});
- },
- title: Text('弹幕跟随视频倍速'),
- description: Text('开启后弹幕速度会随视频倍速而改变'),
- initialValue: danmakuFollowSpeed,
- ),
- SettingsTile.switchTile(
- leading: Icons.vertical_align_top_rounded,
- onToggle: (value) async {
- danmakuTop = value ?? !danmakuTop;
- await GStorage.putSetting<bool>(
- SettingsKeys.danmakuTop, danmakuTop);
- setState(() {});
- },
- title: Text('顶部弹幕'),
- initialValue: danmakuTop,
- ),
- SettingsTile.switchTile(
- leading: Icons.vertical_align_bottom_rounded,
- onToggle: (value) async {
- danmakuBottom = value ?? !danmakuBottom;
- await GStorage.putSetting<bool>(
- SettingsKeys.danmakuBottom, danmakuBottom);
- setState(() {});
- },
- title: Text('底部弹幕'),
- initialValue: danmakuBottom,
- ),
- SettingsTile.switchTile(
- leading: Icons.swap_horiz_rounded,
- onToggle: (value) async {
- danmakuScroll = value ?? !danmakuScroll;
- await GStorage.putSetting<bool>(
- SettingsKeys.danmakuScroll, danmakuScroll);
- setState(() {});
- },
- title: Text('滚动弹幕'),
- initialValue: danmakuScroll,
- ),
- SettingsTile.switchTile(
- leading: Icons.layers_rounded,
- onToggle: (value) async {
- danmakuMassive = value ?? !danmakuMassive;
- await GStorage.putSetting<bool>(
- SettingsKeys.danmakuMassive, danmakuMassive);
- setState(() {});
- },
- title: Text('海量弹幕'),
- description: Text('弹幕过多时进行叠加绘制'),
- initialValue: danmakuMassive,
- ),
- SettingsTile.switchTile(
- leading: Icons.filter_alt_rounded,
- onToggle: (value) async {
- danmakuDeduplication = value ?? !danmakuDeduplication;
- await GStorage.putSetting<bool>(
- SettingsKeys.danmakuDeduplication,
- danmakuDeduplication);
- setState(() {});
- },
- title: Text('弹幕去重'),
- description: Text('相同内容弹幕过多时合并为一条弹幕'),
- initialValue: danmakuDeduplication,
- ),
- ],
- ),
- SettingsSection(
- title: Text('弹幕样式'),
- tiles: [
- SettingsTile.switchTile(
- leading: Icons.border_color_rounded,
- onToggle: (value) async {
- danmakuBorder = value ?? !danmakuBorder;
- await GStorage.putSetting<bool>(
- SettingsKeys.danmakuBorder, danmakuBorder);
- setState(() {});
- },
- title: Text('弹幕描边'),
- initialValue: danmakuBorder,
- ),
- SettingsSliderTile(
- leading: Icons.line_weight_rounded,
- title: Text('弹幕描边粗细'),
- value: defaultdanmakuBorderSize,
- min: 0.1,
- max: 3,
- divisions: 29,
- valueLabel: defaultdanmakuBorderSize.toStringAsFixed(1),
- onChanged: (value) => updateDanmakuBorderSize(
- double.parse(value.toStringAsFixed(1))),
- ),
- SettingsTile.switchTile(
- leading: Icons.palette_rounded,
- onToggle: (value) async {
- danmakuColor = value ?? !danmakuColor;
- await GStorage.putSetting<bool>(
- SettingsKeys.danmakuColor, danmakuColor);
- setState(() {});
- },
- title: Text('弹幕颜色'),
- initialValue: danmakuColor,
- ),
- SettingsSliderTile(
- leading: Icons.format_size_rounded,
- title: Text('字体大小'),
- value: defaultDanmakuFontSize,
- min: 10,
- max: isCompact() ? 32 : 48,
- valueLabel: '${defaultDanmakuFontSize.floor()}',
- onChanged: (value) =>
- updateDanmakuFontSize(value.floorToDouble()),
- ),
- SettingsSliderTile(
- leading: Icons.format_bold_rounded,
- title: Text('字体字重'),
- value: defaultDanmakuFontWeight.toDouble(),
- min: 1,
- max: 9,
- divisions: 8,
- valueLabel: '$defaultDanmakuFontWeight',
- onChanged: (value) => updateDanmakuFontWeight(value.toInt()),
- ),
- SettingsSliderTile(
- leading: Icons.opacity_rounded,
- title: Text('弹幕不透明度'),
- value: defaultDanmakuOpacity,
- min: 0.1,
- max: 1,
- valueLabel: '${(defaultDanmakuOpacity * 100).round()}%',
- onChanged: (value) => updateDanmakuOpacity(
- double.parse(value.toStringAsFixed(2))),
- ),
- ],
- ),
- SettingsSection(
- tiles: [
- SettingsTile(
- leading: Icons.settings_backup_restore_rounded,
- onPressed: (_) => resetDanmakuSettings(),
- title: Text('恢复默认设置'),
- description: Text('将弹幕相关设置恢复为默认值'),
- ),
- ],
- ),
- ],
- ),
+ return SettingsDetailScaffold(
+ title: const Text('弹幕设置'),
+ body: SettingsList(
+ sections: [
+ SettingsSection(
+ title: Text('弹幕来源'),
+ tiles: [
+ SettingsTile.switchTile(
+ leading: Icons.live_tv_rounded,
+ onToggle: (value) async {
+ danmakuBiliBiliSource = value ?? !danmakuBiliBiliSource;
+ await GStorage.putSetting<bool>(
+ SettingsKeys.danmakuBiliBiliSource,
+ danmakuBiliBiliSource);
+ setState(() {});
+ },
+ title: Text('BiliBili'),
+ initialValue: danmakuBiliBiliSource,
+ ),
+ SettingsTile.switchTile(
+ leading: Icons.sports_esports_rounded,
+ onToggle: (value) async {
+ danmakuGamerSource = value ?? !danmakuGamerSource;
+ await GStorage.putSetting<bool>(
+ SettingsKeys.danmakuGamerSource, danmakuGamerSource);
+ setState(() {});
+ },
+ title: Text('Gamer'),
+ initialValue: danmakuGamerSource,
+ ),
+ SettingsTile.switchTile(
+ leading: Icons.forum_rounded,
+ onToggle: (value) async {
+ danmakuDanDanSource = value ?? !danmakuDanDanSource;
+ await GStorage.putSetting<bool>(
+ SettingsKeys.danmakuDanDanSource, danmakuDanDanSource);
+ setState(() {});
+ },
+ title: Text('弹弹play'),
+ initialValue: danmakuDanDanSource,
+ ),
+ ],
+ ),
+ SettingsSection(
+ title: Text('弹幕屏蔽'),
+ tiles: [
+ SettingsTile(
+ leading: Icons.block_rounded,
+ onPressed: (_) {
+ context.pushNamed('/settings/danmaku/shield');
+ },
+ title: Text('关键词屏蔽'),
+ ),
+ ],
+ ),
+ SettingsSection(
+ title: Text('弹幕显示'),
+ tiles: [
+ SettingsSliderTile(
+ leading: Icons.crop_free_rounded,
+ title: Text('弹幕区域'),
+ value: defaultDanmakuArea,
+ min: 0,
+ max: 1,
+ divisions: 8,
+ valueLabel: '${(defaultDanmakuArea * 100).round()}%',
+ onChanged: updateDanmakuArea,
+ ),
+ SettingsSliderTile(
+ leading: Icons.timer_rounded,
+ title: Text('弹幕持续时间'),
+ value: defaultDanmakuDuration,
+ min: 2,
+ max: 16,
+ divisions: 14,
+ valueLabel: '${defaultDanmakuDuration.round()} 秒',
+ onChanged: (value) =>
+ updateDanmakuDuration(value.roundToDouble()),
+ ),
+ SettingsSliderTile(
+ leading: Icons.format_line_spacing_rounded,
+ title: Text('弹幕行高'),
+ value: defaultDanmakuLineHeight,
+ min: 0,
+ max: 3,
+ divisions: 30,
+ valueLabel: defaultDanmakuLineHeight.toStringAsFixed(1),
+ onChanged: (value) => updateDanmakuLineHeight(
+ double.parse(value.toStringAsFixed(1))),
+ ),
+ SettingsTile.switchTile(
+ leading: Icons.speed_rounded,
+ onToggle: (value) async {
+ danmakuFollowSpeed = value ?? !danmakuFollowSpeed;
+ await GStorage.putSetting<bool>(
+ SettingsKeys.danmakuFollowSpeed, danmakuFollowSpeed);
+ setState(() {});
+ },
+ title: Text('弹幕跟随视频倍速'),
+ description: Text('开启后弹幕速度会随视频倍速而改变'),
+ initialValue: danmakuFollowSpeed,
+ ),
+ SettingsTile.switchTile(
+ leading: Icons.vertical_align_top_rounded,
+ onToggle: (value) async {
+ danmakuTop = value ?? !danmakuTop;
+ await GStorage.putSetting<bool>(
+ SettingsKeys.danmakuTop, danmakuTop);
+ setState(() {});
+ },
+ title: Text('顶部弹幕'),
+ initialValue: danmakuTop,
+ ),
+ SettingsTile.switchTile(
+ leading: Icons.vertical_align_bottom_rounded,
+ onToggle: (value) async {
+ danmakuBottom = value ?? !danmakuBottom;
+ await GStorage.putSetting<bool>(
+ SettingsKeys.danmakuBottom, danmakuBottom);
+ setState(() {});
+ },
+ title: Text('底部弹幕'),
+ initialValue: danmakuBottom,
+ ),
+ SettingsTile.switchTile(
+ leading: Icons.swap_horiz_rounded,
+ onToggle: (value) async {
+ danmakuScroll = value ?? !danmakuScroll;
+ await GStorage.putSetting<bool>(
+ SettingsKeys.danmakuScroll, danmakuScroll);
+ setState(() {});
+ },
+ title: Text('滚动弹幕'),
+ initialValue: danmakuScroll,
+ ),
+ SettingsTile.switchTile(
+ leading: Icons.layers_rounded,
+ onToggle: (value) async {
+ danmakuMassive = value ?? !danmakuMassive;
+ await GStorage.putSetting<bool>(
+ SettingsKeys.danmakuMassive, danmakuMassive);
+ setState(() {});
+ },
+ title: Text('海量弹幕'),
+ description: Text('弹幕过多时进行叠加绘制'),
+ initialValue: danmakuMassive,
+ ),
+ SettingsTile.switchTile(
+ leading: Icons.filter_alt_rounded,
+ onToggle: (value) async {
+ danmakuDeduplication = value ?? !danmakuDeduplication;
+ await GStorage.putSetting<bool>(
+ SettingsKeys.danmakuDeduplication, danmakuDeduplication);
+ setState(() {});
+ },
+ title: Text('弹幕去重'),
+ description: Text('相同内容弹幕过多时合并为一条弹幕'),
+ initialValue: danmakuDeduplication,
+ ),
+ ],
+ ),
+ SettingsSection(
+ title: Text('弹幕样式'),
+ tiles: [
+ SettingsTile.switchTile(
+ leading: Icons.border_color_rounded,
+ onToggle: (value) async {
+ danmakuBorder = value ?? !danmakuBorder;
+ await GStorage.putSetting<bool>(
+ SettingsKeys.danmakuBorder, danmakuBorder);
+ setState(() {});
+ },
+ title: Text('弹幕描边'),
+ initialValue: danmakuBorder,
+ ),
+ SettingsSliderTile(
+ leading: Icons.line_weight_rounded,
+ title: Text('弹幕描边粗细'),
+ value: defaultdanmakuBorderSize,
+ min: 0.1,
+ max: 3,
+ divisions: 29,
+ valueLabel: defaultdanmakuBorderSize.toStringAsFixed(1),
+ onChanged: (value) => updateDanmakuBorderSize(
+ double.parse(value.toStringAsFixed(1))),
+ ),
+ SettingsTile.switchTile(
+ leading: Icons.palette_rounded,
+ onToggle: (value) async {
+ danmakuColor = value ?? !danmakuColor;
+ await GStorage.putSetting<bool>(
+ SettingsKeys.danmakuColor, danmakuColor);
+ setState(() {});
+ },
+ title: Text('弹幕颜色'),
+ initialValue: danmakuColor,
+ ),
+ SettingsSliderTile(
+ leading: Icons.format_size_rounded,
+ title: Text('字体大小'),
+ value: defaultDanmakuFontSize,
+ min: 10,
+ max: isCompact() ? 32 : 48,
+ valueLabel: '${defaultDanmakuFontSize.floor()}',
+ onChanged: (value) =>
+ updateDanmakuFontSize(value.floorToDouble()),
+ ),
+ SettingsSliderTile(
+ leading: Icons.format_bold_rounded,
+ title: Text('字体字重'),
+ value: defaultDanmakuFontWeight.toDouble(),
+ min: 1,
+ max: 9,
+ divisions: 8,
+ valueLabel: '$defaultDanmakuFontWeight',
+ onChanged: (value) => updateDanmakuFontWeight(value.toInt()),
+ ),
+ SettingsSliderTile(
+ leading: Icons.opacity_rounded,
+ title: Text('弹幕不透明度'),
+ value: defaultDanmakuOpacity,
+ min: 0.1,
+ max: 1,
+ valueLabel: '${(defaultDanmakuOpacity * 100).round()}%',
+ onChanged: (value) => updateDanmakuOpacity(
+ double.parse(value.toStringAsFixed(2))),
+ ),
+ ],
+ ),
+ SettingsSection(
+ tiles: [
+ SettingsTile(
+ leading: Icons.settings_backup_restore_rounded,
+ onPressed: (_) => resetDanmakuSettings(),
+ title: Text('恢复默认设置'),
+ description: Text('将弹幕相关设置恢复为默认值'),
+ ),
+ ],
+ ),
+ ],
),
);
}
diff --git a/lib/pages/settings/player_settings.dart b/lib/pages/settings/player_settings.dart
index 7cf40e21..5cac42c8 100644
--- a/lib/pages/settings/player_settings.dart
+++ b/lib/pages/settings/player_settings.dart
@@ -132,13 +132,6 @@ class _PlayerSettingsPageState extends State<PlayerSettingsPage> {
KazumiDialog.showToast(message: '已恢复默认播放设置');
}
- void onBackPressed(BuildContext context) {
- if (KazumiDialog.observer.hasKazumiDialog) {
- KazumiDialog.dismiss();
- return;
- }
- }
-
void updateDefaultPlaySpeed(double speed) {
GStorage.putSetting<double>(SettingsKeys.defaultPlaySpeed, speed);
setState(() {
@@ -194,11 +187,10 @@ class _PlayerSettingsPageState extends State<PlayerSettingsPage> {
builder: (BuildContext context, StateSetter setState) {
return TextField(
inputFormatters: [
- FilteringTextInputFormatter.digitsOnly, // 只允许输入数字
+ FilteringTextInputFormatter.digitsOnly,
],
decoration: InputDecoration(
- floatingLabelBehavior:
- FloatingLabelBehavior.never, // 控制label的显示方式
+ floatingLabelBehavior: FloatingLabelBehavior.never,
labelText: initialValue,
),
onChanged: (value) {
@@ -227,7 +219,6 @@ class _PlayerSettingsPageState extends State<PlayerSettingsPage> {
KazumiDialog.showToast(message: '请输入大于0的数字');
return;
}
- // 以新设置的值弹出
KazumiDialog.dismiss(popWith: newValue);
},
child: const Text('确定'),
@@ -265,395 +256,385 @@ class _PlayerSettingsPageState extends State<PlayerSettingsPage> {
@override
Widget build(BuildContext context) {
- return PopScope(
- canPop: true,
- onPopInvokedWithResult: (bool didPop, Object? result) {
- onBackPressed(context);
- },
- child: SettingsDetailScaffold(
- title: const Text('播放设置'),
- body: SettingsList(
- sections: [
- SettingsSection(
- title: Text('解码与渲染'),
- tiles: [
- SettingsTile.switchTile(
- leading: Icons.memory_rounded,
- onToggle: (value) async {
- hAenable = value ?? !hAenable;
- await GStorage.putSetting<bool>(
- SettingsKeys.hAenable, hAenable);
- setState(() {});
- },
- title: Text('硬件解码'),
- initialValue: hAenable,
- ),
- SettingsTile(
- leading: Icons.developer_board_rounded,
- onPressed: (_) async {
- await context.pushNamed('/settings/player/decoder');
- },
- title: Text('硬件解码器'),
- description: Text('仅在硬件解码启用时生效'),
- ),
- if (Platform.isAndroid) ...[
- SettingsTile(
- leading: Icons.tv_rounded,
- onPressed: (_) async {
- await context.pushNamed('/settings/player/renderer');
- },
- title: Text('视频渲染器'),
- description: Text('选择视频输出方式'),
- ),
- ],
- SettingsTile.switchTile(
- leading: Icons.data_saver_on_rounded,
- enabled: !MeteredNetworkService.isMetered,
- onToggle: (value) async {
- lowMemoryMode = value ?? !lowMemoryMode;
- await GStorage.putSetting<bool>(
- SettingsKeys.lowMemoryMode, lowMemoryMode);
- setState(() {});
- },
- title: Text('低内存模式'),
- description: Text(MeteredNetworkService.isMetered
- ? '移动网络下已自动启用'
- : '禁用高级缓存以减少内存占用'),
- // Effective state, not the stored one, which stays untouched.
- initialValue:
- lowMemoryMode || MeteredNetworkService.isMetered,
- ),
- if (Platform.isAndroid) ...[
- SettingsTile.switchTile(
- leading: Icons.graphic_eq_rounded,
- onToggle: (value) async {
- androidEnableOpenSLES = value ?? !androidEnableOpenSLES;
- await GStorage.putSetting<bool>(
- SettingsKeys.androidEnableOpenSLES,
- androidEnableOpenSLES);
- setState(() {});
- },
- title: Text('低延迟音频'),
- description: Text('启用OpenSLES音频输出以降低延时'),
- initialValue: androidEnableOpenSLES,
- ),
- ],
+ return SettingsDetailScaffold(
+ title: const Text('播放设置'),
+ body: SettingsList(
+ sections: [
+ SettingsSection(
+ title: Text('解码与渲染'),
+ tiles: [
+ SettingsTile.switchTile(
+ leading: Icons.memory_rounded,
+ onToggle: (value) async {
+ hAenable = value ?? !hAenable;
+ await GStorage.putSetting<bool>(
+ SettingsKeys.hAenable, hAenable);
+ setState(() {});
+ },
+ title: Text('硬件解码'),
+ initialValue: hAenable,
+ ),
+ SettingsTile(
+ leading: Icons.developer_board_rounded,
+ onPressed: (_) async {
+ await context.pushNamed('/settings/player/decoder');
+ },
+ title: Text('硬件解码器'),
+ description: Text('仅在硬件解码启用时生效'),
+ ),
+ if (Platform.isAndroid) ...[
SettingsTile(
- leading: Icons.auto_awesome_rounded,
+ leading: Icons.tv_rounded,
onPressed: (_) async {
- context.pushNamed('/settings/player/super');
+ await context.pushNamed('/settings/player/renderer');
},
- title: Text('超分辨率'),
+ title: Text('视频渲染器'),
+ description: Text('选择视频输出方式'),
),
],
- ),
- SettingsSection(
- title: Text('播放行为'),
- tiles: [
- SettingsTile.switchTile(
- leading: Icons.headphones_rounded,
- onToggle: (value) async {
- backgroundPlayback = value ?? !backgroundPlayback;
- await GStorage.putSetting<bool>(
- SettingsKeys.backgroundPlayback, backgroundPlayback);
- setState(() {});
- },
- title: Text('后台播放'),
- description: Text('应用退到后台或熄屏时继续播放音频'),
- initialValue: backgroundPlayback,
- ),
- SettingsTile.switchTile(
- leading: Icons.history_rounded,
- onToggle: (value) async {
- playResume = value ?? !playResume;
- await GStorage.putSetting<bool>(
- SettingsKeys.playResume, playResume);
- setState(() {});
- },
- title: Text('自动跳转'),
- description: Text('跳转到上次播放位置'),
- initialValue: playResume,
- ),
- SettingsTile.switchTile(
- leading: Icons.playlist_play_rounded,
- onToggle: (value) async {
- autoPlayNext = value ?? !autoPlayNext;
- await GStorage.putSetting<bool>(
- SettingsKeys.autoPlayNext, autoPlayNext);
- setState(() {});
- },
- title: Text('自动连播'),
- description: Text('当前视频播放完毕后自动播放下一集'),
- initialValue: autoPlayNext,
- ),
- if (Platform.isAndroid)
- SettingsTile.switchTile(
- leading: Icons.picture_in_picture_alt_rounded,
- onToggle: (value) async {
- androidAutoEnterPIP = value ?? !androidAutoEnterPIP;
- await GStorage.putSetting<bool>(
- SettingsKeys.androidAutoEnterPIP,
- androidAutoEnterPIP);
- await PipUtils.setAndroidAutoEnterPIPEnabled(
- androidAutoEnterPIP);
- setState(() {});
- },
- title: Text('自动进入画中画'),
- description: Text('切到后台时,自动进入画中画'),
- initialValue: androidAutoEnterPIP,
- ),
- SettingsTile.switchTile(
- leading: Icons.block_rounded,
- onToggle: (value) async {
- forceAdBlocker = value ?? !forceAdBlocker;
- await GStorage.putSetting<bool>(
- SettingsKeys.forceAdBlocker, forceAdBlocker);
- setState(() {});
- },
- title: Text('广告过滤'),
- description: Text('强制启用HLS广告过滤,忽略规则设置'),
- initialValue: forceAdBlocker,
- ),
- SettingsTile.switchTile(
- leading: Icons.animation_rounded,
- onToggle: (value) async {
- playerDisableAnimations = value ?? !playerDisableAnimations;
- await GStorage.putSetting<bool>(
- SettingsKeys.playerDisableAnimations,
- playerDisableAnimations);
- setState(() {});
- },
- title: Text('禁用动画'),
- description: Text('禁用播放器内的过渡动画'),
- initialValue: playerDisableAnimations,
- ),
- if (!isDesktop())
- SettingsTile.switchTile(
- leading: Icons.swipe_vertical_rounded,
- onToggle: (value) async {
- brightnessVolumeGesture =
- value ?? !brightnessVolumeGesture;
- await GStorage.putSetting<bool>(
- SettingsKeys.brightnessVolumeGesture,
- brightnessVolumeGesture);
- setState(() {});
- },
- title: Text('滑动手势'),
- description: Text('竖向滑动调节音量和亮度'),
- initialValue: brightnessVolumeGesture,
- ),
+ SettingsTile.switchTile(
+ leading: Icons.data_saver_on_rounded,
+ enabled: !MeteredNetworkService.isMetered,
+ onToggle: (value) async {
+ lowMemoryMode = value ?? !lowMemoryMode;
+ await GStorage.putSetting<bool>(
+ SettingsKeys.lowMemoryMode, lowMemoryMode);
+ setState(() {});
+ },
+ title: Text('低内存模式'),
+ description: Text(MeteredNetworkService.isMetered
+ ? '移动网络下已自动启用'
+ : '禁用高级缓存以减少内存占用'),
+ // Effective state, not the stored one, which stays untouched.
+ initialValue: lowMemoryMode || MeteredNetworkService.isMetered,
+ ),
+ if (Platform.isAndroid) ...[
SettingsTile.switchTile(
- leading: Icons.visibility_off_rounded,
+ leading: Icons.graphic_eq_rounded,
onToggle: (value) async {
- privateMode = value ?? !privateMode;
+ androidEnableOpenSLES = value ?? !androidEnableOpenSLES;
await GStorage.putSetting<bool>(
- SettingsKeys.privateMode, privateMode);
+ SettingsKeys.androidEnableOpenSLES,
+ androidEnableOpenSLES);
setState(() {});
},
- title: Text('隐身模式'),
- description: Text('不保留观看记录'),
- initialValue: privateMode,
+ title: Text('低延迟音频'),
+ description: Text('启用OpenSLES音频输出以降低延时'),
+ initialValue: androidEnableOpenSLES,
),
],
- ),
- SettingsSection(
- title: Text('诊断'),
- tiles: [
+ SettingsTile(
+ leading: Icons.auto_awesome_rounded,
+ onPressed: (_) async {
+ context.pushNamed('/settings/player/super');
+ },
+ title: Text('超分辨率'),
+ ),
+ ],
+ ),
+ SettingsSection(
+ title: Text('播放行为'),
+ tiles: [
+ SettingsTile.switchTile(
+ leading: Icons.headphones_rounded,
+ onToggle: (value) async {
+ backgroundPlayback = value ?? !backgroundPlayback;
+ await GStorage.putSetting<bool>(
+ SettingsKeys.backgroundPlayback, backgroundPlayback);
+ setState(() {});
+ },
+ title: Text('后台播放'),
+ description: Text('应用退到后台或熄屏时继续播放音频'),
+ initialValue: backgroundPlayback,
+ ),
+ SettingsTile.switchTile(
+ leading: Icons.history_rounded,
+ onToggle: (value) async {
+ playResume = value ?? !playResume;
+ await GStorage.putSetting<bool>(
+ SettingsKeys.playResume, playResume);
+ setState(() {});
+ },
+ title: Text('自动跳转'),
+ description: Text('跳转到上次播放位置'),
+ initialValue: playResume,
+ ),
+ SettingsTile.switchTile(
+ leading: Icons.playlist_play_rounded,
+ onToggle: (value) async {
+ autoPlayNext = value ?? !autoPlayNext;
+ await GStorage.putSetting<bool>(
+ SettingsKeys.autoPlayNext, autoPlayNext);
+ setState(() {});
+ },
+ title: Text('自动连播'),
+ description: Text('当前视频播放完毕后自动播放下一集'),
+ initialValue: autoPlayNext,
+ ),
+ if (Platform.isAndroid)
SettingsTile.switchTile(
- leading: Icons.error_outline_rounded,
+ leading: Icons.picture_in_picture_alt_rounded,
onToggle: (value) async {
- showPlayerError = value ?? !showPlayerError;
+ androidAutoEnterPIP = value ?? !androidAutoEnterPIP;
await GStorage.putSetting<bool>(
- SettingsKeys.showPlayerError, showPlayerError);
+ SettingsKeys.androidAutoEnterPIP, androidAutoEnterPIP);
+ await PipUtils.setAndroidAutoEnterPIPEnabled(
+ androidAutoEnterPIP);
setState(() {});
},
- title: Text('错误提示'),
- description: Text('显示播放器内部错误提示'),
- initialValue: showPlayerError,
+ title: Text('自动进入画中画'),
+ description: Text('切到后台时,自动进入画中画'),
+ initialValue: androidAutoEnterPIP,
),
+ SettingsTile.switchTile(
+ leading: Icons.block_rounded,
+ onToggle: (value) async {
+ forceAdBlocker = value ?? !forceAdBlocker;
+ await GStorage.putSetting<bool>(
+ SettingsKeys.forceAdBlocker, forceAdBlocker);
+ setState(() {});
+ },
+ title: Text('广告过滤'),
+ description: Text('强制启用HLS广告过滤,忽略规则设置'),
+ initialValue: forceAdBlocker,
+ ),
+ SettingsTile.switchTile(
+ leading: Icons.animation_rounded,
+ onToggle: (value) async {
+ playerDisableAnimations = value ?? !playerDisableAnimations;
+ await GStorage.putSetting<bool>(
+ SettingsKeys.playerDisableAnimations,
+ playerDisableAnimations);
+ setState(() {});
+ },
+ title: Text('禁用动画'),
+ description: Text('禁用播放器内的过渡动画'),
+ initialValue: playerDisableAnimations,
+ ),
+ if (!isDesktop())
SettingsTile.switchTile(
- leading: Icons.bug_report_rounded,
+ leading: Icons.swipe_vertical_rounded,
onToggle: (value) async {
- playerDebugMode = value ?? !playerDebugMode;
+ brightnessVolumeGesture = value ?? !brightnessVolumeGesture;
await GStorage.putSetting<bool>(
- SettingsKeys.playerDebugMode, playerDebugMode);
+ SettingsKeys.brightnessVolumeGesture,
+ brightnessVolumeGesture);
setState(() {});
},
- title: Text('调试模式'),
- description: Text('记录播放器内部日志'),
- initialValue: playerDebugMode,
+ title: Text('滑动手势'),
+ description: Text('竖向滑动调节音量和亮度'),
+ initialValue: brightnessVolumeGesture,
),
- SettingsTile(
- leading: Icons.receipt_long_rounded,
- onPressed: (_) async {
- if (playerLogLevelMenuController.isOpen) {
- playerLogLevelMenuController.close();
- } else {
- playerLogLevelMenuController.open();
- }
+ SettingsTile.switchTile(
+ leading: Icons.visibility_off_rounded,
+ onToggle: (value) async {
+ privateMode = value ?? !privateMode;
+ await GStorage.putSetting<bool>(
+ SettingsKeys.privateMode, privateMode);
+ setState(() {});
+ },
+ title: Text('隐身模式'),
+ description: Text('不保留观看记录'),
+ initialValue: privateMode,
+ ),
+ ],
+ ),
+ SettingsSection(
+ title: Text('诊断'),
+ tiles: [
+ SettingsTile.switchTile(
+ leading: Icons.error_outline_rounded,
+ onToggle: (value) async {
+ showPlayerError = value ?? !showPlayerError;
+ await GStorage.putSetting<bool>(
+ SettingsKeys.showPlayerError, showPlayerError);
+ setState(() {});
+ },
+ title: Text('错误提示'),
+ description: Text('显示播放器内部错误提示'),
+ initialValue: showPlayerError,
+ ),
+ SettingsTile.switchTile(
+ leading: Icons.bug_report_rounded,
+ onToggle: (value) async {
+ playerDebugMode = value ?? !playerDebugMode;
+ await GStorage.putSetting<bool>(
+ SettingsKeys.playerDebugMode, playerDebugMode);
+ setState(() {});
+ },
+ title: Text('调试模式'),
+ description: Text('记录播放器内部日志'),
+ initialValue: playerDebugMode,
+ ),
+ SettingsTile(
+ leading: Icons.receipt_long_rounded,
+ onPressed: (_) async {
+ if (playerLogLevelMenuController.isOpen) {
+ playerLogLevelMenuController.close();
+ } else {
+ playerLogLevelMenuController.open();
+ }
+ },
+ title: Text('日志等级'),
+ description: Text('播放器内部日志等级'),
+ value: MenuAnchor(
+ consumeOutsideTap: true,
+ controller: playerLogLevelMenuController,
+ builder: (_, __, ___) {
+ return Text(
+ playerLogLevelMap[playerLogLevel] ?? '???',
+ );
},
- title: Text('日志等级'),
- description: Text('播放器内部日志等级'),
- value: MenuAnchor(
- consumeOutsideTap: true,
- controller: playerLogLevelMenuController,
- builder: (_, __, ___) {
- return Text(
- playerLogLevelMap[playerLogLevel] ?? '???',
- );
- },
- menuChildren: [
- for (final entry in playerLogLevelMap.entries)
- MenuItemButton(
- requestFocusOnHover: false,
- onPressed: () => updatePlayerLogLevel(entry.key),
- child: Container(
- height: 48,
- constraints: BoxConstraints(minWidth: 112),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Text(
- entry.value,
- style: TextStyle(
- color: entry.key == playerLogLevel
- ? Theme.of(context).colorScheme.primary
- : null,
- ),
+ menuChildren: [
+ for (final entry in playerLogLevelMap.entries)
+ MenuItemButton(
+ requestFocusOnHover: false,
+ onPressed: () => updatePlayerLogLevel(entry.key),
+ child: Container(
+ height: 48,
+ constraints: BoxConstraints(minWidth: 112),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Text(
+ entry.value,
+ style: TextStyle(
+ color: entry.key == playerLogLevel
+ ? Theme.of(context).colorScheme.primary
+ : null,
),
),
),
),
- ],
- ),
- ),
- ],
- ),
- SettingsSection(
- title: Text('播放参数'),
- tiles: [
- SettingsSliderTile(
- leading: Icons.speed_rounded,
- title: Text('默认倍速'),
- value: defaultPlaySpeed,
- min: 0.25,
- max: 3,
- divisions: 11,
- valueLabel: '${defaultPlaySpeed}x',
- onChanged: (value) => updateDefaultPlaySpeed(
- double.parse(value.toStringAsFixed(2))),
- ),
- SettingsSliderTile(
- leading: Icons.fast_forward_rounded,
- title: Text('长按倍速'),
- description: Text('长按屏幕或按住方向键时的倍速'),
- value: defaultShortcutForwardPlaySpeed,
- min: 1.25,
- max: 3,
- divisions: 7,
- valueLabel: '${defaultShortcutForwardPlaySpeed}x',
- onChanged: (value) => updateDefaultShortcutForwardPlaySpeed(
- double.parse(value.toStringAsFixed(2))),
- ),
- SettingsSliderTile(
- leading: Icons.swap_horiz_rounded,
- title: Text('方向键跳转'),
- description: Text('左右方向键的快进/快退秒数'),
- value: playerArrowKeySkipTime.toDouble(),
- min: 0,
- max: 15,
- divisions: 15,
- valueLabel: '$playerArrowKeySkipTime 秒',
- onChanged: (value) {
- final newArrowKeySkipTime = value.toInt();
- if (newArrowKeySkipTime == playerArrowKeySkipTime) {
- return;
- }
- GStorage.putSetting<int>(
- SettingsKeys.arrowKeySkipTime, newArrowKeySkipTime);
- setState(() {
- playerArrowKeySkipTime = newArrowKeySkipTime;
- });
- },
- ),
- SettingsTile(
- leading: Icons.skip_next_rounded,
- onPressed: (_) async {
- await updateButtonSkipTime();
- },
- title: Text('跳过时长'),
- description: Text('顶栏跳过按钮的秒数'),
- value: Text('$playerButtonSkipTime 秒'),
+ ),
+ ],
),
- SettingsSliderTile(
- leading: Icons.timer_rounded,
- title: Text('控制栏消失时间'),
- description: Text('播放控制器自动隐藏前的停留时长'),
- value: playerControllerLayerDisappearSeconds,
- min: _minPlayerControllerLayerDisappearSeconds,
- max: _maxPlayerControllerLayerDisappearSeconds,
- divisions: _playerControllerLayerDisappearDivisions,
- valueLabel: formatPlayerControllerLayerDisappearSeconds(
- playerControllerLayerDisappearSeconds),
- onChanged: updatePlayerControllerLayerDisappearSeconds,
- ),
- SettingsTile(
- leading: Icons.aspect_ratio_rounded,
- onPressed: (_) async {
- if (playerAspectRatioMenuController.isOpen) {
- playerAspectRatioMenuController.close();
- } else {
- playerAspectRatioMenuController.open();
- }
+ ),
+ ],
+ ),
+ SettingsSection(
+ title: Text('播放参数'),
+ tiles: [
+ SettingsSliderTile(
+ leading: Icons.speed_rounded,
+ title: Text('默认倍速'),
+ value: defaultPlaySpeed,
+ min: 0.25,
+ max: 3,
+ divisions: 11,
+ valueLabel: '${defaultPlaySpeed}x',
+ onChanged: (value) => updateDefaultPlaySpeed(
+ double.parse(value.toStringAsFixed(2))),
+ ),
+ SettingsSliderTile(
+ leading: Icons.fast_forward_rounded,
+ title: Text('长按倍速'),
+ description: Text('长按屏幕或按住方向键时的倍速'),
+ value: defaultShortcutForwardPlaySpeed,
+ min: 1.25,
+ max: 3,
+ divisions: 7,
+ valueLabel: '${defaultShortcutForwardPlaySpeed}x',
+ onChanged: (value) => updateDefaultShortcutForwardPlaySpeed(
+ double.parse(value.toStringAsFixed(2))),
+ ),
+ SettingsSliderTile(
+ leading: Icons.swap_horiz_rounded,
+ title: Text('方向键跳转'),
+ description: Text('左右方向键的快进/快退秒数'),
+ value: playerArrowKeySkipTime.toDouble(),
+ min: 0,
+ max: 15,
+ divisions: 15,
+ valueLabel: '$playerArrowKeySkipTime 秒',
+ onChanged: (value) {
+ final newArrowKeySkipTime = value.toInt();
+ if (newArrowKeySkipTime == playerArrowKeySkipTime) {
+ return;
+ }
+ GStorage.putSetting<int>(
+ SettingsKeys.arrowKeySkipTime, newArrowKeySkipTime);
+ setState(() {
+ playerArrowKeySkipTime = newArrowKeySkipTime;
+ });
+ },
+ ),
+ SettingsTile(
+ leading: Icons.skip_next_rounded,
+ onPressed: (_) async {
+ await updateButtonSkipTime();
+ },
+ title: Text('跳过时长'),
+ description: Text('顶栏跳过按钮的秒数'),
+ value: Text('$playerButtonSkipTime 秒'),
+ ),
+ SettingsSliderTile(
+ leading: Icons.timer_rounded,
+ title: Text('控制栏消失时间'),
+ description: Text('播放控制器自动隐藏前的停留时长'),
+ value: playerControllerLayerDisappearSeconds,
+ min: _minPlayerControllerLayerDisappearSeconds,
+ max: _maxPlayerControllerLayerDisappearSeconds,
+ divisions: _playerControllerLayerDisappearDivisions,
+ valueLabel: formatPlayerControllerLayerDisappearSeconds(
+ playerControllerLayerDisappearSeconds),
+ onChanged: updatePlayerControllerLayerDisappearSeconds,
+ ),
+ SettingsTile(
+ leading: Icons.aspect_ratio_rounded,
+ onPressed: (_) async {
+ if (playerAspectRatioMenuController.isOpen) {
+ playerAspectRatioMenuController.close();
+ } else {
+ playerAspectRatioMenuController.open();
+ }
+ },
+ title: Text('默认视频比例'),
+ value: MenuAnchor(
+ consumeOutsideTap: true,
+ controller: playerAspectRatioMenuController,
+ builder: (_, __, ___) {
+ return Text(
+ defaultAspectRatioMode.label,
+ );
},
- title: Text('默认视频比例'),
- value: MenuAnchor(
- consumeOutsideTap: true,
- controller: playerAspectRatioMenuController,
- builder: (_, __, ___) {
- return Text(
- defaultAspectRatioMode.label,
- );
- },
- menuChildren: [
- for (final aspectRatioMode in PlayerAspectRatio.values)
- MenuItemButton(
- requestFocusOnHover: false,
- onPressed: () =>
- updateDefaultAspectRatioMode(aspectRatioMode),
- child: Container(
- height: 48,
- constraints: BoxConstraints(minWidth: 112),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Text(
- aspectRatioMode.label,
- style: TextStyle(
- color: aspectRatioMode ==
- defaultAspectRatioMode
- ? Theme.of(context).colorScheme.primary
- : null,
- ),
+ menuChildren: [
+ for (final aspectRatioMode in PlayerAspectRatio.values)
+ MenuItemButton(
+ requestFocusOnHover: false,
+ onPressed: () =>
+ updateDefaultAspectRatioMode(aspectRatioMode),
+ child: Container(
+ height: 48,
+ constraints: BoxConstraints(minWidth: 112),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Text(
+ aspectRatioMode.label,
+ style: TextStyle(
+ color: aspectRatioMode == defaultAspectRatioMode
+ ? Theme.of(context).colorScheme.primary
+ : null,
),
),
),
),
- ],
- ),
+ ),
+ ],
),
- ],
- ),
- SettingsSection(
- tiles: [
- SettingsTile(
- leading: Icons.settings_backup_restore_rounded,
- onPressed: (_) => resetPlayerSettings(),
- title: Text('恢复默认设置'),
- description: Text('将播放相关设置恢复为默认值'),
- ),
- ],
- ),
- ],
- ),
+ ),
+ ],
+ ),
+ SettingsSection(
+ tiles: [
+ SettingsTile(
+ leading: Icons.settings_backup_restore_rounded,
+ onPressed: (_) => resetPlayerSettings(),
+ title: Text('恢复默认设置'),
+ description: Text('将播放相关设置恢复为默认值'),
+ ),
+ ],
+ ),
+ ],
),
);
}
diff --git a/lib/pages/settings/proxy/proxy_settings_page.dart b/lib/pages/settings/proxy/proxy_settings_page.dart
index ed1d4277..9bf4052c 100644
--- a/lib/pages/settings/proxy/proxy_settings_page.dart
+++ b/lib/pages/settings/proxy/proxy_settings_page.dart
@@ -22,13 +22,6 @@ class _ProxySettingsPageState extends State<ProxySettingsPage> {
proxyEnable = GStorage.getSetting(SettingsKeys.proxyEnable);
}
- void onBackPressed(BuildContext context) {
- if (KazumiDialog.observer.hasKazumiDialog) {
- KazumiDialog.dismiss();
- return;
- }
- }
-
Future<void> updateProxyEnable(bool value) async {
if (value) {
final proxyConfigured = GStorage.getSetting(SettingsKeys.proxyConfigured);
@@ -49,43 +42,36 @@ class _ProxySettingsPageState extends State<ProxySettingsPage> {
@override
Widget build(BuildContext context) {
- return PopScope(
- canPop: true,
- onPopInvokedWithResult: (bool didPop, Object? result) {
- onBackPressed(context);
- },
- child: SettingsDetailScaffold(
- title: const Text('代理设置'),
- body: SettingsList(
- sections: [
- SettingsSection(
- title: Text('代理'),
- tiles: [
- SettingsTile.switchTile(
- leading: Icons.vpn_key_rounded,
- onToggle: (value) async {
- await updateProxyEnable(value ?? !proxyEnable);
- },
- title: Text('启用代理'),
- description: Text('启用后网络请求将通过代理服务器'),
- initialValue: proxyEnable,
- ),
- SettingsTile(
- leading: Icons.tune_rounded,
- onPressed: (_) async {
- await context.pushNamed('/settings/proxy/editor');
- setState(() {
- proxyEnable =
- GStorage.getSetting(SettingsKeys.proxyEnable);
- });
- },
- title: Text('代理配置'),
- description: Text('配置代理服务器地址和认证信息'),
- ),
- ],
- ),
- ],
- ),
+ return SettingsDetailScaffold(
+ title: const Text('代理设置'),
+ body: SettingsList(
+ sections: [
+ SettingsSection(
+ title: Text('代理'),
+ tiles: [
+ SettingsTile.switchTile(
+ leading: Icons.vpn_key_rounded,
+ onToggle: (value) async {
+ await updateProxyEnable(value ?? !proxyEnable);
+ },
+ title: Text('启用代理'),
+ description: Text('启用后网络请求将通过代理服务器'),
+ initialValue: proxyEnable,
+ ),
+ SettingsTile(
+ leading: Icons.tune_rounded,
+ onPressed: (_) async {
+ await context.pushNamed('/settings/proxy/editor');
+ setState(() {
+ proxyEnable = GStorage.getSetting(SettingsKeys.proxyEnable);
+ });
+ },
+ title: Text('代理配置'),
+ description: Text('配置代理服务器地址和认证信息'),
+ ),
+ ],
+ ),
+ ],
),
);
}
diff --git a/lib/pages/settings/storage_settings.dart b/lib/pages/settings/storage_settings.dart
index cfaf4558..86b4ea1d 100644
--- a/lib/pages/settings/storage_settings.dart
+++ b/lib/pages/settings/storage_settings.dart
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart';
+import 'package:kazumi/bean/dialog/dialog_helper.dart';
import 'package:kazumi/bean/settings/settings_detail_scaffold.dart';
import 'package:kazumi/bean/settings/settings_list.dart';
import 'package:kazumi/services/storage/image_cache_service.dart';
@@ -20,14 +21,12 @@ class _StorageSettingsPageState extends State<StorageSettingsPage> {
void _refreshSize() => setState(() => _cacheSize = _cache.sizeInBytes());
void _message(String message) {
- ScaffoldMessenger.of(context)
- ..hideCurrentSnackBar()
- ..showSnackBar(SnackBar(content: Text(message)));
+ KazumiDialog.showToast(context: context, message: message);
}
Future<void> _confirmClear() async {
if (_clearing) return;
- final confirmed = await showDialog<bool>(
+ final confirmed = await KazumiDialog.show<bool>(
context: context,
builder: (context) => AlertDialog(
icon: const Icon(Icons.cleaning_services_rounded),
diff --git a/lib/pages/settings/theme_settings_page.dart b/lib/pages/settings/theme_settings_page.dart
index cce0b444..bf59e637 100644
--- a/lib/pages/settings/theme_settings_page.dart
+++ b/lib/pages/settings/theme_settings_page.dart
@@ -21,7 +21,6 @@ class ThemeSettingsPage extends StatefulWidget {
}
class _ThemeSettingsPageState extends State<ThemeSettingsPage> {
- late dynamic defaultDanmakuArea;
late dynamic defaultThemeMode;
late dynamic defaultThemeColor;
late bool oledEnhance;
@@ -43,13 +42,6 @@ class _ThemeSettingsPageState extends State<ThemeSettingsPage> {
themeProvider = context.read<ThemeProvider>();
}
- void onBackPressed(BuildContext context) {
- if (KazumiDialog.observer.hasKazumiDialog) {
- KazumiDialog.dismiss();
- return;
- }
- }
-
void setTheme(Color? color) {
var defaultDarkTheme = ThemeData(
useMaterial3: true,
@@ -135,271 +127,263 @@ class _ThemeSettingsPageState extends State<ThemeSettingsPage> {
@override
Widget build(BuildContext context) {
- return PopScope(
- canPop: true,
- onPopInvokedWithResult: (bool didPop, Object? result) {
- onBackPressed(context);
- },
- child: SettingsDetailScaffold(
- title: const Text('外观设置'),
- body: SettingsList(
- sections: [
- SettingsSection(
- title: Text('外观'),
- tiles: [
- SettingsTile(
- leading: Icons.dark_mode_rounded,
- onPressed: (_) {
- if (menuController.isOpen) {
- menuController.close();
- } else {
- menuController.open();
- }
+ return SettingsDetailScaffold(
+ title: const Text('外观设置'),
+ body: SettingsList(
+ sections: [
+ SettingsSection(
+ title: Text('外观'),
+ tiles: [
+ SettingsTile(
+ leading: Icons.dark_mode_rounded,
+ onPressed: (_) {
+ if (menuController.isOpen) {
+ menuController.close();
+ } else {
+ menuController.open();
+ }
+ },
+ title: Text('深色模式'),
+ value: MenuAnchor(
+ consumeOutsideTap: true,
+ controller: menuController,
+ builder: (_, __, ___) {
+ return Text(
+ defaultThemeMode == 'light'
+ ? '浅色'
+ : (defaultThemeMode == 'dark' ? '深色' : '跟随系统'),
+ );
},
- title: Text('深色模式'),
- value: MenuAnchor(
- consumeOutsideTap: true,
- controller: menuController,
- builder: (_, __, ___) {
- return Text(
- defaultThemeMode == 'light'
- ? '浅色'
- : (defaultThemeMode == 'dark' ? '深色' : '跟随系统'),
- );
- },
- menuChildren: [
- MenuItemButton(
- requestFocusOnHover: false,
- onPressed: () => updateTheme('system'),
- child: Container(
- height: 48,
- constraints: BoxConstraints(minWidth: 112),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Row(
- children: [
- Icon(
- Icons.brightness_auto_rounded,
+ menuChildren: [
+ MenuItemButton(
+ requestFocusOnHover: false,
+ onPressed: () => updateTheme('system'),
+ child: Container(
+ height: 48,
+ constraints: BoxConstraints(minWidth: 112),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Row(
+ children: [
+ Icon(
+ Icons.brightness_auto_rounded,
+ color: defaultThemeMode == 'system'
+ ? Theme.of(context).colorScheme.primary
+ : null,
+ ),
+ SizedBox(width: 8),
+ Text(
+ '跟随系统',
+ style: TextStyle(
color: defaultThemeMode == 'system'
? Theme.of(context).colorScheme.primary
: null,
),
- SizedBox(width: 8),
- Text(
- '跟随系统',
- style: TextStyle(
- color: defaultThemeMode == 'system'
- ? Theme.of(context).colorScheme.primary
- : null,
- ),
- ),
- ],
- ),
+ ),
+ ],
),
),
),
- MenuItemButton(
- requestFocusOnHover: false,
- onPressed: () => updateTheme('light'),
- child: Container(
- height: 48,
- constraints: BoxConstraints(minWidth: 112),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Row(
- children: [
- Icon(
- Icons.light_mode_rounded,
- color: defaultThemeMode == 'light'
- ? Theme.of(context).colorScheme.primary
- : null,
- ),
- SizedBox(width: 8),
- Text(
- '浅色',
- style: TextStyle(
- color: defaultThemeMode == 'light'
- ? Theme.of(context)
- .colorScheme
- .primary
- : null),
- ),
- ],
- ),
+ ),
+ MenuItemButton(
+ requestFocusOnHover: false,
+ onPressed: () => updateTheme('light'),
+ child: Container(
+ height: 48,
+ constraints: BoxConstraints(minWidth: 112),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Row(
+ children: [
+ Icon(
+ Icons.light_mode_rounded,
+ color: defaultThemeMode == 'light'
+ ? Theme.of(context).colorScheme.primary
+ : null,
+ ),
+ SizedBox(width: 8),
+ Text(
+ '浅色',
+ style: TextStyle(
+ color: defaultThemeMode == 'light'
+ ? Theme.of(context).colorScheme.primary
+ : null),
+ ),
+ ],
),
),
),
- MenuItemButton(
- requestFocusOnHover: false,
- onPressed: () => updateTheme('dark'),
- child: Container(
- height: 48,
- constraints: BoxConstraints(minWidth: 112),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Row(
- children: [
- Icon(
- Icons.dark_mode_rounded,
+ ),
+ MenuItemButton(
+ requestFocusOnHover: false,
+ onPressed: () => updateTheme('dark'),
+ child: Container(
+ height: 48,
+ constraints: BoxConstraints(minWidth: 112),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Row(
+ children: [
+ Icon(
+ Icons.dark_mode_rounded,
+ color: defaultThemeMode == 'dark'
+ ? Theme.of(context).colorScheme.primary
+ : null,
+ ),
+ SizedBox(width: 8),
+ Text(
+ '深色',
+ style: TextStyle(
color: defaultThemeMode == 'dark'
? Theme.of(context).colorScheme.primary
: null,
),
- SizedBox(width: 8),
- Text(
- '深色',
- style: TextStyle(
- color: defaultThemeMode == 'dark'
- ? Theme.of(context).colorScheme.primary
- : null,
- ),
- ),
- ],
- ),
+ ),
+ ],
),
),
),
- ],
- ),
- ),
- SettingsTile(
- leading: Icons.palette_rounded,
- enabled: !useDynamicColor,
- onPressed: (_) async {
- KazumiDialog.show(builder: (context) {
- return AlertDialog(
- title: Text('配色方案'),
- content: StatefulBuilder(builder:
- (BuildContext context, StateSetter setState) {
- final List<Map<String, dynamic>> colorThemes =
- colorThemeTypes;
- return Wrap(
- alignment: WrapAlignment.center,
- spacing: 8,
- runSpacing: isDesktop() ? 8 : 0,
- children: [
- ...colorThemes.map(
- (e) {
- final index = colorThemes.indexOf(e);
- return GestureDetector(
- onTap: () {
- index == 0
- ? resetTheme()
- : setTheme(e['color']);
- KazumiDialog.dismiss();
- },
- child: Column(
- children: [
- PaletteCard(
- color: e['color'],
- selected: (e['color']
- .value
- .toRadixString(16) ==
- defaultThemeColor ||
- (defaultThemeColor == 'default' &&
- index == 0)),
- ),
- Text(e['label']),
- ],
- ),
- );
- },
- )
- ],
- );
- }),
- );
- });
- },
- title: Text('配色方案'),
- ),
- SettingsTile.switchTile(
- leading: Icons.colorize_rounded,
- enabled: !Platform.isIOS,
- onToggle: (value) async {
- useDynamicColor = value ?? !useDynamicColor;
- await GStorage.putSetting(
- SettingsKeys.useDynamicColor, useDynamicColor);
- themeProvider.setDynamic(useDynamicColor);
- setState(() {});
- },
- title: Text('动态配色'),
- initialValue: useDynamicColor,
+ ),
+ ],
),
+ ),
+ SettingsTile(
+ leading: Icons.palette_rounded,
+ enabled: !useDynamicColor,
+ onPressed: (_) async {
+ KazumiDialog.show(builder: (context) {
+ return AlertDialog(
+ title: Text('配色方案'),
+ content: StatefulBuilder(builder:
+ (BuildContext context, StateSetter setState) {
+ final List<Map<String, dynamic>> colorThemes =
+ colorThemeTypes;
+ return Wrap(
+ alignment: WrapAlignment.center,
+ spacing: 8,
+ runSpacing: isDesktop() ? 8 : 0,
+ children: [
+ ...colorThemes.map(
+ (e) {
+ final index = colorThemes.indexOf(e);
+ return GestureDetector(
+ onTap: () {
+ index == 0
+ ? resetTheme()
+ : setTheme(e['color']);
+ KazumiDialog.dismiss();
+ },
+ child: Column(
+ children: [
+ PaletteCard(
+ color: e['color'],
+ selected: (e['color']
+ .value
+ .toRadixString(16) ==
+ defaultThemeColor ||
+ (defaultThemeColor == 'default' &&
+ index == 0)),
+ ),
+ Text(e['label']),
+ ],
+ ),
+ );
+ },
+ )
+ ],
+ );
+ }),
+ );
+ });
+ },
+ title: Text('配色方案'),
+ ),
+ SettingsTile.switchTile(
+ leading: Icons.colorize_rounded,
+ enabled: !Platform.isIOS,
+ onToggle: (value) async {
+ useDynamicColor = value ?? !useDynamicColor;
+ await GStorage.putSetting(
+ SettingsKeys.useDynamicColor, useDynamicColor);
+ themeProvider.setDynamic(useDynamicColor);
+ setState(() {});
+ },
+ title: Text('动态配色'),
+ initialValue: useDynamicColor,
+ ),
+ SettingsTile.switchTile(
+ leading: Icons.font_download_rounded,
+ onToggle: (value) async {
+ useSystemFont = value ?? !useSystemFont;
+ await GStorage.putSetting(
+ SettingsKeys.useSystemFont, useSystemFont);
+ themeProvider.setFontFamily(useSystemFont);
+ dynamic color;
+ if (defaultThemeColor == 'default') {
+ color = Colors.green;
+ } else {
+ color = Color(int.parse(defaultThemeColor, radix: 16));
+ }
+ setTheme(color);
+ setState(() {});
+ },
+ title: Text('使用系统字体'),
+ description: Text('关闭后使用 MI Sans 字体'),
+ initialValue: useSystemFont,
+ ),
+ ],
+ bottomInfo: Text('动态配色仅支持安卓12及以上和桌面平台'),
+ ),
+ SettingsSection(
+ title: Text('显示'),
+ tiles: [
+ SettingsTile.switchTile(
+ leading: Icons.contrast_rounded,
+ onToggle: (value) async {
+ oledEnhance = value ?? !oledEnhance;
+ await GStorage.putSetting(
+ SettingsKeys.oledEnhance, oledEnhance);
+ updateOledEnhance();
+ setState(() {});
+ },
+ title: Text('OLED优化'),
+ description: Text('深色模式下使用纯黑背景'),
+ initialValue: oledEnhance,
+ ),
+ ],
+ ),
+ if (isDesktop())
+ SettingsSection(
+ title: Text('窗口'),
+ tiles: [
SettingsTile.switchTile(
- leading: Icons.font_download_rounded,
+ leading: Icons.web_asset_rounded,
onToggle: (value) async {
- useSystemFont = value ?? !useSystemFont;
+ showWindowButton = value ?? !showWindowButton;
await GStorage.putSetting(
- SettingsKeys.useSystemFont, useSystemFont);
- themeProvider.setFontFamily(useSystemFont);
- dynamic color;
- if (defaultThemeColor == 'default') {
- color = Colors.green;
- } else {
- color = Color(int.parse(defaultThemeColor, radix: 16));
- }
- setTheme(color);
+ SettingsKeys.showWindowButton, showWindowButton);
setState(() {});
},
- title: Text('使用系统字体'),
- description: Text('关闭后使用 MI Sans 字体'),
- initialValue: useSystemFont,
+ title: Text('使用系统标题栏'),
+ description: Text('重启应用生效'),
+ initialValue: showWindowButton,
),
],
- bottomInfo: Text('动态配色仅支持安卓12及以上和桌面平台'),
),
+ if (Platform.isAndroid)
SettingsSection(
- title: Text('显示'),
+ title: Text('屏幕'),
tiles: [
- SettingsTile.switchTile(
- leading: Icons.contrast_rounded,
- onToggle: (value) async {
- oledEnhance = value ?? !oledEnhance;
- await GStorage.putSetting(
- SettingsKeys.oledEnhance, oledEnhance);
- updateOledEnhance();
- setState(() {});
+ SettingsTile(
+ leading: Icons.sixty_fps_rounded,
+ onPressed: (_) async {
+ context.pushNamed('/settings/theme/display');
},
- title: Text('OLED优化'),
- description: Text('深色模式下使用纯黑背景'),
- initialValue: oledEnhance,
+ title: Text('屏幕帧率'),
),
],
),
- if (isDesktop())
- SettingsSection(
- title: Text('窗口'),
- tiles: [
- SettingsTile.switchTile(
- leading: Icons.web_asset_rounded,
- onToggle: (value) async {
- showWindowButton = value ?? !showWindowButton;
- await GStorage.putSetting(
- SettingsKeys.showWindowButton, showWindowButton);
- setState(() {});
- },
- title: Text('使用系统标题栏'),
- description: Text('重启应用生效'),
- initialValue: showWindowButton,
- ),
- ],
- ),
- if (Platform.isAndroid)
- SettingsSection(
- title: Text('屏幕'),
- tiles: [
- SettingsTile(
- leading: Icons.sixty_fps_rounded,
- onPressed: (_) async {
- context.pushNamed('/settings/theme/display');
- },
- title: Text('屏幕帧率'),
- ),
- ],
- ),
- ],
- ),
+ ],
),
);
}
diff --git a/lib/pages/webdav_editor/webdav_setting.dart b/lib/pages/webdav_editor/webdav_setting.dart
index 05a0f951..bf728f3d 100644
--- a/lib/pages/webdav_editor/webdav_setting.dart
+++ b/lib/pages/webdav_editor/webdav_setting.dart
@@ -35,13 +35,6 @@ class _PlayerSettingsPageState extends State<WebDavSettingsPage> {
bangumiSyncEnable = GStorage.getSetting(SettingsKeys.bangumiSyncEnable);
}
- void onBackPressed(BuildContext context) {
- if (KazumiDialog.observer.hasKazumiDialog) {
- KazumiDialog.dismiss();
- return;
- }
- }
-
Future<void> syncHistoryWithWebDav() async {
var webDavEnable = GStorage.getSetting(SettingsKeys.webDavEnable);
if (webDavEnable) {
@@ -71,164 +64,157 @@ class _PlayerSettingsPageState extends State<WebDavSettingsPage> {
@override
Widget build(BuildContext context) {
- return PopScope(
- canPop: true,
- onPopInvokedWithResult: (bool didPop, Object? result) {
- onBackPressed(context);
- },
- child: SettingsDetailScaffold(
- title: const Text('同步设置'),
- body: SettingsList(
- sections: [
- NetworkMirrorSettings(
- enableBangumiProxy: enableBangumiProxy,
- enableGitProxy: enableGitProxy,
- onBangumiChanged: (value) async {
- setState(() => enableBangumiProxy = value);
- await GStorage.putSetting(
- SettingsKeys.enableBangumiProxy, value);
- },
- onGitChanged: (value) async {
- setState(() => enableGitProxy = value);
- await GStorage.putSetting(SettingsKeys.enableGitProxy, value);
- },
- ),
- SettingsSection(
- title: Text('Bangumi'),
- tiles: [
- SettingsTile.switchTile(
- leading: Icons.sync_rounded,
- onToggle: (value) async {
- final tBangumiEnableSync = value ?? !bangumiSyncEnable;
- final bangumi = BangumiSyncService();
- if (tBangumiEnableSync == true) {
- final token =
- GStorage.getSetting(SettingsKeys.bangumiAccessToken)
- .trim();
- if (token.isEmpty) {
- KazumiDialog.showToast(
- message: '请先配置 Bangumi 的 Access Token');
- return;
- } else {
- if (!bangumi.initialized) {
- try {
- await bangumi.init();
- } catch (e) {
- KazumiDialog.showToast(
- message: "Bangumi 初始化失败,请稍后再试");
- return;
- }
- }
- }
- }
- bangumiSyncEnable = tBangumiEnableSync;
- await GStorage.putSetting(
- SettingsKeys.bangumiSyncEnable, bangumiSyncEnable);
- if (!mounted) {
+ return SettingsDetailScaffold(
+ title: const Text('同步设置'),
+ body: SettingsList(
+ sections: [
+ NetworkMirrorSettings(
+ enableBangumiProxy: enableBangumiProxy,
+ enableGitProxy: enableGitProxy,
+ onBangumiChanged: (value) async {
+ setState(() => enableBangumiProxy = value);
+ await GStorage.putSetting(SettingsKeys.enableBangumiProxy, value);
+ },
+ onGitChanged: (value) async {
+ setState(() => enableGitProxy = value);
+ await GStorage.putSetting(SettingsKeys.enableGitProxy, value);
+ },
+ ),
+ SettingsSection(
+ title: Text('Bangumi'),
+ tiles: [
+ SettingsTile.switchTile(
+ leading: Icons.sync_rounded,
+ onToggle: (value) async {
+ final tBangumiEnableSync = value ?? !bangumiSyncEnable;
+ final bangumi = BangumiSyncService();
+ if (tBangumiEnableSync == true) {
+ final token =
+ GStorage.getSetting(SettingsKeys.bangumiAccessToken)
+ .trim();
+ if (token.isEmpty) {
+ KazumiDialog.showToast(
+ message: '请先配置 Bangumi 的 Access Token');
return;
- }
- setState(() {});
- },
- title: Text('Bangumi 同步'),
- description: Text('与Bangumi自动同步追番状态'),
- initialValue: bangumiSyncEnable,
- ),
- SettingsTile(
- leading: Icons.tune_rounded,
- onPressed: (_) async {
- await context.pushNamed('/settings/bangumi/');
- bangumiSyncEnable =
- GStorage.getSetting(SettingsKeys.bangumiSyncEnable);
- setState(() {});
- },
- title: Text('Bangumi 配置'),
- ),
- ],
- ),
- SettingsSection(
- title: Text('WEBDAV'),
- tiles: [
- SettingsTile.switchTile(
- leading: Icons.cloud_sync_rounded,
- onToggle: (value) async {
- webDavEnable = value ?? !webDavEnable;
- if (!WebDav().initialized && webDavEnable) {
- try {
- await WebDav().init();
- } catch (e) {
- webDavEnable = false;
- KazumiDialog.showToast(message: 'WEBDAV初始化失败 $e');
+ } else {
+ if (!bangumi.initialized) {
+ try {
+ await bangumi.init();
+ } catch (e) {
+ KazumiDialog.showToast(
+ message: "Bangumi 初始化失败,请稍后再试");
+ return;
+ }
}
}
- if (!webDavEnable) {
- webDavEnableHistory = false;
- webDavEnableCollect = false;
- await GStorage.putSetting(
- SettingsKeys.webDavEnableHistory, false);
- await GStorage.putSetting(
- SettingsKeys.webDavEnableCollect, false);
+ }
+ bangumiSyncEnable = tBangumiEnableSync;
+ await GStorage.putSetting(
+ SettingsKeys.bangumiSyncEnable, bangumiSyncEnable);
+ if (!mounted) {
+ return;
+ }
+ setState(() {});
+ },
+ title: Text('Bangumi 同步'),
+ description: Text('与Bangumi自动同步追番状态'),
+ initialValue: bangumiSyncEnable,
+ ),
+ SettingsTile(
+ leading: Icons.tune_rounded,
+ onPressed: (_) async {
+ await context.pushNamed('/settings/bangumi/');
+ bangumiSyncEnable =
+ GStorage.getSetting(SettingsKeys.bangumiSyncEnable);
+ setState(() {});
+ },
+ title: Text('Bangumi 配置'),
+ ),
+ ],
+ ),
+ SettingsSection(
+ title: Text('WEBDAV'),
+ tiles: [
+ SettingsTile.switchTile(
+ leading: Icons.cloud_sync_rounded,
+ onToggle: (value) async {
+ webDavEnable = value ?? !webDavEnable;
+ if (!WebDav().initialized && webDavEnable) {
+ try {
+ await WebDav().init();
+ } catch (e) {
+ webDavEnable = false;
+ KazumiDialog.showToast(message: 'WEBDAV初始化失败 $e');
}
+ }
+ if (!webDavEnable) {
+ webDavEnableHistory = false;
+ webDavEnableCollect = false;
await GStorage.putSetting(
- SettingsKeys.webDavEnable, webDavEnable);
- if (mounted) {
- setState(() {});
- }
- },
- title: Text('WEBDAV同步'),
- initialValue: webDavEnable,
- ),
- SettingsTile.switchTile(
- leading: Icons.history_rounded,
- onToggle: (value) async {
- if (!webDavEnable) {
- KazumiDialog.showToast(message: '请先开启WEBDAV同步');
- return;
- }
- webDavEnableHistory = value ?? !webDavEnableHistory;
- await GStorage.putSetting(
- SettingsKeys.webDavEnableHistory, webDavEnableHistory);
- setState(() {});
- },
- title: Text('观看记录同步'),
- description: Text('允许自动同步观看记录'),
- initialValue: webDavEnableHistory,
- ),
- SettingsTile.switchTile(
- leading: Icons.favorite_rounded,
- onToggle: (value) async {
- if (!webDavEnable) {
- KazumiDialog.showToast(message: '请先开启WEBDAV同步');
- return;
- }
- webDavEnableCollect = value ?? !webDavEnableCollect;
+ SettingsKeys.webDavEnableHistory, false);
await GStorage.putSetting(
- SettingsKeys.webDavEnableCollect, webDavEnableCollect);
+ SettingsKeys.webDavEnableCollect, false);
+ }
+ await GStorage.putSetting(
+ SettingsKeys.webDavEnable, webDavEnable);
+ if (mounted) {
setState(() {});
- },
- title: Text('收藏同步'),
- description: Text('允许 WebDAV 参与追番状态同步'),
- initialValue: webDavEnableCollect,
- ),
- SettingsTile(
- leading: Icons.tune_rounded,
- onPressed: (_) async {
- context.pushNamed('/settings/webdav/editor');
- },
- title: Text('WEBDAV配置'),
- ),
- SettingsTile(
- leading: Icons.cloud_upload_rounded,
- trailing: const Icon(Icons.sync_rounded),
- onPressed: (_) {
- syncHistoryWithWebDav();
- },
- title: Text('立即同步观看记录'),
- description: Text('与WEBDAV双向合并观看记录'),
- ),
- ],
- ),
- ],
- ),
+ }
+ },
+ title: Text('WEBDAV同步'),
+ initialValue: webDavEnable,
+ ),
+ SettingsTile.switchTile(
+ leading: Icons.history_rounded,
+ onToggle: (value) async {
+ if (!webDavEnable) {
+ KazumiDialog.showToast(message: '请先开启WEBDAV同步');
+ return;
+ }
+ webDavEnableHistory = value ?? !webDavEnableHistory;
+ await GStorage.putSetting(
+ SettingsKeys.webDavEnableHistory, webDavEnableHistory);
+ setState(() {});
+ },
+ title: Text('观看记录同步'),
+ description: Text('允许自动同步观看记录'),
+ initialValue: webDavEnableHistory,
+ ),
+ SettingsTile.switchTile(
+ leading: Icons.favorite_rounded,
+ onToggle: (value) async {
+ if (!webDavEnable) {
+ KazumiDialog.showToast(message: '请先开启WEBDAV同步');
+ return;
+ }
+ webDavEnableCollect = value ?? !webDavEnableCollect;
+ await GStorage.putSetting(
+ SettingsKeys.webDavEnableCollect, webDavEnableCollect);
+ setState(() {});
+ },
+ title: Text('收藏同步'),
+ description: Text('允许 WebDAV 参与追番状态同步'),
+ initialValue: webDavEnableCollect,
+ ),
+ SettingsTile(
+ leading: Icons.tune_rounded,
+ onPressed: (_) async {
+ context.pushNamed('/settings/webdav/editor');
+ },
+ title: Text('WEBDAV配置'),
+ ),
+ SettingsTile(
+ leading: Icons.cloud_upload_rounded,
+ trailing: const Icon(Icons.sync_rounded),
+ onPressed: (_) {
+ syncHistoryWithWebDav();
+ },
+ title: Text('立即同步观看记录'),
+ description: Text('与WEBDAV双向合并观看记录'),
+ ),
+ ],
+ ),
+ ],
),
);
}
diff --git a/lib/services/player/external_playback_launcher.dart b/lib/services/player/external_playback_launcher.dart
index 5e0960cc..e1feea8f 100644
--- a/lib/services/player/external_playback_launcher.dart
+++ b/lib/services/player/external_playback_launcher.dart
@@ -18,7 +18,6 @@ class ExternalPlaybackLauncher {
if ((Platform.isAndroid || Platform.isWindows) && currentReferer.isEmpty) {
if (await ExternalPlayer.launchUrlWithMime(
currentVideoUrl, 'video/mp4')) {
- KazumiDialog.dismiss();
KazumiDialog.showToast(
message: '尝试唤起外部播放器',
);
@@ -30,7 +29,6 @@ class ExternalPlaybackLauncher {
} else if (Platform.isMacOS || Platform.isIOS) {
if (await ExternalPlayer.launchUrlWithReferer(
currentVideoUrl, currentReferer)) {
- KazumiDialog.dismiss();
KazumiDialog.showToast(
message: '尝试唤起外部播放器',
);
@@ -40,7 +38,6 @@ class ExternalPlaybackLauncher {
);
}
} else if (Platform.isLinux && currentReferer.isEmpty) {
- KazumiDialog.dismiss();
final result =
await ExternalPlayer.launchLinuxDesktopPlayer(currentVideoUrl);
switch (result) {
diff --git a/lib/services/player/timed_shutdown_service.dart b/lib/services/player/timed_shutdown_service.dart
index d3f2d5c9..01f9fde8 100644
--- a/lib/services/player/timed_shutdown_service.dart
+++ b/lib/services/player/timed_shutdown_service.dart
@@ -12,31 +12,16 @@ class TimedShutdownService {
Timer? _shutdownTimer;
int _remainingSeconds = 0;
- bool _isDialogShowing = false;
-
- /// Last set minutes, used for repeat functionality
+ KazumiDialogHandle<void>? _expiryDialog;
int _lastSetMinutes = 0;
-
- /// Callback to invoke when timer expires (e.g., pause video)
VoidCallback? _onExpiredCallback;
- /// Remaining time in seconds notifier
final ValueNotifier<int> remainingSecondsNotifier = ValueNotifier<int>(0);
-
- /// Currently set minutes notifier (for UI display)
final ValueNotifier<int> setMinutesNotifier = ValueNotifier<int>(0);
- /// Whether a shutdown timer is currently active
bool get isActive => _shutdownTimer != null && _shutdownTimer!.isActive;
-
- /// Currently set minutes (0 = disabled)
int get setMinutes => setMinutesNotifier.value;
- /// Remaining time in seconds
- int get remainingSeconds => remainingSecondsNotifier.value;
-
- /// Start the shutdown timer with the given duration in minutes
- /// [onExpired] callback is invoked when timer expires (before showing dialog)
void start(int minutes, {VoidCallback? onExpired}) {
cancel();
if (minutes <= 0) return;
@@ -46,8 +31,6 @@ class TimedShutdownService {
remainingSecondsNotifier.value = _remainingSeconds;
setMinutesNotifier.value = minutes;
_onExpiredCallback = onExpired;
-
- // Update remaining time every second (runs globally, not tied to playback)
_shutdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
if (_remainingSeconds > 0) {
_remainingSeconds--;
@@ -62,14 +45,6 @@ class TimedShutdownService {
});
}
- /// Repeat the timer with the last set duration
- void repeat() {
- if (_lastSetMinutes > 0) {
- start(_lastSetMinutes, onExpired: _onExpiredCallback);
- }
- }
-
- /// Cancel the current shutdown timer
void cancel() {
_shutdownTimer?.cancel();
_shutdownTimer = null;
@@ -81,20 +56,12 @@ class TimedShutdownService {
if (setMinutesNotifier.value != 0) {
setMinutesNotifier.value = 0;
}
-
- // If dialog is showing, dismiss it
- if (_isDialogShowing) {
- KazumiDialog.dismiss();
- _isDialogShowing = false;
- }
+ _expiryDialog?.dismiss();
+ _expiryDialog = null;
}
- /// Called when timer expires: invoke callback and show dialog
void _onTimerExpired() {
- // Reset UI state so it doesn't show 00:00
setMinutesNotifier.value = 0;
-
- // Invoke the callback if set (e.g., pause video)
try {
_onExpiredCallback?.call();
} catch (e) {
@@ -105,15 +72,15 @@ class TimedShutdownService {
_showTimerExpiredDialog();
}
- /// Show the timer expired dialog with repeat/close options
void _showTimerExpiredDialog() {
- if (_isDialogShowing) return;
- _isDialogShowing = true;
+ if (_expiryDialog?.isActive ?? false) return;
+ final dialog = _expiryDialog = KazumiDialogHandle<void>();
- KazumiDialog.show(
+ KazumiDialog.show<void>(
+ handle: dialog,
clickMaskDismiss: false,
onDismiss: () {
- _isDialogShowing = false;
+ if (identical(_expiryDialog, dialog)) _expiryDialog = null;
},
builder: (context) {
return AlertDialog(
@@ -122,17 +89,14 @@ class TimedShutdownService {
actions: [
TextButton(
onPressed: () {
- _isDialogShowing = false;
- KazumiDialog.dismiss();
- repeat();
+ start(_lastSetMinutes, onExpired: _onExpiredCallback);
KazumiDialog.showToast(message: '已重新开始 $_lastSetMinutes 分钟定时');
},
child: const Text('重复'),
),
TextButton(
onPressed: () {
- _isDialogShowing = false;
- KazumiDialog.dismiss();
+ dialog.dismiss();
},
child: Text(
'关闭',
@@ -145,7 +109,6 @@ class TimedShutdownService {
);
}
- /// Format remaining seconds to a readable string (e.g., "15:30")
String formatRemainingTime() {
int totalSeconds = remainingSecondsNotifier.value;
if (totalSeconds <= 0) return '00:00';
@@ -154,7 +117,6 @@ class TimedShutdownService {
return '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
}
- /// Format minutes to readable display string (e.g., "1 小时 30 分钟")
String formatMinutesToDisplay(int totalMinutes) {
final hours = totalMinutes ~/ 60;
final minutes = totalMinutes % 60;
@@ -167,21 +129,12 @@ class TimedShutdownService {
}
}
- /// Show custom timer picker dialog and start timer if user confirms
- /// Uses KazumiDialog to avoid context-related resource leaks
- /// [onExpired] callback is invoked when timer expires (before showing dialog)
static void showCustomTimerDialog({
- String title = '自定义定时',
- bool autoStart = true,
VoidCallback? onExpired,
- void Function(int)? onResult,
}) {
KazumiDialog.show(
builder: (context) => _CustomTimerDialog(
- title: title,
- autoStart: autoStart,
onExpired: onExpired,
- onResult: onResult,
),
);
}
@@ -189,16 +142,10 @@ class TimedShutdownService {
class _CustomTimerDialog extends StatefulWidget {
const _CustomTimerDialog({
- required this.title,
- required this.autoStart,
required this.onExpired,
- required this.onResult,
});
- final String title;
- final bool autoStart;
final VoidCallback? onExpired;
- final void Function(int)? onResult;
@override
State<_CustomTimerDialog> createState() => _CustomTimerDialogState();
@@ -231,21 +178,18 @@ class _CustomTimerDialogState extends State<_CustomTimerDialog> {
KazumiDialog.showToast(message: '请选择有效的时间');
return;
}
- KazumiDialog.dismiss();
- if (widget.autoStart) {
- TimedShutdownService().start(totalMinutes, onExpired: widget.onExpired);
- KazumiDialog.showToast(
- message:
- '已设置 ${TimedShutdownService().formatMinutesToDisplay(totalMinutes)} 后定时关闭',
- );
- }
- widget.onResult?.call(totalMinutes);
+ KazumiDialog.dismiss(context: context);
+ TimedShutdownService().start(totalMinutes, onExpired: widget.onExpired);
+ KazumiDialog.showToast(
+ message:
+ '已设置 ${TimedShutdownService().formatMinutesToDisplay(totalMinutes)} 后定时关闭',
+ );
}
@override
Widget build(BuildContext context) {
return AlertDialog(
- title: Text(widget.title),
+ title: const Text('自定义定时'),
content: SizedBox(
height: 200,
child: Row(
@@ -311,7 +255,7 @@ class _CustomTimerDialogState extends State<_CustomTimerDialog> {
),
actions: [
TextButton(
- onPressed: () => KazumiDialog.dismiss(),
+ onPressed: () => KazumiDialog.dismiss(context: context),
child: Text(
'取消',
style: TextStyle(color: Theme.of(context).colorScheme.outline),
diff --git a/lib/services/update/auto_updater.dart b/lib/services/update/auto_updater.dart
index aee9b719..7c4b2749 100644
--- a/lib/services/update/auto_updater.dart
+++ b/lib/services/update/auto_updater.dart
@@ -15,19 +15,17 @@ import 'package:kazumi/utils/date_time.dart';
import 'package:kazumi/utils/crypto.dart';
import 'package:kazumi/utils/version.dart';
-/// 安装类型枚举
enum InstallationType {
- windowsMsix, // Kazumi_windows_1.7.5.msix
- windowsPortable, // Kazumi_windows_1.7.5.zip
- linuxDeb, // Kazumi_linux_1.7.5_amd64.deb
- linuxTar, // Kazumi_linux_1.7.5_amd64.tar.gz
- macosDmg, // Kazumi_macos_1.7.5.dmg
- androidApk, // Kazumi_android_1.7.5.apk
- ios, // iOS App
+ windowsMsix,
+ windowsPortable,
+ linuxDeb,
+ linuxTar,
+ macosDmg,
+ androidApk,
+ ios,
unknown,
}
-/// 更新信息类
class UpdateInfo {
final String version;
final String description;
@@ -48,8 +46,6 @@ class UpdateInfo {
this.availableInstallationTypes = const [],
this.assets = const [],
});
-
- /// 获取默认的安装类型(第一个可用类型)
InstallationType get recommendedInstallationType {
if (availableInstallationTypes.isNotEmpty) {
return availableInstallationTypes.first;
@@ -86,7 +82,7 @@ String getUpdateDownloadUrlFromAsset(Map<String, dynamic>? asset) {
String getUpdateFileHashFromAsset(Map<String, dynamic> asset) {
final digest = asset['digest'] as String? ?? '';
- if (digest.isNotEmpty && digest.startsWith('sha256:')) {
+ if (digest.startsWith('sha256:')) {
return digest.substring(7);
}
return '';
@@ -119,41 +115,19 @@ class AutoUpdater {
final DownloadHttpClient _downloadClient = DownloadHttpClient.instance;
- /// 检测所有可能的安装类型
- Future<List<InstallationType>> _detectAvailableInstallationTypes() async {
- List<InstallationType> availableTypes = [];
-
- try {
- if (Platform.isWindows) {
- // Windows 平台支持 MSIX 和 ZIP 便携版
- availableTypes.add(InstallationType.windowsMsix);
- availableTypes.add(InstallationType.windowsPortable);
- } else if (Platform.isLinux) {
- // Linux 平台支持 DEB 和 TAR.GZ
- availableTypes.add(InstallationType.linuxDeb);
- availableTypes.add(InstallationType.linuxTar);
- } else if (Platform.isMacOS) {
- // macOS 平台支持 DMG
- availableTypes.add(InstallationType.macosDmg);
- } else if (Platform.isIOS) {
- // iOS 平台通过 Github
- availableTypes.add(InstallationType.ios);
- } else if (Platform.isAndroid) {
- // Android 平台支持 APK
- availableTypes.add(InstallationType.androidApk);
- }
- } catch (e) {
- KazumiLogger().w('Update: detect installation types failed', error: e);
+ List<InstallationType> _detectAvailableInstallationTypes() {
+ if (Platform.isWindows) {
+ return [InstallationType.windowsMsix, InstallationType.windowsPortable];
}
-
- if (availableTypes.isEmpty) {
- availableTypes.add(InstallationType.unknown);
+ if (Platform.isLinux) {
+ return [InstallationType.linuxDeb, InstallationType.linuxTar];
}
-
- return availableTypes;
+ if (Platform.isMacOS) return [InstallationType.macosDmg];
+ if (Platform.isIOS) return [InstallationType.ios];
+ if (Platform.isAndroid) return [InstallationType.androidApk];
+ return [InstallationType.unknown];
}
- /// 检查是否有新版本可用
Future<UpdateInfo?> checkForUpdates() async {
try {
final data = await _latestRelease();
@@ -166,17 +140,15 @@ class AutoUpdater {
final currentVersion = ApiEndpoints.version;
if (needUpdate(currentVersion, remoteVersion)) {
- final availableTypes = await _detectAvailableInstallationTypes();
+ final availableTypes = _detectAvailableInstallationTypes();
return UpdateInfo(
version: remoteVersion,
description: data['body'] ?? '发现新版本',
downloadUrl: '',
- // 将在用户选择安装类型后填充
releaseNotes: data['html_url'] ?? '',
publishedAt: data['published_at'] ?? '',
installationType: availableTypes.first,
- // 保持兼容性
availableInstallationTypes: availableTypes,
assets: data['assets'] ?? [],
);
@@ -198,7 +170,6 @@ class AutoUpdater {
return Map<String, dynamic>.from(data);
}
- /// 自动检查更新(仅在启用自动更新时)
Future<void> autoCheckForUpdates() async {
final autoUpdate = GStorage.getSetting(SettingsKeys.autoUpdate);
if (!autoUpdate) return;
@@ -209,12 +180,10 @@ class AutoUpdater {
_showUpdateDialog(updateInfo, isAutoCheck: true);
}
} catch (e) {
- // 自动检查失败时不显示错误
KazumiLogger().w('Update: auto check for updates failed', error: e);
}
}
- /// 手动检查更新
Future<void> manualCheckForUpdates() async {
try {
final updateInfo = await checkForUpdates();
@@ -228,7 +197,6 @@ class AutoUpdater {
}
}
- /// 显示更新对话框
void _showUpdateDialog(UpdateInfo updateInfo, {bool isAutoCheck = false}) {
KazumiDialog.show(
builder: (context) {
@@ -358,7 +326,6 @@ class AutoUpdater {
TextButton(
onPressed: () {
KazumiDialog.dismiss();
- // 直接使用第一个可用的安装类型
if (updateInfo.availableInstallationTypes.isNotEmpty) {
_downloadUpdateWithType(
updateInfo, updateInfo.availableInstallationTypes.first);
@@ -372,7 +339,6 @@ class AutoUpdater {
);
}
- /// 获取安装类型的描述
String _getInstallationTypeDescription(InstallationType type) {
switch (type) {
case InstallationType.windowsMsix:
@@ -394,11 +360,9 @@ class AutoUpdater {
}
}
- /// 根据选择的类型下载更新
Future<void> _downloadUpdateWithType(
UpdateInfo updateInfo, InstallationType selectedType) async {
try {
- // iOS 和 Linux 直接跳转到 Release 页面
if (selectedType == InstallationType.ios ||
selectedType == InstallationType.linuxDeb ||
selectedType == InstallationType.linuxTar) {
@@ -420,8 +384,6 @@ class AutoUpdater {
}
final expectedHash = getUpdateFileHashFromAsset(asset);
-
- // 创建一个临时的 UpdateInfo 对象用于下载
final downloadInfo = UpdateInfo(
version: updateInfo.version,
description: updateInfo.description,
@@ -440,60 +402,48 @@ class AutoUpdater {
}
}
- /// 下载更新
Future<void> _downloadUpdate(
UpdateInfo updateInfo, String expectedHash) async {
- if (updateInfo.downloadUrl.isEmpty) {
- KazumiDialog.showToast(message: '没有找到合适的下载链接');
- return;
- }
-
- // 显示下载进度对话框
- KazumiDialog.show(
- clickMaskDismiss: false,
- builder: (context) {
- return AlertDialog(
- title: const Text('正在下载更新'),
- content: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- ValueListenableBuilder<double>(
- valueListenable: _downloadProgress,
- builder: (context, value, child) {
- return Column(
- children: [
- LinearProgressIndicator(value: value),
- const SizedBox(height: 8),
- Text('${(value * 100).toStringAsFixed(1)}%'),
- ],
- );
- },
+ if (_downloadDialogs.isRunning) return;
+ await _downloadDialogs.run((task) async {
+ _downloadProgress.value = 0;
+ final cancelToken = CancelToken();
+ final downloadPath = await task.loading(
+ action: () => _downloadFile(updateInfo.downloadUrl, updateInfo.version,
+ expectedHash, cancelToken),
+ onCancel: cancelToken.cancel,
+ builder: (context) {
+ return AlertDialog(
+ title: const Text('正在下载更新'),
+ content: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ ValueListenableBuilder<double>(
+ valueListenable: _downloadProgress,
+ builder: (context, value, child) {
+ return Column(
+ children: [
+ LinearProgressIndicator(value: value),
+ const SizedBox(height: 8),
+ Text('${(value * 100).toStringAsFixed(1)}%'),
+ ],
+ );
+ },
+ ),
+ ],
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => KazumiDialog.dismiss(context: context),
+ child: const Text('取消'),
),
],
- ),
- actions: [
- TextButton(
- onPressed: () {
- _cancelDownload();
- KazumiDialog.dismiss();
- },
- child: const Text('取消'),
- ),
- ],
- );
- },
- );
-
- try {
- final downloadPath = await _downloadFile(
- updateInfo.downloadUrl, updateInfo.version, expectedHash);
+ );
+ },
+ );
- // 不自动关闭对话框,而是显示下载完成状态
_showDownloadCompleteDialog(downloadPath, updateInfo);
- } catch (e) {
- KazumiDialog.dismiss();
-
- // 显示详细的错误信息
+ }, onError: (e, _) {
String errorMessage = '下载失败';
if (e.toString().contains('Permission denied') ||
e.toString().contains('Operation not permitted')) {
@@ -524,13 +474,12 @@ class AutoUpdater {
),
actions: [
TextButton(
- onPressed: () => KazumiDialog.dismiss(),
+ onPressed: () => KazumiDialog.dismiss(context: context),
child: const Text('确定'),
),
TextButton(
onPressed: () {
- KazumiDialog.dismiss();
- // 重新尝试下载
+ KazumiDialog.dismiss(context: context);
_downloadUpdate(updateInfo, expectedHash);
},
child: const Text('重试'),
@@ -541,21 +490,13 @@ class AutoUpdater {
);
KazumiLogger().e('Update: download update failed', error: e);
- }
+ });
}
final ValueNotifier<double> _downloadProgress = ValueNotifier(0.0);
- CancelToken? _cancelToken;
-
- void _cancelDownload() {
- _cancelToken?.cancel();
- }
+ final _downloadDialogs = KazumiDialogController();
- /// 显示下载完成对话框
void _showDownloadCompleteDialog(String filePath, UpdateInfo updateInfo) {
- // 替换当前的下载进度对话框内容
- KazumiDialog.dismiss();
-
KazumiDialog.show(
builder: (context) {
return AlertDialog(
@@ -622,7 +563,7 @@ class AutoUpdater {
if (isDesktop())
TextButton(
onPressed: () {
- // 在文件管理器中显示文件
+ KazumiDialog.dismiss(context: context);
_revealInFileManager(filePath);
},
child: const Text('打开文件夹'),
@@ -641,35 +582,35 @@ class AutoUpdater {
);
}
- /// 下载文件
- Future<String> _downloadFile(
- String url, String version, String expectedHash) async {
- final fileName = _getFileNameFromUrl(url, version);
+ Future<String> _downloadFile(String url, String version, String expectedHash,
+ CancelToken cancelToken) async {
+ // Dio cancellation does not cover filesystem preparation or hash checks.
+ void checkCancelled() {
+ if (cancelToken.isCancelled) throw cancelToken.cancelError!;
+ }
- // 统一使用临时目录
+ checkCancelled();
+ final fileName = _getFileNameFromUrl(url, version);
final tempDir = await getTemporaryDirectory();
+ checkCancelled();
final filePath = '${tempDir.path}/$fileName';
final file = File(filePath);
-
- // 检查文件是否已存在
if (await file.exists()) {
try {
- //使用哈希验证文件完整性
final localHash = await calculateFileHash(file);
+ checkCancelled();
if (localHash == expectedHash) {
- // 文件已存在且哈希匹配,直接返回
KazumiLogger().i(
'Update: file already exists and hash verified, skipping download: $filePath');
_downloadProgress.value = 1.0;
return filePath;
} else {
- // 文件存在但哈希不匹配,删除后重新下载
KazumiLogger().i(
'Update: file hash mismatch detected (local: $localHash, expected: $expectedHash), deleting and re-downloading');
await file.delete();
}
} catch (e) {
- // 验证过程中出错,删除文件重新下载
+ checkCancelled();
KazumiLogger().w(
'Update: file verification failed, deleting and re-downloading',
error: e);
@@ -679,23 +620,21 @@ class AutoUpdater {
}
}
- _cancelToken = CancelToken();
+ checkCancelled();
await _downloadClient.download(
url,
filePath,
- cancelToken: _cancelToken,
+ cancelToken: cancelToken,
onReceiveProgress: (received, total) {
- if (total > 0) {
+ if (!cancelToken.isCancelled && total > 0) {
_downloadProgress.value = received / total;
}
},
);
-
- // 下载完成后验证文件哈希
final downloadedHash = await calculateFileHash(file);
+ checkCancelled();
if (downloadedHash != expectedHash) {
- // 哈希不匹配,删除文件并抛出异常
await file.delete();
throw Exception('文件完整性验证失败: 期望 $expectedHash,实际 $downloadedHash');
}
@@ -704,11 +643,9 @@ class AutoUpdater {
return filePath;
}
- /// 安装更新
void _installUpdate(
String filePath, InstallationType installationType) async {
try {
- // 显示准备退出的提示
KazumiDialog.showToast(message: '准备安装更新,应用即将退出...');
await Future.delayed(const Duration(seconds: 2));
@@ -744,14 +681,10 @@ class AutoUpdater {
}
}
- /// 在文件管理器中显示文件
void _revealInFileManager(String filePath) async {
try {
final type = await FileSystemEntity.type(filePath);
String targetDirOrFile;
-
- // 如果传入的本来就是目录则打开这个目录
- // 如果是文件则打开包含它的目录
if (type == FileSystemEntityType.notFound) {
KazumiDialog.showToast(message: '文件或目录不存在');
return;
@@ -777,7 +710,6 @@ class AutoUpdater {
await Process.start('open', [targetDirOrFile]);
}
} else if (Platform.isLinux) {
- // 尝试打开包含文件的文件夹
await Process.start('xdg-open', [targetDirOrFile]);
} else {
KazumiDialog.showToast(message: '此平台不支持通过此方法打开文件管理器');
@@ -785,15 +717,9 @@ class AutoUpdater {
} catch (e) {
KazumiDialog.showToast(message: '无法打开文件管理器');
KazumiLogger().w('Update: reveal in file manager failed', error: e);
- } finally {
- try {
- // 确保对话框被关闭
- KazumiDialog.dismiss();
- } catch (_) {}
}
}
- /// 从URL获取文件名
String _getFileNameFromUrl(String url, String version) {
final uri = Uri.parse(url);
final fileName = uri.pathSegments.last;
@@ -801,8 +727,6 @@ class AutoUpdater {
if (fileName.isNotEmpty) {
return fileName;
}
-
- // 回退方案
String extension = '';
if (Platform.isWindows) {
extension = '.msix';
diff --git a/test/dialog_helper_test.dart b/test/dialog_helper_test.dart
new file mode 100644
index 00000000..5e5fb8cb
--- /dev/null
+++ b/test/dialog_helper_test.dart
@@ -0,0 +1,282 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:kazumi/bean/dialog/dialog_helper.dart';
+import 'package:kazumi/navigation.dart';
+import 'package:kazumi/services/player/timed_shutdown_service.dart';
+
+Future<void> mountApp(WidgetTester tester) async {
+ await tester.pumpWidget(MaterialApp(
+ navigatorKey: rootNavigatorKey,
+ scaffoldMessengerKey: rootScaffoldMessengerKey,
+ navigatorObservers: [KazumiDialog.observer],
+ home: const Scaffold(body: Text('home')),
+ ));
+ await tester.pumpAndSettle();
+}
+
+Future<void> pushPage(WidgetTester tester) async {
+ unawaited(rootNavigatorKey.currentState!.push<void>(MaterialPageRoute(
+ builder: (_) => const Scaffold(body: Text('new page')),
+ )));
+ await tester.pumpAndSettle();
+}
+
+void main() {
+ testWidgets('observer navigation and scoped toasts work without global keys',
+ (tester) async {
+ late BuildContext pageContext;
+ await tester.pumpWidget(MaterialApp(
+ navigatorObservers: [KazumiDialog.observer],
+ home: Builder(builder: (context) {
+ pageContext = context;
+ return const Scaffold(body: Text('home'));
+ }),
+ ));
+ await tester.pumpAndSettle();
+ final result = KazumiDialog.show<bool>(
+ builder: (_) => const AlertDialog(title: Text('operation')),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('operation'), findsOneWidget);
+ KazumiDialog.dismiss(popWith: true);
+ await tester.pumpAndSettle();
+ expect(await result, isTrue);
+ KazumiDialog.showToast(context: pageContext, message: 'scoped result');
+ await tester.pumpAndSettle();
+ expect(find.text('scoped result'), findsOneWidget);
+ });
+
+ testWidgets('dismiss removes the tracked dialog beneath a newer page',
+ (tester) async {
+ await mountApp(tester);
+ final result = KazumiDialog.show<bool>(
+ builder: (_) => const AlertDialog(title: Text('operation')),
+ );
+ await tester.pumpAndSettle();
+ await pushPage(tester);
+
+ KazumiDialog.dismiss(popWith: true);
+ await tester.pumpAndSettle();
+
+ expect(await result, isTrue);
+ expect(find.text('new page'), findsOneWidget);
+ expect(KazumiDialog.observer.hasKazumiDialog, isFalse);
+ rootNavigatorKey.currentState!.pop();
+ await tester.pumpAndSettle();
+ });
+
+ testWidgets('handles preserve another dialog and return the correct type',
+ (tester) async {
+ await mountApp(tester);
+ final first = KazumiDialogHandle<bool>();
+ final firstResult = KazumiDialog.show<bool>(
+ handle: first,
+ builder: (_) => const AlertDialog(title: Text('first')),
+ );
+ await tester.pumpAndSettle();
+ final second = KazumiDialogHandle<int>();
+ final secondResult = KazumiDialog.show<int>(
+ handle: second,
+ builder: (_) => const AlertDialog(title: Text('second')),
+ );
+ await tester.pumpAndSettle();
+
+ first.dismiss(popWith: true);
+ await tester.pumpAndSettle();
+ expect(await firstResult, isTrue);
+ expect(second.isActive, isTrue);
+ expect(find.text('second'), findsOneWidget);
+ first.dismiss();
+ expect(second.isActive, isTrue);
+ second.dismiss(popWith: 42);
+ await tester.pumpAndSettle();
+ expect(await secondResult, 42);
+ });
+
+ testWidgets('a dialog can finish before its builder is first called',
+ (tester) async {
+ await mountApp(tester);
+ final dialog = KazumiDialogHandle<int>();
+ final result = KazumiDialog.show<int>(
+ handle: dialog,
+ builder: (_) => const AlertDialog(title: Text('fast operation')),
+ );
+ expect(dialog.isActive, isTrue);
+ dialog.dismiss(popWith: 7);
+ await tester.pumpAndSettle();
+ expect(await result, 7);
+ expect(dialog.isActive, isFalse);
+ expect(find.text('fast operation'), findsNothing);
+ });
+
+ testWidgets('context dismissal targets its own dialog beneath another',
+ (tester) async {
+ await mountApp(tester);
+ late BuildContext firstContext;
+ final first = KazumiDialog.show<bool>(builder: (context) {
+ firstContext = context;
+ return const AlertDialog(title: Text('first'));
+ });
+ await tester.pumpAndSettle();
+ final second = KazumiDialogHandle<int>();
+ final secondResult = KazumiDialog.show<int>(
+ handle: second,
+ builder: (_) => const AlertDialog(title: Text('second')),
+ );
+ await tester.pumpAndSettle();
+ KazumiDialog.dismiss(context: firstContext, popWith: true);
+ await tester.pumpAndSettle();
+ expect(await first, isTrue);
+ expect(second.isActive, isTrue);
+ second.dismiss();
+ await tester.pumpAndSettle();
+ await secondResult;
+ });
+
+ testWidgets('back invalidates a handle immediately and awaits cleanup once',
+ (tester) async {
+ await mountApp(tester);
+ final dialog = KazumiDialogHandle<void>();
+ final cleanup = Completer<void>();
+ var cleanupCalls = 0;
+ var finished = false;
+ final result = KazumiDialog.show<void>(
+ handle: dialog,
+ builder: (_) => const AlertDialog(title: Text('operation')),
+ onDismiss: () async {
+ cleanupCalls++;
+ await cleanup.future;
+ },
+ ).then((_) => finished = true);
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 300));
+ await rootNavigatorKey.currentState!.maybePop();
+ expect(dialog.isActive, isFalse);
+ await tester.pumpAndSettle();
+ expect(cleanupCalls, 1);
+ expect(finished, isFalse);
+ cleanup.complete();
+ await result;
+ dialog.dismiss();
+ expect(cleanupCalls, 1);
+ });
+
+ testWidgets('reusing an active handle does not orphan the first dialog',
+ (tester) async {
+ await mountApp(tester);
+ final dialog = KazumiDialogHandle<void>();
+ final result = KazumiDialog.show<void>(
+ handle: dialog,
+ builder: (_) => const AlertDialog(title: Text('first')),
+ );
+ await tester.pumpAndSettle();
+ await expectLater(
+ KazumiDialog.show<void>(handle: dialog, builder: (_) => const SizedBox()),
+ throwsStateError,
+ );
+ expect(dialog.isActive, isTrue);
+ dialog.dismiss();
+ await tester.pumpAndSettle();
+ await result;
+ });
+
+ testWidgets('a toast posted after closing a dialog remains visible',
+ (tester) async {
+ await mountApp(tester);
+ final dialog = KazumiDialog.show<void>(
+ builder: (_) => const AlertDialog(title: Text('share rule')),
+ );
+ await tester.pumpAndSettle();
+ KazumiDialog.dismiss();
+ KazumiDialog.showToast(message: 'rule copied');
+ await tester.pumpAndSettle();
+ await dialog;
+ expect(find.text('rule copied'), findsOneWidget);
+ });
+
+ testWidgets('page pop clears its old toast', (tester) async {
+ await mountApp(tester);
+ await pushPage(tester);
+ KazumiDialog.showToast(message: 'old page');
+ await tester.pumpAndSettle();
+ rootNavigatorKey.currentState!.pop();
+ await tester.pumpAndSettle();
+ expect(find.text('old page'), findsNothing);
+ });
+
+ testWidgets('page pop preserves a toast posted after navigation',
+ (tester) async {
+ await mountApp(tester);
+ await pushPage(tester);
+ KazumiDialog.showToast(message: 'old page');
+ await tester.pumpAndSettle();
+ rootNavigatorKey.currentState!.pop();
+ KazumiDialog.showToast(message: 'new result');
+ await tester.pumpAndSettle();
+ expect(find.text('new result'), findsOneWidget);
+ });
+
+ testWidgets('an action can replace its toast with progress feedback',
+ (tester) async {
+ await mountApp(tester);
+ KazumiDialog.showToast(
+ message: 'updates available',
+ showActionButton: true,
+ actionLabel: 'update all',
+ onActionPressed: () => KazumiDialog.showToast(message: 'updating'),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('update all'));
+ await tester.pumpAndSettle();
+ expect(find.text('updating'), findsOneWidget);
+ });
+
+ testWidgets('cancelling a timer only closes its own expiry dialog',
+ (tester) async {
+ await mountApp(tester);
+ final timer = TimedShutdownService();
+ timer.start(1);
+ await tester.pump(const Duration(minutes: 1));
+ await tester.pumpAndSettle();
+ expect(find.text('定时关闭'), findsOneWidget);
+
+ final second = KazumiDialogHandle<int>();
+ final result = KazumiDialog.show<int>(
+ handle: second,
+ builder: (_) => const AlertDialog(title: Text('unrelated')),
+ );
+ await tester.pumpAndSettle();
+ timer.cancel();
+ await tester.pumpAndSettle();
+ expect(second.isActive, isTrue);
+ expect(find.text('unrelated'), findsOneWidget);
+ second.dismiss();
+ await tester.pumpAndSettle();
+ await result;
+ });
+
+ testWidgets('repeating the timer preserves its duration and expiry callback',
+ (tester) async {
+ await mountApp(tester);
+ final timer = TimedShutdownService();
+ addTearDown(timer.cancel);
+ var expirations = 0;
+ timer.start(1, onExpired: () => expirations++);
+ await tester.pump(const Duration(minutes: 1));
+ await tester.pumpAndSettle();
+ expect(expirations, 1);
+ await tester.tap(find.text('重复'));
+ await tester.pumpAndSettle();
+ expect(timer.isActive, isTrue);
+ expect(timer.setMinutes, 1);
+ expect(find.text('重复'), findsNothing);
+ await tester.pump(const Duration(minutes: 1));
+ await tester.pumpAndSettle();
+ expect(expirations, 2);
+ expect(find.text('重复'), findsOneWidget);
+ timer.cancel();
+ await tester.pumpAndSettle();
+ });
+}
diff --git a/test/dialog_task_test.dart b/test/dialog_task_test.dart
new file mode 100644
index 00000000..2c1b563d
--- /dev/null
+++ b/test/dialog_task_test.dart
@@ -0,0 +1,378 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:kazumi/bean/dialog/dialog_helper.dart';
+import 'package:kazumi/navigation.dart';
+
+Future<void> mountApp(WidgetTester tester, {Widget? home}) async {
+ await tester.pumpWidget(MaterialApp(
+ navigatorKey: rootNavigatorKey,
+ scaffoldMessengerKey: rootScaffoldMessengerKey,
+ navigatorObservers: [KazumiDialog.observer],
+ home: home ?? const Scaffold(body: Text('home')),
+ ));
+ await tester.pumpAndSettle();
+}
+
+Widget progress(BuildContext context) =>
+ const AlertDialog(title: Text('loading'));
+
+void main() {
+ testWidgets('loading returns its value and preserves a newer dialog',
+ (tester) async {
+ await mountApp(tester);
+ final dialogs = KazumiDialogController();
+ addTearDown(dialogs.dispose);
+ final response = Completer<int>();
+ int? result;
+ var cancelled = false;
+ final run = dialogs.run((task) async {
+ result = await task.loading(
+ action: () => response.future,
+ onCancel: () => cancelled = true,
+ builder: progress,
+ );
+ });
+ await tester.pumpAndSettle();
+ final other = KazumiDialogHandle<void>();
+ unawaited(KazumiDialog.show<void>(
+ handle: other,
+ builder: (_) => const AlertDialog(title: Text('other')),
+ ));
+ await tester.pumpAndSettle();
+ response.complete(42);
+ await tester.pumpAndSettle();
+ await run;
+ expect(result, 42);
+ expect(cancelled, isFalse);
+ expect(dialogs.isRunning, isFalse);
+ expect(other.isActive, isTrue);
+ expect(find.text('loading'), findsNothing);
+ other.dismiss();
+ await tester.pumpAndSettle();
+ });
+
+ testWidgets(
+ 'loading can complete before its first frame and continue to a choice',
+ (tester) async {
+ await mountApp(tester);
+ final dialogs = KazumiDialogController();
+ addTearDown(dialogs.dispose);
+ bool? choice;
+ final run = dialogs.run((task) async {
+ expectSync(await task.loading(action: () async => 7), 7);
+ choice = await task.show<bool>(
+ builder: (context) => AlertDialog(
+ title: const Text('choice'),
+ actions: [
+ TextButton(
+ onPressed: () =>
+ KazumiDialog.dismiss(context: context, popWith: false),
+ child: const Text('no'),
+ )
+ ],
+ ));
+ expectSync(await task.loading(action: () async => 8), 8);
+ });
+ await tester.pumpAndSettle();
+ expect(find.text('choice'), findsOneWidget);
+ await tester.tap(find.text('no'));
+ await tester.pumpAndSettle();
+ await run;
+ expect(choice, isFalse);
+ expectSync(KazumiDialog.observer.hasKazumiDialog, isFalse);
+ });
+
+ testWidgets('dismissing a choice stops the remaining workflow',
+ (tester) async {
+ await mountApp(tester);
+ final dialogs = KazumiDialogController();
+ addTearDown(dialogs.dispose);
+ var continued = false;
+ var cancellations = 0;
+ final run = dialogs.run((task) async {
+ await task.show<int>(
+ builder: (_) => const AlertDialog(title: Text('choice')));
+ continued = true;
+ }, onCancelled: () => cancellations++);
+ await tester.pumpAndSettle();
+ await tester.binding.handlePopRoute();
+ await tester.pumpAndSettle();
+ await run;
+ expect(continued, isFalse);
+ expect(cancellations, 1);
+ });
+
+ for (final lateFailure in [false, true]) {
+ testWidgets(
+ 'back ends an uncooperative request and ignores late ${lateFailure ? 'failure' : 'success'}',
+ (tester) async {
+ await mountApp(tester);
+ final dialogs = KazumiDialogController();
+ addTearDown(dialogs.dispose);
+ final response = Completer<int>();
+ var continued = false;
+ var cancellations = 0;
+ var errors = 0;
+ final run = dialogs.run((task) async {
+ await task.loading(
+ action: () => response.future,
+ onCancel: () => cancellations++,
+ builder: progress,
+ );
+ continued = true;
+ }, onError: (error, stackTrace) => errors++);
+ await tester.pumpAndSettle();
+ await tester.binding.handlePopRoute();
+ await tester.pumpAndSettle();
+ await run;
+ dialogs.cancel();
+ expect(dialogs.isRunning, isFalse);
+ expect(response.isCompleted, isFalse);
+ expect(cancellations, 1);
+ if (lateFailure) {
+ response.completeError(StateError('late response'));
+ } else {
+ response.complete(42);
+ }
+ await tester.pumpAndSettle();
+ expect(continued, isFalse);
+ expect(errors, 0);
+ expect(tester.takeException(), isNull);
+ });
+ }
+
+ testWidgets('back wins when a response completes in the same turn',
+ (tester) async {
+ await mountApp(tester);
+ final dialogs = KazumiDialogController();
+ addTearDown(dialogs.dispose);
+ final response = Completer<int>();
+ var continued = false;
+ final run = dialogs.run((task) async {
+ await task.loading(action: () => response.future, builder: progress);
+ continued = true;
+ });
+ await tester.pumpAndSettle();
+ rootNavigatorKey.currentState!.pop();
+ response.complete(42);
+ await tester.pumpAndSettle();
+ await run;
+ expect(continued, isFalse);
+ });
+
+ testWidgets(
+ 'cancellation awaits resource cleanup before fallback or disposal',
+ (tester) async {
+ await mountApp(tester);
+ final dialogs = KazumiDialogController();
+ addTearDown(dialogs.dispose);
+ final response = Completer<int>();
+ final cleanup = Completer<void>();
+ final events = <String>[];
+ final run = dialogs.run((task) async {
+ try {
+ await task.loading(
+ action: () => response.future,
+ builder: progress,
+ onCancel: () async {
+ events.add('save');
+ await cleanup.future;
+ events.add('saved');
+ },
+ );
+ events.add('continued');
+ } finally {
+ events.add('dispose');
+ }
+ }, onCancelled: () => events.add('fallback'));
+ await tester.pumpAndSettle();
+ await tester.binding.handlePopRoute();
+ await tester.pumpAndSettle();
+ expect(events, ['save']);
+ dialogs.cancel();
+ cleanup.complete();
+ await tester.pumpAndSettle();
+ await run;
+ expect(events, ['save', 'saved', 'dispose', 'fallback']);
+ response.complete(0);
+ await tester.pumpAndSettle();
+ });
+
+ testWidgets('replacement ignores old cleanup and keeps the new workflow open',
+ (tester) async {
+ await mountApp(tester);
+ final dialogs = KazumiDialogController();
+ addTearDown(dialogs.dispose);
+ final response = Completer<int>();
+ final cleanup = Completer<void>();
+ var oldFallback = false;
+ late KazumiDialogTask oldTask;
+ final first = dialogs.run((task) async {
+ oldTask = task;
+ await task.loading(
+ action: () => response.future,
+ onCancel: () => cleanup.future,
+ builder: progress,
+ );
+ fail('replaced workflow continued');
+ }, onCancelled: () => oldFallback = true);
+ await tester.pumpAndSettle();
+ final second = dialogs.run((task) async {
+ await task.show<bool>(
+ builder: (_) => const AlertDialog(title: Text('new choice')));
+ });
+ await tester.pumpAndSettle();
+ cleanup.complete();
+ response.completeError(StateError('old failure'));
+ await tester.pumpAndSettle();
+ await first;
+ oldTask.cancel();
+ expect(oldFallback, isFalse);
+ expect(dialogs.isRunning, isTrue);
+ expect(find.text('new choice'), findsOneWidget);
+ await tester.binding.handlePopRoute();
+ await tester.pumpAndSettle();
+ await second;
+ });
+
+ testWidgets('real failures reach the error handler after loading is closed',
+ (tester) async {
+ await mountApp(tester);
+ final dialogs = KazumiDialogController();
+ addTearDown(dialogs.dispose);
+ final response = Completer<int>();
+ final failure = StateError('request failed');
+ Object? reported;
+ var cancelled = false;
+ final run = dialogs.run((task) async {
+ await task.loading(
+ action: () => response.future,
+ onCancel: () => cancelled = true,
+ builder: progress,
+ );
+ fail('failed request continued');
+ }, onError: (error, _) {
+ reported = error;
+ expectSync(KazumiDialog.observer.hasKazumiDialog, isFalse);
+ });
+ await tester.pumpAndSettle();
+ response.completeError(failure);
+ await tester.pumpAndSettle();
+ await run;
+ expect(reported, same(failure));
+ expect(cancelled, isFalse);
+ });
+
+ testWidgets('a synchronous request error uses the configured toast',
+ (tester) async {
+ await mountApp(tester);
+ final dialogs = KazumiDialogController();
+ addTearDown(dialogs.dispose);
+ final run = dialogs.run((task) async {
+ await task.loading<int>(action: () => throw StateError('failed'));
+ }, errorMessage: 'request failed');
+ await tester.pumpAndSettle();
+ await run;
+ expect(find.text('request failed'), findsOneWidget);
+ expectSync(KazumiDialog.observer.hasKazumiDialog, isFalse);
+ });
+
+ testWidgets('owner disposal closes its workflow and preserves another dialog',
+ (tester) async {
+ final present = ValueNotifier(true);
+ addTearDown(present.dispose);
+ final response = Completer<int>();
+ var cancelled = false;
+ var continued = false;
+ var fallback = false;
+ await mountApp(tester,
+ home: ValueListenableBuilder<bool>(
+ valueListenable: present,
+ builder: (context, visible, child) => visible
+ ? _Owner(
+ operation: response.future,
+ onCancel: () => cancelled = true,
+ onResult: () => continued = true,
+ onFallback: () => fallback = true,
+ )
+ : const Scaffold(body: Text('replacement')),
+ ));
+ await tester.tap(find.text('start'));
+ await tester.pumpAndSettle();
+ final other = KazumiDialogHandle<void>();
+ unawaited(KazumiDialog.show<void>(
+ handle: other,
+ builder: (_) => const AlertDialog(title: Text('other')),
+ ));
+ await tester.pumpAndSettle();
+ present.value = false;
+ await tester.pumpAndSettle();
+ expect(cancelled, isTrue);
+ expect(other.isActive, isTrue);
+ response.complete(42);
+ await tester.pumpAndSettle();
+ expect(continued, isFalse);
+ expect(fallback, isFalse);
+ expect(tester.takeException(), isNull);
+ other.dismiss();
+ await tester.pumpAndSettle();
+ expect(find.text('loading'), findsNothing);
+ expect(find.text('replacement'), findsOneWidget);
+ });
+
+ testWidgets('owner rebuilds busy state and applies a result with its context',
+ (tester) async {
+ final response = Completer<int>();
+ var continued = false;
+ await mountApp(tester,
+ home: _Owner(
+ operation: response.future,
+ onCancel: () {},
+ onResult: () => continued = true,
+ onFallback: () {},
+ ));
+ await tester.tap(find.text('start'));
+ await tester.pumpAndSettle();
+ expect(find.text('busy', skipOffstage: false), findsOneWidget);
+ response.complete(42);
+ await tester.pumpAndSettle();
+ expect(continued, isTrue);
+ expect(find.text('start'), findsOneWidget);
+ expect(find.text('busy'), findsNothing);
+ });
+}
+
+class _Owner extends StatefulWidget {
+ const _Owner(
+ {required this.operation,
+ required this.onCancel,
+ required this.onResult,
+ required this.onFallback});
+ final Future<int> operation;
+ final VoidCallback onCancel;
+ final VoidCallback onResult;
+ final VoidCallback onFallback;
+
+ @override
+ State<_Owner> createState() => _OwnerState();
+}
+
+class _OwnerState extends State<_Owner> with KazumiDialogOwner {
+ @override
+ Widget build(BuildContext context) => Scaffold(
+ body: TextButton(
+ onPressed: () => dialogs.run((task) async {
+ await task.loading(
+ action: () => widget.operation,
+ onCancel: widget.onCancel,
+ builder: progress);
+ task.withContext((context) {
+ expectSync(context.mounted, isTrue);
+ widget.onResult();
+ });
+ }, onCancelled: widget.onFallback),
+ child: Text(dialogs.isRunning ? 'busy' : 'start'),
+ ));
+}