A cross platform Audiobookshelf client for Android and iOS
Dart
Fix downloads and improve metadata, playlist and collection editing, covers, and toast messages
Barnabasc8c394aab20c
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arbindex ba96408b..bbbf672b 100644--- a/lib/l10n/app_en.arb+++ b/lib/l10n/app_en.arb@@ -1424,6 +1424,7 @@"castingTo": "Casting to","editDetails": "Edit Details","quickMatch": "Quick Match",+ "quickMatchNoUpdates": "No updates necessary","custom": "Custom","authorOptionalLabel": "Author (optional)","noResultsFound": "No results found.\nTry adjusting your search or provider.",diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dartindex 38708211..984ec35e 100644--- a/lib/l10n/app_localizations.dart+++ b/lib/l10n/app_localizations.dart@@ -5134,6 +5134,12 @@ abstract class AppLocalizations {/// **'Quick Match'**String get quickMatch;+ /// No description provided for @quickMatchNoUpdates.+ ///+ /// In en, this message translates to:+ /// **'No updates necessary'**+ String get quickMatchNoUpdates;+/// No description provided for @custom.////// In en, this message translates to:diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dartindex dcfdeb75..5b652059 100644--- a/lib/l10n/app_localizations_de.dart+++ b/lib/l10n/app_localizations_de.dart@@ -2841,6 +2841,9 @@ class AppLocalizationsDe extends AppLocalizations {@overrideString get quickMatch => 'Schnellabgleich';+ @override+ String get quickMatchNoUpdates => 'No updates necessary';+@overrideString get custom => 'Benutzerdefiniert';diff --git a/lib/l10n/app_localizations_el.dart b/lib/l10n/app_localizations_el.dartindex 7ab4576b..db7115b7 100644--- a/lib/l10n/app_localizations_el.dart+++ b/lib/l10n/app_localizations_el.dart@@ -2815,6 +2815,9 @@ class AppLocalizationsEl extends AppLocalizations {@overrideString get quickMatch => 'Quick Match';+ @override+ String get quickMatchNoUpdates => 'No updates necessary';+@overrideString get custom => 'Custom';diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dartindex 3bd55f9e..a22b58d9 100644--- a/lib/l10n/app_localizations_en.dart+++ b/lib/l10n/app_localizations_en.dart@@ -2815,6 +2815,9 @@ class AppLocalizationsEn extends AppLocalizations {@overrideString get quickMatch => 'Quick Match';+ @override+ String get quickMatchNoUpdates => 'No updates necessary';+@overrideString get custom => 'Custom';diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dartindex cb752202..231172e5 100644--- a/lib/l10n/app_localizations_es.dart+++ b/lib/l10n/app_localizations_es.dart@@ -2815,6 +2815,9 @@ class AppLocalizationsEs extends AppLocalizations {@overrideString get quickMatch => 'Quick Match';+ @override+ String get quickMatchNoUpdates => 'No updates necessary';+@overrideString get custom => 'Custom';diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dartindex 92f81da9..a6c15367 100644--- a/lib/l10n/app_localizations_fr.dart+++ b/lib/l10n/app_localizations_fr.dart@@ -2817,6 +2817,9 @@ class AppLocalizationsFr extends AppLocalizations {@overrideString get quickMatch => 'Quick Match';+ @override+ String get quickMatchNoUpdates => 'No updates necessary';+@overrideString get custom => 'Custom';diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dartindex 4d80702c..cc34f032 100644--- a/lib/l10n/app_localizations_it.dart+++ b/lib/l10n/app_localizations_it.dart@@ -2815,6 +2815,9 @@ class AppLocalizationsIt extends AppLocalizations {@overrideString get quickMatch => 'Quick Match';+ @override+ String get quickMatchNoUpdates => 'No updates necessary';+@overrideString get custom => 'Custom';diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dartindex 5d82757e..bc0df562 100644--- a/lib/l10n/app_localizations_ja.dart+++ b/lib/l10n/app_localizations_ja.dart@@ -2815,6 +2815,9 @@ class AppLocalizationsJa extends AppLocalizations {@overrideString get quickMatch => 'Quick Match';+ @override+ String get quickMatchNoUpdates => 'No updates necessary';+@overrideString get custom => 'Custom';diff --git a/lib/l10n/app_localizations_no.dart b/lib/l10n/app_localizations_no.dartindex 40eea2f3..06292c3b 100644--- a/lib/l10n/app_localizations_no.dart+++ b/lib/l10n/app_localizations_no.dart@@ -2815,6 +2815,9 @@ class AppLocalizationsNo extends AppLocalizations {@overrideString get quickMatch => 'Quick Match';+ @override+ String get quickMatchNoUpdates => 'No updates necessary';+@overrideString get custom => 'Custom';diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dartindex 0d777b4b..0d3d0802 100644--- a/lib/l10n/app_localizations_pt.dart+++ b/lib/l10n/app_localizations_pt.dart@@ -2815,6 +2815,9 @@ class AppLocalizationsPt extends AppLocalizations {@overrideString get quickMatch => 'Quick Match';+ @override+ String get quickMatchNoUpdates => 'No updates necessary';+@overrideString get custom => 'Custom';diff --git a/lib/l10n/app_localizations_ro.dart b/lib/l10n/app_localizations_ro.dartindex 71715f58..7200d25f 100644--- a/lib/l10n/app_localizations_ro.dart+++ b/lib/l10n/app_localizations_ro.dart@@ -2815,6 +2815,9 @@ class AppLocalizationsRo extends AppLocalizations {@overrideString get quickMatch => 'Quick Match';+ @override+ String get quickMatchNoUpdates => 'No updates necessary';+@overrideString get custom => 'Custom';diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dartindex b25fabf5..e4a12d1c 100644--- a/lib/l10n/app_localizations_ru.dart+++ b/lib/l10n/app_localizations_ru.dart@@ -2818,6 +2818,9 @@ class AppLocalizationsRu extends AppLocalizations {@overrideString get quickMatch => 'Quick Match';+ @override+ String get quickMatchNoUpdates => 'No updates necessary';+@overrideString get custom => 'Custom';diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dartindex 4e14e9bb..bb016b83 100644--- a/lib/l10n/app_localizations_zh.dart+++ b/lib/l10n/app_localizations_zh.dart@@ -2746,6 +2746,9 @@ class AppLocalizationsZh extends AppLocalizations {@overrideString get quickMatch => '快速匹配';+ @override+ String get quickMatchNoUpdates => 'No updates necessary';+@overrideString get custom => '自定义';diff --git a/lib/main.dart b/lib/main.dartindex 0320ced8..87429d39 100644--- a/lib/main.dart+++ b/lib/main.dart@@ -114,10 +114,6 @@ void applyTrustAllCerts(bool enabled) {trustAllCerts = enabled;}-/// Global key so non-widget code (e.g. providers) can show snackbars.-final GlobalKey<ScaffoldMessengerState> scaffoldMessengerKey =- GlobalKey<ScaffoldMessengerState>();-/// Global navigator key so non-widget code (e.g. app-icon shortcut handlers)/// can push routes without needing a BuildContext.final GlobalKey<NavigatorState> rootNavigatorKey =@@ -353,7 +349,6 @@ class AbsorbApp extends StatelessWidget {);return MaterialApp(- scaffoldMessengerKey: scaffoldMessengerKey,navigatorKey: rootNavigatorKey,title: 'Absorb',debugShowCheckedModeBanner: false,diff --git a/lib/providers/_lp_absorbing.dart b/lib/providers/_lp_absorbing.dartindex 3697125e..c3daa104 100644--- a/lib/providers/_lp_absorbing.dart+++ b/lib/providers/_lp_absorbing.dart@@ -477,7 +477,7 @@ mixin _AbsorbingMixin on ChangeNotifier, _StateMixin, _CoreMixin {PlayerSettings.getRollingDownloadDeleteFinished().then((delete) {if (!delete) return;DownloadService().deleteDownload(itemId, skipStopCheck: true);- _showRollingSnackBar(_l()?.lpDeletedFinishedDownload ?? 'Deleted finished download',+ _showRollingToast(_l()?.lpDeletedFinishedDownload ?? 'Deleted finished download',icon: Icons.delete_outline_rounded);});}diff --git a/lib/providers/_lp_core.dart b/lib/providers/_lp_core.dartindex 6fbc7939..c20b2784 100644--- a/lib/providers/_lp_core.dart+++ b/lib/providers/_lp_core.dart@@ -1159,13 +1159,14 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {}void _onEncodeFinished(Map<String, dynamic> data) {- final messenger = scaffoldMessengerKey.currentState;- if (messenger == null) return;- final ctx = messenger.context;- final l = AppLocalizations.of(ctx);- messenger- ..clearSnackBars()- ..showSnackBar(SnackBar(content: Text(l?.encodeFinished ?? 'M4B encode finished')));+ final navigator = rootNavigatorKey.currentState;+ if (navigator == null) return;+ final l = AppLocalizations.of(navigator.context);+ showNavigatorOverlayToast(+ navigator,+ l?.encodeFinished ?? 'M4B encode finished',+ icon: Icons.check_circle_outline_rounded,+ );}void _goOffline() {@@ -2307,7 +2308,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {if (newDownloads > 0) {final l = _l();- _showRollingSnackBar(+ _showRollingToast(l?.lpQueueDownloadingItems(newDownloads)?? 'Queue: downloading $newDownloads item${newDownloads == 1 ? '' : 's'}',icon: Icons.download_rounded);@@ -2438,7 +2439,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {if (newDownloads > 0) {final l = _l();- _showRollingSnackBar(+ _showRollingToast(l?.lpDownloadingBooks(newDownloads)?? 'Downloading $newDownloads book${newDownloads == 1 ? '' : 's'}',icon: Icons.download_rounded);@@ -2517,7 +2518,7 @@ mixin _CoreMixin on ChangeNotifier, _StateMixin {if (newDownloads > 0) {final l = _l();- _showRollingSnackBar(+ _showRollingToast(l?.lpDownloadingEpisodes(newDownloads)?? 'Downloading $newDownloads episode${newDownloads == 1 ? '' : 's'}',icon: Icons.download_rounded);diff --git a/lib/providers/_lp_state.dart b/lib/providers/_lp_state.dartindex eb5459e3..5d907056 100644--- a/lib/providers/_lp_state.dart+++ b/lib/providers/_lp_state.dart@@ -335,9 +335,12 @@ mixin _StateMixin on ChangeNotifier {return cached;}- void _showRollingSnackBar(String message, {IconData? icon}) {- final ctx = rootNavigatorKey.currentContext;- if (ctx != null) showOverlayToast(ctx, message, icon: icon);+ void _showRollingToast(String message, {IconData? icon}) {+ showNavigatorOverlayToast(+ rootNavigatorKey.currentState,+ message,+ icon: icon,+ );}/// Look up [AppLocalizations] via the root navigator. Returns null if nodiff --git a/lib/providers/library_provider.dart b/lib/providers/library_provider.dartindex 8d1a778e..bbef9bdd 100644--- a/lib/providers/library_provider.dart+++ b/lib/providers/library_provider.dart@@ -21,7 +21,7 @@ import '../services/socket_service.dart';import '../services/book_search_index.dart';import '../services/home_widget_service.dart';import '../l10n/app_localizations.dart';-import '../main.dart' show scaffoldMessengerKey, rootNavigatorKey;+import '../main.dart' show rootNavigatorKey;import '../widgets/overlay_toast.dart';part '_lp_state.dart';diff --git a/lib/screens/admin_missing_items_screen.dart b/lib/screens/admin_missing_items_screen.dartindex 8ad4354a..cc0f98ee 100644--- a/lib/screens/admin_missing_items_screen.dart+++ b/lib/screens/admin_missing_items_screen.dart@@ -6,6 +6,7 @@ import '../l10n/app_localizations.dart';import '../providers/auth_provider.dart';import '../services/socket_service.dart';import '../widgets/absorb_page_header.dart';+import '../widgets/overlay_toast.dart';/// Admin cleanup screen: lists the items a library has flagged as "issues" -/// missing (files removed from disk) or invalid (present but unparseable) - and@@ -70,13 +71,8 @@ class _AdminMissingItemsScreenState extends State<AdminMissingItemsScreen> {});}- void _msg(String s) => ScaffoldMessenger.of(context)- ..clearSnackBars()- ..showSnackBar(SnackBar(- content: Text(s),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ void _msg(String s, {IconData? icon}) =>+ showOverlayToast(context, s, icon: icon);String _titleOf(Map<String, dynamic> item) =>((item['media'] as Map?)?['metadata'] as Map?)?['title'] as String? ??@@ -121,11 +117,11 @@ class _AdminMissingItemsScreenState extends State<AdminMissingItemsScreen> {_items.removeWhere((it) => (it as Map)['id'] == id);_selected.remove(id);});- _msg(l.adminMissingRemovedOne(title));+ _msg(l.adminMissingRemovedOne(title), icon: Icons.delete_outline_rounded);} else if (status == 403) {- _msg(l.deletePermissionRequired);+ _msg(l.deletePermissionRequired, icon: Icons.lock_outline_rounded);} else {- _msg(l.adminMissingDeleteFailed);+ _msg(l.adminMissingDeleteFailed, icon: Icons.error_outline_rounded);}}@@ -157,9 +153,10 @@ class _AdminMissingItemsScreenState extends State<AdminMissingItemsScreen> {if (!mounted) return;setState(() => _deleting.removeAll(ids));if (forbidden && deleted == 0) {- _msg(l.deletePermissionRequired);+ _msg(l.deletePermissionRequired, icon: Icons.lock_outline_rounded);} else {- _msg(l.adminMissingRemovedMany(deleted));+ _msg(l.adminMissingRemovedMany(deleted),+ icon: Icons.delete_outline_rounded);}}diff --git a/lib/screens/admin_podcasts_screen.dart b/lib/screens/admin_podcasts_screen.dartindex 81a876de..10f01c55 100644--- a/lib/screens/admin_podcasts_screen.dart+++ b/lib/screens/admin_podcasts_screen.dart@@ -8,6 +8,7 @@ import '../services/socket_service.dart';import 'podcast_edit_screen.dart';import '../widgets/absorb_page_header.dart';import '../widgets/html_description.dart';+import '../widgets/overlay_toast.dart';import '../l10n/app_localizations.dart';import '../utils/duration_format.dart';@@ -110,10 +111,13 @@ class _AdminPodcastsScreenState extends State<AdminPodcastsScreen> {if (mounted) {final l = AppLocalizations.of(context)!;setState(() => _checkingEpisodes = false);- ScaffoldMessenger.of(context)..clearSnackBars()..showSnackBar(SnackBar(- content: Text(ok ? l.adminPodcastsCheckingForNew : l.adminPodcastsFailedCheckEpisodes),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));+ showOverlayToast(+ context,+ ok+ ? l.adminPodcastsCheckingForNew+ : l.adminPodcastsFailedCheckEpisodes,+ icon: ok ? Icons.refresh_rounded : Icons.error_outline_rounded,+ );if (ok) Future.delayed(const Duration(seconds: 3), _loadShows);}}@@ -367,10 +371,11 @@ class _PodcastSearchSheetState extends State<_PodcastSearchSheet> {return;}}- ScaffoldMessenger.of(context)..clearSnackBars()..showSnackBar(SnackBar(- content: Text(AppLocalizations.of(context)!.adminPodcastsCouldNotFindFeed),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));+ showOverlayToast(+ context,+ AppLocalizations.of(context)!.adminPodcastsCouldNotFindFeed,+ icon: Icons.search_off_rounded,+ );} catch (_) {if (mounted) setState(() => _lookingUp.remove(itunesId));}@@ -780,10 +785,12 @@ class _PodcastPreviewScreenState extends State<_PodcastPreviewScreen> {setState(() => _adding = false);if (result != null) {widget.onAdded();+ _msg(l2.adminPodcastsAddedToLibrary(_title),+ icon: Icons.check_circle_outline_rounded);Navigator.pop(context);- _msg(l2.adminPodcastsAddedToLibrary(_title));} else {- _msg(l2.adminPodcastsFailedToAdd(_title));+ _msg(l2.adminPodcastsFailedToAdd(_title),+ icon: Icons.error_outline_rounded);}}}@@ -965,8 +972,8 @@ class _PodcastPreviewScreenState extends State<_PodcastPreviewScreen> {child: Icon(Icons.podcasts_rounded, color: cs.primary.withValues(alpha: 0.3), size: 48),);- void _msg(String s) => ScaffoldMessenger.of(context)..clearSnackBars()..showSnackBar(- SnackBar(content: Text(s), behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));+ void _msg(String s, {IconData? icon}) =>+ showOverlayToast(context, s, icon: icon);}@@ -2179,8 +2186,8 @@ class _PodcastDetailScreenState extends State<_PodcastDetailScreen> with SingleT// are date format primitives consistent with how _fmtDate is used in// similar admin/users context. Could be moved to ARB later if needed.- void _msg(String s) => ScaffoldMessenger.of(context)..clearSnackBars()..showSnackBar(- SnackBar(content: Text(s), behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));+ void _msg(String s, {IconData? icon}) =>+ showOverlayToast(context, s, icon: icon);}@@ -2506,22 +2513,30 @@ class _PodcastMatchSheetState extends State<_PodcastMatchSheet> {setState(() => _applying = true);final title = pod['title'] as String? ?? pod['trackName'] as String? ?? pod['collectionName'] as String?;final author = pod['artistName'] as String? ?? pod['author'] as String?;- final result = await api.matchLibraryItem(widget.podcastId, title: title, author: author);+ final result = await api.matchLibraryItem(+ widget.podcastId,+ title: title,+ author: author,+ overrideCover: true,+ overrideDetails: true,+ );if (mounted) {final l = AppLocalizations.of(context)!;setState(() => _applying = false);if (result != null) {widget.onMatched();+ showOverlayToast(+ context,+ l.adminPodcastsPodcastMatched,+ icon: Icons.check_circle_outline_rounded,+ );Navigator.pop(context);- ScaffoldMessenger.of(context)..clearSnackBars()..showSnackBar(SnackBar(- content: Text(l.adminPodcastsPodcastMatched),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));} else {- ScaffoldMessenger.of(context)..clearSnackBars()..showSnackBar(SnackBar(- content: Text(l.adminPodcastsFailedMatch),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));+ showOverlayToast(+ context,+ l.adminPodcastsFailedMatch,+ icon: Icons.error_outline_rounded,+ );}}}diff --git a/lib/screens/admin_screen.dart b/lib/screens/admin_screen.dartindex fe3daefc..9f19fd84 100644--- a/lib/screens/admin_screen.dart+++ b/lib/screens/admin_screen.dart@@ -8,6 +8,7 @@ import '../services/socket_service.dart';import '../widgets/admin_task_indicator.dart';import '../widgets/absorb_page_header.dart';import '../widgets/rmab_config_sheet.dart';+import '../widgets/overlay_toast.dart';import '../l10n/app_localizations.dart';import 'admin_users_screen.dart';import 'admin_upload_screen.dart';@@ -442,9 +443,14 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {if (result.changed || result.disconnected) {await _loadAll();if (!mounted) return;- _msg(result.disconnected- ? l.rmabConfigDisconnectedSnackbar- : l.rmabConfigSavedSnackbar);+ _msg(+ result.disconnected+ ? l.rmabConfigDisconnectedSnackbar+ : l.rmabConfigSavedSnackbar,+ icon: result.disconnected+ ? Icons.link_off_rounded+ : Icons.check_circle_outline_rounded,+ );}}@@ -604,7 +610,8 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {if (mounted) {final l = AppLocalizations.of(context)!;setState(() => _scanningLibraries.remove(id));- _msg(ok ? l.adminScanStarted(name) : l.adminScanFailed(name));+ _msg(ok ? l.adminScanStarted(name) : l.adminScanFailed(name),+ icon: ok ? Icons.refresh_rounded : Icons.error_outline_rounded);}}@@ -624,7 +631,8 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {if (mounted) {final l2 = AppLocalizations.of(context)!;setState(() => _matchingLibraries.remove(id));- _msg(ok ? l2.adminMatchingStarted(name) : l2.adminMatchFailed);+ _msg(ok ? l2.adminMatchingStarted(name) : l2.adminMatchFailed,+ icon: ok ? Icons.manage_search_rounded : Icons.error_outline_rounded);}}@@ -635,7 +643,8 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {if (mounted) {final l = AppLocalizations.of(context)!;setState(() => _creatingBackup = false);- _msg(ok ? l.adminBackupCreated : l.adminBackupFailed);+ _msg(ok ? l.adminBackupCreated : l.adminBackupFailed,+ icon: ok ? Icons.check_circle_outline_rounded : Icons.error_outline_rounded);if (ok) _loadAll();}}@@ -647,12 +656,13 @@ class _AdminScreenState extends State<AdminScreen> with WidgetsBindingObserver {if (mounted) {final l = AppLocalizations.of(context)!;setState(() => _purgingCache = false);- _msg(ok ? l.adminCachePurged : l.adminPurgeCacheFailed);+ _msg(ok ? l.adminCachePurged : l.adminPurgeCacheFailed,+ icon: ok ? Icons.cleaning_services_rounded : Icons.error_outline_rounded);}}- void _msg(String s) => ScaffoldMessenger.of(context)..clearSnackBars()..showSnackBar(- SnackBar(content: Text(s), behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));+ void _msg(String s, {IconData? icon}) =>+ showOverlayToast(context, s, icon: icon);String _fmtB(int b) { if (b < 1024) return '$b B'; if (b < 1048576) return '${(b / 1024).toStringAsFixed(0)} KB';if (b < 1073741824) return '${(b / 1048576).toStringAsFixed(1)} MB'; return '${(b / 1073741824).toStringAsFixed(1)} GB'; }diff --git a/lib/screens/admin_users_screen.dart b/lib/screens/admin_users_screen.dartindex d3676a20..2d6937df 100644--- a/lib/screens/admin_users_screen.dart+++ b/lib/screens/admin_users_screen.dart@@ -10,6 +10,7 @@ import '../providers/library_provider.dart';import '../services/backup_service.dart';import '../widgets/absorb_page_header.dart';import '../widgets/absorb_wave_icon.dart';+import '../widgets/overlay_toast.dart';import '../l10n/app_localizations.dart';import '../utils/duration_format.dart';@@ -835,9 +836,8 @@ class _UserDetailScreenState extends State<_UserDetailScreen> {final token = key?['apiKey'] as String?;if (token == null || token.isEmpty) {if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(content: Text(l.adminSetupFileKeyError)),- );+ showOverlayToast(context, l.adminSetupFileKeyError,+ icon: Icons.error_outline_rounded);}return;}@@ -866,16 +866,14 @@ class _UserDetailScreenState extends State<_UserDetailScreen> {await File(result).writeAsString(jsonStr);}if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(content: Text(l.adminSetupFileSaved(username))),- );+ showOverlayToast(context, l.adminSetupFileSaved(username),+ icon: Icons.check_circle_outline_rounded);}}} catch (e) {if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(content: Text(l.adminSetupFileFailed(e.toString()))),- );+ showOverlayToast(context, l.adminSetupFileFailed(e.toString()),+ icon: Icons.error_outline_rounded);}}}@@ -1071,8 +1069,8 @@ class _UserEditorSheetState extends State<_UserEditorSheet> {final api = context.read<AuthProvider>().apiService; if (api == null) return;final l = AppLocalizations.of(context)!;final username = _usernameCtrl.text.trim();- if (username.isEmpty) { _snk(l.adminUsersUsernameRequired); return; }- if (_isNew && _passwordCtrl.text.isEmpty) { _snk(l.adminUsersPasswordRequired); return; }+ if (username.isEmpty) { _snk(l.adminUsersUsernameRequired, icon: Icons.error_outline_rounded); return; }+ if (_isNew && _passwordCtrl.text.isEmpty) { _snk(l.adminUsersPasswordRequired, icon: Icons.error_outline_rounded); return; }setState(() => _saving = true);final perms = {'download': _canDownload, 'update': _canUpdate, 'delete': _canDelete, 'upload': _canUpload,'accessExplicitContent': _accessExplicit, 'accessAllLibraries': _accessAllLibraries, 'accessAllTags': true};@@ -1091,8 +1089,8 @@ class _UserEditorSheetState extends State<_UserEditorSheet> {if (mounted) {final l2 = AppLocalizations.of(context)!;setState(() => _saving = false);- if (ok) { widget.onSaved(); Navigator.pop(context); _snk(_isNew ? l2.adminUsersUserCreated : l2.adminUsersUserUpdated); }- else { _snk(_isNew ? l2.adminUsersFailedCreate : l2.adminUsersFailedUpdate); }+ if (ok) { widget.onSaved(); _snk(_isNew ? l2.adminUsersUserCreated : l2.adminUsersUserUpdated, icon: Icons.check_circle_outline_rounded); Navigator.pop(context); }+ else { _snk(_isNew ? l2.adminUsersFailedCreate : l2.adminUsersFailedUpdate, icon: Icons.error_outline_rounded); }}}@@ -1112,8 +1110,8 @@ class _UserEditorSheetState extends State<_UserEditorSheet> {if (mounted) {final l2 = AppLocalizations.of(context)!;setState(() => _deleting = false);- if (ok) { widget.onSaved(); Navigator.pop(context); _snk(l2.adminUsersUserDeleted(name)); }- else { _snk(l2.adminUsersFailedDelete); }+ if (ok) { widget.onSaved(); _snk(l2.adminUsersUserDeleted(name), icon: Icons.delete_outline_rounded); Navigator.pop(context); }+ else { _snk(l2.adminUsersFailedDelete, icon: Icons.error_outline_rounded); }}}@@ -1133,13 +1131,13 @@ class _UserEditorSheetState extends State<_UserEditorSheet> {if (mounted) {final l2 = AppLocalizations.of(context)!;setState(() { _unlinking = false; if (ok) _hasOpenIDLink = false; });- if (ok) { widget.onSaved(); _snk(l2.adminUsersOpenIdUnlinked); }- else { _snk(l2.adminUsersFailedUnlinkOpenId); }+ if (ok) { widget.onSaved(); _snk(l2.adminUsersOpenIdUnlinked, icon: Icons.link_off_rounded); }+ else { _snk(l2.adminUsersFailedUnlinkOpenId, icon: Icons.error_outline_rounded); }}}- void _snk(String s) => ScaffoldMessenger.of(context)..clearSnackBars()..showSnackBar(- SnackBar(content: Text(s), behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));+ void _snk(String s, {IconData? icon}) =>+ showOverlayToast(context, s, icon: icon);}// ═══════════════════════════════════════════════════════════════diff --git a/lib/screens/app_shell.dart b/lib/screens/app_shell.dartindex 74d7669a..36a20a91 100644--- a/lib/screens/app_shell.dart+++ b/lib/screens/app_shell.dart@@ -30,6 +30,7 @@ import '../widgets/welcome_sheet.dart';import '../services/review_service.dart';import '../services/update_checker_service.dart';import '../widgets/update_dialog.dart';+import '../widgets/overlay_toast.dart';class AppShell extends StatefulWidget {const AppShell({super.key});@@ -708,18 +709,10 @@ class _AppShellState extends State<AppShell>return;}_lastBackPress = now;- ScaffoldMessenger.of(context).clearSnackBars();- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(- content: Text(- AppLocalizations.of(context)!.appShellPressBackToExit,- ),- duration: const Duration(seconds: 2),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(12),- ),- ),+ showOverlayToast(+ context,+ AppLocalizations.of(context)!.appShellPressBackToExit,+ icon: Icons.exit_to_app_rounded,);return;}diff --git a/lib/screens/bookmarks_screen.dart b/lib/screens/bookmarks_screen.dartindex 49d7e367..d8b75127 100644--- a/lib/screens/bookmarks_screen.dart+++ b/lib/screens/bookmarks_screen.dart@@ -14,6 +14,7 @@ import '../widgets/bookmark_detail_dialog.dart';import '../widgets/card_buttons.dart';import '../services/download_service.dart';import '../widgets/absorb_page_header.dart';+import '../widgets/overlay_toast.dart';import '../l10n/app_localizations.dart';class BookmarksScreen extends StatefulWidget {@@ -234,11 +235,8 @@ class _BookmarksScreenState extends State<BookmarksScreen> {await _load();if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.bookmarksDeletedCount(count)),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ showOverlayToast(context, l.bookmarksDeletedCount(count),+ icon: Icons.delete_outline_rounded);}}@@ -312,10 +310,8 @@ class _BookmarksScreenState extends State<BookmarksScreen> {if (api == null) {if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.bookmarksNotConnected),- behavior: SnackBarBehavior.floating,- ));+ showOverlayToast(context, l.bookmarksNotConnected,+ icon: Icons.cloud_off_rounded);}return;}@@ -323,10 +319,8 @@ class _BookmarksScreenState extends State<BookmarksScreen> {final fullItem = await api.getLibraryItem(itemId);if (fullItem == null) {if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.bookmarksCouldNotLoad),- behavior: SnackBarBehavior.floating,- ));+ showOverlayToast(context, l.bookmarksCouldNotLoad,+ icon: Icons.error_outline_rounded);}return;}@@ -352,7 +346,7 @@ class _BookmarksScreenState extends State<BookmarksScreen> {forceStartTime: true,libraryId: fullItem['libraryId'] as String?,);- if (error != null && mounted) showErrorSnackBar(context, error);+ if (error != null && mounted) showErrorToast(context, error);if (mounted) Navigator.pop(context);AppShell.goToAbsorbingGlobal();diff --git a/lib/screens/car_mode_screen.dart b/lib/screens/car_mode_screen.dartindex 1914cf3c..47623d81 100644--- a/lib/screens/car_mode_screen.dart+++ b/lib/screens/car_mode_screen.dart@@ -11,6 +11,7 @@ import '../providers/library_provider.dart';import '../services/audio_player_service.dart';import '../services/bookmark_service.dart';import '../widgets/card_buttons.dart';+import '../widgets/overlay_toast.dart';import '../l10n/app_localizations.dart';class CarModeScreen extends StatefulWidget {@@ -505,13 +506,8 @@ class _CarModeScreenState extends State<CarModeScreen>positionSeconds: pos,title: chTitle.isNotEmpty ? chTitle : l.carModeBookmarkDefault,);- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(- content: Text(l.carModeBookmarkAdded),- duration: const Duration(seconds: 2),- behavior: SnackBarBehavior.floating,- ),- );+ showOverlayToast(context, l.carModeBookmarkAdded,+ icon: Icons.bookmark_added_rounded);} : null,),],diff --git a/lib/screens/downloads_screen.dart b/lib/screens/downloads_screen.dartindex 8b2aa74a..1ecf3433 100644--- a/lib/screens/downloads_screen.dart+++ b/lib/screens/downloads_screen.dart@@ -6,6 +6,7 @@ import '../providers/library_provider.dart';import '../services/audio_player_service.dart';import '../services/download_service.dart';import '../widgets/absorb_page_header.dart';+import '../widgets/overlay_toast.dart';import '../l10n/app_localizations.dart';class DownloadsScreen extends StatefulWidget {@@ -104,11 +105,8 @@ class _DownloadsScreenState extends State<DownloadsScreen> {await _load();if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.downloadsDeletedCount(count)),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ showOverlayToast(context, l.downloadsDeletedCount(count),+ icon: Icons.delete_outline_rounded);}}@@ -136,11 +134,8 @@ class _DownloadsScreenState extends State<DownloadsScreen> {await DownloadService().deleteDownload(info.itemId);await _load();if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.downloadsRemovedTitle(info.title ?? '')),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ showOverlayToast(context, l.downloadsRemovedTitle(info.title ?? ''),+ icon: Icons.delete_outline_rounded);}}diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dartindex c87b60b3..1e947bdd 100644--- a/lib/screens/home_screen.dart+++ b/lib/screens/home_screen.dart@@ -985,7 +985,7 @@ class _ContinueListeningCardState extends State<_ContinueListeningCard> {libraryId: widget.item['libraryId'] as String?,);if (mounted) {- if (error != null) showErrorSnackBar(context, error);+ if (error != null) showErrorToast(context, error);setState(() => _isLoading = false);}return;@@ -1019,7 +1019,7 @@ class _ContinueListeningCardState extends State<_ContinueListeningCard> {chapters: chapters,libraryId: fullItem['libraryId'] as String?,);- if (error != null && mounted) showErrorSnackBar(context, error);+ if (error != null && mounted) showErrorToast(context, error);// Ensure this book is on the absorbing list (clear any manual remove)if (context.mounted) {diff --git a/lib/screens/login_screen.dart b/lib/screens/login_screen.dartindex be70f66f..09135c0a 100644--- a/lib/screens/login_screen.dart+++ b/lib/screens/login_screen.dart@@ -870,9 +870,8 @@ class _LoginScreenState extends State<LoginScreen>if (!data.containsKey('version')) {if (mounted) {final l = AppLocalizations.of(context)!;- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(content: Text(l.loginInvalidBackupFile)),- );+ showOverlayToast(context, l.loginInvalidBackupFile,+ icon: Icons.error_outline_rounded);}return;}diff --git a/lib/screens/podcast_edit_screen.dart b/lib/screens/podcast_edit_screen.dartindex 1fed47ba..e79e1022 100644--- a/lib/screens/podcast_edit_screen.dart+++ b/lib/screens/podcast_edit_screen.dart@@ -6,6 +6,7 @@ import 'package:cached_network_image/cached_network_image.dart';import '../l10n/app_localizations.dart';import '../providers/auth_provider.dart';import '../providers/library_provider.dart';+import '../widgets/overlay_toast.dart';/// Full-screen editor for a podcast show's info (title, author, description,/// genres, tags, language, release date, explicit flag and cover art).@@ -79,13 +80,7 @@ class _PodcastEditScreenState extends State<PodcastEditScreen> {super.dispose();}- void _msg(String s) => ScaffoldMessenger.of(context)- ..clearSnackBars()- ..showSnackBar(SnackBar(- content: Text(s),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ void _msg(String s) => showOverlayToast(context, s);List<String> _splitList(String text) => text.trim().isEmpty? <String>[]diff --git a/lib/screens/settings_screen.dart b/lib/screens/settings_screen.dartindex 12c71b03..7802bcb8 100644--- a/lib/screens/settings_screen.dart+++ b/lib/screens/settings_screen.dart@@ -1140,11 +1140,8 @@ class _SettingsScreenState extends State<SettingsScreen> {await auth.setLocalServerConfig(enabled: _localServerEnabled, url: _localServerUrl);if (!mounted) return;FocusScope.of(context).unfocus();- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.localServerUrlSetSnackbar),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ showOverlayToast(context, l.localServerUrlSetSnackbar,+ icon: Icons.check_circle_outline_rounded);await auth.checkLocalServer();if (mounted) setState(() {});}@@ -2978,8 +2975,8 @@ class _SettingsScreenState extends State<SettingsScreen> {await AudioPlayer.clearStreamingCache();} catch (_) {}if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(content: Text(l.streamingCacheCleared)));+ showOverlayToast(context, l.streamingCacheCleared,+ icon: Icons.delete_outline_rounded);}},),@@ -3227,12 +3224,8 @@ class _SettingsScreenState extends State<SettingsScreen> {final status = await Permission.notification.status;if (status.isGranted) {if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- duration: const Duration(seconds: 2),- content: Text(l.notificationsAlreadyEnabled),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ showOverlayToast(context, l.notificationsAlreadyEnabled,+ icon: Icons.notifications_active_outlined);}} else {final result = await Permission.notification.request();@@ -3252,12 +3245,8 @@ class _SettingsScreenState extends State<SettingsScreen> {final status = await Permission.ignoreBatteryOptimizations.status;if (status.isGranted) {if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- duration: const Duration(seconds: 2),- content: Text(l.batteryAlreadyUnrestricted),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ showOverlayToast(context, l.batteryAlreadyUnrestricted,+ icon: Icons.battery_saver_outlined);}} else {final result = await Permission.ignoreBatteryOptimizations.request();@@ -3344,11 +3333,13 @@ class _SettingsScreenState extends State<SettingsScreen> {onChanged: _loaded ? (v) {setState(() => _loggingEnabled = v);PlayerSettings.setLoggingEnabled(v);- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(v+ showOverlayToast(+ context,+ v? l.loggingEnabledSnackbar- : l.loggingDisabledSnackbar),- ));+ : l.loggingDisabledSnackbar,+ icon: Icons.article_outlined,+ );} : null,),if (_loggingEnabled && LogService().enabled) ...[@@ -3371,8 +3362,10 @@ class _SettingsScreenState extends State<SettingsScreen> {);} catch (e) {if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(content: Text(l.failedToShare(e.toString()))),+ showOverlayToast(+ context,+ l.failedToShare(e.toString()),+ icon: Icons.error_outline_rounded,);}}@@ -3385,9 +3378,8 @@ class _SettingsScreenState extends State<SettingsScreen> {onTap: () async {await LogService().clearLogs();if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(content: Text(l.logsCleared)),- );+ showOverlayToast(context, l.logsCleared,+ icon: Icons.delete_outline_rounded);}},),@@ -3640,9 +3632,8 @@ class _SettingsScreenState extends State<SettingsScreen> {final info = await UpdateCheckerService.check(force: true, includePreReleases: _includePreReleases);if (!mounted) return;if (info == null || !info.hasUpdate) {- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(content: Text(l.onLatestVersion)),- );+ showOverlayToast(context, l.onLatestVersion,+ icon: Icons.check_circle_outline_rounded);return;}await UpdateDialog.show(context, info);@@ -3837,12 +3828,8 @@ class _SettingsScreenState extends State<SettingsScreen> {Navigator.pop(ctx);await dl.redownloadAllLegacy(api);if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.redownloadStarted),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(12)),- ));+ showOverlayToast(context, l.redownloadStarted,+ icon: Icons.download_rounded);}},child: Text(l.redownload),@@ -3898,12 +3885,8 @@ class _SettingsScreenState extends State<SettingsScreen> {);} catch (e) {if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.cannotWriteToFolder),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(12)),- ));+ showOverlayToast(context, l.cannotWriteToFolder,+ icon: Icons.error_outline_rounded);}return;}@@ -3916,12 +3899,8 @@ class _SettingsScreenState extends State<SettingsScreen> {await FileDownloader().uri.deleteFile(probe);} catch (e) {if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.cannotWriteToFolder),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(12)),- ));+ showOverlayToast(context, l.cannotWriteToFolder,+ icon: Icons.error_outline_rounded);}return;}@@ -3929,12 +3908,8 @@ class _SettingsScreenState extends State<SettingsScreen> {final label = await dl.downloadLocationLabel;if (mounted) {setState(() => _downloadLocationLabel = label);- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.downloadLocationSetTo(label)),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(12)),- ));+ showOverlayToast(context, l.downloadLocationSetTo(label),+ icon: Icons.folder_outlined);}},),@@ -3954,12 +3929,8 @@ class _SettingsScreenState extends State<SettingsScreen> {final label = await dl.downloadLocationLabel;if (mounted) {setState(() => _downloadLocationLabel = label);- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.resetToDefaultStorage),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(12)),- ));+ showOverlayToast(context, l.resetToDefaultStorage,+ icon: Icons.restart_alt_rounded);}},),@@ -4022,20 +3993,19 @@ class _SettingsScreenState extends State<SettingsScreen> {await File(result).writeAsString(jsonStr);}if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(includeAccounts+ showOverlayToast(+ context,+ includeAccounts? l.backupSavedWithAccounts- : l.backupSavedSettingsOnly),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ : l.backupSavedSettingsOnly,+ icon: Icons.check_circle_outline_rounded,+ );}}} catch (e) {if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(content: Text(l.backupFailed(e.toString()))),- );+ showOverlayToast(context, l.backupFailed(e.toString()),+ icon: Icons.error_outline_rounded);}}}@@ -4052,9 +4022,8 @@ class _SettingsScreenState extends State<SettingsScreen> {if (data['version'] == null) {if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(content: Text(l.invalidBackupFile)),- );+ showOverlayToast(context, l.invalidBackupFile,+ icon: Icons.error_outline_rounded);}return;}@@ -4140,17 +4109,13 @@ class _SettingsScreenState extends State<SettingsScreen> {await _loadSettings();if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.settingsRestoredSuccessfully),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ showOverlayToast(context, l.settingsRestoredSuccessfully,+ icon: Icons.check_circle_outline_rounded);}} catch (e) {if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(content: Text(l.restoreFailed(e.toString()))),- );+ showOverlayToast(context, l.restoreFailed(e.toString()),+ icon: Icons.error_outline_rounded);}}}@@ -4338,13 +4303,15 @@ class _SettingsScreenState extends State<SettingsScreen> {_rmabBaseUrl = base;_rmabApiToken = token;});- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(result.disconnected+ showOverlayToast(+ context,+ result.disconnected? l.rmabConfigDisconnectedSnackbar- : l.rmabConfigSavedSnackbar),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ : l.rmabConfigSavedSnackbar,+ icon: result.disconnected+ ? Icons.link_off_rounded+ : Icons.check_circle_outline_rounded,+ );}}@@ -4463,12 +4430,13 @@ class _SettingsScreenState extends State<SettingsScreen> {// Re-pull the active library from the new address.if (ok && wasActive) context.read<LibraryProvider>().refresh();if (context.mounted) setState(() {});- ScaffoldMessenger.of(context)- ..clearSnackBars()- ..showSnackBar(SnackBar(- content: Text(ok ? l.editServerAddressUpdated : l.editServerAddressFailed),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));+ showOverlayToast(+ context,+ ok ? l.editServerAddressUpdated : l.editServerAddressFailed,+ icon: ok+ ? Icons.check_circle_outline_rounded+ : Icons.error_outline_rounded,+ );},child: Text(l.save)),],diff --git a/lib/screens/stats_screen.dart b/lib/screens/stats_screen.dartindex 641883c8..7809cfc4 100644--- a/lib/screens/stats_screen.dart+++ b/lib/screens/stats_screen.dart@@ -1907,10 +1907,8 @@ class SessionDetailsSheetState extends State<SessionDetailsSheet> {if (mounted) {final l = AppLocalizations.of(context)!;setState(() => _jumping = false);- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.bookmarksNotConnected),- behavior: SnackBarBehavior.floating,- ));+ showOverlayToast(context, l.bookmarksNotConnected,+ icon: Icons.error_outline_rounded);}return;}@@ -1928,10 +1926,8 @@ class SessionDetailsSheetState extends State<SessionDetailsSheet> {if (mounted) {final l = AppLocalizations.of(context)!;setState(() => _jumping = false);- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.statsScreenCouldNotLoadItem),- behavior: SnackBarBehavior.floating,- ));+ showOverlayToast(context, l.statsScreenCouldNotLoadItem,+ icon: Icons.error_outline_rounded);}return;}@@ -1956,10 +1952,8 @@ class SessionDetailsSheetState extends State<SessionDetailsSheet> {if (mounted) {final l = AppLocalizations.of(context)!;setState(() => _jumping = false);- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.statsScreenCouldNotFindEpisode),- behavior: SnackBarBehavior.floating,- ));+ showOverlayToast(context, l.statsScreenCouldNotFindEpisode,+ icon: Icons.error_outline_rounded);}return;}diff --git a/lib/services/api_service.dart b/lib/services/api_service.dartindex 87a04917..d27ae59e 100644--- a/lib/services/api_service.dart+++ b/lib/services/api_service.dart@@ -2901,16 +2901,26 @@ class ApiService {return null;}- /// Match a library item with external metadata+ /// Match a library item with external metadata./// POST /api/items/:id/match- Future<Map<String, dynamic>?> matchLibraryItem(String itemId, {String? title, String? author, String? provider}) async {+ ///+ /// When the override flags are omitted, the server applies its configured+ /// "Prefer matched metadata" setting.+ Future<Map<String, dynamic>?> matchLibraryItem(+ String itemId, {+ String? title,+ String? author,+ String? provider,+ bool? overrideCover,+ bool? overrideDetails,+ }) async {try {final body = <String, dynamic>{};if (title != null) body['title'] = title;if (author != null) body['author'] = author;if (provider != null) body['provider'] = provider;- body['overrideCover'] = true;- body['overrideDetails'] = true;+ if (overrideCover != null) body['overrideCover'] = overrideCover;+ if (overrideDetails != null) body['overrideDetails'] = overrideDetails;final r = await _authPost(Uri.parse('$_cleanBaseUrl/api/items/$itemId/match'),body: jsonEncode(body),diff --git a/lib/services/download_service.dart b/lib/services/download_service.dartindex f66aa935..79d8268a 100644--- a/lib/services/download_service.dart+++ b/lib/services/download_service.dart@@ -281,7 +281,26 @@ String _sanitizePath(String name) {class DownloadService extends ChangeNotifier {static final DownloadService _instance = DownloadService._();factory DownloadService() => _instance;- DownloadService._();+ DownloadService._()+ : _initializeOverride = null,+ _cancelTasksOverride = null,+ _deleteTaskRecordOverride = null;++ @visibleForTesting+ DownloadService.forTesting({+ required Future<void> Function() initialize,+ Future<void> Function(List<String>)? cancelTasks,+ Future<void> Function(String)? deleteTaskRecord,+ }) : _initializeOverride = initialize,+ _cancelTasksOverride = cancelTasks,+ _deleteTaskRecordOverride = deleteTaskRecord;++ final Future<void> Function()? _initializeOverride;+ final Future<void> Function(List<String>)? _cancelTasksOverride;+ final Future<void> Function(String)? _deleteTaskRecordOverride;+ Future<void>? _initFuture;+ Future<void>? _iosAudioMigrationFuture;+ bool _initialized = false;/// Set to true (before init) by short-lived background isolates like the/// episode-notification job. Downloads then run as plain background tasks@@ -564,7 +583,28 @@ class DownloadService extends ChangeNotifier {List<DownloadInfo> get queuedDownloads =>_queue.map((q) => _downloads[q.itemId]).whereType<DownloadInfo>().toList();- Future<void> init() async {+ Future<void> init() {+ if (_initialized) return Future.value();+ final inFlight = _initFuture;+ if (inFlight != null) return inFlight;++ final completer = Completer<void>();+ _initFuture = completer.future;+ final initialize = _initializeOverride ?? _initialize;+ Future.sync(initialize).then<void>(+ (_) {+ _initialized = true;+ completer.complete();+ },+ onError: (Object error, StackTrace stackTrace) {+ _initFuture = null;+ completer.completeError(error, stackTrace);+ },+ );+ return completer.future;+ }++ Future<void> _initialize() async {final prefs = await SharedPreferences.getInstance();_customDownloadUri = prefs.getString('custom_download_uri');// Legacy raw-path custom folders can't be converted to a SAF content URI@@ -606,7 +646,8 @@ class DownloadService extends ChangeNotifier {// Runs in background so it doesn't block init() if the user has many// gigabytes of downloaded books to relocate.if (Platform.isIOS) {- unawaited(_migrateIOSAudioToAppGroup());+ _iosAudioMigrationFuture ??= _runIOSAudioMigration();+ unawaited(_iosAudioMigrationFuture!);}// Re-save to persist any metadata extracted from sessionData@@ -915,6 +956,14 @@ class DownloadService extends ChangeNotifier {}}+ Future<void> _runIOSAudioMigration() async {+ try {+ await _migrateIOSAudioToAppGroup();+ } catch (e) {+ debugPrint('[Download] App group audio migration failed: $e');+ }+ }+/// Replace a stale iOS container prefix with the current one./// Paths contain `.../Documents/...` and we split on `/Documents/` then/// rejoin with the current prefix.@@ -1215,6 +1264,16 @@ class DownloadService extends ChangeNotifier {String? episodeId,String? libraryId,}) async {+ try {+ await init().timeout(const Duration(seconds: 8));+ } on TimeoutException catch (e) {+ debugPrint('[Download] Downloader initialization still in progress: $e');+ return 'Downloads are still starting. Please try again in a moment.';+ } catch (e) {+ debugPrint('[Download] Downloader initialization failed: $e');+ return 'Downloads could not start. Please try again.';+ }+if (_activeDownloadIds.contains(itemId)) return null;if (isDownloaded(itemId)) return null;// Already queued — don't duplicate@@ -1231,11 +1290,16 @@ class DownloadService extends ChangeNotifier {final maxConcurrent = await PlayerSettings.getMaxConcurrentDownloads();+ // The checks above ran before settings were loaded, so another tap may+ // have started or queued this item in the meantime.+ if (_activeDownloadIds.contains(itemId) ||+ isDownloaded(itemId) ||+ _queue.any((q) => q.itemId == itemId)) {+ return null;+ }+// If at capacity, queue this oneif (_activeDownloadIds.length >= maxConcurrent) {- // Re-check: the dupe guards at the top ran before the awaits above, so- // two concurrent callers for the same item can both get here.- if (_queue.any((q) => q.itemId == itemId)) return null;debugPrint('[Download] Queued "$title" ($itemId); slots ${_activeDownloadIds.length}/$maxConcurrent full, ${_queue.length} waiting');_queue.add(_QueuedDownload(api: api,@@ -1287,6 +1351,8 @@ class DownloadService extends ChangeNotifier {String? episodeId,String? libraryId,}) async {+ await init();+if (_activeDownloadIds.contains(itemId)) return;if (isDownloaded(itemId)) return;if (_queue.any((q) => q.itemId == itemId)) return;@@ -1388,9 +1454,8 @@ class DownloadService extends ChangeNotifier {? itemId.substring(0, itemId.length - episodeId.length - 1): itemId;- // The playback session is only for METADATA (durations/chapters) needed by- // offline seeking. We do NOT download from its session-scoped contentUrls- // (they die when the session closes); we use durable /file/:ino URLs.+ // The forced direct-play session provides both offline metadata and the+ // authoritative /file/:ino path for every included track.final sessionData = episodeId != null? await api.startEpisodePlaybackSession(apiItemId, episodeId): await api.startPlaybackSession(apiItemId);@@ -1401,7 +1466,7 @@ class DownloadService extends ChangeNotifier {throw Exception('No audio tracks');}- final files = await _resolveDurableFiles(api, apiItemId, episodeId, audioTracks);+ final files = _resolveDurableFiles(api, apiItemId, audioTracks);// Pull the companion ebook into the offline cache too, so a downloaded// book is fully readable offline. Fire-and-forget - never blocks or fails@@ -1549,41 +1614,48 @@ class DownloadService extends ChangeNotifier {}}- /// Map each playback track to a durable, session-independent file URL using- /// the library item's audioFiles[].ino. Index-aligned with [audioTracks].- Future<List<({String url, String filename})>> _resolveDurableFiles(- ApiService api, String apiItemId, String? episodeId, List<dynamic> audioTracks) async {- final item = await api.getLibraryItem(apiItemId);- if (item == null) throw Exception('Failed to load item details');- final media = item['media'] as Map<String, dynamic>? ?? {};-- List<Map<String, dynamic>> audioFiles;- if (episodeId != null) {- final episodes = (media['episodes'] as List<dynamic>?) ?? const [];- Map<String, dynamic>? ep;- for (final e in episodes) {- if (e is Map<String, dynamic> && e['id'] == episodeId) { ep = e; break; }- }- final af = ep?['audioFile'] as Map<String, dynamic>?;- audioFiles = af != null ? [af] : const [];- } else {- audioFiles = ((media['audioFiles'] as List<dynamic>?) ?? const [])- .whereType<Map<String, dynamic>>()- .toList()- ..sort((a, b) => ((a['index'] as num?) ?? 0).compareTo((b['index'] as num?) ?? 0));- }-- if (audioFiles.length < audioTracks.length) {- throw Exception(- 'Audio file mismatch (${audioFiles.length} files vs ${audioTracks.length} tracks)');- }-+ /// Rebuild forced-direct-play track URLs against the current server/token so+ /// native tasks can outlive the playback session that supplied the metadata.+ List<({String url, String filename})> _resolveDurableFiles(+ ApiService api, String apiItemId, List<dynamic> audioTracks) {final out = <({String url, String filename})>[];for (int i = 0; i < audioTracks.length; i++) {final track = audioTracks[i] as Map<String, dynamic>;- final ino = audioFiles[i]['ino']?.toString();- if (ino == null || ino.isEmpty) {- throw Exception('Missing file inode for track ${i + 1}');+ final contentUrl = track['contentUrl'] as String? ?? '';+ final uri = Uri.tryParse(contentUrl);+ if (uri == null) {+ throw Exception('Invalid direct file URL for track ${i + 1}');+ }+ if (uri.hasScheme || uri.hasAuthority) {+ final serverUri = Uri.parse(api.cleanBaseUrl);+ if (!uri.hasScheme ||+ !uri.hasAuthority ||+ (uri.scheme != 'http' && uri.scheme != 'https') ||+ uri.origin != serverUri.origin) {+ throw Exception('Track ${i + 1} points to a different server');+ }+ }+ final segments = uri.pathSegments;+ String? ino;+ for (int segment = 0; segment + 4 < segments.length; segment++) {+ if (segments[segment] != 'api' ||+ segments[segment + 1] != 'items' ||+ segments[segment + 3] != 'file' ||+ segment + 5 != segments.length) {+ continue;+ }+ if (segments[segment + 2] != apiItemId) {+ throw Exception('Track ${i + 1} belongs to a different library item');+ }+ ino = segments[segment + 4];+ break;+ }+ if (ino == null ||+ ino.isEmpty ||+ ino.contains('/') ||+ ino.contains('?') ||+ ino.contains('#')) {+ throw Exception('Missing direct file URL for track ${i + 1}');}out.add((url: api.buildFileUrl(apiItemId, ino), filename: _trackFileName(track, i)));}@@ -1669,25 +1741,47 @@ class DownloadService extends ChangeNotifier {_emitBookProgress(itemId, p);}} else if (update is TaskStatusUpdate) {- p.trackStatus[i] = update.status;- debugPrint('[Download] task $itemId #$i status=${update.status.name}'- '${update.exception != null ? ' ex=${update.exception}' : ''}'- '${update.responseStatusCode != null ? ' code=${update.responseStatusCode}' : ''}');- if (update.status == TaskStatus.complete) p.trackProgress[i] = 1.0;-- // A hard failure aborts the whole book: cancel the remaining siblings so- // it doesn't hang waiting on tracks that will never finish.- if ((update.status == TaskStatus.failed || update.status == TaskStatus.notFound) &&- !p.cancelled && !p.failing) {- p.failing = true;- p.failException = update.exception;- p.failCode = update.responseStatusCode;- unawaited(_cancelSiblings(itemId, p));- }- _checkBookTerminal(itemId, p);+ unawaited(+ _handleTaskStatus(+ itemId: itemId,+ trackIndex: i,+ status: update.status,+ exception: update.exception,+ responseCode: update.responseStatusCode,+ ),+ );}}+ Future<void> _handleTaskStatus({+ required String itemId,+ required int trackIndex,+ required TaskStatus status,+ TaskException? exception,+ int? responseCode,+ }) async {+ final p = _pending[itemId];+ if (p == null) return;+ p.lastUpdate = DateTime.now();+ p.trackStatus[trackIndex] = status;+ debugPrint(+ '[Download] task $itemId #$trackIndex status=${status.name}'+ '${exception != null ? ' ex=$exception' : ''}'+ '${responseCode != null ? ' code=$responseCode' : ''}',+ );+ if (status == TaskStatus.complete) p.trackProgress[trackIndex] = 1.0;++ // A hard failure aborts the whole book so it does not wait forever for+ // sibling tracks that will never finish on their own.+ if ((status == TaskStatus.failed || status == TaskStatus.notFound) && !p.cancelled && !p.failing) {+ p.failing = true;+ p.failException = exception;+ p.failCode = responseCode;+ unawaited(_cancelSiblings(itemId, p));+ }+ await _checkBookTerminal(itemId, p);+ }+void _emitBookProgress(String itemId, _PendingBook p) {final now = DateTime.now();if (now.difference(p.lastUi).inMilliseconds < 250) return;@@ -1706,22 +1800,95 @@ class DownloadService extends ChangeNotifier {}/// Once every track of a book is terminal, route to success / fail / cancel.- void _checkBookTerminal(String itemId, _PendingBook p) {+ Future<void> _checkBookTerminal(String itemId, _PendingBook p) async {if (p.finalizing) return;for (int i = 0; i < p.trackCount; i++) {final s = p.trackStatus[i];if (s == null || !_terminal.contains(s)) return;}- p.finalizing = true; // synchronous guard against a burst of terminal updatesif (p.trackStatus.values.every((s) => s == TaskStatus.complete)) {- unawaited(_finalizeSuccess(itemId));+ p.finalizing = true;+ await _finalizeSuccess(itemId);} else if (p.failing) {- unawaited(_failBook(itemId, taskException: p.failException, responseCode: p.failCode));+ await _failBook(+ itemId,+ taskException: p.failException,+ responseCode: p.failCode,+ );} else {- unawaited(_handleCanceled(itemId));+ p.finalizing = true;+ await _handleCanceled(itemId);}}+ @visibleForTesting+ Future<void> debugSeedPendingDownload({+ required String itemId,+ required int trackCount,+ }) async {+ final bookDir = '${Directory.systemTemp.path}/absorb_download_service_test/$itemId';+ _pending[itemId] = _PendingBook(+ itemId: itemId,+ apiItemId: itemId,+ title: 'Test download',+ bookDir: bookDir,+ trackCount: trackCount,+ expectedPaths: List.generate(+ trackCount,+ (index) => '$bookDir/$index.mp3',+ ),+ );+ _activeDownloadIds.add(itemId);+ _downloads[itemId] = DownloadInfo(+ itemId: itemId,+ status: DownloadStatus.downloading,+ title: 'Test download',+ );+ await _persistPending();+ }++ @visibleForTesting+ Future<void> debugHandleTaskStatus({+ required String itemId,+ required int trackIndex,+ required TaskStatus status,+ int? responseCode,+ }) =>+ _handleTaskStatus(+ itemId: itemId,+ trackIndex: trackIndex,+ status: status,+ responseCode: responseCode,+ );++ @visibleForTesting+ List<({String url, String filename})> debugResolveDurableFiles({+ required ApiService api,+ required String itemId,+ required List<dynamic> audioTracks,+ }) =>+ _resolveDurableFiles(api, itemId, audioTracks);++ @visibleForTesting+ Future<void> debugReset() async {+ _reconcileTimer?.cancel();+ _reconcileTimer = null;+ await _updatesSub?.cancel();+ _updatesSub = null;+ _downloads.clear();+ _activeDownloadIds.clear();+ _cancelledIds.clear();+ _pending.clear();+ _queue.clear();+ _downloaderConfigured = false;+ _initFuture = null;+ _iosAudioMigrationFuture = null;+ _initialized = false;+ backgroundIsolateMode = false;+ final prefs = await SharedPreferences.getInstance();+ await prefs.remove('pending_downloads');+ }+/// Move a completed book's internal files into the SAF folder [treeUri] under/// [subfolder] (e.g. "Author/Title"), via the native DocumentFile helper./// Returns the created folder URI and the per-file content URIs, or null if@@ -1962,7 +2129,11 @@ class DownloadService extends ChangeNotifier {}}- Future<void> _cancelSiblings(String itemId, _PendingBook p, {bool force = false}) async {+ Future<void> _cancelSiblings(+ String itemId,+ _PendingBook p, {+ bool force = false,+ }) async {final ids = <String>[];for (int i = 0; i < p.trackCount; i++) {final s = p.trackStatus[i];@@ -1970,7 +2141,12 @@ class DownloadService extends ChangeNotifier {}if (ids.isNotEmpty) {try {- await FileDownloader().cancelTasksWithIds(ids);+ final cancelTasks = _cancelTasksOverride;+ if (cancelTasks != null) {+ await cancelTasks(ids);+ } else {+ await FileDownloader().cancelTasksWithIds(ids);+ }} catch (_) {}}}@@ -2002,7 +2178,13 @@ class DownloadService extends ChangeNotifier {Future<void> _deleteDbRecords(String itemId, int trackCount) async {for (int i = 0; i < trackCount; i++) {try {- await FileDownloader().database.deleteRecordWithId(_taskId(itemId, i));+ final taskId = _taskId(itemId, i);+ final deleteTaskRecord = _deleteTaskRecordOverride;+ if (deleteTaskRecord != null) {+ await deleteTaskRecord(taskId);+ } else {+ await FileDownloader().database.deleteRecordWithId(taskId);+ }} catch (_) {}}}diff --git a/lib/widgets/absorbing_card.dart b/lib/widgets/absorbing_card.dartindex 9f5936fd..ee5f2989 100644--- a/lib/widgets/absorbing_card.dart+++ b/lib/widgets/absorbing_card.dart@@ -21,6 +21,7 @@ import 'card_buttons.dart';import '../services/chromecast_service.dart';import 'expanded_card.dart';import '../main.dart' show colorSourceNotifier, useColorEverywhereNotifier, manualSeedNotifier, manualColorScheme;+import 'stable_cached_network_image.dart';class AbsorbingCard extends StatefulWidget {final Map<String, dynamic> item;@@ -43,6 +44,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveClireturn _rawCoverScheme;}ImageProvider? _coverProvider; // cached for re-deriving on theme change+ String? _coverProviderIdentity;bool _isStarting = false;List<dynamic>? _fetchedChapters;Map<String, dynamic>? _fetchedEbookFile;@@ -54,7 +56,8 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCliStreamSubscription<Duration>? _chapterTrackSub;int _lastChapterIdx = -1;ui.Image? _blurredCover; // Precached blurred background- String? _blurredCoverUrl; // URL the blur was built from+ String? _blurredCoverIdentity;+ String? _pendingBlurIdentity;List<String> _buttonOrder = PlayerSettings.defaultButtonOrder;int _buttonVisibleCount = PlayerSettings.defaultButtonVisibleCount;bool _iconsOnly = false;@@ -145,7 +148,42 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveClireturn lib.getCoverUrl(_itemId, width: 800);}- bool get _isLocalCover => _coverUrl != null && _coverUrl!.startsWith('/');+ int? _coverUpdatedAt(LibraryProvider lib) {+ final key = widget.item['_absorbingKey'] as String? ?? _itemId;+ final cached = lib.absorbingItemCache[key];+ final candidates = <Object?>[+ widget.item['updatedAt'],+ cached?['updatedAt'],+ lib.itemUpdatedAt(_itemId),+ ];++ int? newest;+ for (final candidate in candidates) {+ final timestamp = switch (candidate) {+ num value => value.toInt(),+ String value => int.tryParse(value),+ _ => null,+ };+ if (timestamp != null && (newest == null || timestamp > newest)) {+ newest = timestamp;+ }+ }+ return newest;+ }++ String? _coverIdentity(String? coverUrl, LibraryProvider lib) {+ if (coverUrl == null) return null;+ if (coverUrl.startsWith('/')) return coverUrl;+ return stableCoverCacheKey(+ coverUrl,+ updatedAt: _coverUpdatedAt(lib),+ );+ }++ String? _currentCoverIdentity() {+ final lib = context.read<LibraryProvider>();+ return _coverIdentity(lib.getCoverUrl(_itemId, width: 800), lib);+ }@overridevoid initState() {@@ -386,8 +424,11 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli_rawCoverScheme = null;_coverBrightness = null;_coverProvider = null;+ _coverProviderIdentity = null;_blurredCover?.dispose();_blurredCover = null;+ _blurredCoverIdentity = null;+ _pendingBlurIdentity = null;_fetchedChapters = null;_fetchedEbookFile = null;_lastChapterIdx = -1;@@ -415,42 +456,68 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveClisuper.dispose();}- void _onCoverLoaded(ImageProvider provider) {+ void _onCoverLoaded(ImageProvider provider, String coverIdentity) {+ if (_currentCoverIdentity() != coverIdentity) return;+ if (_coverProviderIdentity != coverIdentity) {+ _rawCoverScheme = null;+ _coverBrightness = null;+ }_coverProvider = provider;+ _coverProviderIdentity = coverIdentity;_rederiveCoverScheme();// Precache the blurred version of the cover, but only when the blurred// background is actually in use (skip the work for gradient / off modes).- if (_cardBackground == 'blurred' && _blurredCover == null) {- _blurredCoverUrl = _coverUrl;- _precacheBlur(provider);+ if (_cardBackground == 'blurred' &&+ _blurredCoverIdentity != coverIdentity &&+ _pendingBlurIdentity != coverIdentity) {+ _pendingBlurIdentity = coverIdentity;+ _precacheBlur(provider, coverIdentity);}}/// In gradient/off mode the cover image isn't painted, so resolve it directly/// to keep the extracted [_coverScheme] (accent + gradient colors) available.- void _ensureCoverScheme() {- if (_coverProvider != null || _coverUrl == null) return;- final headers = context.read<LibraryProvider>().mediaHeaders;+ void _ensureCoverScheme(+ String? coverUrl,+ String? coverIdentity,+ LibraryProvider lib,+ ) {+ if (coverUrl == null || coverIdentity == null) return;+ if (_coverProvider != null && _coverProviderIdentity == coverIdentity) {+ return;+ }+ final headers = lib.mediaHeaders;final ImageProvider provider;- if (_isLocalCover) {- provider = FileImage(File(_coverUrl!));+ if (coverUrl.startsWith('/')) {+ provider = FileImage(File(coverUrl));} else {- provider = CachedNetworkImageProvider(_coverUrl!, headers: headers);+ provider = CachedNetworkImageProvider(+ coverUrl,+ headers: headers,+ cacheKey: coverIdentity,+ );}- _onCoverLoaded(provider);+ _onCoverLoaded(provider, coverIdentity);}void _rederiveCoverScheme() {final provider = _coverProvider;- if (provider == null) return;+ final coverIdentity = _coverProviderIdentity;+ if (provider == null || coverIdentity == null) return;final brightness = Theme.of(context).brightness;if (_rawCoverScheme != null && _coverBrightness == brightness) return;_coverBrightness = brightness;ColorScheme.fromImageProvider(provider: provider, brightness: brightness).then((s) {- if (mounted) {+ if (mounted &&+ _coverProviderIdentity == coverIdentity &&+ _coverBrightness == brightness) {WidgetsBinding.instance.addPostFrameCallback((_) {- if (mounted) setState(() => _rawCoverScheme = s);+ if (mounted &&+ _coverProviderIdentity == coverIdentity &&+ _coverBrightness == brightness) {+ setState(() => _rawCoverScheme = s);+ }});}})@@ -458,7 +525,10 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCli}/// Resolve the image, render it blurred to an offscreen canvas, cache the result.- Future<void> _precacheBlur(ImageProvider provider) async {+ Future<void> _precacheBlur(+ ImageProvider provider,+ String coverIdentity,+ ) async {try {final completer = Completer<ui.Image>();final stream = provider.resolve(ImageConfiguration.empty);@@ -492,13 +562,22 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveClifinal blurred = await picture.toImage(targetWidth, targetHeight);picture.dispose();- if (mounted) {- setState(() => _blurredCover = blurred);+ if (mounted && _currentCoverIdentity() == coverIdentity) {+ final previous = _blurredCover;+ setState(() {+ _blurredCover = blurred;+ _blurredCoverIdentity = coverIdentity;+ });+ previous?.dispose();} else {blurred.dispose();}} catch (_) {// Fallback: card will show without blurred background, which is fine+ } finally {+ if (_pendingBlurIdentity == coverIdentity) {+ _pendingBlurIdentity = null;+ }}}@@ -511,6 +590,9 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveClifinal l = AppLocalizations.of(context)!;final lib = context.watch<LibraryProvider>();+ final coverUrl = lib.getCoverUrl(_itemId, width: 800);+ final coverIdentity = _coverIdentity(coverUrl, lib);+ final isLocalCover = coverUrl?.startsWith('/') ?? false;_maybeRefetchOnServerChange(lib);// For podcast episodes, look up progress by compound key (itemId-episodeId)final progress = (_episodeId != null)@@ -548,13 +630,10 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveClidebugPrint('[Card] $sig');}- // Invalidate blurred background when cover URL changes (e.g. after server update)- if (_blurredCover != null && _blurredCoverUrl != _coverUrl) {- _blurredCover?.dispose();- _blurredCover = null;- }// In gradient/off mode the cover image isn't painted, so derive its scheme separately.- if (_cardBackground != 'blurred') _ensureCoverScheme();+ if (_cardBackground != 'blurred') {+ _ensureCoverScheme(coverUrl, coverIdentity, lib);+ }final tt = Theme.of(context).textTheme;final mediaHeaders = lib.mediaHeaders;@@ -599,25 +678,27 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveCliheight: double.infinity,),)- else if (_coverUrl != null)+ else if (coverUrl != null && coverIdentity != null)// Fallback while blur is being computed: show unblurred cover dimmedRepaintBoundary(- child: _isLocalCover+ child: isLocalCover? Builder(builder: (_) {- final provider = FileImage(File(_coverUrl!));- _onCoverLoaded(provider);+ final provider = FileImage(File(coverUrl));+ _onCoverLoaded(provider, coverIdentity);return Opacity(opacity: 0.3,- child: Image.file(File(_coverUrl!), fit: BoxFit.cover,+ child: Image.file(File(coverUrl), fit: BoxFit.cover,+ gaplessPlayback: true,errorBuilder: (_, __, ___) => Container(color: isDark ? Colors.black : Colors.white)),);})- : CachedNetworkImage(- imageUrl: _coverUrl!,+ : StableCachedNetworkImage(+ imageUrl: coverUrl,+ cacheKey: coverIdentity,fit: BoxFit.cover,httpHeaders: mediaHeaders,imageBuilder: (_, provider) {- _onCoverLoaded(provider);+ _onCoverLoaded(provider, coverIdentity);return Opacity(opacity: 0.3,child: Image(image: provider, fit: BoxFit.cover),@@ -814,17 +895,24 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveClifit: StackFit.expand,children: [// Cover image- _coverUrl != null- ? _isLocalCover- ? BlurPaddedCover(blurChild: Image.file(File(_coverUrl!), fit: BoxFit.cover,+ coverUrl != null && coverIdentity != null+ ? isLocalCover+ ? BlurPaddedCover(blurChild: Image.file(File(coverUrl), fit: BoxFit.cover,+ gaplessPlayback: true,errorBuilder: (_, __, ___) => const SizedBox.shrink()),- enabled: !_rectangleCovers, child: Image.file(File(_coverUrl!), fit: _rectangleCovers ? BoxFit.cover : BoxFit.contain,+ enabled: !_rectangleCovers, child: Image.file(File(coverUrl), fit: _rectangleCovers ? BoxFit.cover : BoxFit.contain,+ gaplessPlayback: true,errorBuilder: (_, __, ___) => CoverPlaceholder(title: _title, author: _author)))- : BlurPaddedCover(blurChild: CachedNetworkImage(imageUrl: _coverUrl!, fit: BoxFit.cover,+ : BlurPaddedCover(blurChild: StableCachedNetworkImage(imageUrl: coverUrl, cacheKey: coverIdentity, fit: BoxFit.cover,httpHeaders: mediaHeaders,errorWidget: (_, __, ___) => const SizedBox.shrink()),- enabled: !_rectangleCovers, child: CachedNetworkImage(imageUrl: _coverUrl!, fit: _rectangleCovers ? BoxFit.cover : BoxFit.contain,+ enabled: !_rectangleCovers, child: StableCachedNetworkImage(imageUrl: coverUrl, cacheKey: coverIdentity,+ fit: _rectangleCovers ? BoxFit.cover : BoxFit.contain,httpHeaders: mediaHeaders,+ imageBuilder: (_, provider) {+ _onCoverLoaded(provider, coverIdentity);+ return Image(image: provider, fit: _rectangleCovers ? BoxFit.cover : BoxFit.contain);+ },placeholder: (_, __) => CoverPlaceholder(title: _title, author: _author),errorWidget: (_, __, ___) => CoverPlaceholder(title: _title, author: _author))): CoverPlaceholder(title: _title, author: _author),@@ -1146,7 +1234,7 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveClilibraryId: _resolveLibraryId(),);if (mounted) {- if (error != null) showErrorSnackBar(context, error);+ if (error != null) showErrorToast(context, error);setState(() => _isStarting = false);}}@@ -1206,4 +1294,3 @@ class AbsorbingCardState extends State<AbsorbingCard> with AutomaticKeepAliveClivoid _showMoreMenu(BuildContext context, Color accent, TextTheme tt) => _makeActions().showMoreMenu(accent, tt);}-diff --git a/lib/widgets/book_detail_sheet.dart b/lib/widgets/book_detail_sheet.dartindex e31c4959..1ecd91b4 100644--- a/lib/widgets/book_detail_sheet.dart+++ b/lib/widgets/book_detail_sheet.dart@@ -1630,8 +1630,11 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {final ino = ebookFile['ino'] as String?;if (ino == null) {if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(content: Text(l.noEbookFileFound)));+ showOverlayToast(+ context,+ l.noEbookFileFound,+ icon: Icons.error_outline_rounded,+ );}return;}@@ -1673,8 +1676,11 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {if (response.statusCode != 200) {if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(content: Text(l.failedToDownloadEbook(response.statusCode))));+ showOverlayToast(+ context,+ l.failedToDownloadEbook(response.statusCode),+ icon: Icons.error_outline_rounded,+ );}return;}@@ -1685,8 +1691,11 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {if (ct.contains('text/html')) {debugPrint('[Ebook] Server returned HTML instead of ebook file (content-type: $ct)');if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(content: Text(l.serverReturnedErrorPage)));+ showOverlayToast(+ context,+ l.serverReturnedErrorPage,+ icon: Icons.error_outline_rounded,+ );}return;}@@ -1722,17 +1731,20 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {if (mounted) setState(() => _ebookSaved = true);if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(content: Text(l.ebookSaved('$safeTitle$ext')),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- duration: const Duration(seconds: 3)));+ showOverlayToast(+ context,+ l.ebookSaved('$safeTitle$ext'),+ icon: Icons.download_done_rounded,+ );}} catch (e) {debugPrint('[Ebook] Save error: $e');if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(content: Text(l.errorSavingEbook(e.toString()))));+ showOverlayToast(+ context,+ l.errorSavingEbook(e.toString()),+ icon: Icons.error_outline_rounded,+ );}} finally {if (mounted) setState(() => _ebookSaving = false);@@ -1852,7 +1864,7 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {final error = await player.playItem(api: api, itemId: widget.itemId, title: title, author: author, coverUrl: coverUrl, totalDuration: duration, chapters: chapters, libraryId: _item?['libraryId'] as String?);if (error != null) {final ctx = rootNavigatorKey.currentContext;- if (ctx != null) showErrorSnackBar(ctx, error);+ if (ctx != null) showErrorToast(ctx, error);}lib?.refreshLocalProgress();lib?.refresh();@@ -2052,12 +2064,11 @@ class _BookDetailSheetContentState extends State<_BookDetailSheetContent> {if (context.mounted) {// Repaint the library so the grid/card drop the override cover too.context.read<LibraryProvider>().notifyCoverOverridesChanged();- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.localMetadataCleared),- behavior: SnackBarBehavior.floating,- duration: const Duration(seconds: 2),- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ showOverlayToast(+ context,+ l.localMetadataCleared,+ icon: Icons.delete_outline_rounded,+ );}}}@@ -2103,11 +2114,11 @@ class _FullCoverViewerState extends State<_FullCoverViewer> {} catch (e) {if (mounted) {final l = AppLocalizations.of(context)!;- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.failedToSaveError(e.toString())),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ showOverlayToast(+ context,+ l.failedToSaveError(e.toString()),+ icon: Icons.error_outline_rounded,+ );}} finally {if (mounted) setState(() => _saving = false);diff --git a/lib/widgets/bookmark_detail_dialog.dart b/lib/widgets/bookmark_detail_dialog.dartindex 8774e69f..6068aef4 100644--- a/lib/widgets/bookmark_detail_dialog.dart+++ b/lib/widgets/bookmark_detail_dialog.dart@@ -10,6 +10,7 @@ import '../services/bookmark_service.dart';import '../services/bookmark_preview_player.dart';import '../services/download_service.dart';import 'clip_editor_sheet.dart';+import 'overlay_toast.dart';/// Result of [BookmarkDetailSheet]. [action] is 'jump' (caller should seek/// there) or 'saved' (stay put, refresh). [position] is the possibly-nudged@@ -91,10 +92,8 @@ class _BookmarkDetailSheetState extends State<BookmarkDetailSheet> {debugPrint('[BookmarkPreview] toggle failed: $e');if (!mounted) return;final l = AppLocalizations.of(context)!;- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.bookmarkPreviewFailed),- behavior: SnackBarBehavior.floating,- ));+ showOverlayToast(context, l.bookmarkPreviewFailed,+ icon: Icons.error_outline_rounded);}}diff --git a/lib/widgets/card_buttons.dart b/lib/widgets/card_buttons.dartindex cdcb39a7..13efbf0b 100644--- a/lib/widgets/card_buttons.dart+++ b/lib/widgets/card_buttons.dart@@ -71,17 +71,12 @@ class _PressableState extends State<Pressable> {/// Show a toast when the user taps a button that requires active playback.void showInactiveToast(BuildContext context) {final l = AppLocalizations.of(context)!;- ScaffoldMessenger.of(context)- ..clearSnackBars()- ..showSnackBar(SnackBar(- content: Text(l.startPlayingSomethingFirst),- duration: const Duration(seconds: 2),- behavior: SnackBarBehavior.floating,- ));+ showOverlayToast(context, l.startPlayingSomethingFirst,+ icon: Icons.play_disabled_rounded);}/// Show an error message to the user.-void showErrorSnackBar(BuildContext context, String message) {+void showErrorToast(BuildContext context, String message) {showOverlayToast(context, message, icon: Icons.error_outline_rounded);}@@ -495,8 +490,8 @@ class _CardBookmarkButtonInlineState extends State<CardBookmarkButtonInline> {await BookmarkService().addBookmark(itemId: widget.itemId, positionSeconds: pos, title: chTitle ?? l.bookmark, api: AudioPlayerService().currentApi);_loadCount();if (ctx.mounted) {- ScaffoldMessenger.of(ctx).showSnackBar(SnackBar(duration: const Duration(seconds: 2), content: Text(l.bookmarkAdded), behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));+ showOverlayToast(ctx, l.bookmarkAdded,+ icon: Icons.bookmark_added_rounded);}}@@ -2345,11 +2340,10 @@ class _PlaybackHistorySheetBodyState extends State<_PlaybackHistoryBody>Duration(seconds: event.positionSeconds.round()),);Navigator.pop(futureContext);- ScaffoldMessenger.of(widget.parentCtx).showSnackBar(- SnackBar(- duration: const Duration(seconds: 3),- content: Text(l.jumpedToPosition(positionLabel)),- ),+ showOverlayToast(+ widget.parentCtx,+ l.jumpedToPosition(positionLabel),+ icon: Icons.my_location_rounded,);}: null,diff --git a/lib/widgets/clip_editor_sheet.dart b/lib/widgets/clip_editor_sheet.dartindex 229c6b9c..06aa884f 100644--- a/lib/widgets/clip_editor_sheet.dart+++ b/lib/widgets/clip_editor_sheet.dart@@ -8,6 +8,7 @@ import '../l10n/app_localizations.dart';import '../services/api_service.dart';import '../services/clip_editor_controller.dart';import '../services/clip_export_service.dart';+import 'overlay_toast.dart';/// Play-and-mark clip editor. Opened from the bookmark sheet's "Export clip"./// Plays a navigable window around the bookmark; the user marks in/out by ear@@ -80,7 +81,6 @@ class _ClipEditorSheetState extends State<ClipEditorSheet> {Future<void> _save() async {final l = AppLocalizations.of(context)!;- final messenger = ScaffoldMessenger.of(context);final navigator = Navigator.of(context);setState(() => _saving = true);try {@@ -105,11 +105,14 @@ class _ClipEditorSheetState extends State<ClipEditorSheet> {setState(() => _saving = false);return; // user cancelled the save dialog}+ // Insert into the root overlay while this sheet's context is still+ // mounted, then close the sheet. The overlay entry survives the pop.+ showOverlayToast(+ context,+ res.clamped ? l.clipExportClamped : l.clipExportSaved(name),+ icon: Icons.content_cut_rounded,+ );navigator.pop();- messenger.showSnackBar(SnackBar(- content: Text(res.clamped ? l.clipExportClamped : l.clipExportSaved(name)),- behavior: SnackBarBehavior.floating,- ));} catch (e) {debugPrint('[ClipEditor] save failed: $e');if (!mounted) return;diff --git a/lib/widgets/collection_detail_sheet.dart b/lib/widgets/collection_detail_sheet.dartindex 327ba018..f354f305 100644--- a/lib/widgets/collection_detail_sheet.dart+++ b/lib/widgets/collection_detail_sheet.dart@@ -14,6 +14,7 @@ import '../services/audio_player_service.dart';import '../services/download_service.dart';import 'add_books_search_sheet.dart';import 'book_detail_sheet.dart';+import 'editable_sheet_item.dart';import 'stackable_sheet.dart';import '../screens/app_shell.dart';@@ -45,9 +46,11 @@ class CollectionDetailSheet extends StatefulWidget {}class _CollectionDetailSheetState extends State<CollectionDetailSheet> {- bool _reordering = false;+ bool _editing = false;bool _gridView = false;- List<Map<String, dynamic>>? _reorderItems;+ List<Map<String, dynamic>>? _editItems;+ final Set<String> _selectedItemIds = {};+ bool _isRemovingSelected = false;Future<void> _removeItem(LibraryProvider lib, String libraryItemId) async {await lib.removeFromCollection(widget.collectionId, libraryItemId);@@ -89,7 +92,7 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {);}- Widget _headerTextButton(ColorScheme cs, String label, VoidCallback onTap,+ Widget _headerTextButton(ColorScheme cs, String label, VoidCallback? onTap,{required Color color}) {return TextButton(onPressed: onTap,@@ -137,17 +140,18 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {}}- void _startReorder(List<dynamic> books) {+ void _startEdit(List<dynamic> books) {setState(() {- _reordering = true;- _reorderItems = books+ _editing = true;+ _editItems = books.map((b) => Map<String, dynamic>.from(b as Map)).toList();+ _selectedItemIds.clear();});}- void _saveReorder(LibraryProvider lib) {- final items = _reorderItems;+ void _saveEdit(LibraryProvider lib) {+ final items = _editItems;if (items != null) {final bookIds = items.map((b) => b['id'] as String? ?? '')@@ -160,13 +164,40 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {Navigator.pop(context);}- void _cancelReorder() {+ void _cancelEdit() {setState(() {- _reordering = false;- _reorderItems = null;+ _editing = false;+ _editItems = null;+ _selectedItemIds.clear();});}+ Future<void> _removeSelected(LibraryProvider lib) async {+ if (_selectedItemIds.isEmpty) return;+ setState(() => _isRemovingSelected = true);++ final removedIds = <String>{};+ for (final itemId in List<String>.from(_selectedItemIds)) {+ if (await lib.removeFromCollection(widget.collectionId, itemId)) {+ removedIds.add(itemId);+ }+ }++ if (!mounted) return;+ setState(() {+ _editItems?.removeWhere((item) => removedIds.contains(item['id']));+ _selectedItemIds.removeAll(removedIds);+ _isRemovingSelected = false;+ });+ if (removedIds.isNotEmpty) {+ showOverlayToast(+ context,+ AppLocalizations.of(context)!.playlistDetailItemsRemoved(removedIds.length),+ icon: Icons.playlist_remove_rounded,+ );+ }+ }+@overrideWidget build(BuildContext context) {final cs = Theme.of(context).colorScheme;@@ -196,21 +227,26 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {Padding(padding: const EdgeInsets.symmetric(horizontal: 20),child: Row(children: [- if (_reordering) ...[- _headerTextButton(cs, l.cancel, _cancelReorder, color: cs.onSurfaceVariant),+ if (_editing) ...[+ _headerTextButton(cs, l.cancel, _cancelEdit, color: cs.onSurfaceVariant),const Spacer(),Flexible(- child: Text(name,+ child: Text(+ _selectedItemIds.isEmpty+ ? name+ : l.selectedCount(_selectedItemIds.length),maxLines: 1, overflow: TextOverflow.ellipsis,style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.onSurface)),),const Spacer(),- _headerTextButton(cs, l.done, () => _saveReorder(lib), color: cs.primary),+ _headerTextButton(+ cs,+ l.done,+ _isRemovingSelected ? null : () => _saveEdit(lib),+ color: cs.primary,+ ),] else ...[- if (canDeleteCollection)- _headerIconButton(cs, Icons.delete_outline_rounded,- () => _deleteCollection(context, lib), tooltip: l.delete),Icon(Icons.collections_bookmark_rounded, size: 20, color: cs.primary),const SizedBox(width: 8),Expanded(@@ -227,12 +263,13 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {_headerIconButton(cs,_gridView ? Icons.view_list_rounded : Icons.grid_view_rounded,() => setState(() => _gridView = !_gridView)),- if (canEditCollection && books.length > 1)- _headerIconButton(cs, Icons.tune_rounded, () => _startReorder(books)),+ if (canEditCollection)+ _headerIconButton(cs, Icons.edit_rounded, () => _startEdit(books),+ tooltip: l.edit),],]),),- if (!_reordering && description.isNotEmpty) ...[+ if (!_editing && description.isNotEmpty) ...[const SizedBox(height: 4),Padding(padding: const EdgeInsets.symmetric(horizontal: 20),@@ -245,16 +282,43 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {const SizedBox(height: 12),Divider(height: 1, color: cs.outlineVariant.withValues(alpha: 0.3),indent: 20, endIndent: 20),- if (!_reordering)+ if (!_editing)_buildPlayButton(cs, lib, books, name, l),// ContentExpanded(- child: _reordering- ? _buildReorderList(cs, tt, lib, l)+ child: _editing+ ? _buildEditList(cs, tt, lib, l): _gridView? _buildGrid(cs, tt, lib, books, l): _buildItemList(cs, tt, lib, books, l, canEditCollection: canEditCollection),),+ if (_editing && canDeleteCollection)+ Container(+ width: double.infinity,+ padding: EdgeInsets.fromLTRB(16, 8, 16,+ 8 + MediaQuery.of(context).viewPadding.bottom),+ decoration: BoxDecoration(+ color: cs.surfaceContainer,+ border: Border(top: BorderSide(+ color: cs.outlineVariant.withValues(alpha: 0.3))),+ ),+ child: _isRemovingSelected+ ? Center(child: SizedBox(width: 20, height: 20,+ child: CircularProgressIndicator(strokeWidth: 2, color: cs.primary)))+ : _selectedItemIds.isNotEmpty+ ? FilledButton.tonalIcon(+ onPressed: () => _removeSelected(lib),+ icon: const Icon(Icons.playlist_remove_rounded),+ label: Text('${l.remove} (${_selectedItemIds.length})'),+ style: FilledButton.styleFrom(foregroundColor: cs.error),+ )+ : OutlinedButton.icon(+ onPressed: () => _deleteCollection(context, lib),+ icon: const Icon(Icons.delete_outline_rounded),+ label: Text(l.deleteCollection),+ style: OutlinedButton.styleFrom(foregroundColor: cs.error),+ ),+ ),]);}@@ -293,10 +357,10 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {);}- Widget _buildReorderList(ColorScheme cs, TextTheme tt, LibraryProvider lib, AppLocalizations l) {- final items = _reorderItems!;+ Widget _buildEditList(ColorScheme cs, TextTheme tt, LibraryProvider lib, AppLocalizations l) {+ final items = _editItems!;return ReorderableListView.builder(- padding: EdgeInsets.only(top: 8, bottom: 8 + MediaQuery.of(context).viewPadding.bottom),+ padding: const EdgeInsets.only(top: 8, bottom: 8),onReorderStart: (_) => HapticFeedback.mediumImpact(),onReorder: (oldIndex, newIndex) {setState(() {@@ -312,46 +376,32 @@ class _CollectionDetailSheetState extends State<CollectionDetailSheet> {final media = book['media'] as Map<String, dynamic>? ?? {};final metadata = media['metadata'] as Map<String, dynamic>? ?? {};final title = metadata['title'] as String? ?? l.unknown;+ final author = metadata['authorName'] as String? ?? '';final coverUrl = lib.getCoverUrl(itemId);- return Container(+ return EditableSheetItem(key: ValueKey(itemId),- margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 3),- decoration: BoxDecoration(- color: cs.onSurface.withValues(alpha: 0.05),- borderRadius: BorderRadius.circular(12),- border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),- ),- child: ListTile(- dense: true,- leading: SizedBox(- width: 36, height: 36,- child: ClipRRect(- borderRadius: BorderRadius.circular(4),- child: coverUrl != null- ? (coverUrl.startsWith('/')- ? Image.file(File(coverUrl), fit: BoxFit.cover,- errorBuilder: (_, __, ___) => _placeholder(cs))- : Image.network(coverUrl, fit: BoxFit.cover,- headers: lib.mediaHeaders,- errorBuilder: (_, __, ___) => _placeholder(cs)))- : _placeholder(cs),- ),- ),- title: Text(- title,- maxLines: 1, overflow: TextOverflow.ellipsis,- style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500,- color: cs.onSurface),- ),- trailing: ReorderableDragStartListener(- index: index,- child: Padding(- padding: const EdgeInsets.all(8),- child: Icon(Icons.drag_handle_rounded, size: 18,- color: cs.onSurfaceVariant.withValues(alpha: 0.5)),- ),- ),+ index: index,+ selected: _selectedItemIds.contains(itemId),+ onSelectedChanged: (selected) => setState(() {+ if (selected) {+ _selectedItemIds.add(itemId);+ } else {+ _selectedItemIds.remove(itemId);+ }+ }),+ title: title,+ subtitle: author.isEmpty ? null : author,+ leading: ClipRRect(+ borderRadius: BorderRadius.circular(4),+ child: coverUrl != null+ ? (coverUrl.startsWith('/')+ ? Image.file(File(coverUrl), fit: BoxFit.cover,+ errorBuilder: (_, __, ___) => _placeholder(cs))+ : Image.network(coverUrl, fit: BoxFit.cover,+ headers: lib.mediaHeaders,+ errorBuilder: (_, __, ___) => _placeholder(cs)))+ : _placeholder(cs),),);},diff --git a/lib/widgets/ebook_reader_view.dart b/lib/widgets/ebook_reader_view.dartindex 2557e3a8..5fe17553 100644--- a/lib/widgets/ebook_reader_view.dart+++ b/lib/widgets/ebook_reader_view.dart@@ -774,9 +774,8 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsif (_selectionText == null) return;Clipboard.setData(ClipboardData(text: _selectionText!));_dismissSelection();- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(content: Text(AppLocalizations.of(context)!.readerCopied), duration: const Duration(seconds: 1)),- );+ showOverlayToast(context, AppLocalizations.of(context)!.readerCopied,+ icon: Icons.content_copy_rounded);}void _searchSelection() {diff --git a/lib/widgets/edit_metadata_sheet.dart b/lib/widgets/edit_metadata_sheet.dartindex 70295286..30961520 100644--- a/lib/widgets/edit_metadata_sheet.dart+++ b/lib/widgets/edit_metadata_sheet.dart@@ -8,6 +8,7 @@ import '../providers/auth_provider.dart';import '../providers/library_provider.dart';import '../services/socket_service.dart';import '../screens/chapter_editor_screen.dart';+import 'overlay_toast.dart';enum _ETab { details, cover, chapters, match, encode, embed }@@ -17,6 +18,8 @@ enum _ETab { details, cover, chapters, match, encode, embed }/// built here. Each tab has its own scroll controller so swiping between/// adjacent tabs never double-attaches one controller.class MetadataEditView extends StatefulWidget {+ static const quickMatchButtonKey = Key('metadataQuickMatchButton');+final String itemId;final String bookTitle;final Map<String, dynamic> metadata;@@ -78,6 +81,7 @@ class _MetadataEditViewState extends State<MetadataEditView>List<Map<String, dynamic>> _searchResults = [];bool _isSearching = false;bool _hasSearched = false;+ bool _quickMatching = false;String _provider = 'audible';static const _providerKeys = ['audible', 'itunes', 'openlibrary'];@@ -212,6 +216,121 @@ class _MetadataEditViewState extends State<MetadataEditView>// ─── Quick Match ────────────────────────────────────────────+ String _serverMatchProvider() {+ final libraryId = widget.libraryId;+ if (libraryId == null) return 'google';+ for (final library in context.read<LibraryProvider>().libraries) {+ if (library is! Map || library['id'] != libraryId) continue;+ final provider = library['provider']?.toString().trim() ?? '';+ if (provider.isNotEmpty) return provider;+ }+ return 'google';+ }++ Future<void> _runServerQuickMatch() async {+ final l = AppLocalizations.of(context)!;+ final title = _titleCtrl.text.trim();+ if (title.isEmpty) {+ showOverlayToast(context, l.chapterErrorTitleRequired,+ icon: Icons.error_outline_rounded);+ return;+ }++ final api = context.read<AuthProvider>().apiService;+ if (api == null) return;++ FocusScope.of(context).unfocus();+ setState(() => _quickMatching = true);+ final author = _authorCtrl.text.trim();+ final result = await api.matchLibraryItem(+ widget.itemId,+ title: title,+ author: author.isEmpty ? null : author,+ provider: _serverMatchProvider(),+ );+ if (!mounted) return;++ final warning = result?['warning']?.toString().trim() ?? '';+ final updated = result?['updated'] == true;+ setState(() {+ _quickMatching = false;+ if (updated) {+ _loadMatchedLibraryItem(result?['libraryItem']);+ _coverVersion++;+ }+ });++ if (updated) context.read<LibraryProvider>().refresh();++ final message = result == null+ ? l.failedToUpdateMetadata+ : warning.isNotEmpty+ ? warning+ : updated+ ? l.editMetadataUpdatedFromMatch+ : l.quickMatchNoUpdates;+ showOverlayToast(+ context,+ message,+ icon: result == null+ ? Icons.error_outline_rounded+ : warning.isNotEmpty+ ? Icons.warning_amber_rounded+ : updated+ ? Icons.check_circle_outline_rounded+ : Icons.info_outline_rounded,+ );+ }++ void _loadMatchedLibraryItem(dynamic rawItem) {+ if (rawItem is! Map) return;+ final media = rawItem['media'];+ if (media is! Map) return;+ final metadata = media['metadata'];+ if (metadata is! Map) return;++ String value(String key) => _safeString(metadata[key]);+ _titleCtrl.text = value('title');+ _subtitleCtrl.text = value('subtitle');+ _authorCtrl.text = value('authorName');+ _narratorCtrl.text = value('narratorName');+ _descCtrl.text = value('description');+ _publisherCtrl.text = value('publisher');+ _yearCtrl.text = value('publishedYear');+ _languageCtrl.text = value('language');+ _genresCtrl.text = value('genres');+ _tagsCtrl.text = _safeString(media['tags']);+ _asinCtrl.text = value('asin');+ _isbnCtrl.text = value('isbn');++ final previousSeriesRows = List.of(_seriesRows);+ _seriesRows.clear();+ final series = metadata['series'];+ if (series is List) {+ for (final entry in series) {+ if (entry is! Map) continue;+ _seriesRows.add((+ name: TextEditingController(text: _safeString(entry['name'])),+ seq: TextEditingController(text: _safeString(entry['sequence'])),+ ));+ }+ }+ if (_seriesRows.isEmpty) {+ _seriesRows.add((name: TextEditingController(), seq: TextEditingController()));+ }+ WidgetsBinding.instance.addPostFrameCallback((_) {+ for (final row in previousSeriesRows) {+ row.name.dispose();+ row.seq.dispose();+ }+ });++ _searchTitleCtrl.text = _titleCtrl.text;+ _searchAuthorCtrl.text = _authorCtrl.text;+ _coverSearchTitleCtrl.text = _titleCtrl.text;+ _coverSearchAuthorCtrl.text = _authorCtrl.text;+ }+Future<void> _doSearch() async {final title = _searchTitleCtrl.text.trim();if (title.isEmpty) return;@@ -314,23 +433,11 @@ class _MetadataEditViewState extends State<MetadataEditView>context.read<LibraryProvider>().refresh();_coverVersion++;// stays on the edit page- ScaffoldMessenger.of(context)- ..clearSnackBars()- ..showSnackBar(SnackBar(- content: Text(l.editMetadataUpdatedFromMatch),- behavior: SnackBarBehavior.floating,- duration: const Duration(seconds: 2),- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ showOverlayToast(context, l.editMetadataUpdatedFromMatch,+ icon: Icons.check_circle_outline_rounded);} else {- ScaffoldMessenger.of(context)- ..clearSnackBars()- ..showSnackBar(SnackBar(- content: Text(l.failedToUpdateMetadata),- behavior: SnackBarBehavior.floating,- duration: const Duration(seconds: 3),- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ showOverlayToast(context, l.failedToUpdateMetadata,+ icon: Icons.error_outline_rounded);}}@@ -511,23 +618,11 @@ class _MetadataEditViewState extends State<MetadataEditView>context.read<LibraryProvider>().refresh();_coverVersion++;// stays on the edit page- ScaffoldMessenger.of(context)- ..clearSnackBars()- ..showSnackBar(SnackBar(- content: Text(l.metadataUpdated),- behavior: SnackBarBehavior.floating,- duration: const Duration(seconds: 2),- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ showOverlayToast(context, l.metadataUpdated,+ icon: Icons.check_circle_outline_rounded);} else {- ScaffoldMessenger.of(context)- ..clearSnackBars()- ..showSnackBar(SnackBar(- content: Text(l.failedToUpdateMetadata),- behavior: SnackBarBehavior.floating,- duration: const Duration(seconds: 3),- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ showOverlayToast(context, l.failedToUpdateMetadata,+ icon: Icons.error_outline_rounded);}}@@ -849,10 +944,12 @@ class _MetadataEditViewState extends State<MetadataEditView>_runningAction = null;_taskProgress = null;});- ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(l.encodeFailed)));+ showOverlayToast(context, l.encodeFailed,+ icon: Icons.error_outline_rounded);return;}- ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(l.encodeStarted)));+ showOverlayToast(context, l.encodeStarted,+ icon: Icons.graphic_eq_rounded);}Future<void> _startEmbed() async {@@ -885,10 +982,12 @@ class _MetadataEditViewState extends State<MetadataEditView>_runningAction = null;_taskProgress = null;});- ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(l.embedCouldNotStart)));+ showOverlayToast(context, l.embedCouldNotStart,+ icon: Icons.error_outline_rounded);return;}- ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(l.embedStarted)));+ showOverlayToast(context, l.embedStarted,+ icon: Icons.edit_note_rounded);}void _onTaskStarted(Map<String, dynamic> data) {@@ -953,9 +1052,13 @@ class _MetadataEditViewState extends State<MetadataEditView>final msg = failed? (embed ? l.embedFailed : l.encodeFailedTask): (embed ? l.embedComplete : l.encodeComplete);- ScaffoldMessenger.of(context)- ..clearSnackBars()- ..showSnackBar(SnackBar(content: Text(msg)));+ showOverlayToast(+ context,+ msg,+ icon: failed+ ? Icons.error_outline_rounded+ : Icons.check_circle_outline_rounded,+ );}// ─── Build ──────────────────────────────────────────────────@@ -1203,9 +1306,19 @@ class _MetadataEditViewState extends State<MetadataEditView>Padding(padding: const EdgeInsets.fromLTRB(20, 8, 8, 0),child: Row(children: [+ if (widget.isAdmin)+ OutlinedButton.icon(+ key: MetadataEditView.quickMatchButtonKey,+ onPressed: _saving || _quickMatching ? null : _runServerQuickMatch,+ icon: _quickMatching+ ? SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: cs.primary))+ : const Icon(Icons.auto_fix_high_rounded, size: 18),+ label: Text(l.quickMatch),+ style: OutlinedButton.styleFrom(shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))),+ ),const Spacer(),FilledButton.icon(- onPressed: _saving ? null : _saveCustom,+ onPressed: _saving || _quickMatching ? null : _saveCustom,icon: _saving? SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2, color: cs.onPrimary)): const Icon(Icons.check_rounded, size: 18),@@ -1481,9 +1594,8 @@ class _MetadataEditViewState extends State<MetadataEditView>final api = context.read<AuthProvider>().apiService;final title = _coverSearchTitleCtrl.text.trim();if (api == null || title.isEmpty) {- ScaffoldMessenger.of(context)- ..clearSnackBars()- ..showSnackBar(SnackBar(content: Text(l.coverEnterTitleFirst)));+ showOverlayToast(context, l.coverEnterTitleFirst,+ icon: Icons.error_outline_rounded);return;}final author = _coverSearchAuthorCtrl.text.trim();@@ -1509,9 +1621,8 @@ class _MetadataEditViewState extends State<MetadataEditView>if (!mounted) return;setState(() => _coverSearching = false);if (_coverResults.isEmpty) {- ScaffoldMessenger.of(context)- ..clearSnackBars()- ..showSnackBar(SnackBar(content: Text(l.coverNoneFound)));+ showOverlayToast(context, l.coverNoneFound,+ icon: Icons.search_off_rounded);}}@@ -1527,9 +1638,13 @@ class _MetadataEditViewState extends State<MetadataEditView>_saving = false;if (ok) _coverVersion++;});- ScaffoldMessenger.of(context)- ..clearSnackBars()- ..showSnackBar(SnackBar(content: Text(ok ? l.coverUpdated : l.coverCouldNotUpdate)));+ showOverlayToast(+ context,+ ok ? l.coverUpdated : l.coverCouldNotUpdate,+ icon: ok+ ? Icons.check_circle_outline_rounded+ : Icons.error_outline_rounded,+ );}/// Show a cover result full-size with its resolution and an explicit Apply.diff --git a/lib/widgets/editable_sheet_item.dart b/lib/widgets/editable_sheet_item.dartnew file mode 100644index 00000000..2f667d8b--- /dev/null+++ b/lib/widgets/editable_sheet_item.dart@@ -0,0 +1,89 @@+import 'package:flutter/material.dart';++class EditableSheetItem extends StatelessWidget {+ final int index;+ final bool selected;+ final ValueChanged<bool> onSelectedChanged;+ final Widget leading;+ final String title;+ final String? subtitle;++ const EditableSheetItem({+ super.key,+ required this.index,+ required this.selected,+ required this.onSelectedChanged,+ required this.leading,+ required this.title,+ this.subtitle,+ });++ @override+ Widget build(BuildContext context) {+ final cs = Theme.of(context).colorScheme;++ return Padding(+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 3),+ child: Material(+ color: selected+ ? cs.primary.withValues(alpha: 0.08)+ : cs.onSurface.withValues(alpha: 0.05),+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(12),+ side: BorderSide(+ color: selected+ ? cs.primary.withValues(alpha: 0.35)+ : cs.onSurface.withValues(alpha: 0.08),+ ),+ ),+ clipBehavior: Clip.antiAlias,+ child: ListTile(+ dense: true,+ onTap: () => onSelectedChanged(!selected),+ leading: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Checkbox(+ value: selected,+ onChanged: (value) => onSelectedChanged(value ?? false),+ visualDensity: VisualDensity.compact,+ materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,+ ),+ const SizedBox(width: 6),+ SizedBox(width: 36, height: 36, child: leading),+ ],+ ),+ title: Text(+ title,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ fontSize: 13,+ fontWeight: FontWeight.w500,+ color: cs.onSurface,+ ),+ ),+ subtitle: subtitle == null+ ? null+ : Text(+ subtitle!,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(fontSize: 11, color: cs.onSurfaceVariant),+ ),+ trailing: ReorderableDragStartListener(+ index: index,+ child: Padding(+ padding: const EdgeInsets.all(8),+ child: Icon(+ Icons.drag_handle_rounded,+ size: 18,+ color: cs.onSurfaceVariant.withValues(alpha: 0.5),+ ),+ ),+ ),+ ),+ ),+ );+ }+}diff --git a/lib/widgets/episode_detail_sheet.dart b/lib/widgets/episode_detail_sheet.dartindex 6ad48006..6b3a5f0d 100644--- a/lib/widgets/episode_detail_sheet.dart+++ b/lib/widgets/episode_detail_sheet.dart@@ -147,7 +147,7 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {);debugPrint('[PodcastPlay] playItem returned in ${DateTime.now().difference(t0).inMilliseconds}ms (error=${error ?? 'none'})');if (error != null && rootContext.mounted) {- showErrorSnackBar(rootContext, error);+ showErrorToast(rootContext, error);}}@@ -205,12 +205,11 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {);await lib.refresh();if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.episodeDetailMarkedNotFinished),- behavior: SnackBarBehavior.floating,- duration: const Duration(seconds: 2),- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ showOverlayToast(+ context,+ l.episodeDetailMarkedNotFinished,+ icon: Icons.replay_rounded,+ );}} else {// Confirm before marking finished@@ -235,18 +234,20 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {);lib.markFinishedLocally(key, skipAutoAdvance: true);if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.episodeDetailMarkedFinishedNice),- behavior: SnackBarBehavior.floating,- duration: const Duration(seconds: 2),- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ showOverlayToast(+ context,+ l.episodeDetailMarkedFinishedNice,+ icon: Icons.check_circle_outline_rounded,+ );}}} catch (_) {if (mounted) {- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.failedToUpdateCheckConnection)));+ showOverlayToast(+ context,+ l.failedToUpdateCheckConnection,+ icon: Icons.error_outline_rounded,+ );}}}@@ -261,13 +262,11 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {TextButton(onPressed: () {DownloadService().deleteDownload(dlKey);Navigator.pop(ctx);- ScaffoldMessenger.of(context)- ..clearSnackBars()- ..showSnackBar(SnackBar(- content: Text(l.downloadRemoved),- duration: const Duration(seconds: 2),- behavior: SnackBarBehavior.floating,- ));+ showOverlayToast(+ context,+ l.downloadRemoved,+ icon: Icons.delete_outline_rounded,+ );},child: Text(l.remove, style: const TextStyle(color: Colors.redAccent))),],@@ -640,11 +639,11 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {if (lib.isOnAbsorbingList(dlKey)) {await lib.removeFromAbsorbing(dlKey);if (context.mounted) {- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- duration: const Duration(seconds: 3),- content: Text(Wording.of(context).removedFromAbsorbing),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));+ showOverlayToast(+ context,+ Wording.of(context).removedFromAbsorbing,+ icon: Icons.remove_circle_outline_rounded,+ );}} else {await lib.addToAbsorbingQueue(dlKey);@@ -653,11 +652,11 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {cached['_absorbingKey'] = dlKey;lib.absorbingItemCache[dlKey] = cached;if (context.mounted) {- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- duration: const Duration(seconds: 3),- content: Text(Wording.of(context).addedToAbsorbing),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));+ showOverlayToast(+ context,+ Wording.of(context).addedToAbsorbing,+ icon: Icons.add_circle_outline_rounded,+ );}}}),@@ -760,11 +759,13 @@ class _EpisodeDetailSheetState extends State<EpisodeDetailSheet> {if (context.mounted) {context.read<LibraryProvider>().resetProgressFor(compoundKey);- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- duration: const Duration(seconds: 3),- content: Text(ok ? l.progressResetFreshStart : l.resetMayNotHaveSynced),- behavior: SnackBarBehavior.floating,- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12))));+ showOverlayToast(+ context,+ ok ? l.progressResetFreshStart : l.resetMayNotHaveSynced,+ icon: ok+ ? Icons.restart_alt_rounded+ : Icons.warning_amber_rounded,+ );}}diff --git a/lib/widgets/episode_list_sheet.dart b/lib/widgets/episode_list_sheet.dartindex bbd876de..aeca3523 100644--- a/lib/widgets/episode_list_sheet.dart+++ b/lib/widgets/episode_list_sheet.dart@@ -284,14 +284,13 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {_selectedEpisodeIds.clear();});final l = AppLocalizations.of(context)!;- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(finished+ showOverlayToast(+ context,+ finished? l.episodeListMarkedFinished(ids.length)- : l.episodeListMarkedUnfinished(ids.length)),- behavior: SnackBarBehavior.floating,- duration: const Duration(seconds: 2),- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ : l.episodeListMarkedUnfinished(ids.length),+ icon: finished ? Icons.check_circle_rounded : Icons.replay_rounded,+ );}}@@ -343,7 +342,7 @@ class _EpisodeListSheetState extends State<EpisodeListSheet> {libraryId: _podcastItem['libraryId'] as String?,);if (mounted) {- if (error != null) showErrorSnackBar(context, error);+ if (error != null) showErrorToast(context, error);Navigator.of(context, rootNavigator: true).popUntil((route) => route.isFirst);}}diff --git a/lib/widgets/expanded_card.dart b/lib/widgets/expanded_card.dartindex 4d48e272..188bee6a 100644--- a/lib/widgets/expanded_card.dart+++ b/lib/widgets/expanded_card.dart@@ -1112,7 +1112,7 @@ class _ExpandedCardState extends State<ExpandedCard> {libraryId: _resolveLibraryId(),);if (mounted) {- if (error != null) showErrorSnackBar(context, error);+ if (error != null) showErrorToast(context, error);setState(() => _isStarting = false);}}diff --git a/lib/widgets/metadata_lookup_sheet.dart b/lib/widgets/metadata_lookup_sheet.dartindex cf807764..53826f03 100644--- a/lib/widgets/metadata_lookup_sheet.dart+++ b/lib/widgets/metadata_lookup_sheet.dart@@ -4,6 +4,7 @@ import 'package:cached_network_image/cached_network_image.dart';import '../l10n/app_localizations.dart';import '../services/api_service.dart';import '../services/metadata_override_service.dart';+import 'overlay_toast.dart';/// Bottom sheet that lets users search for book metadata via the ABS server/// and pick a result to store as a local override, or manually edit fields.@@ -247,6 +248,12 @@ class _MetadataLookupSheetState extends State<MetadataLookupSheet>);}+ void _showSavedToastAndClose(String message) {+ showOverlayToast(context, message,+ icon: Icons.check_circle_outline_rounded);+ Navigator.pop(context);+ }+Future<void> _applySelectedFields(Map<String, dynamic> result, Set<String> selected) async {final book = result['book'] as Map<String, dynamic>? ?? result;final override = <String, dynamic>{};@@ -296,13 +303,8 @@ class _MetadataLookupSheetState extends State<MetadataLookupSheet>if (mounted) {final l = AppLocalizations.of(context)!;widget.onApplied();- Navigator.pop(context);- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.metadataLookupFieldsSavedLocally(selected.length)),- behavior: SnackBarBehavior.floating,- duration: const Duration(seconds: 2),- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ _showSavedToastAndClose(+ l.metadataLookupFieldsSavedLocally(selected.length));}}@@ -344,13 +346,7 @@ class _MetadataLookupSheetState extends State<MetadataLookupSheet>if (mounted) {final l = AppLocalizations.of(context)!;widget.onApplied();- Navigator.pop(context);- ScaffoldMessenger.of(context).showSnackBar(SnackBar(- content: Text(l.metadataSavedLocally),- behavior: SnackBarBehavior.floating,- duration: const Duration(seconds: 2),- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ _showSavedToastAndClose(l.metadataSavedLocally);}}diff --git a/lib/widgets/overlay_toast.dart b/lib/widgets/overlay_toast.dartindex 8d67eb12..5ce7256a 100644--- a/lib/widgets/overlay_toast.dart+++ b/lib/widgets/overlay_toast.dart@@ -7,12 +7,29 @@ OverlayEntry? _currentToast;////// Pass [icon] for a leading icon (e.g. Icons.check_circle_rounded).void showOverlayToast(BuildContext context, String message, {IconData? icon}) {+ _insertOverlayToast(Overlay.maybeOf(context), message, icon: icon);+}++/// Show the same toast from provider/service code that owns a navigator but+/// does not have a context beneath its overlay.+void showNavigatorOverlayToast(+ NavigatorState? navigator,+ String message, {+ IconData? icon,+}) {+ _insertOverlayToast(navigator?.overlay, message, icon: icon);+}++void _insertOverlayToast(+ OverlayState? overlay,+ String message, {+ IconData? icon,+}) {_currentToast?.remove();_currentToast = null;// No overlay (startup, account switch, background-triggered callers): drop// the toast instead of throwing into whatever async flow asked for it.- final overlay = Overlay.maybeOf(context);if (overlay == null) return;late OverlayEntry entry;entry = OverlayEntry(diff --git a/lib/widgets/playlist_detail_sheet.dart b/lib/widgets/playlist_detail_sheet.dartindex 38265786..2fbcf7d7 100644--- a/lib/widgets/playlist_detail_sheet.dart+++ b/lib/widgets/playlist_detail_sheet.dart@@ -15,6 +15,7 @@ import '../services/download_service.dart';import '../screens/app_shell.dart';import 'add_books_search_sheet.dart';import 'book_detail_sheet.dart';+import 'editable_sheet_item.dart';import 'episode_list_sheet.dart';import 'stackable_sheet.dart';@@ -46,10 +47,9 @@ class PlaylistDetailSheet extends StatefulWidget {}class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {- bool _reordering = false;+ bool _editing = false;bool _gridView = false;- List<Map<String, dynamic>>? _reorderItems;- bool _selectMode = false;+ List<Map<String, dynamic>>? _editItems;final Set<String> _selectedKeys = {}; // "libraryItemId" or "libraryItemId-episodeId"bool _isBatchUpdating = false;@@ -145,7 +145,6 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {final l = AppLocalizations.of(context)!;setState(() {_isBatchUpdating = false;- _selectMode = false;_selectedKeys.clear();});showOverlayToast(@@ -162,34 +161,38 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {if (_selectedKeys.isEmpty) return;setState(() => _isBatchUpdating = true);- final playlist = lib.playlists.cast<Map<String, dynamic>>().where(- (p) => p['id'] == widget.playlistId,- ).firstOrNull;- final items = (playlist?['items'] as List<dynamic>?) ?? [];+ final items = _editItems ?? [];+ final removedKeys = <String>{};for (final key in List<String>.from(_selectedKeys)) {- final item = items.cast<Map<String, dynamic>>().where(+ final item = items.where((i) => _itemKey(i) == key,).firstOrNull;if (item == null) continue;final libraryItemId = item['libraryItemId'] as String? ?? '';final episodeId = item['episodeId'] as String?;- await lib.removeFromPlaylist(widget.playlistId, libraryItemId, episodeId: episodeId);+ if (await lib.removeFromPlaylist(+ widget.playlistId, libraryItemId, episodeId: episodeId,+ )) {+ removedKeys.add(key);+ }}if (mounted) {- final count = _selectedKeys.length;+ final count = removedKeys.length;final l = AppLocalizations.of(context)!;setState(() {_isBatchUpdating = false;- _selectMode = false;- _selectedKeys.clear();+ _editItems?.removeWhere((item) => removedKeys.contains(_itemKey(item)));+ _selectedKeys.removeAll(removedKeys);});- showOverlayToast(- context,- l.playlistDetailItemsRemoved(count),- icon: Icons.playlist_remove_rounded,- );+ if (count > 0) {+ showOverlayToast(+ context,+ l.playlistDetailItemsRemoved(count),+ icon: Icons.playlist_remove_rounded,+ );+ }}}@@ -241,7 +244,7 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {);}- Widget _headerTextButton(ColorScheme cs, String label, VoidCallback onTap,+ Widget _headerTextButton(ColorScheme cs, String label, VoidCallback? onTap,{required Color color}) {return TextButton(onPressed: onTap,@@ -280,17 +283,18 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {}}- void _startReorder(List<dynamic> items) {+ void _startEdit(List<dynamic> items) {setState(() {- _reordering = true;- _reorderItems = items+ _editing = true;+ _editItems = items.map((i) => Map<String, dynamic>.from(i as Map)).toList();+ _selectedKeys.clear();});}- void _saveReorder(LibraryProvider lib) {- final items = _reorderItems;+ void _saveEdit(LibraryProvider lib) {+ final items = _editItems;if (items != null) {// Persist in the background so "Done" closes instantly instead of// hanging on the PATCH + playlists reload.@@ -299,10 +303,11 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {Navigator.pop(context);}- void _cancelReorder() {+ void _cancelEdit() {setState(() {- _reordering = false;- _reorderItems = null;+ _editing = false;+ _editItems = null;+ _selectedKeys.clear();});}@@ -339,42 +344,26 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {Padding(padding: const EdgeInsets.symmetric(horizontal: 20),child: Row(children: [- if (_reordering) ...[- _headerTextButton(cs, l.cancel, _cancelReorder, color: cs.onSurfaceVariant),+ if (_editing) ...[+ _headerTextButton(cs, l.cancel, _cancelEdit, color: cs.onSurfaceVariant),const Spacer(),Flexible(- child: Text(name,+ child: Text(+ _selectedKeys.isEmpty+ ? name+ : l.selectedCount(_selectedKeys.length),maxLines: 1, overflow: TextOverflow.ellipsis,style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.onSurface)),),const Spacer(),- _headerTextButton(cs, l.done, () => _saveReorder(lib), color: cs.primary),- ] else if (_selectMode) ...[- _headerIconButton(cs, Icons.close_rounded, () => setState(() {- _selectMode = false;- _selectedKeys.clear();- })),- const SizedBox(width: 4),- Text(l.selectedCount(_selectedKeys.length),- style: tt.titleSmall?.copyWith(color: cs.onSurfaceVariant, fontWeight: FontWeight.w600)),- const SizedBox(width: 4),- _headerTextButton(cs, l.selectAll, () {- setState(() {- if (_selectedKeys.length == items.length) {- _selectedKeys.clear();- } else {- _selectedKeys.clear();- for (final i in items) {- _selectedKeys.add(_itemKey(i as Map<String, dynamic>));- }- }- });- }, color: cs.primary),- const Spacer(),+ _headerTextButton(+ cs,+ l.done,+ _isBatchUpdating ? null : () => _saveEdit(lib),+ color: cs.primary,+ ),] else ...[- _headerIconButton(cs, Icons.delete_outline_rounded,- () => _deletePlaylist(context, lib), tooltip: l.delete),Icon(Icons.playlist_play_rounded, size: 20, color: cs.primary),const SizedBox(width: 8),Expanded(@@ -391,33 +380,27 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {_headerIconButton(cs,_gridView ? Icons.view_list_rounded : Icons.grid_view_rounded,() => setState(() => _gridView = !_gridView)),- if (items.length > 1) ...[- _headerIconButton(cs, Icons.checklist_rounded,- () => setState(() => _selectMode = true),- color: cs.onSurfaceVariant.withValues(alpha: 0.6)),- _headerIconButton(cs, Icons.tune_rounded, () => _startReorder(items)),- ],+ _headerIconButton(cs, Icons.edit_rounded, () => _startEdit(items),+ tooltip: l.edit),],]),),const SizedBox(height: 12),Divider(height: 1, color: cs.outlineVariant.withValues(alpha: 0.3),indent: 20, endIndent: 20),- if (!_reordering && !_selectMode)+ if (!_editing)_buildPlayButton(cs, lib, items, l),// ContentExpanded(- child: _reordering- ? _buildReorderList(cs, tt, lib, l)- : _selectMode- ? _buildSelectList(cs, tt, lib, items, l)- : _gridView- ? _buildGrid(cs, tt, lib, items, l)- : _buildItemList(cs, tt, lib, items, l),+ child: _editing+ ? _buildEditList(cs, tt, lib, l)+ : _gridView+ ? _buildGrid(cs, tt, lib, items, l)+ : _buildItemList(cs, tt, lib, items, l),),- // Batch action bar- if (_selectMode && _selectedKeys.isNotEmpty)+ if (_editing)Container(+ width: double.infinity,padding: EdgeInsets.fromLTRB(16, 8, 16, 8 + MediaQuery.of(context).viewPadding.bottom),decoration: BoxDecoration(color: cs.surfaceContainer,@@ -426,7 +409,8 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {child: _isBatchUpdating? Center(child: SizedBox(width: 20, height: 20,child: CircularProgressIndicator(strokeWidth: 2, color: cs.primary)))- : Row(children: [+ : _selectedKeys.isNotEmpty+ ? Row(children: [Expanded(child: FilledButton.tonalIcon(onPressed: () => _batchMarkFinished(true, lib),icon: const Icon(Icons.check_circle_rounded, size: 18),@@ -449,7 +433,13 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {backgroundColor: cs.error.withValues(alpha: 0.1),),),- ]),+ ])+ : OutlinedButton.icon(+ onPressed: () => _deletePlaylist(context, lib),+ icon: const Icon(Icons.delete_outline_rounded),+ label: Text(l.deletePlaylist),+ style: OutlinedButton.styleFrom(foregroundColor: cs.error),+ ),),]);}@@ -489,10 +479,10 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {);}- Widget _buildReorderList(ColorScheme cs, TextTheme tt, LibraryProvider lib, AppLocalizations l) {- final items = _reorderItems!;+ Widget _buildEditList(ColorScheme cs, TextTheme tt, LibraryProvider lib, AppLocalizations l) {+ final items = _editItems!;return ReorderableListView.builder(- padding: EdgeInsets.only(top: 8, bottom: 8 + MediaQuery.of(context).viewPadding.bottom),+ padding: const EdgeInsets.only(top: 8, bottom: 8),onReorderStart: (_) => HapticFeedback.mediumImpact(),onReorder: (oldIndex, newIndex) {setState(() {@@ -511,141 +501,58 @@ class _PlaylistDetailSheetState extends State<PlaylistDetailSheet> {return SizedBox.shrink(key: ValueKey('$libraryItemId-${episodeId ?? ''}-$index'));}- final media = libraryItem['media'] as Map<String, dynamic>? ?? {};- final metadata = media['metadata'] as Map<String, dynamic>? ?? {};- final title = metadata['title'] as String? ?? l.unknown;- final coverUrl = lib.getCoverUrl(libraryItemId);-- String? episodeTitle;- if (episodeId != null) {- episodeTitle = _getEpisodeTitle(item, libraryItem, episodeId);- }-- return Container(- key: ValueKey('$libraryItemId-${episodeId ?? ''}'),- margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 3),- decoration: BoxDecoration(- color: cs.onSurface.withValues(alpha: 0.05),- borderRadius: BorderRadius.circular(12),- border: Border.all(color: cs.onSurface.withValues(alpha: 0.08)),- ),- child: ListTile(- dense: true,- leading: SizedBox(- width: 36, height: 36,- child: Stack(children: [- ClipRRect(- borderRadius: BorderRadius.circular(4),- child: coverUrl != null- ? (coverUrl.startsWith('/')- ? Image.file(File(coverUrl), fit: BoxFit.cover, width: 36, height: 36,- errorBuilder: (_, __, ___) => _placeholder(cs))- : Image.network(coverUrl, fit: BoxFit.cover, width: 36, height: 36,- headers: lib.mediaHeaders,- errorBuilder: (_, __, ___) => _placeholder(cs)))- : _placeholder(cs),- ),- if (PlayerSettings.showExplicitBadge && metadata['explicit'] == true)- Positioned(- top: 2, right: 2,- child: Container(- padding: const EdgeInsets.symmetric(horizontal: 3, vertical: 0.5),- decoration: BoxDecoration(- color: Colors.red.withValues(alpha: 0.85),- borderRadius: BorderRadius.circular(3),- ),- child: Text(l.bookCardExplicitBadge, style: const TextStyle(color: Colors.white, fontSize: 7, fontWeight: FontWeight.w800)),- ),- ),- ]),- ),- title: Text(- episodeTitle ?? title,- maxLines: 1, overflow: TextOverflow.ellipsis,- style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500,- color: cs.onSurface),- ),- trailing: ReorderableDragStartListener(- index: index,- child: Padding(- padding: const EdgeInsets.all(8),- child: Icon(Icons.drag_handle_rounded, size: 18,- color: cs.onSurfaceVariant.withValues(alpha: 0.5)),- ),- ),- ),- );- },- );- }-- Widget _buildSelectList(ColorScheme cs, TextTheme tt, LibraryProvider lib, List<dynamic> items, AppLocalizations l) {- return ListView.builder(- controller: widget.scrollController,- padding: EdgeInsets.only(bottom: (_selectedKeys.isNotEmpty ? 64.0 : 32.0) + MediaQuery.of(context).viewPadding.bottom),- itemCount: items.length,- itemBuilder: (context, index) {- final item = items[index] as Map<String, dynamic>;- final libraryItemId = item['libraryItemId'] as String? ?? '';- final episodeId = item['episodeId'] as String?;- final libraryItem = item['libraryItem'] as Map<String, dynamic>?;- if (libraryItem == null) return const SizedBox.shrink();-final media = libraryItem['media'] as Map<String, dynamic>? ?? {};final metadata = media['metadata'] as Map<String, dynamic>? ?? {};final title = metadata['title'] as String? ?? l.unknown;final author = metadata['authorName'] as String? ?? '';final coverUrl = lib.getCoverUrl(libraryItemId);- final key = _itemKey(item);- final selected = _selectedKeys.contains(key);+ final itemKey = _itemKey(item);String? episodeTitle;if (episodeId != null) {episodeTitle = _getEpisodeTitle(item, libraryItem, episodeId);}- return InkWell(- onTap: () => setState(() {- if (selected) { _selectedKeys.remove(key); } else { _selectedKeys.add(key); }+ return EditableSheetItem(+ key: ValueKey(itemKey),+ index: index,+ selected: _selectedKeys.contains(itemKey),+ onSelectedChanged: (selected) => setState(() {+ if (selected) {+ _selectedKeys.add(itemKey);+ } else {+ _selectedKeys.remove(itemKey);+ }}),- child: Padding(- padding: const EdgeInsets.fromLTRB(12, 6, 12, 6),- child: Row(children: [- Checkbox(- value: selected,- onChanged: (v) => setState(() {- if (v == true) { _selectedKeys.add(key); } else { _selectedKeys.remove(key); }- }),- visualDensity: VisualDensity.compact,- materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,- ),- const SizedBox(width: 8),- SizedBox(- width: 40, height: 40,- child: ClipRRect(- borderRadius: BorderRadius.circular(6),- child: coverUrl != null- ? (coverUrl.startsWith('/')- ? Image.file(File(coverUrl), fit: BoxFit.cover,- errorBuilder: (_, __, ___) => _placeholder(cs))- : Image.network(coverUrl, fit: BoxFit.cover,- headers: lib.mediaHeaders,- errorBuilder: (_, __, ___) => _placeholder(cs)))- : _placeholder(cs),+ title: episodeTitle ?? title,+ subtitle: episodeTitle != null ? title : (author.isEmpty ? null : author),+ leading: Stack(children: [+ ClipRRect(+ borderRadius: BorderRadius.circular(4),+ child: coverUrl != null+ ? (coverUrl.startsWith('/')+ ? Image.file(File(coverUrl), fit: BoxFit.cover,+ width: 36, height: 36,+ errorBuilder: (_, __, ___) => _placeholder(cs))+ : Image.network(coverUrl, fit: BoxFit.cover,+ width: 36, height: 36,+ headers: lib.mediaHeaders,+ errorBuilder: (_, __, ___) => _placeholder(cs)))+ : _placeholder(cs),+ ),+ if (PlayerSettings.showExplicitBadge && metadata['explicit'] == true)+ Positioned(+ top: 2, right: 2,+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 3, vertical: 0.5),+ decoration: BoxDecoration(+ color: Colors.red.withValues(alpha: 0.85),+ borderRadius: BorderRadius.circular(3),+ ),+ child: Text(l.bookCardExplicitBadge, style: const TextStyle(color: Colors.white, fontSize: 7, fontWeight: FontWeight.w800)),),),- const SizedBox(width: 12),- Expanded(child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(episodeTitle ?? title, maxLines: 1, overflow: TextOverflow.ellipsis,- style: TextStyle(fontSize: 13, fontWeight: FontWeight.w500, color: cs.onSurface)),- Text(episodeTitle != null ? title : author, maxLines: 1, overflow: TextOverflow.ellipsis,- style: TextStyle(fontSize: 11, color: cs.onSurfaceVariant)),- ],- )),- ]),- ),+ ]),);},);diff --git a/lib/widgets/podcast_episode_feed.dart b/lib/widgets/podcast_episode_feed.dartindex e3b6cdb7..c3cf0958 100644--- a/lib/widgets/podcast_episode_feed.dart+++ b/lib/widgets/podcast_episode_feed.dart@@ -10,7 +10,7 @@ import '../services/audio_player_service.dart';import '../services/chromecast_service.dart';import '../services/download_service.dart';import '../services/scoped_prefs.dart';-import 'card_buttons.dart' show showErrorSnackBar;+import 'card_buttons.dart' show showErrorToast;import 'episode_list_sheet.dart';import 'episode_row.dart';import 'overlay_toast.dart';@@ -229,7 +229,7 @@ class _PodcastEpisodeFeedState extends State<PodcastEpisodeFeed> {libraryId: (ep['podcast'] as Map<String, dynamic>?)?['libraryId'] as String? ??widget.libraryId,);- if (error != null && mounted) showErrorSnackBar(context, error);+ if (error != null && mounted) showErrorToast(context, error);}Future<void> _downloadEpisode(Map<String, dynamic> ep) async {diff --git a/lib/widgets/rmab_book_detail_sheet.dart b/lib/widgets/rmab_book_detail_sheet.dartindex 3cc06f47..5a48aaf1 100644--- a/lib/widgets/rmab_book_detail_sheet.dart+++ b/lib/widgets/rmab_book_detail_sheet.dart@@ -5,6 +5,7 @@ import '../l10n/app_localizations.dart';import '../services/rmab_service.dart';import '../services/scoped_prefs.dart';import 'html_description.dart';+import 'overlay_toast.dart';import 'rmab_config_sheet.dart' show kRmabBaseUrlKey, kRmabApiTokenKey;import 'rmab_request_status_chip.dart';import 'stackable_sheet.dart';@@ -144,14 +145,7 @@ class _RmabBookDetailContentState extends State<_RmabBookDetailContent> {}void _toast(String msg) {- ScaffoldMessenger.of(context)- ..clearSnackBars()- ..showSnackBar(SnackBar(- content: Text(msg),- behavior: SnackBarBehavior.floating,- shape:- RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),- ));+ showOverlayToast(context, msg);}@overridediff --git a/lib/widgets/stable_cached_network_image.dart b/lib/widgets/stable_cached_network_image.dartnew file mode 100644index 00000000..8c87cc36--- /dev/null+++ b/lib/widgets/stable_cached_network_image.dart@@ -0,0 +1,31 @@+import 'package:cached_network_image/cached_network_image.dart';++String stableCoverCacheKey(String imageUrl, {int? updatedAt}) {+ final uri = Uri.tryParse(imageUrl);+ if (uri == null ||+ !uri.path.contains('/api/items/') ||+ !uri.path.endsWith('/cover')) {+ return imageUrl;+ }++ final query = Map<String, String>.from(uri.queryParameters);+ final revision = updatedAt?.toString() ?? query['ts'];+ query.remove('token');+ query.remove('ts');+ if (revision != null) query['ts'] = revision;++ return uri.replace(queryParameters: query.isEmpty ? null : query).toString();+}++class StableCachedNetworkImage extends CachedNetworkImage {+ StableCachedNetworkImage({+ super.key,+ required super.imageUrl,+ required super.cacheKey,+ super.fit,+ super.httpHeaders,+ super.imageBuilder,+ super.placeholder,+ super.errorWidget,+ }) : super(useOldImageOnUrlChange: true);+}