Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Bring the web branch up to date with main through 1.11.1 Beta 5

Barnabas555804668d91
diff --cc lib/l10n/app_localizations_de.dart
index c2b73d47,01348bf4..3b879d9e
--- a/lib/l10n/app_localizations_de.dart
+++ b/lib/l10n/app_localizations_de.dart
@@@ -3588,17 -3730,8 +3746,17 @@@ class AppLocalizationsDe extends AppLoc
String get switchLibraryTooltip => 'Bibliothek wechseln';
@override
- String get refreshTooltip => 'Refresh';
+ String get refreshTooltip => 'Aktualisieren';
+ @override
+ String get openNowPlayingTooltip => 'Open Now Playing';
+
+ @override
+ String get previousChapterTooltip => 'Previous chapter';
+
+ @override
+ String get nextChapterTooltip => 'Next chapter';
+
@override
String get noBooksFound => 'Keine Bücher gefunden';
@@@ -5734,19 -5871,16 +5896,19 @@@
}
@override
- String get upcomingReleasesBadgeNew => 'NEW';
+ String get upcomingReleasesBadgeNew => 'NEU';
+ @override
+ String get upcomingReleasesOpenSeries => 'Open series on Audible';
+
@override
- String get upcomingReleasesOpenLibrarySeries => 'Open series in library';
+ String get upcomingReleasesOpenLibrarySeries => 'Serie in Bibliothek öffnen';
@override
- String get upcomingReleasesAsinCopied => 'Series ASIN copied';
+ String get upcomingReleasesAsinCopied => 'Serien ASIN kopiert';
@override
- String get upcomingReleasesSetSeriesAsin => 'Set series ASIN';
+ String get upcomingReleasesSetSeriesAsin => 'Serien ASIN setzen';
@override
String get upcomingReleasesSetAsinInstructions =>
diff --cc lib/main.dart
index e3f6b73c,8b5f54a4..7a221f13
--- a/lib/main.dart
+++ b/lib/main.dart
@@@ -690,18 -780,18 +798,22 @@@ class _AuthGateState extends State<Auth
// the UI has bootstrapped the current item) through the existing
// home-widget restore path. Registered as a static callback to avoid a
// circular import between AudioPlayerService and HomeWidgetService.
- AudioPlayerService.onColdStartPlayRequested =
- HomeWidgetService().resumeLastPlayedIfAvailable;
- // A headset press may have cold-launched this process into the background
- // with the native core already playing - adopt that audio now rather than
- // leaving the lock screen blank until the next press.
- unawaited(AudioPlayerService().adoptBackgroundEngineIfRunning());
+ if (!AppPlatform.isWeb) {
+ AudioPlayerService.onColdStartPlayRequested =
+ HomeWidgetService().resumeLastPlayedIfAvailable;
++ // A headset press may have cold-launched this process into the background
++ // with the native core already playing - adopt that audio now rather than
++ // leaving the lock screen blank until the next press.
++ unawaited(AudioPlayerService().adoptBackgroundEngineIfRunning());
+ }
debugPrint('[Init] AudioPlayerService done (${sw.elapsedMilliseconds}ms)');
- try {
- await Permission.notification.request();
- } catch (e) {
- debugPrint('[Init] Permission request failed: $e');
+ if (!AppPlatform.isWeb) {
+ try {
+ await Permission.notification.request();
+ } catch (e) {
+ debugPrint('[Init] Permission request failed: $e');
+ }
}
// Initialize Chromecast (Android only)
@@@ -721,9 -811,12 +833,12 @@@
// fold it into the offline ledger so the normal flush ships it.
await ProgressSyncService().migrateOrphanStreamingTime();
await LocalSessionService().init();
- await EqualizerService().init();
+ if (!AppPlatform.isWeb) await EqualizerService().init();
await SleepTimerService().loadAutoSleepSettings();
+ // Watch for settings changes and pull the synced copy on the way in.
+ await SettingsSyncService().startIfEnabled();
+ unawaited(SettingsSyncService().onAppForegrounded());
- if (Platform.isAndroid) {
+ if (AppPlatform.isAndroid) {
// Pre-populate Android Auto browse tree in background.
Future.microtask(() => AndroidAutoService().refresh());
}
diff --cc lib/providers/_lp_core.dart
index d226cf01,64169deb..b9e2f918
--- a/lib/providers/_lp_core.dart
+++ b/lib/providers/_lp_core.dart
@@@ -2542,13 -2695,21 +2724,26 @@@ mixin _CoreMixin on ChangeNotifier, _St
// ── Rolling auto-download ──
+ /// Whether a progress entry shows real listening. A reset keeps the row:
+ /// Absorb's own reset writes it back with progress 0, position 0, hidden
+ /// from Continue Listening and the newest lastUpdate, so picking anchors
+ /// by lastUpdate alone let an accidentally played then reset episode drag
+ /// a whole show's rolling window to the newest episodes.
+ static bool _hasListened(Map<String, dynamic>? progress) {
+ if (progress == null) return false;
+ if (progress['hideFromContinueListening'] == true) return false;
+ final fraction = (progress['progress'] as num?)?.toDouble() ?? 0;
+ final currentTime = (progress['currentTime'] as num?)?.toDouble() ?? 0;
+ return fraction > 0 || currentTime > 0;
+ }
+
void _catchUpRollingDownloads() async {
- if (_api == null || isOffline || _rollingDownloadSeries.isEmpty) return;
+ if (AppPlatform.isWeb ||
+ _api == null ||
+ isOffline ||
+ _rollingDownloadSeries.isEmpty) {
+ return;
+ }
final wifiOnly = await PlayerSettings.getWifiOnlyDownloads();
if (wifiOnly) {
diff --cc lib/providers/auth_provider.dart
index ba5e0222,e0dae7f5..c821ff82
--- a/lib/providers/auth_provider.dart
+++ b/lib/providers/auth_provider.dart
@@@ -740,8 -743,11 +756,12 @@@ class AuthProvider extends ChangeNotifi
_isLegacyToken = tokens.isLegacy;
_accessToken = tokens.token;
_refreshToken = tokens.refreshToken;
+ _serverReachable = true;
debugPrint('[Auth] Login response keys: ${result.keys.toList()}');
+ final serverSettings = result['serverSettings'];
+ debugPrint('[Auth] Server version='
+ '${serverSettings is Map ? serverSettings['version'] : null} '
+ 'source=${result['Source']}');
debugPrint('[Auth] Login user keys: ${user.keys.toList()}');
debugPrint(
'[Auth] accessToken=${tokens.accessToken != null}, refreshToken=${tokens.refreshToken != null}, legacyToken=${tokens.legacyToken != null}, isLegacy=$_isLegacyToken',
diff --cc lib/screens/absorbing_screen.dart
index d6fcfd4e,2a4ec7db..f3980ea1
--- a/lib/screens/absorbing_screen.dart
+++ b/lib/screens/absorbing_screen.dart
@@@ -1550,61 -1019,56 +1561,69 @@@ class _PageDots extends StatelessWidge
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
- return LayoutBuilder(builder: (context, constraints) {
- // Active dot is 20 wide, inactive is 6, each has horizontal padding on both sides.
- // Solve for padding: count * (6 + 2*pad) + (20 - 6) <= maxWidth
- // pad = (maxWidth - 14 - count * 6) / (count * 2)
- const double dotSize = 6;
- const double activeDotWidth = 20;
- final maxWidth = constraints.maxWidth;
- final extraActive = activeDotWidth - dotSize;
- final available = maxWidth - extraActive - count * dotSize;
- final hPad = (available / (count * 2)).clamp(1.5, 8.0);
-
- return ListenableBuilder(
- listenable: controller,
- builder: (_, __) {
- final page = controller.hasClients && controller.positions.length == 1 ? (controller.page ?? 0).round() : 0;
- // The compact phone header can leave less width than the dots'
- // minimum footprint (padding bottoms out at 1.5); an unclipped Row
- // then paints under the Stop button. Scale the whole strip down
- // instead when it genuinely doesn't fit.
- return FittedBox(
- fit: BoxFit.scaleDown,
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: List.generate(count, (i) {
- final active = i == page;
- return GestureDetector(
- behavior: HitTestBehavior.opaque,
- onTap: () => controller.animateToPage(i,
- duration: const Duration(milliseconds: 400),
- curve: Curves.easeOutCubic),
- child: Padding(
- padding: EdgeInsets.symmetric(horizontal: hPad, vertical: 12),
- child: AnimatedContainer(
- duration: const Duration(milliseconds: 300),
+ return LayoutBuilder(
+ builder: (context, constraints) {
+ // Active dot is 20 wide, inactive is 6, each has horizontal padding on both sides.
+ // Solve for padding: count * (6 + 2*pad) + (20 - 6) <= maxWidth
+ // pad = (maxWidth - 14 - count * 6) / (count * 2)
+ const double dotSize = 6;
+ const double activeDotWidth = 20;
+ final maxWidth = constraints.maxWidth;
+ final extraActive = activeDotWidth - dotSize;
+ final available = maxWidth - extraActive - count * dotSize;
+ final hPad = (available / (count * 2)).clamp(1.5, 8.0);
+
+ return ListenableBuilder(
+ listenable: controller,
+ builder: (_, __) {
+ final page =
+ controller.hasClients && controller.positions.length == 1
+ ? (controller.page ?? 0).round()
+ : 0;
- return Row(
++ // The compact phone header can leave less width than the dots'
++ // minimum footprint (padding bottoms out at 1.5); an unclipped Row
++ // then paints under the Stop button. Scale the whole strip down
++ // instead when it genuinely doesn't fit.
++ return FittedBox(
++ fit: BoxFit.scaleDown,
++ child: Row(
++ mainAxisSize: MainAxisSize.min,
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: List.generate(count, (i) {
+ final active = i == page;
+ return GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () => controller.animateToPage(
+ i,
+ duration: const Duration(milliseconds: 400),
curve: Curves.easeOutCubic,
- width: active ? activeDotWidth : dotSize,
- height: dotSize,
- decoration: BoxDecoration(
- color: active ? cs.onSurface.withValues(alpha: 0.54) : cs.onSurface.withValues(alpha: 0.15),
- borderRadius: BorderRadius.circular(3),
+ ),
+ child: Padding(
+ padding: EdgeInsets.symmetric(
+ horizontal: hPad,
+ vertical: 12,
+ ),
+ child: AnimatedContainer(
+ duration: const Duration(milliseconds: 300),
+ curve: Curves.easeOutCubic,
+ width: active ? activeDotWidth : dotSize,
+ height: dotSize,
+ decoration: BoxDecoration(
+ color: active
+ ? cs.onSurface.withValues(alpha: 0.54)
+ : cs.onSurface.withValues(alpha: 0.15),
+ borderRadius: BorderRadius.circular(3),
+ ),
),
),
- ),
- );
- }),
- ),
- );
- },
- );
- });
+ );
+ }),
++ ),
+ );
+ },
+ );
+ },
+ );
}
}
@@@ -2731,59 -2032,51 +2792,65 @@@ class _AbsorbingQueuePanelState extend
decoration: BoxDecoration(
color: isPlaying
? cs.primaryContainer.withValues(alpha: 0.25)
- : (isFinished ? cs.onSurface.withValues(alpha: 0.03) : Colors.transparent),
+ : (isFinished
+ ? cs.onSurface.withValues(alpha: 0.03)
+ : Colors.transparent),
borderRadius: BorderRadius.circular(12),
),
- child: Row(children: [
- SizedBox(
- width: 30,
- child: FittedBox(
- fit: BoxFit.scaleDown,
- alignment: Alignment.centerLeft,
- child: Text('${index + 1}',
+ child: Row(
+ children: [
+ SizedBox(
- width: 24,
- child: Text(
- '${index + 1}',
- style: tt.labelMedium?.copyWith(
- color: isFinished
- ? cs.onSurface.withValues(alpha: 0.3)
- : cs.primary,
- fontWeight: FontWeight.w700,
++ width: 30,
++ child: FittedBox(
++ fit: BoxFit.scaleDown,
++ alignment: Alignment.centerLeft,
++ child: Text(
++ '${index + 1}',
+ maxLines: 1,
+ softWrap: false,
+ style: tt.labelMedium?.copyWith(
- color: isFinished ? cs.onSurface.withValues(alpha: 0.3) : cs.primary,
++ color: isFinished
++ ? cs.onSurface.withValues(alpha: 0.3)
++ : cs.primary,
+ fontWeight: FontWeight.w700,
- )),
++ ),
+ ),
+ ),
),
- ),
- if (isFinished)
- Icon(Icons.check_circle_rounded,
- size: 16, color: Colors.green.withValues(alpha: 0.5))
- else
- () {
- final progress = widget.lib.getProgress(key);
- return progress > 0
- ? SizedBox(
- width: 16,
- height: 16,
- child: CircularProgressIndicator(
- value: progress,
- strokeWidth: 2.5,
- backgroundColor: cs.surfaceContainerHighest,
- color: cs.primary,
- ),
- )
- : Icon(Icons.circle_outlined,
- size: 16, color: cs.onSurface.withValues(alpha: 0.2));
- }(),
- const SizedBox(width: 8),
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(epTitle ?? title,
+ if (isFinished)
+ Icon(
+ Icons.check_circle_rounded,
+ size: 16,
+ color: Colors.green.withValues(alpha: 0.5),
+ )
+ else
+ () {
+ final progress = widget.lib.getProgress(key);
+ return progress > 0
+ ? SizedBox(
+ width: 16,
+ height: 16,
+ child: CircularProgressIndicator(
+ value: progress,
+ strokeWidth: 2.5,
+ backgroundColor: cs.surfaceContainerHighest,
+ color: cs.primary,
+ ),
+ )
+ : Icon(
+ Icons.circle_outlined,
+ size: 16,
+ color: cs.onSurface.withValues(alpha: 0.2),
+ );
+ }(),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ epTitle ?? title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: tt.bodyMedium?.copyWith(
diff --cc lib/screens/app_shell.dart
index 0d29c55f,7c6f99a3..8fab8947
--- a/lib/screens/app_shell.dart
+++ b/lib/screens/app_shell.dart
@@@ -9,11 -7,10 +9,12 @@@ import 'package:url_launcher/url_launch
import '../providers/auth_provider.dart';
import '../providers/library_provider.dart';
import '../services/audio_player_service.dart';
+ import '../services/volume_key_service.dart';
import '../services/chromecast_service.dart';
import '../services/home_widget_service.dart';
+import '../services/server_task_tracker.dart';
import '../services/sleep_timer_service.dart';
+import '../services/audiobookshelf_update_service.dart';
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:palette_generator/palette_generator.dart';
@@@ -503,21 -352,8 +526,22 @@@ class _AppShellState extends State<AppS
void initState() {
super.initState();
_instance = this;
+ EreaderVolumeNav.ensureHandler();
- if (!widget.startOnAbsorbing) _loadStartScreen();
+ if (AppPlatform.isWeb) {
+ _serverTaskTracker = ServerTaskTracker();
+ _serverUpdateController.addListener(_onServerUpdateChanged);
+ }
+ _paneNavigatorObserver = _PaneNavigatorObserver(_syncPaneRouteState);
+ DesktopWorkspaceNavigator.register(() => _paneNavigatorKey.currentState);
+ DesktopWorkspaceNavigator.exitGuardChanges.addListener(
+ _onDesktopExitGuardChanged,
+ );
+ unawaited(_loadDesktopSidebarPreference());
+ if (AppPlatform.isWeb) {
+ _currentIndex = 0;
+ } else if (!widget.startOnAbsorbing) {
+ _loadStartScreen();
+ }
_ensurePageBuilt(_currentIndex);
_playerHadBook = _player.hasBook;
_wasPlaying = _player.isPlaying;
@@@ -756,13 -576,12 +780,17 @@@
// playback from elsewhere (another tab, the nav long-press) shouldn't
// yank the user into the player.
if (_currentIndex != 2) return;
+ // The ebook reader is a route above this shell, so the tab check can't
+ // see it: audio started from the reader (Find in audiobook with "Keep
+ // reading", volume-key play) must not pop the full player underneath it.
+ if (context.read<LibraryProvider>().readerQuiet) return;
final enabled = await PlayerSettings.getFullScreenPlayer();
- if (!enabled || !mounted || !_player.hasBook) return;
+ if (!enabled) return;
+ await _openExpandedPlayer();
+ }
+
+ Future<void> _openExpandedPlayer() async {
+ if (!mounted || !_player.hasBook || _expandedIsOpen) return;
// Synthesize item data from player state
final itemId = _player.currentItemId;
@@@ -861,10 -684,9 +894,11 @@@
context.read<LibraryProvider>().onAppForegrounded();
SleepTimerService().onAppForegrounded();
AudioPlayerService.onAppForegrounded();
- HomeWidgetService().onAppForegrounded();
- ReviewService.onAppForegrounded();
+ if (!AppPlatform.isWeb) {
+ HomeWidgetService().onAppForegrounded();
+ ReviewService.onAppForegrounded();
+ }
+ unawaited(SettingsSyncService().onAppForegrounded());
_refreshDataForTab(_currentIndex);
// Check auto sleep in case we resumed into the window
SleepTimerService().checkAutoSleep();
@@@ -879,7 -699,8 +913,8 @@@
context.read<LibraryProvider>().onAppBackgrounded();
SleepTimerService().onAppBackgrounded();
AudioPlayerService.onAppBackgrounded();
- HomeWidgetService().onAppBackgrounded();
+ if (!AppPlatform.isWeb) HomeWidgetService().onAppBackgrounded();
+ unawaited(SettingsSyncService().onAppBackgrounded());
}
@override
diff --cc lib/screens/bookmarks_screen.dart
index 86a8a746,c51c3981..ee28bdc9
--- a/lib/screens/bookmarks_screen.dart
+++ b/lib/screens/bookmarks_screen.dart
@@@ -13,9 -15,13 +15,14 @@@ import '../services/scoped_prefs.dart'
import '../widgets/bookmark_detail_dialog.dart';
import '../widgets/card_buttons.dart';
import '../services/download_service.dart';
+ import '../services/ebook_annotation_service.dart';
+ import '../services/ebook_cache.dart';
+ import '../utils/episode_key.dart';
import '../widgets/absorb_page_header.dart';
import '../widgets/adaptive_modal.dart';
+import '../widgets/desktop_page_body.dart';
+ import '../widgets/ebook_router.dart';
+ import '../widgets/quote_share_sheet.dart';
import '../widgets/overlay_toast.dart';
import '../l10n/app_localizations.dart';
@@@ -271,10 -445,31 +446,31 @@@ class _BookmarksScreenState extends Sta
return null;
}
- Future<void> _jumpToBookmark(String itemId, Bookmark bookmark, String bookTitle) async {
+ /// The show a podcast episode belongs to, shown under the episode name so a
+ /// row of episodes from different feeds can be told apart. Null for books.
+ String? _resolveShowTitle(String key) {
+ final ids = splitEpisodeKey(key);
+ if (ids.episodeId == null) return null;
+ final libCache =
+ context.read<LibraryProvider>().absorbingItemCache[ids.itemId];
+ final metadata = (libCache?['media'] as Map<String, dynamic>?)?['metadata']
+ as Map<String, dynamic>?;
+ final title = metadata?['title'] as String?;
+ if (title != null && title.isNotEmpty) return title;
+ final cached = _titleCache[ids.itemId];
+ if (cached != null && cached.isNotEmpty) return cached;
+ final dl = DownloadService().getInfo(key);
+ if (dl.author != null && dl.author!.isNotEmpty) return dl.author;
+ return null;
+ }
+
+ Future<void> _jumpToBookmark(String key, Bookmark bookmark, String bookTitle) async {
final l = AppLocalizations.of(context)!;
final api = context.read<AuthProvider>().apiService;
+ final ids = splitEpisodeKey(key);
+ final itemId = ids.itemId;
+ final episodeId = ids.episodeId;
- final result = await showModalBottomSheet<BookmarkDetailResult>(
+ final result = await showAdaptiveActionMenu<BookmarkDetailResult>(
context: context,
isScrollControlled: true,
showDragHandle: true,
@@@ -282,10 -477,9 +478,11 @@@
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
),
+ desktopWidth: 560,
+ desktopScrollWrap: false,
builder: (ctx) => BookmarkDetailSheet(
itemId: itemId,
+ episodeId: episodeId,
bookmark: bookmark,
api: api,
),
diff --cc lib/screens/chapter_editor_screen.dart
index fb6d2256,534b0a18..d4b7a7f7
--- a/lib/screens/chapter_editor_screen.dart
+++ b/lib/screens/chapter_editor_screen.dart
@@@ -8,7 -9,10 +9,11 @@@ import '../l10n/app_localizations.dart'
import '../providers/auth_provider.dart';
import '../services/api_service.dart';
import '../services/audio_player_service.dart';
+import '../widgets/adaptive_modal.dart';
+ import '../services/chapter_start_finder.dart';
+ import '../services/download_service.dart';
+ import '../services/remote_audio_slice.dart';
+ import '../services/transcription_service.dart';
import '../widgets/overlay_toast.dart';
/// Mutable working copy of one chapter. [uid] is a stable identity that
diff --cc lib/screens/home_screen.dart
index eb4b210a,3f01f5f5..6f2613fe
--- a/lib/screens/home_screen.dart
+++ b/lib/screens/home_screen.dart
@@@ -48,7 -42,9 +48,8 @@@ class HomeScreenState extends State<Hom
final _player = AudioPlayerService();
bool _hideEbookOnly = false;
bool _rectangleCovers = false;
+ int _bookshelfCoverSize = 120;
+ bool _showSubtitles = false;
-
- // ── Batch selection ──
bool _selectionMode = false;
bool _batchActionBusy = false;
final Set<String> _selectedItemIds = {};
@@@ -224,14 -211,13 +225,16 @@@
final results = await Future.wait([
PlayerSettings.getHideEbookOnly(),
PlayerSettings.getRectangleCoversFor(libId),
+ PlayerSettings.getBookshelfCoverSize(),
+ PlayerSettings.getShowSubtitlesFor(libId),
]);
- if (mounted) setState(() {
- _hideEbookOnly = results[0];
- _rectangleCovers = results[1];
- _showSubtitles = results[2];
- });
+ if (mounted)
+ setState(() {
+ _hideEbookOnly = results[0] as bool;
+ _rectangleCovers = results[1] as bool;
+ _bookshelfCoverSize = results[2] as int;
++ _showSubtitles = results[3] as bool;
+ });
}
@override
@@@ -383,11 -349,12 +386,14 @@@
// Cover shape can differ per library; re-resolve after a library switch.
if (lib.selectedLibraryId != _coversLibraryId) {
_coversLibraryId = lib.selectedLibraryId;
+ _resetSelectionState();
PlayerSettings.getRectangleCoversFor(_coversLibraryId).then((v) {
- if (mounted && v != _rectangleCovers) setState(() => _rectangleCovers = v);
+ if (mounted && v != _rectangleCovers)
+ setState(() => _rectangleCovers = v);
});
+ PlayerSettings.getShowSubtitlesFor(_coversLibraryId).then((v) {
+ if (mounted && v != _showSubtitles) setState(() => _showSubtitles = v);
+ });
}
if (lib.isLoading) {
// Reset cache so stale data isn't shown after a user switch
@@@ -878,101 -761,37 +884,102 @@@
entities: entities,
coverAspectRatio: _rectangleCovers ? 2 / 3 : 1.0,
);
+ } else {
+ sectionIcon = _sectionIcons[id] ?? Icons.album_outlined;
+ // Author/series sections don't have book-shaped entities,
+ // so skip the book-oriented SectionDetailSheet for them.
+ if (type != 'authors' && type != 'series') {
+ final sectionLabel = label;
+ titleTap = () => SectionDetailSheet.show(
+ context,
+ title: sectionLabel,
+ icon: sectionIcon,
+ entities: entities,
+ coverAspectRatio: _rectangleCovers ? 2 / 3 : 1.0,
+ );
+ }
}
- }
- return <Widget>[
- SliverToBoxAdapter(
- child: HomeSection(
- title: label,
- icon: sectionIcon,
- entities: entities,
- sectionType: type,
- sectionId: id,
- onTitleTap: _selectionMode ? null : titleTap,
- coverAspectRatio: _rectangleCovers ? 2 / 3 : 1.0,
- showSubtitles: _showSubtitles,
- selectionMode: selectionAvailable && _selectionMode,
- selectedItemIds: _selectedItemIds,
- onSelectionToggle: selectionAvailable
- ? _toggleSelection
- : null,
+ return <Widget>[
+ SliverToBoxAdapter(
+ child: HomeSection(
+ title: label,
+ icon: sectionIcon,
+ entities: entities,
+ sectionType: type,
+ sectionId: id,
+ onTitleTap: _selectionMode ? null : titleTap,
+ coverAspectRatio: _rectangleCovers ? 2 / 3 : 1.0,
+ desktopScale: _desktopShelfScale,
++ showSubtitles: _showSubtitles,
+ selectionMode: selectionAvailable && _selectionMode,
+ selectedItemIds: _selectedItemIds,
+ onSelectionToggle: selectionAvailable
+ ? _toggleSelection
+ : null,
+ ),
),
- ),
- ];
- }),
+ ];
+ }),
- const SliverPadding(padding: EdgeInsets.only(bottom: 100)),
- ],
+ SliverPadding(
+ padding: EdgeInsets.only(bottom: desktop ? 80 : 100),
+ ),
+ ],
+ ),
),
),
- ),
),
),
+ floatingActionButton: !desktop
+ ? null
+ : _selectionMode
+ ? DesktopBatchActionBar(
+ selectedCount: _selectedItemIds.length,
+ selectableCount: selectableHomeItems.length,
+ busy: _batchActionBusy,
+ canQuickMatch:
+ context.watch<AuthProvider>().isAdmin &&
+ !lib.isPodcastLibrary &&
+ !lib.isOffline,
+ canMarkProgress: !lib.isPodcastLibrary,
+ canDelete:
+ context.watch<AuthProvider>().canDelete && !lib.isOffline,
+ onSelectAll: _toggleSelectAll,
+ onClear: _clearSelection,
+ onQuickMatch: () => _runBatchAction(
+ () => DesktopBatchActions.quickMatch(
+ context,
+ _selectedItemIds.toList(),
+ ),
+ ),
+ onMarkFinished: () => _runBatchAction(
+ () => DesktopBatchActions.setFinished(
+ context,
+ _selectedItemIds.toList(),
+ isFinished: true,
+ ),
+ ),
+ onMarkUnfinished: () => _runBatchAction(
+ () => DesktopBatchActions.setFinished(
+ context,
+ _selectedItemIds.toList(),
+ isFinished: false,
+ ),
+ ),
+ onDelete: () => _runBatchAction(
+ () => DesktopBatchActions.delete(
+ context,
+ _selectedItemIds.toList(),
+ ),
+ ),
+ )
+ : DesktopCoverSizeControl(
+ value: _bookshelfCoverSize,
+ onDecrease: () => _changeBookshelfCoverSize(-1),
+ onIncrease: () => _changeBookshelfCoverSize(1),
+ ),
+ floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
);
}
}
@@@ -1242,110 -1035,73 +1249,111 @@@ class _ContinueListeningCardState exten
}
}
- final card = Material(
- color: Colors.transparent,
- borderRadius: BorderRadius.circular(14),
- clipBehavior: Clip.antiAlias,
- child: Ink(
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(14),
- gradient: LinearGradient(
- begin: Alignment.topLeft,
- end: Alignment.bottomRight,
- colors: [cardBgTop, cardBgBottom],
+ final canEdit =
+ !lib.isPodcastLibrary &&
+ !lib.isOffline &&
+ recentEpisode == null &&
- context.watch<AuthProvider>().canUpdateMetadata;
++ isDesktopWorkspace(context) &&
++ (context.watch<AuthProvider?>()?.canUpdateMetadata ?? false);
+ return HoverCoverActions(
+ onMenu: widget.selectionMode ? null : openQuickActions,
+ editItemId: canEdit && !widget.selectionMode ? itemId : null,
+ selectionMode: widget.selectionMode,
+ selected: widget.selected,
+ onSelectionToggle: widget.onSelectionToggle,
+ child: Material(
+ color: Colors.transparent,
+ borderRadius: BorderRadius.circular(14),
+ clipBehavior: Clip.antiAlias,
+ child: Ink(
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(14),
+ gradient: LinearGradient(
+ begin: Alignment.topLeft,
+ end: Alignment.bottomRight,
+ colors: [cardBgTop, cardBgBottom],
+ ),
),
- ),
- child: InkWell(
- onTap: widget.selectionMode ? widget.onSelectionToggle : resume,
- onLongPress: widget.selectionMode ? null : openQuickActions,
- borderRadius: BorderRadius.circular(14),
- child: SizedBox(
- width: 150,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- // Floating cover with a colored glow
- Padding(
- padding: const EdgeInsets.fromLTRB(10, 10, 10, 4),
- child: DecoratedBox(
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(10),
- boxShadow: [
- BoxShadow(
- color: accent.withValues(alpha: 0.45),
- blurRadius: 14,
- spreadRadius: -2,
- offset: const Offset(0, 5),
- ),
- ],
- ),
- child: ClipRRect(
- borderRadius: BorderRadius.circular(10),
- child: AspectRatio(
- aspectRatio: widget.rectangleCovers ? 2 / 3 : 1,
- child: Stack(children: [
- Positioned.fill(
- child: _buildCoverImage(coverUrl, cs, lib.mediaHeaders),
- ),
- if (isCurrentItem && player.isPlaying)
- Positioned(
- right: 6, bottom: 6,
- child: Container(
- padding: const EdgeInsets.all(5),
- decoration: BoxDecoration(
- color: Colors.black.withValues(alpha: 0.55),
- shape: BoxShape.circle,
- ),
- child: const Icon(Icons.graphic_eq_rounded,
- size: 14, color: Colors.white),
+ child: InkWell(
+ onTap: widget.selectionMode && widget.onSelectionToggle != null
+ ? widget.onSelectionToggle
+ : gesturePolicy.continueListeningTapOpensDetails
+ ? openDetails
+ : resume,
+ onLongPress:
+ !widget.selectionMode && gesturePolicy.allowsLongPressShortcuts
+ ? openQuickActions
+ : null,
+ borderRadius: BorderRadius.circular(14),
+ child: SizedBox(
+ width: isDesktopWorkspace(context) ? widget.desktopWidth : 150,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ // Floating cover with a colored glow
+ Padding(
+ padding: const EdgeInsets.fromLTRB(10, 10, 10, 4),
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(10),
+ boxShadow: [
+ BoxShadow(
+ color: accent.withValues(alpha: 0.45),
+ blurRadius: 14,
+ spreadRadius: -2,
+ offset: const Offset(0, 5),
+ ),
+ ],
),
- ),
- if (_isLoading)
- Positioned.fill(
- child: Container(
- color: Colors.black.withValues(alpha: 0.4),
- child: const Center(
- child: SizedBox(
- width: 22, height: 22,
- child: CircularProgressIndicator(
- strokeWidth: 2, color: Colors.white),
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(10),
+ child: AspectRatio(
+ aspectRatio: widget.rectangleCovers ? 2 / 3 : 1,
+ child: Stack(
+ children: [
+ Positioned.fill(
+ child: _buildCoverImage(
+ coverUrl,
+ cs,
+ lib.mediaHeaders,
+ ),
+ ),
+ if (isCurrentItem && player.isPlaying)
+ Positioned(
+ right: 6,
+ bottom: 6,
+ child: Container(
+ padding: const EdgeInsets.all(5),
+ decoration: BoxDecoration(
+ color: Colors.black.withValues(
+ alpha: 0.55,
+ ),
+ shape: BoxShape.circle,
+ ),
+ child: const Icon(
+ Icons.graphic_eq_rounded,
+ size: 14,
+ color: Colors.white,
+ ),
+ ),
+ ),
+ if (_isLoading)
+ Positioned.fill(
+ child: Container(
+ color: Colors.black.withValues(alpha: 0.4),
+ child: const Center(
+ child: SizedBox(
+ width: 22,
+ height: 22,
+ child: CircularProgressIndicator(
+ strokeWidth: 2,
+ color: Colors.white,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
),
),
),
diff --cc lib/screens/library_screen.dart
index 73dee18f,0fee3e22..e9b35e85
--- a/lib/screens/library_screen.dart
+++ b/lib/screens/library_screen.dart
@@@ -21,7 -20,9 +20,11 @@@ import '../widgets/library_search_resul
import '../widgets/podcast_episode_feed.dart';
import '../main.dart' show flatNotifier, gradientIntensityNotifier;
import '../widgets/library_sort_filter_sheet.dart';
+ import '../widgets/desktop_batch_actions.dart';
++import '../widgets/desktop_cover_size_control.dart';
+ import '../widgets/overlay_toast.dart';
import '../widgets/library_books_tab.dart';
++import '../utils/desktop_workspace.dart';
import '../widgets/library_series_tab.dart';
import '../widgets/library_authors_tab.dart';
import '../widgets/library_narrators_tab.dart';
@@@ -43,107 -42,19 +44,70 @@@ import '../widgets/scroll_reveal.dart'
import '../services/scoped_prefs.dart';
import '../services/user_account_service.dart';
import '../l10n/app_localizations.dart';
- import '../utils/app_platform.dart';
- import '../utils/desktop_workspace.dart';
- const double kDesktopLibraryTileMaxExtent = 220;
-
- LinearGradient _libraryBackgroundGradient(
- ColorScheme colorScheme,
- Color scaffoldBackground,
- ) {
- final lowerFade =
- Color.lerp(colorScheme.surface, scaffoldBackground, 0.55) ??
- scaffoldBackground;
- return LinearGradient(
- begin: Alignment.topCenter,
- end: Alignment.bottomCenter,
- stops: const [0.0, 0.22, 0.72, 1.0],
- colors: [
- colorScheme.primary.withValues(alpha: gradientIntensityNotifier.value),
- colorScheme.surface,
- lowerFade,
- scaffoldBackground,
- ],
- );
- }
+ /// Responsive grid column count based on available width and the cover size
+ /// setting; scales up on tablets/iPads.
+ int responsiveGridCount(BuildContext context) => coverGridCount(context);
- class _LibraryHeaderGradientPainter extends CustomPainter {
- const _LibraryHeaderGradientPainter({
- required this.backgroundColor,
- required this.gradient,
- required this.topInset,
- required this.screenHeight,
- });
-
- final Color backgroundColor;
- final LinearGradient gradient;
- final double topInset;
- final double screenHeight;
-
- @override
- void paint(Canvas canvas, Size size) {
- final paintBounds = Offset.zero & size;
- canvas.drawRect(paintBounds, Paint()..color = backgroundColor);
- final shaderBounds = Rect.fromLTWH(0, -topInset, size.width, screenHeight);
- canvas.drawRect(
- paintBounds,
- Paint()..shader = gradient.createShader(shaderBounds),
- );
- }
+ /// Bottom padding for the library tab grids/lists so the last row clears the
+ /// floating tab bar (`Library/Series/Authors/Narrators`) plus the AppShell
+ /// `NavigationBar` once both reappear at the end of a scroll. When the bars
+ /// hide-on-scroll then snap back, the viewport shrinks but the scroll offset
+ /// stays put, so the bottom items end up closer to the pill than steady-state
+ /// math would suggest. This value keeps a comfortable gap even in that case.
-const double libraryGridBottomPadding = 180;
++/// Room under the grid for the playing pill and the nav bar, which the
++/// desktop workspace does not have.
++double libraryGridBottomPadding(BuildContext context) =>
++ isDesktopWorkspace(context) ? 80 : 180;
+
- @override
- bool shouldRepaint(_LibraryHeaderGradientPainter oldDelegate) =>
- backgroundColor != oldDelegate.backgroundColor ||
- gradient != oldDelegate.gradient ||
- topInset != oldDelegate.topInset ||
- screenHeight != oldDelegate.screenHeight;
- }
++const double kDesktopLibraryTileMaxExtent = 220;
+
++/// [crossAxisCount] is the phone column count from the cover size setting;
++/// without it the count falls back to the width. [mainAxisExtent] sizes the
++/// cell outright (subtitled tiles), on every layout.
+SliverGridDelegate libraryGridDelegateForWidth(
+ double width, {
+ required bool desktopWorkspace,
+ required double childAspectRatio,
+ double desktopMaxCrossAxisExtent = kDesktopLibraryTileMaxExtent,
++ int? crossAxisCount,
++ double? mainAxisExtent,
+}) {
+ if (desktopWorkspace) {
+ return SliverGridDelegateWithMaxCrossAxisExtent(
+ maxCrossAxisExtent: desktopMaxCrossAxisExtent,
+ childAspectRatio: childAspectRatio,
++ mainAxisExtent: mainAxisExtent,
+ crossAxisSpacing: 10,
+ mainAxisSpacing: 10,
+ );
+ }
+ return SliverGridDelegateWithFixedCrossAxisCount(
- crossAxisCount: (width / 130).floor().clamp(3, 10),
++ crossAxisCount: crossAxisCount ?? (width / 130).floor().clamp(3, 10),
+ childAspectRatio: childAspectRatio,
++ mainAxisExtent: mainAxisExtent,
+ crossAxisSpacing: 10,
+ mainAxisSpacing: 10,
+ );
+}
+
+SliverGridDelegate libraryGridDelegate(
+ BuildContext context, {
+ required double childAspectRatio,
+ double desktopMaxCrossAxisExtent = kDesktopLibraryTileMaxExtent,
++ int? crossAxisCount,
++ double? mainAxisExtent,
+}) {
+ return libraryGridDelegateForWidth(
+ MediaQuery.sizeOf(context).width,
+ desktopWorkspace: isDesktopWorkspace(context),
+ childAspectRatio: childAspectRatio,
+ desktopMaxCrossAxisExtent: desktopMaxCrossAxisExtent,
++ crossAxisCount: crossAxisCount,
++ mainAxisExtent: mainAxisExtent,
+ );
+}
- /// Bottom padding for the library tab grids/lists so the last row clears the
- /// floating tab bar (`Library/Series/Authors/Narrators`) plus the AppShell
- /// `NavigationBar` once both reappear at the end of a scroll. When the bars
- /// hide-on-scroll then snap back, the viewport shrinks but the scroll offset
- /// stays put, so the bottom items end up closer to the pill than steady-state
- /// math would suggest. The desktop workspace has neither bar.
- double libraryGridBottomPadding(BuildContext context) =>
- isDesktopWorkspace(context) ? 80 : 180;
-
// ─── Sort modes ──────────────────────────────────────────────
enum LibrarySort {
recentlyAdded,
@@@ -544,116 -471,8 +524,23 @@@ class LibraryScreenState extends State<
// ── Cover aspect ratio ──
bool _rectangleCovers = false;
+ bool _showSubtitles = false;
++ // Desktop grid tile size, stepped by the control at the bottom right. Phone
++ // grids take their size from the cover size setting instead.
+ int _bookshelfCoverSize = 120;
- double get _coverAspectRatio => _rectangleCovers ? 2 / 3 : 1.0;
+ double get _desktopTileMaxExtent =>
+ kDesktopLibraryTileMaxExtent * (_bookshelfCoverSize / 120);
+
- bool _selectionMode = false;
- bool _batchActionBusy = false;
- bool _matchingAuthors = false;
- String? _matchingAuthorId;
- int _authorMatchPosition = 0;
- int _authorMatchTotal = 0;
- final Set<String> _selectedItemIds = {};
- int? _lastSelectedVisibleIndex;
-
- void _resetSelectionState() {
- _selectionMode = false;
- _batchActionBusy = false;
- _selectedItemIds.clear();
- _lastSelectedVisibleIndex = null;
- }
-
- void _clearSelection() {
- if (!_selectionMode && _selectedItemIds.isEmpty) return;
- setState(_resetSelectionState);
- }
-
- List<Map<String, dynamic>> _selectableVisibleItems() {
- if (_tabController != null && _currentTab == 2) {
- return _authors
- .where((author) => author['id'] is String)
- .toList(growable: false);
- }
- final lib = context.read<LibraryProvider>();
- return _visibleLibraryItems(lib)
- .where(
- (item) =>
- !item.containsKey('collapsedSeries') && item['id'] is String,
- )
- .toList();
- }
-
- void _toggleSelection(Map<String, dynamic> item, int visibleIndex) {
- final itemId = item['id'] as String?;
- if (itemId == null) return;
- final shiftPressed = HardwareKeyboard.instance.isShiftPressed;
- setState(() {
- _selectionMode = true;
- if (shiftPressed && _lastSelectedVisibleIndex != null) {
- final items = _selectableVisibleItems();
- final start = min(_lastSelectedVisibleIndex!, visibleIndex);
- final end = max(_lastSelectedVisibleIndex!, visibleIndex);
- for (var index = start; index <= end && index < items.length; index++) {
- final rangeItem = items[index];
- if (rangeItem.containsKey('collapsedSeries')) continue;
- final rangeId = rangeItem['id'] as String?;
- if (rangeId != null) _selectedItemIds.add(rangeId);
- }
- } else if (!_selectedItemIds.add(itemId)) {
- _selectedItemIds.remove(itemId);
- }
- _lastSelectedVisibleIndex = visibleIndex;
- });
- }
-
- void _toggleSelectAll() {
- final ids = _selectableVisibleItems()
- .map((item) => item['id'] as String)
- .toSet();
- setState(() {
- _selectionMode = true;
- if (ids.isNotEmpty && _selectedItemIds.containsAll(ids)) {
- _selectedItemIds.removeAll(ids);
- } else {
- _selectedItemIds.addAll(ids);
- }
- _lastSelectedVisibleIndex = null;
- });
- }
-
- Future<void> _runBatchAction(Future<bool?> Function() action) async {
- if (_batchActionBusy) return;
- final visibleIds = _selectableVisibleItems()
- .map((item) => item['id'] as String)
- .toSet();
- setState(() {
- _selectedItemIds.retainAll(visibleIds);
- if (_selectedItemIds.isEmpty) {
- _resetSelectionState();
- } else {
- _batchActionBusy = true;
- }
- });
- if (_selectedItemIds.isEmpty) return;
- final success = await action();
- if (!mounted) return;
- setState(() {
- _batchActionBusy = false;
- if (success == true) _resetSelectionState();
- });
- }
-
+ void _changeBookshelfCoverSize(int direction) {
+ final sizes = PlayerSettings.bookshelfCoverSizes;
+ final currentIndex = sizes.indexOf(_bookshelfCoverSize);
+ final nextIndex = (currentIndex + direction).clamp(0, sizes.length - 1);
+ final next = sizes[nextIndex];
+ if (next == _bookshelfCoverSize) return;
+ setState(() => _bookshelfCoverSize = next);
+ PlayerSettings.setBookshelfCoverSize(next);
+ }
+ double get _coverAspectRatio => _rectangleCovers ? 2 / 3 : 1.0;
// ── Scroll-to-hide bars ──
/// Continuous 0..1 reveal: 1 = header + nav fully visible, 0 = both hidden.
@@@ -768,7 -601,7 +669,10 @@@
lib.selectedLibraryId != null) {
_lastLibraryId = lib.selectedLibraryId;
_loadGeneration++;
- // Cover shape can differ per library.
+ // Cover shape and subtitles can differ per library.
++ PlayerSettings.getBookshelfCoverSize().then((v) {
++ if (mounted && v != _bookshelfCoverSize) setState(() => _bookshelfCoverSize = v);
++ });
PlayerSettings.getRectangleCoversFor(lib.selectedLibraryId).then((v) {
if (mounted && v != _rectangleCovers)
setState(() => _rectangleCovers = v);
@@@ -2721,9 -2599,8 +2670,12 @@@
final cs = Theme.of(context).colorScheme;
final tt = Theme.of(context).textTheme;
final l = AppLocalizations.of(context)!;
+ final desktopWorkspace = isDesktopWorkspace(context);
++ // The bars the reveal driver hides are the phone's; the desktop
++ // workspace pins its header and has no floating pill.
+ _revealDriver.setEnabled(!desktopWorkspace);
final scaffoldBg = Theme.of(context).scaffoldBackgroundColor;
+ final lowerFade = Color.lerp(cs.surface, scaffoldBg, 0.55) ?? scaffoldBg;
// Watch LibraryProvider so this screen rebuilds when the active library
// or its data changes; the actual lib object is consumed inside
// _buildHeaderSliver via context.watch.
@@@ -2760,13 -2636,11 +2711,15 @@@
final selectionAvailable =
authorSelectionAvailable || bookSelectionAvailable;
if (!selectionAvailable && _selectionMode) _resetSelectionState();
+ final showCoverControl =
+ desktopWorkspace &&
+ !_isInSearchMode &&
+ (hasTabs ? _currentTab != 3 : _podcastView == 0);
- final selectableItems = selectionAvailable
+ final selectableItems = selectionAvailable && _selectionMode
? _selectableVisibleItems()
: const <Map<String, dynamic>>[];
+ // Drop ids that scrolled out of the current filter so the count and the
+ // select-all state always describe what is on screen.
if (_selectionMode) {
_selectedItemIds.retainAll(
selectableItems.map((item) => item['id'] as String).toSet(),
@@@ -2776,6 -2650,66 +2729,72 @@@
return Scaffold(
backgroundColor: scaffoldBg,
+ floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
+ floatingActionButton: !_selectionMode
- ? null
++ ? (showCoverControl
++ ? DesktopCoverSizeControl(
++ value: _bookshelfCoverSize,
++ onDecrease: () => _changeBookshelfCoverSize(-1),
++ onIncrease: () => _changeBookshelfCoverSize(1),
++ )
++ : null)
+ : authorSelectionAvailable
+ ? DesktopBatchActionBar(
+ selectedCount: _selectedItemIds.length,
+ selectableCount: selectableCount,
+ busy: _batchActionBusy,
+ busyLabel: _authorMatchTotal > 0
+ ? '$_authorMatchPosition/$_authorMatchTotal'
+ : null,
+ canQuickMatch: true,
+ canMarkProgress: false,
+ canDelete: false,
+ onSelectAll: _toggleSelectAll,
+ onClear: _clearSelection,
+ onQuickMatch: () =>
+ _runBatchAction(() => _quickMatchAuthors(_selectedAuthors())),
+ onMarkFinished: () {},
+ onMarkUnfinished: () {},
+ onDelete: () {},
+ )
+ : bookSelectionAvailable
+ ? DesktopBatchActionBar(
+ selectedCount: _selectedItemIds.length,
+ selectableCount: selectableCount,
+ busy: _batchActionBusy,
+ canQuickMatch: auth.isAdmin && !libWatch.isPodcastLibrary,
+ canMarkProgress: !libWatch.isPodcastLibrary,
+ canDelete: auth.canDelete,
+ onSelectAll: _toggleSelectAll,
+ onClear: _clearSelection,
+ onQuickMatch: () => _runBatchAction(
+ () => DesktopBatchActions.quickMatch(
+ context,
+ _selectedItemIds.toList(),
+ ),
+ ),
+ onMarkFinished: () => _runBatchAction(
+ () => DesktopBatchActions.setFinished(
+ context,
+ _selectedItemIds.toList(),
+ isFinished: true,
+ ),
+ ),
+ onMarkUnfinished: () => _runBatchAction(
+ () => DesktopBatchActions.setFinished(
+ context,
+ _selectedItemIds.toList(),
+ isFinished: false,
+ ),
+ ),
+ onDelete: () => _runBatchAction(
+ () => DesktopBatchActions.delete(
+ context,
+ _selectedItemIds.toList(),
+ ),
+ ),
+ )
+ : null,
body: Stack(
children: [
if (!flatNotifier.value)
@@@ -2836,10 -2786,7 +2871,7 @@@
},
),
),
- if (hasTabs &&
- !_isInSearchMode &&
- !desktopWorkspace &&
- !_selectionMode)
- if (hasTabs && !_isInSearchMode)
++ if (hasTabs && !_isInSearchMode && !desktopWorkspace)
Positioned(
left: 0,
right: 0,
@@@ -3014,14 -2882,48 +2967,50 @@@
!lib.isOffline &&
!_isInSearchMode &&
(canSelectAuthors ||
- (desktop &&
- (_tabController == null
- ? _podcastView == 0
- : _currentTab == 0)));
+ (_tabController == null ? _podcastView == 0 : _currentTab == 0));
+ final libraryName =
+ lib.selectedLibrary?['name'] as String? ?? l.libraryFallback;
+ final topInset = MediaQuery.of(context).padding.top;
+ final screenH = MediaQuery.of(context).size.height;
+ final headerBackground = flatNotifier.value
+ ? ColoredBox(color: scaffoldBg)
+ : ClipRect(
+ child: OverflowBox(
+ maxHeight: screenH,
+ minHeight: 0,
+ alignment: Alignment.topCenter,
+ child: Transform.translate(
+ offset: Offset(0, -topInset),
+ child: SizedBox(
+ height: screenH,
+ width: double.infinity,
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ color: scaffoldBg,
+ gradient: LinearGradient(
+ begin: Alignment.topCenter,
+ end: Alignment.bottomCenter,
+ stops: const [0.0, 0.22, 0.72, 1.0],
+ colors: [
+ cs.primary.withValues(
+ alpha: gradientIntensityNotifier.value,
+ ),
+ cs.surface,
+ lowerFade,
+ scaffoldBg,
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
++ final desktop = isDesktopWorkspace(context);
return SliverAppBar(
- floating: true,
- snap: true,
+ floating: !desktop,
+ snap: !desktop,
+ pinned: desktop,
// primary: false disables Material's automatic status
// bar padding so the header doesn't get inset twice
// (we already wrap the whole NestedScrollView in
@@@ -3047,7 -2949,6 +3036,7 @@@
children: [
AbsorbPageHeader(
title: l.libraryTitle,
- showBranding: !isDesktopWorkspace(context),
++ showBranding: !desktop,
trailing: OfflineStatusIcon(
onTapWhenOnline: () {
lib.setManualOffline(true);
@@@ -3064,173 -2965,123 +3053,175 @@@
},
),
actions: [
- if (hasMultipleLibraries)
- GestureDetector(
- onTap: () => showLibraryPickerSheet(context, lib),
- child: Container(
- padding: const EdgeInsets.symmetric(
- horizontal: 10,
- vertical: 5,
- ),
- decoration: BoxDecoration(
- color: cs.onSurface.withValues(alpha: 0.06),
- borderRadius: BorderRadius.circular(20),
- border: Border.all(
- color: cs.onSurface.withValues(alpha: 0.08),
- ),
- ),
- child: SizedBox(
- height: 20,
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(
- lib.isPodcastLibrary
- ? Icons.podcasts_rounded
- : Icons.auto_stories_rounded,
- size: 18,
- color: cs.onSurfaceVariant,
+ if (hasMultipleLibraries)
+ GestureDetector(
+ onTap: () => showLibraryPickerSheet(context, lib),
+ child: Container(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 10,
+ vertical: 5,
+ ),
+ decoration: BoxDecoration(
+ color: cs.onSurface.withValues(alpha: 0.06),
+ borderRadius: BorderRadius.circular(20),
+ border: Border.all(
+ color: cs.onSurface.withValues(alpha: 0.08),
),
- const SizedBox(width: 6),
- ConstrainedBox(
- constraints: const BoxConstraints(
- maxWidth: 140,
- ),
- child: Text(
- libraryName,
- style: TextStyle(
- fontSize: 13,
- fontWeight: FontWeight.w600,
+ ),
+ child: SizedBox(
+ height: 20,
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(
+ lib.isPodcastLibrary
+ ? Icons.podcasts_rounded
+ : Icons.auto_stories_rounded,
+ size: 18,
color: cs.onSurfaceVariant,
),
- overflow: TextOverflow.ellipsis,
- maxLines: 1,
- ),
- ),
- const SizedBox(width: 4),
- Icon(
- Icons.unfold_more_rounded,
- size: 18,
- color: cs.onSurfaceVariant,
+ const SizedBox(width: 6),
+ ConstrainedBox(
+ constraints: const BoxConstraints(
+ maxWidth: 140,
+ ),
+ child: Text(
+ libraryName,
+ style: TextStyle(
+ fontSize: 13,
+ fontWeight: FontWeight.w600,
+ color: cs.onSurfaceVariant,
+ ),
+ overflow: TextOverflow.ellipsis,
+ maxLines: 1,
+ ),
+ ),
+ const SizedBox(width: 4),
+ Icon(
+ Icons.unfold_more_rounded,
+ size: 18,
+ color: cs.onSurfaceVariant,
+ ),
+ ],
),
- ],
+ ),
),
),
- ),
- ),
- if (canSelectItems)
- Tooltip(
- message: _selectionMode
- ? l.downloadsCancelSelection
- : l.downloadsSelect,
- child: IconButton(
- onPressed: _batchActionBusy
- ? null
- : _selectionMode
- ? _clearSelection
- : () => setState(() => _selectionMode = true),
- icon: Icon(
- _selectionMode
- ? Icons.close_rounded
- : Icons.library_add_check_rounded,
+ if (canSelectItems)
+ Tooltip(
+ message: _selectionMode
+ ? l.downloadsCancelSelection
+ : l.downloadsSelect,
+ child: IconButton(
+ onPressed: _batchActionBusy
+ ? null
+ : _selectionMode
+ ? _clearSelection
+ : () => setState(() => _selectionMode = true),
+ icon: Icon(
+ _selectionMode
+ ? Icons.close_rounded
+ : Icons.library_add_check_rounded,
+ ),
+ ),
),
- ),
- ),
- ],
+ ],
),
- Padding(
- padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
- child: SearchBar(
- // Same GlobalKey on whichever SearchBar gets the shared
- // focus, so when _isInSearchMode toggles and the tree
- // swaps from tabbed -> search results, Flutter re-parents
- // the existing Element instead of destroying and
- // recreating it. Keeps focus + keyboard alive.
- key: useSharedFocus ? _searchBarKey : null,
- controller: _searchController,
- // Only the active tab's SearchBar binds to the screen-
- // level focus node. Inactive tabs' SearchBars use their
- // own internal focus so multiple instances in the
- // IndexedStack don't fight over the same FocusNode (the
- // bug that left tap-to-focus dead until you switched
- // libraries to force a state reset).
- focusNode: useSharedFocus ? _focusNode : null,
- hintText: lib.isPodcastLibrary
- ? l.librarySearchShowsHint
- : l.librarySearchBooksHint,
- leading: const Padding(
- padding: EdgeInsets.only(left: 8),
- child: Icon(Icons.search_rounded),
- ),
- trailing: [
- if (_searchController.text.isNotEmpty)
- IconButton(
- icon: const Icon(Icons.clear_rounded),
- onPressed: () {
- _searchController.clear();
- _onSearchChanged('');
- _focusNode.unfocus();
- },
- ),
- ],
- onChanged: _onSearchChanged,
- padding: const WidgetStatePropertyAll(
- EdgeInsets.symmetric(horizontal: 8),
- ),
- side: WidgetStatePropertyAll(
- BorderSide(color: cs.onSurface.withValues(alpha: 0.08)),
- ),
- ),
+ Builder(
+ builder: (context) {
+ final searchBar = SearchBar(
+ // Same GlobalKey on whichever SearchBar gets the shared
+ // focus, so when _isInSearchMode toggles and the tree
+ // swaps from tabbed -> search results, Flutter re-parents
+ // the existing Element instead of destroying and
+ // recreating it. Keeps focus + keyboard alive.
+ key: useSharedFocus ? _searchBarKey : null,
+ controller: _searchController,
+ // Only the active tab's SearchBar binds to the screen-
+ // level focus node. Inactive tabs' SearchBars use their
+ // own internal focus so multiple instances in the
+ // IndexedStack don't fight over the same FocusNode (the
+ // bug that left tap-to-focus dead until you switched
+ // libraries to force a state reset).
+ focusNode: useSharedFocus ? _focusNode : null,
+ hintText: lib.isPodcastLibrary
+ ? l.librarySearchShowsHint
+ : l.librarySearchBooksHint,
+ leading: const Padding(
+ padding: EdgeInsets.only(left: 8),
+ child: Icon(Icons.search_rounded),
+ ),
+ trailing: [
+ if (_searchController.text.isNotEmpty)
+ IconButton(
+ icon: const Icon(Icons.clear_rounded),
+ onPressed: () {
+ _searchController.clear();
+ _onSearchChanged('');
+ _focusNode.unfocus();
+ },
+ ),
+ ],
+ onChanged: _onSearchChanged,
+ padding: const WidgetStatePropertyAll(
+ EdgeInsets.symmetric(horizontal: 8),
+ ),
+ side: WidgetStatePropertyAll(
+ BorderSide(color: cs.onSurface.withValues(alpha: 0.08)),
+ ),
+ );
+ if (!desktop) {
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
+ child: searchBar,
+ );
+ }
++ // Desktop: the tab pill sits next to the search box, and a
++ // refresh chip stands in for pull to refresh.
+ final hasBookTabs =
+ _tabController != null && !_isInSearchMode;
+ final showsPodcastPill =
+ !hasBookTabs &&
+ lib.isPodcastLibrary &&
+ !_isInSearchMode;
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
+ child: Row(
+ children: [
+ Flexible(
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 560),
+ child: searchBar,
+ ),
+ ),
+ if (hasBookTabs) ...[
+ const SizedBox(width: 12),
+ _buildFloatingTabBar(cs, floating: false),
+ ],
+ if (showsPodcastPill) ...[
+ const SizedBox(width: 12),
+ _buildPodcastViewPill(cs, floating: false),
+ if (context.read<AuthProvider>().isAdmin) ...[
+ const SizedBox(width: 8),
+ _buildFloatingManageButton(cs),
+ ],
+ ],
+ const Spacer(),
+ if (!lib.isOffline)
+ Tooltip(
+ message: l.refreshTooltip,
+ child: IconButton(
+ onPressed: _refreshCurrentTab,
+ icon: Icon(
+ Icons.refresh_rounded,
+ color: cs.onSurfaceVariant,
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+ },
),
// Item count + filter badge row
if (!_isInSearchMode) _buildInfoRow(cs, tt, l),
@@@ -3244,166 -3095,91 +3235,121 @@@
// Shows | Episodes switcher for podcast libraries, styled like the book
// libraries' floating tab pills.
- Widget _buildPodcastViewPill(ColorScheme cs) {
+ Widget _buildPodcastViewPill(ColorScheme cs, {bool floating = true}) {
final l = AppLocalizations.of(context)!;
final labels = [l.appShellShowsTab, l.libraryTabEpisodes];
- final pill = Container(
- padding: const EdgeInsets.all(4),
- decoration: BoxDecoration(
- color: floating
- ? cs.surface.withValues(alpha: 0.6)
- : cs.surfaceContainerLow,
- borderRadius: BorderRadius.circular(24),
- border: Border.all(
- color: floating
- ? cs.primary.withValues(alpha: 0.25)
- : cs.outlineVariant.withValues(alpha: 0.45),
++ // Inline in the desktop header the pill is opaque: nothing scrolls under
++ // it, so the blur would only cost a saveLayer.
++ if (!floating) {
++ return Container(
++ padding: const EdgeInsets.all(4),
++ decoration: BoxDecoration(
++ color: cs.surfaceContainerLow,
++ borderRadius: BorderRadius.circular(24),
++ border: Border.all(color: cs.outlineVariant.withValues(alpha: 0.45)),
+ ),
- ),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: List.generate(labels.length, (i) {
- final active = _podcastView == i;
- return GestureDetector(
- onTap: () {
- if (!active) {
- setState(() {
- _podcastView = i;
- _resetSelectionState();
- });
- PlayerSettings.setPodcastView(i);
- } else if (i == 0) {
- // Re-tap on the active Shows pill opens the sort sheet,
- // same as the book libraries' pills.
- _showSortFilterSheet(context, cs, Theme.of(context).textTheme);
- }
- },
- child: AnimatedContainer(
- duration: const Duration(milliseconds: 200),
- curve: Curves.easeInOut,
- padding: EdgeInsets.symmetric(
- horizontal: active ? 14 : 12,
- vertical: 8,
- ),
- decoration: BoxDecoration(
- color: active
- ? cs.primary.withValues(alpha: 0.15)
- : Colors.transparent,
- borderRadius: BorderRadius.circular(20),
- ),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(
- labels[i],
- maxLines: 1,
- softWrap: false,
- style: TextStyle(
- fontSize: 13,
- fontWeight: active ? FontWeight.w700 : FontWeight.w500,
- color: active ? cs.primary : cs.onSurfaceVariant,
- ),
- ),
- if (active && i == 0) ...[
- const SizedBox(width: 4),
- Icon(Icons.sort_rounded, size: 14, color: cs.primary),
- ],
- ],
- ),
- ),
- );
- }),
- ),
- );
- if (!floating) return pill;
++ child: _podcastViewPillRow(cs, labels),
++ );
++ }
return ClipRRect(
borderRadius: BorderRadius.circular(24),
child: BackdropFilter(
filter: ui.ImageFilter.blur(sigmaX: 20, sigmaY: 20),
- child: pill,
+ child: Container(
+ padding: const EdgeInsets.all(4),
+ decoration: BoxDecoration(
+ color: cs.surface.withValues(alpha: 0.6),
+ borderRadius: BorderRadius.circular(24),
+ border: Border.all(color: cs.primary.withValues(alpha: 0.25)),
+ ),
- child: Row(
++ child: _podcastViewPillRow(cs, labels),
++ ),
+ ),
+ );
+ }
+
++ Widget _podcastViewPillRow(ColorScheme cs, List<String> labels) {
++ return Builder(builder: (context) {
++ return Row(
+ mainAxisSize: MainAxisSize.min,
+ children: List.generate(labels.length, (i) {
+ final active = _podcastView == i;
+ return GestureDetector(
+ onTap: () {
+ if (!active) {
+ setState(() => _podcastView = i);
+ PlayerSettings.setPodcastView(i);
+ } else if (i == 0) {
+ // Re-tap on the active Shows pill opens the sort sheet,
+ // same as the book libraries' pills.
+ _showSortFilterSheet(
+ context,
+ cs,
+ Theme.of(context).textTheme,
+ );
+ }
+ },
+ child: AnimatedContainer(
+ duration: const Duration(milliseconds: 200),
+ curve: Curves.easeInOut,
+ padding: EdgeInsets.symmetric(
+ horizontal: active ? 14 : 12,
+ vertical: 8,
+ ),
+ decoration: BoxDecoration(
+ color: active
+ ? cs.primary.withValues(alpha: 0.15)
+ : Colors.transparent,
+ borderRadius: BorderRadius.circular(20),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ labels[i],
+ maxLines: 1,
+ softWrap: false,
+ style: TextStyle(
+ fontSize: 13,
+ fontWeight: active
+ ? FontWeight.w700
+ : FontWeight.w500,
+ color: active ? cs.primary : cs.onSurfaceVariant,
+ ),
+ ),
+ if (active && i == 0) ...[
+ const SizedBox(width: 4),
+ Icon(Icons.sort_rounded, size: 14, color: cs.primary),
+ ],
+ ],
+ ),
+ ),
+ );
+ }),
- ),
- ),
- ),
- );
++ );
++ });
+ }
+
- Widget _buildFloatingTabBar(ColorScheme cs) {
+ Widget _buildFloatingTabBar(ColorScheme cs, {bool floating = true}) {
final l = AppLocalizations.of(context)!;
final labels = [
l.libraryTabLibrary,
l.libraryTabSeries,
l.libraryTabAuthors,
l.libraryTabNarrators,
- if (_showLists) 'Lists',
+ 'Lists',
];
- final pill = Container(
- padding: const EdgeInsets.all(4),
- decoration: BoxDecoration(
- color: floating
- ? cs.surface.withValues(alpha: 0.6)
- : cs.surfaceContainerLow,
- borderRadius: BorderRadius.circular(24),
- border: Border.all(
- color: floating
- ? cs.primary.withValues(alpha: 0.25)
- : cs.outlineVariant.withValues(alpha: 0.45),
- ),
- ),
- child: FittedBox(
- fit: BoxFit.scaleDown,
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: List.generate(labels.length, (i) {
- final active = _currentTab == i;
- return GestureDetector(
- onTap: () {
- if (active) {
- _showSortFilterSheet(
- context,
- cs,
- Theme.of(context).textTheme,
- );
- } else {
- _tabController?.animateTo(i);
- }
- },
- child: AnimatedContainer(
- duration: const Duration(milliseconds: 200),
- curve: Curves.easeInOut,
- padding: EdgeInsets.symmetric(
- horizontal: active ? 14 : 12,
- vertical: 8,
- ),
- decoration: BoxDecoration(
- color: active
- ? cs.primary.withValues(alpha: 0.15)
- : Colors.transparent,
- borderRadius: BorderRadius.circular(20),
- ),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(
- labels[i],
- maxLines: 1,
- softWrap: false,
- style: TextStyle(
- fontSize: 13,
- fontWeight: active ? FontWeight.w700 : FontWeight.w500,
- color: active ? cs.primary : cs.onSurfaceVariant,
- ),
- ),
- if (active) ...[
- const SizedBox(width: 4),
- Icon(Icons.sort_rounded, size: 14, color: cs.primary),
- ],
- ],
- ),
- ),
- );
- }),
++ if (!floating) {
++ return Container(
++ padding: const EdgeInsets.all(4),
++ decoration: BoxDecoration(
++ color: cs.surfaceContainerLow,
++ borderRadius: BorderRadius.circular(24),
++ border: Border.all(color: cs.outlineVariant.withValues(alpha: 0.45)),
+ ),
- ),
- );
- if (!floating) return pill;
++ child: _tabPillRow(cs, labels),
++ );
++ }
return Center(
child: Padding(
// Inset from the screen edges; the FittedBox below scales the whole
@@@ -3414,13 -3190,83 +3360,87 @@@
borderRadius: BorderRadius.circular(24),
child: BackdropFilter(
filter: ui.ImageFilter.blur(sigmaX: 20, sigmaY: 20),
- child: pill,
+ child: Container(
+ padding: const EdgeInsets.all(4),
+ decoration: BoxDecoration(
+ color: cs.surface.withValues(alpha: 0.6),
+ borderRadius: BorderRadius.circular(24),
+ border: Border.all(color: cs.primary.withValues(alpha: 0.25)),
+ ),
- child: FittedBox(
++ child: _tabPillRow(cs, labels),
++ ),
+ ),
+ ),
+ ),
+ );
+ }
+
++ Widget _tabPillRow(ColorScheme cs, List<String> labels) {
++ return FittedBox(
+ fit: BoxFit.scaleDown,
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: List.generate(labels.length, (i) {
+ final active = _currentTab == i;
+ return GestureDetector(
+ onTap: () {
+ if (active) {
+ _showSortFilterSheet(
+ context,
+ cs,
+ Theme.of(context).textTheme,
+ );
+ } else {
+ _tabController?.animateTo(i);
+ }
+ },
+ child: AnimatedContainer(
+ duration: const Duration(milliseconds: 200),
+ curve: Curves.easeInOut,
+ padding: EdgeInsets.symmetric(
+ horizontal: active ? 14 : 12,
+ vertical: 8,
+ ),
+ decoration: BoxDecoration(
+ color: active
+ ? cs.primary.withValues(alpha: 0.15)
+ : Colors.transparent,
+ borderRadius: BorderRadius.circular(20),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ labels[i],
+ maxLines: 1,
+ softWrap: false,
+ style: TextStyle(
+ fontSize: 13,
+ fontWeight: active
+ ? FontWeight.w700
+ : FontWeight.w500,
+ color: active
+ ? cs.primary
+ : cs.onSurfaceVariant,
+ ),
+ ),
+ if (active) ...[
+ const SizedBox(width: 4),
+ Icon(
+ Icons.sort_rounded,
+ size: 14,
+ color: cs.primary,
+ ),
+ ],
+ ],
+ ),
+ ),
+ );
+ }),
+ ),
- ),
- ),
- ),
- ),
- ),
+ );
+ }
+
Future<void> _openUpcomingReleases() async {
final saved = await PlayerSettings.getAudibleRegion();
if (saved.isEmpty) {
@@@ -3713,8 -3523,7 +3713,8 @@@
// ═══════════════════════════════════════════════════════════════
Widget _buildGrid(Widget headerSliver) {
final lib = context.watch<LibraryProvider>();
- final selectionAvailable = isDesktopWorkspace(context) && !lib.isOffline;
return LibraryBooksTab(
++ desktopMaxCrossAxisExtent: _desktopTileMaxExtent,
items: _visibleLibraryItems(lib),
isLoadingPage: _isLoadingPage,
hasMore: _hasMore,
@@@ -3767,6 -3791,6 +3982,7 @@@
// ═══════════════════════════════════════════════════════════════
Widget _buildAuthorsGrid(Widget headerSliver) {
return LibraryAuthorsTab(
++ desktopMaxCrossAxisExtent: _desktopTileMaxExtent,
authors: _authors,
isLoadingAuthors: _isLoadingAuthors,
authorsLoaded: _authorsLoaded,
diff --cc lib/screens/settings_screen.dart
index 868f6aa6,ba389917..9fcd298d
--- a/lib/screens/settings_screen.dart
+++ b/lib/screens/settings_screen.dart
@@@ -58,175 -50,32 +50,161 @@@ import '../widgets/welcome_sheet.dart'
import '../widgets/rmab_config_sheet.dart';
import '../widgets/server_connection_editor.dart';
import '../widgets/server_admin_status_badges.dart';
- import '../widgets/desktop_wheel_scroll_region.dart';
import '../l10n/app_localizations.dart';
++import '../utils/desktop_workspace.dart';
++import '../widgets/desktop_wheel_scroll_region.dart';
+
+class _SettingsSectionDestination {
+ final String id;
+ final IconData icon;
+ final String label;
+
+ const _SettingsSectionDestination(this.id, this.icon, this.label);
+}
+
- Future<T?> _showAdaptiveSettingsSurface<T>({
- required BuildContext context,
- required Widget Function(BuildContext context, bool desktopMode) builder,
- double maxWidth = 620,
- }) {
- final cs = Theme.of(context).colorScheme;
- return showAdaptiveActionMenu<T>(
- context: context,
- desktopWidth: maxWidth,
- desktopMaxHeightFraction: 0.86,
- desktopScrollWrap: false,
- isScrollControlled: true,
- useSafeArea: true,
- backgroundColor: cs.surfaceContainerHigh,
- shape: const RoundedRectangleBorder(
- borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
- ),
- builder: (ctx) => builder(ctx, ModalSurface.isDesktopOf(ctx)),
- );
- }
-
++/// Desktop: a section list on the left as a table of contents, the
++/// settings on the right. Off the desktop workspace it is just [child].
+class _SettingsAdaptiveFrame extends StatelessWidget {
+ final bool desktopMode;
+ final String? selectedSection;
+ final List<_SettingsSectionDestination> destinations;
+ final ValueChanged<String> onSectionSelected;
+ final ScrollController scrollController;
+ final Widget child;
+
+ const _SettingsAdaptiveFrame({
+ required this.desktopMode,
+ required this.selectedSection,
+ required this.destinations,
+ required this.onSectionSelected,
+ required this.scrollController,
+ required this.child,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ if (!desktopMode) return child;
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ return Row(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ SizedBox(
+ width: 224,
+ child: Material(
+ color: cs.surface.withValues(alpha: 0.38),
+ child: ListView(
+ padding: const EdgeInsets.fromLTRB(14, 20, 14, 20),
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(12, 0, 12, 12),
+ child: Text(
+ AppLocalizations.of(context)!.settingsTitle,
+ style: tt.labelMedium?.copyWith(
+ color: cs.onSurfaceVariant,
+ fontWeight: FontWeight.w700,
+ letterSpacing: 0.8,
+ ),
+ ),
+ ),
+ for (final destination in destinations)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 4),
+ child: Material(
+ color: selectedSection == destination.id
+ ? cs.primary.withValues(alpha: 0.14)
+ : Colors.transparent,
+ borderRadius: BorderRadius.circular(11),
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ onTap: () => onSectionSelected(destination.id),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ vertical: 11,
+ ),
+ child: Row(
+ children: [
+ Icon(
+ destination.icon,
+ size: 19,
+ color: selectedSection == destination.id
+ ? cs.primary
+ : cs.onSurfaceVariant,
+ ),
+ const SizedBox(width: 11),
+ Expanded(
+ child: Text(
+ destination.label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.bodyMedium?.copyWith(
+ color: selectedSection == destination.id
+ ? cs.onSurface
+ : cs.onSurfaceVariant,
+ fontWeight:
+ selectedSection == destination.id
+ ? FontWeight.w700
+ : FontWeight.w500,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ VerticalDivider(
+ width: 1,
+ thickness: 1,
+ color: cs.outlineVariant.withValues(alpha: 0.35),
+ ),
+ Expanded(
+ child: DesktopWheelScrollRegion(
+ controller: scrollController,
+ child: Align(
+ alignment: Alignment.topCenter,
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 880),
+ child: SizedBox.expand(child: child),
+ ),
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+}
class SettingsScreen extends StatefulWidget {
const SettingsScreen({super.key});
@override
- State<SettingsScreen> createState() => _SettingsScreenState();
+ State<SettingsScreen> createState() => SettingsScreenState();
}
-class _SettingsScreenState extends State<SettingsScreen> {
+class SettingsScreenState extends State<SettingsScreen> {
static const _isPlayStoreBuild = bool.fromEnvironment('PLAYSTORE_BUILD');
static const _isGithubBuild = bool.fromEnvironment('GITHUB_BUILD');
+ static const _isDevBuild = bool.fromEnvironment('DEV_BUILD');
// Distribution label shown next to the version. The F-Droid build passes
- // neither define, so it falls through here.
- static String get _flavorLabel => _isGithubBuild
- ? 'GitHub'
- : _isPlayStoreBuild
- ? 'Play Store'
- : 'F-Droid';
+ // no define, so it falls through here.
+ static String get _flavorLabel => _isDevBuild
+ ? 'Dev'
+ : _isGithubBuild ? 'GitHub' : _isPlayStoreBuild ? 'Play Store' : 'F-Droid';
+
+ String _versionLine(AppLocalizations l) {
+ final base = Platform.isIOS
+ ? l.appVersionFormat(_appVersion)
+ : '$_flavorLabel - $_appVersion';
+ final beta = betaNumberFor(_appVersion);
+ return beta == null ? base : '$base (${l.betaLabel(beta)})';
+ }
AutoRewindSettings _rewindSettings = const AutoRewindSettings();
double _defaultSpeed = 1.0;
@@@ -364,16 -206,12 +335,35 @@@
AutoSleepSettings _autoSleepSettings = const AutoSleepSettings();
String _appVersion = '';
String? _expandedSection;
- final ScrollController _settingsScrollController = ScrollController();
final Map<String, GlobalKey> _sectionKeys = {};
+ final TextEditingController _settingsSearchController = TextEditingController();
+ String _settingsQuery = '';
++ /// The desktop sidebar's account button opens the same sheet the profile
++ /// card does.
+ void showAccountMenu() {
+ if (mounted) _showAccountSheet(context);
+ }
+
- GlobalKey _keyFor(String section) =>
- _sectionKeys.putIfAbsent(section, () => GlobalKey());
+ GlobalKey _keyFor(String section) => _sectionKeys.putIfAbsent(section, () => GlobalKey());
+
++ final _settingsScrollController = ScrollController();
++
++ /// The desktop sidebar: open the section and bring it into view.
++ void _jumpToSection(String section) {
++ setState(() => _expandedSection = section);
++ WidgetsBinding.instance.addPostFrameCallback((_) {
++ final ctx = _keyFor(section).currentContext;
++ if (!mounted || ctx == null) return;
++ Scrollable.ensureVisible(
++ ctx,
++ alignment: 0.02,
++ duration: const Duration(milliseconds: 220),
++ curve: Curves.easeOut,
++ );
++ });
++ }
+
void _onSectionExpanded(String section, bool expanded) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
@@@ -461,9 -292,8 +444,9 @@@
SocketService().removeItemsChangedListener(_onServerItemsChanged);
_issueBadgeDebounce?.cancel();
PlayerSettings.settingsChanged.removeListener(_onExternalSettingsChange);
- _serverUpdateController.removeListener(_onServerUpdateChanged);
_localServerController.dispose();
+ _settingsSearchController.dispose();
+ _settingsScrollController.dispose();
super.dispose();
}
@@@ -1738,310 -1555,270 +1708,293 @@@
});
}
++ final isDesktopSettings = isDesktopWorkspace(context);
++ // Media controls, downloads and permissions are phone matters; the rest
++ // is what the desktop sidebar lists.
++ final destinations = <_SettingsSectionDestination>[
++ _SettingsSectionDestination('Appearance', Icons.palette_outlined, l.sectionAppearance),
++ _SettingsSectionDestination('Customize Stats', Icons.bar_chart_rounded, l.settingsCustomizeStats),
++ _SettingsSectionDestination('Absorbing Cards', Icons.style_rounded, Wording.of(context).sectionAbsorbingCards),
++ _SettingsSectionDestination('Playback', Icons.play_circle_outline_rounded, l.sectionPlayback),
++ _SettingsSectionDestination('Sleep Timer', Icons.bedtime_outlined, l.sectionSleepTimer),
++ _SettingsSectionDestination('Library', Icons.auto_stories_outlined, l.sectionLibrary),
++ _SettingsSectionDestination('Issues & Support', Icons.support_agent_rounded, l.sectionIssuesAndSupport),
++ _SettingsSectionDestination('Advanced', Icons.tune_rounded, l.sectionAdvanced),
++ ];
return Scaffold(
body: Container(
- decoration: flatNotifier.value
- ? null
- : BoxDecoration(
- gradient: LinearGradient(
- begin: Alignment.topCenter,
- end: Alignment.bottomCenter,
- stops: const [0.0, 0.35, 1.0],
- colors: [
- cs.primary.withValues(
- alpha: gradientIntensityNotifier.value,
- ),
- Theme.of(context).scaffoldBackgroundColor,
- Theme.of(context).scaffoldBackgroundColor,
- ],
- ),
- ),
+ decoration: flatNotifier.value ? null : BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.topCenter,
+ end: Alignment.bottomCenter,
+ stops: const [0.0, 0.35, 1.0],
+ colors: [
+ cs.primary.withValues(alpha: gradientIntensityNotifier.value),
+ Theme.of(context).scaffoldBackgroundColor,
+ Theme.of(context).scaffoldBackgroundColor,
+ ],
+ ),
+ ),
child: SafeArea(
- child: LayoutBuilder(
- builder: (context, constraints) {
- final isDesktopSettings = isDesktopWorkspace(context);
- final requestedSection = _expandedSection;
- final expandedSection =
- isDesktopSettings &&
- (requestedSection == null ||
- requestedSection == 'Account' ||
- requestedSection == 'Media Controls')
- ? 'Appearance'
- : requestedSection;
- final absorbingSectionLabel = isDesktopSettings
- ? Wording.of(context).absorbingTitle
- : Wording.of(context).sectionAbsorbingCards;
- final destinations = <_SettingsSectionDestination>[
- if (!isDesktopSettings)
- _SettingsSectionDestination(
- 'Account',
- Icons.person_outline_rounded,
- l.userFallback,
- ),
- _SettingsSectionDestination(
- 'Appearance',
- Icons.palette_outlined,
- l.sectionAppearance,
- ),
- _SettingsSectionDestination(
- 'Customize Stats',
- Icons.bar_chart_rounded,
- l.settingsCustomizeStats,
- ),
- _SettingsSectionDestination(
- 'Absorbing Cards',
- Icons.style_rounded,
- absorbingSectionLabel,
- ),
- _SettingsSectionDestination(
- 'Playback',
- Icons.play_circle_outline_rounded,
- l.sectionPlayback,
++ child: _SettingsAdaptiveFrame(
++ desktopMode: isDesktopSettings,
++ selectedSection: _expandedSection,
++ destinations: destinations,
++ scrollController: _settingsScrollController,
++ onSectionSelected: _jumpToSection,
+ child: CustomScrollView(
++ controller: _settingsScrollController,
+ slivers: [
+ SliverToBoxAdapter(
+ child: AbsorbPageHeader(
+ title: l.settingsTitle,
++ showBranding: !isDesktopSettings,
+ padding: const EdgeInsets.fromLTRB(20, 12, 20, 8),
+ ),
+ ),
+ SliverToBoxAdapter(
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),
+ child: Container(
+ height: 44,
+ decoration: BoxDecoration(
+ color: cs.surfaceContainerHigh,
+ borderRadius: BorderRadius.circular(22),
),
- if (!isDesktopSettings)
- _SettingsSectionDestination(
- 'Media Controls',
- Icons.dvr_rounded,
- l.sectionMediaControls,
+ child: Row(children: [
+ const SizedBox(width: 14),
+ Icon(Icons.search_rounded, size: 20, color: cs.onSurfaceVariant),
+ const SizedBox(width: 8),
+ Expanded(
+ child: TextField(
+ controller: _settingsSearchController,
+ onChanged: (v) => setState(() => _settingsQuery = v),
+ decoration: InputDecoration(
+ hintText: l.settingsSearchHint,
+ border: InputBorder.none,
+ isDense: true,
+ ),
+ style: tt.bodyMedium,
+ ),
),
- _SettingsSectionDestination(
- 'Sleep Timer',
- Icons.bedtime_outlined,
- l.sectionSleepTimer,
- ),
- _SettingsSectionDestination(
- 'Library',
- Icons.auto_stories_outlined,
- l.sectionLibrary,
- ),
- _SettingsSectionDestination(
- 'Issues & Support',
- Icons.support_agent_rounded,
- l.sectionIssuesAndSupport,
- ),
- _SettingsSectionDestination(
- 'Advanced',
- Icons.tune_rounded,
- l.sectionAdvanced,
- ),
- ];
- final content = CustomScrollView(
- controller: _settingsScrollController,
- slivers: [
- SliverToBoxAdapter(
- child: AbsorbPageHeader(
- title: l.settingsTitle,
- showBranding: !isDesktopSettings,
- padding: const EdgeInsets.fromLTRB(20, 12, 20, 8),
+ if (_settingsQuery.isNotEmpty)
+ IconButton(
+ icon: const Icon(Icons.close_rounded, size: 18),
+ color: cs.onSurfaceVariant,
+ onPressed: () => setState(() {
+ _settingsSearchController.clear();
+ _settingsQuery = '';
+ }),
+ ),
+ const SizedBox(width: 4),
+ ]),
+ ),
+ ),
+ ),
+ if (_settingsQuery.trim().isEmpty)
+ SliverToBoxAdapter(
+ child: Column(
+ children: [
+ const SizedBox(height: 8),
+
+ // ── Tips & Tricks ──
++ if (!isDesktopSettings)
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
+ child: GestureDetector(
+ onTap: () => showTipsSheet(context),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
+ decoration: BoxDecoration(
+ gradient: flatNotifier.value ? null : LinearGradient(
+ colors: [cs.primaryContainer, cs.tertiaryContainer],
+ ),
+ color: flatNotifier.value ? cs.surfaceContainerHigh : null,
+ borderRadius: BorderRadius.circular(16),
+ ),
+ child: Row(
+ children: [
+ Icon(Icons.auto_awesome_rounded, color: cs.onPrimaryContainer, size: 22),
+ const SizedBox(width: 12),
+ Expanded(child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(l.tipsAndHiddenFeatures, style: tt.titleSmall?.copyWith(
+ fontWeight: FontWeight.w600, color: cs.onPrimaryContainer)),
+ const SizedBox(height: 2),
+ Text(l.tipsSubtitle, style: tt.bodySmall?.copyWith(
+ color: cs.onPrimaryContainer.withValues(alpha: 0.7))),
+ ],
+ )),
+ Icon(Icons.chevron_right_rounded, color: cs.onPrimaryContainer.withValues(alpha: 0.5)),
+ ],
+ ),
),
),
- SliverToBoxAdapter(
- child: Column(
- children: [
- if (!isDesktopSettings) const SizedBox(height: 8),
-
- // ── Tips & Tricks ──
- if (!isDesktopSettings)
- Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 16,
- vertical: 4,
- ),
- child: GestureDetector(
- onTap: () => showTipsSheet(context),
- child: Container(
- padding: const EdgeInsets.symmetric(
- horizontal: 16,
- vertical: 14,
- ),
+ ),
+ const SizedBox(height: 8),
+
+ // ── User Profile ──
++ if (!isDesktopSettings)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
+ child: GestureDetector(
+ onTap: () => _showAccountSheet(context),
+ child: Container(
+ padding: const EdgeInsets.all(16),
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(18),
+ gradient: LinearGradient(
+ begin: Alignment.topLeft,
+ end: Alignment.bottomRight,
+ colors: [
+ cs.primary.withValues(alpha: 0.12),
+ cs.primary.withValues(alpha: 0.04),
+ ],
+ ),
+ border: Border.all(color: cs.primary.withValues(alpha: 0.15)),
+ ),
+ child: Row(children: [
+ Container(
+ width: 40, height: 40,
+ decoration: BoxDecoration(
+ color: cs.primary.withValues(alpha: 0.15),
+ borderRadius: BorderRadius.circular(12),
+ ),
+ child: Icon(Icons.person_rounded, size: 22, color: cs.primary),
+ ),
+ const SizedBox(width: 14),
+ Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Row(children: [
+ Flexible(child: Text(auth.username ?? l.userFallback, style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w700),
+ overflow: TextOverflow.ellipsis)),
+ if (auth.isAdmin) ...[
+ const SizedBox(width: 8),
+ Container(
+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
decoration: BoxDecoration(
- gradient: flatNotifier.value
- ? null
- : LinearGradient(
- colors: [
- cs.primaryContainer,
- cs.tertiaryContainer,
- ],
- ),
- color: flatNotifier.value
- ? cs.surfaceContainerHigh
- : null,
- borderRadius: BorderRadius.circular(16),
- ),
- child: Row(
- children: [
- Icon(
- Icons.auto_awesome_rounded,
- color: cs.onPrimaryContainer,
- size: 22,
- ),
- const SizedBox(width: 12),
- Expanded(
- child: Column(
- crossAxisAlignment:
- CrossAxisAlignment.start,
- children: [
- Text(
- l.tipsAndHiddenFeatures,
- style: tt.titleSmall?.copyWith(
- fontWeight: FontWeight.w600,
- color: cs.onPrimaryContainer,
- ),
- ),
- const SizedBox(height: 2),
- Text(
- l.tipsSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onPrimaryContainer
- .withValues(alpha: 0.7),
- ),
- ),
- ],
- ),
- ),
- Icon(
- Icons.chevron_right_rounded,
- color: cs.onPrimaryContainer.withValues(
- alpha: 0.5,
- ),
- ),
- ],
+ color: auth.isRoot ? Colors.amber.withValues(alpha: 0.12) : cs.primary.withValues(alpha: 0.12),
+ borderRadius: BorderRadius.circular(4),
),
+ child: Text(auth.isRoot ? l.root : l.admin, style: tt.labelSmall?.copyWith(
+ color: auth.isRoot ? Colors.amber : cs.primary, fontWeight: FontWeight.w600, fontSize: 9)),
),
- ),
+ ],
+ ]),
+ const SizedBox(height: 2),
+ Text(
+ auth.serverUrl?.replaceAll(RegExp(r'^https?://'), '').replaceAll(RegExp(r'/+$'), '') ?? '',
+ maxLines: 1, overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.6))),
+ ])),
+ Icon(Icons.chevron_right_rounded, size: 20, color: cs.primary.withValues(alpha: 0.5)),
+ ]),
+ ),
+ ),
+ ),
+
+ // ── Admin Controls ──
+ if (auth.isAdmin)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
+ child: Material(
+ color: cs.surfaceContainerHigh,
+ borderRadius: BorderRadius.circular(14),
+ child: InkWell(
+ borderRadius: BorderRadius.circular(14),
+ onTap: () async {
+ await Navigator.push(context, MaterialPageRoute(
+ builder: (_) => const AdminScreen(),
+ ));
+ _loadAdminIssueCount();
+ },
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
+ child: Row(
+ children: [
+ Icon(Icons.admin_panel_settings_rounded, color: cs.primary, size: 22),
+ const SizedBox(width: 14),
+ Expanded(child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(l.serverAdmin, style: tt.titleSmall?.copyWith(
+ fontWeight: FontWeight.w600)),
+ Text(l.serverAdminSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ ],
+ )),
+ if (_adminIssueCount > 0 || _serverUpdate != null) ...[
+ ServerAdminStatusBadges(
+ issueCount: _adminIssueCount,
+ updateVersion: _serverUpdate?.latestVersion,
+ updateTooltip: _serverUpdate == null
+ ? ''
+ : l.serverUpdateAvailable(_serverUpdate!.latestVersion),
+ ),
+ const SizedBox(width: 10),
+ ],
+ Icon(Icons.chevron_right_rounded, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ ],
),
- const SizedBox(height: 8),
+ ),
+ ),
+ ),
+ ),
- // ── User Profile ──
- if (!isDesktopSettings)
- Padding(
- key: _keyFor('Account'),
- padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
- child: GestureDetector(
- onTap: () => _showAccountSheet(context),
- child: Container(
- padding: const EdgeInsets.all(16),
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(18),
- gradient: LinearGradient(
- begin: Alignment.topLeft,
- end: Alignment.bottomRight,
- colors: [
- cs.primary.withValues(alpha: 0.12),
- cs.primary.withValues(alpha: 0.04),
- ],
- ),
- border: Border.all(
- color: cs.primary.withValues(alpha: 0.15),
- ),
- ),
- child: Row(
- children: [
- Container(
- width: 40,
- height: 40,
- decoration: BoxDecoration(
- color: cs.primary.withValues(
- alpha: 0.15,
- ),
- borderRadius: BorderRadius.circular(12),
- ),
- child: Icon(
- Icons.person_rounded,
- size: 22,
- color: cs.primary,
- ),
- ),
- const SizedBox(width: 14),
- Expanded(
- child: Column(
- crossAxisAlignment:
- CrossAxisAlignment.start,
- children: [
- Row(
- children: [
- Flexible(
- child: Text(
- auth.username ??
- l.userFallback,
- style: tt.titleMedium
- ?.copyWith(
- fontWeight:
- FontWeight.w700,
- ),
- overflow:
- TextOverflow.ellipsis,
- ),
- ),
- if (auth.isAdmin) ...[
- const SizedBox(width: 8),
- Container(
- padding:
- const EdgeInsets.symmetric(
- horizontal: 6,
- vertical: 1,
- ),
- decoration: BoxDecoration(
- color: auth.isRoot
- ? Colors.amber
- .withValues(
- alpha: 0.12,
- )
- : cs.primary.withValues(
- alpha: 0.12,
- ),
- borderRadius:
- BorderRadius.circular(
- 4,
- ),
- ),
- child: Text(
- auth.isRoot
- ? l.root
- : l.admin,
- style: tt.labelSmall
- ?.copyWith(
- color: auth.isRoot
- ? Colors.amber
- : cs.primary,
- fontWeight:
- FontWeight.w600,
- fontSize: 9,
- ),
- ),
- ),
- ],
- ],
- ),
- const SizedBox(height: 2),
- Text(
- auth.serverUrl
- ?.replaceAll(
- RegExp(r'^https?://'),
- '',
- )
- .replaceAll(
- RegExp(r'/+$'),
- '',
- ) ??
- '',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: tt.labelSmall?.copyWith(
- color: cs.onSurfaceVariant
- .withValues(alpha: 0.6),
- ),
- ),
- ],
- ),
- ),
- Icon(
- Icons.chevron_right_rounded,
- size: 20,
- color: cs.primary.withValues(alpha: 0.5),
- ),
- ],
- ),
+ const SizedBox(height: 20),
+
+ // ── Appearance ──
+ CollapsibleSection(
+ key: _keyFor('Appearance'),
+ icon: Icons.palette_outlined,
+ title: l.sectionAppearance,
+ cs: cs,
+ isExpanded: _expandedSection == 'Appearance',
+ onExpansionChanged: (v) => _onSectionExpanded('Appearance', v),
+ children: [
+ InkWell(
+ onTap: _loaded ? () => _pickLanguage() : null,
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(16, 14, 16, 14),
+ child: Row(
+ children: [
+ Expanded(child: Text(l.languageLabel, style: tt.titleSmall)),
+ Text(
+ _languageDisplayName(_language, l),
+ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ Icon(Icons.chevron_right_rounded,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ ],
+ ),
+ ),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(l.themeLabel, style: tt.titleSmall),
+ const SizedBox(height: 12),
+ SizedBox(
+ width: double.infinity,
+ child: SegmentedButton<String>(
+ showSelectedIcon: false,
+ segments: [
+ ButtonSegment(value: 'dark', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.themeDark, maxLines: 1))),
+ ButtonSegment(value: 'light', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.themeLight, maxLines: 1))),
+ ButtonSegment(value: 'system', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.themeAuto, maxLines: 1))),
+ ],
+ selected: {_themeMode},
+ onSelectionChanged: _loaded ? (selected) {
+ final mode = selected.first;
+ setState(() => _themeMode = mode);
+ PlayerSettings.setThemeMode(mode);
+ applyThemeMode(mode);
+ } : null,
+ style: const ButtonStyle(
+ visualDensity: VisualDensity.compact,
),
),
),
@@@ -2126,4909 -1912,2435 +2088,2439 @@@
),
),
),
-
- const SizedBox(height: 20),
-
- // ── Appearance ──
- CollapsibleSection(
- key: _keyFor('Appearance'),
- icon: Icons.palette_outlined,
- title: l.sectionAppearance,
- cs: cs,
- isExpanded: expandedSection == 'Appearance',
- desktopMode: isDesktopSettings,
- onExpansionChanged: (v) =>
- _onSectionExpanded('Appearance', v),
- children: [
- InkWell(
- onTap: _loaded ? () => _pickLanguage() : null,
- child: Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 14,
- 16,
- 14,
- ),
- child: Row(
- children: [
- Expanded(
- child: Text(
- l.languageLabel,
- style: tt.titleSmall,
- ),
- ),
- Text(
- _languageDisplayName(_language, l),
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- Icon(
- Icons.chevron_right_rounded,
- color: cs.onSurfaceVariant.withValues(
- alpha: 0.5,
- ),
- ),
- ],
- ),
- ),
+ const SizedBox(height: 6),
+ Text(
+ _colorSource == 'manual' ? l.colorSourceManualDescription : l.colorSourceCoverDescription,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ if (_colorSource == 'manual') ...[
+ const SizedBox(height: 14),
+ _buildColorSwatches(cs),
+ SwitchListTile.adaptive(
+ contentPadding: EdgeInsets.zero,
+ title: Text(l.useColorEverywhereLabel, style: tt.bodyLarge),
+ subtitle: Text(l.useColorEverywhereSubtitle, style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _useColorEverywhere,
+ onChanged: _loaded ? (v) {
+ setState(() => _useColorEverywhere = v);
+ PlayerSettings.setUseColorEverywhere(v);
+ applyUseColorEverywhere(v);
+ } : null,
),
- const Divider(height: 1, indent: 16, endIndent: 16),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 12,
- 16,
- 16,
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(l.themeLabel, style: tt.titleSmall),
- const SizedBox(height: 12),
- SizedBox(
- width: double.infinity,
- child: SegmentedButton<String>(
- showSelectedIcon: false,
- segments: [
- ButtonSegment(
- value: 'dark',
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(
- l.themeDark,
- maxLines: 1,
- ),
- ),
- ),
- ButtonSegment(
- value: 'light',
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(
- l.themeLight,
- maxLines: 1,
- ),
- ),
- ),
- ButtonSegment(
- value: 'system',
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(
- l.themeAuto,
- maxLines: 1,
- ),
- ),
- ),
- ],
- selected: {_themeMode},
- onSelectionChanged: _loaded
- ? (selected) {
- final mode = selected.first;
- setState(() => _themeMode = mode);
- PlayerSettings.setThemeMode(mode);
- applyThemeMode(mode);
- }
- : null,
- style: const ButtonStyle(
- visualDensity: VisualDensity.compact,
- ),
- ),
- ),
- SwitchListTile.adaptive(
- contentPadding: EdgeInsets.zero,
- title: Text(
- l.flatBackgroundLabel,
- style: tt.bodyLarge,
- ),
- subtitle: Text(
- l.flatBackgroundSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _flatBackground,
- onChanged: _loaded
- ? (v) {
- setState(() => _flatBackground = v);
- PlayerSettings.setFlatBackground(v);
- applyFlatBackground(v);
- }
- : null,
- ),
- if (!_flatBackground) ...[
- const SizedBox(height: 4),
- Text(
- l.backgroundIntensityLabel,
- style: tt.bodyMedium,
- ),
- Slider(
- value: _gradientIntensity.clamp(
- 0.0,
- 0.45,
- ),
- min: 0.0,
- max: 0.45,
- onChanged: _loaded
- ? (v) {
- setState(
- () => _gradientIntensity = v,
- );
- applyGradientIntensity(v);
- }
- : null,
- onChangeEnd: (v) =>
- PlayerSettings.setGradientIntensity(
- v,
- ),
- ),
- ],
- ],
+ ],
+ ],
+ ),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 12),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(l.startScreenLabel, style: tt.titleSmall),
+ const SizedBox(height: 4),
+ Text(
+ l.startScreenSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ const SizedBox(height: 12),
+ SizedBox(
+ width: double.infinity,
+ child: SegmentedButton<int>(
+ showSelectedIcon: false,
+ segments: [
+ ButtonSegment(value: 0, label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.startScreenHome, maxLines: 1))),
+ ButtonSegment(value: 1, label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.startScreenLibrary, maxLines: 1))),
+ ButtonSegment(value: 2, label: FittedBox(fit: BoxFit.scaleDown, child: Text(Wording.of(context).startScreenAbsorb, maxLines: 1))),
+ ButtonSegment(value: 3, label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.startScreenStats, maxLines: 1))),
+ ],
+ selected: {_startScreen},
+ onSelectionChanged: _loaded ? (selected) {
+ final idx = selected.first;
+ setState(() => _startScreen = idx);
+ PlayerSettings.setStartScreen(idx);
+ } : null,
+ style: const ButtonStyle(
+ visualDensity: VisualDensity.compact,
),
),
- const Divider(height: 1, indent: 16, endIndent: 16),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 12,
- 16,
- 16,
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- l.colorSourceLabel,
- style: tt.titleSmall,
- ),
- const SizedBox(height: 12),
- SizedBox(
- width: double.infinity,
- child: SegmentedButton<String>(
- showSelectedIcon: false,
- segments: [
- ButtonSegment(
- value: 'dynamic',
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(
- l.colorSourceDynamic,
- maxLines: 1,
- ),
- ),
- ),
- ButtonSegment(
- value: 'manual',
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(
- l.colorSourceManual,
- maxLines: 1,
- ),
- ),
- ),
- ],
- selected: {_colorSource},
- onSelectionChanged: _loaded
- ? (selected) {
- final src = selected.first;
- setState(
- () => _colorSource = src,
- );
- PlayerSettings.setColorSource(
- src,
- );
- applyColorSource(src);
- }
- : null,
- style: const ButtonStyle(
- visualDensity: VisualDensity.compact,
- ),
- ),
- ),
- const SizedBox(height: 6),
- Text(
- _colorSource == 'manual'
- ? l.colorSourceManualDescription
- : l.colorSourceCoverDescription,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- if (_colorSource == 'manual') ...[
- const SizedBox(height: 14),
- _buildColorSwatches(cs),
- SwitchListTile.adaptive(
- contentPadding: EdgeInsets.zero,
- title: Text(
- l.useColorEverywhereLabel,
- style: tt.bodyLarge,
- ),
- subtitle: Text(
- l.useColorEverywhereSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _useColorEverywhere,
- onChanged: _loaded
- ? (v) {
- setState(
- () => _useColorEverywhere = v,
- );
- PlayerSettings.setUseColorEverywhere(
- v,
- );
- applyUseColorEverywhere(v);
- }
- : null,
- ),
- ],
- ],
+ ),
+ ],
+ ),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 12),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(l.progressTextSize, style: tt.titleSmall),
+ const SizedBox(height: 12),
+ SizedBox(
+ width: double.infinity,
+ child: SegmentedButton<double>(
+ showSelectedIcon: false,
+ segments: const [
+ ButtonSegment(value: 1.0, label: Text('A', style: TextStyle(fontSize: 13))),
+ ButtonSegment(value: 1.5, label: Text('A', style: TextStyle(fontSize: 17))),
+ ButtonSegment(value: 2.0, label: Text('A', style: TextStyle(fontSize: 21))),
+ ],
+ selected: {_progressTextScale},
+ onSelectionChanged: _loaded ? (selected) {
+ final v = selected.first;
+ setState(() => _progressTextScale = v);
+ PlayerSettings.setProgressTextScale(v);
+ } : null,
+ style: const ButtonStyle(
+ visualDensity: VisualDensity.compact,
),
),
- const Divider(height: 1, indent: 16, endIndent: 16),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 12,
- 16,
- 12,
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- l.startScreenLabel,
- style: tt.titleSmall,
- ),
- const SizedBox(height: 4),
- Text(
- l.startScreenSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- const SizedBox(height: 12),
- SizedBox(
- width: double.infinity,
- child: SegmentedButton<int>(
- showSelectedIcon: false,
- segments: [
- ButtonSegment(
- value: 0,
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(
- l.startScreenHome,
- maxLines: 1,
- ),
- ),
- ),
- ButtonSegment(
- value: 1,
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(
- l.startScreenLibrary,
- maxLines: 1,
- ),
- ),
- ),
- ButtonSegment(
- value: 2,
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(
- Wording.of(
- context,
- ).startScreenAbsorb,
- maxLines: 1,
- ),
- ),
- ),
- ButtonSegment(
- value: 3,
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(
- l.startScreenStats,
- maxLines: 1,
- ),
- ),
- ),
- ],
- selected: {_startScreen},
- onSelectionChanged: _loaded
- ? (selected) {
- final idx = selected.first;
- setState(
- () => _startScreen = idx,
- );
- PlayerSettings.setStartScreen(
- idx,
- );
- }
- : null,
- style: const ButtonStyle(
- visualDensity: VisualDensity.compact,
- ),
- ),
- ),
- ],
+ ),
+ ],
+ ),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: Text(l.disablePageFade),
+ subtitle: Text(
+ _snappyTransitions ? l.disablePageFadeOnSubtitle : l.disablePageFadeOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _snappyTransitions,
+ onChanged: _loaded ? (v) {
+ setState(() => _snappyTransitions = v);
+ PlayerSettings.setSnappyTransitions(v);
+ snappyTransitionsNotifier.value = v;
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: Text(l.showSubtitles),
+ subtitle: Text(
+ _showSubtitles ? l.showSubtitlesOnSubtitle : l.showSubtitlesOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _showSubtitles,
+ onChanged: _loaded ? (v) {
+ setState(() => _showSubtitles = v);
+ PlayerSettings.setShowSubtitles(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: Text(l.rectangleBookCovers),
+ subtitle: Text(
+ _rectangleCovers ? l.rectangleBookCoversOnSubtitle : l.rectangleBookCoversOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _rectangleCovers,
+ onChanged: _loaded ? (v) {
+ setState(() => _rectangleCovers = v);
+ PlayerSettings.setRectangleCovers(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 12),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(l.coverSize, style: tt.titleSmall),
+ const SizedBox(height: 4),
+ Text(
+ l.coverSizeSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ const SizedBox(height: 12),
+ SizedBox(
+ width: double.infinity,
+ child: SegmentedButton<String>(
+ showSelectedIcon: false,
+ segments: [
+ ButtonSegment(value: 'small', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.coverSizeSmall, maxLines: 1))),
+ ButtonSegment(value: 'medium', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.coverSizeMedium, maxLines: 1))),
+ ButtonSegment(value: 'large', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.coverSizeLarge, maxLines: 1))),
+ ],
+ selected: {_coverSize},
+ onSelectionChanged: _loaded ? (selected) {
+ final v = selected.first;
+ setState(() => _coverSize = v);
+ PlayerSettings.setCoverSize(v);
+ } : null,
+ style: const ButtonStyle(
+ visualDensity: VisualDensity.compact,
),
),
- const Divider(height: 1, indent: 16, endIndent: 16),
+ ),
+ ],
+ ),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: const Text('Classic wording'),
+ subtitle: Text(
+ _classicWording
+ ? 'Using "Play", "Now Playing", "Finished"'
+ : 'Using "Absorb", "Absorbing", "Fully Absorbed"',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _classicWording,
+ onChanged: _loaded ? (v) {
+ setState(() => _classicWording = v);
+ PlayerSettings.setClassicWording(v);
+ classicWordingNotifier.value = v;
+ } : null,
+ ),
+ // iPadOS ignores orientation preferences for multitasking
+ // apps, so the lock can't work there - hide it on iPad.
+ if (!(Platform.isIOS && MediaQuery.sizeOf(context).shortestSide >= 600)) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: const Text('Lock rotation'),
+ subtitle: Text(
+ _lockPortrait
+ ? 'Screen stays in portrait'
+ : 'Screen can rotate with the device',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _lockPortrait,
+ onChanged: _loaded ? (v) {
+ setState(() => _lockPortrait = v);
+ PlayerSettings.setLockPortrait(v);
+ applyOrientationLock();
+ } : null,
+ ),
+ ],
+ ],
+ ),
+ const SizedBox(height: 16),
+
+ // ── Customize Stats ──
+ CollapsibleSection(
+ key: _keyFor('Customize Stats'),
+ icon: Icons.bar_chart_rounded,
+ title: l.settingsCustomizeStats,
+ cs: cs,
+ isExpanded: _expandedSection == 'Customize Stats',
+ onExpansionChanged: (v) => _onSectionExpanded('Customize Stats', v),
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 12),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(l.statsGoalTitle, style: tt.titleSmall),
+ const SizedBox(height: 12),
+ SizedBox(
+ width: double.infinity,
+ child: SegmentedButton<String>(
+ showSelectedIcon: false,
+ multiSelectionEnabled: true,
+ emptySelectionAllowed: true,
+ segments: [
+ for (final p in PlayerSettings.statsGoalPeriods)
+ ButtonSegment(
+ value: p,
+ label: FittedBox(
+ fit: BoxFit.scaleDown,
+ child: Text(_statsGoalLabel(l, p), maxLines: 1))),
+ ],
+ selected: {
+ for (final e in _statsGoalMinutes.entries)
+ if (e.value > 0) e.key
+ },
+ onSelectionChanged: _loaded ? (selected) {
+ for (final p in PlayerSettings.statsGoalPeriods) {
+ final on = selected.contains(p);
+ if (on == (_statsGoalMinutes[p]! > 0)) continue;
+ _toggleStatsGoal(p, on);
+ }
+ } : null,
+ style: const ButtonStyle(visualDensity: VisualDensity.compact),
+ ),
+ ),
+ if (_statsGoalMinutes.values.every((m) => m == 0))
Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 12,
- 16,
- 12,
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- l.progressTextSize,
- style: tt.titleSmall,
- ),
- const SizedBox(height: 12),
- SizedBox(
- width: double.infinity,
- child: SegmentedButton<double>(
- showSelectedIcon: false,
- segments: const [
- ButtonSegment(
- value: 1.0,
- label: Text(
- 'A',
- style: TextStyle(fontSize: 13),
- ),
- ),
- ButtonSegment(
- value: 1.5,
- label: Text(
- 'A',
- style: TextStyle(fontSize: 17),
- ),
- ),
- ButtonSegment(
- value: 2.0,
- label: Text(
- 'A',
- style: TextStyle(fontSize: 21),
- ),
- ),
- ],
- selected: {_progressTextScale},
- onSelectionChanged: _loaded
- ? (selected) {
- final v = selected.first;
- setState(
- () => _progressTextScale = v,
- );
- PlayerSettings.setProgressTextScale(
- v,
- );
- }
- : null,
- style: const ButtonStyle(
- visualDensity: VisualDensity.compact,
- ),
- ),
- ),
- ],
- ),
+ padding: const EdgeInsets.only(top: 8),
+ child: Text(l.statsGoalOff,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
),
- const Divider(height: 1, indent: 16, endIndent: 16),
- SwitchListTile(
- title: Text(l.disablePageFade),
- subtitle: Text(
- _snappyTransitions
- ? l.disablePageFadeOnSubtitle
- : l.disablePageFadeOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _snappyTransitions,
- onChanged: _loaded
- ? (v) {
- setState(() => _snappyTransitions = v);
- PlayerSettings.setSnappyTransitions(v);
- snappyTransitionsNotifier.value = v;
+ for (final p in PlayerSettings.statsGoalPeriods)
+ if (_statsGoalMinutes[p]! > 0)
+ _statsGoalRow(cs, tt, l, p),
+ ],
+ ),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 12),
+ child: Row(children: [
+ Expanded(
+ child: Text(l.statsWeekStartsOn,
+ style: tt.bodyMedium
+ ?.copyWith(color: cs.onSurfaceVariant))),
+ DropdownButton<int>(
+ value: _statsWeekStart,
+ underline: const SizedBox.shrink(),
+ items: [
+ DropdownMenuItem(value: 0, child: Text(l.absorbingSharedSunday)),
+ DropdownMenuItem(value: 1, child: Text(l.absorbingSharedMonday)),
+ DropdownMenuItem(value: 6, child: Text(l.absorbingSharedSaturday)),
+ ],
+ onChanged: _loaded
+ ? (v) {
+ if (v == null) return;
+ setState(() => _statsWeekStart = v);
+ PlayerSettings.setStatsWeekStart(v);
+ }
+ : null,
+ ),
+ ]),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 12),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(l.statsBookChallengeTitle, style: tt.titleSmall),
+ _statsStepperRow(cs, tt, l.statsBookChallengeDesc,
+ _statsBookGoal == 0 ? l.statsGoalOff : l.statsBooksShort(_statsBookGoal),
+ onTapValue: _editStatsBookTarget,
+ onMinus: _statsBookGoal > 0
+ ? () {
+ setState(() => _statsBookGoal--);
+ PlayerSettings.setStatsBookGoal(_statsBookGoal);
}
: null,
- ),
- const Divider(height: 1, indent: 16, endIndent: 16),
- SwitchListTile(
- title: Text(l.rectangleBookCovers),
- subtitle: Text(
- _rectangleCovers
- ? l.rectangleBookCoversOnSubtitle
- : l.rectangleBookCoversOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _rectangleCovers,
- onChanged: _loaded
- ? (v) {
- setState(() => _rectangleCovers = v);
- PlayerSettings.setRectangleCovers(v);
+ onPlus: _statsBookGoal < 500
+ ? () {
+ setState(() => _statsBookGoal++);
+ PlayerSettings.setStatsBookGoal(_statsBookGoal);
}
- : null,
+ : null),
+ ],
+ ),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 12),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(l.statsChartTitle, style: tt.titleSmall),
+ const SizedBox(height: 12),
+ SizedBox(
+ width: double.infinity,
+ child: SegmentedButton<String>(
+ showSelectedIcon: false,
+ segments: [
+ ButtonSegment(value: 'bar', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.statsChartBar, maxLines: 1))),
+ ButtonSegment(value: 'line', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.statsChartLine, maxLines: 1))),
+ ],
+ selected: {_statsChartStyle},
+ onSelectionChanged: _loaded ? (selected) {
+ setState(() => _statsChartStyle = selected.first);
+ PlayerSettings.setStatsChartStyle(_statsChartStyle);
+ } : null,
+ style: const ButtonStyle(visualDensity: VisualDensity.compact),
),
- const Divider(height: 1, indent: 16, endIndent: 16),
- SwitchListTile(
- title: const Text('Classic wording'),
- subtitle: Text(
- _classicWording
- ? 'Using "Play", "Now Playing", "Finished"'
- : 'Using "Absorb", "Absorbing", "Fully Absorbed"',
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _classicWording,
- onChanged: _loaded
- ? (v) {
- setState(() => _classicWording = v);
- PlayerSettings.setClassicWording(v);
- classicWordingNotifier.value = v;
- }
- : null,
+ ),
+ const SizedBox(height: 8),
+ SizedBox(
+ width: double.infinity,
+ child: SegmentedButton<int>(
+ showSelectedIcon: false,
+ segments: [
+ ButtonSegment(value: 7, label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.statsChartDays7, maxLines: 1))),
+ ButtonSegment(value: 30, label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.statsChartDays30, maxLines: 1))),
+ ],
+ selected: {_statsChartRange},
+ onSelectionChanged: _loaded ? (selected) {
+ setState(() => _statsChartRange = selected.first);
+ PlayerSettings.setStatsChartRange(_statsChartRange);
+ } : null,
+ style: const ButtonStyle(visualDensity: VisualDensity.compact),
),
- // iPadOS ignores orientation preferences for multitasking
- // apps, so the lock can't work there - hide it on iPad.
- if (!AppPlatform.isWeb &&
- !(AppPlatform.isIOS &&
- MediaQuery.sizeOf(context).shortestSide >=
- 600)) ...[
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- SwitchListTile(
- title: const Text('Lock rotation'),
- subtitle: Text(
- _lockPortrait
- ? 'Screen stays in portrait'
- : 'Screen can rotate with the device',
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _lockPortrait,
- onChanged: _loaded
- ? (v) {
- setState(() => _lockPortrait = v);
- PlayerSettings.setLockPortrait(v);
- applyOrientationLock();
- }
- : null,
- ),
- ],
+ ),
+ ],
+ ),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(l.statsSectionsTitle, style: tt.titleSmall),
+ const SizedBox(height: 4),
+ Text(
+ l.dragToReorderTapEye,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ const SizedBox(height: 8),
+ _statsSectionsList(cs, tt, l),
+ ],
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 16),
+
+ // ── Absorbing Cards ──
+ CollapsibleSection(
+ key: _keyFor('Absorbing Cards'),
+ icon: Icons.style_rounded,
+ title: Wording.of(context).sectionAbsorbingCards,
+ cs: cs,
+ isExpanded: _expandedSection == 'Absorbing Cards',
+ onExpansionChanged: (v) => _onSectionExpanded('Absorbing Cards', v),
+ children: [
+ SwitchListTile(
+ title: Text(l.fullScreenPlayer),
+ subtitle: Text(
+ _fullScreenPlayer ? l.fullScreenPlayerOnSubtitle : l.fullScreenPlayerOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _fullScreenPlayer,
+ onChanged: _loaded ? (v) {
+ setState(() => _fullScreenPlayer = v);
+ PlayerSettings.setFullScreenPlayer(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: Text(l.coverPlayPause),
+ subtitle: Text(
+ _coverPlayButton ? l.coverPlayPauseOnSubtitle : l.coverPlayPauseOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _coverPlayButton,
+ onChanged: _loaded ? (v) {
+ setState(() => _coverPlayButton = v);
+ PlayerSettings.setCoverPlayButton(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 12),
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Text(l.cardBackground, style: tt.bodyMedium?.copyWith(color: cs.onSurface)),
+ const SizedBox(height: 8),
+ SizedBox(width: double.infinity, child: SegmentedButton<String>(
+ showSelectedIcon: false,
+ segments: [
+ ButtonSegment(value: 'blurred', icon: const Icon(Icons.blur_on_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.cardBackgroundBlurred))),
+ ButtonSegment(value: 'gradient', icon: const Icon(Icons.gradient_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.cardBackgroundGradient))),
+ ButtonSegment(value: 'off', icon: const Icon(Icons.block_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.off))),
],
- ),
- if (!isDesktopSettings ||
- expandedSection == 'Appearance')
- const SizedBox(height: 16),
-
- // ── Customize Stats ──
- CollapsibleSection(
- key: _keyFor('Customize Stats'),
- icon: Icons.bar_chart_rounded,
- title: l.settingsCustomizeStats,
- cs: cs,
- isExpanded: expandedSection == 'Customize Stats',
- desktopMode: isDesktopSettings,
- onExpansionChanged: (v) =>
- _onSectionExpanded('Customize Stats', v),
- children: [
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 12,
- 16,
- 12,
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(l.statsGoalTitle, style: tt.titleSmall),
- const SizedBox(height: 12),
- SizedBox(
- width: double.infinity,
- child: SegmentedButton<String>(
- showSelectedIcon: false,
- multiSelectionEnabled: true,
- emptySelectionAllowed: true,
- segments: [
- for (final p
- in PlayerSettings.statsGoalPeriods)
- ButtonSegment(
- value: p,
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(
- _statsGoalLabel(l, p),
- maxLines: 1,
- ),
- ),
- ),
- ],
- selected: {
- for (final e
- in _statsGoalMinutes.entries)
- if (e.value > 0) e.key,
- },
- onSelectionChanged: _loaded
- ? (selected) {
- for (final p
- in PlayerSettings
- .statsGoalPeriods) {
- final on = selected.contains(p);
- if (on ==
- (_statsGoalMinutes[p]! > 0))
- continue;
- _toggleStatsGoal(p, on);
- }
- }
- : null,
- style: const ButtonStyle(
- visualDensity: VisualDensity.compact,
- ),
- ),
- ),
- if (_statsGoalMinutes.values.every(
- (m) => m == 0,
- ))
- Padding(
- padding: const EdgeInsets.only(top: 8),
- child: Text(
- l.statsGoalOff,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- ),
- for (final p
- in PlayerSettings.statsGoalPeriods)
- if (_statsGoalMinutes[p]! > 0)
- _statsGoalRow(cs, tt, l, p),
- ],
- ),
- ),
- const Divider(height: 1, indent: 16, endIndent: 16),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 12,
- 16,
- 12,
- ),
- child: Row(
- children: [
- Expanded(
- child: Text(
- l.statsWeekStartsOn,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- ),
- DropdownButton<int>(
- value: _statsWeekStart,
- underline: const SizedBox.shrink(),
- items: [
- DropdownMenuItem(
- value: 0,
- child: Text(l.absorbingSharedSunday),
- ),
- DropdownMenuItem(
- value: 1,
- child: Text(l.absorbingSharedMonday),
- ),
- DropdownMenuItem(
- value: 6,
- child: Text(l.absorbingSharedSaturday),
- ),
- ],
- onChanged: _loaded
- ? (v) {
- if (v == null) return;
- setState(() => _statsWeekStart = v);
- PlayerSettings.setStatsWeekStart(v);
- }
- : null,
- ),
- ],
- ),
- ),
- const Divider(height: 1, indent: 16, endIndent: 16),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 12,
- 16,
- 12,
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- l.statsBookChallengeTitle,
- style: tt.titleSmall,
- ),
- _statsStepperRow(
- cs,
- tt,
- l.statsBookChallengeDesc,
- _statsBookGoal == 0
- ? l.statsGoalOff
- : l.statsBooksShort(_statsBookGoal),
- onTapValue: _editStatsBookTarget,
- onMinus: _statsBookGoal > 0
- ? () {
- setState(() => _statsBookGoal--);
- PlayerSettings.setStatsBookGoal(
- _statsBookGoal,
- );
- }
- : null,
- onPlus: _statsBookGoal < 500
- ? () {
- setState(() => _statsBookGoal++);
- PlayerSettings.setStatsBookGoal(
- _statsBookGoal,
- );
- }
- : null,
- ),
- ],
- ),
- ),
- const Divider(height: 1, indent: 16, endIndent: 16),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 12,
- 16,
- 12,
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(l.statsChartTitle, style: tt.titleSmall),
- const SizedBox(height: 12),
- SizedBox(
- width: double.infinity,
- child: SegmentedButton<String>(
- showSelectedIcon: false,
- segments: [
- ButtonSegment(
- value: 'bar',
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(
- l.statsChartBar,
- maxLines: 1,
- ),
- ),
- ),
- ButtonSegment(
- value: 'line',
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(
- l.statsChartLine,
- maxLines: 1,
- ),
- ),
- ),
- ],
- selected: {_statsChartStyle},
- onSelectionChanged: _loaded
- ? (selected) {
- setState(
- () => _statsChartStyle =
- selected.first,
- );
- PlayerSettings.setStatsChartStyle(
- _statsChartStyle,
- );
- }
- : null,
- style: const ButtonStyle(
- visualDensity: VisualDensity.compact,
- ),
- ),
- ),
- const SizedBox(height: 8),
- SizedBox(
- width: double.infinity,
- child: SegmentedButton<int>(
- showSelectedIcon: false,
- segments: [
- ButtonSegment(
- value: 7,
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(
- l.statsChartDays7,
- maxLines: 1,
- ),
- ),
- ),
- ButtonSegment(
- value: 30,
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(
- l.statsChartDays30,
- maxLines: 1,
- ),
- ),
- ),
- ],
- selected: {_statsChartRange},
- onSelectionChanged: _loaded
- ? (selected) {
- setState(
- () => _statsChartRange =
- selected.first,
- );
- PlayerSettings.setStatsChartRange(
- _statsChartRange,
- );
- }
- : null,
- style: const ButtonStyle(
- visualDensity: VisualDensity.compact,
- ),
- ),
- ),
- ],
- ),
- ),
- const Divider(height: 1, indent: 16, endIndent: 16),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 12,
- 16,
- 16,
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- l.statsSectionsTitle,
- style: tt.titleSmall,
- ),
- const SizedBox(height: 4),
- Text(
- l.dragToReorderTapEye,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- const SizedBox(height: 8),
- _statsSectionsList(cs, tt, l),
- ],
- ),
+ selected: {_cardBackground},
+ onSelectionChanged: _loaded ? (s) {
+ if (s.isEmpty) return;
+ setState(() => _cardBackground = s.first);
+ PlayerSettings.setCardBackground(s.first);
+ } : null,
+ style: const ButtonStyle(visualDensity: VisualDensity.compact),
+ )),
+ ]),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 14),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ l.cardScrubbers,
+ style: tt.bodyMedium?.copyWith(
+ color: cs.onSurface,
),
- ],
- ),
- if (!isDesktopSettings ||
- expandedSection == 'Customize Stats')
- const SizedBox(height: 16),
-
- // ── Absorbing Cards ──
- CollapsibleSection(
- key: _keyFor('Absorbing Cards'),
- icon: Icons.style_rounded,
- title: absorbingSectionLabel,
- cs: cs,
- isExpanded: expandedSection == 'Absorbing Cards',
- desktopMode: isDesktopSettings,
- onExpansionChanged: (v) =>
- _onSectionExpanded('Absorbing Cards', v),
- children: [
- if (!AppPlatform.isWeb) ...[
- SwitchListTile(
- title: Text(l.fullScreenPlayer),
- subtitle: Text(
- _fullScreenPlayer
- ? l.fullScreenPlayerOnSubtitle
- : l.fullScreenPlayerOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _fullScreenPlayer,
- onChanged: _loaded
- ? (v) {
- setState(() => _fullScreenPlayer = v);
- PlayerSettings.setFullScreenPlayer(v);
- }
- : null,
- ),
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- ],
- SwitchListTile(
- title: Text(l.coverPlayPause),
- subtitle: Text(
- _coverPlayButton
- ? l.coverPlayPauseOnSubtitle
- : l.coverPlayPauseOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _coverPlayButton,
- onChanged: _loaded
- ? (v) {
- setState(() => _coverPlayButton = v);
- PlayerSettings.setCoverPlayButton(v);
- }
- : null,
+ ),
+ const SizedBox(height: 4),
+ Text(
+ switch (_cardScrubberMode) {
+ CardScrubberMode.both =>
+ l.cardScrubbersBothSubtitle,
+ CardScrubberMode.chapter =>
+ l.cardScrubbersChapterSubtitle,
+ CardScrubberMode.locked =>
+ l.cardScrubbersLockedSubtitle,
+ },
+ style: tt.bodySmall?.copyWith(
+ color: cs.onSurfaceVariant,
),
- const Divider(height: 1, indent: 16, endIndent: 16),
- if (!isDesktopSettings) ...[
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 12,
- 16,
- 12,
- ),
- child: Column(
+ ),
+ const SizedBox(height: 10),
+ CardScrubberModeSelector(
+ mode: _cardScrubberMode,
+ enabled: _loaded,
+ onChanged: (mode) {
+ setState(() => _cardScrubberMode = mode);
+ PlayerSettings.setCardScrubberMode(mode);
+ },
+ ),
+ ],
+ ),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: Text(l.speedAdjustedTime),
+ subtitle: Text(
+ _speedAdjustedTime ? l.speedAdjustedTimeOnSubtitle : l.speedAdjustedTimeOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _speedAdjustedTime,
+ onChanged: _loaded ? (v) {
+ setState(() => _speedAdjustedTime = v);
+ PlayerSettings.setSpeedAdjustedTime(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ValueListenableBuilder<bool>(
+ valueListenable: classicWordingNotifier,
+ builder: (context, _, __) {
+ final w = Wording.of(context);
+ // The dedicated Podcasts tab implies merged libraries;
+ // show it locked on rather than a toggle that snaps back.
+ final effectiveMerge =
+ _mergeAbsorbingLibraries || _podcastTabEnabled;
+ return SwitchListTile(
+ title: Row(children: [
+ Flexible(child: Text(w.mergeLibraries)),
+ _infoIcon(w.mergeLibrariesInfoTitle, w.mergeLibrariesInfoContent),
+ ]),
+ subtitle: Text(
+ _podcastTabEnabled
+ ? l.settingsMergeImpliedByPodcastTab
+ : effectiveMerge
+ ? w.mergeLibrariesOnSubtitle
+ : w.mergeLibrariesOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: effectiveMerge,
+ onChanged: (_loaded && !_podcastTabEnabled) ? (v) async {
+ setState(() => _mergeAbsorbingLibraries = v);
+ await PlayerSettings.setMergeAbsorbingLibraries(v);
+ unawaited(lib.syncQueueAutoDownloads());
+ } : null,
+ );
+ },
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
+ child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
+ Row(children: [
+ Text(l.queueMode, style: tt.bodyMedium?.copyWith(color: cs.onSurface)),
+ const SizedBox(width: 4),
+ GestureDetector(
+ onTap: () => showDialog(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: Text(l.queueModeInfoTitle),
+ content: Column(
+ mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- Text(
- l.cardBackground,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurface,
- ),
- ),
- const SizedBox(height: 8),
- SizedBox(
- width: double.infinity,
- child: SegmentedButton<String>(
- showSelectedIcon: false,
- segments: [
- ButtonSegment(
- value: 'blurred',
- icon: const Icon(
- Icons.blur_on_rounded,
- size: 18,
- ),
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(
- l.cardBackgroundBlurred,
- ),
- ),
- ),
- ButtonSegment(
- value: 'gradient',
- icon: const Icon(
- Icons.gradient_rounded,
- size: 18,
- ),
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(
- l.cardBackgroundGradient,
- ),
- ),
- ),
- ButtonSegment(
- value: 'off',
- icon: const Icon(
- Icons.block_rounded,
- size: 18,
- ),
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(l.off),
- ),
- ),
- ],
- selected: {_cardBackground},
- onSelectionChanged: _loaded
- ? (s) {
- if (s.isEmpty) return;
- setState(
- () =>
- _cardBackground = s.first,
- );
- PlayerSettings.setCardBackground(
- s.first,
- );
- }
- : null,
- style: const ButtonStyle(
- visualDensity: VisualDensity.compact,
- ),
- ),
- ),
+ Text(l.queueModeInfoOff, style: const TextStyle(fontWeight: FontWeight.w600)),
+ const SizedBox(height: 4),
+ Text(l.queueModeInfoOffDesc),
+ const SizedBox(height: 12),
+ Text(l.queueModeInfoManual, style: const TextStyle(fontWeight: FontWeight.w600)),
+ const SizedBox(height: 4),
+ Text(Wording.of(ctx).queueModeInfoManualDesc),
+ const SizedBox(height: 12),
+ Text(l.queueModeInfoSeries, style: const TextStyle(fontWeight: FontWeight.w600)),
+ const SizedBox(height: 4),
+ Text(l.queueModeInfoSeriesDesc),
+ const SizedBox(height: 12),
+ Text(l.queueModeInfoPlaylist, style: const TextStyle(fontWeight: FontWeight.w600)),
+ const SizedBox(height: 4),
+ Text(l.queueModeInfoPlaylistDesc),
],
),
+ actions: [TextButton(onPressed: () => Navigator.pop(ctx), child: Text(l.gotIt))],
),
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- ],
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 12,
- 16,
- 14,
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- l.cardScrubbers,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurface,
- ),
- ),
- const SizedBox(height: 4),
- Text(
- switch (_cardScrubberMode) {
- CardScrubberMode.both =>
- l.cardScrubbersBothSubtitle,
- CardScrubberMode.chapter =>
- l.cardScrubbersChapterSubtitle,
- CardScrubberMode.locked =>
- l.cardScrubbersLockedSubtitle,
- },
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- const SizedBox(height: 10),
- CardScrubberModeSelector(
- mode: _cardScrubberMode,
- enabled: _loaded,
- onChanged: (mode) {
- setState(() => _cardScrubberMode = mode);
- PlayerSettings.setCardScrubberMode(mode);
- },
- ),
- ],
- ),
- ),
- const Divider(height: 1, indent: 16, endIndent: 16),
- SwitchListTile(
- title: Text(l.speedAdjustedTime),
- subtitle: Text(
- _speedAdjustedTime
- ? l.speedAdjustedTimeOnSubtitle
- : l.speedAdjustedTimeOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _speedAdjustedTime,
- onChanged: _loaded
- ? (v) {
- setState(() => _speedAdjustedTime = v);
- PlayerSettings.setSpeedAdjustedTime(v);
- }
- : null,
),
- const Divider(height: 1, indent: 16, endIndent: 16),
- if (isDesktopSettings) ...[
- SwitchListTile(
- title: Text(l.chapterProgressInNowPlayingBar),
- subtitle: Text(
- _notifChapterProgress
- ? l.chapterProgressInNowPlayingBarOnSubtitle
- : l.chapterProgressInNowPlayingBarOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _notifChapterProgress,
- onChanged: _loaded
- ? (v) {
- setState(
- () => _notifChapterProgress = v,
- );
- PlayerSettings.setNotificationChapterProgress(
- v,
- );
- }
- : null,
- ),
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
+ child: Icon(Icons.info_outline_rounded, size: 16, color: cs.onSurfaceVariant),
+ ),
+ ]),
+ const SizedBox(height: 8),
+ // When libraries are merged, show a single unified control
+ if (_mergeAbsorbingLibraries || _podcastTabEnabled) ...[
+ Text(l.queueModeMergedSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ const SizedBox(height: 8),
+ SizedBox(width: double.infinity, child: SegmentedButton<String>(
+ showSelectedIcon: false,
+ segments: [
+ ButtonSegment(value: 'off', icon: const Icon(Icons.stop_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeOff))),
+ ButtonSegment(value: 'manual', icon: const Icon(Icons.queue_music_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeManual))),
+ ButtonSegment(value: 'auto_next', icon: const Icon(Icons.skip_next_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeAuto))),
+ ButtonSegment(value: 'playlist', icon: const Icon(Icons.playlist_play_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModePlaylist))),
],
- ValueListenableBuilder<bool>(
- valueListenable: classicWordingNotifier,
- builder: (context, _, __) {
- final w = Wording.of(context);
- // The dedicated Podcasts tab implies merged libraries;
- // show it locked on rather than a toggle that snaps back.
- final effectiveMerge =
- _mergeAbsorbingLibraries ||
- _podcastTabEnabled;
- return SwitchListTile(
- title: Row(
- children: [
- Flexible(child: Text(w.mergeLibraries)),
- _infoIcon(
- w.mergeLibrariesInfoTitle,
- w.mergeLibrariesInfoContent,
- ),
- ],
- ),
- subtitle: Text(
- _podcastTabEnabled
- ? l.settingsMergeImpliedByPodcastTab
- : effectiveMerge
- ? w.mergeLibrariesOnSubtitle
- : w.mergeLibrariesOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: effectiveMerge,
- onChanged: (_loaded && !_podcastTabEnabled)
- ? (v) async {
- setState(
- () => _mergeAbsorbingLibraries = v,
- );
- await PlayerSettings.setMergeAbsorbingLibraries(
- v,
- );
- unawaited(
- lib.syncQueueAutoDownloads(),
- );
- }
- : null,
- );
- },
- ),
- const Divider(height: 1, indent: 16, endIndent: 16),
- Padding(
- padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Row(
- children: [
- Text(
- l.queueMode,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurface,
- ),
- ),
- const SizedBox(width: 4),
- GestureDetector(
- onTap: () => showDialog(
- context: context,
- builder: (ctx) => AlertDialog(
- title: Text(l.queueModeInfoTitle),
- content: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment:
- CrossAxisAlignment.start,
- children: [
- Text(
- l.queueModeInfoOff,
- style: const TextStyle(
- fontWeight: FontWeight.w600,
- ),
- ),
- const SizedBox(height: 4),
- Text(l.queueModeInfoOffDesc),
- const SizedBox(height: 12),
- Text(
- l.queueModeInfoManual,
- style: const TextStyle(
- fontWeight: FontWeight.w600,
- ),
- ),
- const SizedBox(height: 4),
- Text(
- Wording.of(
- ctx,
- ).queueModeInfoManualDesc,
- ),
- const SizedBox(height: 12),
- Text(
- l.queueModeInfoSeries,
- style: const TextStyle(
- fontWeight: FontWeight.w600,
- ),
- ),
- const SizedBox(height: 4),
- Text(l.queueModeInfoSeriesDesc),
- const SizedBox(height: 12),
- Text(
- l.queueModeInfoPlaylist,
- style: const TextStyle(
- fontWeight: FontWeight.w600,
- ),
- ),
- const SizedBox(height: 4),
- Text(
- l.queueModeInfoPlaylistDesc,
- ),
- ],
- ),
- actions: [
- TextButton(
- onPressed: () =>
- Navigator.pop(ctx),
- child: Text(l.gotIt),
- ),
- ],
- ),
- ),
- child: Icon(
- Icons.info_outline_rounded,
- size: 16,
- color: cs.onSurfaceVariant,
- ),
- ),
- ],
- ),
- const SizedBox(height: 8),
- // When libraries are merged, show a single unified control
- if (_mergeAbsorbingLibraries ||
- _podcastTabEnabled) ...[
- Text(
- l.queueModeMergedSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- const SizedBox(height: 8),
- SizedBox(
- width: double.infinity,
- child: SegmentedButton<String>(
- showSelectedIcon: false,
- segments: [
- ButtonSegment(
- value: 'off',
- icon: const Icon(
- Icons.stop_rounded,
- size: 18,
- ),
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(l.queueModeOff),
- ),
- ),
- ButtonSegment(
- value: 'manual',
- icon: const Icon(
- Icons.queue_music_rounded,
- size: 18,
- ),
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(l.queueModeManual),
- ),
- ),
- ButtonSegment(
- value: 'auto_next',
- icon: const Icon(
- Icons.skip_next_rounded,
- size: 18,
- ),
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(l.queueModeAuto),
- ),
- ),
- ButtonSegment(
- value: 'playlist',
- icon: const Icon(
- Icons.playlist_play_rounded,
- size: 18,
- ),
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(l.queueModePlaylist),
- ),
- ),
- ],
- selected: {_mergedQueueMode},
- onSelectionChanged: _loaded
- ? (s) {
- if (s.isNotEmpty)
- _setMergedQueueMode(s.first);
- }
- : null,
- style: const ButtonStyle(
- visualDensity: VisualDensity.compact,
- ),
- ),
- ),
- ] else ...[
- // Separate controls per type
- Text(
- l.queueModeBooks,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- fontWeight: FontWeight.w600,
- ),
- ),
- const SizedBox(height: 4),
- SizedBox(
- width: double.infinity,
- child: SegmentedButton<String>(
- showSelectedIcon: false,
- segments: [
- ButtonSegment(
- value: 'off',
- icon: const Icon(
- Icons.stop_rounded,
- size: 18,
- ),
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(l.queueModeOff),
- ),
- ),
- ButtonSegment(
- value: 'manual',
- icon: const Icon(
- Icons.queue_music_rounded,
- size: 18,
- ),
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(l.queueModeManual),
- ),
- ),
- ButtonSegment(
- value: 'auto_next',
- icon: const Icon(
- Icons.skip_next_rounded,
- size: 18,
- ),
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(
- l.queueModeSeriesLabel,
- ),
- ),
- ),
- ButtonSegment(
- value: 'playlist',
- icon: const Icon(
- Icons.playlist_play_rounded,
- size: 18,
- ),
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(l.queueModePlaylist),
- ),
- ),
- ],
- selected: {_bookQueueMode},
- onSelectionChanged: _loaded
- ? (s) {
- if (s.isNotEmpty)
- _setBookQueueMode(s.first);
- }
- : null,
- style: const ButtonStyle(
- visualDensity: VisualDensity.compact,
- ),
- ),
- ),
- if (lib.libraries.any(
- (lib) => lib['mediaType'] == 'podcast',
- )) ...[
- const SizedBox(height: 8),
- Text(
- l.queueModePodcasts,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- fontWeight: FontWeight.w600,
- ),
- ),
- const SizedBox(height: 4),
- SizedBox(
- width: double.infinity,
- child: SegmentedButton<String>(
- showSelectedIcon: false,
- segments: [
- ButtonSegment(
- value: 'off',
- icon: const Icon(
- Icons.stop_rounded,
- size: 18,
- ),
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(l.queueModeOff),
- ),
- ),
- ButtonSegment(
- value: 'manual',
- icon: const Icon(
- Icons.queue_music_rounded,
- size: 18,
- ),
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(l.queueModeManual),
- ),
- ),
- ButtonSegment(
- value: 'auto_next',
- icon: const Icon(
- Icons.skip_next_rounded,
- size: 18,
- ),
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(
- l.queueModeShowLabel,
- ),
- ),
- ),
- ButtonSegment(
- value: 'playlist',
- icon: const Icon(
- Icons.playlist_play_rounded,
- size: 18,
- ),
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(
- l.queueModePlaylist,
- ),
- ),
- ),
- ],
- selected: {_podcastQueueMode},
- onSelectionChanged: _loaded
- ? (s) {
- if (s.isNotEmpty)
- _setPodcastQueueMode(
- s.first,
- );
- }
- : null,
- style: const ButtonStyle(
- visualDensity:
- VisualDensity.compact,
- ),
- ),
- ),
- ],
- ],
- if (_bookQueueMode != 'off' ||
- _podcastQueueMode != 'off') ...[
- const SizedBox(height: 4),
- SwitchListTile(
- title: Text(l.autoDownloadQueue),
- subtitle: Text(
- _queueAutoDownload
- ? l.autoDownloadQueueOnSubtitle(
- _rollingDownloadCount,
- )
- : l.autoDownloadQueueOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _queueAutoDownload,
- onChanged: _loaded
- ? (v) async {
- setState(
- () => _queueAutoDownload = v,
- );
- await PlayerSettings.setQueueAutoDownload(
- v,
- );
- unawaited(
- lib.syncQueueAutoDownloads(),
- );
- }
- : null,
- dense: true,
- contentPadding: EdgeInsets.zero,
- ),
- ],
- ],
- ),
+ selected: {_mergedQueueMode},
+ onSelectionChanged: _loaded
+ ? (s) { if (s.isNotEmpty) _setMergedQueueMode(s.first); }
+ : null,
+ style: const ButtonStyle(visualDensity: VisualDensity.compact),
+ )),
+ ] else ...[
+ // Separate controls per type
+ Text(l.queueModeBooks, style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant, fontWeight: FontWeight.w600)),
+ const SizedBox(height: 4),
+ SizedBox(width: double.infinity, child: SegmentedButton<String>(
+ showSelectedIcon: false,
+ segments: [
+ ButtonSegment(value: 'off', icon: const Icon(Icons.stop_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeOff))),
+ ButtonSegment(value: 'manual', icon: const Icon(Icons.queue_music_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeManual))),
+ ButtonSegment(value: 'auto_next', icon: const Icon(Icons.skip_next_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeSeriesLabel))),
+ ButtonSegment(value: 'playlist', icon: const Icon(Icons.playlist_play_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModePlaylist))),
+ ],
+ selected: {_bookQueueMode},
+ onSelectionChanged: _loaded
+ ? (s) { if (s.isNotEmpty) _setBookQueueMode(s.first); }
+ : null,
+ style: const ButtonStyle(visualDensity: VisualDensity.compact),
+ )),
+ if (lib.libraries.any((lib) => lib['mediaType'] == 'podcast')) ...[
+ const SizedBox(height: 8),
+ Text(l.queueModePodcasts, style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant, fontWeight: FontWeight.w600)),
+ const SizedBox(height: 4),
+ SizedBox(width: double.infinity, child: SegmentedButton<String>(
+ showSelectedIcon: false,
+ segments: [
+ ButtonSegment(value: 'off', icon: const Icon(Icons.stop_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeOff))),
+ ButtonSegment(value: 'manual', icon: const Icon(Icons.queue_music_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeManual))),
+ ButtonSegment(value: 'auto_next', icon: const Icon(Icons.skip_next_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModeShowLabel))),
+ ButtonSegment(value: 'playlist', icon: const Icon(Icons.playlist_play_rounded, size: 18), label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.queueModePlaylist))),
+ ],
+ selected: {_podcastQueueMode},
+ onSelectionChanged: _loaded
+ ? (s) { if (s.isNotEmpty) _setPodcastQueueMode(s.first); }
+ : null,
+ style: const ButtonStyle(visualDensity: VisualDensity.compact),
+ )),
+ ],
+ ],
+ if (_bookQueueMode != 'off' || _podcastQueueMode != 'off') ...[
+ const SizedBox(height: 4),
+ SwitchListTile(
+ title: Text(l.autoDownloadQueue),
+ subtitle: Text(
+ _queueAutoDownload
+ ? l.autoDownloadQueueOnSubtitle(_rollingDownloadCount)
+ : l.autoDownloadQueueOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _queueAutoDownload,
+ onChanged: _loaded ? (v) async {
+ setState(() => _queueAutoDownload = v);
+ await PlayerSettings.setQueueAutoDownload(v);
+ unawaited(lib.syncQueueAutoDownloads());
+ } : null,
+ dense: true,
+ contentPadding: EdgeInsets.zero,
+ ),
+ ],
+ ]),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
+ child: Center(child: TextButton.icon(
+ onPressed: _loaded ? () async {
+ final confirmed = await showDialog<bool>(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: Text(l.resetButtonGridQuestion),
+ content: Text(l.resetButtonGridContent),
+ actions: [
+ TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text(l.cancel)),
+ TextButton(onPressed: () => Navigator.pop(ctx, true), child: Text(l.reset)),
+ ],
),
- const Divider(height: 1, indent: 16, endIndent: 16),
- Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 16,
- vertical: 10,
- ),
- child: Center(
- child: TextButton.icon(
- onPressed: _loaded
- ? () async {
- final confirmed =
- await showDialog<bool>(
- context: context,
- builder: (ctx) => AlertDialog(
- title: Text(
- l.resetButtonGridQuestion,
- ),
- content: Text(
- l.resetButtonGridContent,
- ),
- actions: [
- TextButton(
- onPressed: () =>
- Navigator.pop(
- ctx,
- false,
- ),
- child: Text(l.cancel),
- ),
- TextButton(
- onPressed: () =>
- Navigator.pop(
- ctx,
- true,
- ),
- child: Text(l.reset),
- ),
- ],
- ),
- );
- if (confirmed != true || !mounted)
- return;
- await PlayerSettings.setCardButtonOrder(
- PlayerSettings.defaultButtonOrder,
- );
- await PlayerSettings.setCardButtonVisibleCount(
- PlayerSettings
- .defaultButtonVisibleCount,
- );
- await PlayerSettings.setCardIconsOnly(
- false,
- );
- await PlayerSettings.setCardMoreInline(
- false,
- );
- if (mounted)
- showOverlayToast(
- context,
- l.buttonGridReset,
- icon: Icons.restart_alt_rounded,
- );
- }
- : null,
- icon: Icon(
- Icons.restart_alt_rounded,
- size: 16,
- color: cs.onSurfaceVariant,
- ),
- label: Text(
- l.resetButtonGrid,
- style: TextStyle(
- fontSize: 13,
- color: cs.onSurfaceVariant,
- ),
- ),
- ),
- ),
+ );
+ if (confirmed != true || !mounted) return;
+ await PlayerSettings.setCardButtonOrder(PlayerSettings.defaultButtonOrder);
+ await PlayerSettings.setCardButtonVisibleCount(PlayerSettings.defaultButtonVisibleCount);
+ await PlayerSettings.setCardIconsOnly(false);
+ await PlayerSettings.setCardMoreInline(false);
+ if (mounted) showOverlayToast(context, l.buttonGridReset, icon: Icons.restart_alt_rounded);
+ } : null,
+ icon: Icon(Icons.restart_alt_rounded, size: 16, color: cs.onSurfaceVariant),
+ label: Text(l.resetButtonGrid, style: TextStyle(fontSize: 13, color: cs.onSurfaceVariant)),
+ )),
+ ),
+ ],
+ ),
+ const SizedBox(height: 16),
+
+ // ── Playback ──
+ CollapsibleSection(
+ key: _keyFor('Playback'),
+ icon: Icons.play_circle_outline_rounded,
+ title: l.sectionPlayback,
+ cs: cs,
+ isExpanded: _expandedSection == 'Playback',
+ onExpansionChanged: (v) => _onSectionExpanded('Playback', v),
+ children: [
+ // Default speed
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text(l.defaultSpeed, style: tt.bodyMedium),
+ Text(l.speedValue(_defaultSpeed.toStringAsFixed(2)),
+ style: tt.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w700, color: cs.primary)),
+ ],
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 0),
+ child: Text(l.defaultSpeedSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant, fontSize: 11)),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 4, 16, 0),
+ child: Row(children: [
+ GestureDetector(
+ onTap: _loaded ? () => _setDefaultSpeed(_defaultSpeed - 0.05) : null,
+ child: Container(
+ width: 36, height: 36,
+ decoration: BoxDecoration(shape: BoxShape.circle, color: cs.onSurface.withValues(alpha: 0.08)),
+ child: Icon(Icons.remove_rounded, size: 20, color: cs.onSurface.withValues(alpha: 0.7)),
+ ),
+ ),
+ Expanded(child: AbsorbSlider(
+ value: _defaultSpeed,
+ min: 0.5,
+ max: 5.0,
+ divisions: 90,
+ activeColor: cs.primary,
+ onChanged: _loaded ? _setDefaultSpeed : null,
+ )),
+ GestureDetector(
+ onTap: _loaded ? () => _setDefaultSpeed(_defaultSpeed + 0.05) : null,
+ child: Container(
+ width: 36, height: 36,
+ decoration: BoxDecoration(shape: BoxShape.circle, color: cs.onSurface.withValues(alpha: 0.08)),
+ child: Icon(Icons.add_rounded, size: 20, color: cs.onSurface.withValues(alpha: 0.7)),
+ ),
+ ),
+ ]),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(52, 0, 52, 0),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text('0.5x', style: TextStyle(color: cs.onSurface.withValues(alpha: 0.3), fontSize: 11)),
+ Text('5.0x', style: TextStyle(color: cs.onSurface.withValues(alpha: 0.3), fontSize: 11)),
+ ],
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
+ child: Wrap(
+ spacing: 6, runSpacing: 4,
+ children: [0.75, 1.0, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0, 4.0, 5.0].map((s) {
+ final isActive = (_defaultSpeed - s).abs() < 0.01;
+ return ActionChip(
+ label: Text(l.speedValue(s.toString()),
+ style: TextStyle(
+ fontSize: 12,
+ fontWeight: isActive ? FontWeight.w700 : FontWeight.w400,
+ color: isActive ? cs.onPrimary : cs.onSurface,
+ )),
+ backgroundColor: isActive ? cs.primary : cs.surfaceContainerHighest,
+ side: BorderSide.none,
+ onPressed: _loaded ? () => _setDefaultSpeed(s) : null,
+ );
+ }).toList(),
+ ),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ leading: Icon(Icons.refresh_rounded, color: cs.onSurfaceVariant),
+ title: Text(l.resetSpeedPresets),
+ subtitle: Text(l.resetSpeedPresetsSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ onTap: () async {
+ await PlayerSettings.resetSpeedPresets();
+ if (!mounted) return;
+ showOverlayToast(context, l.speedPresetsReset,
+ icon: Icons.refresh_rounded);
+ },
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ // Skip amounts
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text(l.skipBack, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
+ Text(l.secondsValue(_backSkip.toString()), style: tt.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w600, color: cs.primary)),
+ ],
+ ),
+ ),
+ AbsorbSlider(
+ value: _backSkip.toDouble(),
+ min: 5, max: 60, divisions: 11,
+ onChanged: _loaded ? (v) {
+ setState(() => _backSkip = v.round());
+ PlayerSettings.setBackSkip(v.round());
+ } : null,
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text(l.skipForward, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
+ Text(l.secondsValue(_forwardSkip.toString()), style: tt.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w600, color: cs.primary)),
+ ],
+ ),
+ ),
+ AbsorbSlider(
+ value: _forwardSkip.toDouble(),
+ min: 5, max: 60, divisions: 11,
+ onChanged: _loaded ? (v) {
+ setState(() => _forwardSkip = v.round());
+ PlayerSettings.setForwardSkip(v.round());
+ } : null,
+ ),
+ if (Platform.isIOS)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 4, 16, 8),
+ child: Text(
+ l.iosLockScreenSkipHint,
+ style: tt.bodySmall?.copyWith(
+ color: cs.onSurfaceVariant, height: 1.35),
+ ),
+ ),
+ SwitchListTile(
+ title: Row(children: [
+ Expanded(child: Text(l.chapterBarrierOnRewind)),
+ GestureDetector(
+ onTap: () => showDialog(
+ context: context,
+ builder: (_) => AlertDialog(
+ title: Text(l.chapterBarrierInfoTitle),
+ content: Text(l.chapterBarrierInfoContent),
+ actions: [TextButton(onPressed: () => Navigator.pop(context), child: Text(l.gotIt))],
),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.all(4),
+ child: Icon(Icons.info_outline_rounded, size: 18, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ ),
+ ),
+ ]),
+ subtitle: Text(
+ _skipChapterBarrier ? l.chapterBarrierOnRewindOnSubtitle : l.chapterBarrierOnRewindOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ value: _skipChapterBarrier,
+ onChanged: _loaded ? (v) {
+ setState(() => _skipChapterBarrier = v);
+ PlayerSettings.setSkipChapterBarrier(v);
+ } : null,
+ ),
+ // Long skip pair (GH #242)
+ SwitchListTile(
+ title: Text(l.longSkipButtons),
+ subtitle: Text(
+ _longSkipButtons ? l.longSkipButtonsOnSubtitle : l.longSkipButtonsOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ value: _longSkipButtons,
+ onChanged: _loaded ? (v) {
+ setState(() => _longSkipButtons = v);
+ PlayerSettings.setLongSkipButtons(v);
+ } : null,
+ ),
+ if (_longSkipButtons) ...[
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text(l.longSkipBack, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
+ Text(l.minutesValue(_longBackSkip ~/ 60), style: tt.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w600, color: cs.primary)),
],
),
- if (!isDesktopSettings ||
- expandedSection == 'Absorbing Cards')
- const SizedBox(height: 16),
-
- // ── Playback ──
- CollapsibleSection(
- key: _keyFor('Playback'),
- icon: Icons.play_circle_outline_rounded,
- title: l.sectionPlayback,
- cs: cs,
- isExpanded: expandedSection == 'Playback',
- desktopMode: isDesktopSettings,
- onExpansionChanged: (v) =>
- _onSectionExpanded('Playback', v),
+ ),
+ AbsorbSlider(
+ value: (_longBackSkip ~/ 60).toDouble(),
+ min: 1, max: 10, divisions: 9,
+ onChanged: _loaded ? (v) {
+ setState(() => _longBackSkip = v.round() * 60);
+ PlayerSettings.setLongBackSkip(v.round() * 60);
+ } : null,
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
- // Default speed
- Padding(
- padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
- child: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- children: [
- Text(l.defaultSpeed, style: tt.bodyMedium),
- Text(
- l.speedValue(
- _defaultSpeed.toStringAsFixed(2),
- ),
- style: tt.bodyMedium?.copyWith(
- fontWeight: FontWeight.w700,
- color: cs.primary,
- ),
- ),
- ],
- ),
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(16, 0, 16, 0),
- child: Text(
- l.defaultSpeedSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- fontSize: 11,
- ),
- ),
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(16, 4, 16, 0),
- child: Row(
- children: [
- GestureDetector(
- onTap: _loaded
- ? () => _setDefaultSpeed(
- _defaultSpeed - 0.05,
- )
- : null,
- child: Container(
- width: 36,
- height: 36,
- decoration: BoxDecoration(
- shape: BoxShape.circle,
- color: cs.onSurface.withValues(
- alpha: 0.08,
- ),
- ),
- child: Icon(
- Icons.remove_rounded,
- size: 20,
- color: cs.onSurface.withValues(
- alpha: 0.7,
- ),
- ),
- ),
- ),
- Expanded(
- child: AbsorbSlider(
- value: _defaultSpeed,
- min: 0.5,
- max: 3.0,
- divisions: 50,
- activeColor: cs.primary,
- onChanged: _loaded
- ? _setDefaultSpeed
- : null,
- ),
- ),
- GestureDetector(
- onTap: _loaded
- ? () => _setDefaultSpeed(
- _defaultSpeed + 0.05,
- )
- : null,
- child: Container(
- width: 36,
- height: 36,
- decoration: BoxDecoration(
- shape: BoxShape.circle,
- color: cs.onSurface.withValues(
- alpha: 0.08,
- ),
- ),
- child: Icon(
- Icons.add_rounded,
- size: 20,
- color: cs.onSurface.withValues(
- alpha: 0.7,
- ),
- ),
- ),
- ),
- ],
- ),
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(52, 0, 52, 0),
- child: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- children: [
- Text(
- '0.5x',
- style: TextStyle(
- color: cs.onSurface.withValues(
- alpha: 0.3,
- ),
- fontSize: 11,
- ),
- ),
- Text(
- '3.0x',
- style: TextStyle(
- color: cs.onSurface.withValues(
- alpha: 0.3,
- ),
- fontSize: 11,
- ),
- ),
- ],
+ Text(l.longSkipForward, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
+ Text(l.minutesValue(_longForwardSkip ~/ 60), style: tt.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w600, color: cs.primary)),
+ ],
+ ),
+ ),
+ AbsorbSlider(
+ value: (_longForwardSkip ~/ 60).toDouble(),
+ min: 1, max: 10, divisions: 9,
+ onChanged: _loaded ? (v) {
+ setState(() => _longForwardSkip = v.round() * 60);
+ PlayerSettings.setLongForwardSkip(v.round() * 60);
+ } : null,
+ ),
+ ],
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ // ── Auto-Rewind ──
+ SwitchListTile(
+ title: Text(l.autoRewindOnResume),
+ subtitle: Text(
+ _rewindSettings.enabled
+ ? l.autoRewindOnSubtitleFormat(_rewindSettings.minRewind.round().toString(), _rewindSettings.maxRewind.round().toString())
+ : l.autoRewindOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _rewindSettings.enabled,
+ onChanged: _loaded ? (v) => _saveRewind(
+ AutoRewindSettings(
+ enabled: v,
+ minRewind: _rewindSettings.minRewind,
+ maxRewind: _rewindSettings.maxRewind,
+ activationDelay: _rewindSettings.activationDelay,
+ chapterBarrier: _rewindSettings.chapterBarrier,
+ sessionStartRewind: _rewindSettings.sessionStartRewind,
+ ),
+ ) : null,
+ ),
+ if (_rewindSettings.enabled) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text(l.rewindRange, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
+ Text(l.rewindRangeValue(_rewindSettings.minRewind.round().toString(), _rewindSettings.maxRewind.round().toString()),
+ style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.primary)),
+ ],
+ ),
+ ),
+ AbsorbRangeSlider(
+ values: RangeValues(_rewindSettings.minRewind, _rewindSettings.maxRewind),
+ min: 0, max: 60, divisions: 60,
+ onChanged: (v) => _saveRewind(AutoRewindSettings(
+ enabled: true, minRewind: v.start, maxRewind: v.end,
+ activationDelay: _rewindSettings.activationDelay,
+ chapterBarrier: _rewindSettings.chapterBarrier,
+ sessionStartRewind: _rewindSettings.sessionStartRewind,
+ )),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Expanded(child: Text(l.rewindAfterPausedFor,
+ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant))),
+ Text(_rewindSettings.activationDelay == 0 ? l.rewindAnyPause : l.rewindActivationDelayValue(_rewindSettings.activationDelay.round().toString()),
+ style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.primary)),
+ ],
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8),
+ child: Slider(
+ value: _rewindSettings.activationDelay, min: 0, max: 10, divisions: 10,
+ label: _rewindSettings.activationDelay == 0 ? l.rewindAlwaysLabel : l.secondsValue(_rewindSettings.activationDelay.round().toString()),
+ onChanged: (v) => _saveRewind(AutoRewindSettings(
+ enabled: true, minRewind: _rewindSettings.minRewind,
+ maxRewind: _rewindSettings.maxRewind, activationDelay: v,
+ chapterBarrier: _rewindSettings.chapterBarrier,
+ sessionStartRewind: _rewindSettings.sessionStartRewind,
+ )),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),
+ child: Text(
+ _rewindSettings.activationDelay == 0
+ ? l.rewindAlwaysDescription
+ : l.rewindAfterDescription(_rewindSettings.activationDelay.round().toString()),
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant, fontSize: 11)),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: Text(l.chapterBarrier),
+ subtitle: Text(
+ l.chapterBarrierSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _rewindSettings.chapterBarrier,
+ onChanged: (v) => _saveRewind(AutoRewindSettings(
+ enabled: true,
+ minRewind: _rewindSettings.minRewind,
+ maxRewind: _rewindSettings.maxRewind,
+ activationDelay: _rewindSettings.activationDelay,
+ chapterBarrier: v,
+ sessionStartRewind: _rewindSettings.sessionStartRewind,
+ )),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: Row(children: [
+ Expanded(child: Text(l.rewindOnSessionStart)),
+ GestureDetector(
+ onTap: () => showDialog(
+ context: context,
+ builder: (_) => AlertDialog(
+ title: Text(l.rewindOnSessionStart),
+ content: Text(l.rewindOnSessionStartInfoContent),
+ actions: [TextButton(onPressed: () => Navigator.pop(context), child: Text(l.gotIt))],
),
),
- Padding(
- padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
- child: Wrap(
- spacing: 6,
- runSpacing: 4,
- children:
- [
- 0.75,
- 1.0,
- 1.25,
- 1.5,
- 1.75,
- 2.0,
- 2.5,
- 3.0,
- ].map((s) {
- final isActive =
- (_defaultSpeed - s).abs() < 0.01;
- return ActionChip(
- label: Text(
- l.speedValue(s.toString()),
- style: TextStyle(
- fontSize: 12,
- fontWeight: isActive
- ? FontWeight.w700
- : FontWeight.w400,
- color: isActive
- ? cs.onPrimary
- : cs.onSurface,
- ),
- ),
- backgroundColor: isActive
- ? cs.primary
- : cs.surfaceContainerHighest,
- side: BorderSide.none,
- onPressed: _loaded
- ? () => _setDefaultSpeed(s)
- : null,
- );
- }).toList(),
- ),
+ child: Padding(
+ padding: const EdgeInsets.all(4),
+ child: Icon(Icons.info_outline_rounded, size: 18, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
),
- const Divider(height: 1, indent: 16, endIndent: 16),
- ListTile(
- leading: Icon(
- Icons.refresh_rounded,
- color: cs.onSurfaceVariant,
- ),
- title: Text(l.resetSpeedPresets),
- subtitle: Text(
- l.resetSpeedPresetsSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- onTap: () async {
- await PlayerSettings.resetSpeedPresets();
- if (!mounted) return;
- showOverlayToast(
- context,
- l.speedPresetsReset,
- icon: Icons.refresh_rounded,
- );
- },
- ),
- const Divider(height: 1, indent: 16, endIndent: 16),
- // Skip amounts
- Padding(
- padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
- child: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- children: [
- Text(
- l.skipBack,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- Text(
- l.secondsValue(_backSkip.toString()),
- style: tt.bodyMedium?.copyWith(
- fontWeight: FontWeight.w600,
- color: cs.primary,
- ),
- ),
- ],
- ),
- ),
- AbsorbSlider(
- value: _backSkip.toDouble(),
- min: 5,
- max: 60,
- divisions: 11,
- onChanged: _loaded
- ? (v) {
- setState(() => _backSkip = v.round());
- PlayerSettings.setBackSkip(v.round());
- }
- : null,
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),
- child: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- children: [
- Text(
- l.skipForward,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- Text(
- l.secondsValue(_forwardSkip.toString()),
- style: tt.bodyMedium?.copyWith(
- fontWeight: FontWeight.w600,
- color: cs.primary,
- ),
- ),
- ],
- ),
- ),
- AbsorbSlider(
- value: _forwardSkip.toDouble(),
- min: 5,
- max: 60,
- divisions: 11,
- onChanged: _loaded
- ? (v) {
- setState(() => _forwardSkip = v.round());
- PlayerSettings.setForwardSkip(v.round());
- }
- : null,
- ),
- SwitchListTile(
- title: Row(
- children: [
- Expanded(
- child: Text(l.chapterBarrierOnRewind),
- ),
- GestureDetector(
- onTap: () => showDialog(
- context: context,
- builder: (dialogContext) => AlertDialog(
- title: Text(l.chapterBarrierInfoTitle),
- content: Text(
- l.chapterBarrierInfoContent,
- ),
- actions: [
- TextButton(
- onPressed: () =>
- Navigator.pop(dialogContext),
- child: Text(l.gotIt),
- ),
- ],
- ),
- ),
- child: Padding(
- padding: const EdgeInsets.all(4),
- child: Icon(
- Icons.info_outline_rounded,
- size: 18,
- color: cs.onSurfaceVariant.withValues(
- alpha: 0.5,
- ),
- ),
- ),
- ),
- ],
- ),
- subtitle: Text(
- _skipChapterBarrier
- ? l.chapterBarrierOnRewindOnSubtitle
- : l.chapterBarrierOnRewindOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _skipChapterBarrier,
- onChanged: _loaded
- ? (v) {
- setState(() => _skipChapterBarrier = v);
- PlayerSettings.setSkipChapterBarrier(v);
- }
- : null,
- ),
- // Long skip pair (GH #242)
- SwitchListTile(
- title: Text(l.longSkipButtons),
- subtitle: Text(
- _longSkipButtons
- ? l.longSkipButtonsOnSubtitle
- : l.longSkipButtonsOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _longSkipButtons,
- onChanged: _loaded
- ? (v) {
- setState(() => _longSkipButtons = v);
- PlayerSettings.setLongSkipButtons(v);
- }
- : null,
- ),
- if (_longSkipButtons) ...[
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 12,
- 16,
- 4,
- ),
- child: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- children: [
- Text(
- l.longSkipBack,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- Text(
- l.minutesValue(_longBackSkip ~/ 60),
- style: tt.bodyMedium?.copyWith(
- fontWeight: FontWeight.w600,
- color: cs.primary,
- ),
- ),
- ],
- ),
- ),
- AbsorbSlider(
- value: (_longBackSkip ~/ 60).toDouble(),
- min: 1,
- max: 10,
- divisions: 9,
- onChanged: _loaded
- ? (v) {
- setState(
- () => _longBackSkip = v.round() * 60,
- );
- PlayerSettings.setLongBackSkip(
- v.round() * 60,
- );
- }
- : null,
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 0,
- 16,
- 4,
- ),
- child: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- children: [
- Text(
- l.longSkipForward,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- Text(
- l.minutesValue(_longForwardSkip ~/ 60),
- style: tt.bodyMedium?.copyWith(
- fontWeight: FontWeight.w600,
- color: cs.primary,
- ),
- ),
- ],
- ),
- ),
- AbsorbSlider(
- value: (_longForwardSkip ~/ 60).toDouble(),
- min: 1,
- max: 10,
- divisions: 9,
- onChanged: _loaded
- ? (v) {
- setState(
- () =>
- _longForwardSkip = v.round() * 60,
- );
- PlayerSettings.setLongForwardSkip(
- v.round() * 60,
- );
- }
- : null,
- ),
- ],
- const Divider(height: 1, indent: 16, endIndent: 16),
- // ── Auto-Rewind ──
- SwitchListTile(
- title: Text(l.autoRewindOnResume),
- subtitle: Text(
- _rewindSettings.enabled
- ? l.autoRewindOnSubtitleFormat(
- _rewindSettings.minRewind
- .round()
- .toString(),
- _rewindSettings.maxRewind
- .round()
- .toString(),
- )
- : l.autoRewindOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _rewindSettings.enabled,
- onChanged: _loaded
- ? (v) => _saveRewind(
- AutoRewindSettings(
- enabled: v,
- minRewind: _rewindSettings.minRewind,
- maxRewind: _rewindSettings.maxRewind,
- activationDelay:
- _rewindSettings.activationDelay,
- chapterBarrier:
- _rewindSettings.chapterBarrier,
- sessionStartRewind:
- _rewindSettings.sessionStartRewind,
- ),
- )
- : null,
- ),
- if (_rewindSettings.enabled) ...[
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 12,
- 16,
- 4,
- ),
- child: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- children: [
- Text(
- l.rewindRange,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- Text(
- l.rewindRangeValue(
- _rewindSettings.minRewind
- .round()
- .toString(),
- _rewindSettings.maxRewind
- .round()
- .toString(),
- ),
- style: tt.bodyMedium?.copyWith(
- fontWeight: FontWeight.w600,
- color: cs.primary,
- ),
- ),
- ],
- ),
- ),
- AbsorbRangeSlider(
- values: RangeValues(
- _rewindSettings.minRewind,
- _rewindSettings.maxRewind,
- ),
- min: 0,
- max: 60,
- divisions: 60,
- onChanged: (v) => _saveRewind(
- AutoRewindSettings(
- enabled: true,
- minRewind: v.start,
- maxRewind: v.end,
- activationDelay:
- _rewindSettings.activationDelay,
- chapterBarrier:
- _rewindSettings.chapterBarrier,
- sessionStartRewind:
- _rewindSettings.sessionStartRewind,
- ),
- ),
- ),
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 12,
- 16,
- 4,
- ),
- child: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- children: [
- Expanded(
- child: Text(
- l.rewindAfterPausedFor,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- ),
- Text(
- _rewindSettings.activationDelay == 0
- ? l.rewindAnyPause
- : l.rewindActivationDelayValue(
- _rewindSettings.activationDelay
- .round()
- .toString(),
- ),
- style: tt.bodyMedium?.copyWith(
- fontWeight: FontWeight.w600,
- color: cs.primary,
- ),
- ),
- ],
- ),
- ),
- Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 8,
- ),
- child: Slider(
- value: _rewindSettings.activationDelay,
- min: 0,
- max: 10,
- divisions: 10,
- label: _rewindSettings.activationDelay == 0
- ? l.rewindAlwaysLabel
- : l.secondsValue(
- _rewindSettings.activationDelay
- .round()
- .toString(),
- ),
- onChanged: (v) => _saveRewind(
- AutoRewindSettings(
- enabled: true,
- minRewind: _rewindSettings.minRewind,
- maxRewind: _rewindSettings.maxRewind,
- activationDelay: v,
- chapterBarrier:
- _rewindSettings.chapterBarrier,
- sessionStartRewind:
- _rewindSettings.sessionStartRewind,
- ),
- ),
- ),
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 0,
- 16,
- 4,
- ),
- child: Text(
- _rewindSettings.activationDelay == 0
- ? l.rewindAlwaysDescription
- : l.rewindAfterDescription(
- _rewindSettings.activationDelay
- .round()
- .toString(),
- ),
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- fontSize: 11,
- ),
- ),
- ),
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- SwitchListTile(
- title: Text(l.chapterBarrier),
- subtitle: Text(
- l.chapterBarrierSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _rewindSettings.chapterBarrier,
- onChanged: (v) => _saveRewind(
- AutoRewindSettings(
- enabled: true,
- minRewind: _rewindSettings.minRewind,
- maxRewind: _rewindSettings.maxRewind,
- activationDelay:
- _rewindSettings.activationDelay,
- chapterBarrier: v,
- sessionStartRewind:
- _rewindSettings.sessionStartRewind,
- ),
- ),
- ),
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- SwitchListTile(
- title: Row(
- children: [
- Expanded(
- child: Text(l.rewindOnSessionStart),
- ),
- GestureDetector(
- onTap: () => showDialog(
- context: context,
- builder: (dialogContext) => AlertDialog(
- title: Text(l.rewindOnSessionStart),
- content: Text(
- l.rewindOnSessionStartInfoContent,
- ),
- actions: [
- TextButton(
- onPressed: () =>
- Navigator.pop(dialogContext),
- child: Text(l.gotIt),
- ),
- ],
- ),
- ),
- child: Padding(
- padding: const EdgeInsets.all(4),
- child: Icon(
- Icons.info_outline_rounded,
- size: 18,
- color: cs.onSurfaceVariant.withValues(
- alpha: 0.5,
- ),
- ),
- ),
- ),
- ],
- ),
- subtitle: Text(
- _rewindSettings.sessionStartRewind
- ? l.rewindOnSessionStartOnSubtitle(
- _rewindSettings.maxRewind
- .round()
- .toString(),
- )
- : l.autoRewindOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _rewindSettings.sessionStartRewind,
- onChanged: (v) => _saveRewind(
- AutoRewindSettings(
- enabled: true,
- minRewind: _rewindSettings.minRewind,
- maxRewind: _rewindSettings.maxRewind,
- activationDelay:
- _rewindSettings.activationDelay,
- chapterBarrier:
- _rewindSettings.chapterBarrier,
- sessionStartRewind: v,
- ),
- ),
- ),
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 8,
- 16,
- 12,
- ),
- child: Container(
- padding: const EdgeInsets.all(12),
- decoration: BoxDecoration(
- color: cs.surfaceContainerHighest,
- borderRadius: BorderRadius.circular(12),
- ),
- child: Column(
- crossAxisAlignment:
- CrossAxisAlignment.start,
- children: [
- Text(
- l.preview,
- style: tt.labelSmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- const SizedBox(height: 4),
- ..._buildRewindPreviews(cs, tt, l),
- ],
- ),
- ),
- ),
- ],
- ],
- ),
- if (!isDesktopSettings || expandedSection == 'Playback')
- const SizedBox(height: 16),
-
- // ── Media Controls ──
- if (!isDesktopSettings) ...[
- CollapsibleSection(
- key: _keyFor('Media Controls'),
- icon: Icons.dvr_rounded,
- title: l.sectionMediaControls,
- cs: cs,
- isExpanded: expandedSection == 'Media Controls',
- desktopMode: isDesktopSettings,
- onExpansionChanged: (v) =>
- _onSectionExpanded('Media Controls', v),
- children: [
- SwitchListTile(
- title: Text(
- AppPlatform.isIOS
- ? l.chapterProgressInNotificationIos
- : l.chapterProgressInNotification,
- ),
- subtitle: Text(
- _notifChapterProgress
- ? (AppPlatform.isIOS
- ? l.chapterProgressOnSubtitleIos
- : l.chapterProgressOnSubtitle)
- : l.chapterProgressOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _notifChapterProgress,
- onChanged: _loaded
- ? (v) {
- setState(
- () => _notifChapterProgress = v,
- );
- PlayerSettings.setNotificationChapterProgress(
- v,
- );
- }
- : null,
- ),
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- // Cross-platform: drops the seek action so the scrubber in the
- // notification / lockscreen / car can't be dragged.
- SwitchListTile(
- title: Text(l.lockSeekBar),
- subtitle: Text(
- _lockSeekBar
- ? l.lockSeekBarOnSubtitle
- : l.lockSeekBarOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _lockSeekBar,
- onChanged: _loaded
- ? (v) {
- setState(() => _lockSeekBar = v);
- PlayerSettings.setLockSeekBar(v);
- }
- : null,
- ),
- // Android only: chooses which pair fills the phone media
- // player's two extra slots. iOS uses CarPlay's own buttons.
- if (AppPlatform.isAndroid) ...[
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- SwitchListTile(
- title: const Text('Duck brief interruptions'),
- subtitle: Text(
- _duckBriefInterruptions
- ? 'Notifications and prompts lower the volume instead of pausing'
- : 'Notifications and prompts pause playback',
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _duckBriefInterruptions,
- onChanged: _loaded
- ? (v) {
- setState(
- () => _duckBriefInterruptions = v,
- );
- PlayerSettings.setDuckBriefInterruptions(
- v,
- );
- }
- : null,
- ),
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- SwitchListTile(
- title: Text(l.speedBookmarkInControls),
- subtitle: Text(
- _notifSpeedBookmark
- ? l.speedBookmarkOnSubtitle
- : l.speedBookmarkOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _notifSpeedBookmark,
- onChanged: _loaded
- ? (v) {
- setState(
- () => _notifSpeedBookmark = v,
- );
- PlayerSettings.setMediaControlsSpeedBookmark(
- v,
- );
- }
- : null,
- ),
- ],
- ],
- ),
- const SizedBox(height: 16),
- ],
-
- // ── Sleep Timer ──
- CollapsibleSection(
- key: _keyFor('Sleep Timer'),
- icon: Icons.bedtime_outlined,
- title: l.sectionSleepTimer,
- cs: cs,
- isExpanded: expandedSection == 'Sleep Timer',
- desktopMode: isDesktopSettings,
- onExpansionChanged: (v) =>
- _onSectionExpanded('Sleep Timer', v),
- children: [
- if (!AppPlatform.isWeb) ...[
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 8,
- 16,
- 4,
- ),
- child: Text(
- l.shakeDuringSleepTimer,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 8,
- 16,
- 8,
- ),
- child: SizedBox(
- width: double.infinity,
- child: SegmentedButton<String>(
- showSelectedIcon: false,
- segments: [
- ButtonSegment(
- value: 'off',
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(l.shakeOff),
- ),
- ),
- ButtonSegment(
- value: 'addTime',
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(l.shakeAddTime),
- ),
- ),
- ButtonSegment(
- value: 'resetTimer',
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(l.shakeReset),
- ),
- ),
- ],
- selected: {_shakeMode},
- onSelectionChanged: _loaded
- ? (v) {
- setState(
- () => _shakeMode = v.first,
- );
- PlayerSettings.setShakeMode(
- v.first,
- );
- SleepTimerService()
- .restartShakeDetection();
- }
- : null,
- ),
- ),
- ),
- if (_shakeMode != 'off') ...[
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 12,
- 16,
- 4,
- ),
- child: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- children: [
- Text(
- l.shakeSensitivity,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- Text(
- _shakeSensitivityLabel(
- l,
- _shakeSensitivity,
- ),
- style: tt.bodyMedium?.copyWith(
- fontWeight: FontWeight.w600,
- color: cs.primary,
- ),
- ),
- ],
- ),
- ),
- AbsorbSlider(
- value: _shakeSensitivityIndex(
- _shakeSensitivity,
- ).toDouble(),
- min: 0,
- max: 4,
- divisions: 4,
- onChanged: _loaded
- ? (v) {
- final key = _shakeSensitivityKey(
- v.round(),
- );
- setState(
- () => _shakeSensitivity = key,
- );
- PlayerSettings.setShakeSensitivity(
- key,
- );
- SleepTimerService()
- .restartShakeDetection();
- }
- : null,
- ),
- const SizedBox(height: 4),
- ],
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 12,
- 16,
- 0,
- ),
- child: Text(
- l.buttonDuringSleepTimer,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 8,
- 16,
- 8,
- ),
- child: SizedBox(
- width: double.infinity,
- child: SegmentedButton<String>(
- showSelectedIcon: false,
- segments: [
- ButtonSegment(
- value: 'off',
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(l.shakeOff),
- ),
- ),
- ButtonSegment(
- value: 'addTime',
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(l.shakeAddTime),
- ),
- ),
- ButtonSegment(
- value: 'resetTimer',
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(l.shakeReset),
- ),
- ),
- ],
- selected: {_sleepButtonMode},
- onSelectionChanged: _loaded
- ? (v) {
- setState(
- () => _sleepButtonMode = v.first,
- );
- PlayerSettings.setSleepButtonMode(
- v.first,
- );
- }
- : null,
- ),
- ),
- ),
- if (_sleepButtonMode != 'off')
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 0,
- 16,
- 8,
- ),
- child: Text(
- l.buttonDuringSleepTimerHint,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant.withValues(
- alpha: 0.7,
- ),
- fontSize: 11,
- ),
- ),
- ),
- // Shared by shake and button add-time modes, so
- // it shows whenever either trigger needs it
- if (_shakeMode == 'addTime' ||
- _sleepButtonMode == 'addTime') ...[
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 12,
- 16,
- 4,
- ),
- child: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- children: [
- Text(
- l.sleepAddAmount,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- Text(
- l.shakeAddsValue(_shakeAddMinutes),
- style: tt.bodyMedium?.copyWith(
- fontWeight: FontWeight.w600,
- color: cs.primary,
- ),
- ),
- ],
- ),
- ),
- AbsorbSlider(
- value: _shakeAddMinutes.toDouble(),
- min: 1,
- max: 30,
- divisions: 29,
- onChanged: _loaded
- ? (v) {
- setState(
- () => _shakeAddMinutes = v.round(),
- );
- PlayerSettings.setShakeAddMinutes(
- v.round(),
- );
- }
- : null,
- ),
- const SizedBox(height: 4),
- ],
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- ],
- SwitchListTile(
- title: Text(l.resetTimerOnPause),
- subtitle: Text(
- _resetSleepOnPause
- ? l.resetTimerOnPauseOnSubtitle
- : l.resetTimerOnPauseOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _resetSleepOnPause,
- onChanged: _loaded
- ? (v) {
- setState(() => _resetSleepOnPause = v);
- PlayerSettings.setResetSleepOnPause(v);
- }
- : null,
- ),
- const Divider(height: 1, indent: 16, endIndent: 16),
- Padding(
- padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
- child: Row(
- children: [
- Icon(
- Icons.replay_rounded,
- size: 18,
- color: _sleepRewindSeconds > 0
- ? cs.primary
- : cs.onSurfaceVariant,
- ),
- const SizedBox(width: 10),
- Expanded(
- child: Text(
- l.sleepTimerSheetRewindOnSleep,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- ),
- Text(
- _rewindLabel(_sleepRewindSeconds, l),
- style: tt.bodyMedium?.copyWith(
- fontWeight: FontWeight.w600,
- color: _sleepRewindSeconds > 0
- ? cs.primary
- : cs.onSurfaceVariant,
- ),
- ),
- ],
- ),
- ),
- AbsorbSlider(
- value: (_sleepRewindSeconds / 60).clamp(
- 0.0,
- _maxRewindMinutes.toDouble(),
- ),
- min: 0,
- max: _maxRewindMinutes.toDouble(),
- divisions: _maxRewindMinutes,
- onChanged: _loaded
- ? (v) {
- final seconds = (v * 60).round();
- setState(
- () => _sleepRewindSeconds = seconds,
- );
- PlayerSettings.setSleepRewindSeconds(
- seconds,
- );
- }
- : null,
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(28, 0, 28, 4),
- child: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- children: [
- Text(
- l.off,
- style: TextStyle(
- color: cs.onSurface.withValues(
- alpha: 0.3,
- ),
- fontSize: 11,
- ),
- ),
- Text(
- l.sleepTimerSheetMinShort(
- _maxRewindMinutes,
- ),
- style: TextStyle(
- color: cs.onSurface.withValues(
- alpha: 0.3,
- ),
- fontSize: 11,
- ),
- ),
- ],
- ),
- ),
- if (_sleepRewindSeconds > 0)
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 28,
- 0,
- 28,
- 10,
- ),
- child: Text(
- l.sleepRewindUndoNote(
- SleepTimerService
- .sleepRewindUndoWindow
- .inMinutes,
- ),
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- ),
- const Divider(height: 1, indent: 16, endIndent: 16),
- SwitchListTile(
- title: Text(l.fadeVolumeBeforeSleep),
- subtitle: Text(
- _sleepFadeOut
- ? l.fadeVolumeOnSubtitleDynamic(
- _sleepFadeDuration,
- )
- : l.fadeVolumeOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _sleepFadeOut,
- onChanged: _loaded
- ? (v) {
- setState(() => _sleepFadeOut = v);
- PlayerSettings.setSleepFadeOut(v);
- }
- : null,
- ),
- const Divider(height: 1, indent: 16, endIndent: 16),
- SwitchListTile(
- title: Text(l.chimeBeforeSleep),
- subtitle: Text(
- _sleepChime
- ? l.chimeBeforeSleepOnSubtitle
- : l.chimeBeforeSleepOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _sleepChime,
- onChanged: _loaded
- ? (v) {
- setState(() => _sleepChime = v);
- PlayerSettings.setSleepChime(v);
- }
- : null,
- ),
- if (_sleepChime) ...[
- Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 16,
- ),
- child: Row(
- children: [
- Icon(
- Icons.volume_down_rounded,
- size: 18,
- color: cs.onSurfaceVariant,
- ),
- Expanded(
- child: Slider(
- value: _sleepChimeVolume,
- min: 0.5,
- max: 3.0,
- divisions: 10,
- label:
- '${(_sleepChimeVolume * 100 / 3).round()}%',
- onChanged: _loaded
- ? (v) {
- setState(
- () => _sleepChimeVolume = v,
- );
- PlayerSettings.setSleepChimeVolume(
- v,
- );
- }
- : null,
- ),
- ),
- Icon(
- Icons.volume_up_rounded,
- size: 18,
- color: cs.onSurfaceVariant,
- ),
- ],
- ),
- ),
- ],
- if (_sleepFadeOut || _sleepChime) ...[
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- ListTile(
- title: Text(l.windDownDuration),
- subtitle: Text(
- l.windDownDurationSubtitle(
- _sleepFadeDuration,
- ),
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- ),
- Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 16,
- ),
- child: Row(
- children: [
- Text(
- l.secondsValue(
- _sleepFadeDuration.toString(),
- ),
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- Expanded(
- child: Slider(
- value: _sleepFadeDuration.toDouble(),
- min: 10,
- max: 60,
- divisions: 10,
- label: l.secondsValue(
- _sleepFadeDuration.toString(),
- ),
- onChanged: _loaded
- ? (v) {
- setState(
- () => _sleepFadeDuration = v
- .round(),
- );
- PlayerSettings.setSleepFadeDuration(
- v.round(),
- );
- }
- : null,
- ),
- ),
- ],
- ),
- ),
- ],
- const Divider(height: 1, indent: 16, endIndent: 16),
- // ── Auto Sleep Timer ──
- SwitchListTile(
- title: Text(l.autoSleepTimer),
- subtitle: Text(
- _autoSleepSettings.enabled
- ? l.autoSleepTimerEnabledSubtitle(
- _autoSleepSettings.startLabel,
- _autoSleepSettings.endLabel,
- _autoSleepSettings.useEndOfChapter
- ? l.endOfChapterShort
- : l.shakeAddsValue(
- _autoSleepSettings
- .durationMinutes,
- ),
- )
- : l.autoSleepTimerOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _autoSleepSettings.enabled,
- onChanged: _loaded
- ? (v) {
- final updated = _autoSleepSettings
- .copyWith(enabled: v);
- setState(
- () => _autoSleepSettings = updated,
- );
- updated.save();
- SleepTimerService()
- .updateAutoSleepSettings(updated);
- }
- : null,
- ),
- if (_autoSleepSettings.enabled) ...[
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- // Start time picker
- ListTile(
- title: Text(l.windowStart),
- trailing: Text(
- _autoSleepSettings.startLabel,
- style: tt.bodyMedium?.copyWith(
- fontWeight: FontWeight.w600,
- color: cs.primary,
- ),
- ),
- onTap: () async {
- final picked = await showTimePicker(
- context: context,
- initialTime: TimeOfDay(
- hour: _autoSleepSettings.startHour,
- minute: _autoSleepSettings.startMinute,
- ),
- );
- if (picked != null) {
- final updated = _autoSleepSettings.copyWith(
- startHour: picked.hour,
- startMinute: picked.minute,
- );
- setState(
- () => _autoSleepSettings = updated,
- );
- updated.save();
- SleepTimerService().updateAutoSleepSettings(
- updated,
- );
- }
- },
- ),
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- // End time picker
- ListTile(
- title: Text(l.windowEnd),
- trailing: Text(
- _autoSleepSettings.endLabel,
- style: tt.bodyMedium?.copyWith(
- fontWeight: FontWeight.w600,
- color: cs.primary,
- ),
- ),
- onTap: () async {
- final picked = await showTimePicker(
- context: context,
- initialTime: TimeOfDay(
- hour: _autoSleepSettings.endHour,
- minute: _autoSleepSettings.endMinute,
- ),
- );
- if (picked != null) {
- final updated = _autoSleepSettings.copyWith(
- endHour: picked.hour,
- endMinute: picked.minute,
- );
- setState(
- () => _autoSleepSettings = updated,
- );
- updated.save();
- SleepTimerService().updateAutoSleepSettings(
- updated,
- );
- }
- },
- ),
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- // End of chapter toggle
- SwitchListTile(
- title: Text(l.endOfChapterShort),
- subtitle: Text(
- _autoSleepSettings.useEndOfChapter
- ? l.endOfChapterOnSubtitle
- : l.endOfChapterOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _autoSleepSettings.useEndOfChapter,
- onChanged: _loaded
- ? (v) {
- final updated = _autoSleepSettings
- .copyWith(useEndOfChapter: v);
- setState(
- () => _autoSleepSettings = updated,
- );
- updated.save();
- SleepTimerService()
- .updateAutoSleepSettings(updated);
- }
- : null,
- ),
- // Duration slider (only for timed mode)
- if (!_autoSleepSettings.useEndOfChapter) ...[
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 12,
- 16,
- 4,
- ),
- child: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- children: [
- Text(
- l.timerDuration,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- Text(
- l.shakeAddsValue(
- _autoSleepSettings.durationMinutes,
- ),
- style: tt.bodyMedium?.copyWith(
- fontWeight: FontWeight.w600,
- color: cs.primary,
- ),
- ),
- ],
- ),
- ),
- AbsorbSlider(
- value: _autoSleepSettings.durationMinutes
- .toDouble(),
- min: 5,
- max: 120,
- divisions: 23,
- onChanged: _loaded
- ? (v) {
- final updated = _autoSleepSettings
- .copyWith(
- durationMinutes: v.round(),
- );
- setState(
- () => _autoSleepSettings = updated,
- );
- updated.save();
- SleepTimerService()
- .updateAutoSleepSettings(updated);
- }
- : null,
- ),
- ],
- const SizedBox(height: 4),
- ],
- ],
- ),
- if (!isDesktopSettings ||
- expandedSection == 'Sleep Timer')
- const SizedBox(height: 16),
-
- // ── Downloads & Storage ──
- if (!AppPlatform.isWeb)
- CollapsibleSection(
- key: _keyFor('Downloads & Storage'),
- icon: Icons.download_outlined,
- title: l.sectionDownloadsAndStorage,
- cs: cs,
- isExpanded:
- expandedSection == 'Downloads & Storage',
- desktopMode: isDesktopSettings,
- onExpansionChanged: (v) =>
- _onSectionExpanded('Downloads & Storage', v),
- children: [
- Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 16,
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- const SizedBox(height: 12),
- Text(
- l.downloadOverWifiOnly,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurface,
- ),
- ),
- const SizedBox(height: 8),
- SizedBox(
- width: double.infinity,
- child: SegmentedButton<bool>(
- showSelectedIcon: false,
- segments: [
- ButtonSegment(
- value: true,
- label: Text(
- l.downloadOverWifiOnSubtitle,
- ),
- ),
- ButtonSegment(
- value: false,
- label: Text(
- l.downloadOverWifiOffSubtitle,
- ),
- ),
- ],
- selected: {_wifiOnlyDownloads},
- onSelectionChanged: _loaded
- ? (v) {
- setState(
- () => _wifiOnlyDownloads =
- v.first,
- );
- PlayerSettings.setWifiOnlyDownloads(
- v.first,
- );
- }
- : null,
- ),
- ),
- const SizedBox(height: 8),
- ],
- ),
- ),
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- SwitchListTile(
- title: Row(
- children: [
- Flexible(child: Text(l.autoDownloadOnWifi)),
- _infoIcon(
- l.autoDownloadOnWifiInfoTitle,
- l.autoDownloadOnWifiInfoContent,
- ),
- ],
- ),
- subtitle: Text(
- _autoDownloadOnStream
- ? l.autoDownloadOnWifiOnSubtitle
- : l.autoDownloadOnWifiOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _autoDownloadOnStream,
- onChanged: _loaded
- ? (v) {
- setState(
- () => _autoDownloadOnStream = v,
- );
- PlayerSettings.setAutoDownloadOnStream(
- v,
- );
- }
- : null,
- ),
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- SwitchListTile(
- title: const Text('Auto-download series'),
- subtitle: Text(
- _autoSeriesDownloadDefault
- ? 'Starting a book in a series keeps the next books downloaded'
- : 'Turn on series downloads yourself from the series menu',
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _autoSeriesDownloadDefault,
- onChanged: _loaded
- ? (v) {
- setState(
- () => _autoSeriesDownloadDefault = v,
- );
- PlayerSettings.setAutoSeriesDownloadDefault(
- v,
- );
- }
- : null,
- ),
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 16,
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- const SizedBox(height: 12),
- Text(
- l.concurrentDownloads,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurface,
- ),
- ),
- const SizedBox(height: 8),
- SizedBox(
- width: double.infinity,
- child: SegmentedButton<int>(
- showSelectedIcon: false,
- segments: const [
- ButtonSegment(
- value: 1,
- label: Text('1'),
- ),
- ButtonSegment(
- value: 2,
- label: Text('2'),
- ),
- ButtonSegment(
- value: 3,
- label: Text('3'),
- ),
- ButtonSegment(
- value: 4,
- label: Text('4'),
- ),
- ButtonSegment(
- value: 5,
- label: Text('5'),
- ),
- ],
- selected: {_maxConcurrentDownloads},
- onSelectionChanged: (v) {
- setState(
- () => _maxConcurrentDownloads =
- v.first,
- );
- PlayerSettings.setMaxConcurrentDownloads(
- v.first,
- );
- },
- ),
- ),
- const SizedBox(height: 8),
- ],
- ),
- ),
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- ListTile(
- title: Text(l.autoDownload),
- subtitle: Text(
- l.autoDownloadSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- leading: Icon(
- Icons.downloading_rounded,
- color: cs.primary,
- ),
- ),
- _buildAutoDownloadSources(lib, l, cs, tt),
- Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 16,
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Row(
- children: [
- Text(
- l.keepNext,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurface,
- ),
- ),
- _infoIcon(
- l.keepNextInfoTitle,
- l.keepNextInfoContent,
- ),
- ],
- ),
- const SizedBox(height: 8),
- SizedBox(
- width: double.infinity,
- child: SegmentedButton<int>(
- showSelectedIcon: false,
- segments: const [
- ButtonSegment(
- value: 2,
- label: Text('2'),
- ),
- ButtonSegment(
- value: 3,
- label: Text('3'),
- ),
- ButtonSegment(
- value: 4,
- label: Text('4'),
- ),
- ButtonSegment(
- value: 5,
- label: Text('5'),
- ),
- ],
- selected: {_rollingDownloadCount},
- onSelectionChanged: (v) async {
- setState(
- () =>
- _rollingDownloadCount = v.first,
- );
- await PlayerSettings.setRollingDownloadCount(
- v.first,
- );
- if (_queueAutoDownload) {
- unawaited(
- lib.syncQueueAutoDownloads(),
- );
- }
- },
- ),
- ),
- const SizedBox(height: 8),
- ],
- ),
- ),
- SwitchListTile(
- title: Row(
- children: [
- Flexible(
- child: Text(
- Wording.of(
- context,
- ).deleteAbsorbedDownloads,
- ),
- ),
- _infoIcon(
- Wording.of(
- context,
- ).deleteAbsorbedDownloadsInfoTitle,
- l.deleteAbsorbedDownloadsInfoContent,
- ),
- ],
- ),
- subtitle: Text(
- _rollingDownloadDeleteFinished
- ? l.deleteAbsorbedOnSubtitle
- : l.deleteAbsorbedOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _rollingDownloadDeleteFinished,
- onChanged: _loaded
- ? (v) {
- setState(
- () => _rollingDownloadDeleteFinished =
- v,
- );
- PlayerSettings.setRollingDownloadDeleteFinished(
- v,
- );
- }
- : null,
- ),
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- if (!AppPlatform.isIOS &&
- _canPickDownloadLocation)
- ListTile(
- leading: Icon(
- Icons.folder_outlined,
- color: cs.primary,
- ),
- title: Text(l.downloadLocation),
- subtitle: Text(
- _downloadLocationLabel,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- ),
- trailing: const Icon(Icons.chevron_right),
- onTap: () =>
- _pickDownloadLocation(context, cs, tt),
- ),
- if (_totalDownloadSizeBytes > 0 ||
- _deviceTotalBytes > 0) ...[
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- ListTile(
- leading: Icon(
- Icons.data_usage_rounded,
- color: cs.onSurfaceVariant,
- ),
- title: Text(l.storageUsed),
- subtitle: Text(
- [
- if (_totalDownloadSizeBytes > 0)
- l.storageUsedByDownloads(
- _formatBytes(_totalDownloadSizeBytes),
- ),
- if (_deviceTotalBytes > 0)
- l.storageFreeOfTotal(
- _formatBytes(_deviceAvailableBytes),
- _formatBytes(_deviceTotalBytes),
- ),
- ].join('\n'),
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- isThreeLine:
- _totalDownloadSizeBytes > 0 &&
- _deviceTotalBytes > 0,
- ),
- ],
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- ListTile(
- leading: Icon(
- Icons.storage_rounded,
- color: cs.primary,
- ),
- title: Text(l.manageDownloads),
- trailing: const Icon(Icons.chevron_right),
- onTap: () => Navigator.push(
- context,
- MaterialPageRoute(
- builder: (_) => const DownloadsScreen(),
- ),
- ),
- ),
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 16,
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- const SizedBox(height: 12),
- Row(
- children: [
- Text(
- l.streamingCache,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurface,
- ),
- ),
- _infoIcon(
- l.streamingCacheInfoTitle,
- l.streamingCacheInfoContent,
- ),
- ],
- ),
- const SizedBox(height: 4),
- Text(
- _streamingCacheSizeMb == 0
- ? l.streamingCacheOffSubtitle
- : l.streamingCacheOnSubtitle(
- _streamingCacheSizeMb,
- ),
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- const SizedBox(height: 8),
- SizedBox(
- width: double.infinity,
- child: SegmentedButton<int>(
- showSelectedIcon: false,
- segments: [
- ButtonSegment(
- value: 0,
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text(l.streamingCacheOff),
- ),
- ),
- const ButtonSegment(
- value: 128,
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text('128 MB'),
- ),
- ),
- const ButtonSegment(
- value: 256,
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text('256 MB'),
- ),
- ),
- const ButtonSegment(
- value: 512,
- label: FittedBox(
- fit: BoxFit.scaleDown,
- child: Text('512 MB'),
- ),
- ),
- ],
- selected: {_streamingCacheSizeMb},
- onSelectionChanged: (v) {
- setState(
- () =>
- _streamingCacheSizeMb = v.first,
- );
- PlayerSettings.setStreamingCacheSizeMb(
- v.first,
- );
- },
- ),
- ),
- if (_streamingCacheSizeMb > 0) ...[
- const SizedBox(height: 8),
- TextButton.icon(
- icon: const Icon(
- Icons.delete_sweep_outlined,
- size: 18,
- ),
- label: Text(l.clearCache),
- onPressed: () async {
- try {
- await AudioPlayer.clearStreamingCache();
- } catch (_) {}
- if (mounted) {
- showOverlayToast(
- context,
- l.streamingCacheCleared,
- icon:
- Icons.delete_outline_rounded,
- );
- }
- },
- ),
- ],
- const SizedBox(height: 8),
- ],
- ),
- ),
- ],
- ),
- if (!isDesktopSettings ||
- expandedSection == 'Downloads & Storage')
- const SizedBox(height: 16),
-
- // ── Library ──
- CollapsibleSection(
- key: _keyFor('Library'),
- icon: Icons.auto_stories_outlined,
- title: l.sectionLibrary,
- cs: cs,
- isExpanded: expandedSection == 'Library',
- desktopMode: isDesktopSettings,
- onExpansionChanged: (v) =>
- _onSectionExpanded('Library', v),
- children: [
- Consumer<LibraryProvider>(
- builder: (context, lib, _) {
- final podcastLibs = lib.libraries
- .whereType<Map<String, dynamic>>()
- .where(
- (l) =>
- (l['mediaType'] as String? ??
- 'book') ==
- 'podcast',
- )
- .toList();
- if (podcastLibs.isEmpty)
- return const SizedBox.shrink();
- final currentName =
- podcastLibs.firstWhere(
- (p) =>
- p['id'] == _podcastTabLibraryId,
- orElse: () => podcastLibs.first,
- )['name']
- as String? ??
- '';
- return Column(
- children: [
- SwitchListTile(
- title: Text(l.settingsPodcastTab),
- subtitle: Text(
- l.settingsPodcastTabDesc,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _podcastTabEnabled,
- onChanged: _loaded
- ? (v) async {
- var libId = _podcastTabLibraryId;
- if (v &&
- !podcastLibs.any(
- (p) => p['id'] == libId,
- )) {
- libId =
- podcastLibs.first['id']
- as String;
- await PlayerSettings.setPodcastTabLibraryId(
- libId,
- );
- }
- setState(() {
- _podcastTabEnabled = v;
- _podcastTabLibraryId = libId;
- });
- await PlayerSettings.setPodcastTabEnabled(
- v,
- );
- }
- : null,
- ),
- if (_podcastTabEnabled &&
- podcastLibs.length > 1)
- ListTile(
- title: Text(
- l.settingsPodcastTabLibrary,
- ),
- subtitle: Text(
- currentName,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- trailing: Icon(
- Icons.chevron_right_rounded,
- color: cs.onSurfaceVariant,
- ),
- onTap: () =>
- _pickPodcastTabLibrary(podcastLibs),
- ),
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- ],
- );
- },
- ),
- SwitchListTile(
- title: Text(l.hideEbookOnlyTitles),
- subtitle: Text(
- _hideEbookOnly
- ? l.hideEbookOnlyOnSubtitle
- : l.hideEbookOnlyOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _hideEbookOnly,
- onChanged: _loaded
- ? (v) {
- setState(() => _hideEbookOnly = v);
- PlayerSettings.setHideEbookOnly(v);
- }
- : null,
- ),
- const Divider(height: 1, indent: 16, endIndent: 16),
- SwitchListTile(
- title: Text(l.showGoodreadsButton),
- subtitle: Text(
- _showGoodreadsButton
- ? l.showGoodreadsOnSubtitle
- : l.showGoodreadsOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _showGoodreadsButton,
- onChanged: _loaded
- ? (v) {
- setState(() => _showGoodreadsButton = v);
- PlayerSettings.setShowGoodreadsButton(v);
- }
- : null,
- ),
- const Divider(height: 1, indent: 16, endIndent: 16),
- SwitchListTile(
- title: Text(l.showExplicitBadge),
- subtitle: Text(
- _showExplicitBadge
- ? l.showExplicitBadgeOnSubtitle
- : l.showExplicitBadgeOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _showExplicitBadge,
- onChanged: _loaded
- ? (v) {
- setState(() => _showExplicitBadge = v);
- PlayerSettings.setShowExplicitBadge(v);
- }
- : null,
- ),
- if (lib.libraries.length > 1) ...[
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- ...lib.libraries.map((library) {
- final id = library['id'] as String;
- final name =
- library['name'] as String? ??
- l.libraryFallback;
- final mediaType =
- library['mediaType'] as String? ?? 'book';
- final isSelected = id == lib.selectedLibraryId;
- return ListTile(
- leading: Icon(
- mediaType == 'podcast'
- ? Icons.podcasts_rounded
- : Icons.auto_stories_rounded,
- color: isSelected
- ? cs.primary
- : cs.onSurfaceVariant,
- ),
- title: Text(name),
- trailing: isSelected
- ? Icon(
- Icons.check_circle_rounded,
- color: cs.primary,
- )
- : null,
- onTap: () {
- if (!isSelected) lib.selectLibrary(id);
- },
- );
- }),
- ],
- if (_curLibId != null) ...[
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 12,
- 16,
- 2,
- ),
- child: Text(
- l.currentLibrarySettingsTitle(
- lib.selectedLibrary?['name'] as String? ??
- l.libraryFallback,
- ),
- style: tt.titleSmall,
- ),
- ),
- InkWell(
- onTap: _loaded
- ? () => _pickCurrentLibraryCoverShape()
- : null,
- child: Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 14,
- 16,
- 14,
- ),
- child: Row(
- children: [
- Expanded(child: Text(l.coverShapeLabel)),
- Text(
- _coverShapeValueLabel(
- l,
- _curLibCoverShape,
- ),
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- Icon(
- Icons.chevron_right_rounded,
- color: cs.onSurfaceVariant.withValues(
- alpha: 0.5,
- ),
- ),
- ],
- ),
- ),
- ),
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- SwitchListTile(
- title: Text(l.currentLibrarySkipOverride),
- subtitle: Text(
- _curLibSkipOverride
- ? l.currentLibrarySkipOverrideOnSubtitle
- : l.currentLibrarySkipOverrideOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _curLibSkipOverride,
- onChanged: _loaded
- ? (v) {
- setState(() => _curLibSkipOverride = v);
- if (v) {
- PlayerSettings.setSkipOverride(
- _curLibId!,
- forward: _curLibSkipForward,
- back: _curLibSkipBack,
- );
- } else {
- PlayerSettings.setSkipOverride(
- _curLibId!,
- forward: null,
- back: null,
- );
- }
- }
- : null,
- ),
- if (_curLibSkipOverride) ...[
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 12,
- 16,
- 4,
- ),
- child: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- children: [
- Text(
- l.currentLibrarySkipBack,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- Text(
- l.secondsValue(
- _curLibSkipBack.toString(),
- ),
- style: tt.bodyMedium?.copyWith(
- fontWeight: FontWeight.w600,
- color: cs.primary,
- ),
- ),
- ],
- ),
- ),
- AbsorbSlider(
- value: _curLibSkipBack.toDouble(),
- min: 5,
- max: 60,
- divisions: 11,
- onChanged: _loaded
- ? (v) {
- setState(
- () => _curLibSkipBack = v.round(),
- );
- PlayerSettings.setSkipOverride(
- _curLibId!,
- forward: _curLibSkipForward,
- back: v.round(),
- );
- }
- : null,
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 0,
- 16,
- 4,
- ),
- child: Row(
- mainAxisAlignment:
- MainAxisAlignment.spaceBetween,
- children: [
- Text(
- l.currentLibrarySkipForward,
- style: tt.bodyMedium?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- Text(
- l.secondsValue(
- _curLibSkipForward.toString(),
- ),
- style: tt.bodyMedium?.copyWith(
- fontWeight: FontWeight.w600,
- color: cs.primary,
- ),
- ),
- ],
- ),
- ),
- AbsorbSlider(
- value: _curLibSkipForward.toDouble(),
- min: 5,
- max: 60,
- divisions: 11,
- onChanged: _loaded
- ? (v) {
- setState(
- () =>
- _curLibSkipForward = v.round(),
- );
- PlayerSettings.setSkipOverride(
- _curLibId!,
- forward: v.round(),
- back: _curLibSkipBack,
- );
- }
- : null,
- ),
- ],
- ],
- ],
- ),
- if (!isDesktopSettings || expandedSection == 'Library')
- const SizedBox(height: 16),
-
- // ── Permissions ──
- if (!AppPlatform.isWeb)
- CollapsibleSection(
- key: _keyFor('Permissions'),
- icon: Icons.shield_outlined,
- title: l.sectionPermissions,
- cs: cs,
- isExpanded: expandedSection == 'Permissions',
- desktopMode: isDesktopSettings,
- onExpansionChanged: (v) =>
- _onSectionExpanded('Permissions', v),
- children: [
- ListTile(
- leading: const Icon(
- Icons.notifications_outlined,
- ),
- title: Text(l.notifications),
- subtitle: Text(
- l.notificationsSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- trailing: Icon(
- Icons.chevron_right_rounded,
- color: cs.onSurfaceVariant,
- ),
- onTap: () async {
- final status =
- await Permission.notification.status;
- if (status.isGranted) {
- if (mounted) {
- showOverlayToast(
- context,
- l.notificationsAlreadyEnabled,
- icon:
- Icons.notifications_active_outlined,
- );
- }
- } else {
- final result = await Permission.notification
- .request();
- if (result.isPermanentlyDenied && mounted)
- await openAppSettings();
- }
- },
- ),
- if (AppPlatform.isAndroid) ...[
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- ListTile(
- leading: const Icon(
- Icons.notifications_active_outlined,
- ),
- title: Text(l.settingsEpisodeNotifs),
- subtitle: Text(
- '${l.settingsEpisodeNotifsDesc} - ${_episodeNotifLabel(l)}',
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- trailing: Icon(
- Icons.chevron_right_rounded,
- color: cs.onSurfaceVariant,
- ),
- onTap: _loaded
- ? _pickEpisodeNotifInterval
- : null,
- ),
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- ListTile(
- leading: const Icon(
- Icons.battery_saver_outlined,
- ),
- title: Text(l.unrestrictedBattery),
- subtitle: Text(
- l.unrestrictedBatterySubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- trailing: Icon(
- Icons.chevron_right_rounded,
- color: cs.onSurfaceVariant,
- ),
- onTap: () async {
- final status = await Permission
- .ignoreBatteryOptimizations
- .status;
- if (status.isGranted) {
- if (mounted) {
- showOverlayToast(
- context,
- l.batteryAlreadyUnrestricted,
- icon: Icons.battery_saver_outlined,
- );
- }
- } else {
- final result = await Permission
- .ignoreBatteryOptimizations
- .request();
- if (result.isPermanentlyDenied && mounted)
- await openAppSettings();
- }
- },
- ),
- ],
+ ),
+ ]),
+ subtitle: Text(
+ _rewindSettings.sessionStartRewind
+ ? l.rewindOnSessionStartOnSubtitle(_rewindSettings.maxRewind.round().toString())
+ : l.autoRewindOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _rewindSettings.sessionStartRewind,
+ onChanged: (v) => _saveRewind(AutoRewindSettings(
+ enabled: true,
+ minRewind: _rewindSettings.minRewind,
+ maxRewind: _rewindSettings.maxRewind,
+ activationDelay: _rewindSettings.activationDelay,
+ chapterBarrier: _rewindSettings.chapterBarrier,
+ sessionStartRewind: v,
+ )),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 12),
+ child: Container(
+ padding: const EdgeInsets.all(12),
+ decoration: BoxDecoration(
+ color: cs.surfaceContainerHighest,
+ borderRadius: BorderRadius.circular(12)),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(l.preview, style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant)),
+ const SizedBox(height: 4),
+ ..._buildRewindPreviews(cs, tt, l),
],
),
- if (!isDesktopSettings ||
- expandedSection == 'Permissions')
- const SizedBox(height: 16),
-
- // ── Issues & Support ──
- CollapsibleSection(
- key: _keyFor('Issues & Support'),
- icon: Icons.support_agent_rounded,
- title: l.sectionIssuesAndSupport,
- cs: cs,
- isExpanded: expandedSection == 'Issues & Support',
- desktopMode: isDesktopSettings,
- onExpansionChanged: (v) =>
- _onSectionExpanded('Issues & Support', v),
+ ),
+ ),
+ ],
+ ],
+ ),
+ const SizedBox(height: 16),
+
+ // ── Media Controls ──
++ if (!isDesktopSettings)
+ CollapsibleSection(
+ key: _keyFor('Media Controls'),
+ icon: Icons.dvr_rounded,
+ title: l.sectionMediaControls,
+ cs: cs,
+ isExpanded: _expandedSection == 'Media Controls',
+ onExpansionChanged: (v) => _onSectionExpanded('Media Controls', v),
+ children: [
+ SwitchListTile(
+ title: Text(Platform.isIOS
+ ? l.chapterProgressInNotificationIos
+ : l.chapterProgressInNotification),
+ subtitle: Text(
+ _notifChapterProgress
+ ? (Platform.isIOS
+ ? l.chapterProgressOnSubtitleIos
+ : l.chapterProgressOnSubtitle)
+ : l.chapterProgressOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _notifChapterProgress,
+ onChanged: _loaded ? (v) {
+ setState(() => _notifChapterProgress = v);
+ PlayerSettings.setNotificationChapterProgress(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ // Cross-platform: drops the seek action so the scrubber in the
+ // notification / lockscreen / car can't be dragged.
+ SwitchListTile(
+ title: Text(l.lockSeekBar),
+ subtitle: Text(
+ _lockSeekBar ? l.lockSeekBarOnSubtitle : l.lockSeekBarOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _lockSeekBar,
+ onChanged: _loaded ? (v) {
+ setState(() => _lockSeekBar = v);
+ PlayerSettings.setLockSeekBar(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: Text(Platform.isIOS
+ ? l.carConnectAutoplayIos
+ : l.carConnectAutoplay),
+ subtitle: Text(
+ _autoplayOnCarConnect
+ ? l.carConnectAutoplayOnSubtitle
+ : l.carConnectAutoplayOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _autoplayOnCarConnect,
+ onChanged: _loaded ? (v) {
+ setState(() => _autoplayOnCarConnect = v);
+ PlayerSettings.setAutoplayOnCarConnect(v);
+ } : null,
+ ),
+ // Android only: chooses which pair fills the phone media
+ // player's two extra slots. iOS uses CarPlay's own buttons.
+ if (Platform.isAndroid) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: const Text('Duck brief interruptions'),
+ subtitle: Text(
+ _duckBriefInterruptions
+ ? 'Notifications and prompts lower the volume instead of pausing'
+ : 'Notifications and prompts pause playback',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _duckBriefInterruptions,
+ onChanged: _loaded ? (v) {
+ setState(() => _duckBriefInterruptions = v);
+ PlayerSettings.setDuckBriefInterruptions(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: Text(l.speedBookmarkInControls),
+ subtitle: Text(
+ _notifSpeedBookmark
+ ? l.speedBookmarkOnSubtitle
+ : l.speedBookmarkOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _notifSpeedBookmark,
+ onChanged: _loaded ? (v) {
+ setState(() => _notifSpeedBookmark = v);
+ PlayerSettings.setMediaControlsSpeedBookmark(v);
+ } : null,
+ ),
+ ],
+ ],
+ ),
+ const SizedBox(height: 16),
+
+ // ── Sleep Timer ──
+ CollapsibleSection(
+ key: _keyFor('Sleep Timer'),
+ icon: Icons.bedtime_outlined,
+ title: l.sectionSleepTimer,
+ cs: cs,
+ isExpanded: _expandedSection == 'Sleep Timer',
+ onExpansionChanged: (v) => _onSectionExpanded('Sleep Timer', v),
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 4),
+ child: Text(l.shakeDuringSleepTimer, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
+ child: SizedBox(
+ width: double.infinity,
+ child: SegmentedButton<String>(
+ showSelectedIcon: false,
+ segments: [
+ ButtonSegment(value: 'off', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.shakeOff))),
+ ButtonSegment(value: 'addTime', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.shakeAddTime))),
+ ButtonSegment(value: 'resetTimer', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.shakeReset))),
+ ],
+ selected: {_shakeMode},
+ onSelectionChanged: _loaded ? (v) {
+ setState(() => _shakeMode = v.first);
+ PlayerSettings.setShakeMode(v.first);
+ SleepTimerService().restartShakeDetection();
+ } : null,
+ ),
+ ),
+ ),
+ if (_shakeMode != 'off') ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
- ListTile(
- leading: Icon(
- Icons.lightbulb_outline_rounded,
- color: cs.onSurfaceVariant,
- ),
- title: Text(l.showTipsAgain),
- subtitle: Text(
- l.showTipsAgainSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- onTap: () async {
- await FeatureHint.resetAll();
- if (!mounted) return;
- showOverlayToast(
- context,
- l.tipsRestored,
- icon: Icons.lightbulb_outline_rounded,
- );
- // Re-trigger the welcome dialog without an app
- // restart. resetAll() already cleared the flag.
- WelcomeSheet.showIfNeeded(context);
- },
- ),
- const Divider(height: 1, indent: 16, endIndent: 16),
- ListTile(
- leading: Icon(
- Icons.bug_report_outlined,
- color: cs.onSurfaceVariant,
- ),
- title: Text(l.bugsAndFeatureRequests),
- subtitle: Text(
- l.bugsAndFeatureRequestsSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- trailing: Icon(
- Icons.open_in_new_rounded,
- size: 18,
- color: cs.onSurfaceVariant,
- ),
- onTap: () => launchUrl(
- Uri.parse(
- 'https://github.com/pounat/absorb/issues',
- ),
- mode: LaunchMode.externalApplication,
- ),
- ),
- const Divider(height: 1, indent: 16, endIndent: 16),
- ListTile(
- leading: Icon(
- Icons.discord,
- color: cs.onSurfaceVariant,
- ),
- title: Text(l.joinDiscord),
- subtitle: Text(
- l.joinDiscordSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- trailing: Icon(
- Icons.open_in_new_rounded,
- size: 18,
- color: cs.onSurfaceVariant,
- ),
- onTap: () => launchUrl(
- Uri.parse('https://discord.gg/bwH6hdvzZ4'),
- mode: LaunchMode.externalApplication,
- ),
- ),
- const Divider(height: 1, indent: 16, endIndent: 16),
- ListTile(
- leading: Icon(
- Icons.email_outlined,
- color: cs.primary,
- ),
- title: Text(l.contact),
- subtitle: Text(
- l.contactSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- trailing: const Icon(Icons.chevron_right_rounded),
- onTap: () {
- LogService().contactEmail(
- serverVersion: auth.serverVersion,
- );
- },
- ),
- const Divider(height: 1, indent: 16, endIndent: 16),
- SwitchListTile(
- title: Text(l.enableLogging),
- subtitle: Text(
- _loggingEnabled
- ? l.enableLoggingOnSubtitle
- : l.enableLoggingOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _loggingEnabled,
- onChanged: _loaded
- ? (v) {
- setState(() => _loggingEnabled = v);
- PlayerSettings.setLoggingEnabled(v);
- showOverlayToast(
- context,
- v
- ? l.loggingEnabledSnackbar
- : l.loggingDisabledSnackbar,
- icon: Icons.article_outlined,
- );
- }
- : null,
- ),
- if (_loggingEnabled && LogService().enabled) ...[
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- ListTile(
- leading: Icon(
- AppPlatform.isWeb
- ? Icons.download_rounded
- : Icons.attach_file_rounded,
- color: cs.primary,
- ),
- title: Text(l.sendLogs),
- subtitle: Text(
- l.sendLogsSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- trailing: Icon(
- AppPlatform.isWeb
- ? Icons.download_rounded
- : Icons.chevron_right_rounded,
- ),
- onTap: () async {
- try {
- final box =
- context.findRenderObject()
- as RenderBox?;
- final origin = box != null
- ? box.localToGlobal(Offset.zero) &
- box.size
- : null;
- await LogService().shareLogs(
- serverVersion: auth.serverVersion,
- sharePositionOrigin: origin,
- );
- } catch (e) {
- if (mounted) {
- showOverlayToast(
- context,
- l.failedToShare(e.toString()),
- icon: Icons.error_outline_rounded,
- );
- }
- }
- },
- ),
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- ListTile(
- leading: Icon(
- Icons.delete_outline_rounded,
- color: cs.error,
- ),
- title: Text(l.clearLogs),
- onTap: () async {
- await LogService().clearLogs();
- if (mounted) {
- showOverlayToast(
- context,
- l.logsCleared,
- icon: Icons.delete_outline_rounded,
- );
- }
- },
- ),
- ],
+ Text(l.shakeSensitivity, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
+ Text(_shakeSensitivityLabel(l, _shakeSensitivity),
+ style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.primary)),
+ ],
+ ),
+ ),
+ AbsorbSlider(
+ value: _shakeSensitivityIndex(_shakeSensitivity).toDouble(),
+ min: 0, max: 4, divisions: 4,
+ onChanged: _loaded ? (v) {
+ final key = _shakeSensitivityKey(v.round());
+ setState(() => _shakeSensitivity = key);
+ PlayerSettings.setShakeSensitivity(key);
+ SleepTimerService().restartShakeDetection();
+ } : null,
+ ),
+ const SizedBox(height: 4),
+ ],
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
+ child: Text(l.buttonDuringSleepTimer, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
+ child: SizedBox(
+ width: double.infinity,
+ child: SegmentedButton<String>(
+ showSelectedIcon: false,
+ segments: [
+ ButtonSegment(value: 'off', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.shakeOff))),
+ ButtonSegment(value: 'addTime', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.shakeAddTime))),
+ ButtonSegment(value: 'resetTimer', label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.shakeReset))),
],
+ selected: {_sleepButtonMode},
+ onSelectionChanged: _loaded ? (v) {
+ setState(() => _sleepButtonMode = v.first);
+ PlayerSettings.setSleepButtonMode(v.first);
+ } : null,
),
- if (!isDesktopSettings ||
- expandedSection == 'Issues & Support')
- const SizedBox(height: 16),
-
- // ── Advanced ──
- CollapsibleSection(
- key: _keyFor('Advanced'),
- icon: Icons.tune_rounded,
- title: l.sectionAdvanced,
- cs: cs,
- isExpanded: expandedSection == 'Advanced',
- desktopMode: isDesktopSettings,
- onExpansionChanged: (v) =>
- _onSectionExpanded('Advanced', v),
+ ),
+ ),
+ if (_sleepButtonMode != 'off')
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
+ child: Text(l.buttonDuringSleepTimerHint,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant.withValues(alpha: 0.7), fontSize: 11)),
+ ),
+ // Shared by shake and button add-time modes, so it shows
+ // whenever either trigger needs it
+ if (_shakeMode == 'addTime' || _sleepButtonMode == 'addTime') ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
- if (!AppPlatform.isWeb) ...[
- SwitchListTile(
- title: Row(
- children: [
- Flexible(child: Text(l.localServer)),
- _infoIcon(
- l.localServerInfoTitle,
- l.localServerInfoContent,
- ),
- ],
- ),
- subtitle: Text(
- _localServerEnabled
- ? (auth.useLocalServer
- ? l.localServerOnConnectedSubtitle
- : l.localServerOnRemoteSubtitle)
- : l.localServerOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _localServerEnabled,
- onChanged: _loaded
- ? (v) {
- setState(() => _localServerEnabled = v);
- auth.setLocalServerConfig(
- enabled: v,
- url: _localServerUrl,
- );
- }
- : null,
- ),
- if (_localServerEnabled) ...[
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 8,
- 16,
- 0,
- ),
- child: TextField(
- controller: _localServerController,
- decoration: InputDecoration(
- labelText: l.localServerUrlLabel,
- hintText: l.localServerUrlHint,
- border: OutlineInputBorder(
- borderRadius: BorderRadius.circular(12),
- ),
- ),
- onSubmitted: (_) =>
- _saveLocalServerUrl(auth, l),
- ),
- ),
- Padding(
- padding: const EdgeInsets.fromLTRB(
- 16,
- 8,
- 16,
- 8,
- ),
- child: Align(
- alignment: Alignment.centerRight,
- child: FilledButton.icon(
- icon: const Icon(
- Icons.check_rounded,
- size: 18,
- ),
- label: Text(l.setTooltip),
- onPressed: () =>
- _saveLocalServerUrl(auth, l),
- ),
- ),
- ),
- if (auth.useLocalServer) ...[
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- ListTile(
- leading: Icon(
- Icons.check_circle_rounded,
- color: Colors.greenAccent.shade400,
- ),
- title: Text(
- l.localServerOnConnectedSubtitle,
- ),
- subtitle: Text(
- _localServerUrl,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- ),
- ],
- ],
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
+ Text(l.sleepAddAmount, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
+ Text(l.shakeAddsValue(_shakeAddMinutes),
+ style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.primary)),
+ ],
+ ),
+ ),
+ AbsorbSlider(
+ value: _shakeAddMinutes.toDouble(),
+ min: 1, max: 30, divisions: 29,
+ onChanged: _loaded ? (v) {
+ setState(() => _shakeAddMinutes = v.round());
+ PlayerSettings.setShakeAddMinutes(v.round());
+ } : null,
+ ),
+ const SizedBox(height: 4),
+ ],
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: Text(l.resetTimerOnPause),
+ subtitle: Text(
+ _resetSleepOnPause
+ ? l.resetTimerOnPauseOnSubtitle
+ : l.resetTimerOnPauseOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _resetSleepOnPause,
+ onChanged: _loaded ? (v) {
+ setState(() => _resetSleepOnPause = v);
+ PlayerSettings.setResetSleepOnPause(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
+ child: Row(children: [
+ Icon(Icons.replay_rounded, size: 18,
+ color: _sleepRewindSeconds > 0 ? cs.primary : cs.onSurfaceVariant),
+ const SizedBox(width: 10),
+ Expanded(child: Text(l.sleepTimerSheetRewindOnSleep,
+ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant))),
+ Text(_rewindLabel(_sleepRewindSeconds, l),
+ style: tt.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w600,
+ color: _sleepRewindSeconds > 0 ? cs.primary : cs.onSurfaceVariant)),
+ ]),
+ ),
+ AbsorbSlider(
+ value: (_sleepRewindSeconds / 60).clamp(0.0, _maxRewindMinutes.toDouble()),
+ min: 0,
+ max: _maxRewindMinutes.toDouble(),
+ divisions: _maxRewindMinutes,
+ onChanged: _loaded ? (v) {
+ final seconds = (v * 60).round();
+ setState(() => _sleepRewindSeconds = seconds);
+ PlayerSettings.setSleepRewindSeconds(seconds);
+ } : null,
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(28, 0, 28, 4),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text(l.off, style: TextStyle(color: cs.onSurface.withValues(alpha: 0.3), fontSize: 11)),
+ Text(l.sleepTimerSheetMinShort(_maxRewindMinutes),
+ style: TextStyle(color: cs.onSurface.withValues(alpha: 0.3), fontSize: 11)),
+ ],
+ ),
+ ),
+ if (_sleepRewindSeconds > 0)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(28, 0, 28, 10),
+ child: Text(
+ l.sleepRewindUndoNote(
+ SleepTimerService.sleepRewindUndoWindow.inMinutes),
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: Text(l.fadeVolumeBeforeSleep),
+ subtitle: Text(
+ _sleepFadeOut
+ ? l.fadeVolumeOnSubtitleDynamic(_sleepFadeDuration)
+ : l.fadeVolumeOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _sleepFadeOut,
+ onChanged: _loaded ? (v) {
+ setState(() => _sleepFadeOut = v);
+ PlayerSettings.setSleepFadeOut(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: Text(l.chimeBeforeSleep),
+ subtitle: Text(
+ _sleepChime
+ ? l.chimeBeforeSleepOnSubtitle
+ : l.chimeBeforeSleepOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _sleepChime,
+ onChanged: _loaded ? (v) {
+ setState(() => _sleepChime = v);
+ PlayerSettings.setSleepChime(v);
+ } : null,
+ ),
+ if (_sleepChime) ...[
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Row(children: [
+ Icon(Icons.volume_down_rounded, size: 18, color: cs.onSurfaceVariant),
+ Expanded(child: Slider(
+ value: _sleepChimeVolume,
+ min: 0.5, max: 3.0, divisions: 10,
+ label: '${(_sleepChimeVolume * 100 / 3).round()}%',
+ onChanged: _loaded ? (v) {
+ setState(() => _sleepChimeVolume = v);
+ PlayerSettings.setSleepChimeVolume(v);
+ } : null,
+ )),
+ Icon(Icons.volume_up_rounded, size: 18, color: cs.onSurfaceVariant),
+ ]),
+ ),
+ ],
+ if (_sleepFadeOut || _sleepChime) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ title: Text(l.windDownDuration),
+ subtitle: Text(
+ l.windDownDurationSubtitle(_sleepFadeDuration),
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ ),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Row(children: [
+ Text(l.secondsValue(_sleepFadeDuration.toString()), style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ Expanded(child: Slider(
+ value: _sleepFadeDuration.toDouble(),
+ min: 10, max: 60, divisions: 10,
+ label: l.secondsValue(_sleepFadeDuration.toString()),
+ onChanged: _loaded ? (v) {
+ setState(() => _sleepFadeDuration = v.round());
+ PlayerSettings.setSleepFadeDuration(v.round());
+ } : null,
+ )),
+ ]),
+ ),
+ ],
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ // ── Auto Sleep Timer ──
+ SwitchListTile(
+ title: Text(l.autoSleepTimer),
+ subtitle: Text(
+ _autoSleepSettings.enabled
+ ? l.autoSleepTimerEnabledSubtitle(
+ _autoSleepSettings.startLabel,
+ _autoSleepSettings.endLabel,
+ _autoSleepSettings.useEndOfChapter
+ ? l.endOfChapterShort
+ : l.shakeAddsValue(_autoSleepSettings.durationMinutes))
+ : l.autoSleepTimerOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _autoSleepSettings.enabled,
+ onChanged: _loaded ? (v) {
+ final updated = _autoSleepSettings.copyWith(enabled: v);
+ setState(() => _autoSleepSettings = updated);
+ updated.save();
+ SleepTimerService().updateAutoSleepSettings(updated);
+ } : null,
+ ),
+ if (_autoSleepSettings.enabled) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ // Start time picker
+ ListTile(
+ title: Text(l.windowStart),
+ trailing: Text(_autoSleepSettings.startLabel,
+ style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.primary)),
+ onTap: () async {
+ final picked = await showTimePicker(
+ context: context,
+ initialTime: TimeOfDay(hour: _autoSleepSettings.startHour, minute: _autoSleepSettings.startMinute),
+ );
+ if (picked != null) {
+ final updated = _autoSleepSettings.copyWith(startHour: picked.hour, startMinute: picked.minute);
+ setState(() => _autoSleepSettings = updated);
+ updated.save();
+ SleepTimerService().updateAutoSleepSettings(updated);
+ }
+ },
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ // End time picker
+ ListTile(
+ title: Text(l.windowEnd),
+ trailing: Text(_autoSleepSettings.endLabel,
+ style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.primary)),
+ onTap: () async {
+ final picked = await showTimePicker(
+ context: context,
+ initialTime: TimeOfDay(hour: _autoSleepSettings.endHour, minute: _autoSleepSettings.endMinute),
+ );
+ if (picked != null) {
+ final updated = _autoSleepSettings.copyWith(endHour: picked.hour, endMinute: picked.minute);
+ setState(() => _autoSleepSettings = updated);
+ updated.save();
+ SleepTimerService().updateAutoSleepSettings(updated);
+ }
+ },
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ // End of chapter toggle
+ SwitchListTile(
+ title: Text(l.endOfChapterShort),
+ subtitle: Text(
+ _autoSleepSettings.useEndOfChapter
+ ? l.endOfChapterOnSubtitle
+ : l.endOfChapterOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _autoSleepSettings.useEndOfChapter,
+ onChanged: _loaded ? (v) {
+ final updated = _autoSleepSettings.copyWith(useEndOfChapter: v);
+ setState(() => _autoSleepSettings = updated);
+ updated.save();
+ SleepTimerService().updateAutoSleepSettings(updated);
+ } : null,
+ ),
+ // Duration slider (only for timed mode)
+ if (!_autoSleepSettings.useEndOfChapter) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text(l.timerDuration, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
+ Text(l.shakeAddsValue(_autoSleepSettings.durationMinutes),
+ style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.primary)),
],
- if (!AppPlatform.isWeb)
- SwitchListTile(
- title: Row(
- children: [
- Flexible(
- child: Text(l.trustAllCertificates),
- ),
- _infoIcon(
- l.trustAllCertificatesInfoTitle,
- l.trustAllCertificatesInfoContent,
- ),
- ],
- ),
- subtitle: Text(
- _trustAllCerts
- ? l.trustAllCertificatesOnSubtitle
- : l.trustAllCertificatesOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _trustAllCerts,
- onChanged: _loaded
- ? (v) async {
- setState(() => _trustAllCerts = v);
- await PlayerSettings.setTrustAllCerts(
- v,
- );
- applyTrustAllCerts(v);
- }
- : null,
- ),
- if (AppPlatform.isAndroid) ...[
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- SwitchListTile(
- title: Row(
- children: [
- Flexible(child: Text(l.mp3IndexSeeking)),
- _infoIcon(
- l.mp3IndexSeekingInfoTitle,
- l.mp3IndexSeekingInfoContent,
- ),
- ],
- ),
- subtitle: Text(
- _mp3IndexSeeking
- ? l.mp3IndexSeekingOnSubtitle
- : l.mp3IndexSeekingOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _mp3IndexSeeking,
- onChanged: _loaded
- ? (v) {
- setState(() => _mp3IndexSeeking = v);
- PlayerSettings.setMp3IndexSeeking(v);
- }
- : null,
- ),
+ ),
+ ),
+ AbsorbSlider(
+ value: _autoSleepSettings.durationMinutes.toDouble(),
+ min: 5, max: 120, divisions: 23,
+ onChanged: _loaded ? (v) {
+ final updated = _autoSleepSettings.copyWith(durationMinutes: v.round());
+ setState(() => _autoSleepSettings = updated);
+ updated.save();
+ SleepTimerService().updateAutoSleepSettings(updated);
+ } : null,
+ ),
+ ],
+ const SizedBox(height: 4),
+ ],
+ ],
+ ),
+ const SizedBox(height: 16),
+
+ // ── Downloads & Storage ──
++ if (!isDesktopSettings)
+ CollapsibleSection(
+ key: _keyFor('Downloads & Storage'),
+ icon: Icons.download_outlined,
+ title: l.sectionDownloadsAndStorage,
+ cs: cs,
+ isExpanded: _expandedSection == 'Downloads & Storage',
+ onExpansionChanged: (v) => _onSectionExpanded('Downloads & Storage', v),
+ children: [
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ const SizedBox(height: 12),
+ Text(l.downloadOverWifiOnly, style: tt.bodyMedium?.copyWith(color: cs.onSurface)),
+ const SizedBox(height: 8),
+ SizedBox(width: double.infinity, child: SegmentedButton<bool>(
+ showSelectedIcon: false,
+ segments: [
+ ButtonSegment(value: true, label: Text(l.downloadOverWifiOnSubtitle)),
+ ButtonSegment(value: false, label: Text(l.downloadOverWifiOffSubtitle)),
],
- if (_isGithubBuild) ...[
- if (!AppPlatform.isWeb)
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- SwitchListTile(
- title: Row(
- children: [
- Flexible(child: Text(l.includePreReleases)),
- _infoIcon(
- l.preReleaseUpdatesInfoTitle,
- l.preReleaseUpdatesInfoContent,
- ),
- ],
- ),
- subtitle: Text(
- _includePreReleases
- ? l.includePreReleasesOnSubtitle
- : l.includePreReleasesOffSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- value: _includePreReleases,
- onChanged: _loaded
- ? (v) async {
- setState(() => _includePreReleases = v);
- await PlayerSettings.setIncludePreReleases(
- v,
- );
- }
- : null,
- ),
+ selected: {_wifiOnlyDownloads},
+ onSelectionChanged: _loaded ? (v) {
+ setState(() => _wifiOnlyDownloads = v.first);
+ PlayerSettings.setWifiOnlyDownloads(v.first);
+ } : null,
+ )),
+ const SizedBox(height: 8),
+ ],
+ ),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: Row(children: [
+ Flexible(child: Text(l.autoDownloadOnWifi)),
+ _infoIcon(l.autoDownloadOnWifiInfoTitle, l.autoDownloadOnWifiInfoContent),
+ ]),
+ subtitle: Text(
+ _autoDownloadOnStream
+ ? l.autoDownloadOnWifiOnSubtitle
+ : l.autoDownloadOnWifiOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _autoDownloadOnStream,
+ onChanged: _loaded ? (v) {
+ setState(() => _autoDownloadOnStream = v);
+ PlayerSettings.setAutoDownloadOnStream(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: const Text('Auto-download series'),
+ subtitle: Text(
+ _autoSeriesDownloadDefault
+ ? 'Starting a book in a series keeps the next books downloaded'
+ : 'Turn on series downloads yourself from the series menu',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _autoSeriesDownloadDefault,
+ onChanged: _loaded ? (v) {
+ setState(() => _autoSeriesDownloadDefault = v);
+ PlayerSettings.setAutoSeriesDownloadDefault(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ const SizedBox(height: 12),
+ Text(l.concurrentDownloads, style: tt.bodyMedium?.copyWith(color: cs.onSurface)),
+ const SizedBox(height: 8),
+ SizedBox(width: double.infinity, child: SegmentedButton<int>(
+ showSelectedIcon: false,
+ segments: const [
+ ButtonSegment(value: 1, label: Text('1')),
+ ButtonSegment(value: 2, label: Text('2')),
+ ButtonSegment(value: 3, label: Text('3')),
+ ButtonSegment(value: 4, label: Text('4')),
+ ButtonSegment(value: 5, label: Text('5')),
],
- if (!AppPlatform.isWeb || _isGithubBuild)
- const Divider(
- height: 1,
- indent: 16,
- endIndent: 16,
- ),
- ListTile(
- leading: Icon(
- Icons.menu_book_rounded,
- color: cs.primary,
- ),
- title: Text(l.adminRmab),
- subtitle: Text(
- ((_rmabBaseUrl ?? '').isNotEmpty &&
- (_rmabApiToken ?? '').isNotEmpty)
- ? l.adminRmabConnected
- : l.adminRmabAskAdmin,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- trailing: Icon(
- Icons.chevron_right_rounded,
- color: cs.onSurfaceVariant.withValues(
- alpha: 0.5,
- ),
- ),
- onTap: _openRmabSheetFromSettings,
+ selected: {_maxConcurrentDownloads},
+ onSelectionChanged: (v) {
+ setState(() => _maxConcurrentDownloads = v.first);
+ PlayerSettings.setMaxConcurrentDownloads(v.first);
+ },
+ )),
+ const SizedBox(height: 8),
+ ],
+ ),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ title: Text(l.autoDownload),
+ subtitle: Text(
+ l.autoDownloadSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ leading: Icon(Icons.downloading_rounded, color: cs.primary),
+ ),
+ _buildAutoDownloadSources(lib, l, cs, tt),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(children: [
+ Text(l.keepNext, style: tt.bodyMedium?.copyWith(color: cs.onSurface)),
+ _infoIcon(l.keepNextInfoTitle, l.keepNextInfoContent),
+ ]),
+ const SizedBox(height: 8),
+ SizedBox(width: double.infinity, child: SegmentedButton<int>(
+ showSelectedIcon: false,
+ segments: const [
+ ButtonSegment(value: 2, label: Text('2')),
+ ButtonSegment(value: 3, label: Text('3')),
+ ButtonSegment(value: 4, label: Text('4')),
+ ButtonSegment(value: 5, label: Text('5')),
+ ],
+ selected: {_rollingDownloadCount},
+ onSelectionChanged: (v) async {
+ setState(() => _rollingDownloadCount = v.first);
+ await PlayerSettings.setRollingDownloadCount(v.first);
+ if (_queueAutoDownload) {
+ unawaited(lib.syncQueueAutoDownloads());
+ }
+ },
+ )),
+ const SizedBox(height: 8),
+ ],
+ ),
+ ),
+ SwitchListTile(
+ title: Row(children: [
+ Flexible(child: Text(Wording.of(context).deleteAbsorbedDownloads)),
+ _infoIcon(Wording.of(context).deleteAbsorbedDownloadsInfoTitle, l.deleteAbsorbedDownloadsInfoContent),
+ ]),
+ subtitle: Text(
+ _rollingDownloadDeleteFinished
+ ? l.deleteAbsorbedOnSubtitle
+ : l.deleteAbsorbedOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _rollingDownloadDeleteFinished,
+ onChanged: _loaded ? (v) {
+ setState(() => _rollingDownloadDeleteFinished = v);
+ PlayerSettings.setRollingDownloadDeleteFinished(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ if (!Platform.isIOS && _canPickDownloadLocation)
+ ListTile(
+ leading: Icon(Icons.folder_outlined, color: cs.primary),
+ title: Text(l.downloadLocation),
+ subtitle: Text(
+ _downloadLocationLabel,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ trailing: const Icon(Icons.chevron_right),
+ onTap: () => _pickDownloadLocation(context, cs, tt),
+ ),
+ if (_totalDownloadSizeBytes > 0 || _deviceTotalBytes > 0) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ leading: Icon(Icons.data_usage_rounded, color: cs.onSurfaceVariant),
+ title: Text(l.storageUsed),
+ subtitle: Text(
+ [
+ if (_totalDownloadSizeBytes > 0) l.storageUsedByDownloads(_formatBytes(_totalDownloadSizeBytes)),
+ if (_deviceTotalBytes > 0) l.storageFreeOfTotal(_formatBytes(_deviceAvailableBytes), _formatBytes(_deviceTotalBytes)),
+ ].join('\n'),
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ isThreeLine: _totalDownloadSizeBytes > 0 && _deviceTotalBytes > 0,
+ ),
+ ],
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ leading: Icon(Icons.storage_rounded, color: cs.primary),
+ title: Text(l.manageDownloads),
+ trailing: const Icon(Icons.chevron_right),
+ onTap: () => Navigator.push(context,
+ MaterialPageRoute(builder: (_) => const DownloadsScreen())),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ const SizedBox(height: 12),
+ Row(children: [
+ Text(l.streamingCache, style: tt.bodyMedium?.copyWith(color: cs.onSurface)),
+ _infoIcon(l.streamingCacheInfoTitle, l.streamingCacheInfoContent),
+ ]),
+ const SizedBox(height: 4),
+ Text(
+ _streamingCacheSizeMb == 0
+ ? l.streamingCacheOffSubtitle
+ : l.streamingCacheOnSubtitle(_streamingCacheSizeMb),
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ const SizedBox(height: 8),
+ SizedBox(width: double.infinity, child: SegmentedButton<int>(
+ showSelectedIcon: false,
+ segments: [
+ ButtonSegment(value: 0, label: FittedBox(fit: BoxFit.scaleDown, child: Text(l.streamingCacheOff))),
+ const ButtonSegment(value: 128, label: FittedBox(fit: BoxFit.scaleDown, child: Text('128 MB'))),
+ const ButtonSegment(value: 256, label: FittedBox(fit: BoxFit.scaleDown, child: Text('256 MB'))),
+ const ButtonSegment(value: 512, label: FittedBox(fit: BoxFit.scaleDown, child: Text('512 MB'))),
+ ],
+ selected: {_streamingCacheSizeMb},
+ onSelectionChanged: (v) {
+ setState(() => _streamingCacheSizeMb = v.first);
+ PlayerSettings.setStreamingCacheSizeMb(v.first);
+ },
+ )),
+ if (_streamingCacheSizeMb > 0) ...[
+ const SizedBox(height: 8),
+ TextButton.icon(
+ icon: const Icon(Icons.delete_sweep_outlined, size: 18),
+ label: Text(l.clearCache),
+ onPressed: () async {
+ try {
+ await AudioPlayer.clearStreamingCache();
+ } catch (_) {}
+ if (mounted) {
+ showOverlayToast(context, l.streamingCacheCleared,
+ icon: Icons.delete_outline_rounded);
+ }
+ },
),
],
+ const SizedBox(height: 8),
+ ],
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 16),
+
+ // ── Library ──
+ CollapsibleSection(
+ key: _keyFor('Library'),
+ icon: Icons.auto_stories_outlined,
+ title: l.sectionLibrary,
+ cs: cs,
+ isExpanded: _expandedSection == 'Library',
+ onExpansionChanged: (v) => _onSectionExpanded('Library', v),
+ children: [
+ Consumer<LibraryProvider>(builder: (context, lib, _) {
+ final podcastLibs = lib.libraries
+ .whereType<Map<String, dynamic>>()
+ .where((l) => (l['mediaType'] as String? ?? 'book') == 'podcast')
+ .toList();
+ if (podcastLibs.isEmpty) return const SizedBox.shrink();
+ final currentName = podcastLibs.firstWhere(
+ (p) => p['id'] == _podcastTabLibraryId,
+ orElse: () => podcastLibs.first,
+ )['name'] as String? ?? '';
+ return Column(children: [
+ SwitchListTile(
+ title: Text(l.settingsPodcastTab),
+ subtitle: Text(l.settingsPodcastTabDesc,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _podcastTabEnabled,
+ onChanged: _loaded ? (v) async {
+ var libId = _podcastTabLibraryId;
+ if (v && !podcastLibs.any((p) => p['id'] == libId)) {
+ libId = podcastLibs.first['id'] as String;
+ await PlayerSettings.setPodcastTabLibraryId(libId);
+ }
+ setState(() {
+ _podcastTabEnabled = v;
+ _podcastTabLibraryId = libId;
+ });
+ await PlayerSettings.setPodcastTabEnabled(v);
+ } : null,
),
- if (!isDesktopSettings || expandedSection == 'Advanced')
- const SizedBox(height: 16),
-
- // ── Support the Dev ──
- if (!isDesktopSettings ||
- expandedSection == 'Issues & Support')
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: 16),
- child: Column(
- children: [
- Card(
- color: cs.surfaceContainerHigh,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(14),
- ),
- clipBehavior: Clip.antiAlias,
- child: ListTile(
- leading: Icon(
- Icons.coffee_rounded,
- color: Colors.amber.shade600,
- ),
- title: Text(l.supportTheDev),
- subtitle: Text(
- l.buyMeACoffee,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- trailing: Icon(
- Icons.favorite_rounded,
- size: 18,
- color: Colors.amber.shade600,
- ),
- onTap: () => launchUrl(
- Uri.parse(
- 'https://www.buymeacoffee.com/BarnabasApps',
- ),
- mode: LaunchMode.externalApplication,
- ),
- ),
- ),
- ],
- ),
+ if (_podcastTabEnabled && podcastLibs.length > 1)
+ ListTile(
+ title: Text(l.settingsPodcastTabLibrary),
+ subtitle: Text(currentName,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: Icon(Icons.chevron_right_rounded, color: cs.onSurfaceVariant),
+ onTap: () => _pickPodcastTabLibrary(podcastLibs),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ]);
+ }),
+ SwitchListTile(
+ title: Text(l.hideEbookOnlyTitles),
+ subtitle: Text(
+ _hideEbookOnly
+ ? l.hideEbookOnlyOnSubtitle
+ : l.hideEbookOnlyOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _hideEbookOnly,
+ onChanged: _loaded ? (v) {
+ setState(() => _hideEbookOnly = v);
+ PlayerSettings.setHideEbookOnly(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: Text(l.showGoodreadsButton),
+ subtitle: Text(
+ _showGoodreadsButton
+ ? l.showGoodreadsOnSubtitle
+ : l.showGoodreadsOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _showGoodreadsButton,
+ onChanged: _loaded ? (v) {
+ setState(() => _showGoodreadsButton = v);
+ PlayerSettings.setShowGoodreadsButton(v);
+ } : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: Text(l.showExplicitBadge),
+ subtitle: Text(
+ _showExplicitBadge
+ ? l.showExplicitBadgeOnSubtitle
+ : l.showExplicitBadgeOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _showExplicitBadge,
+ onChanged: _loaded ? (v) {
+ setState(() => _showExplicitBadge = v);
+ PlayerSettings.setShowExplicitBadge(v);
+ } : null,
+ ),
+ if (lib.libraries.length > 1) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ...lib.libraries
+ .map((library) {
+ final id = library['id'] as String;
+ final name = library['name'] as String? ?? l.libraryFallback;
+ final mediaType = library['mediaType'] as String? ?? 'book';
+ final isSelected = id == lib.selectedLibraryId;
+ return ListTile(
+ leading: Icon(
+ mediaType == 'podcast' ? Icons.podcasts_rounded : Icons.auto_stories_rounded,
+ color: isSelected ? cs.primary : cs.onSurfaceVariant),
+ title: Text(name),
+ trailing: isSelected ? Icon(Icons.check_circle_rounded, color: cs.primary) : null,
+ onTap: () { if (!isSelected) lib.selectLibrary(id); },
+ );
+ }),
+ ],
+ if (_curLibId != null) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 2),
+ child: Text(
+ l.currentLibrarySettingsTitle(lib.selectedLibrary?['name'] as String? ?? l.libraryFallback),
+ style: tt.titleSmall,
+ ),
+ ),
+ InkWell(
+ onTap: _loaded ? () => _pickCurrentLibraryCoverShape() : null,
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(16, 14, 16, 14),
+ child: Row(children: [
+ Expanded(child: Text(l.coverShapeLabel)),
+ Text(_coverShapeValueLabel(l, _curLibCoverShape),
+ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
+ Icon(Icons.chevron_right_rounded,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ ]),
+ ),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ InkWell(
+ onTap: _loaded ? () => _pickCurrentLibrarySubtitles() : null,
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(16, 14, 16, 14),
+ child: Row(children: [
+ Expanded(child: Text(l.subtitleVisibilityLabel)),
+ Text(_subtitleVisibilityValueLabel(l, _curLibSubtitles),
+ style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
+ Icon(Icons.chevron_right_rounded,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ ]),
+ ),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: Text(l.currentLibrarySkipOverride),
+ subtitle: Text(
+ _curLibSkipOverride
+ ? l.currentLibrarySkipOverrideOnSubtitle
+ : l.currentLibrarySkipOverrideOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),
+ ),
+ value: _curLibSkipOverride,
+ onChanged: _loaded ? (v) {
+ setState(() => _curLibSkipOverride = v);
+ if (v) {
+ PlayerSettings.setSkipOverride(_curLibId!,
+ forward: _curLibSkipForward, back: _curLibSkipBack);
+ } else {
+ PlayerSettings.setSkipOverride(_curLibId!, forward: null, back: null);
+ }
+ } : null,
+ ),
+ if (_curLibSkipOverride) ...[
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text(l.currentLibrarySkipBack, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
+ Text(l.secondsValue(_curLibSkipBack.toString()), style: tt.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w600, color: cs.primary)),
+ ],
+ ),
+ ),
+ AbsorbSlider(
+ value: _curLibSkipBack.toDouble(),
+ min: 5, max: 60, divisions: 11,
+ onChanged: _loaded ? (v) {
+ setState(() => _curLibSkipBack = v.round());
+ PlayerSettings.setSkipOverride(_curLibId!,
+ forward: _curLibSkipForward, back: v.round());
+ } : null,
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 0, 16, 4),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text(l.currentLibrarySkipForward, style: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant)),
+ Text(l.secondsValue(_curLibSkipForward.toString()), style: tt.bodyMedium?.copyWith(
+ fontWeight: FontWeight.w600, color: cs.primary)),
+ ],
),
+ ),
+ AbsorbSlider(
+ value: _curLibSkipForward.toDouble(),
+ min: 5, max: 60, divisions: 11,
+ onChanged: _loaded ? (v) {
+ setState(() => _curLibSkipForward = v.round());
+ PlayerSettings.setSkipOverride(_curLibId!,
+ forward: v.round(), back: _curLibSkipBack);
+ } : null,
+ ),
+ ],
+ ],
+ ],
+ ),
+ const SizedBox(height: 16),
- if (!isDesktopSettings ||
- expandedSection == 'Issues & Support')
- const SizedBox(height: 16),
-
- // ── Backup & Restore ──
- if (!isDesktopSettings || expandedSection == 'Advanced')
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: 16),
- child: Card(
- elevation: 0,
- color: cs.surfaceContainerHigh,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(14),
- ),
- child: Padding(
- padding: const EdgeInsets.all(16),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Row(
- children: [
- Icon(
- Icons.settings_backup_restore_rounded,
- color: cs.primary,
- size: 22,
- ),
- const SizedBox(width: 10),
- Text(
- l.backupAndRestore,
- style: tt.titleSmall?.copyWith(
- fontWeight: FontWeight.w600,
- ),
- ),
- ],
- ),
- const SizedBox(height: 4),
- Text(
- l.backupAndRestoreSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- const SizedBox(height: 14),
- Row(
- children: [
- Expanded(
- child: FilledButton.tonalIcon(
- icon: const Icon(
- Icons.upload_rounded,
- size: 18,
- ),
- label: Text(l.backUp),
- onPressed: () => _backupSettings(
- context,
- cs,
- tt,
- ),
- ),
- ),
- const SizedBox(width: 10),
- Expanded(
- child: OutlinedButton.icon(
- icon: const Icon(
- Icons.download_rounded,
- size: 18,
- ),
- label: Text(l.restore),
- onPressed: () => _restoreSettings(
- context,
- cs,
- tt,
- ),
- ),
- ),
- ],
- ),
- ],
- ),
- ),
+ // ── Permissions ──
++ if (!isDesktopSettings)
+ CollapsibleSection(
+ key: _keyFor('Permissions'),
+ icon: Icons.shield_outlined,
+ title: l.sectionPermissions,
+ cs: cs,
+ isExpanded: _expandedSection == 'Permissions',
+ onExpansionChanged: (v) => _onSectionExpanded('Permissions', v),
+ children: [
+ ListTile(
+ leading: const Icon(Icons.notifications_outlined),
+ title: Text(l.notifications),
+ subtitle: Text(l.notificationsSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: Icon(Icons.chevron_right_rounded, color: cs.onSurfaceVariant),
+ onTap: () async {
+ final status = await Permission.notification.status;
+ if (status.isGranted) {
+ if (mounted) {
+ showOverlayToast(context, l.notificationsAlreadyEnabled,
+ icon: Icons.notifications_active_outlined);
+ }
+ } else {
+ final result = await Permission.notification.request();
+ if (result.isPermanentlyDenied && mounted) await openAppSettings();
+ }
+ },
+ ),
+ if (Platform.isAndroid) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ leading: const Icon(Icons.notifications_active_outlined),
+ title: Text(l.settingsEpisodeNotifs),
+ subtitle: Text(
+ '${l.settingsEpisodeNotifsDesc} - ${_episodeNotifLabel(l)}',
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: Icon(Icons.chevron_right_rounded, color: cs.onSurfaceVariant),
+ onTap: _loaded ? _pickEpisodeNotifInterval : null,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ leading: const Icon(Icons.battery_saver_outlined),
+ title: Text(l.unrestrictedBattery),
+ subtitle: Text(l.unrestrictedBatterySubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: Icon(Icons.chevron_right_rounded, color: cs.onSurfaceVariant),
+ onTap: () async {
+ final status = await Permission.ignoreBatteryOptimizations.status;
+ if (status.isGranted) {
+ if (mounted) {
+ showOverlayToast(context, l.batteryAlreadyUnrestricted,
+ icon: Icons.battery_saver_outlined);
+ }
+ } else {
+ final result = await Permission.ignoreBatteryOptimizations.request();
+ if (result.isPermanentlyDenied && mounted) await openAppSettings();
+ }
+ },
+ ),
+ ],
+ ],
+ ),
+ const SizedBox(height: 16),
+
+ // ── Issues & Support ──
+ CollapsibleSection(
+ key: _keyFor('Issues & Support'),
+ icon: Icons.support_agent_rounded,
+ title: l.sectionIssuesAndSupport,
+ cs: cs,
+ isExpanded: _expandedSection == 'Issues & Support',
+ onExpansionChanged: (v) => _onSectionExpanded('Issues & Support', v),
+ children: [
+ ListTile(
+ leading: Icon(Icons.lightbulb_outline_rounded,
+ color: cs.onSurfaceVariant),
+ title: Text(l.showTipsAgain),
+ subtitle: Text(l.showTipsAgainSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ onTap: () async {
+ await FeatureHint.resetAll();
+ if (!mounted) return;
+ showOverlayToast(context, l.tipsRestored,
+ icon: Icons.lightbulb_outline_rounded);
+ // Re-trigger the welcome dialog without an app
+ // restart. resetAll() already cleared the flag.
+ WelcomeSheet.showIfNeeded(context);
+ },
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ leading: Icon(Icons.bug_report_outlined, color: cs.onSurfaceVariant),
+ title: Text(l.bugsAndFeatureRequests),
+ subtitle: Text(l.bugsAndFeatureRequestsSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: Icon(Icons.open_in_new_rounded,
+ size: 18, color: cs.onSurfaceVariant),
+ onTap: () => launchUrl(
+ Uri.parse('https://github.com/pounat/absorb/issues'),
+ mode: LaunchMode.externalApplication),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ leading: Icon(Icons.discord, color: cs.onSurfaceVariant),
+ title: Text(l.joinDiscord),
+ subtitle: Text(l.joinDiscordSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: Icon(Icons.open_in_new_rounded,
+ size: 18, color: cs.onSurfaceVariant),
+ onTap: () => launchUrl(
+ Uri.parse('https://discord.gg/bwH6hdvzZ4'),
+ mode: LaunchMode.externalApplication),
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ leading: Icon(Icons.email_outlined, color: cs.primary),
+ title: Text(l.contact),
+ subtitle: Text(l.contactSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: const Icon(Icons.chevron_right_rounded),
+ onTap: () {
+ LogService().contactEmail(
+ serverVersion: auth.serverVersion,
+ );
+ },
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: Text(l.enableLogging),
+ subtitle: Text(
+ _loggingEnabled
+ ? l.enableLoggingOnSubtitle
+ : l.enableLoggingOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _loggingEnabled,
+ onChanged: _loaded ? (v) {
+ setState(() => _loggingEnabled = v);
+ PlayerSettings.setLoggingEnabled(v);
+ showOverlayToast(
+ context,
+ v
+ ? l.loggingEnabledSnackbar
+ : l.loggingDisabledSnackbar,
+ icon: Icons.article_outlined,
+ );
+ } : null,
+ ),
+ if (_loggingEnabled && LogService().enabled) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ leading: Icon(Icons.attach_file_rounded, color: cs.primary),
+ title: Text(l.sendLogs),
+ subtitle: Text(l.sendLogsSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: const Icon(Icons.chevron_right_rounded),
+ onTap: () async {
+ try {
+ await LogService().shareLogs(
+ serverVersion: auth.serverVersion,
+ sharePositionOrigin: shareOriginFor(context),
+ );
+ } catch (e) {
+ if (mounted) {
+ showOverlayToast(
+ context,
+ l.failedToShare(e.toString()),
+ icon: Icons.error_outline_rounded,
+ );
+ }
+ }
+ },
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ leading: Icon(Icons.delete_outline_rounded, color: cs.error),
+ title: Text(l.clearLogs),
+ onTap: () async {
+ final confirmed = await showDialog<bool>(
+ context: context,
+ builder: (ctx) => AlertDialog(
+ title: Text(l.clearLogsQuestion),
+ content: Text(l.clearLogsContent),
+ actions: [
+ TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text(l.cancel)),
+ TextButton(onPressed: () => Navigator.pop(ctx, true), child: Text(l.clear)),
+ ],
),
+ );
+ if (confirmed != true || !mounted) return;
+ await LogService().clearLogs();
+ if (mounted) {
+ showOverlayToast(context, l.logsCleared,
+ icon: Icons.delete_outline_rounded);
+ }
+ },
+ ),
+ ],
+ ],
+ ),
+ const SizedBox(height: 16),
+
+ // ── Advanced ──
+ CollapsibleSection(
+ key: _keyFor('Advanced'),
+ icon: Icons.tune_rounded,
+ title: l.sectionAdvanced,
+ cs: cs,
+ isExpanded: _expandedSection == 'Advanced',
+ onExpansionChanged: (v) => _onSectionExpanded('Advanced', v),
+ children: [
+ ListTile(
+ title: Text(l.navHoldSettingTitle),
+ subtitle: Text(l.navHoldSettingSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: const Icon(Icons.chevron_right_rounded),
+ onTap: _showNavHoldDialog,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: Row(children: [
+ Flexible(child: Text(l.localServer)),
+ _infoIcon(l.localServerInfoTitle, l.localServerInfoContent),
+ ]),
+ subtitle: Text(
+ _localServerEnabled
+ ? (auth.useLocalServer
+ ? l.localServerOnConnectedSubtitle
+ : l.localServerOnRemoteSubtitle)
+ : l.localServerOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _localServerEnabled,
+ onChanged: _loaded ? (v) {
+ setState(() => _localServerEnabled = v);
+ auth.setLocalServerConfig(enabled: v, url: _localServerUrl);
+ } : null,
+ ),
+ if (_localServerEnabled) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
+ child: TextField(
+ controller: _localServerController,
+ decoration: InputDecoration(
+ labelText: l.localServerUrlLabel,
+ hintText: l.localServerUrlHint,
+ border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
+ ),
+ onSubmitted: (_) => _saveLocalServerUrl(auth, l),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
+ child: Align(
+ alignment: Alignment.centerRight,
+ child: FilledButton.icon(
+ icon: const Icon(Icons.check_rounded, size: 18),
+ label: Text(l.setTooltip),
+ onPressed: () => _saveLocalServerUrl(auth, l),
),
+ ),
+ ),
+ if (auth.useLocalServer) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ leading: Icon(Icons.check_circle_rounded, color: Colors.greenAccent.shade400),
+ title: Text(l.localServerOnConnectedSubtitle),
+ subtitle: Text(_localServerUrl,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ ),
+ ],
+ ],
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: Row(children: [
+ Flexible(child: Text(l.trustAllCertificates)),
+ _infoIcon(l.trustAllCertificatesInfoTitle, l.trustAllCertificatesInfoContent),
+ ]),
+ subtitle: Text(
+ _trustAllCerts
+ ? l.trustAllCertificatesOnSubtitle
+ : l.trustAllCertificatesOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _trustAllCerts,
+ onChanged: _loaded ? (v) async {
+ setState(() => _trustAllCerts = v);
+ await PlayerSettings.setTrustAllCerts(v);
+ applyTrustAllCerts(v);
+ } : null,
+ ),
+ if (Platform.isAndroid) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: Row(children: [
+ Flexible(child: Text(l.mp3IndexSeeking)),
+ _infoIcon(l.mp3IndexSeekingInfoTitle, l.mp3IndexSeekingInfoContent),
+ ]),
+ subtitle: Text(
+ _mp3IndexSeeking
+ ? l.mp3IndexSeekingOnSubtitle
+ : l.mp3IndexSeekingOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _mp3IndexSeeking,
+ onChanged: _loaded ? (v) {
+ setState(() => _mp3IndexSeeking = v);
+ PlayerSettings.setMp3IndexSeeking(v);
+ } : null,
+ ),
+ ],
+ if (_isGithubBuild) ...[
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ SwitchListTile(
+ title: Row(children: [
+ Flexible(child: Text(l.includePreReleases)),
+ _infoIcon(l.preReleaseUpdatesInfoTitle, l.preReleaseUpdatesInfoContent),
+ ]),
+ subtitle: Text(
+ _includePreReleases
+ ? l.includePreReleasesOnSubtitle
+ : l.includePreReleasesOffSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ value: _includePreReleases,
+ onChanged: _loaded ? (v) async {
+ setState(() => _includePreReleases = v);
+ await PlayerSettings.setIncludePreReleases(v);
+ } : null,
+ ),
+ ],
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ leading: Icon(Icons.menu_book_rounded, color: cs.primary),
+ title: Text(l.adminRmab),
+ subtitle: Text(
+ ((_rmabBaseUrl ?? '').isNotEmpty && (_rmabApiToken ?? '').isNotEmpty)
+ ? l.adminRmabConnected
+ : l.adminRmabAskAdmin,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: Icon(Icons.chevron_right_rounded, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ onTap: _openRmabSheetFromSettings,
+ ),
+ const Divider(height: 1, indent: 16, endIndent: 16),
+ ListTile(
+ leading: Icon(Icons.record_voice_over_rounded, color: cs.primary),
+ title: Text(l.transcriptionTitle),
+ subtitle: Text(l.transcriptionAdvancedSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: Icon(Icons.chevron_right_rounded, color: cs.onSurfaceVariant.withValues(alpha: 0.5)),
+ onTap: () => Navigator.push(context, MaterialPageRoute(
+ builder: (_) => const TranscriptionSettingsScreen())),
+ ),
+ ],
+ ),
+ const SizedBox(height: 16),
- if (!isDesktopSettings ||
- expandedSection == 'Advanced' ||
- expandedSection == 'Library')
- const SizedBox(height: 10),
+ // ── Support the Dev ──
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Column(
+ children: [
+ Card(
+ color: cs.surfaceContainerHigh,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(14)),
+ clipBehavior: Clip.antiAlias,
+ child: ListTile(
+ leading: Icon(Icons.coffee_rounded,
+ color: Colors.amber.shade600),
+ title: Text(l.supportTheDev),
+ subtitle: Text(l.buyMeACoffee,
+ style: tt.bodySmall
+ ?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: Icon(Icons.favorite_rounded,
+ size: 18, color: Colors.amber.shade600),
+ onTap: () => launchUrl(
+ Uri.parse(
+ 'https://www.buymeacoffee.com/BarnabasApps'),
+ mode: LaunchMode.externalApplication),
+ ),
+ ),
+ ],
+ ),
+ ),
- // ── All Bookmarks ──
- if (!isDesktopSettings || expandedSection == 'Library')
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: 16),
- child: Card(
- elevation: 0,
- color: cs.surfaceContainerHigh,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(14),
- ),
- child: ListTile(
- leading: Icon(
- Icons.bookmarks_rounded,
- color: cs.primary,
- ),
- title: Text(l.allBookmarks),
- subtitle: Text(
- l.allBookmarksSubtitle,
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant,
- ),
- ),
- trailing: Icon(
- Icons.chevron_right_rounded,
- color: cs.onSurfaceVariant,
- ),
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(14),
- ),
- onTap: () => Navigator.push(
- context,
- MaterialPageRoute(
- builder: (_) => const BookmarksScreen(),
- ),
- ),
- ),
- ),
- ),
+ const SizedBox(height: 16),
- // ── Version Info ──
- if (!isDesktopSettings || expandedSection == 'Advanced')
- Center(
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Text(
- // Flavor prefix is an Android distribution concept
- // (GitHub / Play Store / F-Droid). iOS has no flavor, so
- // it keeps the plain version.
- AppPlatform.isIOS || AppPlatform.isWeb
- ? l.appVersionFormat(_appVersion)
- : '$_flavorLabel - $_appVersion',
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant.withValues(
- alpha: 0.4,
- ),
- ),
- ),
- const SizedBox(width: 4),
- Icon(
- _isGithubBuild
- ? Icons.code_rounded
- : Icons.store_rounded,
- size: 14,
- color: cs.onSurfaceVariant.withValues(
- alpha: 0.3,
- ),
- ),
- if (auth.serverVersion != null)
- Text(
- l.appVersionServerSuffix(
- auth.serverVersion!,
- ),
- style: tt.bodySmall?.copyWith(
- color: cs.onSurfaceVariant.withValues(
- alpha: 0.4,
- ),
- ),
- ),
- ],
- ),
- ),
+ // ── Backup and sync ──
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Card(
+ elevation: 0,
+ color: cs.surfaceContainerHigh,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
+ child: ListTile(
+ leading: Icon(Icons.cloud_sync_rounded, color: cs.primary),
+ title: Text(l.backupAndSync),
+ subtitle: Text(_backupSyncStatus(l),
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: Icon(Icons.chevron_right_rounded, color: cs.onSurfaceVariant),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
+ onTap: () async {
+ await Navigator.push(context,
+ MaterialPageRoute(builder: (_) => const BackupSyncScreen()));
+ if (mounted) await _refreshSyncStatus();
+ },
+ // Shortcut for the impatient: push straight from here
+ // rather than opening the screen for one button. Only
+ // offered while sync is on, since there is nowhere to
+ // send it otherwise.
+ onLongPress: _syncOn ? () => _uploadSyncNow(l) : null,
+ ),
+ ),
+ ),
- if (_isGithubBuild && !AppPlatform.isWeb) ...[
- const SizedBox(height: 4),
- Center(
- child: TextButton.icon(
- onPressed: () async {
- final info = await UpdateCheckerService.check(
- force: true,
- includePreReleases: _includePreReleases,
- );
- if (!mounted) return;
- if (info == null || !info.hasUpdate) {
- showOverlayToast(
- context,
- l.onLatestVersion,
- icon: Icons.check_circle_outline_rounded,
- );
- return;
- }
- await UpdateDialog.show(context, info);
- },
- icon: const Icon(
- Icons.system_update_rounded,
- size: 16,
- ),
- label: Text(l.checkForUpdate),
- ),
- ),
- ],
+ const SizedBox(height: 10),
- SizedBox(height: isDesktopSettings ? 24 : 100),
- ],
+ // ── All Bookmarks ──
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Card(
+ elevation: 0,
+ color: cs.surfaceContainerHigh,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
+ child: ListTile(
+ leading: Icon(Icons.bookmarks_rounded, color: cs.primary),
+ title: Text(l.allBookmarks),
+ subtitle: Text(l.allBookmarksSubtitle,
+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),
+ trailing: Icon(Icons.chevron_right_rounded, color: cs.onSurfaceVariant),
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(14)),
+ onTap: () => Navigator.push(context,
+ MaterialPageRoute(builder: (_) => const BookmarksScreen())),
),
),
+ ),
+
+ // ── Version Info ──
+ Center(child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(
+ // Flavor prefix is an Android distribution concept
+ // (GitHub / Play Store / F-Droid). iOS has no flavor, so
+ // it keeps the plain version. Beta builds add which
+ // beta of the cycle this is; full releases show nothing.
+ _versionLine(l),
+ style: tt.bodySmall?.copyWith(
+ color: cs.onSurfaceVariant.withValues(alpha: 0.4)),
+ ),
+ const SizedBox(width: 4),
+ Icon(
+ _isGithubBuild ? Icons.code_rounded : Icons.store_rounded,
+ size: 14,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.3),
+ ),
+ if (auth.serverVersion != null)
+ Text(
+ l.appVersionServerSuffix(auth.serverVersion!),
+ style: tt.bodySmall?.copyWith(
+ color: cs.onSurfaceVariant.withValues(alpha: 0.4)),
+ ),
+ ],
+ )),
+
+ if (_isGithubBuild) ...[
+ const SizedBox(height: 4),
+ Center(child: TextButton.icon(
+ onPressed: () async {
+ final info = await UpdateCheckerService.check(force: true, includePreReleases: _includePreReleases);
+ if (!mounted) return;
+ if (info == null || !info.hasUpdate) {
+ showOverlayToast(context, l.onLatestVersion,
+ icon: Icons.check_circle_outline_rounded);
+ return;
+ }
+ await UpdateDialog.show(context, info);
+ },
+ icon: const Icon(Icons.system_update_rounded, size: 16),
+ label: Text(l.checkForUpdate),
+ )),
],
- );
- return _SettingsAdaptiveFrame(
- desktopMode: isDesktopSettings,
- selectedSection: expandedSection,
- destinations: destinations,
- scrollController: _settingsScrollController,
- onSectionSelected: (section) {
- setState(() => _expandedSection = section);
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (!mounted || !_settingsScrollController.hasClients) {
- return;
- }
- _settingsScrollController.animateTo(
- 0,
- duration: const Duration(milliseconds: 180),
- curve: Curves.easeOut,
- );
- });
- },
- child: content,
- );
- },
- ),
- ),
+
+ const SizedBox(height: 100),
+ ],
+ ),
+ )
+ else
+ SliverToBoxAdapter(
+ child: SettingsSearchResults(
+ results: filterSettingEntries(
+ settingsSearchEntries(context), _settingsQuery),
+ onOpen: _openSearchResult,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
);
}
diff --cc lib/services/audio_player_service.dart
index 442e27cd,a12ea3d4..e1ba6e88
--- a/lib/services/audio_player_service.dart
+++ b/lib/services/audio_player_service.dart
@@@ -26,7 -27,7 +26,10 @@@ import 'session_cache.dart'
import 'home_widget_service.dart';
import 'bookmark_service.dart';
import 'review_service.dart';
++import 'dart:io' show ProcessInfo;
++import 'package:flutter/foundation.dart' show kIsWeb;
+import '../utils/app_platform.dart';
+ import '../utils/episode_key.dart';
export 'player_settings.dart';
String playbackDownloadKey(String itemId, String? episodeId) =>
@@@ -121,6 -132,24 +134,24 @@@ class AudioPlayerHandler extends BaseAu
/// enough that a headset press hours after the drive is taken at face value.
static const _carClientWindow = Duration(hours: 2);
+ /// Whether another app is playing on the music stream right now. A media
+ /// key that reaches us while we are paused and something else is audible
+ /// was meant for that something else - an earbud's wear detection pausing
+ /// a video, say. Android routes keys to the last media session, and video
+ /// apps often have none, so it lands here; playing on top of the video is
+ /// the last thing the user wants. Unknown reads as nothing playing.
+ static Future<bool> _otherAudioActive() async {
- if (!Platform.isAndroid) return false;
++ if (!AppPlatform.isAndroid) return false;
+ try {
+ final active = await AndroidAudioManager().isMusicActive();
+ debugPrint('[Handler] other audio active=$active');
+ return active;
+ } catch (e) {
+ debugPrint('[Handler] isMusicActive failed: $e');
+ return false;
+ }
+ }
+
/// Whether a car client has touched the media browse tree recently, per the
/// Java-side stamp. The MEDIA_PAUSE-while-paused phantom (GH #243) only
/// exists on Android Auto, so this is what decides whether the click
@@@ -1023,6 -1126,7 +1128,7 @@@
Map<String, dynamic>? options,
]) async {
debugPrint('[Handler] getChildren($parentMediaId)');
- if (Platform.isAndroid) unawaited(_maybeAutoplayOnCarConnect());
++ if (AppPlatform.isAndroid) unawaited(_maybeAutoplayOnCarConnect());
// Don't await refresh() here — getChildrenOf() handles it:
// downloads are populated instantly, server data loads in background.
return _autoService.getChildrenOf(parentMediaId);
@@@ -1522,6 -1707,12 +1710,12 @@@ class AudioPlayerService extends Change
_handler!.refreshPlaybackState();
}
});
- if (Platform.isIOS) {
++ if (AppPlatform.isIOS) {
+ unawaited(
+ Future.wait([fwdFuture, backFuture])
+ .then((v) => _pushIosSkipIntervals(v[0], v[1])),
+ );
+ }
}
/// Fill in a missing library id for the playing item so per-library skip
@@@ -2111,6 -2302,121 +2305,121 @@@
}
}
+ /// iOS: re-take the Now Playing claim after something may have knocked it
+ /// out while paused - a stretch suspended in the background where an
+ /// interruption came and went unseen, the user opening another app that
+ /// played something, or the headphones being stowed. iOS deactivates the
+ /// session for the interrupter, and a paused app that never re-activates
+ /// quietly falls out of Now Playing candidacy: the next headset press then
+ /// goes to Apple Music instead.
+ ///
+ /// Deliberately NOT called when an interruption ends while paused. Plenty
+ /// of apps deactivate their session on pause, which arrives here as an
+ /// interruption ending, and claiming at that moment would take the headset
+ /// away from the app the user just paused. The foreground and
+ /// route-disconnect calls pick the claim back up the next time the user
+ /// comes back to Absorb.
+ ///
+ /// Re-activating and republishing metadata is NOT enough on its own. iOS
+ /// only hands the slot to an app that has actually rendered audio, which is
+ /// what build 249 got wrong and 251 fixed with a silent blip - so the claim
+ /// goes through the native primer rather than being done here. Doing it in
+ /// Dart looked like it worked, because setActive succeeds either way.
+ ///
+ /// Only runs when nothing else is audibly playing: the claim matters
+ /// exactly when the next press should reach this app, and grabbing it out
+ /// from under an app mid-playback would be rude. The primer re-checks that
+ /// and activates the session itself, so nothing is activated from Dart and
+ /// the guard and the activation stay together with no gap between them.
+ Future<void> reassertIosClaimWhilePaused(String reason) async {
- if (!Platform.isIOS || !hasBook || isPlaying) return;
++ if (!AppPlatform.isIOS || !hasBook || isPlaying) return;
+ try {
+ final info = await _eqChannelForDiag
+ .invokeMethod<Map<dynamic, dynamic>>('getAudioDiagnostics');
+ if (info?['isOtherAudioPlaying'] == true ||
+ info?['secondaryAudioShouldBeSilencedHint'] == true) {
+ debugPrint(
+ '[AudioSession] claim reassert skipped ($reason) - other audio is playing',
+ );
+ return;
+ }
+ // Publish this book before the blip, so the slot we take back shows the
+ // right title rather than whatever the app that stole it left behind.
+ _handler?.refreshPlaybackState();
+ final started = await _eqChannelForDiag.invokeMethod<bool>(
+ 'reclaimNowPlaying',
+ {'reason': reason},
+ );
+ debugPrint(
+ '[AudioSession] claim reassert ($reason): blip started=$started',
+ );
+ } catch (e) {
+ debugPrint('[AudioSession] claim reassert failed ($reason): $e');
+ }
+ }
+
+ /// iOS: a headset press can cold-launch the app into the background with
+ /// the native core already driving the shared engine (its remote commands
+ /// arm at app launch). Dart then boots with no book loaded, so
+ /// audio_service publishes a blank Now Playing over the native core's and
+ /// every later press defers to a player that knows nothing - the lock
+ /// screen shows audio running with no title, cover or progress. Adopt
+ /// instead: restore the last-played item at the engine's own live position,
+ /// which re-publishes full metadata and puts Dart in charge of the audio
+ /// that is already running. Called once from main.dart after init.
+ Future<void> adoptBackgroundEngineIfRunning() async {
- if (!Platform.isIOS) return;
++ if (!AppPlatform.isIOS) return;
+ if (_currentItemId != null) return;
+ final player = _player;
+ if (player == null) return;
+ try {
+ var state = await player.engineState();
+ // A press-launched process races this check twice over: Dart init can
+ // get here before the native core has even LOADED the engine (a field
+ // log had this check lose by two milliseconds), and a stream then
+ // buffers for a while before isPlaying flips. Deciding on the first
+ // read left Dart bookless under live audio. So poll: a press-loaded
+ // engine shows up within the first second, and once it is loaded, give
+ // the buffer the rest of the budget. On a normal launch nothing ever
+ // loads and this waits out the budget then does nothing - harmless,
+ // since the primer has the lock screen and the command center routes
+ // any early press to the cold-start restore.
+ var waited = 0;
+ while ((state == null || !state.isLoaded || !state.isPlaying) &&
+ waited < 4000) {
+ await Future.delayed(const Duration(milliseconds: 500));
+ waited += 500;
+ // Dart started something itself while this waited - a card tap, a
+ // CarPlay autoplay, a headset press routed through the handler. That
+ // is Dart's own playback, not an orphaned engine: the restore below
+ // is the play/pause toggle, and calling it now would pause it.
+ if (_currentItemId != null) return;
+ state = await player.engineState();
+ }
+ if (_currentItemId != null) return;
+ if (state != null && state.isLoaded && state.isPlaying) {
+ debugPrint(
+ '[Player] boot: native engine already playing at '
+ '${state.globalPositionS.toStringAsFixed(1)}s with no book loaded - adopting'
+ '${waited > 0 ? " (waited ${waited}ms for the stream to start)" : ""}',
+ );
+ if (state.globalPositionS > 0) {
+ await HomeWidgetService().stashLivePosition(state.globalPositionS);
+ }
+ final restore = AudioPlayerService.onColdStartPlayRequested;
+ if (restore != null) await restore();
+ return;
+ }
+ // Idle engine: leave the player empty. The book only loads when the
+ // user actually plays - an early headset press still works because the
+ // handler routes play-with-nothing-loaded to the cold-start restore.
+ // (This used to load the last played book paused as a press target,
+ // which put an unasked-for book in the player on every launch.)
+ } catch (e) {
+ debugPrint('[Player] boot engine adopt failed: $e');
+ }
+ }
+
/// iOS foreground reconciliation after a possible widget-driven session.
///
/// The shared engine (AbsorbAudioEngine) persists across Flutter suspension,
@@@ -2524,10 -2865,16 +2871,16 @@@
// Initialize cached skip amounts so notification icons show the correct values
_handler!._cachedForwardSkip = fwdSkip;
_handler!._cachedBackSkip = backSkip;
+ // Nothing is loaded yet so there's no library override to apply; the
+ // per-library amounts follow from _syncNotifSkipCache once an item does.
- if (Platform.isIOS) {
++ if (AppPlatform.isIOS) {
+ unawaited(_pushIosSkipIntervals(fwdSkip, backSkip));
+ }
_handler!._cachedNotifSpeedBookmark =
await PlayerSettings.getMediaControlsSpeedBookmark();
_handler!._cachedLockSeekBar = await PlayerSettings.getLockSeekBar();
debugPrint('[Player] AudioService initialized');
- if (Platform.isIOS) unawaited(_reportPreviousBackgroundDeath());
++ if (AppPlatform.isIOS) unawaited(_reportPreviousBackgroundDeath());
// Configure streaming cache if enabled
final cacheSizeMb = await PlayerSettings.getStreamingCacheSizeMb();
debugPrint('[Player] Streaming cache setting: $cacheSizeMb MB');
@@@ -2727,6 -3076,22 +3085,22 @@@
return;
}
+ // iOS says whether the interrupter wants us back: shouldResume is
+ // set after a call, Siri or an alarm, and clear when the user
+ // started another app's audio. audio_session surfaces that as
+ // type `pause` (resume) versus `unknown` (don't). Resuming over a
+ // clear flag would cut off the app the user had just chosen - it
+ // only failed to because the activation was refused while that
+ // app still held the audio.
- if (Platform.isIOS &&
++ if (AppPlatform.isIOS &&
+ event.type == AudioInterruptionType.unknown &&
+ service._wasPlayingBeforeInterrupt) {
+ debugPrint(
+ '[AudioSession] Interruption ended without shouldResume - staying paused',
+ );
+ service._wasPlayingBeforeInterrupt = false;
+ return;
+ }
// Don't auto-resume if the pause was caused by BT/headphone disconnect.
// Some devices fire interruption-end AFTER becoming-noisy, which would
// resume playback on the phone speaker.
@@@ -2859,12 -3236,112 +3245,112 @@@
static void onAppBackgrounded() {
_instance._isBackgrounded = true;
debugPrint('[ClickDebug] App backgrounded');
- if (Platform.isIOS) _trimMemoryForBackground();
++ if (AppPlatform.isIOS) _trimMemoryForBackground();
+ }
+
+ /// iOS: a paused app in the background has no audio keeping it alive, is
+ /// suspended within seconds, and is a jetsam candidate whenever memory gets
+ /// tight. When iOS evicts it, the audio session goes with it, and any app
+ /// Absorb interrupted earlier is told to resume - it starts playing and owns
+ /// Now Playing from then on. Nothing keeps a paused app alive for hours, so
+ /// the lever is footprint: drop the decoded covers (up to 100MB) on the way
+ /// out. They reload lazily on return, and the screen is off meanwhile.
+ static void _trimMemoryForBackground() {
+ final cache = PaintingBinding.instance.imageCache;
+ final beforeMb = cache.currentSizeBytes ~/ 1048576;
+ cache.clear();
+ cache.clearLiveImages();
- final rssMb = ProcessInfo.currentRss ~/ 1048576;
++ final rssMb = kIsWeb ? -1 : ProcessInfo.currentRss ~/ 1048576;
+ unawaited(_logBackgroundMemory(rssMb, beforeMb));
+ }
+
+ static const _bgMarkerKey = 'ios_bg_marker';
+
+ /// iOS memory figures from the native side: `footprint` is what jetsam
+ /// judges (phys_footprint, not RSS) and `available` is how much more the
+ /// process may take before it is killed. Both in MB, -1 when unavailable.
+ static Future<({int footprintMb, int availableMb})> _iosMemoryInfo() async {
+ try {
+ final info = await _eqChannelForDiag
+ .invokeMethod<Map<dynamic, dynamic>>('getMemoryInfo');
+ int mb(dynamic v) {
+ final n = (v as num?)?.toInt() ?? -1;
+ return n < 0 ? -1 : n ~/ 1048576;
+ }
+ return (
+ footprintMb: mb(info?['footprint']),
+ availableMb: mb(info?['available']),
+ );
+ } catch (_) {
+ return (footprintMb: -1, availableMb: -1);
+ }
+ }
+
+ /// Log the footprint on the way out and leave a marker that the next
+ /// foreground clears. If a later launch still finds it, the process never
+ /// came back from the background: iOS ended it there (or the user swiped
+ /// it away).
+ static Future<void> _logBackgroundMemory(int rssMb, int droppedMb) async {
+ final m = await _iosMemoryInfo();
+ final playing = _instance.isPlaying;
+ debugPrint('[Memory] Backgrounded: footprint=${m.footprintMb}MB '
+ 'available=${m.availableMb}MB rss=${rssMb}MB playing=$playing, '
+ 'dropped ${droppedMb}MB of decoded covers');
+ try {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setString(
+ _bgMarkerKey,
+ '${DateTime.now().millisecondsSinceEpoch}|${m.footprintMb}|'
+ '${m.availableMb}|$playing',
+ );
+ } catch (_) {}
+ }
+
+ static Future<void> _logForegroundMemory() async {
+ try {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.remove(_bgMarkerKey);
+ } catch (_) {}
+ final m = await _iosMemoryInfo();
+ debugPrint('[Memory] Foregrounded: footprint=${m.footprintMb}MB '
+ 'available=${m.availableMb}MB');
+ }
+
+ static Future<void> _reportPreviousBackgroundDeath() async {
+ try {
+ final prefs = await SharedPreferences.getInstance();
+ final raw = prefs.getString(_bgMarkerKey);
+ if (raw == null) return;
+ await prefs.remove(_bgMarkerKey);
+ final parts = raw.split('|');
+ final at = int.tryParse(parts[0]) ?? 0;
+ final ago = DateTime.now()
+ .difference(DateTime.fromMillisecondsSinceEpoch(at))
+ .inMinutes;
+ String part(int i) => parts.length > i ? parts[i] : '?';
+ debugPrint('[Memory] Previous process ended in the background, '
+ '${ago}min after it went there (or was swiped away): '
+ 'footprint=${part(1)}MB available=${part(2)}MB playing=${part(3)}');
+ } catch (_) {}
+ }
+
+ /// Flutter forwards iOS memory warnings here (and drops its image cache on
+ /// its own). Logging them with the numbers says how close to the edge the
+ /// app was, before jetsam makes the decision for it.
+ static void onMemoryPressure() {
- if (!Platform.isIOS) return;
++ if (!AppPlatform.isIOS) return;
+ unawaited(() async {
+ final m = await _iosMemoryInfo();
+ debugPrint('[Memory] iOS memory warning: footprint=${m.footprintMb}MB '
+ 'available=${m.availableMb}MB');
+ }());
}
static Future<void> onAppForegrounded() async {
final service = _instance;
service._isBackgrounded = false;
_lastForegroundAt = DateTime.now();
- if (Platform.isIOS) unawaited(_logForegroundMemory());
++ if (AppPlatform.isIOS) unawaited(_logForegroundMemory());
// Relative timing on foreground arrival is the second half of the
// AA-disconnect fingerprint (variant 3): raw pause, then foreground
// within ~2s. Log sincePrevPauseMs / sincePrevPlayMs so the disconnect
@@@ -2890,8 -3367,8 +3376,8 @@@
'[ClickDebug] App foregrounded: sincePrevPauseMs=$sincePrevPauseMs, '
'sincePrevPlayMs=$sincePrevPlayMs, aaDisconnectSuspect=$aaDisconnectSuspect',
);
- service._positionSyncFailures = 0; // retry on foreground
+ service.resetServerSyncBackoff();
- if (Platform.isIOS && service._iosResyncPending) {
+ if (AppPlatform.isIOS && service._iosResyncPending) {
unawaited(service._iosForegroundResyncIfNeeded());
}
// After a widget-driven session the shared engine may have kept playing
@@@ -2940,8 -3417,14 +3426,14 @@@
// require it, and play()/startLocalPlayback reacquire focus themselves.
if (service.isPlaying) {
try {
- (await AudioSession.instance).setActive(true);
+ await _setAudioSessionActive(true);
} catch (_) {}
- } else if (Platform.isIOS && service.hasBook) {
++ } else if (AppPlatform.isIOS && service.hasBook) {
+ // Paused with a book loaded: an interruption while iOS had this app
+ // suspended may have silently dropped the Now Playing claim. The
+ // Android concern above (activation grabbing focus and pausing other
+ // apps) doesn't apply - the reassert has its own other-audio guard.
+ await service.reassertIosClaimWhilePaused('foreground');
}
// Re-push playback state so the system re-registers the MediaSession
_handler?.refreshPlaybackState();
@@@ -3125,6 -3615,29 +3624,29 @@@
startTime = newerStashedPos;
localTimestampAtStart = DateTime.now().millisecondsSinceEpoch;
}
+ // iOS: the shared engine may be playing this very item right now (the
+ // native core started it from a headset press and Dart never adopted
+ // it). Its position is the live truth - the stash was written once at
+ // press time and local progress stopped at the last pause, so resuming
+ // from either threw away everything listened since. The stash match
+ // above ties the engine's content to this episode; the engine itself
+ // only knows the library item.
- if (Platform.isIOS && (episodeId == null || stashedPos != null)) {
++ if (AppPlatform.isIOS && (episodeId == null || stashedPos != null)) {
+ try {
+ final engine = await _player?.engineState();
+ if (engine != null &&
+ engine.isLoaded &&
+ engine.itemId == itemId &&
+ engine.globalPositionS > startTime + 1.0) {
+ debugPrint(
+ '[Player] Resuming from live engine position: '
+ '${engine.globalPositionS.toStringAsFixed(1)}s (was ${startTime}s)',
+ );
+ startTime = engine.globalPositionS;
+ localTimestampAtStart = DateTime.now().millisecondsSinceEpoch;
+ }
+ } catch (_) {}
+ }
}
// Set seek target early so the UI doesn't flash chapter 1 while loading
@@@ -3746,8 -4373,11 +4387,11 @@@
_handler?.refreshPlaybackState();
await Future.delayed(const Duration(milliseconds: 200));
try {
- (await AudioSession.instance).setActive(true);
+ await _setAudioSessionActive(true);
} catch (_) {}
+ if (_startSuperseded(gen)) {
+ return _abandonStart(null, null, 'local, before play');
+ }
_player!.play();
_scheduleAudioDiagnostics('local');
notifyListeners();
@@@ -3932,8 -4589,12 +4603,12 @@@
_handler?.refreshPlaybackState();
await Future.delayed(const Duration(milliseconds: 200));
try {
- (await AudioSession.instance).setActive(true);
+ await _setAudioSessionActive(true);
} catch (_) {}
+ if (_startSuperseded(playbackGeneration)) {
+ dropPendingSession();
+ return _abandonStart(null, null, 'cached start, before play');
+ }
_cachedStartReconcileGeneration = playbackGeneration;
_player!.play();
_scheduleAudioDiagnostics('cached-session');
@@@ -4353,8 -5051,11 +5065,11 @@@
_handler?.refreshPlaybackState();
await Future.delayed(const Duration(milliseconds: 200));
try {
- (await AudioSession.instance).setActive(true);
+ await _setAudioSessionActive(true);
} catch (_) {}
+ if (_startSuperseded(gen)) {
+ return _abandonStart(api, ownSessionId, 'before play');
+ }
_player!.play();
_scheduleAudioDiagnostics('stream');
notifyListeners();
@@@ -4516,8 -5236,12 +5250,12 @@@
await EqualizerService().switchItem(itemId);
debugPrint('[Player] Transcoded playback starting at ${speed}x');
try {
- (await AudioSession.instance).setActive(true);
+ await _setAudioSessionActive(true);
} catch (_) {}
+ if (_startSuperseded(gen)) {
+ _abandonStart(api, ownSessionId, 'transcode retry, before play');
+ return;
+ }
_player!.play();
_scheduleAudioDiagnostics('transcoded');
notifyListeners();
diff --cc lib/services/download_service.dart
index e82bb009,22a30ee3..07fbe66e
--- a/lib/services/download_service.dart
+++ b/lib/services/download_service.dart
@@@ -1272,11 -1325,20 +1330,23 @@@ class DownloadService extends ChangeNot
String? episodeId,
String? libraryId,
bool Function()? shouldStart,
+ // Set by the auto-download planners. An item the user deleted by hand is
+ // skipped when automatic; a manual (or download-on-stream) call clears
+ // that block, since the user asked for it back.
+ bool automatic = false,
}) async {
+ if (AppPlatform.isWeb) {
+ return 'Downloads are not available in the browser.';
+ }
if (shouldStart?.call() == false) return null;
+ // Episodes are keyed "podcastId-episodeId" everywhere below. A caller
+ // holding the bare podcast id (the transcription download prompt did)
+ // used to fail in the key math before a single request went out.
+ if (episodeId != null && !itemId.endsWith('-$episodeId')) {
+ debugPrint('[Download] "$title": composing the episode key from '
+ 'podcast $itemId + episode $episodeId');
+ itemId = '$itemId-$episodeId';
+ }
try {
await init().timeout(const Duration(seconds: 8));
} on TimeoutException catch (e) {
diff --cc lib/services/log_service.dart
index e0fb4019,b926c5ca..ae204e05
--- a/lib/services/log_service.dart
+++ b/lib/services/log_service.dart
@@@ -5,7 -4,7 +5,8 @@@ import 'package:flutter/foundation.dart
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
import 'package:url_launcher/url_launcher.dart';
+import '../utils/text_file_download.dart';
+ import '../build_info.dart';
import 'api_service.dart';
class LogService {
diff --cc lib/services/player_settings.dart
index 1274148f,b0470140..61300a4c
--- a/lib/services/player_settings.dart
+++ b/lib/services/player_settings.dart
@@@ -235,9 -204,138 +247,139 @@@ class PlayerSettings
/// Bookmark sort: 'newest' (default) or 'position'
static Future<String> getBookmarkSort() => _get('bookmarkSort', 'newest');
- static Future<void> setBookmarkSort(String value) => _set('bookmarkSort', value);
+ static Future<void> setBookmarkSort(String value) =>
+ _set('bookmarkSort', value);
+ // On-device bookmark transcription (Whisper, opt-in). Stored globally
+ // (raw SharedPreferences, not per-account) because the downloaded Whisper
+ // model is shared across every profile on the device.
+
+ static Future<bool> getTranscriptionEnabled() async {
+ final prefs = await SharedPreferences.getInstance();
+ return prefs.getBool('transcriptionEnabled') ?? false;
+ }
+ static Future<void> setTranscriptionEnabled(bool value) async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setBool('transcriptionEnabled', value);
+ _notify();
+ }
+
+ /// How much audio a bookmark transcription covers, in seconds.
+ static Future<int> getTranscriptionWindowSeconds() async {
+ final prefs = await SharedPreferences.getInstance();
+ return prefs.getInt('transcriptionWindowSeconds') ?? 30;
+ }
+ static Future<void> setTranscriptionWindowSeconds(int value) async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setInt('transcriptionWindowSeconds', value);
+ }
+
+ /// Replace a bookmark transcript with the ebook's exact text when a
+ /// confident match is found (only offered when the book has an EPUB).
+ static Future<bool> getTranscriptionUseEbookText() async {
+ final prefs = await SharedPreferences.getInstance();
+ return prefs.getBool('transcriptionUseEbookText') ?? true;
+ }
+ static Future<void> setTranscriptionUseEbookText(bool value) async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setBool('transcriptionUseEbookText', value);
+ }
+
+ /// Live transcript overlay: line font size and how many lines may wrap.
+ static Future<double> getLyricsFontSize() async {
+ final prefs = await SharedPreferences.getInstance();
+ return prefs.getDouble('lyricsFontSize') ?? 16;
+ }
+ static Future<void> setLyricsFontSize(double value) async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setDouble('lyricsFontSize', value);
+ }
+ static Future<bool> getLyricsIntroShown() async {
+ final prefs = await SharedPreferences.getInstance();
+ return prefs.getBool('lyricsIntroShown') ?? false;
+ }
+ static Future<void> setLyricsIntroShown() async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setBool('lyricsIntroShown', true);
+ }
+
+ /// Color the spoken words are painted in for read along and the live
+ /// transcript overlay, as an ARGB value. Amber by default: it stays legible
+ /// on the light, sepia and dark reader themes alike.
+ static const int defaultReadAlongColor = 0xFFFFC400;
+ static Future<int> getReadAlongColor() async {
+ final prefs = await SharedPreferences.getInstance();
+ return prefs.getInt('readAlongColor') ?? defaultReadAlongColor;
+ }
+ static Future<void> setReadAlongColor(int value) async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setInt('readAlongColor', value);
+ }
+
+ /// How closely read along follows the narration: 'word' colors one word at
+ /// a time with the rest of the sentence dimmed, 'sentence' colors the whole
+ /// sentence at once.
+ static Future<String> getReadAlongMode() async {
+ final prefs = await SharedPreferences.getInstance();
+ return prefs.getString('readAlongMode') ?? 'word';
+ }
+ static Future<void> setReadAlongMode(String value) async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setString('readAlongMode', value);
+ }
+
+ /// How far ahead of your ears the playhead runs, in milliseconds, so the
+ /// transcript can be held back to match. Bluetooth adds a couple of hundred
+ /// milliseconds that the phone's own speaker doesn't, so the two are
+ /// remembered separately and picked by whatever you are listening on.
+ static Future<int> getTranscriptOffsetMs({required bool bluetooth}) async {
+ final prefs = await SharedPreferences.getInstance();
+ return prefs.getInt(bluetooth ? 'transcriptOffsetBt' : 'transcriptOffset') ?? 0;
+ }
+ static Future<void> setTranscriptOffsetMs(int value,
+ {required bool bluetooth}) async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setInt(
+ bluetooth ? 'transcriptOffsetBt' : 'transcriptOffset', value);
+ }
+
+ /// Whether the live transcript takes over the whole cover instead of
+ /// sitting in a strip across the bottom of it.
+ static Future<bool> getLyricsFullCover() async {
+ final prefs = await SharedPreferences.getInstance();
+ return prefs.getBool('lyricsFullCover') ?? true;
+ }
+ static Future<void> setLyricsFullCover(bool value) async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setBool('lyricsFullCover', value);
+ }
+
+ static Future<int> getLyricsMaxLines() async {
+ final prefs = await SharedPreferences.getInstance();
+ return prefs.getInt('lyricsMaxLines') ?? 3;
+ }
+ static Future<void> setLyricsMaxLines(int value) async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setInt('lyricsMaxLines', value);
+ }
+
+ /// Where Find in audiobook lands on success: true = switch to the player,
+ /// false = stay in the reader while the audio plays.
+ /// Where a successful Find in audiobook lands: 'stay' in the reader,
+ /// 'player', or 'readalong' - stay and switch read along on from there.
+ static Future<String> getFindInAudiobookAfter() async {
+ final prefs = await SharedPreferences.getInstance();
+ final v = prefs.getString('findInAudiobookAfter');
+ if (v != null) return v;
+ // The setting used to be a two-way switch.
+ final old = prefs.getBool('findInAudiobookGoToPlayer');
+ return old == false ? 'stay' : 'player';
+ }
+ static Future<void> setFindInAudiobookAfter(String value) async {
+ final prefs = await SharedPreferences.getInstance();
+ await prefs.setString('findInAudiobookAfter', value);
+ }
+
// The dedicated Podcasts tab implies merged behavior: playback must survive
// the tab-driven library flips and the Absorbing tab must keep showing the
// playing item from either tab.
@@@ -925,20 -896,15 +1075,17 @@@
/// 'off' | 'addTime' | 'resetTimer'. A press inside the wind-down window
/// resets or extends the timer instead of pausing.
static Future<String> getSleepButtonMode() => _get('sleepButtonMode', 'off');
- static Future<void> setSleepButtonMode(String v) =>
- _set('sleepButtonMode', v);
+ static Future<void> setSleepButtonMode(String v) => _set('sleepButtonMode', v);
- static Future<bool> getResetSleepOnPause() =>
- _get('resetSleepOnPause', false);
- static Future<void> setResetSleepOnPause(bool value) =>
- _set('resetSleepOnPause', value);
+ static Future<bool> getResetSleepOnPause() => _get('resetSleepOnPause', false);
+ static Future<void> setResetSleepOnPause(bool value) => _set('resetSleepOnPause', value);
static Future<bool> getSleepFadeOut() => _get('sleepFadeOut', true);
- static Future<void> setSleepFadeOut(bool value) => _set('sleepFadeOut', value);
+ static Future<void> setSleepFadeOut(bool value) =>
+ _set('sleepFadeOut', value);
static Future<int> getSleepFadeDuration() => _get('sleepFadeDuration', 30);
- static Future<void> setSleepFadeDuration(int seconds) => _set('sleepFadeDuration', seconds);
+ static Future<void> setSleepFadeDuration(int seconds) =>
+ _set('sleepFadeDuration', seconds);
static Future<bool> getSleepChime() => _get('sleepChime', false);
static Future<void> setSleepChime(bool value) => _set('sleepChime', value);
static Future<double> getSleepChimeVolume() => _get('sleepChimeVolume', 2.0);
@@@ -1149,36 -1054,41 +1296,50 @@@
// Ebook reader: turn pages with the volume keys. 'off' | 'normal'
// (up = previous page, down = next, matching the ABS app) | 'mirrored'.
- static Future<String> getEreaderVolumeNav() => _get('ereaderVolumeNav', 'off');
- static Future<void> setEreaderVolumeNav(String value) => _set('ereaderVolumeNav', value, notify: true);
+ static Future<String> getEreaderVolumeNav() =>
+ _get('ereaderVolumeNav', 'off');
+ static Future<void> setEreaderVolumeNav(String value) =>
+ _set('ereaderVolumeNav', value, notify: true);
// Keep turning pages with the volume keys even while audio is playing
// (off = playing audio gives the keys back to system volume).
- static Future<bool> getEreaderVolumeNavWhilePlaying() => _get('ereaderVolumeNavWhilePlaying', false);
- static Future<void> setEreaderVolumeNavWhilePlaying(bool value) => _set('ereaderVolumeNavWhilePlaying', value, notify: true);
+ static Future<bool> getEreaderVolumeNavWhilePlaying() =>
+ _get('ereaderVolumeNavWhilePlaying', false);
+ static Future<void> setEreaderVolumeNavWhilePlaying(bool value) =>
+ _set('ereaderVolumeNavWhilePlaying', value, notify: true);
+ static Future<double> getEreaderAutoScrollSpeed() => _get('ereaderAutoScrollSpeed', 40.0);
+ static Future<void> setEreaderAutoScrollSpeed(double value) => _set('ereaderAutoScrollSpeed', value);
+ static Future<int> getEreaderAutoScrollSleepMinutes() => _get('ereaderAutoScrollSleepMinutes', 30);
+ static Future<void> setEreaderAutoScrollSleepMinutes(int value) => _set('ereaderAutoScrollSleepMinutes', value);
+
/// When on, the screen is locked to portrait (rotation disabled). Default off
/// keeps the current behaviour where all orientations are allowed.
static Future<bool> getLockPortrait() => _get('lockPortrait', false);
- static Future<void> setLockPortrait(bool value) => _set('lockPortrait', value);
+ static Future<void> setLockPortrait(bool value) =>
+ _set('lockPortrait', value);
- static Future<bool> getSnappyTransitions() => _get('snappyTransitions', false);
- static Future<void> setSnappyTransitions(bool value) => _set('snappyTransitions', value);
+ static Future<bool> getSnappyTransitions() =>
+ _get('snappyTransitions', false);
+ static Future<void> setSnappyTransitions(bool value) =>
+ _set('snappyTransitions', value);
static Future<bool> getClassicWording() => _get('classicWording', false);
- static Future<void> setClassicWording(bool value) => _set('classicWording', value);
+ static Future<void> setClassicWording(bool value) =>
+ _set('classicWording', value);
static Future<bool> getRectangleCovers() => _get('rectangleCovers', false);
- static Future<void> setRectangleCovers(bool value) => _set('rectangleCovers', value, notify: true);
+ static Future<void> setRectangleCovers(bool value) =>
+ _set('rectangleCovers', value, notify: true);
+ /// Cached value for synchronous access in grid builders.
+ /// 'small' | 'medium' | 'large'; medium keeps the long-standing layout.
+ static String coverSize = 'medium';
+ static Future<String> getCoverSize() => _get('coverSize', 'medium');
+ static Future<void> setCoverSize(String value) async {
+ coverSize = value;
+ await _set('coverSize', value, notify: true);
+ }
+
/// Per-library cover-shape override: 'rect', 'square', or null (= follow
/// the global toggle). Lets an ebook library run tall covers while the
/// audiobook libraries stay square.
@@@ -1208,13 -1115,41 +1369,43 @@@
return getRectangleCovers();
}
+ static Future<bool> getShowSubtitles() => _get('showSubtitles', false);
+ static Future<void> setShowSubtitles(bool value) => _set('showSubtitles', value, notify: true);
+
+ /// Per-library subtitle override: 'show', 'hide', or null (= follow the
+ /// global toggle). Most libraries leave the field empty, so a library that
+ /// does fill it in can show subtitles without the rest going taller.
+ static Future<String?> getShowSubtitlesOverride(String libraryId) async {
+ final v = await ScopedPrefs.getString('showSubtitles_$libraryId');
+ return (v == 'show' || v == 'hide') ? v : null;
+ }
+
+ static Future<void> setShowSubtitlesOverride(String libraryId, String? value) async {
+ if (value == null) {
+ await ScopedPrefs.remove('showSubtitles_$libraryId');
+ } else {
+ await ScopedPrefs.setString('showSubtitles_$libraryId', value);
+ }
+ _notify();
+ }
+
+ /// Subtitle visibility for a library: its override if set, else the global
+ /// toggle.
+ static Future<bool> getShowSubtitlesFor(String? libraryId) async {
+ if (libraryId != null) {
+ final v = await getShowSubtitlesOverride(libraryId);
+ if (v != null) return v == 'show';
+ }
+ return getShowSubtitles();
+ }
+
static Future<bool> getSectionGridView() => _get('sectionGridView', false);
- static Future<void> setSectionGridView(bool value) => _set('sectionGridView', value);
+ static Future<void> setSectionGridView(bool value) =>
+ _set('sectionGridView', value);
static Future<bool> getCoverPlayButton() => _get('coverPlayButton', false);
- static Future<void> setCoverPlayButton(bool value) => _set('coverPlayButton', value, notify: true);
+ static Future<void> setCoverPlayButton(bool value) =>
+ _set('coverPlayButton', value, notify: true);
/// Absorbing-card background style: 'blurred' (cover blur, default), 'gradient'
/// (gradient from the extracted cover colors), or 'off' (plain theme surface).
@@@ -1388,9 -1288,18 +1568,19 @@@
static Future<bool> getFlatBackground() => _get('flatBackground', false);
static Future<void> setFlatBackground(bool v) => _set('flatBackground', v);
+ /// E-ink mode: an override layer for e-ink screens - light flat monochrome
+ /// theme, no animations, plain cards, and the live socket stays down for
+ /// battery. The user's individual appearance settings are left untouched so
+ /// turning it off restores everything. Device-specific by nature, so it is
+ /// deliberately absent from settings sync and backups. The static mirrors
+ /// the stored value for cheap checks from non-async code.
+ static bool einkMode = false;
+ static Future<bool> getEinkMode() => _get('einkMode', false);
+ static Future<void> setEinkMode(bool v) => _set('einkMode', v);
+
/// Seed color (ARGB int) used when [getColorSource] is 'manual'.
- static Future<int> getManualSeedColor() => _get('manualSeedColor', 0xFF7C6FBF);
+ static Future<int> getManualSeedColor() =>
+ _get('manualSeedColor', 0xFF7C6FBF);
static Future<void> setManualSeedColor(int v) => _set('manualSeedColor', v);
/// Strength of the primary-tinted background gradient (top alpha, 0 = flat).
diff --cc lib/widgets/absorbing_card.dart
index 20baf83a,a3363707..00ff6e60
--- a/lib/widgets/absorbing_card.dart
+++ b/lib/widgets/absorbing_card.dart
@@@ -965,9 -858,7 +975,9 @@@ class AbsorbingCardState extends State<
listenable: Listenable.merge([ChromecastService(), widget.player]),
builder: (context, _) => LayoutBuilder(
builder: (context, constraints) {
- final maxW = constraints.maxWidth * 0.85;
+ final maxW = spaciousDesktop
+ ? (constraints.maxWidth * 0.9).clamp(0.0, 780.0).toDouble()
- : constraints.maxWidth * 0.75;
++ : constraints.maxWidth * 0.85;
final rawH = constraints.maxHeight.isFinite ? constraints.maxHeight : maxW;
final maxH = rawH - 24;
double coverW, coverH;
diff --cc lib/widgets/absorbing_shared.dart
index 6e51403e,27ba240f..5231a828
--- a/lib/widgets/absorbing_shared.dart
+++ b/lib/widgets/absorbing_shared.dart
@@@ -7,7 -7,7 +7,8 @@@ import '../providers/auth_provider.dart
import '../providers/library_provider.dart';
import '../services/download_service.dart';
import '../services/playback_history_service.dart';
+import '../utils/app_platform.dart';
+ import '../services/player_settings.dart';
import 'overlay_toast.dart';
String dateLabel(DateTime dt, [AppLocalizations? l]) {
@@@ -289,7 -300,7 +313,7 @@@ class _DownloadWideButtonState extends
actions: [
TextButton(onPressed: () => Navigator.pop(ctx), child: Text(l.cancel)),
TextButton(onPressed: () {
- dl.deleteDownload(widget.itemId);
- _dl.deleteDownload(widget.itemId, byUser: true);
++ dl.deleteDownload(widget.itemId, byUser: true);
Navigator.pop(ctx);
showOverlayToast(context, l.downloadRemoved, icon: Icons.delete_outline_rounded);
},
diff --cc lib/widgets/book_card.dart
index 9d4aaa8b,c4e45d89..bf9b92bd
--- a/lib/widgets/book_card.dart
+++ b/lib/widgets/book_card.dart
@@@ -11,8 -10,6 +11,9 @@@ import '../services/download_service.da
import 'absorbing_shared.dart';
import 'book_detail_sheet.dart';
import 'episode_list_sheet.dart';
+import 'hover_cover_actions.dart';
+import '../utils/app_platform.dart';
++import '../utils/desktop_workspace.dart';
class BookCard extends StatelessWidget {
final Map<String, dynamic> item;
@@@ -72,59 -71,60 +75,80 @@@
final headers = lib.mediaHeaders;
final card = isWide
- ? _buildWideCard(
- context,
- cs,
- tt,
- l,
- title,
- authorName,
- coverUrl,
- progress,
- headers,
- isExplicit: isExplicit,
- )
- : _buildCompactCard(
- context,
- cs,
- tt,
- l,
- title,
- authorName,
- coverUrl,
- progress,
- headers,
- isFinished: isFinished,
- isDownloaded: isDownloaded,
- isExplicit: isExplicit,
- unfinishedCount: unfinishedCount,
- );
-
- final canEdit =
- itemId != null &&
+ ? _buildWideCard(context, cs, tt, l, title, authorName, coverUrl, progress, headers, isExplicit: isExplicit)
+ : _buildCompactCard(context, cs, tt, l, title, subtitle, authorName, coverUrl, progress, headers, isFinished: isFinished, isDownloaded: isDownloaded, isExplicit: isExplicit, unfinishedCount: unfinishedCount);
- if (!selectionMode) return card;
++ final canEdit = itemId != null &&
+ !lib.isPodcastLibrary &&
+ !lib.isOffline &&
- context.watch<AuthProvider>().canUpdateMetadata;
- return HoverCoverActions(
- onMenu: itemId == null || selectionMode
- ? null
- : () => _onLongPress(context),
++ isDesktopWorkspace(context) &&
++ (context.watch<AuthProvider?>()?.canUpdateMetadata ?? false);
++ // Desktop hover actions only; selection is drawn below, on every layout.
++ final hovered = HoverCoverActions(
++ onMenu: itemId == null || selectionMode ? null : () => _onLongPress(context),
+ editItemId: canEdit && !selectionMode ? itemId : null,
+ selectionMode: selectionMode,
- selected: selected,
- onSelectionToggle: onSelectionToggle,
+ child: card,
+ );
++ if (!selectionMode) return hovered;
+ // Selection sits on top of the finished card rather than inside both
+ // layouts: the overlay swallows the tap, so nothing below it can open a
+ // sheet while the shelf is being ticked through.
+ return Stack(
+ children: [
- card,
++ hovered,
+ Positioned.fill(
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onSelectionToggle,
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(12),
+ border: selected
+ ? Border.all(color: cs.primary, width: 3)
+ : null,
+ color: selected
+ ? cs.primary.withValues(alpha: 0.18)
+ : Colors.transparent,
+ ),
+ ),
+ ),
+ ),
+ Positioned(
+ top: 6,
+ left: 6,
+ child: IgnorePointer(
+ child: Container(
+ width: 26,
+ height: 26,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: selected
+ ? cs.primary
+ : Colors.black.withValues(alpha: 0.55),
+ border: Border.all(
+ color: selected ? cs.primary : Colors.white70,
+ ),
+ ),
+ child: Icon(
+ selected ? Icons.check_rounded : Icons.circle_outlined,
+ size: 17,
+ color: selected ? cs.onPrimary : Colors.white70,
+ ),
+ ),
+ ),
+ ),
+ ],
+ );
}
+ void _handleTap(BuildContext context) {
+ if (selectionMode && onSelectionToggle != null) {
+ onSelectionToggle!();
+ return;
+ }
+ _navigateToDetail(context);
+ }
+
void _navigateToDetail(BuildContext context) {
final itemId = item['id'] as String?;
if (itemId == null) return;
@@@ -220,28 -218,12 +244,21 @@@
height: 120,
child: Stack(
children: [
- _CoverImage(
- coverUrl: coverUrl,
- cs: cs,
- fit: BoxFit.contain,
- httpHeaders: headers,
- title: title,
- author: authorName,
- ),
+ _CoverImage(coverUrl: coverUrl, cs: cs, fit: BoxFit.contain, httpHeaders: headers, title: title, author: authorName),
if (isExplicit)
Positioned(
- top: 4, right: DownloadService().isDownloaded(item['id'] as String? ?? '') ? 30 : 4,
+ top: 4,
+ right:
+ DownloadService().isDownloaded(
+ item['id'] as String? ?? '',
+ )
+ ? 30
+ : 4,
child: Container(
- padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
+ padding: const EdgeInsets.symmetric(
+ horizontal: 4,
+ vertical: 1,
+ ),
decoration: BoxDecoration(
color: Colors.red.withValues(alpha: 0.85),
borderRadius: BorderRadius.circular(4),
diff --cc lib/widgets/book_detail_sheet.dart
index 9330fe56,7ca50d24..646cebd4
--- a/lib/widgets/book_detail_sheet.dart
+++ b/lib/widgets/book_detail_sheet.dart
@@@ -52,7 -51,7 +55,8 @@@ import 'adaptive_modal.dart'
import 'stackable_sheet.dart';
import 'ebook_router.dart';
import '../utils/duration_format.dart';
+import '../utils/url_file_download.dart';
+ import '../utils/share_origin.dart';
// ─── BOOK DETAIL BOTTOM SHEET ───────────────────────────────
@@@ -651,24 -856,7 +862,15 @@@ class _BookDetailSheetContentState exte
else
const SizedBox(height: 20),
const SizedBox(height: 12),
- if (progress > 0 && !isFinished) ...[
- ClipRRect(borderRadius: BorderRadius.circular(3),
- child: LinearProgressIndicator(value: progress.clamp(0.0, 1.0), minHeight: 4,
- backgroundColor: cs.onSurface.withValues(alpha: 0.1), valueColor: AlwaysStoppedAnimation(accent))),
- const SizedBox(height: 4),
- Text(l.percentComplete((progress * 100).toStringAsFixed(1)), textAlign: TextAlign.center,
- style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant)),
- const SizedBox(height: 12),
- ],
- if (isEbookOnly && ebookFile != null && canReadEbook(ebookFile))
+ if (isEbookOnly && AppPlatform.isWeb)
+ SizedBox(height: 52, child: FilledButton.icon(
+ onPressed: null,
+ icon: const Icon(Icons.menu_book_rounded, size: 24),
+ label: Text(l.ebookOnlyNoAudio,
+ style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600)),
+ style: FilledButton.styleFrom(shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16))),
+ ))
+ else if (isEbookOnly && ebookFile != null && canReadEbook(ebookFile))
SizedBox(height: 52, child: FilledButton.icon(
onPressed: () => _openEbookReader(context, auth, ebookFile, title),
icon: const Icon(Icons.menu_book_rounded, size: 24),
@@@ -755,14 -975,61 +989,65 @@@
},
),
),
- // Primary action row: Download | Fully Absorb | Read (when ebook)
+ // A companion ebook gets its own, smaller button under Absorb with the
+ // reading progress filled in the same way. Ebook-only books already
+ // have Read as the big button above.
+ if (!isEbookOnly && ebookFile != null && canReadEbook(ebookFile)) ...[
+ const SizedBox(height: 8),
+ Builder(builder: (context) {
+ final ebookProgress = lib.getEbookProgress(widget.itemId);
+ final showFill = ebookProgress > 0 && ebookProgress < 1;
+ return SizedBox(
+ height: 40,
+ child: Material(
+ color: accent.withValues(alpha: 0.14),
+ borderRadius: BorderRadius.circular(14),
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ onTap: () => _openEbookReader(context, auth, ebookFile, title),
+ child: Stack(children: [
+ if (showFill)
+ FractionallySizedBox(
+ widthFactor: ebookProgress.clamp(0.0, 1.0),
+ child: Container(color: accent.withValues(alpha: 0.22)),
+ ),
+ Center(
+ child: Row(mainAxisSize: MainAxisSize.min, children: [
+ Icon(Icons.menu_book_rounded, size: 18, color: accent),
+ const SizedBox(width: 8),
+ Text(l.readEbook,
+ style: tt.labelLarge?.copyWith(fontWeight: FontWeight.w600, color: accent)),
+ ]),
+ ),
+ if (showFill)
+ Positioned(
+ right: 14,
+ top: 0,
+ bottom: 0,
+ child: Center(
+ child: Text(
+ '${(ebookProgress * 100).toStringAsFixed(0)}%',
+ style: tt.labelSmall?.copyWith(
+ fontWeight: FontWeight.w700,
+ color: accent.withValues(alpha: 0.85),
+ ),
+ ),
+ ),
+ ),
+ ]),
+ ),
+ ),
+ );
+ }),
+ ],
+ // Primary action row: Download | Fully Absorb | ebook download (ebook-only)
const SizedBox(height: 12),
Row(children: [
- if (!isEbookOnly) ...[
+ if (AppPlatform.isWeb && auth.canDownload) ...[
+ Expanded(child: _webDownloadButton(context, cs, l, auth)),
+ const SizedBox(width: 8),
+ ],
+ if (!isEbookOnly && !AppPlatform.isWeb) ...[
Expanded(child: DownloadWideButton(itemId: widget.itemId, coverUrl: _coverUrl, title: title, author: authorName, accent: accent)),
const SizedBox(width: 8),
],
@@@ -794,7 -1061,7 +1079,7 @@@
]),
),
)),
- if (!AppPlatform.isWeb && ebookFile != null && canReadEbook(ebookFile)) ...[
- if (isEbookOnly && ebookFile != null && canReadEbook(ebookFile)) ...[
++ if (!AppPlatform.isWeb && isEbookOnly && ebookFile != null && canReadEbook(ebookFile)) ...[
const SizedBox(width: 8),
// For ebook-only books the big button above is already "Read", so this
// slot is the offline download (matching the audiobook download
@@@ -1134,11 -1354,9 +1432,11 @@@
// Primary actions: Absorb | Download side by side
if (!isEbookOnly)
Row(children: [
- Expanded(child: _quickAbsorbButton(context, cs, tt, auth, accent, onAccent, title, authorName, duration, chapters, isFinished)),
+ Expanded(child: _quickAbsorbButton(context, cs, tt, auth, accent, onAccent, title, authorName, duration, chapters, isFinished, progress)),
- const SizedBox(width: 10),
- Expanded(child: DownloadWideButton(itemId: widget.itemId, coverUrl: _coverUrl, title: title, author: authorName, accent: accent)),
+ if (!AppPlatform.isWeb) ...[
+ const SizedBox(width: 10),
+ Expanded(child: DownloadWideButton(itemId: widget.itemId, coverUrl: _coverUrl, title: title, author: authorName, accent: accent)),
+ ],
])
else
SizedBox(height: 44, child: Center(child: Text(l.ebookOnlyNoAudio,
@@@ -1758,20 -1989,34 +2091,48 @@@
);
}
+ Future<void> _launchAudibleReviews(BuildContext context, Uri uri) async {
+ var opened = false;
+ try {
+ opened = await launchUrl(uri, webOnlyWindowName: '_blank');
+ } catch (_) {}
+ if (!opened && context.mounted) {
+ showOverlayToast(
+ context,
+ AppLocalizations.of(context)!.audibleSeriesCouldNotOpenAudible,
+ icon: Icons.error_outline_rounded,
+ );
+ }
+ }
+
+ // The name and its comma are one Wrap child so the comma can never start
+ // the next line. Padding makes the tap target the full line height, not
+ // just the glyphs, so a thumb between two stacked links lands on one.
+ Widget _nameLink(String name, TextStyle? linkStyle, TextStyle? commaStyle,
+ {required bool comma, required VoidCallback onTap}) {
+ return Row(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.end,
+ children: [
+ Flexible(
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onTap,
+ child: Padding(
+ padding: EdgeInsets.fromLTRB(2, 6, comma ? 0 : 2, 6),
+ child: Text(name, style: linkStyle),
+ ),
+ ),
+ ),
+ if (comma)
+ Padding(
+ padding: const EdgeInsets.symmetric(vertical: 6),
+ child: Text(', ', style: commaStyle),
+ ),
+ ],
+ );
+ }
+
Widget _buildAuthorLinks(BuildContext context, Map<String, dynamic> metadata, ColorScheme cs, TextTheme tt, Color accent) {
final authors = metadata['authors'] as List<dynamic>? ?? [];
// Fall back to authorName string if no structured authors array
diff --cc lib/widgets/bookmark_detail_dialog.dart
index d78ce0fc,45013149..5e3444b8
--- a/lib/widgets/bookmark_detail_dialog.dart
+++ b/lib/widgets/bookmark_detail_dialog.dart
@@@ -7,11 -11,16 +11,18 @@@ import '../services/api_service.dart'
import '../services/audio_player_service.dart';
import '../services/bookmark_service.dart';
import '../services/bookmark_preview_player.dart';
+ import '../services/chapter_lookup.dart';
import '../services/download_service.dart';
+import '../utils/app_platform.dart';
+import 'adaptive_modal.dart';
+ import '../services/ebook_cache.dart';
+ import '../services/transcription_service.dart';
+ import '../utils/episode_key.dart';
+ import '../utils/passage_match.dart';
import 'clip_editor_sheet.dart';
import 'overlay_toast.dart';
+ import 'progress_dialog.dart';
+ import 'quote_share_sheet.dart';
/// Result of [BookmarkDetailSheet]. [action] is 'jump' (caller should seek
/// there) or 'saved' (stay put, refresh). [position] is the possibly-nudged
@@@ -123,7 -169,7 +171,7 @@@ class _BookmarkDetailSheetState extend
// iOS can't export from a streaming book, so prompt to download up front
// rather than letting the user trim a clip and only fail at Save. Android
// exports streamed clips fine, so it always opens the editor.
- if (AppPlatform.isIOS && !DownloadService().isDownloaded(widget.itemId)) {
- if (Platform.isIOS && !DownloadService().isDownloaded(widget._key)) {
++ if (AppPlatform.isIOS && !DownloadService().isDownloaded(widget._key)) {
await _promptDownload();
return;
}
@@@ -308,17 -623,35 +626,37 @@@
),
),
const SizedBox(height: 8),
- SizedBox(
- width: double.infinity,
- child: OutlinedButton.icon(
- icon: const Icon(Icons.content_cut_rounded, size: 18),
- label: Text(l.clipExport),
- onPressed: _saving ? null : _openClipEditor,
+ if (!AppPlatform.isWeb) ...[
+ SizedBox(
+ width: double.infinity,
+ child: OutlinedButton.icon(
+ icon: const Icon(Icons.content_cut_rounded, size: 18),
+ label: Text(l.clipExport),
+ onPressed: _saving ? null : _openClipEditor,
+ ),
),
- const SizedBox(height: 16),
- ),
+ ],
+ if (_transcriptionOn) ...[
+ const SizedBox(height: 8),
+ SizedBox(
+ width: double.infinity,
+ child: OutlinedButton.icon(
+ icon: const Icon(Icons.record_voice_over_rounded, size: 18),
+ label: Text(l.transcribe),
+ onPressed: _saving ? null : _transcribe,
+ ),
+ ),
+ ],
+ const SizedBox(height: 8),
+ SizedBox(
+ width: double.infinity,
+ child: OutlinedButton.icon(
+ icon: const Icon(Icons.ios_share_rounded, size: 18),
+ label: Text(l.quoteShareTitle),
+ onPressed: _saving || _noteC.text.trim().isEmpty ? null : _shareNote,
+ ),
+ ),
+ const SizedBox(height: 16),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
diff --cc lib/widgets/card_buttons.dart
index 456ee345,fdbe9e15..fa6a62c2
--- a/lib/widgets/card_buttons.dart
+++ b/lib/widgets/card_buttons.dart
@@@ -17,9 -19,9 +19,10 @@@ import '../services/equalizer_service.d
import '../services/playback_history_service.dart';
import '../services/scoped_prefs.dart';
import '../services/sleep_timer_service.dart';
+ import '../utils/episode_key.dart';
import 'absorb_slider.dart';
import 'absorbing_shared.dart';
+import 'adaptive_modal.dart';
import 'book_detail_sheet.dart';
import 'bookmark_detail_dialog.dart';
import 'card_button_config.dart';
@@@ -497,10 -538,12 +539,10 @@@ class _CardBookmarkButtonInlineState ex
}
void _showBookmarks(BuildContext context) {
- showModalBottomSheet(
- context: context, backgroundColor: Colors.transparent, isScrollControlled: true, useSafeArea: true,
- builder: (ctx) => DraggableScrollableSheet(
- initialChildSize: 0.6, minChildSize: 0.05, snap: true, maxChildSize: 0.9, expand: false,
- builder: (ctx, sc) => SimpleBookmarkSheet(itemId: widget.itemId, episodeId: widget.episodeId, player: widget.player, accent: widget.accent, scrollController: sc, onChanged: _loadCount),
- ),
+ showAdaptiveSheetDialog(
+ context: context, widthClass: DialogWidthClass.action, backgroundColor: Colors.transparent, useSafeArea: true,
+ initialChildSize: 0.6, minChildSize: 0.05, snap: true, maxChildSize: 0.9, expand: false,
- builder: (ctx, sc) => SimpleBookmarkSheet(itemId: widget.itemId, player: widget.player, accent: widget.accent, scrollController: sc, onChanged: _loadCount),
++ builder: (ctx, sc) => SimpleBookmarkSheet(itemId: widget.itemId, episodeId: widget.episodeId, player: widget.player, accent: widget.accent, scrollController: sc, onChanged: _loadCount),
);
}
}
@@@ -1759,9 -1950,11 +1988,9 @@@ class CardActionDelegate
enabled: isPlaybackActive,
onTap: () {
Navigator.pop(ctx);
- showModalBottomSheet(context: context, backgroundColor: Colors.transparent, isScrollControlled: true, useSafeArea: true,
- builder: (_) => DraggableScrollableSheet(
- initialChildSize: 0.6, minChildSize: 0.05, snap: true, maxChildSize: 0.9, expand: false,
- builder: (_, sc) => SimpleBookmarkSheet(itemId: itemId, episodeId: _bookmarkEpisodeId, player: player, accent: accent, scrollController: sc, onChanged: () {}),
- ),
+ showAdaptiveSheetDialog(context: context, widthClass: DialogWidthClass.action, backgroundColor: Colors.transparent, useSafeArea: true,
+ initialChildSize: 0.6, minChildSize: 0.05, snap: true, maxChildSize: 0.9, expand: false,
- builder: (_, sc) => SimpleBookmarkSheet(itemId: itemId, player: player, accent: accent, scrollController: sc, onChanged: () {}),
++ builder: (_, sc) => SimpleBookmarkSheet(itemId: itemId, episodeId: _bookmarkEpisodeId, player: player, accent: accent, scrollController: sc, onChanged: () {}),
);
},
);
diff --cc lib/widgets/card_progress_bar.dart
index 5871b572,23b5b930..0f8a66a7
--- a/lib/widgets/card_progress_bar.dart
+++ b/lib/widgets/card_progress_bar.dart
@@@ -23,8 -23,11 +23,13 @@@ class CardDualProgressBar extends State
final int totalChapters;
final String? itemId;
final bool compact;
++ /// Show the book percentage (desktop now playing pane) in the time row.
+ final bool showBookPercentage;
- const CardDualProgressBar({super.key, required this.player, required this.accent, required this.isActive, required this.staticProgress, required this.staticDuration, required this.chapters, this.showBookBar = true, this.showChapterBar = true, this.chapterName, this.chapterIndex = 0, this.totalChapters = 0, this.itemId, this.compact = false, this.showBookPercentage = false});
+ /// Render the book percentage centered in the book bar's own time row
+ /// (between elapsed and remaining) instead of the caller stacking a
+ /// separate percent line above - saves a row on the full screen player.
+ final bool showCenterPercent;
- const CardDualProgressBar({super.key, required this.player, required this.accent, required this.isActive, required this.staticProgress, required this.staticDuration, required this.chapters, this.showBookBar = true, this.showChapterBar = true, this.chapterName, this.chapterIndex = 0, this.totalChapters = 0, this.itemId, this.compact = false, this.showCenterPercent = false});
++ const CardDualProgressBar({super.key, required this.player, required this.accent, required this.isActive, required this.staticProgress, required this.staticDuration, required this.chapters, this.showBookBar = true, this.showChapterBar = true, this.chapterName, this.chapterIndex = 0, this.totalChapters = 0, this.itemId, this.compact = false, this.showBookPercentage = false, this.showCenterPercent = false});
@override State<CardDualProgressBar> createState() => _CardDualProgressBarState();
}
@@@ -365,30 -357,30 +370,36 @@@ class _CardDualProgressBarState extend
child: CustomPaint(size: Size(w, 32), painter: AbsorbProgressPainter(progress: p, accent: widget.accent.withValues(alpha: 0.5), isDragging: _bookDragValue != null)),
);
})),
- Padding(
- padding: const EdgeInsets.only(top: 2, bottom: 6),
- child: Stack(
- alignment: Alignment.center,
- children: [
- Row(
- children: [
- Text(_fmt(_bookDragValue != null ? _bookDragValue! * totalDur / speedDiv : bookElapsed), style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? cs.onSurface.withValues(alpha: 0.7) : cs.onSurfaceVariant, fontSize: 12 * _progressTextScale, fontWeight: FontWeight.w600, shadows: [Shadow(color: Theme.of(context).brightness == Brightness.dark ? Colors.black.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.5), blurRadius: 3)])),
- const Spacer(),
- Text('-${_fmt(_bookDragValue != null ? (1.0 - _bookDragValue!) * totalDur / speedDiv : bookRemaining)}', style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? cs.onSurface.withValues(alpha: 0.7) : cs.onSurfaceVariant, fontSize: 12 * _progressTextScale, fontWeight: FontWeight.w600, shadows: [Shadow(color: Theme.of(context).brightness == Brightness.dark ? Colors.black.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.5), blurRadius: 3)])),
- ],
- ),
- if (_bookDragValue != null && _bookScrubSpeed < 1.0)
- Text(_scrubSpeedLabel(l, _bookScrubSpeed), style: tt.labelSmall?.copyWith(color: widget.accent, fontSize: 11, fontWeight: FontWeight.w500))
- else if (widget.showBookPercentage)
- Text(
- bookPercentageLabel,
- key: const ValueKey('desktop-current-percent'),
- style: bookPercentageStyle,
- ),
- ],
- ),
- ),
+ Padding(padding: const EdgeInsets.only(top: 2, bottom: 6), child: Stack(
+ alignment: Alignment.center,
+ children: [
+ Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Text(_fmt(_bookDragValue != null ? _bookDragValue! * totalDur / speedDiv : bookElapsed), style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? cs.onSurface.withValues(alpha: 0.7) : cs.onSurfaceVariant, fontSize: 12 * _progressTextScale, fontWeight: FontWeight.w600, shadows: [Shadow(color: Theme.of(context).brightness == Brightness.dark ? Colors.black.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.5), blurRadius: 3)])),
+ Text('-${_fmt(_bookDragValue != null ? (1.0 - _bookDragValue!) * totalDur / speedDiv : bookRemaining)}', style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? cs.onSurface.withValues(alpha: 0.7) : cs.onSurfaceVariant, fontSize: 12 * _progressTextScale, fontWeight: FontWeight.w600, shadows: [Shadow(color: Theme.of(context).brightness == Brightness.dark ? Colors.black.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.5), blurRadius: 3)])),
+ ],
+ ),
+ if (_bookDragValue != null && _bookScrubSpeed < 1.0)
+ Text(_scrubSpeedLabel(l, _bookScrubSpeed), style: tt.labelSmall?.copyWith(color: widget.accent, fontSize: 11, fontWeight: FontWeight.w500))
++ else if (widget.showBookPercentage)
++ Text(
++ bookPercentageLabel,
++ key: const ValueKey('desktop-current-percent'),
++ style: bookPercentageStyle,
++ )
+ else if (widget.showCenterPercent)
+ Text('${(( _bookDragValue ?? bookProgress) * 100).clamp(0, 100).toStringAsFixed(1)}%', style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant, fontSize: 12 * _progressTextScale, fontWeight: FontWeight.w600, shadows: [Shadow(color: Theme.of(context).brightness == Brightness.dark ? Colors.black.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.5), blurRadius: 3)])),
+ ],
+ )),
] else ...[
+ // No book seeking: the caller relying on showCenterPercent has
+ // dropped its own percent line, so render one here instead.
+ if (widget.showCenterPercent)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 2),
+ child: Text('${(bookProgress * 100).clamp(0, 100).toStringAsFixed(1)}%', style: tt.labelSmall?.copyWith(color: cs.onSurfaceVariant, fontSize: 11 * _progressTextScale, fontWeight: FontWeight.w500, shadows: [Shadow(color: Theme.of(context).brightness == Brightness.dark ? Colors.black.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.5), blurRadius: 3)])),
+ ),
Row(children: [
Text(_fmt(_bookDragValue != null ? _bookDragValue! * totalDur / speedDiv : bookElapsed), style: tt.labelSmall?.copyWith(color: _bookDragValue != null ? cs.onSurface.withValues(alpha: 0.6) : cs.onSurface.withValues(alpha: 0.5), fontSize: 11 * _progressTextScale, fontWeight: FontWeight.w500, shadows: [Shadow(color: Theme.of(context).brightness == Brightness.dark ? Colors.black.withValues(alpha: 0.5) : Colors.white.withValues(alpha: 0.5), blurRadius: 3)])),
const SizedBox(width: 8),
diff --cc lib/widgets/ebook_reader_view.dart
index b9d6d586,163e5d70..00ec30a3
--- a/lib/widgets/ebook_reader_view.dart
+++ b/lib/widgets/ebook_reader_view.dart
@@@ -15,10 -24,23 +24,24 @@@ import '../services/find_in_ebook.dart'
import '../services/progress_sync_service.dart';
import '../services/reader_font_service.dart';
import '../services/scoped_prefs.dart';
+ import '../services/lyrics_service.dart';
+ import '../services/read_along_script.dart';
+ import '../services/screen_wake.dart';
+ import '../services/sync_point_store.dart';
+ import '../services/transcript_line_store.dart';
+ import '../services/transcription_service.dart';
import '../services/volume_key_service.dart';
+import 'adaptive_modal.dart';
import 'overlay_toast.dart';
- import 'card_buttons.dart' show CardSpeedSheet;
+ import 'transcription_download_prompt.dart';
+ import 'progress_dialog.dart';
+ import 'quote_share_sheet.dart';
+ import 'book_detail_sheet.dart';
+ import 'card_buttons.dart' show CardSpeedSheet, MoreMenuItem, SimpleBookmarkSheet;
+ import 'card_chapters_sheet.dart';
+ import 'chromecast_button.dart';
+ import 'equalizer_sheet.dart';
+ import 'sleep_timer_sheet.dart';
/// Reader background/text presets (e-reader themes). Colors are hex so they
/// feed both the WebView CSS and the Flutter overlays.
@@@ -936,7 -1477,9 +1479,9 @@@ class EbookReaderViewState extends Stat
// Live preview for the side-margin slider so the WebView only re-paginates
// when the drag ends, not on every step.
int hPreview = _marginH;
+ var sheetRaMode = LyricsService.instance.readAlongMode;
+ var sheetRaColor = LyricsService.instance.readAlongColor;
- showModalBottomSheet(
+ showAdaptiveActionMenu(
context: context,
backgroundColor: cs.surface,
shape: const RoundedRectangleBorder(
@@@ -1550,21 -2340,2340 +2344,2341 @@@
}
}
- void _showAnnotationsSheet() {
- final cs = Theme.of(context).colorScheme;
- final tt = Theme.of(context).textTheme;
- final highlights = _annotations.where((a) => a.type == AnnotationType.highlight).toList();
- final bookmarks = _annotations.where((a) => a.type == AnnotationType.bookmark).toList();
+ /// Fuzzy-search the book for the transcript and apply the confidence rules.
+ /// Returns {href, excerpt} for a trustworthy hit, null when not confident.
+ Future<Map<String, dynamic>?> _decideFindTarget(
+ String transcript, String? chapterHint,
+ {double? nearSeconds}) async {
+ // Whisper sometimes emits bracketed non-speech tags; they'd poison matching.
+ final cleaned = transcript
+ .replaceAll(RegExp(r'\[[^\]]*\]|\([^)]*\)'), ' ')
+ .replaceAll(RegExp(r'\s+'), ' ')
+ .trim();
+ if (cleaned.split(' ').length < 3) {
+ debugPrint('[FindEbook] transcript too short after cleaning: "$cleaned"');
+ return null;
+ }
- showAdaptiveActionMenu(
- context: context,
- backgroundColor: cs.surface,
- isScrollControlled: true,
- shape: const RoundedRectangleBorder(
- borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
- ),
+ // Spine sections whose TOC chapter agrees with the audio chapter get
+ // searched first (and an early exit on a strong hit there).
+ // Sections that earlier finds or read along pinned near this time come
+ // before the chapter-title guess: they are known, the title is inferred.
+ final hintBases = <String>[];
+ if (nearSeconds != null) hintBases.addAll(await _syncHintBases(nearSeconds));
+ if (chapterHint != null) {
+ for (final ch in _chapters) {
+ if (_chapterTitlesAgree(chapterHint, ch.title)) {
+ final base = ch.href.split('#').first.split('/').last.toLowerCase();
+ if (base.isNotEmpty && !hintBases.contains(base)) hintBases.add(base);
+ }
+ }
+ }
+ debugPrint('[FindEbook] query="$cleaned" hintBases=$hintBases');
+
+ final raw = await _fuzzyFindPassage(cleaned, hintBases);
+ if (raw == null) return null;
+ final best = raw['best'] as Map<String, dynamic>?;
+ final second = raw['second'] as Map<String, dynamic>?;
+ if (best == null) {
+ debugPrint('[FindEbook] no candidates');
+ return null;
+ }
+
+ double scoreOf(Map<String, dynamic> c) {
+ final fine = (c['fine'] as num?)?.toDouble() ?? 0;
+ final agrees = chapterHint != null &&
+ _chapterTitlesAgree(chapterHint, _chapterForHref(c['href'] as String? ?? '') ?? '');
+ return fine + (agrees ? _findHintBonus : 0);
+ }
+
+ final bestFine = (best['fine'] as num?)?.toDouble() ?? 0;
+ final bestScore = scoreOf(best);
+ double? secondScore;
+ var sameSpot = false;
+ if (second != null) {
+ secondScore = scoreOf(second);
+ final bestStart = (best['s'] as num?)?.toDouble() ?? 0;
+ final secondStart = (second['s'] as num?)?.toDouble() ?? 0;
+ sameSpot =
+ second['idx'] == best['idx'] && (secondStart - bestStart).abs() < 200;
+ }
+ final margin = secondScore == null || sameSpot || bestScore - secondScore >= _findMargin;
+ final confident =
+ bestFine >= _findFineFloor && bestScore >= _findAcceptScore && margin;
+ debugPrint('[FindEbook] best fine=${bestFine.toStringAsFixed(3)} '
+ 'score=${bestScore.toStringAsFixed(3)} href=${best['href']} '
+ 'chapter=${_chapterForHref(best['href'] as String? ?? '')} '
+ 'second=${secondScore?.toStringAsFixed(3)} sameSpot=$sameSpot '
+ 'confident=$confident excerpt="${best['excerpt']}"');
+ if (!confident) return null;
+ return {
+ 'href': best['href'] as String? ?? '',
+ 'excerpt': best['excerpt'] as String? ?? '',
+ 'idx': best['idx'],
+ 's': best['s'],
+ 'e': best['e'],
+ };
+ }
+
+ /// Spine sections holding sync points recorded within ten minutes of
+ /// [seconds], nearest first - the sections a transcript from around that
+ /// time almost certainly lives in.
+ Future<List<String>> _syncHintBases(double seconds) async {
+ final pts = await SyncPointStore.instance.load(widget.itemId);
+ if (pts.isEmpty) return const [];
+ final near = pts.where((p) => (p.t - seconds).abs() <= 600).toList()
+ ..sort((a, b) => (a.t - seconds).abs().compareTo((b.t - seconds).abs()));
+ if (near.isEmpty) return const [];
+ final hrefs = await _spineHrefs();
+ final out = <String>[];
+ for (final p in near) {
+ if (p.si < 0 || p.si >= hrefs.length) continue;
+ final base = hrefs[p.si].split('#').first.split('/').last.toLowerCase();
+ if (base.isNotEmpty && !out.contains(base)) out.add(base);
+ if (out.length >= 3) break;
+ }
+ return out;
+ }
+
+ /// A confirmed hit from a transcript taken at [seconds] becomes a sync
+ /// point at [off] characters into section [idx]; [err] is how far the
+ /// transcript window could put the words from [seconds].
+ Future<void> _rememberEbookHit(
+ Map<String, dynamic> decision, double seconds, double off, double err) async {
+ final idx = decision['idx'];
+ if (idx is! num || seconds < 0) return;
+ final hrefs = await _spineHrefs();
+ await SyncPointStore.instance.add(
+ widget.itemId,
+ SyncPoint(t: seconds, si: idx.toInt(), off: off, src: 'e', err: err),
+ spineLength: hrefs.isEmpty ? null : hrefs.length,
+ );
+ }
+
+ /// True when an audio chapter title and a TOC chapter title plausibly name
+ /// the same chapter: equal, one's words are a subset of the other's, or they
+ /// share a number. Word-level, not substring - raw containment would make
+ /// "Chapter 1" match "Chapter 10". Spelled-out numbers normalize to digits
+ /// first, so "Chapter Nine" can't claim "Chapter Thirty-Nine" via word
+ /// subset (the hyphen splits it into two words), and "Chapter 39" matches
+ /// "Chapter Thirty-Nine" like it should.
+ bool _chapterTitlesAgree(String? audio, String? toc) {
+ if (audio == null || toc == null) return false;
+ final a = _chapterTitleWords(audio), t = _chapterTitleWords(toc);
+ if (a.isEmpty || t.isEmpty) return false;
+ if (a.containsAll(t) || t.containsAll(a)) return true;
+ final an = a.where((w) => RegExp(r'^\d+$').hasMatch(w)).toSet();
+ final tn = t.where((w) => RegExp(r'^\d+$').hasMatch(w)).toSet();
+ return an.isNotEmpty && an.intersection(tn).isNotEmpty;
+ }
+
+ static const _numberUnits = {
+ 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6,
+ 'seven': 7, 'eight': 8, 'nine': 9, 'ten': 10, 'eleven': 11, 'twelve': 12,
+ 'thirteen': 13, 'fourteen': 14, 'fifteen': 15, 'sixteen': 16,
+ 'seventeen': 17, 'eighteen': 18, 'nineteen': 19,
+ };
+ static const _numberTens = {
+ 'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50, 'sixty': 60,
+ 'seventy': 70, 'eighty': 80, 'ninety': 90,
+ };
+
+ /// Title words with spelled-out numbers collapsed to digit tokens
+ /// ("thirty nine" -> "39", "nine" -> "9").
+ Set<String> _chapterTitleWords(String s) {
+ final raw = s
+ .toLowerCase()
+ .replaceAll(RegExp(r'[^\p{L}\p{N} ]+', unicode: true), ' ')
+ .split(RegExp(r'\s+'))
+ .where((w) => w.isNotEmpty)
+ .toList();
+ final out = <String>{};
+ for (var i = 0; i < raw.length; i++) {
+ final w = raw[i];
+ final tens = _numberTens[w];
+ if (tens != null) {
+ final unit = i + 1 < raw.length ? _numberUnits[raw[i + 1]] : null;
+ if (unit != null && unit < 10) {
+ out.add('${tens + unit}');
+ i++;
+ } else {
+ out.add('$tens');
+ }
+ continue;
+ }
+ final unit = _numberUnits[w];
+ out.add(unit != null ? '$unit' : w);
+ }
+ return out;
+ }
+
+ /// Fuzzy passage search over the separate search Book (same instance the
+ /// exact search uses - never the live book, that wedges page turns). Token
+ /// bag-of-words narrows candidate windows cheaply, then character-level
+ /// Levenshtein on the normalized window ranks them. Returns the two best
+ /// candidates across the book, hinted sections first with early exit.
+ Future<Map<String, dynamic>?> _fuzzyFindPassage(
+ String transcript, List<String> hintBases) async {
+ final wc = _epubController?.webViewController;
+ if (wc == null) return null;
+ final res = await wc.callAsyncJavaScript(
+ functionBody: r'''
+ var sb = window.__absorbSearchBook;
+ if (!sb) {
+ sb = ePub();
+ sb.spine.unpack(book.packaging, book.resolve.bind(book), book.canonical.bind(book));
+ window.__absorbSearchBook = sb;
+ }
+ function toks(s){ return (s.toLowerCase().match(/[\p{L}\p{N}']+/gu) || []); }
+ function base(h){ return (h||'').split('#')[0].split('/').pop().toLowerCase(); }
+ function lev(a,b){
+ var m=a.length,n=b.length; if(!m)return n; if(!n)return m;
+ var prev=new Array(n+1), cur=new Array(n+1), i, j, tmp;
+ for(j=0;j<=n;j++)prev[j]=j;
+ for(i=1;i<=m;i++){ cur[0]=i; var ca=a.charCodeAt(i-1);
+ for(j=1;j<=n;j++){ var cost=(ca===b.charCodeAt(j-1))?0:1;
+ cur[j]=Math.min(prev[j]+1, cur[j-1]+1, prev[j-1]+cost); }
+ tmp=prev; prev=cur; cur=tmp; }
+ return prev[n];
+ }
+ var T = toks(transcript);
+ if (T.length < 3) return JSON.stringify({err:'short'});
+ var need = {}; T.forEach(function(t){ need[t]=(need[t]||0)+1; });
+ var tNorm = T.join(' ');
+ var W = T.length;
+ var items = (sb.spine && sb.spine.spineItems) ? sb.spine.spineItems : [];
+ var order = [], i;
+ for (i=0;i<items.length;i++){ if (hints.indexOf(base(items[i].href))!==-1) order.push(i); }
+ for (i=0;i<items.length;i++){ if (order.indexOf(i)===-1) order.push(i); }
+ var best=null, second=null;
+ function offer(c){
+ if (!best || c.fine > best.fine){ second = best; best = c; }
+ else if (!second || c.fine > second.fine){ second = c; }
+ }
+ for (var oi=0; oi<order.length; oi++){
+ var idx=order[oi], item=items[idx], text='';
+ try {
+ await item.load(book.load.bind(book));
+ var d=item.document;
+ text = d ? ((d.body && d.body.textContent) || (d.documentElement && d.documentElement.textContent) || '') : '';
+ } catch(e){ text=''; }
+ finally { try { item.unload(); } catch(e2){} }
+ if (!text) continue;
+ var st=[], re=/[\p{L}\p{N}']+/gu, mm;
+ while((mm=re.exec(text))!==null){ st.push({t:mm[0].toLowerCase(), s:mm.index, e:mm.index+mm[0].length}); }
+ if (st.length < 3) continue;
+ var have={}, matched=0, cands=[], p;
+ for (p=0;p<st.length;p++){
+ var tk=st[p].t; have[tk]=(have[tk]||0)+1; if (have[tk] <= (need[tk]||0)) matched++;
+ if (p>=W){ var old=st[p-W].t; if (have[old] <= (need[old]||0)) matched--; have[old]--; }
+ if (matched >= Math.max(2, Math.floor(W*0.4))) cands.push({i:Math.max(0,p-W+1), m:matched});
+ }
+ cands.sort(function(a,b){ return b.m-a.m; });
+ var used=[], picked=[];
+ for (var c=0;c<cands.length && picked.length<4;c++){
+ var s0=cands[c].i, ok=true;
+ for (var u=0;u<used.length;u++){ if (Math.abs(used[u]-s0) < W) { ok=false; break; } }
+ if (ok){ picked.push(cands[c]); used.push(s0); }
+ }
+ for (var pc=0;pc<picked.length;pc++){
+ var s1=picked[pc].i, e1=Math.min(st.length-1, s1+W-1);
+ var winNorm = st.slice(s1,e1+1).map(function(x){return x.t;}).join(' ');
+ var dl = lev(tNorm, winNorm);
+ var fine = 1 - dl/Math.max(tNorm.length, winNorm.length);
+ offer({ href:item.href||'', idx:idx, s:st[s1].s, e:st[e1].e,
+ fine:fine, coarse:picked[pc].m/W,
+ excerpt:text.substring(st[s1].s, st[e1].e) });
+ }
+ // A strong hit inside a hinted section is trustworthy enough to stop.
+ if (best && best.fine >= 0.85 && hints.indexOf(base(item.href))!==-1) break;
+ }
+ return JSON.stringify({best:best, second:second, tokens:W});
+ ''',
+ arguments: {'transcript': transcript, 'hints': hintBases},
+ ).timeout(const Duration(seconds: 90), onTimeout: () => null);
+ final raw = res?.value;
+ if (raw is! String || raw.isEmpty) return null;
+ try {
+ return jsonDecode(raw) as Map<String, dynamic>;
+ } catch (_) {
+ return null;
+ }
+ }
+
+ /// Displays the hit's section, re-finds the matched excerpt in the LIVE
+ /// rendered DOM (whitespace-normalized - the search doc is parsed as XML and
+ /// whitespace differs), rebuilds the range there and lands on its CFI with
+ /// the search flash. Restores the previous position when the re-find fails,
+ /// so a bad anchor never strands the user at a chapter start.
+ Future<bool> _jumpToFindHit(String href, String excerpt,
+ {bool flash = true}) async {
+ final wc = _epubController?.webViewController;
+ if (wc == null || href.isEmpty || excerpt.trim().isEmpty) return false;
+ // A hit that runs across several paragraphs gives epub.js a range it
+ // displays ten pages short of (seen with a 12s read along window). The
+ // first paragraph on its own lands on the right page.
+ var anchor = excerpt;
+ for (final part in excerpt.split('\n')) {
+ final t = part.trim();
+ if (t.split(RegExp(r'\s+')).length >= 4) {
+ anchor = t;
+ break;
+ }
+ }
+ if (anchor != excerpt) {
+ debugPrint('[FindEbook] anchoring on the first paragraph of the hit: '
+ '"${anchor.length > 60 ? anchor.substring(0, 60) : anchor}..."');
+ excerpt = anchor;
+ }
+ final res = await wc.callAsyncJavaScript(
+ functionBody: r'''
+ var dbg = { matched: false };
+ var backCfi = null;
+ try {
+ try { var loc = rendition.currentLocation(); backCfi = loc && loc.start ? loc.start.cfi : null; } catch(e0){}
+ await rendition.display(href);
+ var target=null; try { target = book.spine.get(href); } catch(e1){}
+ var si = target ? target.index : -1;
+ var contents = (typeof rendition.getContents === 'function') ? rendition.getContents() : [];
+ var c=null;
+ for (var i=0;i<contents.length;i++){ if (si<0 || contents[i].sectionIndex===si){ c=contents[i]; break; } }
+ if (!c) c = contents[0];
+ var doc = c && c.document;
+ if (doc) {
+ var tw = doc.createTreeWalker(doc.body||doc, NodeFilter.SHOW_TEXT, null, false);
+ var nodes=[], raw='', node;
+ while (node = tw.nextNode()) { nodes.push({node:node, start:raw.length, len:node.textContent.length}); raw += node.textContent; }
+ var lower = raw.toLowerCase();
+ var normChars=[], map=[], prevSpace=true;
+ for (var k=0;k<lower.length;k++){
+ var ch=lower[k];
+ if (/\s/.test(ch)) { if (!prevSpace){ normChars.push(' '); map.push(k); } prevSpace=true; }
+ else { normChars.push(ch); map.push(k); prevSpace=false; }
+ }
+ var hay = normChars.join('');
+ var needle = excerpt.toLowerCase().replace(/\s+/g,' ').trim();
+ var pos = hay.indexOf(needle);
+ dbg.pos = pos; dbg.hayLen = hay.length;
+ if (pos !== -1 && nodes.length) {
+ var rawStart = map[pos], rawEnd = map[pos + needle.length - 1] + 1;
+ var locate = function(off){
+ for (var q=0;q<nodes.length;q++){ var e2=nodes[q]; if (off < e2.start + e2.len) return {node:e2.node, offset:off - e2.start}; }
+ var last = nodes[nodes.length-1]; return {node:last.node, offset:last.len};
+ };
+ var sp = locate(rawStart), ep = locate(rawEnd);
+ var r = doc.createRange();
+ r.setStart(sp.node, sp.offset); r.setEnd(ep.node, ep.offset);
+ var liveCfi = c.cfiFromRange(r);
+ if (liveCfi) { dbg.matched = true; dbg.cfi = liveCfi; await rendition.display(liveCfi); }
+ }
+ }
+ if (!dbg.matched && backCfi) { try { await rendition.display(backCfi); } catch(e3){} }
+ } catch(e){ dbg.err = String(e); if (backCfi) { try { await rendition.display(backCfi); } catch(e4){} } }
+ return JSON.stringify(dbg);
+ ''',
+ arguments: {'href': href, 'excerpt': excerpt},
+ ).timeout(const Duration(seconds: 30), onTimeout: () => null);
+ final raw = res?.value;
+ debugPrint('[FindEbook] anchor $raw');
+ if (raw is! String) return false;
+ try {
+ final d = jsonDecode(raw) as Map<String, dynamic>;
+ if (d['matched'] == true && d['cfi'] is String) {
+ if (flash) _highlightSearchHit(d['cfi'] as String);
+ return true;
+ }
+ } catch (_) {}
+ return false;
+ }
+
+ // Find in audiobook: how much audio each probe transcribes, how many
+ // estimate-correct-retry rounds the main anchor gets, and the ceiling once
+ // the fallback candidates (player position, book percentage, neighbouring
+ // chapters) have taken two rounds each. A probe is roughly ten seconds.
+ static const double _probeWindowSeconds = 30.0;
+ static const int _maxProbes = 5;
+ static const int _maxTotalProbes = 12;
+ // Narration pace measured on real books: ~0.07-0.08 s per character. Used
+ // when no audio chapter anchors the estimate, and to reject absurd
+ // chapter-derived rates (3-second "chapters" exist in the wild).
+ static const double _fallbackSecPerChar = 0.075;
+ // How far a failed probe shifts the search around the original estimate,
+ // at minimum; a long section widens it so the probes spread across it.
+ static const double _scanStepSeconds = 90.0;
+
+ /// Reverse of Find in ebook: locate the selected text in the audio and start
+ /// listening there. Estimate from the audio chapter and how far through the
+ /// section's text the selection sits, then verify by transcribing a probe
+ /// window and fuzzy-matching it back into this section - the miss distance
+ /// in characters converts to seconds and corrects the estimate.
+ /// [cfiOverride]/[textOverride] let an existing highlight reuse this flow
+ /// without a live selection.
+ Future<void> _findInAudiobookFromSelection(
+ {String? cfiOverride, String? textOverride}) async {
+ final l = AppLocalizations.of(context)!;
+ final cfi = cfiOverride ?? _selectionCfi;
+ final selText = textOverride ?? _selectionText ?? '';
+ _dismissSelection();
+ if (cfi == null) return;
+ if (!TranscriptionService.instance.canTranscribeBook(widget.itemId)) {
+ showOverlayToast(context, l.transcriptionNotDownloadedBook,
+ icon: Icons.download_rounded);
+ return;
+ }
+
+ // Set expectations (it listens for a while, a bad match moves nothing) and
+ // let the user pick where a successful find lands. Choice is remembered.
+ var after = await PlayerSettings.getFindInAudiobookAfter();
+ if (!mounted) return;
+ final go = await showDialog<bool>(
+ context: context,
+ builder: (ctx) => StatefulBuilder(
+ builder: (ctx, setDialogState) {
+ Widget option(String value, String label) => RadioListTile<String>(
+ dense: true,
+ contentPadding: EdgeInsets.zero,
+ title: Text(label),
+ value: value,
+ groupValue: after,
+ onChanged: (v) => setDialogState(() => after = v ?? after),
+ );
+ return AlertDialog(
+ icon: const Icon(Icons.headphones_rounded),
+ title: Text(l.findInAudiobook),
+ content: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(l.findInAudiobookIntroBody),
+ const SizedBox(height: 16),
+ Text(l.findInAudiobookAfterLabel,
+ style: Theme.of(ctx).textTheme.labelMedium?.copyWith(
+ color: Theme.of(ctx).colorScheme.onSurfaceVariant)),
+ const SizedBox(height: 4),
+ option('stay', l.findInAudiobookStay),
+ option('player', l.findInAudiobookGoPlayer),
+ option('readalong', l.readAlong),
+ ],
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(ctx, false),
+ child: Text(l.cancel),
+ ),
+ FilledButton(
+ onPressed: () => Navigator.pop(ctx, true),
+ child: Text(l.findInAudiobook),
+ ),
+ ],
+ );
+ },
+ ),
+ );
+ if (go != true || !mounted) return;
+ await PlayerSettings.setFindInAudiobookAfter(after);
+ if (!mounted) return;
+
+ final status = ValueNotifier<String>(l.findInAudiobookSearching);
+ showProgressDialogListenable(context, status);
+ // A long chapter can take a dozen ten-second probes; say so rather than
+ // spin in silence.
+ final slowTimer = Timer(const Duration(seconds: 10), () {
+ status.value = l.findInAudiobookStillSearching;
+ });
+ final longTimer = Timer(const Duration(seconds: 35), () {
+ status.value = l.findInAudiobookSearchingLong;
+ });
+ double? targetTime;
+ try {
+ targetTime = await _locateAudioForSelection(cfi, selText);
+ } catch (e) {
+ debugPrint('[FindAudio] failed: $e');
+ }
+ slowTimer.cancel();
+ longTimer.cancel();
+ if (!mounted) return;
+ Navigator.pop(context); // progress dialog
+ if (targetTime == null) {
+ showOverlayToast(context, l.findInAudiobookNotFound,
+ icon: Icons.search_off_rounded);
+ return;
+ }
+ await _startAudioAt(targetTime,
+ goToPlayer: after == 'player', passageCfi: cfi);
+ // Third landing: stay in the reader and follow along from the spot the
+ // user highlighted, now that the audio is playing this book. playItem can
+ // resolve a beat before the player state settles - wait for it, or the
+ // toggle would reload the book and lose the found position.
+ if (after == 'readalong' && mounted && !_readAlongOn) {
+ for (var i = 0;
+ i < 20 && AudioPlayerService().currentItemId != widget.itemId;
+ i++) {
+ await Future.delayed(const Duration(milliseconds: 150));
+ }
+ if (mounted) await _toggleReadAlong();
+ }
+ }
+
+ Future<double?> _locateAudioForSelection(String cfi, String selText) async {
+ final info = await _selectionSectionInfo(cfi, selText);
+ if (info == null) {
+ debugPrint('[FindAudio] selection offset not resolved');
+ return null;
+ }
+ final si = (info['si'] as num).toInt();
+ final offset = (info['offset'] as num).toDouble();
+ final total = (info['total'] as num).toDouble();
+ final href = info['href'] as String? ?? '';
+ if (total <= 0 || offset < 0) return null;
+
+ final api = context.read<AuthProvider>().apiService;
+ final audio = await resolveAudioChapters(widget.itemId, api);
+ if (audio.chapters.isEmpty) {
+ debugPrint('[FindAudio] no audio chapters');
+ return null;
+ }
+ final spineAll = await _spineHrefs();
+ await SyncPointStore.instance.load(
+ widget.itemId,
+ audioDuration: audio.duration > 0 ? audio.duration : null,
+ spineLength: spineAll.isEmpty ? null : spineAll.length,
+ );
+ Future<double> remember(double t) async {
+ await SyncPointStore.instance.add(
+ widget.itemId,
+ SyncPoint(t: t, si: si, off: offset, src: 'a'),
+ );
+ return t;
+ }
+
+ // Which audio chapter is this section? That anchors both the initial
+ // estimate and the seconds-per-character correction rate. Books whose
+ // chapters are plain names (alternating POV) repeat titles, so collect
+ // every agreeing audio chapter and pick by occurrence - the 3rd "Sydney"
+ // section anchors on the 3rd "Sydney" audio chapter. When the counts
+ // don't line up, take the one nearest the selection's position in the
+ // book, and keep a runner-up to probe if the first anchor turns out wrong.
+ final tocTitle = _chapterForHref(href);
+ final bookEnd = audio.duration > 0 ? audio.duration : double.infinity;
+ final pct = (info['pct'] as num?)?.toDouble();
+ final agreeing = <Map<String, dynamic>>[];
+ for (final ch in audio.chapters) {
+ final m = ch as Map<String, dynamic>;
+ if (_chapterTitlesAgree(m['title'] as String?, tocTitle)) agreeing.add(m);
+ }
+ Map<String, dynamic>? audioCh;
+ Map<String, dynamic>? audioChAlt;
+ if (agreeing.length == 1) {
+ audioCh = agreeing.first;
+ } else if (agreeing.length > 1) {
+ // Occurrence counting walks the spine and counts transitions into the
+ // title, so a chapter split across several files still counts once and
+ // two same-named chapters separated by an unnamed split file count
+ // twice.
+ final hrefs = await _spineHrefs();
+ var occurrence = 0;
+ String? prev;
+ for (var i = 0; i <= si && i < hrefs.length; i++) {
+ final t = _chapterForHref(hrefs[i]);
+ if (t == tocTitle && prev != tocTitle) occurrence++;
+ prev = t;
+ }
+ final targetFrac = (pct != null && pct > 0)
+ ? pct
+ : (hrefs.isNotEmpty ? si / hrefs.length : 0.5);
+ double fracOf(Map<String, dynamic> m) {
+ final s = (m['start'] as num?)?.toDouble() ?? 0;
+ final e = (m['end'] as num?)?.toDouble() ?? s;
+ return audio.duration > 0 ? ((s + e) / 2) / audio.duration : 0;
+ }
+ final byFrac = List<Map<String, dynamic>>.from(agreeing)
+ ..sort((x, y) => (fracOf(x) - targetFrac)
+ .abs()
+ .compareTo((fracOf(y) - targetFrac).abs()));
+ final picked = (occurrence >= 1 && occurrence <= agreeing.length)
+ ? agreeing[occurrence - 1]
+ : byFrac.first;
+ audioCh = picked;
+ for (final m in byFrac) {
+ if (!identical(m, picked)) {
+ audioChAlt = m;
+ break;
+ }
+ }
+ debugPrint('[FindAudio] "$tocTitle" matches ${agreeing.length} audio '
+ 'chapters, occurrence #$occurrence -> '
+ '"${picked['title']}"@${((picked['start'] as num?)?.toDouble() ?? 0).toStringAsFixed(0)}s'
+ '${audioChAlt != null ? ', runner-up @${((audioChAlt['start'] as num?)?.toDouble() ?? 0).toStringAsFixed(0)}s' : ''}');
+ }
+
+ double lo, hi, rate;
+ double est;
+ var anchorRate = double.nan;
+ if (audioCh != null) {
+ final a = _chapterAnchorEstimate(audioCh, offset, total, bookEnd);
+ lo = a.lo;
+ hi = a.hi;
+ rate = a.rate;
+ est = a.est;
+ final chStart = (audioCh['start'] as num?)?.toDouble() ?? 0;
+ final chEnd = (audioCh['end'] as num?)?.toDouble() ?? bookEnd;
+ anchorRate = (chEnd - chStart) / total;
+ if (anchorRate > 0.2 && chEnd.isFinite) {
+ // One audio chapter covering several ebook sections (a whole part
+ // with no chapter markers): pace through the text of the sections
+ // before this one under the same TOC entry, and take the rate from
+ // the run as a whole rather than this section alone.
+ final hrefs = await _spineHrefs();
+ var first = si;
+ while (first > 0 &&
+ first > si - 12 &&
+ first - 1 < hrefs.length &&
+ _chapterForHref(hrefs[first - 1]) == tocTitle) {
+ first--;
+ }
+ var last = si;
+ while (last + 1 < hrefs.length &&
+ last < si + 12 &&
+ (_chapterForHref(hrefs[last + 1]) ?? tocTitle) == tocTitle) {
+ last++;
+ }
+ final counts = await _sectionCharCounts(first, last);
+ if (counts.length == last - first + 1) {
+ double before = 0, run = 0;
+ for (var i = 0; i < counts.length; i++) {
+ final n = first + i == si ? total : counts[i];
+ run += n;
+ if (first + i < si) before += n;
+ }
+ final runRate = run > 0 ? (chEnd - chStart) / run : double.nan;
+ rate = (runRate >= 0.03 && runRate <= 0.2)
+ ? runRate
+ : _fallbackSecPerChar;
+ est = (chStart + (before + offset) * rate).clamp(chStart, chEnd);
+ lo = chStart;
+ hi = chEnd;
+ debugPrint('[FindAudio] anchor spans sections $first-$last '
+ '(${run.toInt()} chars, ${before.toInt()} before this one) '
+ 'rate=${rate.toStringAsFixed(4)} est=${est.toStringAsFixed(1)}');
+ }
+ }
+ // A marker that sits a little late (the part's interlude narrated under
+ // the previous chapter) puts the passage just before the anchor, where
+ // a scan clamped at the chapter start can never look.
+ lo = (lo - 900).clamp(0.0, lo);
+ debugPrint('[FindAudio] si=$si target@${offset.toInt()}/${total.toInt()} '
+ 'toc="$tocTitle" audioCh="${audioCh['title']}" '
+ '${lo.toStringAsFixed(0)}-${hi.isFinite ? hi.toStringAsFixed(0) : '?'}s '
+ 'rate=${rate.toStringAsFixed(4)} est=${est.toStringAsFixed(1)}');
+ } else {
+ // Calibre-split books often have spine sections the TOC never names
+ // (toc=null), or titles no audio chapter agrees with. Best fallback:
+ // anchor on the nearest PRECEDING section that does map to an audio
+ // chapter and pace forward through the intervening text. The whole-book
+ // percentage is the last resort - on books with songs or front matter
+ // it was measured ~800s off, far outside the probes' scan range.
+ double? anchoredEst;
+ var anchorStart = 0.0;
+ final hrefs = await _spineHrefs();
+ for (var a = si - 1; a >= 0 && a >= si - 8; a--) {
+ if (a >= hrefs.length) continue;
+ final aTitle = _chapterForHref(hrefs[a]);
+ if (aTitle == null) continue;
+ Map<String, dynamic>? aCh;
+ for (final ch in audio.chapters) {
+ final m = ch as Map<String, dynamic>;
+ if (_chapterTitlesAgree(m['title'] as String?, aTitle)) {
+ aCh = m;
+ break;
+ }
+ }
+ if (aCh == null) continue;
+ final aStart = (aCh['start'] as num?)?.toDouble() ?? 0;
+ final counts = await _sectionCharCounts(a, si - 1);
+ if (counts.length == si - a) {
+ final between = counts.fold<double>(0, (x, y) => x + y);
+ anchorStart = aStart;
+ anchoredEst = aStart + (between + offset) * _fallbackSecPerChar;
+ debugPrint('[FindAudio] anchored on si=$a "${aCh['title']}" '
+ 'start=${aStart.toStringAsFixed(0)} '
+ 'charsBetween=${between.toInt()} est=${anchoredEst.toStringAsFixed(1)}');
+ }
+ break;
+ }
+
+ if (anchoredEst != null) {
+ lo = anchorStart;
+ hi = bookEnd;
+ rate = _fallbackSecPerChar;
+ est = anchoredEst;
+ } else if (pct != null && pct > 0 && audio.duration > 0) {
+ lo = 0;
+ hi = audio.duration;
+ rate = _fallbackSecPerChar;
+ est = (pct * audio.duration).clamp(0.0, audio.duration);
+ debugPrint('[FindAudio] fallback estimate (toc="$tocTitle") '
+ 'pct=${(pct * 100).toStringAsFixed(2)}% est=${est.toStringAsFixed(1)}');
+ } else {
+ debugPrint('[FindAudio] no audio chapter matches toc="$tocTitle", '
+ 'no anchor, no location percentage - giving up');
+ return null;
+ }
+ }
+ if (hi.isInfinite) hi = est + 3600;
+
+ // The section's narration length sets how far apart the probes spread:
+ // 90s steps suit a short section, a 40-minute chapter wants them wider so
+ // five probes cover it instead of one corner.
+ final scanStep = (total * rate / 4).clamp(_scanStepSeconds, 300.0);
+ final dur = audio.duration;
+ final probed = <double>[est];
+ var probesLeft = _maxTotalProbes;
+
+ Future<double?> run(String label, double e, double from, double to,
+ double pace, int rounds, {double? step}) async {
+ if (probesLeft <= 0) return null;
+ final n = rounds < probesLeft ? rounds : probesLeft;
+ probesLeft -= n;
+ debugPrint('[FindAudio] $label est=${e.toStringAsFixed(1)} '
+ 'window ${from.toStringAsFixed(0)}-${to.toStringAsFixed(0)}s '
+ 'rounds=$n');
+ return _probeForTarget(
+ si: si,
+ offset: offset,
+ estimate: e,
+ lo: from,
+ hi: to,
+ rate: pace,
+ duration: dur,
+ maxProbes: n,
+ scanStepSeconds: step ?? scanStep,
+ );
+ }
+
+ // A spot this book has already been matched at, in this section or the
+ // one either side, beats any chapter-title guess: it is known, and two
+ // of them give the real pace between. Probed first, in a window sized to
+ // how far the pacing had to reach.
+ final sync = await _syncPointCandidate(
+ si: si,
+ offset: offset,
+ total: total,
+ fallbackRate: rate,
+ top: dur > 0 ? dur : est + 3600);
+ if (sync != null) {
+ probed.add(sync.est);
+ final window = sync.hi - sync.lo;
+ final r = await run(sync.label, sync.est, sync.lo, sync.hi, sync.rate, 3,
+ step: (window / 3).clamp(45.0, _scanStepSeconds));
+ if (r != null) return remember(r);
+ }
+
+ final t = await run('anchor', est, lo, hi, rate, _maxProbes);
+ if (t != null) return remember(t);
+
+ // The anchor never matched. Fallback candidates, most likely first, two
+ // rounds each.
+ final extras =
+ <({String label, double est, double lo, double hi, double rate})>[];
+ final top = dur > 0 ? dur : double.infinity;
+ final pctEst = (pct != null && pct > 0 && dur > 0)
+ ? (pct * dur).clamp(0.0, dur)
+ : null;
+
+ // Where the audio is parked right now. People mostly look up the passage
+ // they just heard, so a player position near the estimate or the book
+ // percentage is the best lead there is.
+ final player = AudioPlayerService();
+ if (player.currentItemId == widget.itemId) {
+ final now = player.position.inMilliseconds / 1000.0;
+ final near = (now - est).abs() <= 1800 ||
+ (pctEst != null && (now - pctEst).abs() <= 1800);
+ if (near) {
+ extras.add((
+ label: 'player position',
+ est: now,
+ lo: (now - 900).clamp(0.0, now),
+ hi: (now + 900).clamp(now, top),
+ rate: _fallbackSecPerChar,
+ ));
+ }
+ }
+ // The whole-book percentage disagreeing with the anchor by more than a
+ // few minutes usually means the anchor is the wrong chapter.
+ if (pctEst != null && (pctEst - est).abs() > 300) {
+ extras.add((
+ label: 'book percentage',
+ est: pctEst,
+ lo: (pctEst - 1200).clamp(0.0, pctEst),
+ hi: (pctEst + 1200).clamp(pctEst, dur),
+ rate: _fallbackSecPerChar,
+ ));
+ }
+ // The same title elsewhere in the book.
+ if (audioChAlt != null) {
+ final alt = _chapterAnchorEstimate(audioChAlt, offset, total, bookEnd);
+ extras.add((
+ label: 'runner-up "${audioChAlt['title']}"',
+ est: alt.est,
+ lo: alt.lo,
+ hi: alt.hi.isFinite ? alt.hi : alt.est + 3600,
+ rate: alt.rate,
+ ));
+ }
+ // A chapter-derived pace far from real narration says the audio and
+ // ebook chapters are numbered differently (twice too fast means the ebook
+ // chapter holds twice the text the audio chapter narrates): try the
+ // neighbours, nearest to the book percentage first.
+ if (audioCh != null &&
+ (anchorRate.isNaN || anchorRate < 0.05 || anchorRate > 0.12)) {
+ final idx = audio.chapters.indexOf(audioCh);
+ final neighbours = <Map<String, dynamic>>[];
+ if (idx > 0) neighbours.add(audio.chapters[idx - 1] as Map<String, dynamic>);
+ if (idx >= 0 && idx + 1 < audio.chapters.length) {
+ neighbours.add(audio.chapters[idx + 1] as Map<String, dynamic>);
+ }
+ final withEst = neighbours
+ .map((n) => (ch: n, a: _chapterAnchorEstimate(n, offset, total, bookEnd)))
+ .toList();
+ if (pctEst != null) {
+ withEst.sort((x, y) =>
+ (x.a.est - pctEst).abs().compareTo((y.a.est - pctEst).abs()));
+ }
+ for (final n in withEst) {
+ extras.add((
+ label: 'neighbour "${n.ch['title']}"',
+ est: n.a.est,
+ lo: n.a.lo,
+ hi: n.a.hi.isFinite ? n.a.hi : n.a.est + 3600,
+ rate: n.a.rate,
+ ));
+ }
+ }
+
+ for (final c in extras) {
+ if (probed.any((p) => (p - c.est).abs() <= 120)) {
+ debugPrint('[FindAudio] skip ${c.label}: '
+ 'est=${c.est.toStringAsFixed(1)} already probed');
+ continue;
+ }
+ probed.add(c.est);
+ final r = await run(c.label, c.est, c.lo, c.hi, c.rate, 2);
+ if (r != null) return remember(r);
+ }
+ debugPrint('[FindAudio] no candidate matched');
+ return null;
+ }
+
+ /// Where the sync points say [offset] in section [si] should be in the
+ /// audio. Same-section points first; failing that the last point of the
+ /// previous section or the first of the next, paced through the text in
+ /// between. Null when nothing recorded is close enough to help.
+ Future<({String label, double est, double lo, double hi, double rate})?>
+ _syncPointCandidate({
+ required int si,
+ required double offset,
+ required double total,
+ required double fallbackRate,
+ required double top,
+ }) async {
+ final pts = SyncPointStore.instance.cached(widget.itemId);
+ if (pts.isEmpty) return null;
+ final same = pts.where((p) => p.si == si).toList();
+ var e = SyncPointEstimator.inSection(same, offset, fallbackRate);
+ var label = 'sync points';
+ if (e == null) {
+ SyncPoint? prev, next;
+ for (final p in pts) {
+ if (p.si == si - 1 && (prev == null || p.off > prev.off)) prev = p;
+ if (p.si == si + 1 && (next == null || p.off < next.off)) next = p;
+ }
+ if (prev != null) {
+ final counts = await _sectionCharCounts(si - 1, si - 1);
+ if (counts.length == 1 && counts.first > 0) {
+ final chars = (counts.first - prev.off) + offset;
+ if (chars * fallbackRate <= 1800) {
+ e = SyncPointEstimator.fromPoint(prev, chars, fallbackRate);
+ label = 'sync point in the previous section';
+ }
+ }
+ }
+ if (e == null && next != null) {
+ final chars = (total - offset) + next.off;
+ if (chars * fallbackRate <= 1800) {
+ e = SyncPointEstimator.fromPoint(next, -chars, fallbackRate);
+ label = 'sync point in the next section';
+ }
+ }
+ }
+ if (e == null) return null;
+ debugPrint('[FindAudio] $label (${e.how}) from ${pts.length} points: '
+ 'est=${e.est.toStringAsFixed(1)} rate=${e.rate.toStringAsFixed(4)}');
+ return (
+ label: '$label (${e.how})',
+ est: e.est.clamp(0.0, top),
+ lo: e.lo.clamp(0.0, top),
+ hi: e.hi.clamp(0.0, top),
+ rate: e.rate,
+ );
+ }
+
+ /// Initial search window and seconds-per-character pacing from an audio
+ /// chapter anchor.
+ ({double lo, double hi, double rate, double est}) _chapterAnchorEstimate(
+ Map<String, dynamic> ch, double offset, double total, double bookEnd) {
+ final chStart = (ch['start'] as num?)?.toDouble() ?? 0;
+ final chEnd = (ch['end'] as num?)?.toDouble() ?? bookEnd;
+ final chRate = (chEnd - chStart) / total;
+ if (chRate >= 0.03 && chRate <= 0.2) {
+ return (
+ lo: chStart,
+ hi: chEnd,
+ rate: chRate,
+ est: chStart + offset * chRate,
+ );
+ }
+ // Mis-tagged audio chapters (a 3-second "chapter" was seen in the wild)
+ // give an absurd rate. Trust the chapter START as an anchor, pace the
+ // estimate at normal narration speed, leave the end open.
+ return (
+ lo: chStart,
+ hi: bookEnd,
+ rate: _fallbackSecPerChar,
+ est: chStart + offset * _fallbackSecPerChar,
+ );
+ }
+
+ /// Probe-transcribes around [estimate], correcting toward the selection at
+ /// [offset] each round. Returns the resolved global time, or null when
+ /// [maxProbes] rounds never matched the section text.
+ Future<double?> _probeForTarget({
+ required int si,
+ required double offset,
+ required double estimate,
+ required double lo,
+ required double hi,
+ required double rate,
+ required double duration,
+ required int maxProbes,
+ required double scanStepSeconds,
+ }) async {
+ var est = estimate;
+ final baseEst = est;
+ var scanStep = 0;
+ for (var attempt = 0; attempt < maxProbes; attempt++) {
+ final maxStart =
+ (hi - _probeWindowSeconds) > lo ? hi - _probeWindowSeconds : lo;
+ var probeStart = (est - _probeWindowSeconds / 2).clamp(lo, maxStart);
+ // A chapter start is usually a file start too. A window centred on it
+ // begins in the previous file and gets cut at the boundary, so it only
+ // ever hears the end of the last chapter. Start at the boundary instead
+ // so the estimate is inside what gets transcribed.
+ final boundary = TranscriptionService.instance
+ .trackBoundaryBetween(widget.itemId, probeStart, est);
+ if (boundary != null) {
+ debugPrint('[FindAudio] probe#$attempt window start '
+ '${probeStart.toStringAsFixed(1)} -> file boundary '
+ '${boundary.toStringAsFixed(1)}');
+ probeStart = boundary.clamp(lo, maxStart > boundary ? maxStart : boundary);
+ }
+
+ List<({double start, double end, String text})> segs;
+ try {
+ segs = await TranscriptionService.instance.transcribeWindowSegments(
+ itemId: widget.itemId,
+ startSeconds: probeStart,
+ windowSeconds: _probeWindowSeconds,
+ preferAccuracy: false,
+ );
+ } on TranscriptionException catch (e) {
+ // A silent or music-only window transcribes to nothing, and a probe
+ // landing at the tail of a track file gets truncated to nearly zero
+ // (windows don't span file boundaries) - scan on rather than giving
+ // up. Setup problems can't be scanned away.
+ if (e.kind != TranscriptionError.empty &&
+ e.kind != TranscriptionError.extractFailed) {
+ rethrow;
+ }
+ segs = const [];
+ }
+ final probeText = segs.map((s) => s.text).join(' ').trim();
+ final match =
+ probeText.isEmpty ? null : await _locateTranscriptInSection(si, probeText);
+ final fine = match == null ? 0.0 : (match['fine'] as num).toDouble();
+
+ if (match == null || fine < 0.5) {
+ // Bad probe (music, silence, or the estimate is off enough that the
+ // audio here isn't in this section): scan around the original
+ // estimate instead of declining on the first miss.
+ scanStep = scanStep >= 0 ? -(scanStep + 1) : -scanStep;
+ est = (baseEst + scanStep * scanStepSeconds).clamp(lo, hi);
+ debugPrint('[FindAudio] probe#$attempt start=${probeStart.toStringAsFixed(1)} '
+ 'no usable match (fine=${fine.toStringAsFixed(3)}) - '
+ 'scanning to ${est.toStringAsFixed(1)}');
+ continue;
+ }
+
+ final mOff = (match['s'] as num).toDouble();
+ final mEnd = (match['e'] as num).toDouble();
+ debugPrint('[FindAudio] probe#$attempt start=${probeStart.toStringAsFixed(1)} '
+ 'match=${mOff.toInt()}-${mEnd.toInt()} '
+ 'fine=${fine.toStringAsFixed(3)} target=${offset.toInt()}');
+
+ if (offset >= mOff && offset <= mEnd) {
+ // Target is inside the probed audio: walk the segments to the one
+ // covering the target's share of the matched text.
+ final frac = (mEnd - mOff) > 0 ? (offset - mOff) / (mEnd - mOff) : 0.0;
+ final lens = segs.map((s) => s.text.length + 1).toList();
+ final totalLen = lens.fold<int>(0, (a, b) => a + b);
+ final targetChar = frac * totalLen;
+ var t = probeStart + segs.last.start;
+ var acc = 0.0;
+ for (var i = 0; i < segs.length; i++) {
+ if (targetChar <= acc + lens[i] || i == segs.length - 1) {
+ final inFrac = lens[i] > 0
+ ? ((targetChar - acc) / lens[i]).clamp(0.0, 1.0)
+ : 0.0;
+ t = probeStart + segs[i].start + inFrac * (segs[i].end - segs[i].start);
+ break;
+ }
+ acc += lens[i];
+ }
+ debugPrint('[FindAudio] resolved t=${t.toStringAsFixed(1)}s');
+ return duration > 0 ? t.clamp(0.0, duration) : t;
+ }
+
+ // Probe landed off-target: correct by the miss distance and retry. A
+ // correction too small to move the next probe means the rate is off -
+ // step most of a window toward the target instead.
+ var correction = (offset - (mOff + mEnd) / 2) * rate;
+ if (correction.abs() < 2.0) {
+ correction = correction.isNegative
+ ? -_probeWindowSeconds * 0.75
+ : _probeWindowSeconds * 0.75;
+ }
+ est = (est + correction).clamp(lo, hi);
+ }
+ debugPrint('[FindAudio] gave up after $maxProbes probes');
+ return null;
+ }
+
+ /// Spine hrefs by spine index, for mapping neighboring sections to TOC and
+ /// audio chapters.
+ Future<List<String>> _spineHrefs() async {
+ final wc = _epubController?.webViewController;
+ if (wc == null) return const [];
+ final res = await wc.callAsyncJavaScript(functionBody: r'''
+ var out = [];
+ try {
+ var items = (book.spine && book.spine.spineItems) ? book.spine.spineItems : [];
+ for (var i = 0; i < items.length; i++) out.push(items[i].href || '');
+ } catch(e){}
+ return JSON.stringify(out);
+ ''');
+ final raw = res?.value;
+ if (raw is! String || raw.isEmpty) return const [];
+ try {
+ return (jsonDecode(raw) as List<dynamic>).cast<String>();
+ } catch (_) {
+ return const [];
+ }
+ }
+
+ /// Text length in characters of each spine section from [from] to [to]
+ /// inclusive, via the separate search book (never the live one).
+ Future<List<double>> _sectionCharCounts(int from, int to) async {
+ final wc = _epubController?.webViewController;
+ if (wc == null || to < from) return const [];
+ final res = await wc.callAsyncJavaScript(functionBody: r'''
+ var sb = window.__absorbSearchBook;
+ if (!sb) {
+ sb = ePub();
+ sb.spine.unpack(book.packaging, book.resolve.bind(book), book.canonical.bind(book));
+ window.__absorbSearchBook = sb;
+ }
+ var out = [];
+ var items = (sb.spine && sb.spine.spineItems) ? sb.spine.spineItems : [];
+ for (var i = from; i <= to && i < items.length; i++) {
+ var n = 0;
+ try {
+ await items[i].load(book.load.bind(book));
+ var d = items[i].document;
+ var text = d ? ((d.body && d.body.textContent) || (d.documentElement && d.documentElement.textContent) || '') : '';
+ n = text.length;
+ } catch(e){}
+ finally { try { items[i].unload(); } catch(e2){} }
+ out.push(n);
+ }
+ return JSON.stringify(out);
+ ''', arguments: {'from': from, 'to': to});
+ final raw = res?.value;
+ if (raw is! String || raw.isEmpty) return const [];
+ try {
+ return (jsonDecode(raw) as List<dynamic>)
+ .map((n) => (n as num).toDouble())
+ .toList();
+ } catch (_) {
+ return const [];
+ }
+ }
+
+ /// Section index, character offset of the selection start, and the section's
+ /// total character count - resolved in the live DOM. Falls back to locating
+ /// the selected text when the CFI-to-range resolution fails.
+ Future<Map<String, dynamic>?> _selectionSectionInfo(
+ String cfi, String selText) async {
+ final wc = _epubController?.webViewController;
+ if (wc == null) return null;
+ final res = await wc.callAsyncJavaScript(functionBody: r'''
+ var out = {};
+ try {
+ var contents = (typeof rendition.getContents === 'function') ? rendition.getContents() : [];
+ // The CFI names its spine section; only that section may resolve it.
+ // Chapter documents are structurally identical, so epub.js happily
+ // "resolves" a chapter-5 CFI inside a pre-rendered chapter-4 DOM at
+ // the same path - which sent Find in audiobook to the wrong chapter.
+ var wantSi = -1;
+ try {
+ var pos = new ePub.CFI(cfi).spinePos;
+ if (typeof pos === 'number' && pos >= 0) wantSi = pos;
+ } catch(eS){}
+ var ordered = [];
+ for (var i = 0; i < contents.length; i++) { if (contents[i].sectionIndex === wantSi) ordered.push(contents[i]); }
+ for (var i = 0; i < contents.length; i++) { if (contents[i].sectionIndex !== wantSi) ordered.push(contents[i]); }
+ for (var i = 0; i < ordered.length; i++) {
+ var c = ordered[i], doc = c.document;
+ if (!doc) continue;
+ var tw = doc.createTreeWalker(doc.body||doc, NodeFilter.SHOW_TEXT, null, false);
+ var nodes=[], text='', node;
+ while (node = tw.nextNode()) { nodes.push({node:node, start:text.length, len:node.textContent.length}); text += node.textContent; }
+ var off = -1, r = null;
+ if (wantSi < 0 || c.sectionIndex === wantSi) {
+ try { r = c.range(cfi); } catch(e){}
+ }
+ if (r) {
+ for (var k=0;k<nodes.length;k++){ if (nodes[k].node === r.startContainer) { off = nodes[k].start + r.startOffset; break; } }
+ }
+ if (off < 0 && selText) {
+ var p = text.toLowerCase().indexOf(selText.toLowerCase());
+ if (p !== -1) off = p;
+ }
+ if (off >= 0) {
+ var href = '';
+ try { var sec = book.spine.get(c.sectionIndex); href = sec ? sec.href : ''; } catch(e2){}
+ var pct = null;
+ try {
+ var nLoc = (typeof book.locations.length === 'function')
+ ? book.locations.length() : (book.locations ? book.locations.length : 0);
+ if (nLoc) pct = book.locations.percentageFromCfi(cfi);
+ } catch(e3){}
+ out = { si: c.sectionIndex, offset: off, total: text.length, href: href, pct: pct };
+ break;
+ }
+ }
+ } catch(e){ out.err = String(e); }
+ return JSON.stringify(out);
+ ''', arguments: {'cfi': cfi, 'selText': selText});
+ final raw = res?.value;
+ debugPrint('[FindAudio] selectionInfo $raw');
+ if (raw is! String || raw.isEmpty) return null;
+ try {
+ final d = jsonDecode(raw) as Map<String, dynamic>;
+ if (d['si'] is num && d['offset'] is num && d['total'] is num) return d;
+ } catch (_) {}
+ return null;
+ }
+
+ /// Fuzzy-locates a probe transcript inside one live section's text. Same
+ /// token bag + Levenshtein scoring as the ebook-direction search, but scoped
+ /// to a single section that is already rendered.
+ Future<Map<String, dynamic>?> _locateTranscriptInSection(
+ int sectionIndex, String transcript) async {
+ final wc = _epubController?.webViewController;
+ if (wc == null) return null;
+ final res = await wc.callAsyncJavaScript(functionBody: r'''
+ var out = null;
+ try {
+ var contents = (typeof rendition.getContents === 'function') ? rendition.getContents() : [];
+ var c = null;
+ for (var i=0;i<contents.length;i++){ if (contents[i].sectionIndex === si) { c = contents[i]; break; } }
+ if (!c) c = contents[0];
+ var doc = c && c.document;
+ if (doc) {
+ var tw = doc.createTreeWalker(doc.body||doc, NodeFilter.SHOW_TEXT, null, false);
+ var text='', node;
+ while (node = tw.nextNode()) text += node.textContent;
+ function toks(s){ return (s.toLowerCase().match(/[\p{L}\p{N}']+/gu) || []); }
+ function lev(a,b){
+ var m=a.length,n=b.length; if(!m)return n; if(!n)return m;
+ var prev=new Array(n+1), cur=new Array(n+1), x, j, tmp;
+ for(j=0;j<=n;j++)prev[j]=j;
+ for(x=1;x<=m;x++){ cur[0]=x; var ca=a.charCodeAt(x-1);
+ for(j=1;j<=n;j++){ var cost=(ca===b.charCodeAt(j-1))?0:1;
+ cur[j]=Math.min(prev[j]+1, cur[j-1]+1, prev[j-1]+cost); }
+ tmp=prev; prev=cur; cur=tmp; }
+ return prev[n];
+ }
+ var T = toks(transcript);
+ if (T.length >= 3) {
+ var need = {}; T.forEach(function(t){ need[t]=(need[t]||0)+1; });
+ var tNorm = T.join(' ');
+ var W = T.length;
+ var st=[], re=/[\p{L}\p{N}']+/gu, mm;
+ while((mm=re.exec(text))!==null){ st.push({t:mm[0].toLowerCase(), s:mm.index, e:mm.index+mm[0].length}); }
+ if (st.length >= 3) {
+ var have={}, matched=0, cands=[], p;
+ for (p=0;p<st.length;p++){
+ var tk=st[p].t; have[tk]=(have[tk]||0)+1; if (have[tk] <= (need[tk]||0)) matched++;
+ if (p>=W){ var old=st[p-W].t; if (have[old] <= (need[old]||0)) matched--; have[old]--; }
+ if (matched >= Math.max(2, Math.floor(W*0.4))) cands.push({i:Math.max(0,p-W+1), m:matched});
+ }
+ cands.sort(function(a,b){ return b.m-a.m; });
+ var used=[], picked=[];
+ for (var cc=0;cc<cands.length && picked.length<4;cc++){
+ var s0=cands[cc].i, ok=true;
+ for (var u=0;u<used.length;u++){ if (Math.abs(used[u]-s0) < W) { ok=false; break; } }
+ if (ok){ picked.push(cands[cc]); used.push(s0); }
+ }
+ for (var pc=0;pc<picked.length;pc++){
+ var s1=picked[pc].i, e1=Math.min(st.length-1, s1+W-1);
+ var winNorm = st.slice(s1,e1+1).map(function(x2){return x2.t;}).join(' ');
+ var dl = lev(tNorm, winNorm);
+ var fine = 1 - dl/Math.max(tNorm.length, winNorm.length);
+ if (!out || fine > out.fine) out = { s: st[s1].s, e: st[e1].e, fine: fine };
+ }
+ }
+ }
+ }
+ } catch(e){ out = null; }
+ return JSON.stringify(out);
+ ''', arguments: {'si': sectionIndex, 'transcript': transcript});
+ final raw = res?.value;
+ if (raw is! String || raw.isEmpty || raw == 'null') return null;
+ try {
+ return jsonDecode(raw) as Map<String, dynamic>;
+ } catch (_) {
+ return null;
+ }
+ }
+
+ /// Seek the audiobook to [seconds] and start playing, loading the book into
+ /// the player first when it isn't the current item. Position is decided
+ /// before playback starts. [goToPlayer] closes the reader and lands on the
+ /// player; otherwise the reader stays open while the audio plays, with
+ /// [passageCfi] flashed so the eye lands back on the matched passage.
+ Future<void> _startAudioAt(double seconds,
+ {required bool goToPlayer, String? passageCfi}) async {
+ final l = AppLocalizations.of(context)!;
+ final player = AudioPlayerService();
+
+ // For "Open the player", close the reader BEFORE playback starts: the
+ // shell's full-screen auto-expand is suppressed while the reader is open
+ // (so "Keep reading" can't get yanked into the player), which means it
+ // only fires for this path if the reader is already gone when play begins.
+ // Everything context-dependent is gathered first; the position was decided
+ // long before, so play still starts exactly where the match landed.
+ final api = context.read<AuthProvider>().apiService;
+ final lib = context.read<LibraryProvider>();
+ final needsLoad = player.currentItemId != widget.itemId;
+ Map<String, dynamic>? fullItem;
+ if (needsLoad) {
+ if (api == null) {
+ showOverlayToast(context, l.bookmarksNotConnected,
+ icon: Icons.cloud_off_rounded);
+ return;
+ }
+ fullItem = await api.getLibraryItem(widget.itemId);
+ if (fullItem == null) {
+ if (mounted) {
+ showOverlayToast(context, l.findInAudiobookNotFound,
+ icon: Icons.error_outline_rounded);
+ }
+ return;
+ }
+ if (!mounted) return;
+ }
+ final coverUrl = lib.getCoverUrl(widget.itemId);
+
+ if (goToPlayer && mounted) {
+ Navigator.of(context).pop(); // close the reader
+ AppShell.goToAbsorbingGlobal();
+ }
+
+ if (!needsLoad) {
+ await player.seekTo(Duration(milliseconds: (seconds * 1000).round()));
+ if (!player.isPlaying) player.play();
+ } else {
+ final media = fullItem!['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final error = await player.playItem(
+ api: api!,
+ itemId: widget.itemId,
+ title: metadata['title'] as String? ?? widget.title,
+ author: metadata['authorName'] as String? ?? '',
+ coverUrl: coverUrl,
+ totalDuration:
+ (media['duration'] is num) ? (media['duration'] as num).toDouble() : 0.0,
+ chapters: (media['chapters'] as List<dynamic>?) ?? [],
+ startTime: seconds,
+ forceStartTime: true,
+ libraryId: fullItem['libraryId'] as String?,
+ );
+ if (error != null) {
+ debugPrint('[FindAudio] playItem failed: $error');
+ if (mounted) {
+ showOverlayToast(context, error, icon: Icons.error_outline_rounded);
+ }
+ return;
+ }
+ }
+
+ if (!goToPlayer && mounted) {
+ if (passageCfi != null) {
+ _flashHighlight(passageCfi, duration: const Duration(seconds: 8));
+ }
+ showOverlayToast(context, l.findInAudiobookPlaying,
+ icon: Icons.headphones_rounded);
+ }
+ }
+
+ void _highlightSearchHit(String cfi) {
+ // The jump behind this ran display() twice in quick succession, which
+ // leaves the page/percent bar stale until the next page turn (the final
+ // relocated event never reaches the handlers - reportLocation() alone
+ // didn't fix it on device). Read the location directly and push the
+ // numbers into state ourselves.
+ _refreshLocationAfterJump();
+ _flashHighlight(cfi);
+ }
+
+ /// Load this book into the player and start it, for read along pressed
+ /// while something else (or nothing) is playing - pressing the feature IS
+ /// the intent to hear this book. False when it could not start (offline
+ /// with no API, or the item failed to load).
+ Future<bool> _ensureThisBookPlaying() async {
+ final player = AudioPlayerService();
+ if (player.currentItemId == widget.itemId &&
+ player.currentEpisodeId == null) {
+ if (!player.isPlaying) await player.play();
+ return true;
+ }
+ final api = context.read<AuthProvider>().apiService;
+ final lib = context.read<LibraryProvider>();
+ if (api == null) return false;
+ final fullItem = await api.getLibraryItem(widget.itemId);
+ if (fullItem == null || !mounted) return false;
+ final media = fullItem['media'] as Map<String, dynamic>? ?? {};
+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};
+ final error = await player.playItem(
+ api: api,
+ itemId: widget.itemId,
+ title: metadata['title'] as String? ?? widget.title,
+ author: metadata['authorName'] as String? ?? '',
+ coverUrl: lib.getCoverUrl(widget.itemId),
+ totalDuration:
+ (media['duration'] is num) ? (media['duration'] as num).toDouble() : 0.0,
+ chapters: (media['chapters'] as List<dynamic>?) ?? [],
+ libraryId: fullItem['libraryId'] as String?,
+ );
+ return error == null;
+ }
+
+ /// Toggle read along (episodes have no ebook). Reuses the live-transcript
+ /// pipeline for lines, so the cache is shared with the player overlay. A
+ /// book that isn't playing yet gets loaded and started - nobody presses
+ /// read along on a book they don't want to hear.
+ Future<void> _toggleReadAlong() async {
+ final l = AppLocalizations.of(context)!;
+ if (_readAlongOn) {
+ _stopReadAlong();
+ return;
+ }
+ final player = AudioPlayerService();
+ if (player.currentItemId != widget.itemId ||
+ player.currentEpisodeId != null) {
+ final ok = await _ensureThisBookPlaying();
+ if (!ok || !mounted) {
+ if (mounted) {
+ showOverlayToast(context, l.readAlongNeedsPlaying,
+ icon: Icons.headphones_rounded);
+ }
+ return;
+ }
+ }
+ if (!await PlayerSettings.getTranscriptionEnabled()) {
+ if (mounted) {
+ showOverlayToast(context, l.transcriptionDisabledHint,
+ icon: Icons.record_voice_over_rounded);
+ }
+ return;
+ }
+ if (!TranscriptionService.instance.canTranscribeBook(widget.itemId)) {
+ if (mounted) {
+ await promptDownloadForTranscription(context,
+ itemId: widget.itemId, title: widget.title);
+ }
+ return;
+ }
+ // Read along turns the pages itself, so the blind can't run at the same
+ // time - one of them has to own the page.
+ if (_autoScroll) {
+ await _epubController?.autoScrollStop();
+ if (mounted) setState(() {
+ _autoScroll = false;
+ _autoScrollPaused = false;
+ });
+ }
+ // Pause first: the runway fills faster against a still playhead, and
+ // nobody wants to hear words the page can't show yet. A playing book
+ // resumes by itself once ready; a paused one gets a toast.
+ final wasPlaying = player.isPlaying;
+ if (wasPlaying) await player.pause();
+ _readAlongGateArmed = false;
+ _readAlongGatePaused = wasPlaying;
+ _readAlongGateWaiting = !wasPlaying;
+ if (mounted) {
+ setState(() {
+ _readAlongOn = true;
+ _readAlongPrep = 'finding';
+ });
+ }
+ // Go to where the audio is before anything else. Waiting for the first
+ // sentence to arrive and then paging forward from the saved spot took a
+ // page turn per page between the two.
+ await _readAlongJumpToAudio();
+ if (!mounted || !_readAlongOn) return;
+ setState(() => _readAlongPrep = 'listening');
+ if (!LyricsService.instance.isOn) {
+ await LyricsService.instance.enableForCurrent();
+ _readAlongStartedPipeline = true;
+ }
+ if (!mounted || !_readAlongOn) return;
+ LyricsService.instance.readerOwns = true;
+ _readAlongColor = LyricsService.instance.readAlongColor;
+ _readAlongMode = LyricsService.instance.readAlongMode;
+ _readAlongLastPos = player.position.inMilliseconds / 1000.0;
+ final wc = _epubController?.webViewController;
+ await wc?.evaluateJavascript(source: _readAlongBootstrapSource());
+ await wc?.evaluateJavascript(
+ source: 'window.__absorbRA && __absorbRA.start()');
+ // The first anchor may be behind the page you left the reader on.
+ _readAlongAllowBack = true;
+ _readAlongLastMatch = DateTime.now();
+ _readAlongLost = false;
+ _readAlongSeekAt = null;
+ ScreenWake.keepOn(true);
+ _readAlongTimer?.cancel();
+ // 100ms so a word is never skipped at 2x: the sweep below moves at most
+ // one word per tick, ten words a second.
+ _readAlongTimer = Timer.periodic(
+ const Duration(milliseconds: 100), (_) => _readAlongTick());
+ debugPrint('[ReadAlong] enabled for ${widget.itemId}');
+ }
+
+ // Word by word repaints the page several times a second; on e-ink every
+ // one is a flash, so there read along follows by sentence whatever the
+ // setting says.
+ bool get _readAlongWordMode =>
+ !PlayerSettings.einkMode && LyricsService.instance.readAlongMode == 'word';
+
+ String _readAlongBootstrapSource() {
+ final p = _resolvePalette(context);
+ return readAlongBootstrap(_readAlongColor,
+ eink: PlayerSettings.einkMode,
+ fgArgb: p.fgColor.toARGB32(),
+ bgArgb: p.bgColor.toARGB32());
+ }
+
+ /// Put the page where the audio is. The book's own lines at the playhead
+ /// are the best needle when the transcript already has them; otherwise
+ /// listen to a short window around the playhead. Not finding it is not
+ /// fatal - the whole-book scan still runs once lines arrive.
+ Future<void> _readAlongJumpToAudio() async {
+ final player = AudioPlayerService();
+ final pos = player.position.inMilliseconds / 1000.0;
+ String? chapterHint;
+ final chapters = player.chapters;
+ final chIdx =
+ ChapterLookup.indexAtWithGrace(chapters, pos, player.totalDuration);
+ if (chIdx != null) {
+ final t = ((chapters[chIdx] as Map<String, dynamic>)['title'] as String?)
+ ?.trim();
+ if (t != null && t.isNotEmpty) chapterHint = t;
+ }
+ final store = TranscriptLineStore.instance;
+ String? text;
+ var source = 'transcript';
+ final near = store.lineNear(widget.itemId, pos, holdAfter: 4, preShow: 4);
+ if (near != null && near.exact && !near.approx) {
+ final run = store
+ .fromLine(widget.itemId, near.start, 3)
+ .where((l) => l.exact && !l.approx)
+ .map((l) => l.text.trim())
+ .join(' ');
+ text = run.isEmpty ? near.text.trim() : run;
+ source = 'cached lines';
+ }
+ Map<String, dynamic>? decision;
+ var err = 4.0;
+ try {
+ if (text != null) {
+ decision = await _decideFindTarget(text, chapterHint,
+ nearSeconds: pos);
+ }
+ // Whisper around the playhead: a short window first, a longer one if
+ // the words were too ordinary to pin down.
+ for (final window in const [12.0, 30.0]) {
+ if (decision != null || !mounted || !_readAlongOn) break;
+ final r = await _transcribeForJump(pos, window);
+ if (r == null) break;
+ source = '${window.toStringAsFixed(0)}s window';
+ err = window / 2;
+ decision = await _decideFindTarget(r, chapterHint, nearSeconds: pos);
+ }
+ } catch (e) {
+ debugPrint('[ReadAlong] find place failed: $e');
+ }
+ if (!mounted || !_readAlongOn) return;
+ if (decision == null) {
+ debugPrint('[ReadAlong] could not place the audio in the book '
+ '(pos ${pos.toStringAsFixed(1)}s, $source) - following from here');
+ return;
+ }
+ final jumped = await _jumpToFindHit(
+ decision['href'] as String, decision['excerpt'] as String);
+ debugPrint('[ReadAlong] placed the audio at ${pos.toStringAsFixed(1)}s '
+ 'via $source -> ${decision['href']} jumped=$jumped');
+ // The window sat around the playhead, so its middle is where the audio
+ // was. The lines that follow pin it exactly.
+ if (jumped && decision['s'] is num && decision['e'] is num) {
+ final mid = ((decision['s'] as num) + (decision['e'] as num)) / 2;
+ unawaited(_rememberEbookHit(decision, pos, mid, err));
+ }
+ }
+
+ /// A transcript of [window] seconds around [pos], or null when the engine
+ /// can't (busy for too long, nothing downloaded, silence).
+ Future<String?> _transcribeForJump(double pos, double window) async {
+ for (var attempt = 0; attempt < 8; attempt++) {
+ try {
+ final r = await TranscriptionService.instance.transcribeAt(
+ itemId: widget.itemId,
+ positionSeconds: pos + window / 2,
+ windowSeconds: window,
+ leadSeconds: window,
+ preferAccuracy: false,
+ feature: TranscriptionFeature.readAlong,
+ );
+ try {
+ final f = File(r.audioPath);
+ if (f.existsSync()) await f.delete();
+ } catch (_) {}
+ final t = r.text.trim();
+ return t.isEmpty ? null : t;
+ } on TranscriptionException catch (e) {
+ if (e.kind == TranscriptionError.busy) {
+ await Future.delayed(const Duration(milliseconds: 700));
+ if (!mounted || !_readAlongOn) return null;
+ continue;
+ }
+ debugPrint('[ReadAlong] find place transcription failed: $e');
+ return null;
+ }
+ }
+ return null;
+ }
+
+ /// Centre-screen card while read along gets going, like Find in ebook's:
+ /// what it is doing and how far along the runway is.
+ Widget _readAlongPrepCard(Color bg, Color fg, Color accent) {
+ final svc = LyricsService.instance;
+ return AnimatedBuilder(
+ animation: svc,
+ builder: (ctx, _) {
+ final l = AppLocalizations.of(ctx)!;
+ final listening = _readAlongPrep == 'listening';
+ final gate = svc.gateProgress;
+ final text = listening
+ ? (gate != null && gate > 0
+ ? '${l.lyricsListeningAhead} ${(gate * 100).round()}%'
+ : l.lyricsListeningAhead)
+ : l.findInEbookSearching;
+ // An indeterminate bar animates forever, which e-ink hates.
+ final value = listening ? gate : (PlayerSettings.einkMode ? 0.0 : null);
+ return Container(
+ width: 280,
+ padding: const EdgeInsets.fromLTRB(20, 18, 20, 18),
+ decoration: BoxDecoration(
+ color: bg,
+ borderRadius: BorderRadius.circular(16),
+ border: Border.all(color: fg.withValues(alpha: 0.15)),
+ boxShadow: PlayerSettings.einkMode
+ ? null
+ : [
+ BoxShadow(
+ color: Colors.black.withValues(alpha: 0.18),
+ blurRadius: 18,
+ offset: const Offset(0, 6),
+ ),
+ ],
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Row(
+ children: [
+ Icon(listening ? Icons.hearing_rounded : Icons.manage_search_rounded,
+ size: 18, color: fg.withValues(alpha: 0.7)),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(
+ text,
+ style: TextStyle(
+ fontSize: 14,
+ fontWeight: FontWeight.w600,
+ color: fg.withValues(alpha: 0.9)),
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 14),
+ ClipRRect(
+ borderRadius: BorderRadius.circular(3),
+ child: LinearProgressIndicator(
+ value: value,
+ minHeight: 5,
+ backgroundColor: fg.withValues(alpha: 0.1),
+ valueColor: AlwaysStoppedAnimation(accent),
+ ),
+ ),
+ ],
+ ),
+ );
+ },
+ );
+ }
+
+ /// The same transcript sync adjuster the player overlay has, for tuning
+ /// read along against Bluetooth latency without leaving the reader. Lives
+ /// in the bottom chrome, so it is there whenever the controls are.
+ Widget _readAlongSyncPill(Color fg) {
+ final svc = LyricsService.instance;
+ // The start-up card already says what the pill would, in the middle of
+ // the page; showing both reads as two different things happening.
+ if (_readAlongPrep != null) return const SizedBox.shrink();
+ return AnimatedBuilder(
+ animation: svc,
+ builder: (context, _) {
+ if (_readAlongLost) {
+ return Container(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
+ decoration: BoxDecoration(
+ color: fg.withValues(alpha: 0.08),
+ borderRadius: BorderRadius.circular(20),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(Icons.hearing_disabled_rounded,
+ size: 13, color: fg.withValues(alpha: 0.6)),
+ const SizedBox(width: 8),
+ Text(
+ AppLocalizations.of(context)!.readAlongLost,
+ style: TextStyle(
+ fontSize: 12,
+ fontWeight: FontWeight.w600,
+ color: fg.withValues(alpha: 0.75)),
+ ),
+ ],
+ ),
+ );
+ }
+ // After the gate, a seek can still land outside the transcript; the
+ // next chunk takes a few seconds and until then nothing lights up.
+ final gate = svc.gateProgress ?? (svc.buffering ? 0.0 : null);
+ if (gate != null) {
+ return Container(
+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
+ decoration: BoxDecoration(
+ color: fg.withValues(alpha: 0.08),
+ borderRadius: BorderRadius.circular(20),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ SizedBox(
+ width: 12,
+ height: 12,
+ child: CircularProgressIndicator(
+ value: gate > 0 ? gate : null,
+ strokeWidth: 2,
+ color: fg.withValues(alpha: 0.6),
+ ),
+ ),
+ const SizedBox(width: 8),
+ Text(
+ gate > 0
+ ? '${AppLocalizations.of(context)!.lyricsListeningAhead} '
+ '${(gate * 100).round()}%'
+ : AppLocalizations.of(context)!.lyricsListeningAhead,
+ style: TextStyle(
+ fontSize: 12,
+ fontWeight: FontWeight.w600,
+ color: fg.withValues(alpha: 0.75)),
+ ),
+ ],
+ ),
+ );
+ }
+ final ms = svc.offsetMs;
+ final label = ms == 0
+ ? '0'
+ : '${ms > 0 ? '+' : '-'}${(ms.abs() / 1000).toStringAsFixed(2)}s';
+ Widget button(IconData icon, int delta) => GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () => svc.nudgeOffset(delta),
+ child: Padding(
+ padding:
+ const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
+ child: Icon(icon, size: 16, color: fg.withValues(alpha: 0.75)),
+ ),
+ );
+ return Container(
+ decoration: BoxDecoration(
+ color: fg.withValues(alpha: 0.08),
+ borderRadius: BorderRadius.circular(20),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Padding(
+ padding: const EdgeInsets.only(left: 10, right: 2),
+ child: Icon(
+ svc.onBluetooth
+ ? Icons.bluetooth_rounded
+ : Icons.volume_up_rounded,
+ size: 13,
+ color: fg.withValues(alpha: 0.5)),
+ ),
+ button(Icons.remove_rounded, -50),
+ // Long press to drop back to no offset.
+ GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onLongPress: svc.clearOffset,
+ child: SizedBox(
+ width: 52,
+ child: Text(label,
+ textAlign: TextAlign.center,
+ style: TextStyle(
+ fontSize: 12,
+ fontWeight: FontWeight.w600,
+ color: fg.withValues(alpha: 0.75))),
+ ),
+ ),
+ button(Icons.add_rounded, 50),
+ const SizedBox(width: 4),
+ ],
+ ),
+ );
+ },
+ );
+ }
+
+ void _stopReadAlong() {
+ _readAlongTimer?.cancel();
+ _readAlongTimer = null;
+ _flushEbookPush();
+ // Runs from dispose() too, when the WebView may already be on its way out.
+ try {
+ _epubController?.webViewController
+ ?.evaluateJavascript(source: 'window.__absorbRA && __absorbRA.stop()')
+ .catchError((_) => null);
+ } catch (_) {}
+ _readAlongLineStart = null;
+ _readAlongPageWords = 0;
+ _readAlongLineWords = 0;
+ _readAlongWordIndex = -1;
+ _readAlongAt = -1;
+ _readAlongAllowBack = false;
+ _readAlongSeekAt = null;
+ _readAlongLastMatch = null;
+ _readAlongLost = false;
+ _readAlongGateArmed = false;
+ _readAlongGateWaiting = false;
+ if (_readAlongPrep != null) {
+ _readAlongPrep = null;
+ if (mounted) setState(() {});
+ }
+ // Leaving during the wait: put playback back the way it was found, or
+ // the book sits paused with nothing on screen to say why.
+ if (_readAlongGatePaused) {
+ _readAlongGatePaused = false;
+ final player = AudioPlayerService();
+ if (!player.isPlaying && player.currentItemId == widget.itemId) {
+ debugPrint('[ReadAlong] stopped while paused for the runway, resuming');
+ unawaited(player.play(logDetail: 'read along stopped', fromUi: true));
+ }
+ }
+ LyricsService.instance.readerOwns = false;
+ _syncScreenWake();
+ if (_readAlongStartedPipeline) {
+ LyricsService.instance.disable();
+ _readAlongStartedPipeline = false;
+ }
+ if (mounted && _readAlongOn) setState(() => _readAlongOn = false);
+ }
+
+ Future<void> _readAlongTick() async {
+ if (!mounted || !_readAlongOn) return;
+ final player = AudioPlayerService();
+ if (player.currentItemId != widget.itemId) {
+ _stopReadAlong();
+ return;
+ }
+ final svc = LyricsService.instance;
+ // Changing the color or word/sentence tracking in settings applies without
+ // leaving the reader.
+ if (svc.readAlongColor != _readAlongColor) {
+ _readAlongColor = svc.readAlongColor;
+ _epubController?.webViewController?.evaluateJavascript(
+ source: 'window.__absorbRA && '
+ '__absorbRA.setColor("${cssHex(_readAlongColor)}")');
+ }
+ if (svc.readAlongMode != _readAlongMode) {
+ _readAlongMode = svc.readAlongMode;
+ _readAlongLineStart = null;
+ }
+ // Same runway gate as the live transcript: painting before it is banked
+ // means the first stall leaves the page stuck on a stale sentence.
+ if (svc.gateProgress != null) {
+ if (_readAlongGateArmed) {
+ _readAlongGateArmed = false;
+ if (player.isPlaying) {
+ _readAlongGatePaused = true;
+ debugPrint('[ReadAlong] pausing while the runway builds');
+ await player.pause();
+ } else {
+ _readAlongGateWaiting = true;
+ }
+ } else if (_readAlongGatePaused && player.isPlaying) {
+ // Pressed play during the wait: their call, don't touch it again.
+ _readAlongGatePaused = false;
+ }
+ return;
+ }
+ _readAlongGateArmed = false;
+ if (_readAlongPrep != null && mounted) {
+ setState(() => _readAlongPrep = null);
+ }
+ if (_readAlongGatePaused) {
+ _readAlongGatePaused = false;
+ if (!player.isPlaying) {
+ debugPrint('[ReadAlong] runway ready, resuming');
+ await player.play(logDetail: 'read along ready', fromUi: true);
+ }
+ } else if (_readAlongGateWaiting) {
+ // The card leaving and the first sentence lighting up say it all.
+ _readAlongGateWaiting = false;
+ }
+ final pos = player.position.inMilliseconds / 1000.0;
+ // Same sync offset the player uses, so headphones don't run the reader's
+ // coloring ahead of the voice either.
+ final heard = pos - svc.offsetSeconds;
+ // The overlay shows a line a beat early because that reads like
+ // subtitles; on the page it cuts the last word of every sentence off. A
+ // small lead matched to the word timing, and almost no pre-show, so a
+ // sentence gets heard through before the next one takes over.
+ final line = TranscriptLineStore.instance.lineNear(
+ widget.itemId, heard + 0.15 * player.speed, preShow: 0.15);
+ // A seek re-anchors everything; without one, narration only moves
+ // forward, so an older line surfacing again (overlapping cached lines,
+ // a repeated phrase) must not drag the coloring back up the page.
+ final seeked = (pos - _readAlongLastPos).abs() > 3;
+ _readAlongLastPos = pos;
+ if (seeked) {
+ _readAlongAt = -1;
+ _readAlongLineStart = null;
+ _readAlongPageWords = 0;
+ _readAlongAllowBack = true;
+ _readAlongSeekAt = DateTime.now();
+ _readAlongLastMatch = DateTime.now();
+ _epubController?.webViewController
+ ?.evaluateJavascript(source: 'window.__absorbRA && __absorbRA.clear()')
+ .catchError((_) => null);
+ debugPrint('[ReadAlong] seek to ${pos.toStringAsFixed(1)}s, re-anchoring');
+ }
+ // A scrub is a run of seeks. Wait for the playhead to settle before
+ // relocating, so dragging the slider produces one relocate, not one per
+ // tick.
+ final seekAt = _readAlongSeekAt;
+ if (seekAt != null) {
+ if (DateTime.now().difference(seekAt) < const Duration(milliseconds: 1500)) {
+ return;
+ }
+ _readAlongSeekAt = null;
+ }
+ // Narration that doesn't match the page for a long stretch (an intro,
+ // an ad read, an abridged edition) leaves the last sentence lit forever
+ // otherwise. After 45s of playing with no match, say so and clear it;
+ // locating carries on, and the next hit clears the message.
+ final lastMatch = _readAlongLastMatch;
+ if (!_readAlongLost &&
+ lastMatch != null &&
+ player.isPlaying &&
+ DateTime.now().difference(lastMatch) > const Duration(seconds: 45)) {
+ _readAlongLost = true;
+ _readAlongLineStart = null;
+ _readAlongPageWords = 0;
+ _epubController?.webViewController
+ ?.evaluateJavascript(source: 'window.__absorbRA && __absorbRA.clear()')
+ .catchError((_) => null);
+ debugPrint('[ReadAlong] no match for 45s, marking lost');
+ if (mounted) setState(() {});
+ }
+ // Previews carry guessed timing for text the audio hasn't reached. The
+ // player overlay can dim them; a highlight in the book can't look
+ // tentative, and anchoring on one freezes the never-go-backwards guard
+ // when the real line lands - so read along waits for real coverage.
+ if (line == null || line.approx || line.text.trim().isEmpty) return;
+ if (!seeked &&
+ _readAlongLineStart != null &&
+ line.start < _readAlongLineStart!) {
+ debugPrint('[ReadAlong] skipped a line that goes backwards: '
+ '${line.start.toStringAsFixed(1)}s < '
+ '${_readAlongLineStart!.toStringAsFixed(1)}s');
+ return;
+ }
+ // A following line must not take over while the current sentence is
+ // still being heard - but "heard" means its last word has had its turn,
+ // not that the segment's trailing silence has run out, or every switch
+ // lands a beat late.
+ if (_readAlongLineStart != null &&
+ line.start != _readAlongLineStart &&
+ line.start > _readAlongLineStart! &&
+ heard < _readAlongLineLastWord) {
+ return;
+ }
+ if (line.start != _readAlongLineStart) {
+ if (_readAlongLocating) return;
+ _readAlongLineStart = line.start;
+ _readAlongLineLastWord = line.wordStarts.isNotEmpty
+ ? min(line.end, line.wordStarts.last + 0.35)
+ : line.end - 0.1;
+ _readAlongLineWords = line.words.length;
+ var needle = line.text.trim();
+ var needleExact = line.exact;
+ // A line cached before word timing existed can only be followed whole.
+ var wordMode = _readAlongWordMode && line.wordStarts.isNotEmpty;
+ // Whisper's own words are never on the page. Anchored, the previous
+ // sentence simply stays lit until a book line comes. With no anchor
+ // yet (just started, just seeked) that left the reader on the wrong
+ // page for as long as the stretch lasted, so find the next book line
+ // and go to where it is; the audio gets there in a moment.
+ if (!line.exact && _readAlongAt < 0 && _readAlongPageWords == 0) {
+ final nxt = TranscriptLineStore.instance
+ .nextExactLine(widget.itemId, line.end);
+ if (nxt != null) {
+ debugPrint('[ReadAlong] no anchor and this line is not the book\'s '
+ 'words - locating the next book line instead');
+ needle = nxt.text.trim();
+ needleExact = true;
+ wordMode = false;
+ }
+ }
+ _readAlongLocating = true;
+ try {
+ await _paintReadAlongLine(needle,
+ exact: needleExact,
+ wordMode: wordMode,
+ lineStart: needleExact && needle == line.text.trim() ? line.start : null);
+ } finally {
+ _readAlongLocating = false;
+ }
+ return;
+ }
+ // Same sentence, later word: a cheap repaint from the cached offsets.
+ if (_readAlongLocating ||
+ _readAlongPageWords == 0 ||
+ !_readAlongWordMode) {
+ return;
+ }
+ final idx = line.wordIndexAt(heard + 0.15 * player.speed);
+ if (idx < 0) return;
+ // Whisper's word count and the page's can differ on a corrected line, so
+ // scale the index across instead of running off the end.
+ final scaled = _readAlongLineWords > 0
+ ? (idx * _readAlongPageWords / _readAlongLineWords).floor()
+ : idx;
+ var wordIndex = scaled.clamp(0, _readAlongPageWords - 1);
+ // Sweep rather than jump: at speed a tick can land several words on, and
+ // the short ones in between would never light up. One word per tick
+ // catches up within a few ticks; a bigger gap snaps.
+ if (_readAlongWordIndex >= 0 &&
+ wordIndex > _readAlongWordIndex + 1 &&
+ wordIndex - _readAlongWordIndex <= 4) {
+ wordIndex = _readAlongWordIndex + 1;
+ }
+ if (wordIndex == _readAlongWordIndex) return;
+ _readAlongWordIndex = wordIndex;
+ final raw = await _epubController?.webViewController?.evaluateJavascript(
+ source: 'window.__absorbRA ? __absorbRA.word($wordIndex) : ""');
+ if (!mounted || !_readAlongOn) return;
+ Map<String, dynamic>? d;
+ if (raw is String && raw.isNotEmpty) {
+ try {
+ d = jsonDecode(raw) as Map<String, dynamic>;
+ } catch (_) {}
+ }
+ // The page turned into a different section and took the anchor with it:
+ // locate the sentence again on the next tick.
+ if (d == null || d['held'] != true) {
+ _readAlongLineStart = null;
+ _readAlongPageWords = 0;
+ _readAlongAt = -1;
+ return;
+ }
+ // The narration has run onto the next page mid-sentence. Turn there now
+ // rather than leaving you staring at a page the voice has left behind -
+ // and, coming the other way, without turning early and stranding the
+ // colouring off-screen until the sentence catches up.
+ _readAlongLastMatch = DateTime.now();
+ if (d['visible'] == false) {
+ final since = DateTime.now().difference(_readAlongOffPageLog);
+ if (since > const Duration(seconds: 2)) {
+ _readAlongOffPageLog = DateTime.now();
+ debugPrint('[ReadAlong] word $wordIndex off page: dir=${d['dir']} '
+ 'x=${d['x']} of ${d['w']}');
+ }
+ _readAlongTurn(d['cfi'], d['dir'], why: 'word $wordIndex is off the page');
+ }
+ }
+
+ /// Every read-along page turn goes through here. Narration only moves
+ /// forward, so a turn backwards is refused unless a seek or a fresh start
+ /// re-anchored things - otherwise a sentence found earlier on the page and
+ /// a word on the next page take turns dragging the spread back and forth.
+ void _readAlongTurn(Object? cfi, Object? dir, {required String why}) {
+ if (dir is! num || dir == 0) return;
+ final back = dir < 0;
+ if (back && !_readAlongAllowBack) {
+ debugPrint('[ReadAlong] not turning back: $why');
+ return;
+ }
+ // One turn at a time: judging the next word before the last turn has
+ // landed reads it as still off the page and turns again, and the page
+ // ends up one ahead of the voice. The relocation callback clears this;
+ // a stuck one gives up after 3s.
+ final pending = _readAlongTurnPending;
+ if (pending != null &&
+ DateTime.now().difference(pending) < const Duration(seconds: 3)) {
+ return;
+ }
+ final since = DateTime.now().difference(_readAlongLastTurn);
+ if (since < const Duration(milliseconds: 700)) return;
+ _readAlongLastTurn = DateTime.now();
+ _readAlongTurnPending = DateTime.now();
+ // A forward turn that lands with the voice behind the page was our own
+ // overshoot; one turn back is allowed to correct it.
+ _readAlongAllowBack = !back;
+ // Step a page the way a tap does rather than jumping to a position: the
+ // position jump silently did nothing on some devices, and a target more
+ // than a page away simply takes another step on the next tick.
+ debugPrint('[ReadAlong] turning ${back ? 'back' : 'forward'}: $why');
+ if (back) {
+ _epubController?.prev();
+ } else {
+ _epubController?.next();
+ }
+ }
+
+ /// Find the line's text in the rendered pages and move the follow-coloring
+ /// there, page-turning when the line has moved past the visible page. A
+ /// line that isn't in the rendered sections (chapter boundary) is found via
+ /// the search book when its text is ebook-exact; Whisper-flavored lines
+ /// that don't match are skipped - the next exact line re-anchors.
+ /// [lineStart] is the audio time the sentence starts at, when the needle is
+ /// a book line heard at a known moment; every such hit is a sync point.
+ Future<void> _paintReadAlongLine(String needle,
+ {required bool exact, required bool wordMode, double? lineStart}) async {
+ final wc = _epubController?.webViewController;
+ if (wc == null) return;
+ final watch = Stopwatch()..start();
+ final res = await wc.callAsyncJavaScript(
+ functionBody: 'return window.__absorbRA ? '
+ '__absorbRA.locate(needle, wordMode, minOffset) : "";',
+ arguments: {
+ 'needle': needle,
+ 'wordMode': wordMode,
+ 'minOffset': _readAlongAt,
+ },
+ );
+ final raw = res?.value;
+ if (!mounted || !_readAlongOn) return;
+ Map<String, dynamic>? d;
+ if (raw is String && raw.isNotEmpty) {
+ try {
+ d = jsonDecode(raw) as Map<String, dynamic>;
+ } catch (_) {}
+ }
+ final head = needle.length > 50 ? '${needle.substring(0, 50)}...' : needle;
+ if (d != null && d['found'] == true) {
+ _readAlongMissSince = null;
+ _readAlongStepped = false;
+ _readAlongLastMatch = DateTime.now();
+ if (_readAlongLost) {
+ _readAlongLost = false;
+ if (mounted) setState(() {});
+ }
+ _readAlongPageWords = (d['words'] as num?)?.toInt() ?? 0;
+ _readAlongWordIndex = wordMode && _readAlongPageWords > 0 ? 0 : -1;
+ _readAlongAt = (d['at'] as num?)?.toInt() ?? -1;
+ // Logs the heard line against the page sentence it landed on, so a
+ // mis-mapping shows up as two different sentences on one line.
+ debugPrint('[ReadAlong] "$head" -> page@$_readAlongAt '
+ 'words=$_readAlongPageWords visible=${d['visible']} '
+ '${watch.elapsedMilliseconds}ms | page: "${d['sentence']}"');
+ if (lineStart != null && d['si'] is num && _readAlongAt >= 0) {
+ unawaited(SyncPointStore.instance.add(
+ widget.itemId,
+ SyncPoint(
+ t: lineStart,
+ si: (d['si'] as num).toInt(),
+ off: _readAlongAt.toDouble(),
+ src: 'r',
+ ),
+ audioDuration: AudioPlayerService().currentItemId == widget.itemId
+ ? AudioPlayerService().displayDuration
+ : null,
+ ));
+ }
+ if (d['visible'] == false) {
+ _readAlongTurn(d['cfi'], d['dir'], why: 'sentence is off the page');
+ }
+ return;
+ }
+ debugPrint('[ReadAlong] "$head" not on the rendered pages '
+ '(${watch.elapsedMilliseconds}ms, exact=$exact)');
+ // Not in the rendered pages: an exact line can be found globally (chapter
+ // crossings land here); a whisper line just waits for the next one.
+ if (!exact) return;
+ // That scan loads every section of the book, which takes seconds and
+ // stalls the page while it runs, and it lands on the section start, not
+ // the sentence. One miss is usually a sentence sitting off the current
+ // page or a page turn still rendering, so it only runs once a sentence
+ // has stayed missing for a couple of seconds, well clear of any turn.
+ final now = DateTime.now();
+ _readAlongMissSince ??= now;
+ // With no anchor at all (just started, just seeked) the audio can be
+ // anywhere in the book, and the delays below only left the reader on
+ // the wrong page while the book's lines went by. Scan straight away.
+ final unanchored = _readAlongAt < 0 && _readAlongPageWords == 0;
+ // Narration runs forward, and the next sentence not being in the rendered
+ // pages usually means it starts the next section - which is simply the
+ // next page. Step once and look again before paying for a scan.
+ if (!unanchored && !_readAlongStepped) {
+ _readAlongStepped = true;
+ _readAlongTurn(null, 1, why: 'sentence is not on this page, trying the next');
+ return;
+ }
+ final missing = now.difference(_readAlongMissSince!);
+ final sinceTurn = now.difference(_readAlongLastTurn);
+ final since = now.difference(_readAlongLastScan);
+ if ((!unanchored &&
+ (missing < const Duration(seconds: 2) ||
+ sinceTurn < const Duration(seconds: 3))) ||
+ since < const Duration(seconds: 10)) {
+ debugPrint('[ReadAlong] holding the whole-book scan '
+ '(missing ${missing.inMilliseconds}ms, turn ${sinceTurn.inSeconds}s ago, '
+ 'scan ${since.inSeconds}s ago)');
+ return;
+ }
+ _readAlongLastScan = now;
+ final hres = await wc.callAsyncJavaScript(functionBody: r'''
+ var sb = window.__absorbSearchBook;
+ if (!sb) {
+ sb = ePub();
+ sb.spine.unpack(book.packaging, book.resolve.bind(book), book.canonical.bind(book));
+ window.__absorbSearchBook = sb;
+ }
+ var q = needle.toLowerCase().replace(/\s+/g,' ').trim();
+ var items = (sb.spine && sb.spine.spineItems) ? sb.spine.spineItems : [];
+ var found = '';
+ for (var i = 0; i < items.length; i++) {
+ var item = items[i], text = '';
+ try {
+ await item.load(book.load.bind(book));
+ var d = item.document;
+ text = d ? ((d.body && d.body.textContent) || (d.documentElement && d.documentElement.textContent) || '') : '';
+ } catch(e){}
+ finally { try { item.unload(); } catch(e2){} }
+ await new Promise(function(r) { setTimeout(r, 0); });
+ if (!text) continue;
+ if (text.toLowerCase().replace(/\s+/g,' ').indexOf(q) !== -1) { found = item.href || ''; break; }
+ }
+ return JSON.stringify({href: found});
+ ''', arguments: {'needle': needle});
+ final hraw = hres?.value;
+ if (!mounted || !_readAlongOn || hraw is! String) return;
+ String href = '';
+ try {
+ href = (jsonDecode(hraw) as Map<String, dynamic>)['href'] as String? ?? '';
+ } catch (_) {}
+ if (href.isEmpty) return;
+ // Land on the sentence itself, the way Find in ebook does, and let the
+ // next tick paint it. Only if the sentence can't be pinned in the live
+ // section does it fall back to the section start, which then costs a
+ // page turn per page to reach the narration.
+ wc.evaluateJavascript(source: 'window.__absorbRA && __absorbRA.clear()');
+ _readAlongPageWords = 0;
+ _readAlongAt = -1;
+ _readAlongAllowBack = true;
+ _readAlongLastTurn = DateTime.now();
+ _readAlongMissSince = null;
+ _readAlongLineStart = null;
+ final landed = await _jumpToFindHit(href, needle, flash: false);
+ debugPrint('[ReadAlong] whole-book scan -> $href, on the sentence: $landed');
+ if (!landed && mounted && _readAlongOn) {
+ _readAlongLastTurn = DateTime.now();
+ _epubController?.display(cfi: href);
+ }
+ }
+
+ /// Brief highlight so the user can spot the passage on the page. Strong
+ /// opacity and a vivid amber so it stays visible across light, sepia, and
+ /// dark themes (the highlight blends with the page, so a faint tint washes
+ /// out on some).
+ void _flashHighlight(String cfi,
+ {Duration duration = const Duration(seconds: 4)}) {
+ _epubController?.addHighlight(
+ cfi: cfi,
+ color: const Color(0xFFFFC400),
+ opacity: 0.9,
+ );
+ Future.delayed(duration, () {
+ if (!mounted) return;
+ _epubController?.removeHighlight(cfi: cfi);
+ });
+ }
+
+ /// Reads epub.js's current location and pushes page/chapter/percent into
+ /// state, bypassing the relocated-event plumbing that a scripted jump can
+ /// leave stale. Waits out the display's settle first.
+ Future<void> _refreshLocationAfterJump() async {
+ final wc = _epubController?.webViewController;
+ if (wc == null) return;
+ final res = await wc.callAsyncJavaScript(functionBody: r'''
+ await new Promise(function(r){ setTimeout(r, 450); });
+ try { rendition.reportLocation(); } catch(e0){}
+ var out = {};
+ try {
+ var loc = rendition.currentLocation();
+ if (loc && loc.start) {
+ out.cfi = loc.start.cfi || null;
+ out.href = loc.start.href || '';
+ if (loc.start.displayed) {
+ out.page = loc.start.displayed.page;
+ out.total = loc.start.displayed.total;
+ }
+ var info = (typeof readerPageInfo === 'function') ? readerPageInfo() : null;
+ if (info) {
+ out.page = info.page;
+ out.total = info.total;
+ out.href = info.href || out.href;
+ }
+ out.percentage = (typeof loc.start.percentage === 'number') ? loc.start.percentage : null;
+ if ((out.percentage == null || out.percentage === 0) && book.locations && loc.start.cfi) {
+ try {
+ var nLoc = (typeof book.locations.length === 'function')
+ ? book.locations.length() : book.locations.length;
+ if (nLoc) out.percentage = book.locations.percentageFromCfi(loc.start.cfi);
+ } catch(e1){}
+ }
+ }
+ } catch(e){ out.err = String(e); }
+ return JSON.stringify(out);
+ ''');
+ final raw = res?.value;
+ debugPrint('[Search] refreshLocation $raw');
+ if (!mounted || raw is! String || raw.isEmpty) return;
+ Map<String, dynamic> d;
+ try {
+ d = jsonDecode(raw) as Map<String, dynamic>;
+ } catch (_) {
+ return;
+ }
+ final cfi = d['cfi'] as String?;
+ final href = d['href'] as String? ?? '';
+ final page = (d['page'] as num?)?.toInt();
+ final total = (d['total'] as num?)?.toInt();
+ final pct = (d['percentage'] as num?)?.toDouble();
+ setState(() {
+ if (page != null && total != null && total > 0) {
+ _chapterPage = page;
+ _chapterPageTotal = total;
+ }
+ if (href.isNotEmpty) {
+ _currentChapterTitle = _chapterForHref(href) ?? _currentChapterTitle;
+ }
+ if (pct != null && pct > 0 && _locationsReady) {
+ _progress = pct.clamp(0.0, 1.0);
+ }
+ });
+ if (cfi != null && cfi.isNotEmpty) {
+ _currentCfi = cfi;
+ _updateBookmarkState();
+ _syncProgress(cfi, _progress);
+ }
+ }
+
+ Future<void> _openSearchScreen() async {
+ // Fullscreen route — opaque so the WebView is fully covered. Bottom-sheet
+ // approach had soft-keyboard taps leaking through to the reader's JS
+ // swipe-to-turn handlers underneath.
+ final selected = await Navigator.of(context, rootNavigator: true).push<EpubSearchResult>(
+ MaterialPageRoute(
+ fullscreenDialog: true,
+ builder: (_) => _EbookSearchScreen(
+ initialQuery: _searchQuery,
+ initialResults: _searchResults,
+ initialChapters: _resultChapters,
+ initialLastQuery: _lastSearchedQuery,
+ runSearch: (q) async {
+ final payload = await _searchBook(q);
+ // Persist back on the parent state so reopening the search screen
+ // restores the same list.
+ if (mounted) {
+ setState(() {
+ _searchQuery = q;
+ _searchResults = payload.results;
+ _resultChapters = payload.chapters;
+ _lastSearchedQuery = q;
+ });
+ }
+ return payload;
+ },
+ ),
+ ),
+ );
+ if (selected != null && mounted) {
+ _jumpToSearchResult(selected);
+ }
+ }
+
+ void _showAnnotationsSheet() {
+ final cs = Theme.of(context).colorScheme;
+ final tt = Theme.of(context).textTheme;
+ final highlights = _annotations.where((a) => a.type == AnnotationType.highlight).toList();
+ final bookmarks = _annotations.where((a) => a.type == AnnotationType.bookmark).toList();
+
- showModalBottomSheet(
++ showAdaptiveActionMenu(
+ context: context,
+ backgroundColor: cs.surface,
+ isScrollControlled: true,
+ shape: const RoundedRectangleBorder(
+ borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
+ ),
- builder: (ctx) => DraggableScrollableSheet(
+ desktopScrollWrap: false,
+ builder: (ctx) => AdaptiveDraggableScrollableSheet(
expand: false,
initialChildSize: 0.6,
maxChildSize: 0.9,
diff --cc lib/widgets/expanded_card.dart
index 969c7dfa,73f01cab..208529de
--- a/lib/widgets/expanded_card.dart
+++ b/lib/widgets/expanded_card.dart
@@@ -17,10 -16,12 +17,13 @@@ import 'card_progress_bar.dart'
import 'card_playback_controls.dart';
import 'card_buttons.dart';
import 'ebook_router.dart';
+ import '../services/lyrics_service.dart';
+ import 'lyrics_overlay.dart';
import 'overlay_toast.dart';
import '../services/ebook_cache.dart';
+ import '../services/find_in_ebook.dart';
import '../main.dart' show colorSourceNotifier, useColorEverywhereNotifier, manualSeedNotifier, manualColorScheme;
+import '../utils/app_platform.dart';
// ─── Custom route: slide-up + fade ────────────────────────────
@@@ -193,10 -196,9 +200,10 @@@ class _ExpandedCardState extends State<
}
final lib = context.read<LibraryProvider>();
- return lib.getCoverUrl(_itemId, width: 800);
+ return lib.getCoverUrl(_itemId, width: 1200);
}
- bool get _isLocalCover => _coverUrl != null && _coverUrl!.startsWith('/');
+ bool get _isLocalCover =>
+ !AppPlatform.isWeb && _coverUrl != null && _coverUrl!.startsWith('/');
@override
void initState() {
diff --cc lib/widgets/home_section.dart
index 23eab461,7b736c72..200cdca8
--- a/lib/widgets/home_section.dart
+++ b/lib/widgets/home_section.dart
@@@ -22,7 -18,7 +22,8 @@@ class HomeSection extends StatelessWidg
final String sectionId;
final VoidCallback? onTitleTap;
final double coverAspectRatio;
+ final double desktopScale;
+ final bool showSubtitles;
final bool selectionMode;
final Set<String> selectedItemIds;
final ValueChanged<Map<String, dynamic>>? onSelectionToggle;
@@@ -36,7 -32,7 +37,8 @@@
required this.sectionId,
this.onTitleTap,
this.coverAspectRatio = 1.0,
+ this.desktopScale = 1.2,
+ this.showSubtitles = false,
this.selectionMode = false,
this.selectedItemIds = const {},
this.onSelectionToggle,
@@@ -72,17 -66,15 +74,18 @@@
final effectiveEpisode = isEpisodeSection || hasEpisodeEntities;
final bool isRectCover = coverAspectRatio < 1.0;
+ final desktop = isDesktopWorkspace(context);
+ final scale = desktop ? desktopScale : 1.0;
final double cardWidth =
- isContinueListening ? 300 : (isAuthorSection ? 120 : 140);
+ (isContinueListening ? 300 : (isAuthorSection ? 120 : 140)) * scale;
+ // Book cards grow by a line when subtitles are on; author and episode
+ // cards have no subtitle to show, so they stay as they are.
+ final bool subtitleLine =
+ showSubtitles && !isContinueListening && !effectiveEpisode && !isAuthorSection;
final double cardHeight =
- (isContinueListening
- ? 120
- : effectiveEpisode
- ? 200
- : (isAuthorSection ? 170 : (isRectCover ? 260 : 200))) *
- scale;
- (isContinueListening ? 120 : effectiveEpisode ? 200 : (isAuthorSection ? 170 : (isRectCover ? 260 : 200)))
- + (subtitleLine ? 18 : 0);
++ ((isContinueListening ? 120 : effectiveEpisode ? 200 : (isAuthorSection ? 170 : (isRectCover ? 260 : 200)))
++ + (subtitleLine ? 18 : 0)) *
++ scale;
return Padding(
padding: const EdgeInsets.only(top: 24),
@@@ -205,10 -184,9 +208,11 @@@
child: BookCard(
item: entity,
showProgress: isContinueListening,
+ showSubtitle: subtitleLine,
isWide: isContinueListening,
- coverAspectRatio: isContinueListening ? 1.0 : coverAspectRatio,
+ coverAspectRatio: isContinueListening
+ ? 1.0
+ : coverAspectRatio,
sourcePlaylistId: sourcePlaylistId,
sourcePlaylistEpisodeId: sourcePlaylistEpisodeId,
sourceCollectionId: sourceCollectionId,
diff --cc lib/widgets/library_authors_tab.dart
index bedd2a6f,d40a6f0f..5165b911
--- a/lib/widgets/library_authors_tab.dart
+++ b/lib/widgets/library_authors_tab.dart
@@@ -8,7 -7,11 +8,12 @@@ class LibraryAuthorsTab extends Statele
final List<Map<String, dynamic>> authors;
final bool isLoadingAuthors;
final bool authorsLoaded;
+ final double desktopMaxCrossAxisExtent;
+
+ /// More pages exist past [authors]: the grid shows a loader cell and calls
+ /// [onLoadMore] as the user nears the bottom.
+ final bool hasMore;
+ final VoidCallback? onLoadMore;
final Future<void> Function() onRefresh;
final Widget? headerSliver;
final ScrollController? scrollController;
@@@ -23,7 -26,8 +28,9 @@@
required this.authors,
required this.isLoadingAuthors,
required this.authorsLoaded,
+ this.desktopMaxCrossAxisExtent = kDesktopLibraryTileMaxExtent,
+ this.hasMore = false,
+ this.onLoadMore,
required this.onRefresh,
this.headerSliver,
this.scrollController,
@@@ -89,31 -104,39 +112,44 @@@
slivers: [
...headers,
SliverPadding(
- padding: const EdgeInsets.fromLTRB(16, 8, 16, libraryGridBottomPadding),
+ padding: EdgeInsets.fromLTRB(
+ 16,
+ 8,
+ 16,
+ libraryGridBottomPadding(context),
+ ),
sliver: SliverGrid(
- gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
- crossAxisCount: cols,
+ gridDelegate: libraryGridDelegate(
+ context,
childAspectRatio: 0.68,
- crossAxisSpacing: 10,
- mainAxisSpacing: 10,
+ desktopMaxCrossAxisExtent: desktopMaxCrossAxisExtent,
++ crossAxisCount: cols,
+ ),
+ delegate: SliverChildBuilderDelegate(
+ (context, index) {
+ maybeLoadAhead(index);
+ if (index >= authors.length) {
+ return const Center(
+ child: Padding(
+ padding: EdgeInsets.all(16),
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ),
+ );
+ }
+ final author = authors[index];
+ final authorId = author['id'] as String? ?? '';
+ return GridAuthorTile(
+ author: author,
+ selectionMode: selectionMode,
+ isSelected: selectedAuthorIds.contains(authorId),
+ isMatching: matchingAuthorId == authorId,
+ onSelectionToggle: onSelectionToggle == null
+ ? null
+ : () => onSelectionToggle!(author, index),
+ );
+ },
+ childCount: authors.length + (hasMore ? 1 : 0),
),
- delegate: SliverChildBuilderDelegate((context, index) {
- final author = authors[index];
- final authorId = author['id'] as String? ?? '';
- return GridAuthorTile(
- author: author,
- selectionMode: selectionMode,
- isSelected: selectedAuthorIds.contains(authorId),
- isMatching: matchingAuthorId == authorId,
- onSelectionToggle: onSelectionToggle == null
- ? null
- : () => onSelectionToggle!(author, index),
- );
- }, childCount: authors.length),
),
),
],
diff --cc lib/widgets/library_books_tab.dart
index 37d86521,1be8a7c5..88a29ef5
--- a/lib/widgets/library_books_tab.dart
+++ b/lib/widgets/library_books_tab.dart
@@@ -1,7 -1,7 +1,8 @@@
import 'package:flutter/material.dart';
import '../l10n/app_localizations.dart';
import '../screens/library_screen.dart';
+import '../utils/desktop_workspace.dart';
+ import 'books_sheet_shared.dart';
import 'library_grid_tiles.dart';
class LibraryBooksTab extends StatelessWidget {
@@@ -13,11 -17,8 +18,12 @@@
final String? tagFilter;
final bool isPodcastLibrary;
final bool rectangleCovers;
+ final bool showSubtitles;
final double coverAspectRatio;
+ final double desktopMaxCrossAxisExtent;
+ final bool selectionMode;
+ final Set<String> selectedItemIds;
+ final void Function(Map<String, dynamic> item, int index)? onSelectionToggle;
final Future<void> Function() onRefresh;
final VoidCallback onClearFilter;
@@@ -46,11 -57,8 +59,12 @@@
this.tagFilter,
this.isPodcastLibrary = false,
required this.rectangleCovers,
+ required this.showSubtitles,
required this.coverAspectRatio,
+ this.desktopMaxCrossAxisExtent = kDesktopLibraryTileMaxExtent,
+ this.selectionMode = false,
+ this.selectedItemIds = const {},
+ this.onSelectionToggle,
required this.onRefresh,
required this.onClearFilter,
required this.onLoadMore,
@@@ -160,76 -210,71 +224,80 @@@
slivers: [
...headers,
SliverPadding(
- padding: const EdgeInsets.fromLTRB(16, 8, 16, libraryGridBottomPadding),
+ padding: EdgeInsets.fromLTRB(
+ 16,
+ 8,
+ 16,
+ libraryGridBottomPadding(context),
+ ),
sliver: SliverGrid(
- gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
- crossAxisCount: cols,
+ gridDelegate: libraryGridDelegate(
+ context,
childAspectRatio: rectangleCovers ? 0.48 : 0.68,
+ desktopMaxCrossAxisExtent: desktopMaxCrossAxisExtent,
++ crossAxisCount: cols,
+ // Subtitles add a line under every title, and how much room
+ // that needs depends on the cover size, so size the cell from
+ // the tile itself rather than from a second fixed ratio.
+ mainAxisExtent: showSubtitles
+ ? coverGridTileWidth(context) / (rectangleCovers ? 0.48 : 0.68)
+ + coverGridSubtitleHeight(context)
+ : null,
- crossAxisSpacing: 10,
- mainAxisSpacing: 10,
),
- delegate: SliverChildBuilderDelegate((context, index) {
- if (index >= items.length) {
- return const Center(
- child: Padding(
- padding: EdgeInsets.all(16),
- child: CircularProgressIndicator(strokeWidth: 2),
- ),
- );
- }
- final item = items[index];
- if (item.containsKey('collapsedSeries')) {
- return GridSeriesTile(
+ delegate: SliverChildBuilderDelegate(
+ (context, index) {
+ maybeLoadAhead(index);
+ if (index >= items.length) {
+ if (loadFailed) {
+ return Center(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(l.failedToLoad,
+ textAlign: TextAlign.center,
+ style: tt.bodySmall
+ ?.copyWith(color: cs.onSurfaceVariant)),
+ TextButton(
+ onPressed: onLoadMore, child: Text(l.retry)),
+ ],
+ ),
+ );
+ }
+ return const Center(
+ child: Padding(
+ padding: EdgeInsets.all(16),
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ),
+ );
+ }
+ final item = items[index];
+ if (item.containsKey('collapsedSeries')) {
+ return GridSeriesTile(item: item, coverAspectRatio: coverAspectRatio);
+ }
+ final itemId = item['id'] as String?;
+ return GridBookTile(
item: item,
coverAspectRatio: coverAspectRatio,
+ showSubtitle: showSubtitles,
+ selectionMode: selectionMode,
+ selected: itemId != null && selectedItemIds.contains(itemId),
+ onSelectionToggle: itemId == null || onSelectionToggle == null
+ ? null
+ : () => onSelectionToggle!(item, index),
);
- }
- final itemId = item['id'] as String?;
- return GridBookTile(
- item: item,
- coverAspectRatio: coverAspectRatio,
- selectionMode: selectionMode,
- selected: itemId != null && selectedItemIds.contains(itemId),
- onSelectionToggle: itemId == null || onSelectionToggle == null
- ? null
- : () => onSelectionToggle!(item, index),
- );
- }, childCount: items.length + (hasMore ? 1 : 0)),
+ },
+ childCount: items.length + (hasMore ? 1 : 0),
+ ),
),
),
],
);
}
- // On a tall/wide viewport (tablets) the first page often doesn't fill the
- // screen, so nothing scrolls and the bottom-trigger below never fires. After
- // layout, if the grid isn't scrollable yet and there's more to load, pull
- // the next page. Repeats on each rebuild until the viewport fills or we run
- // out of items.
- if (hasMore && !isLoadingPage && items.isNotEmpty) {
- WidgetsBinding.instance.addPostFrameCallback((_) {
- final c = scrollController;
- if (c != null && c.hasClients && c.position.maxScrollExtent <= 0) {
- onLoadMore();
- }
- });
- }
-
- return NotificationListener<ScrollNotification>(
- onNotification: (n) {
- if (n is ScrollUpdateNotification &&
- n.metrics.pixels >= n.metrics.maxScrollExtent - 400) {
- onLoadMore();
- }
- return false;
- },
- child: isDesktopWorkspace(context)
- return RefreshIndicator(onRefresh: onRefresh, child: body);
++ // Paging is index-driven (maybeLoadAhead above); only the pull to
++ // refresh differs, and the desktop workspace has a refresh chip instead.
++ return isDesktopWorkspace(context)
+ ? body
- : RefreshIndicator(onRefresh: onRefresh, child: body),
- );
++ : RefreshIndicator(onRefresh: onRefresh, child: body);
}
}
diff --cc lib/widgets/library_grid_tiles.dart
index f4c493f0,fa073cc0..45683059
--- a/lib/widgets/library_grid_tiles.dart
+++ b/lib/widgets/library_grid_tiles.dart
@@@ -10,12 -10,11 +10,15 @@@ import '../services/audio_player_servic
import '../services/download_service.dart';
import 'absorbing_shared.dart';
import 'book_detail_sheet.dart';
+ import 'books_sheet_shared.dart' show coverGridTextScale, coverGridDecodeWidth;
import 'episode_list_sheet.dart';
+import 'hover_cover_actions.dart';
+ import '../services/upcoming_releases_service.dart';
import 'series_books_sheet.dart';
import 'author_books_sheet.dart';
+import '../utils/app_platform.dart';
+import '../utils/media_card_gesture_policy.dart';
++import '../utils/desktop_workspace.dart';
// ═══════════════════════════════════════════════════════════════
// Grid book tile (cover + title + author)
@@@ -76,120 -77,87 +81,103 @@@ class _GridBookTileState extends State<
final author = metadata['authorName'] as String? ?? '';
final coverUrl = lib.getCoverUrl(itemId);
final progress = lib.getProgress(itemId);
- final isExplicit =
- PlayerSettings.showExplicitBadge && metadata['explicit'] == true;
+ final isExplicit = PlayerSettings.showExplicitBadge && metadata['explicit'] == true;
final isDownloaded = _dl.isDownloaded(itemId);
final isFinished = lib.getProgressData(itemId)?['isFinished'] == true;
- final isSubscribed =
- lib.isPodcastLibrary && lib.isPodcastSubscribed(itemId);
- final unfinishedCount = lib.isPodcastLibrary
- ? lib.getUnfinishedEpisodeCount(widget.item)
- : 0;
+ final isSubscribed = lib.isPodcastLibrary && lib.isPodcastSubscribed(itemId);
+ final unfinishedCount =
+ lib.isPodcastLibrary ? lib.getUnfinishedEpisodeCount(widget.item) : 0;
- final canEdit =
- itemId.isNotEmpty &&
- return GestureDetector(
++ final gesturePolicy = MediaCardGesturePolicy(isWeb: AppPlatform.isWeb);
++ final canEdit = itemId.isNotEmpty &&
+ !lib.isPodcastLibrary &&
+ !lib.isOffline &&
- context.watch<AuthProvider>().canUpdateMetadata;
++ isDesktopWorkspace(context) &&
++ (context.watch<AuthProvider?>()?.canUpdateMetadata ?? false);
++ // Desktop hover actions only; selection is drawn by the tile itself.
+ return HoverCoverActions(
- onMenu:
- (!widget.selectionMode && itemId.isNotEmpty && !lib.isPodcastLibrary)
- ? () =>
- showQuickActionsSheet(context, itemId, initialItem: widget.item)
++ onMenu: (!widget.selectionMode && itemId.isNotEmpty && !lib.isPodcastLibrary)
++ ? () => showQuickActionsSheet(context, itemId, initialItem: widget.item)
+ : null,
+ editItemId: canEdit && !widget.selectionMode ? itemId : null,
+ selectionMode: widget.selectionMode,
- selected: widget.selected,
- onSelectionToggle: widget.onSelectionToggle,
+ child: GestureDetector(
- // opaque so taps on the blank space below the title (the tile's tall
- // aspect ratio leaves a gap when the Column children stop short)
- // still trigger the onTap. Without this, taps in that blank strip
- // miss the Column's hit test and nothing happens.
- behavior: HitTestBehavior.opaque,
- onTap: () {
- if (widget.selectionMode && widget.onSelectionToggle != null) {
- widget.onSelectionToggle!();
- return;
- }
- if (itemId.isNotEmpty) {
- if (lib.isPodcastLibrary) {
- EpisodeListSheet.show(context, widget.item);
- } else {
- showBookDetailSheet(context, itemId);
- }
+ // opaque so taps on the blank space below the title (the tile's tall
+ // aspect ratio leaves a gap when the Column children stop short)
+ // still trigger the onTap. Without this, taps in that blank strip
+ // miss the Column's hit test and nothing happens.
+ behavior: HitTestBehavior.opaque,
+ onTap: () {
+ if (widget.selectionMode && widget.onSelectionToggle != null) {
+ widget.onSelectionToggle!();
+ return;
+ }
+ if (itemId.isNotEmpty) {
+ if (lib.isPodcastItem(widget.item)) {
+ EpisodeListSheet.show(context, widget.item);
+ } else {
+ showBookDetailSheet(context, itemId);
}
- },
- // Long-press a book cover for the quick-actions sheet (podcasts skipped).
- onLongPress:
- (!widget.selectionMode &&
- gesturePolicy.allowsLongPressShortcuts &&
- itemId.isNotEmpty &&
- !lib.isPodcastLibrary)
- ? () => showQuickActionsSheet(
- context,
- itemId,
- initialItem: widget.item,
- )
- : null,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- // Cover
- AspectRatio(
- aspectRatio: widget.coverAspectRatio,
- child: ClipRRect(
- borderRadius: BorderRadius.circular(10),
- child: Stack(
- fit: StackFit.expand,
- children: [
- // Cover image
- coverUrl != null
- ? _blurCover(
- coverUrl,
- lib.mediaHeaders,
- cs,
- widget.coverAspectRatio,
- title,
- author,
- )
- : CoverPlaceholder(title: title, author: author),
+ }
+ },
+ // Long-press a book cover for the quick-actions sheet (podcasts skipped).
+ // Selection mode owns the gesture instead, so a long-press can't fire a
+ // sheet over a grid the user is ticking through.
+ onLongPress:
- (!widget.selectionMode && itemId.isNotEmpty && !lib.isPodcastLibrary)
++ (!widget.selectionMode &&
++ gesturePolicy.allowsLongPressShortcuts &&
++ itemId.isNotEmpty &&
++ !lib.isPodcastLibrary)
+ ? () => showQuickActionsSheet(context, itemId, initialItem: widget.item)
+ : null,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ // Cover
+ AspectRatio(
+ aspectRatio: widget.coverAspectRatio,
+ child: ClipRRect(
+ borderRadius: BorderRadius.circular(10),
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ // Cover image
+ coverUrl != null
+ ? _blurCover(coverUrl, lib.mediaHeaders, cs, widget.coverAspectRatio, title, author)
+ : CoverPlaceholder(title: title, author: author),
- // Progress bar at bottom of cover
- if (progress > 0 && !isFinished)
- Positioned(
- left: 0,
- right: 0,
- bottom: 0,
- child: LinearProgressIndicator(
- value: progress.clamp(0.0, 1.0),
- minHeight: 3,
- backgroundColor: Colors.black38,
- valueColor: AlwaysStoppedAnimation(cs.primary),
- ),
+ // Progress bar at bottom of cover
+ if (progress > 0 && !isFinished)
+ Positioned(
+ left: 0,
+ right: 0,
+ bottom: 0,
+ child: LinearProgressIndicator(
+ value: progress.clamp(0.0, 1.0),
+ minHeight: 3,
+ backgroundColor: Colors.black38,
+ valueColor: AlwaysStoppedAnimation(cs.primary),
),
+ ),
- // Unplayed-episode count badge (podcasts only)
- if (unfinishedCount > 0)
- Positioned(
- top: 4,
- right: 4,
- child: Container(
- padding: const EdgeInsets.symmetric(
- horizontal: 6,
- vertical: 2,
- ),
- decoration: BoxDecoration(
- color: cs.primary,
- borderRadius: BorderRadius.circular(10),
- ),
- child: Text(
- '$unfinishedCount',
- style: TextStyle(
- color: cs.onPrimary,
- fontSize: 10,
- fontWeight: FontWeight.w700,
- ),
+ // Unplayed-episode count badge (podcasts only)
+ if (unfinishedCount > 0)
+ Positioned(
+ top: 4,
+ right: 4,
+ child: Container(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 6, vertical: 2),
+ decoration: BoxDecoration(
+ color: cs.primary,
+ borderRadius: BorderRadius.circular(10),
+ ),
+ child: Text(
+ '$unfinishedCount',
+ style: TextStyle(
+ color: cs.onPrimary,
+ fontSize: 10,
+ fontWeight: FontWeight.w700,
),
),
),
@@@ -287,83 -280,65 +300,73 @@@
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: tt.labelSmall?.copyWith(
- fontWeight: FontWeight.w600,
- color: cs.onSurface,
- fontSize: 11,
+ color: cs.onSurfaceVariant.withValues(alpha: 0.75),
+ fontSize: 10 * coverGridTextScale(context),
),
),
- // Author
- if (author.isNotEmpty)
- Text(
- author,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: tt.labelSmall?.copyWith(
- color: cs.onSurfaceVariant,
- fontSize: 10,
- ),
+ // Author
+ if (author.isNotEmpty)
+ Text(
+ author,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: tt.labelSmall?.copyWith(
+ color: cs.onSurfaceVariant,
+ fontSize: 10 * coverGridTextScale(context),
),
- ],
- ),
+ ),
+ ],
+ ),
+ ),
);
}
- Widget _blurCover(String coverUrl, Map<String, String> headers, ColorScheme cs, double aspectRatio, String title, String author) {
+ Widget _blurCover(
+ String coverUrl,
+ Map<String, String> headers,
+ ColorScheme cs,
+ double aspectRatio,
+ String title,
+ String author,
+ ) {
final placeholder = CoverPlaceholder(title: title, author: author);
final isSquare = (aspectRatio - 1.0).abs() < 0.01;
+ final decodeWidth = coverGridDecodeWidth(context);
if (!isSquare) {
if (coverUrl.startsWith('/')) {
- return Image.file(
- File(coverUrl),
- fit: BoxFit.cover,
- errorBuilder: (_, __, ___) => placeholder,
- );
+ return Image.file(File(coverUrl), fit: BoxFit.cover,
+ cacheWidth: decodeWidth,
+ errorBuilder: (_, __, ___) => placeholder);
}
- return CachedNetworkImage(
- imageUrl: coverUrl,
- fit: BoxFit.cover,
- httpHeaders: headers,
- placeholder: (_, __) => placeholder,
- errorWidget: (_, __, ___) => placeholder,
- );
+ return CachedNetworkImage(imageUrl: coverUrl, fit: BoxFit.cover,
+ httpHeaders: headers, memCacheWidth: decodeWidth,
+ placeholder: (_, __) => placeholder,
+ errorWidget: (_, __, ___) => placeholder);
}
+ // The letterbox fill behind non-square art. A real gaussian here means one
+ // offscreen blur layer per tile, which piles up GPU memory on dense grids
+ // and gets the app OOM-killed mid-scroll - a tiny decode stretched to size
+ // looks the same under the scrim at tile sizes and costs nothing.
if (coverUrl.startsWith('/')) {
- return BlurPaddedCover(
- blurChild: Image.file(
- File(coverUrl),
- fit: BoxFit.cover,
- errorBuilder: (_, __, ___) => const SizedBox.shrink(),
- ),
- child: Image.file(
- File(coverUrl),
- fit: BoxFit.contain,
- errorBuilder: (_, __, ___) => placeholder,
- ),
- );
+ return Stack(fit: StackFit.expand, children: [
+ Image.file(File(coverUrl), fit: BoxFit.cover, cacheWidth: 32,
+ errorBuilder: (_, __, ___) => const SizedBox.shrink()),
+ Container(color: Colors.black.withValues(alpha: 0.15)),
+ Image.file(File(coverUrl), fit: BoxFit.contain,
+ cacheWidth: decodeWidth,
+ errorBuilder: (_, __, ___) => placeholder),
+ ]);
}
- return BlurPaddedCover(
- blurChild: CachedNetworkImage(
- imageUrl: coverUrl,
- fit: BoxFit.cover,
- httpHeaders: headers,
- errorWidget: (_, __, ___) => const SizedBox.shrink(),
- ),
- child: CachedNetworkImage(
- imageUrl: coverUrl,
- fit: BoxFit.contain,
- httpHeaders: headers,
- placeholder: (_, __) => placeholder,
- errorWidget: (_, __, ___) => placeholder,
- ),
- );
+ return Stack(fit: StackFit.expand, children: [
+ CachedNetworkImage(imageUrl: coverUrl, fit: BoxFit.cover,
+ httpHeaders: headers, memCacheWidth: 32,
+ errorWidget: (_, __, ___) => const SizedBox.shrink()),
+ Container(color: Colors.black.withValues(alpha: 0.15)),
+ CachedNetworkImage(imageUrl: coverUrl, fit: BoxFit.contain,
+ httpHeaders: headers, memCacheWidth: decodeWidth,
+ placeholder: (_, __) => placeholder,
+ errorWidget: (_, __, ___) => placeholder),
+ ]);
}
}
@@@ -680,11 -623,25 +663,26 @@@ class GridSeriesTileDirect extends Stat
final lib = context.watch<LibraryProvider>();
final auth = context.read<AuthProvider>();
- final seriesName = series['name'] as String? ?? l.libraryGridTilesUnknownSeries;
+ final seriesName =
+ series['name'] as String? ?? l.libraryGridTilesUnknownSeries;
final seriesId = series['id'] as String? ?? '';
final books = series['books'] as List<dynamic>? ?? [];
- final numBooks = books.length;
+ // Some servers send the series list without the books, carrying only
+ // libraryItemIds + numBooks (the collapsed-series shape). Covers, count and
+ // progress only need the ids, so fall back to those.
+ final itemIds = books.isNotEmpty
+ ? books
+ .map((b) => (b as Map<String, dynamic>)['id'] as String? ?? '')
+ .where((id) => id.isNotEmpty)
+ .toList()
+ : ((series['libraryItemIds'] as List<dynamic>?)
+ ?.map((e) => e.toString())
+ .toList() ??
+ const <String>[]);
+ final rawNumBooks = series['numBooks'] as int? ?? 0;
+ final numBooks = books.isNotEmpty
+ ? books.length
+ : (rawNumBooks > 0 ? rawNumBooks : itemIds.length);
// Get author from first book
String author = '';
diff --cc lib/widgets/library_lists_tab.dart
index 5501f736,8bc49830..b687ccaf
--- a/lib/widgets/library_lists_tab.dart
+++ b/lib/widgets/library_lists_tab.dart
@@@ -1,6 -1,6 +1,7 @@@
import 'package:flutter/material.dart';
+ import '../l10n/app_localizations.dart';
import '../screens/library_screen.dart';
+import '../utils/desktop_workspace.dart';
import 'library_grid_tiles.dart';
/// Library "Lists" tab: a stacked-cover grid of all collections and playlists
diff --cc lib/widgets/notes_sheet.dart
index 7e81e628,af489a68..d26667a6
--- a/lib/widgets/notes_sheet.dart
+++ b/lib/widgets/notes_sheet.dart
@@@ -6,7 -6,7 +6,8 @@@ import 'package:share_plus/share_plus.d
import 'package:url_launcher/url_launcher.dart';
import '../l10n/app_localizations.dart';
import '../services/notes_service.dart';
+import 'adaptive_modal.dart';
+ import '../utils/share_origin.dart';
/// Bottom sheet displaying notes for a library item.
class NotesSheet extends StatefulWidget {
diff --cc lib/widgets/series_books_sheet.dart
index 410641fb,46ef96af..1181956a
--- a/lib/widgets/series_books_sheet.dart
+++ b/lib/widgets/series_books_sheet.dart
@@@ -16,9 -21,9 +21,10 @@@ import 'book_detail_sheet.dart'
import 'library_grid_tiles.dart';
import 'episode_list_sheet.dart';
import 'stackable_sheet.dart';
+ import '../services/upcoming_releases_service.dart';
import 'audible_series_sheet.dart';
import 'action_pill.dart';
+import 'adaptive_modal.dart';
import 'books_sheet_shared.dart';
import '../services/api_service.dart';
import '../utils/duration_format.dart';
@@@ -778,23 -1195,37 +1197,38 @@@ class _SeriesBooksSheetState extends St
);
}
- void _showSeriesMoreSheet(ColorScheme cs, bool allDownloaded, int downloaded, bool allDone, bool hasSeriesId) {
+ /// The series actions. [tint] set on a pill means it is switched on.
+ List<ActionPillData> _actionPills(BuildContext ctx) {
final l = AppLocalizations.of(context)!;
- showAdaptiveActionMenu(
- context: context,
- backgroundColor: Theme.of(context).bottomSheetTheme.backgroundColor,
- shape: const RoundedRectangleBorder(
- borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
- ),
- builder: (ctx) {
- return SafeArea(
- child: Padding(
- padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
- child: Column(mainAxisSize: MainAxisSize.min, children: [
- Center(child: Container(width: 40, height: 4, margin: const EdgeInsets.only(bottom: 16),
- decoration: BoxDecoration(color: cs.onSurface.withValues(alpha: 0.24), borderRadius: BorderRadius.circular(2)))),
- ActionPillGrid(items: [
- if (!AppPlatform.isWeb && !allDownloaded)
+ final cs = Theme.of(context).colorScheme;
+ final allDone = _allFinished;
+ final dl = DownloadService();
+ var downloaded = 0;
+ for (final book in _books) {
+ if (dl.isDownloaded(book['id'] as String? ?? '')) downloaded++;
+ }
- final allDownloaded = downloaded == _books.length;
++ // Nothing downloads in a browser, so neither download pill shows there.
++ final allDownloaded = AppPlatform.isWeb || downloaded == _books.length;
+ final hasSeriesId = widget.seriesId != null && widget.seriesId!.isNotEmpty;
+ return [
+ // Only once the up next book is past the first few rows.
+ if (_jumpTargetIndex >= 3)
+ ActionPillData(
+ icon: Icons.keyboard_double_arrow_down_rounded,
+ label: l.seriesJumpToUpNext,
+ onTap: _jumpToUpNext),
- if (hasSeriesId)
++ if (!AppPlatform.isWeb && hasSeriesId)
+ ActionPillData(
+ icon: _autoDownloadEnabled ? Icons.downloading_rounded : Icons.download_outlined,
+ label: _autoDownloadEnabled ? l.turnAutoDownloadOff : l.turnAutoDownloadOn,
+ tint: _autoDownloadEnabled ? cs.primary : null,
+ onTap: () async {
+ final lib = context.read<LibraryProvider>();
+ await lib.toggleRollingDownload(widget.seriesId!,
+ name: widget.seriesName, kind: 'series');
+ if (mounted) setState(() => _autoDownloadEnabled = lib.isRollingDownloadEnabled(widget.seriesId!));
+ }),
+ if (!allDownloaded)
ActionPillData(
icon: Icons.download_rounded,
label: downloaded > 0 ? l.downloadRemainingCount((_totalBooks > 0 ? _totalBooks : _books.length) - downloaded) : l.downloadAll,
@@@ -832,25 -1262,18 +1265,18 @@@
if (confirmed == true) _markAllFinished();
}
}),
- if (hasSeriesId)
+ if (!AppPlatform.isWeb && hasSeriesId)
ActionPillData(
- icon: _autoDownloadEnabled ? Icons.downloading_rounded : Icons.download_outlined,
- label: _autoDownloadEnabled ? l.turnAutoDownloadOff : l.turnAutoDownloadOn,
+ icon: _scanExcluded ? Icons.visibility_rounded : Icons.visibility_off_rounded,
+ label: _scanExcluded ? l.seriesIncludeInScan : l.seriesExcludeFromScan,
onTap: () async {
- Navigator.pop(ctx);
- final lib = context.read<LibraryProvider>();
- await lib.toggleRollingDownload(widget.seriesId!,
- name: widget.seriesName, kind: 'series');
- setState(() => _autoDownloadEnabled = lib.isRollingDownloadEnabled(widget.seriesId!));
+ final next = !_scanExcluded;
+ await UpcomingReleasesService.setNeverScan(widget.seriesId!, next);
+ if (mounted) setState(() => _scanExcluded = next);
}),
ActionPillData(icon: Icons.search_rounded, label: l.seriesBooksFindMissingTitle,
- onTap: () { Navigator.pop(ctx); _findOnAudible(); }),
- ]),
- ]),
- ),
- );
- },
- );
+ onTap: _findOnAudible),
+ ];
}
Future<void> _downloadAll() async {
diff --cc packages/whisper_ggml_plus/lib/src/whisper_unsupported.dart
index 00000000,00000000..113aae52
new file mode 100644
--- /dev/null
+++ b/packages/whisper_ggml_plus/lib/src/whisper_unsupported.dart
@@@ -1,0 -1,0 +1,74 @@@
++// Absorb patch: the engine and its controller for platforms without dart:ffi
++// (the web). Same public surface as whisper.dart and whisper_controller.dart,
++// so the app compiles for the browser; every call reports that transcription
++// is not available there. Picked by the conditional exports in
++// whisper_ggml_plus.dart.
++import 'package:whisper_ggml_plus/src/models/whisper_model.dart';
++
++import 'models/requests/transcribe_request.dart';
++import 'models/requests/whisper_vad_mode.dart';
++import 'models/responses/whisper_transcribe_response.dart';
++import 'models/whisper_result.dart';
++import 'whisper_audio_convert.dart';
++
++UnsupportedError _unsupported() =>
++ UnsupportedError('On-device transcription is not available in a browser');
++
++class Whisper {
++ const Whisper({required this.model, this.modelDir});
++
++ final WhisperModel model;
++ final String? modelDir;
++
++ static final bool usesCompatEngine = false;
++
++ Future<({WhisperTranscribeResponse response, String? language})> transcribe({
++ required TranscribeRequest transcribeRequest,
++ required String modelPath,
++ }) async {
++ throw _unsupported();
++ }
++
++ Future<String?> getVersion() async => null;
++
++ Future<void> abort() async {}
++
++ Future<void> dispose() async {}
++}
++
++class WhisperController {
++ static void registerAudioConverter(WhisperAudioConverter converter) {}
++
++ Future<void> initModel(WhisperModel model) async {}
++
++ Future<TranscribeResult?> transcribe({
++ required WhisperModel model,
++ required String audioPath,
++ String lang = 'en',
++ bool diarize = false,
++ bool withTimestamps = true,
++ bool splitOnWord = false,
++ bool convert = true,
++ int threads = 6,
++ bool isTranslate = false,
++ bool speedUp = false,
++ bool noFallback = false,
++ WhisperVadMode vadMode = WhisperVadMode.auto,
++ String? vadModelPath,
++ }) async {
++ throw _unsupported();
++ }
++
++ // No model directory in a browser: nothing can be downloaded to it, so
++ // isModelDownloaded reads false and the app treats the model as missing.
++ static Future<String> getModelDir() async => '';
++
++ Future<String> getPath(WhisperModel model) async =>
++ 'ggml-${model.modelName}.bin';
++
++ Future<String> downloadModel(WhisperModel model) async {
++ throw _unsupported();
++ }
++
++ Future<void> dispose({WhisperModel model = WhisperModel.base}) async {}
++}
diff --cc packages/whisper_ggml_plus/lib/whisper_ggml_plus.dart
index 00000000,e6d0bab5..37e09365
mode 000000,100644..100644
--- a/packages/whisper_ggml_plus/lib/whisper_ggml_plus.dart
+++ b/packages/whisper_ggml_plus/lib/whisper_ggml_plus.dart
@@@ -1,0 -1,5 +1,7 @@@
+ export 'src/models/whisper_model.dart';
-export 'src/whisper.dart';
++// Absorb patch: the ffi engine only where dart:ffi exists; the browser gets
++// a stub with the same surface that reports transcription as unavailable.
++export 'src/whisper_unsupported.dart' if (dart.library.ffi) 'src/whisper.dart';
+ export 'src/whisper_audio_convert.dart';
-export 'src/whisper_controller.dart';
++export 'src/whisper_unsupported.dart' if (dart.library.ffi) 'src/whisper_controller.dart';
+ export 'src/models/_models.dart';