A cross platform Audiobookshelf client for Android and iOS
Dart
Read along improvements and catch up pop up
Barnabas2bdbf3105b24
diff --git a/lib/build_info.dart b/lib/build_info.dartindex 70abad43..7c86822f 100644--- a/lib/build_info.dart+++ b/lib/build_info.dart@@ -2,7 +2,7 @@/// the same commit as the version bump for each beta. Full releases use an/// even patch number and never show it, so a stale value can't leak into a/// stable build - it only has to be right during a beta cycle.-const int kBetaNumber = 7;+const int kBetaNumber = 8;/// The beta number to show for [version] (`1.9.3+240` or `1.9.3`), or null/// when this isn't a beta build. Odd patch = beta cycle, even = full release.diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arbindex c0f26e18..8473229c 100644--- a/lib/l10n/app_en.arb+++ b/lib/l10n/app_en.arb@@ -5061,5 +5061,8 @@"findInAudiobookAfterLabel": "When the spot is found","findInAudiobookStay": "Keep reading","findInAudiobookGoPlayer": "Open the player",- "findInAudiobookPlaying": "Playing this passage in the audiobook"+ "findInAudiobookPlaying": "Playing this passage in the audiobook",+ "catchUpAudioAhead": "The audiobook is further along. Tap to go there.",+ "catchUpPageAhead": "This page is ahead of the audiobook. Tap to move the audiobook here.",+ "readerShortcutButton": "Shortcut button"}diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dartindex f7155867..a362df71 100644--- a/lib/l10n/app_localizations.dart+++ b/lib/l10n/app_localizations.dart@@ -15548,6 +15548,24 @@ abstract class AppLocalizations {/// In en, this message translates to:/// **'Playing this passage in the audiobook'**String get findInAudiobookPlaying;++ /// No description provided for @catchUpAudioAhead.+ ///+ /// In en, this message translates to:+ /// **'The audiobook is further along. Tap to go there.'**+ String get catchUpAudioAhead;++ /// No description provided for @catchUpPageAhead.+ ///+ /// In en, this message translates to:+ /// **'This page is ahead of the audiobook. Tap to move the audiobook here.'**+ String get catchUpPageAhead;++ /// No description provided for @readerShortcutButton.+ ///+ /// In en, this message translates to:+ /// **'Shortcut button'**+ String get readerShortcutButton;}class _AppLocalizationsDelegatediff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dartindex 8a9d127f..3a46446c 100644--- a/lib/l10n/app_localizations_de.dart+++ b/lib/l10n/app_localizations_de.dart@@ -9146,4 +9146,15 @@ class AppLocalizationsDe extends AppLocalizations {@overrideString get findInAudiobookPlaying => 'Playing this passage in the audiobook';++ @override+ String get catchUpAudioAhead =>+ 'The audiobook is further along. Tap to go there.';++ @override+ String get catchUpPageAhead =>+ 'This page is ahead of the audiobook. Tap to move the audiobook here.';++ @override+ String get readerShortcutButton => 'Shortcut button';}diff --git a/lib/l10n/app_localizations_el.dart b/lib/l10n/app_localizations_el.dartindex 1f6c6506..da79134b 100644--- a/lib/l10n/app_localizations_el.dart+++ b/lib/l10n/app_localizations_el.dart@@ -9025,4 +9025,15 @@ class AppLocalizationsEl extends AppLocalizations {@overrideString get findInAudiobookPlaying => 'Playing this passage in the audiobook';++ @override+ String get catchUpAudioAhead =>+ 'The audiobook is further along. Tap to go there.';++ @override+ String get catchUpPageAhead =>+ 'This page is ahead of the audiobook. Tap to move the audiobook here.';++ @override+ String get readerShortcutButton => 'Shortcut button';}diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dartindex 620ba2d6..11e33b71 100644--- a/lib/l10n/app_localizations_en.dart+++ b/lib/l10n/app_localizations_en.dart@@ -9025,4 +9025,15 @@ class AppLocalizationsEn extends AppLocalizations {@overrideString get findInAudiobookPlaying => 'Playing this passage in the audiobook';++ @override+ String get catchUpAudioAhead =>+ 'The audiobook is further along. Tap to go there.';++ @override+ String get catchUpPageAhead =>+ 'This page is ahead of the audiobook. Tap to move the audiobook here.';++ @override+ String get readerShortcutButton => 'Shortcut button';}diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dartindex 7ee312bd..0ffa7784 100644--- a/lib/l10n/app_localizations_es.dart+++ b/lib/l10n/app_localizations_es.dart@@ -9027,4 +9027,15 @@ class AppLocalizationsEs extends AppLocalizations {@overrideString get findInAudiobookPlaying => 'Playing this passage in the audiobook';++ @override+ String get catchUpAudioAhead =>+ 'The audiobook is further along. Tap to go there.';++ @override+ String get catchUpPageAhead =>+ 'This page is ahead of the audiobook. Tap to move the audiobook here.';++ @override+ String get readerShortcutButton => 'Shortcut button';}diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dartindex 93eaa37a..3d3222fb 100644--- a/lib/l10n/app_localizations_fr.dart+++ b/lib/l10n/app_localizations_fr.dart@@ -9078,4 +9078,15 @@ class AppLocalizationsFr extends AppLocalizations {@overrideString get findInAudiobookPlaying => 'Playing this passage in the audiobook';++ @override+ String get catchUpAudioAhead =>+ 'The audiobook is further along. Tap to go there.';++ @override+ String get catchUpPageAhead =>+ 'This page is ahead of the audiobook. Tap to move the audiobook here.';++ @override+ String get readerShortcutButton => 'Shortcut button';}diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dartindex 4ce902f6..7ae0b9ea 100644--- a/lib/l10n/app_localizations_it.dart+++ b/lib/l10n/app_localizations_it.dart@@ -9025,4 +9025,15 @@ class AppLocalizationsIt extends AppLocalizations {@overrideString get findInAudiobookPlaying => 'Playing this passage in the audiobook';++ @override+ String get catchUpAudioAhead =>+ 'The audiobook is further along. Tap to go there.';++ @override+ String get catchUpPageAhead =>+ 'This page is ahead of the audiobook. Tap to move the audiobook here.';++ @override+ String get readerShortcutButton => 'Shortcut button';}diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dartindex ab1db14f..1bae5e5c 100644--- a/lib/l10n/app_localizations_ja.dart+++ b/lib/l10n/app_localizations_ja.dart@@ -9025,4 +9025,15 @@ class AppLocalizationsJa extends AppLocalizations {@overrideString get findInAudiobookPlaying => 'Playing this passage in the audiobook';++ @override+ String get catchUpAudioAhead =>+ 'The audiobook is further along. Tap to go there.';++ @override+ String get catchUpPageAhead =>+ 'This page is ahead of the audiobook. Tap to move the audiobook here.';++ @override+ String get readerShortcutButton => 'Shortcut button';}diff --git a/lib/l10n/app_localizations_no.dart b/lib/l10n/app_localizations_no.dartindex f411002d..0fa8cb44 100644--- a/lib/l10n/app_localizations_no.dart+++ b/lib/l10n/app_localizations_no.dart@@ -9025,4 +9025,15 @@ class AppLocalizationsNo extends AppLocalizations {@overrideString get findInAudiobookPlaying => 'Playing this passage in the audiobook';++ @override+ String get catchUpAudioAhead =>+ 'The audiobook is further along. Tap to go there.';++ @override+ String get catchUpPageAhead =>+ 'This page is ahead of the audiobook. Tap to move the audiobook here.';++ @override+ String get readerShortcutButton => 'Shortcut button';}diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dartindex 87ee1fcb..f5b44c5f 100644--- a/lib/l10n/app_localizations_pt.dart+++ b/lib/l10n/app_localizations_pt.dart@@ -9025,4 +9025,15 @@ class AppLocalizationsPt extends AppLocalizations {@overrideString get findInAudiobookPlaying => 'Playing this passage in the audiobook';++ @override+ String get catchUpAudioAhead =>+ 'The audiobook is further along. Tap to go there.';++ @override+ String get catchUpPageAhead =>+ 'This page is ahead of the audiobook. Tap to move the audiobook here.';++ @override+ String get readerShortcutButton => 'Shortcut button';}diff --git a/lib/l10n/app_localizations_ro.dart b/lib/l10n/app_localizations_ro.dartindex 050264ae..2a204995 100644--- a/lib/l10n/app_localizations_ro.dart+++ b/lib/l10n/app_localizations_ro.dart@@ -9025,4 +9025,15 @@ class AppLocalizationsRo extends AppLocalizations {@overrideString get findInAudiobookPlaying => 'Playing this passage in the audiobook';++ @override+ String get catchUpAudioAhead =>+ 'The audiobook is further along. Tap to go there.';++ @override+ String get catchUpPageAhead =>+ 'This page is ahead of the audiobook. Tap to move the audiobook here.';++ @override+ String get readerShortcutButton => 'Shortcut button';}diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dartindex 707ad4e0..018dfd66 100644--- a/lib/l10n/app_localizations_ru.dart+++ b/lib/l10n/app_localizations_ru.dart@@ -9030,4 +9030,15 @@ class AppLocalizationsRu extends AppLocalizations {@overrideString get findInAudiobookPlaying => 'Playing this passage in the audiobook';++ @override+ String get catchUpAudioAhead =>+ 'The audiobook is further along. Tap to go there.';++ @override+ String get catchUpPageAhead =>+ 'This page is ahead of the audiobook. Tap to move the audiobook here.';++ @override+ String get readerShortcutButton => 'Shortcut button';}diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dartindex 31458f0b..0b8274ab 100644--- a/lib/l10n/app_localizations_zh.dart+++ b/lib/l10n/app_localizations_zh.dart@@ -8933,4 +8933,15 @@ class AppLocalizationsZh extends AppLocalizations {@overrideString get findInAudiobookPlaying => 'Playing this passage in the audiobook';++ @override+ String get catchUpAudioAhead =>+ 'The audiobook is further along. Tap to go there.';++ @override+ String get catchUpPageAhead =>+ 'This page is ahead of the audiobook. Tap to move the audiobook here.';++ @override+ String get readerShortcutButton => 'Shortcut button';}diff --git a/lib/services/backup_service.dart b/lib/services/backup_service.dartindex 5c46e1fa..aaac1a2d 100644--- a/lib/services/backup_service.dart+++ b/lib/services/backup_service.dart@@ -328,6 +328,7 @@ class BackupService {'spread': await ScopedPrefs.getInt('ereader_spread'),'theme': await ScopedPrefs.getString('ereader_theme'),'font': await ScopedPrefs.getString('ereader_font'),+ 'barAction': await ScopedPrefs.getString('ereader_bar_action'),'volumeNav': await PlayerSettings.getEreaderVolumeNav(),'volumeNavWhilePlaying': await PlayerSettings.getEreaderVolumeNavWhilePlaying(),};@@ -996,6 +997,7 @@ class BackupService {if (er['marginV'] != null) await ScopedPrefs.setInt('ereader_margin_v', er['marginV'] as int);if (er['spread'] != null) await ScopedPrefs.setInt('ereader_spread', er['spread'] as int);if (er['theme'] != null) await ScopedPrefs.setString('ereader_theme', er['theme'] as String);+ if (er['barAction'] != null) await ScopedPrefs.setString('ereader_bar_action', er['barAction'] as String);if (er['font'] != null) {final fontId = er['font'] as String;await ScopedPrefs.setString('ereader_font', fontId);diff --git a/lib/services/transcription_service.dart b/lib/services/transcription_service.dartindex c81553b7..7178db35 100644--- a/lib/services/transcription_service.dart+++ b/lib/services/transcription_service.dart@@ -16,6 +16,7 @@ import 'api_service.dart';import 'download_service.dart';import 'player_settings.dart';import 'remote_audio_slice.dart';+import '../utils/whisper_language.dart';/// On-device bookmark transcription using Whisper (whisper.cpp via/// whisper_ggml_plus). Opt-in. Downloaded books decode from their files;@@ -165,6 +166,34 @@ class TranscriptionService {// window and pass the answer explicitly from then on.final Map<String, String> _bookLang = {};+ // The book's metadata language as a Whisper code, so a tagged book skips+ // detection altogether.+ final Map<String, String> _metadataLang = {};++ String _langFor(String? itemId) {+ if (itemId == null) return 'auto';+ final known = _bookLang[itemId] ?? _metadataLang[itemId];+ if (known != null) return known;+ // Streamed books get theirs from the item fetch in _streamTracksFor.+ final raw = DownloadService().getCachedSessionData(itemId);+ if (raw == null || raw.isEmpty) return 'auto';+ String? named;+ try {+ final session = jsonDecode(raw) as Map<String, dynamic>;+ final meta = session['mediaMetadata'] as Map<String, dynamic>?;+ named = whisperLanguageCode(meta?['language'] as String?);+ } catch (_) {}+ if (named == null) return 'auto';+ _rememberMetadataLanguage(itemId, named);+ return named;+ }++ void _rememberMetadataLanguage(String itemId, String code) {+ if (_metadataLang.containsKey(itemId)) return;+ _metadataLang[itemId] = code;+ debugPrint('[Transcribe] $itemId is tagged "$code", skipping detection');+ }+// Model managementFuture<String> _modelDir() => WhisperController.getModelDir();@@ -273,6 +302,9 @@ class TranscriptionService {final item = await api.getLibraryItem(apiItemId);final media = item?['media'] as Map<String, dynamic>?;if (media == null) return null;+ final named = whisperLanguageCode(+ (media['metadata'] as Map<String, dynamic>?)?['language'] as String?);+ if (named != null) _rememberMetadataLanguage(itemId, named);final raw = <Map<String, dynamic>>[];if (isEpisode) {final episodeId = itemId.substring(37);@@ -506,7 +538,7 @@ class TranscriptionService {// inferred rather than naming it. `.transcription` is a (exported)// WhisperTranscribeResponse whose `.text` is the full transcript.final String text;- final lang = _bookLang[itemId] ?? 'auto';+ final lang = _langFor(itemId);try {_markStep('audio decoded, running whisper ${info.fileName}');final result = await _whisper.transcribe(@@ -597,7 +629,7 @@ class TranscriptionService {}final List<({double start, double end, String text})> segments;- final lang = _bookLang[itemId] ?? 'auto';+ final lang = _langFor(itemId);try {_markStep('audio decoded, running whisper ${info.fileName}');final result = await _whisper.transcribe(@@ -694,7 +726,7 @@ class TranscriptionService {_busy = true;final watch = Stopwatch()..start();try {- final lang = itemId == null ? 'auto' : (_bookLang[itemId] ?? 'auto');+ final lang = _langFor(itemId);final String text;try {_markStep('audio decoded, running whisper ${info.fileName}');@@ -740,7 +772,7 @@ class TranscriptionService {lastModelUsed = info.size;_busy = true;try {- final lang = itemId == null ? 'auto' : (_bookLang[itemId] ?? 'auto');+ final lang = _langFor(itemId);final List<({double start, double end, String text})> segments;try {_markStep('audio decoded, running whisper ${info.fileName}');diff --git a/lib/utils/chapter_title_match.dart b/lib/utils/chapter_title_match.dartnew file mode 100644index 00000000..92df671e--- /dev/null+++ b/lib/utils/chapter_title_match.dart@@ -0,0 +1,139 @@+/// 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;+}++const _units = {+ '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,+};+const _tens = {+ 'twenty': 20, 'thirty': 30, 'forty': 40, 'fifty': 50, 'sixty': 60,+ 'seventy': 70, 'eighty': 80, 'ninety': 90,+};+const _ordinals = {+ 'first': 1, 'second': 2, 'third': 3, 'fourth': 4, 'fifth': 5, 'sixth': 6,+ 'seventh': 7, 'eighth': 8, 'ninth': 9, 'tenth': 10, 'eleventh': 11,+ 'twelfth': 12, 'thirteenth': 13, 'fourteenth': 14, 'fifteenth': 15,+ 'sixteenth': 16, 'seventeenth': 17, 'eighteenth': 18, 'nineteenth': 19,+ 'twentieth': 20, 'thirtieth': 30, 'fortieth': 40, 'fiftieth': 50,+ 'sixtieth': 60, 'seventieth': 70, 'eightieth': 80, 'ninetieth': 90,+};+const _headings = {+ 'chapter', 'ch', 'part', 'book', 'section', 'volume', 'vol', 'act',+ 'scene', 'episode', 'letter', 'canto',+};+const _romanValues = {'i': 1, 'v': 5, 'x': 10, 'l': 50, 'c': 100};+const _romanNumerals = [+ (100, 'c'), (90, 'xc'), (50, 'l'), (40, 'xl'), (10, 'x'), (9, 'ix'),+ (5, 'v'), (4, 'iv'), (1, 'i'),+];++/// [w] as a roman numeral, only when written the standard way.+int? _roman(String w) {+ if (w.isEmpty || w.length > 9) return null;+ var total = 0, highest = 0;+ for (var i = w.length - 1; i >= 0; i--) {+ final v = _romanValues[w[i]];+ if (v == null) return null;+ total += v < highest ? -v : v;+ if (v > highest) highest = v;+ }+ if (total <= 0) return null;+ var rest = total;+ final back = StringBuffer();+ for (final (value, numeral) in _romanNumerals) {+ while (rest >= value) {+ back.write(numeral);+ rest -= value;+ }+ }+ return back.toString() == w ? total : null;+}++/// Title words with numbers collapsed to digit tokens ("thirty nine" -> "39").+/// Ordinals and roman numerals only count as the chapter's number ("Chapter+/// XII", "Part the Second", "IV. The Duel"), not inside "What I Did".+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();+ bool numeral(String w) =>+ int.tryParse(w) != null ||+ _units.containsKey(w) ||+ _tens.containsKey(w) ||+ _ordinals.containsKey(w) ||+ _roman(w) != null;+ final onlyNumeral = raw.every((w) => w == 'the' || numeral(w));+ final leadingRoman = RegExp(r'^\s*[ivxlc]+\s*[.:)\-\u2013\u2014]',+ caseSensitive: false)+ .hasMatch(s);+ bool afterHeading(int i) {+ var j = i - 1;+ if (j >= 0 && raw[j] == 'the') j--;+ return j >= 0 && _headings.contains(raw[j]);+ }+ bool beforeHeading(int i) =>+ i + 1 < raw.length && _headings.contains(raw[i + 1]);++ final out = <String>{};+ for (var i = 0; i < raw.length; i++) {+ final w = raw[i];+ final tens = _tens[w];+ if (tens != null) {+ final next = i + 1 < raw.length ? raw[i + 1] : null;+ final unit = next == null ? null : _units[next];+ if (unit != null && unit < 10) {+ out.add('${tens + unit}');+ i++;+ continue;+ }+ final ordinal = next == null ? null : _ordinals[next];+ if (ordinal != null &&+ ordinal < 10 &&+ (onlyNumeral || afterHeading(i) || beforeHeading(i + 1))) {+ out.add('${tens + ordinal}');+ i++;+ continue;+ }+ out.add('$tens');+ continue;+ }+ final unit = _units[w];+ if (unit != null) {+ out.add('$unit');+ continue;+ }+ final ordinal = _ordinals[w];+ if (ordinal != null &&+ (onlyNumeral || afterHeading(i) || beforeHeading(i))) {+ out.add('$ordinal');+ continue;+ }+ final roman = _roman(w);+ if (roman != null &&+ (onlyNumeral || afterHeading(i) || (i == 0 && leadingRoman))) {+ out.add('$roman');+ continue;+ }+ out.add(w);+ }+ return out;+}diff --git a/lib/utils/whisper_language.dart b/lib/utils/whisper_language.dartnew file mode 100644index 00000000..af44eaec--- /dev/null+++ b/lib/utils/whisper_language.dart@@ -0,0 +1,71 @@+// Whisper's languages by code. whisper.cpp does not fall back to detection+// on a code outside this table, so nothing else may be passed to it.+const _whisperLanguages = {+ 'en': 'english', 'zh': 'chinese', 'de': 'german', 'es': 'spanish',+ 'ru': 'russian', 'ko': 'korean', 'fr': 'french', 'ja': 'japanese',+ 'pt': 'portuguese', 'tr': 'turkish', 'pl': 'polish', 'ca': 'catalan',+ 'nl': 'dutch', 'ar': 'arabic', 'sv': 'swedish', 'it': 'italian',+ 'id': 'indonesian', 'hi': 'hindi', 'fi': 'finnish', 'vi': 'vietnamese',+ 'he': 'hebrew', 'uk': 'ukrainian', 'el': 'greek', 'ms': 'malay',+ 'cs': 'czech', 'ro': 'romanian', 'da': 'danish', 'hu': 'hungarian',+ 'ta': 'tamil', 'no': 'norwegian', 'th': 'thai', 'ur': 'urdu',+ 'hr': 'croatian', 'bg': 'bulgarian', 'lt': 'lithuanian', 'la': 'latin',+ 'mi': 'maori', 'ml': 'malayalam', 'cy': 'welsh', 'sk': 'slovak',+ 'te': 'telugu', 'fa': 'persian', 'lv': 'latvian', 'bn': 'bengali',+ 'sr': 'serbian', 'az': 'azerbaijani', 'sl': 'slovenian', 'kn': 'kannada',+ 'et': 'estonian', 'mk': 'macedonian', 'br': 'breton', 'eu': 'basque',+ 'is': 'icelandic', 'hy': 'armenian', 'ne': 'nepali', 'mn': 'mongolian',+ 'bs': 'bosnian', 'kk': 'kazakh', 'sq': 'albanian', 'sw': 'swahili',+ 'gl': 'galician', 'mr': 'marathi', 'pa': 'punjabi', 'si': 'sinhala',+ 'km': 'khmer', 'sn': 'shona', 'yo': 'yoruba', 'so': 'somali',+ 'af': 'afrikaans', 'oc': 'occitan', 'ka': 'georgian', 'be': 'belarusian',+ 'tg': 'tajik', 'sd': 'sindhi', 'gu': 'gujarati', 'am': 'amharic',+ 'yi': 'yiddish', 'lo': 'lao', 'uz': 'uzbek', 'fo': 'faroese',+ 'ht': 'haitian creole', 'ps': 'pashto', 'tk': 'turkmen', 'nn': 'nynorsk',+ 'mt': 'maltese', 'sa': 'sanskrit', 'lb': 'luxembourgish', 'my': 'myanmar',+ 'bo': 'tibetan', 'tl': 'tagalog', 'mg': 'malagasy', 'as': 'assamese',+ 'tt': 'tatar', 'haw': 'hawaiian', 'ln': 'lingala', 'ha': 'hausa',+ 'ba': 'bashkir', 'jw': 'javanese', 'su': 'sundanese',+};++const _aliases = {+ 'eng': 'en', 'deu': 'de', 'ger': 'de', 'fra': 'fr', 'fre': 'fr',+ 'spa': 'es', 'ita': 'it', 'por': 'pt', 'nld': 'nl', 'dut': 'nl',+ 'rus': 'ru', 'jpn': 'ja', 'zho': 'zh', 'chi': 'zh', 'kor': 'ko',+ 'pol': 'pl', 'swe': 'sv', 'nor': 'no', 'nob': 'no', 'nb': 'no',+ 'dan': 'da', 'fin': 'fi', 'ell': 'el', 'gre': 'el', 'ron': 'ro',+ 'rum': 'ro', 'ces': 'cs', 'cze': 'cs', 'hun': 'hu', 'tur': 'tr',+ 'ukr': 'uk', 'ara': 'ar', 'heb': 'he', 'iw': 'he', 'hin': 'hi',+ 'cat': 'ca', 'lat': 'la', 'ind': 'id', 'vie': 'vi', 'tha': 'th',+ 'deutsch': 'de', 'español': 'es', 'espanol': 'es', 'castellano': 'es',+ 'castilian': 'es', 'français': 'fr', 'francais': 'fr', 'italiano': 'it',+ 'português': 'pt', 'portugues': 'pt', 'nederlands': 'nl', 'flemish': 'nl',+ 'русский': 'ru', '日本語': 'ja', '中文': 'zh', 'mandarin': 'zh',+ '한국어': 'ko', 'polski': 'pl', 'svenska': 'sv', 'norsk': 'no',+ 'bokmål': 'no', 'dansk': 'da', 'suomi': 'fi', 'ελληνικά': 'el',+ 'română': 'ro', 'romana': 'ro', 'čeština': 'cs', 'cestina': 'cs',+ 'magyar': 'hu', 'türkçe': 'tr', 'turkce': 'tr', 'українська': 'uk',+ 'burmese': 'my', 'farsi': 'fa', 'filipino': 'tl',+};++/// The Whisper code for a metadata language ("English", "eng", "en-US"), or+/// null when it names no single language the engine knows.+String? whisperLanguageCode(String? raw) {+ if (raw == null) return null;+ final s = raw.toLowerCase().replaceAll(RegExp(r'\([^)]*\)'), ' ').trim();+ if (s.isEmpty || RegExp(r'[,;/&+]|\band\b').hasMatch(s)) return null;+ String? known(String v) {+ if (_whisperLanguages.containsKey(v)) return v;+ final alias = _aliases[v];+ if (alias != null) return alias;+ for (final e in _whisperLanguages.entries) {+ if (e.value == v) return e.key;+ }+ return null;+ }+ final direct = known(s);+ if (direct != null) return direct;+ // "en-US", "pt_BR": the region says nothing Whisper can use.+ final tag = RegExp(r'^([a-z]{2,3})[-_][a-z0-9]{2,8}$').firstMatch(s);+ return tag == null ? null : known(tag.group(1)!);+}diff --git a/lib/widgets/ebook_reader_view.dart b/lib/widgets/ebook_reader_view.dartindex 163e5d70..4a68e2a5 100644--- a/lib/widgets/ebook_reader_view.dart+++ b/lib/widgets/ebook_reader_view.dart@@ -31,17 +31,28 @@ import '../services/sync_point_store.dart';import '../services/transcript_line_store.dart';import '../services/transcription_service.dart';import '../services/volume_key_service.dart';+import '../utils/chapter_title_match.dart';import 'overlay_toast.dart';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_button_config.dart' show buttonDefById, localizedCardButtonLabel;+import 'card_buttons.dart'+ show CardSpeedSheet, MoreMenuItem, SimpleBookmarkSheet, showInactiveToast;import 'card_chapters_sheet.dart';import 'chromecast_button.dart';import 'equalizer_sheet.dart';import 'sleep_timer_sheet.dart';+typedef _ReaderAction = ({+ IconData icon,+ String label,+ Color? tint,+ bool enabled,+ VoidCallback onTap,+});+/// Reader background/text presets (e-reader themes). Colors are hex so they/// feed both the WebView CSS and the Flutter overlays.class _ReaderPalette {@@ -174,6 +185,12 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs// Read along: follow the audiobook by coloring the words being spoken.bool _readAlongOn = false;bool _didAutoReadAlong = false;+ // Backgrounding stops read along; this brings it back on return.+ bool _readAlongResume = false;+ // Catch up offers: each direction is offered once per visit.+ bool _didScheduleCatchUp = false;+ bool _offeredPageToAudio = false;+ bool _offeredAudioToPage = false;// Listening ahead: the runway fills faster with the playhead standing// still, and nobody wants to hear words the page can't show yet. Armed at// start; the first gated tick pauses a playing book (resumed by itself@@ -257,6 +274,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsstatic const _kFont = 'ereader_font';static const _kPinTop = 'ereader_pin_top';static const _kKeepAwake = 'ereader_keep_awake';+ static const _kBarAction = 'ereader_bar_action';// Gates the WebView mount until the entering route animation completes, so// the heavy platform view doesn't stutter the open transition.@@ -274,6 +292,8 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsString _audioAuthor = '';String? _audioCoverUrl;bool _startingAudio = false;+ // Which control sits in the player bar's left slot.+ String _barAction = 'speed';// Held from initState so dispose can lift the quiet without a context read.late final LibraryProvider _quietLib;@@ -325,13 +345,18 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsfinal drifted = _bgDrifted;_bgCfi = null;_bgDrifted = false;+ final resumeReadAlong = _readAlongResume;+ _readAlongResume = false;if (drifted && cfi != null && cfi.isNotEmpty) {Future.delayed(const Duration(milliseconds: 350), () async {if (!mounted || !_readerActive) return;await _epubController?.display(cfi: cfi);// The live page moved under the blind; re-seat it on the page after.if (_autoScroll) await _epubController?.autoScrollResync();+ if (resumeReadAlong) await _resumeReadAlong();});+ } else if (resumeReadAlong) {+ unawaited(_resumeReadAlong());}} else if (state == AppLifecycleState.paused ||state == AppLifecycleState.hidden) {@@ -343,6 +368,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs// a second, and nobody is reading a page they can't see.if (_readAlongOn) {debugPrint('[ReadAlong] app backgrounded - stopping');+ _readAlongResume = true;_stopReadAlong();}} else {@@ -389,7 +415,9 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObslibraryId: lib.selectedLibraryId,fromUi: true,);- if (mounted) setState(() => _startingAudio = false);+ if (!mounted) return;+ setState(() => _startingAudio = false);+ unawaited(_maybeOfferCatchUp(audioStarting: true));}void _loadSkipSettings() {@@ -436,6 +464,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs_fontId = await ScopedPrefs.getString(_kFont) ?? 'original';_pinTop = await ScopedPrefs.getBool(_kPinTop) ?? false;_keepAwake = await ScopedPrefs.getBool(_kKeepAwake) ?? true;+ _barAction = await ScopedPrefs.getString(_kBarAction) ?? 'speed';if (mounted) _syncScreenWake();_volumeNavMode = await PlayerSettings.getEreaderVolumeNav();_volumeNavWhilePlaying = await PlayerSettings.getEreaderVolumeNavWhilePlaying();@@ -2273,14 +2302,15 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs/// Runs the whole Find in ebook flow: fuzzy-locate the transcript, decide/// whether the best hit is trustworthy, then jump + flash or toast and stay.- Future<void> _runFindInEbook(String transcript, String? chapterHint) async {+ Future<void> _runFindInEbook(String transcript, String? chapterHint,+ {double? positionSeconds}) async {final l = AppLocalizations.of(context)!;if (_finding) return;setState(() => _finding = true);showProgressDialog(context, l.findInEbookSearching);Map<String, dynamic>? decision;- final pos = widget.findPositionSeconds;+ final pos = positionSeconds ?? widget.findPositionSeconds;var windowSeconds = findInEbookWindowSeconds;try {decision = await _decideFindTarget(transcript, chapterHint,@@ -2363,7 +2393,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsif (nearSeconds != null) hintBases.addAll(await _syncHintBases(nearSeconds));if (chapterHint != null) {for (final ch in _chapters) {- if (_chapterTitlesAgree(chapterHint, ch.title)) {+ if (chapterTitlesAgree(chapterHint, ch.title)) {final base = ch.href.split('#').first.split('/').last.toLowerCase();if (base.isNotEmpty && !hintBases.contains(base)) hintBases.add(base);}@@ -2383,7 +2413,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsdouble scoreOf(Map<String, dynamic> c) {final fine = (c['fine'] as num?)?.toDouble() ?? 0;final agrees = chapterHint != null &&- _chapterTitlesAgree(chapterHint, _chapterForHref(c['href'] as String? ?? '') ?? '');+ chapterTitlesAgree(chapterHint, _chapterForHref(c['href'] as String? ?? '') ?? '');return fine + (agrees ? _findHintBonus : 0);}@@ -2451,63 +2481,6 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs);}- /// 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@@ -2701,6 +2674,193 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs// 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;+ static const double _catchUpMinGapSeconds = 300;++ /// Where the audiobook should be for the page at [cfi] and the range it+ /// could sit in, from sync points or a uniquely named audio chapter. Nothing+ /// is transcribed.+ Future<({double est, double lo, double hi})?> _audioEstimateForPage(+ String cfi) async {+ final api = context.read<AuthProvider>().apiService;+ final info = await _selectionSectionInfo(cfi, '');+ if (info == null) return null;+ final si = (info['si'] as num).toInt();+ final offset = (info['offset'] as num).toDouble();+ final total = (info['total'] as num).toDouble();+ if (total <= 0 || offset < 0) return null;+ final audio = await resolveAudioChapters(widget.itemId, api);+ if (audio.duration <= 0) return null;+ final spine = await _spineHrefs();+ await SyncPointStore.instance.load(+ widget.itemId,+ audioDuration: audio.duration,+ spineLength: spine.isEmpty ? null : spine.length,+ );+ final sync = await _syncPointCandidate(+ si: si,+ offset: offset,+ total: total,+ fallbackRate: _fallbackSecPerChar,+ top: audio.duration);+ if (sync != null) return (est: sync.est, lo: sync.lo, hi: sync.hi);+ // A title that several audio chapters share can't place the page.+ final tocTitle = _chapterForHref(info['href'] as String? ?? '');+ final named = [+ for (final ch in audio.chapters)+ if (ch is Map<String, dynamic> &&+ chapterTitlesAgree(ch['title'] as String?, tocTitle))+ ch,+ ];+ if (named.length != 1) return null;+ final a =+ _chapterAnchorEstimate(named.first, offset, total, audio.duration);+ return (est: a.est, lo: a.lo, hi: a.hi);+ }++ /// Offers to close a big gap between the page and the audiobook. Opening+ /// the book only offers going to the audio; starting audio from here+ /// ([audioStarting]) can offer either. Nothing moves until the toast is tapped.+ Future<void> _maybeOfferCatchUp({required bool audioStarting}) async {+ if (!mounted || !_readerActive || !_hasAudio || !_transcriptionOn) return;+ if (_readAlongOn || _finding) return;+ // These opens put a page on screen that is not where the reading stopped.+ if (widget.findText != null ||+ widget.openAtCfi != null ||+ widget.startReadAlong) {+ return;+ }+ if (_offeredPageToAudio && (_offeredAudioToPage || !audioStarting)) return;+ final cfi = _currentCfi;+ if (cfi == null || cfi.isEmpty) return;+ final transcription = TranscriptionService.instance;+ if (!transcription.canTranscribeBook(widget.itemId)) return;+ final l = AppLocalizations.of(context)!;+ final lib = context.read<LibraryProvider>();+ if (lib.getProgressData(widget.itemId)?['isFinished'] == true) return;+ var hasModel = false;+ for (final size in TranscriptionModelSize.values) {+ if (await transcription.isModelDownloaded(size)) {+ hasModel = true;+ break;+ }+ }+ if (!hasModel) return;+ final player = AudioPlayerService();+ final live = player.currentItemId == widget.itemId &&+ player.currentEpisodeId == null;+ final audioAt = live+ ? player.position.inMilliseconds / 1000.0+ : await ProgressSyncService().getSavedPosition(widget.itemId);+ if (!mounted) return;+ ({double est, double lo, double hi})? page;+ try {+ page = await _audioEstimateForPage(cfi);+ } catch (e) {+ debugPrint('[CatchUp] estimate failed: $e');+ }+ if (!mounted || page == null || _readAlongOn || _finding) return;+ final gap = page.est - audioAt;+ final apart = gap.abs() >= _catchUpMinGapSeconds &&+ (audioAt < page.lo || audioAt > page.hi);+ debugPrint('[CatchUp] page est=${page.est.toStringAsFixed(0)}s '+ '(${page.lo.toStringAsFixed(0)}-${page.hi.toStringAsFixed(0)}s) '+ 'audio=${audioAt.toStringAsFixed(0)}s apart=$apart '+ 'audioStarting=$audioStarting');+ if (!apart) return;+ if (gap < 0) {+ if (_offeredPageToAudio) return;+ if (!audioStarting) {+ // Already offered at this audio position.+ final key = 'catchup_offered_at_${widget.itemId}';+ final last = await ScopedPrefs.getDouble(key);+ if (last != null && (last - audioAt).abs() < 120) return;+ await ScopedPrefs.setDouble(key, audioAt);+ if (!mounted) return;+ }+ _offeredPageToAudio = true;+ showOverlayToast(context, l.catchUpAudioAhead,+ icon: Icons.headphones_rounded,+ onTap: () => _catchUpPageToAudio(audioAt));+ } else {+ if (!audioStarting || _offeredAudioToPage) return;+ _offeredAudioToPage = true;+ showOverlayToast(context, l.catchUpPageAhead,+ icon: Icons.menu_book_rounded,+ onTap: () => _findInAudiobookFromSelection(+ cfiOverride: _currentCfi ?? cfi,+ textOverride: '',+ flashPassage: false));+ }+ }++ /// Waits briefly for the audiobook's details and the first page.+ Future<void> _catchUpOnOpen() async {+ for (var i = 0;+ i < 20 && mounted && (!_hasAudio || _currentCfi == null);+ i++) {+ await Future.delayed(const Duration(milliseconds: 500));+ }+ if (mounted) await _maybeOfferCatchUp(audioStarting: false);+ }++ /// Find in ebook from inside the reader, at the audiobook's position+ /// ([savedAt] when this book is not the one loaded).+ Future<void> _catchUpPageToAudio(double savedAt) async {+ if (!mounted || _finding || _readAlongOn) return;+ final l = AppLocalizations.of(context)!;+ final api = context.read<AuthProvider>().apiService;+ final player = AudioPlayerService();+ final live = player.currentItemId == widget.itemId &&+ player.currentEpisodeId == null;+ final pos = live ? player.position.inMilliseconds / 1000.0 : savedAt;+ showProgressDialog(context, l.transcribing);+ String? text;+ String? error;+ try {+ final r = await TranscriptionService.instance.transcribeAt(+ itemId: widget.itemId,+ positionSeconds: pos,+ windowSeconds: findInEbookWindowSeconds,+ leadSeconds: findInEbookWindowSeconds,+ preferAccuracy: false,+ feature: TranscriptionFeature.readAlong,+ );+ text = r.text.trim();+ try {+ final f = File(r.audioPath);+ if (f.existsSync()) await f.delete();+ } catch (_) {}+ } on TranscriptionException catch (e) {+ error = switch (e.kind) {+ TranscriptionError.busy => l.transcriptionBusyMsg,+ TranscriptionError.empty => l.transcriptionEmptyMsg,+ TranscriptionError.modelMissing => l.transcriptionNoModelDownloaded,+ TranscriptionError.notDownloaded => l.transcriptionNotDownloadedBook,+ _ => l.transcriptionFailedMsg,+ };+ } catch (_) {+ error = l.transcriptionFailedMsg;+ }+ if (!mounted) return;+ Navigator.pop(context); // progress dialog+ if (error != null || text == null || text.isEmpty) {+ showOverlayToast(context, error ?? l.transcriptionEmptyMsg,+ icon: Icons.error_outline_rounded);+ return;+ }+ final audio = await resolveAudioChapters(widget.itemId, api);+ if (!mounted) return;+ String? chapterHint;+ final chIdx =+ ChapterLookup.indexAtWithGrace(audio.chapters, pos, audio.duration);+ if (chIdx != null) {+ final t = ((audio.chapters[chIdx] as Map<String, dynamic>)['title']+ as String?)+ ?.trim();+ if (t != null && t.isNotEmpty) chapterHint = t;+ }+ await _runFindInEbook(text, chapterHint, positionSeconds: pos);+ }/// 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@@ -2710,7 +2870,9 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs/// [cfiOverride]/[textOverride] let an existing highlight reuse this flow/// without a live selection.Future<void> _findInAudiobookFromSelection(- {String? cfiOverride, String? textOverride}) async {+ {String? cfiOverride,+ String? textOverride,+ bool flashPassage = true}) async {final l = AppLocalizations.of(context)!;final cfi = cfiOverride ?? _selectionCfi;final selText = textOverride ?? _selectionText ?? '';@@ -2800,7 +2962,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsreturn;}await _startAudioAt(targetTime,- goToPlayer: after == 'player', passageCfi: cfi);+ goToPlayer: after == 'player', passageCfi: flashPassage ? cfi : null);// 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@@ -2860,7 +3022,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsfinal 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);+ if (chapterTitlesAgree(m['title'] as String?, tocTitle)) agreeing.add(m);}Map<String, dynamic>? audioCh;Map<String, dynamic>? audioChAlt;@@ -2983,7 +3145,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsMap<String, dynamic>? aCh;for (final ch in audio.chapters) {final m = ch as Map<String, dynamic>;- if (_chapterTitlesAgree(m['title'] as String?, aTitle)) {+ if (chapterTitlesAgree(m['title'] as String?, aTitle)) {aCh = m;break;}@@ -3715,6 +3877,31 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs}return;}+ await _startReadAlong();+ }++ /// Picks read along back up after the app was backgrounded, without+ /// touching playback: coming back must never pause what you are hearing.+ Future<void> _resumeReadAlong() async {+ final player = AudioPlayerService();+ bool stillWanted() =>+ mounted &&+ _readerActive &&+ !_readAlongOn &&+ player.currentItemId == widget.itemId &&+ player.currentEpisodeId == null;+ if (!stillWanted()) return;+ if (!await PlayerSettings.getTranscriptionEnabled()) return;+ if (!stillWanted() ||+ !TranscriptionService.instance.canTranscribeBook(widget.itemId)) {+ return;+ }+ debugPrint('[ReadAlong] back in the foreground - picking up again');+ await _startReadAlong(holdPlayback: false);+ }++ Future<void> _startReadAlong({bool holdPlayback = true}) async {+ final player = AudioPlayerService();// 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) {@@ -3728,9 +3915,10 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs// 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();+ final hold = holdPlayback && wasPlaying;+ if (hold) await player.pause();_readAlongGateArmed = false;- _readAlongGatePaused = wasPlaying;+ _readAlongGatePaused = hold;_readAlongGateWaiting = !wasPlaying;if (mounted) {setState(() {@@ -5118,7 +5306,6 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs/// sense with the book open, on the app surface like the speed sheet.void _showReaderControls() {final accent = Theme.of(context).colorScheme.primary;- final tt = Theme.of(context).textTheme;showModalBottomSheet(context: context,backgroundColor: Colors.transparent,@@ -5154,11 +5341,19 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsfinal cellH =(cols == 2 ? 72.0 : 80.0) * textScale.clamp(1.0, 1.7) + 8;return Wrap(spacing: gap, runSpacing: gap, children: [- for (final tile in _readerControlTiles(ctx, accent, tt))+ for (final tile in _readerControlTiles(ctx, accent))SizedBox(width: cellW, height: cellH, child: tile),]);}),- const SizedBox(height: 8),+ const SizedBox(height: 4),+ TextButton.icon(+ onPressed: () {+ Navigator.pop(ctx);+ _pickBarAction();+ },+ icon: const Icon(Icons.swap_horiz_rounded, size: 18),+ label: Text(AppLocalizations.of(ctx)!.readerShortcutButton),+ ),]),),),@@ -5167,156 +5362,281 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs);}- List<Widget> _readerControlTiles(BuildContext ctx, Color accent, TextTheme tt) {+ List<Widget> _readerControlTiles(BuildContext ctx, Color accent) {+ Widget tile(String id) {+ Widget build() {+ final a = _readerAction(id);+ return MoreMenuItem(+ icon: a.icon,+ label: a.label,+ accent: a.tint ?? accent,+ enabled: a.enabled,+ onTap: () {+ Navigator.pop(ctx);+ a.onTap();+ },+ );+ }++ final listenable = _readerActionListenable(id);+ return listenable == null+ ? build()+ : ListenableBuilder(listenable: listenable, builder: (_, __) => build());+ }++ return [+ for (final id in _readerActionIds)+ if (id != _barActionId) tile(id),+ ];+ }++ // Cast is Android only; iPhones get the AirPlay route picker instead, same+ // split as the card.+ List<String> get _readerActionIds => [+ 'chapters',+ 'speed',+ 'sleep',+ 'bookmarks',+ 'equalizer',+ Platform.isIOS ? 'airplay' : 'cast',+ 'details',+ 'download',+ ];++ // A choice restored from the other platform may not exist on this one.+ String get _barActionId =>+ _readerActionIds.contains(_barAction) ? _barAction : 'speed';++ Listenable? _readerActionListenable(String id) => switch (id) {+ 'cast' => ChromecastService(),+ 'download' => DownloadService(),+ _ => null,+ };++ /// One of the reader's audio controls as it stands right now, for a tile in+ /// the controls sheet or the player bar's shortcut.+ _ReaderAction _readerAction(String id) {final l = AppLocalizations.of(context)!;+ final accent = Theme.of(context).colorScheme.primary;final player = AudioPlayerService();- final isActive = player.hasBook && player.currentItemId == widget.itemId;- return [- MoreMenuItem(- icon: Icons.list_rounded,- label: l.chapters,- accent: accent,- onTap: () {- Navigator.pop(ctx);- _showAudioChapters(accent, tt);- },- ),- MoreMenuItem(- icon: Icons.nightlight_round_outlined,- label: l.timer,- accent: accent,- onTap: () {- Navigator.pop(ctx);- showSleepTimerSheet(context, accent);- },- ),- MoreMenuItem(- icon: Icons.bookmark_outline_rounded,- label: l.bookmarks,- accent: accent,- enabled: isActive,- 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: widget.itemId,- player: player,- accent: accent,- scrollController: sc,- onChanged: () {},+ switch (id) {+ case 'chapters':+ return (+ icon: Icons.list_rounded,+ label: l.chapters,+ tint: null,+ enabled: true,+ onTap: () => _showAudioChapters(accent, Theme.of(context).textTheme),+ );+ case 'speed':+ return (+ icon: Icons.speed_rounded,+ label: l.speed,+ tint: null,+ enabled: true,+ onTap: () => showModalBottomSheet(+ context: context,+ backgroundColor: Theme.of(context).colorScheme.surface,+ shape: const RoundedRectangleBorder(+ borderRadius: BorderRadius.vertical(top: Radius.circular(20)),+ ),+ // The sheet sits on the app surface, not the page, so it+ // keeps the theme accent.+ builder: (_) => CardSpeedSheet(+ player: player,+ accent: accent,+ itemId: widget.itemId,+ ),),- ),- );- },- ),- MoreMenuItem(- icon: Icons.equalizer_rounded,- label: l.equalizerLabel,- accent: accent,- onTap: () {- Navigator.pop(ctx);- showEqualizerSheet(context, accent,- itemId: widget.itemId, itemTitle: widget.title);- },- ),- // Cast is Android only; iPhones get the AirPlay route picker instead,- // same split as the card.- if (Platform.isIOS)- MoreMenuItem(+ );+ case 'sleep':+ return (+ icon: Icons.nightlight_round_outlined,+ label: l.timer,+ tint: null,+ enabled: true,+ onTap: () => showSleepTimerSheet(context, accent),+ );+ case 'bookmarks':+ return (+ icon: Icons.bookmark_outline_rounded,+ label: l.bookmarks,+ tint: null,+ enabled: player.hasBook && player.currentItemId == widget.itemId,+ onTap: () => 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: widget.itemId,+ player: player,+ accent: accent,+ scrollController: sc,+ onChanged: () {},+ ),+ ),+ ),+ );+ case 'equalizer':+ return (+ icon: Icons.equalizer_rounded,+ label: l.equalizerLabel,+ tint: null,+ enabled: true,+ onTap: () => showEqualizerSheet(context, accent,+ itemId: widget.itemId, itemTitle: widget.title),+ );+ case 'airplay':+ return (icon: Icons.airplay_rounded,label: 'AirPlay',- accent: accent,+ tint: null,+ enabled: true,+ onTap: () => const MethodChannel('com.absorb.audio_output')+ .invokeMethod('showRoutePicker')+ .catchError((_) => null),+ );+ case 'cast':+ final cast = ChromecastService();+ final String label;+ if (cast.isCasting && cast.castingItemId == widget.itemId) {+ label = l.castingToDevice(cast.connectedDeviceName ?? 'device');+ } else if (cast.isConnected) {+ label = l.castToDeviceNamed(cast.connectedDeviceName ?? 'device');+ } else {+ label = l.castToDevice;+ }+ return (+ icon: cast.isConnected+ ? Icons.cast_connected_rounded+ : Icons.cast_rounded,+ label: label,+ tint: null,+ enabled: true,+ onTap: _castFromReader,+ );+ case 'details':+ return (+ icon: Icons.info_outline_rounded,+ label: l.bookDetailsLabel,+ tint: null,+ enabled: true,+ onTap: () => showBookDetailSheet(context, widget.itemId),+ );+ default:+ final dl = DownloadService();+ final downloaded = dl.isDownloaded(widget.itemId);+ final downloading = dl.isDownloading(widget.itemId);+ final isDark = Theme.of(context).brightness == Brightness.dark;+ return (+ icon: downloaded+ ? Icons.download_done_rounded+ : downloading+ ? Icons.downloading_rounded+ : Icons.download_outlined,+ label: downloaded+ ? l.saved+ : downloading+ ? '${(dl.downloadProgress(widget.itemId) * 100).toStringAsFixed(0)}%'+ : l.download,+ tint: !downloaded+ ? null+ : isDark+ ? Colors.greenAccent.withValues(alpha: 0.7)+ : Colors.green.shade700,+ enabled: true,onTap: () {- Navigator.pop(ctx);- const MethodChannel('com.absorb.audio_output')- .invokeMethod('showRoutePicker')- .catchError((_) => null);+ if (!downloaded && !downloading) _downloadFromReader();},- )- else- ListenableBuilder(- listenable: ChromecastService(),- builder: (_, __) {- final cast = ChromecastService();- final String label;- if (cast.isCasting && cast.castingItemId == widget.itemId) {- label = l.castingToDevice(cast.connectedDeviceName ?? 'device');- } else if (cast.isConnected) {- label = l.castToDeviceNamed(cast.connectedDeviceName ?? 'device');- } else {- label = l.castToDevice;- }- return MoreMenuItem(- icon: cast.isConnected- ? Icons.cast_connected_rounded- : Icons.cast_rounded,- label: label,- accent: accent,- onTap: () {- Navigator.pop(ctx);- _castFromReader();- },- );- },- ),- MoreMenuItem(- icon: Icons.info_outline_rounded,- label: l.bookDetailsLabel,- accent: accent,- onTap: () {- Navigator.pop(ctx);- showBookDetailSheet(context, widget.itemId);- },- ),- ListenableBuilder(- listenable: DownloadService(),- builder: (_, __) {- final dl = DownloadService();- final downloaded = dl.isDownloaded(widget.itemId);- final downloading = dl.isDownloading(widget.itemId);- final progress = dl.downloadProgress(widget.itemId);- final isDark = Theme.of(ctx).brightness == Brightness.dark;- final green = isDark- ? Colors.greenAccent.withValues(alpha: 0.7)- : Colors.green.shade700;- final IconData icon;- final String label;- final Color tileAccent;- if (downloaded) {- icon = Icons.download_done_rounded;- label = l.saved;- tileAccent = green;- } else if (downloading) {- icon = Icons.downloading_rounded;- label = '${(progress * 100).toStringAsFixed(0)}%';- tileAccent = accent;- } else {- icon = Icons.download_outlined;- label = l.download;- tileAccent = accent;- }- return MoreMenuItem(- icon: icon,- label: label,- accent: tileAccent,- onTap: () {- Navigator.pop(ctx);- if (!downloaded && !downloading) _downloadFromReader();- },- );- },- ),- ];+ );+ }+ }++ /// The player bar's left slot. Long press swaps what sits there.+ Widget _barShortcut(Color fg, Color dim) {+ final id = _barActionId;+ Widget build() {+ final a = _readerAction(id);+ return GestureDetector(+ onLongPress: _pickBarAction,+ child: id == 'speed'+ ? TextButton(+ style: TextButton.styleFrom(+ padding: const EdgeInsets.symmetric(horizontal: 8),+ minimumSize: const Size(0, 36),+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,+ ),+ onPressed: a.onTap,+ child: Text(_speedLabel(AudioPlayerService().speed),+ style: TextStyle(color: fg, fontWeight: FontWeight.w700)),+ )+ : IconButton(+ icon: Icon(a.icon, color: a.enabled ? fg : dim),+ iconSize: 26,+ onPressed:+ a.enabled ? a.onTap : () => showInactiveToast(context),+ ),+ );+ }++ final listenable = _readerActionListenable(id);+ return listenable == null+ ? build()+ : ListenableBuilder(listenable: listenable, builder: (_, __) => build());+ }++ Future<void> _pickBarAction() async {+ final l = AppLocalizations.of(context)!;+ final current = _barActionId;+ final picked = await showModalBottomSheet<String>(+ context: context,+ isScrollControlled: true,+ useSafeArea: true,+ builder: (ctx) {+ final cs = Theme.of(ctx).colorScheme;+ return SafeArea(+ child: SingleChildScrollView(+ child: Column(mainAxisSize: MainAxisSize.min, children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 18, 20, 6),+ child: Align(+ alignment: Alignment.centerLeft,+ child: Text(l.readerShortcutButton,+ style: Theme.of(ctx)+ .textTheme+ .titleSmall+ ?.copyWith(fontWeight: FontWeight.w600)),+ ),+ ),+ for (final id in _readerActionIds)+ ListTile(+ leading: Icon(+ buttonDefById(id)?.icon ?? _readerAction(id).icon),+ title: Text(switch (buttonDefById(id)) {+ final def? => localizedCardButtonLabel(l, def),+ null => _readerAction(id).label,+ }),+ trailing: id == current+ ? Icon(Icons.check_rounded, color: cs.primary)+ : null,+ onTap: () => Navigator.pop(ctx, id),+ ),+ const SizedBox(height: 8),+ ]),+ ),+ );+ },+ );+ if (picked == null || picked == current || !mounted) return;+ setState(() => _barAction = picked);+ await ScopedPrefs.setString(_kBarAction, picked);}Future<void> _showAudioChapters(Color accent, TextTheme tt) async {@@ -5443,29 +5763,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObswidth: 64,child: Align(alignment: Alignment.centerLeft,- child: TextButton(- style: TextButton.styleFrom(- padding: const EdgeInsets.symmetric(horizontal: 8),- minimumSize: const Size(0, 36),- tapTargetSize: MaterialTapTargetSize.shrinkWrap,- ),- onPressed: () => showModalBottomSheet(- context: context,- backgroundColor: Theme.of(context).colorScheme.surface,- shape: const RoundedRectangleBorder(- borderRadius: BorderRadius.vertical(top: Radius.circular(20)),- ),- // The sheet sits on the app surface, not the page, so- // it keeps the theme accent.- builder: (_) => CardSpeedSheet(- player: player,- accent: Theme.of(context).colorScheme.primary,- itemId: widget.itemId,- ),- ),- child: Text(_speedLabel(player.speed),- style: TextStyle(color: fg, fontWeight: FontWeight.w700)),- ),+ child: _barShortcut(fg, dim),),),Expanded(@@ -5490,7 +5788,13 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsonPressed: _startingAudio? null: (isActive- ? () => player.togglePlayPause(fromUi: true)+ ? () {+ final starting = !player.isPlaying;+ player.togglePlayPause(fromUi: true);+ if (starting) {+ _maybeOfferCatchUp(audioStarting: true);+ }+ }: _startThisBook),),IconButton(@@ -5667,6 +5971,13 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsif (mounted && !_readAlongOn) _toggleReadAlong();});}+ if (!_didScheduleCatchUp) {+ _didScheduleCatchUp = true;+ // Past the load rescue and settle re-displays.+ Future.delayed(const Duration(milliseconds: 2500), () {+ if (mounted) _catchUpOnOpen();+ });+ }final findText = widget.findText;if (findText != null && findText.isNotEmpty && !_didStartFind) {_didStartFind = true;diff --git a/lib/widgets/overlay_toast.dart b/lib/widgets/overlay_toast.dartindex 994d2dae..e05e8ddb 100644--- a/lib/widgets/overlay_toast.dart+++ b/lib/widgets/overlay_toast.dart@@ -17,9 +17,13 @@ void _removeToast(OverlayEntry entry) {/// Show a styled toast that renders above modal sheets and overlays.///-/// Pass [icon] for a leading icon (e.g. Icons.check_circle_rounded).-void showOverlayToast(BuildContext context, String message, {IconData? icon}) {- _insertOverlayToast(Overlay.maybeOf(context), message, icon: icon);+/// Pass [icon] for a leading icon (e.g. Icons.check_circle_rounded). With+/// [onTap] the toast is an offer: it stays up longer and tapping it runs the+/// action.+void showOverlayToast(BuildContext context, String message,+ {IconData? icon, VoidCallback? onTap}) {+ _insertOverlayToast(Overlay.maybeOf(context), message,+ icon: icon, onTap: onTap);}/// Show the same toast from provider/service code that owns a navigator but@@ -36,6 +40,7 @@ void _insertOverlayToast(OverlayState? overlay,String message, {IconData? icon,+ VoidCallback? onTap,}) {final previous = _currentToast;if (previous != null) _removeToast(previous);@@ -49,6 +54,7 @@ void _insertOverlayToast(builder: (_) => _AnimatedToast(message: message,icon: icon,+ onTap: onTap,onDone: () {_removeToast(entry);if (_currentToast == entry) _currentToast = null;@@ -152,9 +158,11 @@ class _LiveToast extends StatelessWidget {class _AnimatedToast extends StatefulWidget {final String message;final IconData? icon;+ final VoidCallback? onTap;final VoidCallback onDone;- const _AnimatedToast({required this.message, this.icon, required this.onDone});+ const _AnimatedToast(+ {required this.message, this.icon, this.onTap, required this.onDone});@overrideState<_AnimatedToast> createState() => _AnimatedToastState();@@ -172,7 +180,7 @@ class _AnimatedToastState extends State<_AnimatedToast>vsync: this,)..forward();- Future.delayed(const Duration(seconds: 2), () {+ Future.delayed(Duration(seconds: widget.onTap != null ? 6 : 2), () {if (mounted) _controller.reverse().then((_) => widget.onDone());});}@@ -198,36 +206,45 @@ class _AnimatedToastState extends State<_AnimatedToast>end: Offset.zero,).animate(CurvedAnimation(parent: _controller, curve: Curves.easeOut)),child: Center(- child: ClipRRect(- borderRadius: BorderRadius.circular(24),- child: BackdropFilter(- filter: ui.ImageFilter.blur(sigmaX: 20, sigmaY: 20),- child: Container(- padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),- decoration: BoxDecoration(- color: cs.surface.withValues(alpha: 0.7),- borderRadius: BorderRadius.circular(24),- border: Border.all(color: cs.primary.withValues(alpha: 0.25)),- ),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- if (widget.icon != null) ...[- Icon(widget.icon, size: 18, color: cs.primary),- const SizedBox(width: 8),- ],- Flexible(- child: Text(- widget.message,- style: TextStyle(- color: cs.onSurface,- fontSize: 13,- fontWeight: FontWeight.w500,- decoration: TextDecoration.none,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: widget.onTap == null+ ? null+ : () {+ widget.onDone();+ widget.onTap!();+ },+ child: ClipRRect(+ borderRadius: BorderRadius.circular(24),+ child: BackdropFilter(+ filter: ui.ImageFilter.blur(sigmaX: 20, sigmaY: 20),+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),+ decoration: BoxDecoration(+ color: cs.surface.withValues(alpha: 0.7),+ borderRadius: BorderRadius.circular(24),+ border: Border.all(color: cs.primary.withValues(alpha: 0.25)),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ if (widget.icon != null) ...[+ Icon(widget.icon, size: 18, color: cs.primary),+ const SizedBox(width: 8),+ ],+ Flexible(+ child: Text(+ widget.message,+ style: TextStyle(+ color: cs.onSurface,+ fontSize: 13,+ fontWeight: FontWeight.w500,+ decoration: TextDecoration.none,+ ),),),- ),- ],+ ],+ ),),),),diff --git a/pubspec.yaml b/pubspec.yamlindex a62f3437..e2d0ab54 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -1,7 +1,7 @@name: absorbdescription: An Audiobookshelf Clientpublish_to: 'none'-version: 1.11.1+287+version: 1.11.1+288environment:sdk: '>=3.10.0 <4.0.0'