A cross platform Audiobookshelf client for Android and iOS
Dart
Make read along turn pages the moment the voice crosses the edge, keep the highlight to one paragraph, roll the color through each word, and put its settings in the reader
Barnabas98d260692736
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arbindex 3f5bfe51..de297e40 100644--- a/lib/l10n/app_en.arb+++ b/lib/l10n/app_en.arb@@ -4896,6 +4896,10 @@"readAlongFollowWord": "Word","readAlongFollowSentence": "Sentence","readAlongColor": "Read along color",+ "readAlongLost": "Can't find the narration on the page",+ "@readAlongLost": {+ "description": "Read along pill after 45s of narration that matches nothing on the page"+ },"findInEbook": "Find in ebook","findInEbookSearching": "Finding this spot in the ebook...","findInEbookNotFound": "Couldn't find this spot in the ebook.",diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dartindex 6b575d17..1916e161 100644--- a/lib/l10n/app_localizations.dart+++ b/lib/l10n/app_localizations.dart@@ -15057,6 +15057,12 @@ abstract class AppLocalizations {/// **'Read along color'**String get readAlongColor;+ /// Read along pill after 45s of narration that matches nothing on the page+ ///+ /// In en, this message translates to:+ /// **'Can\'t find the narration on the page'**+ String get readAlongLost;+/// No description provided for @findInEbook.////// In en, this message translates to:diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dartindex 56c18bdc..913d05e8 100644--- a/lib/l10n/app_localizations_de.dart+++ b/lib/l10n/app_localizations_de.dart@@ -8832,6 +8832,9 @@ class AppLocalizationsDe extends AppLocalizations {@overrideString get readAlongColor => 'Read along color';+ @override+ String get readAlongLost => 'Can\'t find the narration on the page';+@overrideString get findInEbook => 'Find in ebook';diff --git a/lib/l10n/app_localizations_el.dart b/lib/l10n/app_localizations_el.dartindex b1f9fe15..a22d6a4f 100644--- a/lib/l10n/app_localizations_el.dart+++ b/lib/l10n/app_localizations_el.dart@@ -8711,6 +8711,9 @@ class AppLocalizationsEl extends AppLocalizations {@overrideString get readAlongColor => 'Read along color';+ @override+ String get readAlongLost => 'Can\'t find the narration on the page';+@overrideString get findInEbook => 'Find in ebook';diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dartindex 9731014b..0efbb2af 100644--- a/lib/l10n/app_localizations_en.dart+++ b/lib/l10n/app_localizations_en.dart@@ -8711,6 +8711,9 @@ class AppLocalizationsEn extends AppLocalizations {@overrideString get readAlongColor => 'Read along color';+ @override+ String get readAlongLost => 'Can\'t find the narration on the page';+@overrideString get findInEbook => 'Find in ebook';diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dartindex 0b3dc7ac..f4e6a52d 100644--- a/lib/l10n/app_localizations_es.dart+++ b/lib/l10n/app_localizations_es.dart@@ -8713,6 +8713,9 @@ class AppLocalizationsEs extends AppLocalizations {@overrideString get readAlongColor => 'Read along color';+ @override+ String get readAlongLost => 'Can\'t find the narration on the page';+@overrideString get findInEbook => 'Find in ebook';diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dartindex 80dcc0dc..db451439 100644--- a/lib/l10n/app_localizations_fr.dart+++ b/lib/l10n/app_localizations_fr.dart@@ -8764,6 +8764,9 @@ class AppLocalizationsFr extends AppLocalizations {@overrideString get readAlongColor => 'Read along color';+ @override+ String get readAlongLost => 'Can\'t find the narration on the page';+@overrideString get findInEbook => 'Find in ebook';diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dartindex a92cbc95..191752e9 100644--- a/lib/l10n/app_localizations_it.dart+++ b/lib/l10n/app_localizations_it.dart@@ -8711,6 +8711,9 @@ class AppLocalizationsIt extends AppLocalizations {@overrideString get readAlongColor => 'Read along color';+ @override+ String get readAlongLost => 'Can\'t find the narration on the page';+@overrideString get findInEbook => 'Find in ebook';diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dartindex 826f1078..ce3f49a5 100644--- a/lib/l10n/app_localizations_ja.dart+++ b/lib/l10n/app_localizations_ja.dart@@ -8711,6 +8711,9 @@ class AppLocalizationsJa extends AppLocalizations {@overrideString get readAlongColor => 'Read along color';+ @override+ String get readAlongLost => 'Can\'t find the narration on the page';+@overrideString get findInEbook => 'Find in ebook';diff --git a/lib/l10n/app_localizations_no.dart b/lib/l10n/app_localizations_no.dartindex a7d55c67..3038b637 100644--- a/lib/l10n/app_localizations_no.dart+++ b/lib/l10n/app_localizations_no.dart@@ -8711,6 +8711,9 @@ class AppLocalizationsNo extends AppLocalizations {@overrideString get readAlongColor => 'Read along color';+ @override+ String get readAlongLost => 'Can\'t find the narration on the page';+@overrideString get findInEbook => 'Find in ebook';diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dartindex d1bf1c67..9c394de2 100644--- a/lib/l10n/app_localizations_pt.dart+++ b/lib/l10n/app_localizations_pt.dart@@ -8711,6 +8711,9 @@ class AppLocalizationsPt extends AppLocalizations {@overrideString get readAlongColor => 'Read along color';+ @override+ String get readAlongLost => 'Can\'t find the narration on the page';+@overrideString get findInEbook => 'Find in ebook';diff --git a/lib/l10n/app_localizations_ro.dart b/lib/l10n/app_localizations_ro.dartindex 78d79264..e84a4e20 100644--- a/lib/l10n/app_localizations_ro.dart+++ b/lib/l10n/app_localizations_ro.dart@@ -8711,6 +8711,9 @@ class AppLocalizationsRo extends AppLocalizations {@overrideString get readAlongColor => 'Read along color';+ @override+ String get readAlongLost => 'Can\'t find the narration on the page';+@overrideString get findInEbook => 'Find in ebook';diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dartindex 545a4b8b..974b4d6a 100644--- a/lib/l10n/app_localizations_ru.dart+++ b/lib/l10n/app_localizations_ru.dart@@ -8716,6 +8716,9 @@ class AppLocalizationsRu extends AppLocalizations {@overrideString get readAlongColor => 'Read along color';+ @override+ String get readAlongLost => 'Can\'t find the narration on the page';+@overrideString get findInEbook => 'Find in ebook';diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dartindex 3a77ad99..9831d3ec 100644--- a/lib/l10n/app_localizations_zh.dart+++ b/lib/l10n/app_localizations_zh.dart@@ -8619,6 +8619,9 @@ class AppLocalizationsZh extends AppLocalizations {@overrideString get readAlongColor => 'Read along color';+ @override+ String get readAlongLost => 'Can\'t find the narration on the page';+@overrideString get findInEbook => 'Find in ebook';diff --git a/lib/screens/transcription_settings_screen.dart b/lib/screens/transcription_settings_screen.dartindex cc9f276a..ece4c6e7 100644--- a/lib/screens/transcription_settings_screen.dart+++ b/lib/screens/transcription_settings_screen.dart@@ -9,16 +9,6 @@ import '../widgets/overlay_toast.dart';/// Colors the spoken words can be painted in. Vivid enough to read on the/// light, sepia and dark reader pages alike, and over cover art.-const _readAlongPalette = [- 0xFFFFC400,- 0xFFFF6D00,- 0xFFFF1744,- 0xFFFF4081,- 0xFFD500F9,- 0xFF2979FF,- 0xFF00B8D4,- 0xFF00C853,-];/// Advanced > Bookmark transcription settings: opt-in toggle and on-device/// Whisper model management (download / pick / delete). Everything here runs@@ -367,7 +357,7 @@ class _TranscriptionSettingsScreenStatespacing: 12,runSpacing: 12,children: [- for (final c in _readAlongPalette)+ for (final c in PlayerSettings.readAlongPalette)_colorSwatch(c, cs),],),diff --git a/lib/services/lyrics_service.dart b/lib/services/lyrics_service.dartindex 962dfdae..ee80fa27 100644--- a/lib/services/lyrics_service.dart+++ b/lib/services/lyrics_service.dart@@ -97,6 +97,18 @@ class LyricsService extends ChangeNotifier {bool _reachedEnd = false;bool get isOn => _on;++ /// True while the ebook reader's read along is driving the transcript.+ /// The card overlay stays out of the way then - one of them at a time -+ /// including during the reader's exit animation, before it can disable+ /// the pipeline it started.+ bool _readerOwns = false;+ bool get readerOwns => _readerOwns;+ set readerOwns(bool v) {+ if (_readerOwns == v) return;+ _readerOwns = v;+ notifyListeners();+ }/// The store key lyrics are currently running for, so card overlays can/// render only on the playing item's card.String? get activeKey => _key;diff --git a/lib/services/player_settings.dart b/lib/services/player_settings.dartindex 06db56b4..176fc89c 100644--- a/lib/services/player_settings.dart+++ b/lib/services/player_settings.dart@@ -62,6 +62,18 @@ extension CardScrubberModeBehavior on CardScrubberMode {}class PlayerSettings {+ /// Swatches offered for the read along and live transcript color.+ static const List<int> readAlongPalette = [+ 0xFFFFC400,+ 0xFFFF6D00,+ 0xFFFF1744,+ 0xFFFF4081,+ 0xFFD500F9,+ 0xFF2979FF,+ 0xFF00B8D4,+ 0xFF00C853,+];+/// Notifier that fires when any player setting changes./// Widgets can listen to this instead of polling SharedPreferences.static final ChangeNotifier settingsChanged = ChangeNotifier();diff --git a/lib/services/read_along_script.dart b/lib/services/read_along_script.dartindex 31808683..4d3c6c48 100644--- a/lib/services/read_along_script.dart+++ b/lib/services/read_along_script.dart@@ -2,10 +2,11 @@////// epub.js annotations are an SVG overlay drawn on top of the page, so they/// can only ever box or underline text - they cannot repaint the words-/// themselves. This paints the real glyphs instead: the CSS Custom Highlight-/// API where the WebView has it (no DOM changes at all), and wrapping the-/// range in spans on older WebViews (iOS below 17.2), unwrapped again on every-/// move so the page ends up exactly as it started.+/// themselves. This wraps the current sentence in one span per word and+/// drives everything after that with CSS classes, so the tint rolls from+/// word to word and fades in on a new sentence through ordinary CSS+/// transitions instead of repainting. The spans are unwrapped again when the+/// sentence moves on, so the page ends up exactly as it started.library;/// Six-digit hex for an ARGB value, for CSS.@@ -17,23 +18,46 @@ String cssHex(int argb) =>String readAlongBootstrap(int argb) {final hex = cssHex(argb);final r = (argb >> 16) & 0xFF, g = (argb >> 8) & 0xFF, b = argb & 0xFF;- return '''-(function() {- var RA = window.__absorbRA = window.__absorbRA || {};- RA.color = '$hex';- RA.dimRgba = 'rgba($r, $g, $b, 0.8)';+ return '(function() {'+ 'var RA = window.__absorbRA = window.__absorbRA || {};'+ "RA.color = '$hex'; RA.rgb = '$r, $g, $b';"+ '$_body'+ '})();';+}++const String _body = r'''RA.cur = null;+ // Block elements: a sentence never runs past one of these, so a scene+ // divider or a heading between two sentences can't glue them together.+ RA.BLOCKS = 'p,div,h1,h2,h3,h4,h5,h6,li,blockquote,pre,td,th,dd,dt,' ++ 'figcaption,section,article,aside,header,footer,tr,hr,table,figure';++ // The word's glyphs are painted from two background layers clipped to the+ // text: the dim color underneath, the full color on top. The top layer+ // grows from the left as the narration reaches the word, so the color+ // rolls through it, and stays once the word is read. The text color itself+ // is transparent so the layers show; the "in" state keeps it at the page+ // color for a frame so a fresh sentence fades into the dim tone instead+ // of snapping.RA.css = function() {- var mix = 'color-mix(in srgb, ' + RA.color + ' 55%, currentColor)';- return '::highlight(absorbRaWord) { color: ' + RA.color + '; }' +- '::highlight(absorbRaDim) { color: ' + RA.dimRgba + '; }' +- '.absorb-ra-word { color: ' + RA.color + ' !important; }' +- '.absorb-ra-dim { color: ' + RA.dimRgba + ' !important; }' +- '@supports (color: color-mix(in srgb, red 50%, blue)) {' +- ' ::highlight(absorbRaDim) { color: ' + mix + '; }' +- ' .absorb-ra-dim { color: ' + mix + ' !important; }' +- '}';+ var c = RA.color, rgb = RA.rgb;+ var dim = 'rgba(' + rgb + ', 0.8)';+ return '' ++ '.absorb-ra-w { color: transparent !important;' ++ ' background-image: linear-gradient(' + c + ', ' + c + '),' ++ ' linear-gradient(' + dim + ', ' + dim + ');' ++ ' background-size: 0% 100%, 100% 100%; background-repeat: no-repeat;' ++ ' background-position: 0 0, 0 0;' ++ ' -webkit-background-clip: text; background-clip: text;' ++ ' box-decoration-break: clone; -webkit-box-decoration-break: clone;' ++ ' transition: background-size 220ms ease-out, color 180ms ease; }' ++ '.absorb-ra-w.absorb-ra-on, .absorb-ra-w.absorb-ra-done {' ++ ' background-size: 100% 100%, 100% 100%; }' ++ '.absorb-ra-s { color: ' + c + ' !important;' ++ ' transition: color 180ms ease; }' ++ '.absorb-ra-w.absorb-ra-in, .absorb-ra-s.absorb-ra-in {' ++ ' color: inherit !important; }';};RA.style = function(doc) {@@ -62,23 +86,32 @@ String readAlongBootstrap(int argb) {RA.setColor = function(hex) {RA.color = hex;- RA.dimRgba = hex;- var m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})\$/i.exec(hex);+ var m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex);if (m) {- RA.dimRgba = 'rgba(' + parseInt(m[1], 16) + ', ' + parseInt(m[2], 16) +- ', ' + parseInt(m[3], 16) + ', 0.8)';+ RA.rgb = parseInt(m[1], 16) + ', ' + parseInt(m[2], 16) + ', ' + parseInt(m[3], 16);}var cs = RA.docs();for (var i = 0; i < cs.length; i++) RA.style(cs[i].document);};- // Char offset -> text node map for a page document. Rebuilt after any span- // wrapping, since that splits text nodes; the raw text never changes, so- // offsets stay valid across rebuilds.+ // Char offset -> text node map for a page document. A virtual newline is+ // put into the raw text wherever the block element changes, so sentence+ // bounds stop at paragraph edges; those newlines belong to no node. The+ // raw text never changes when spans are added, so offsets stay valid+ // across rebuilds.RA.nodeMap = function(doc) {var tw = doc.createTreeWalker(doc.body || doc, NodeFilter.SHOW_TEXT, null, false);- var nodes = [], raw = '', node;+ var nodes = [], raw = '', node, prevBlock = null;while (node = tw.nextNode()) {+ var pe = node.parentElement;+ if (pe) {+ var tag = pe.tagName ? pe.tagName.toLowerCase() : '';+ if (tag === 'script' || tag === 'style') continue;+ }+ var block = null;+ try { block = pe ? pe.closest(RA.BLOCKS) : null; } catch (e) {}+ if (raw.length && block !== prevBlock) raw += '\n';+ prevBlock = block;nodes.push({ node: node, start: raw.length, len: node.textContent.length });raw += node.textContent;}@@ -88,6 +121,7 @@ String readAlongBootstrap(int argb) {RA.locateOffset = function(map, off) {for (var i = 0; i < map.nodes.length; i++) {var e = map.nodes[i];+ if (off < e.start) return { node: e.node, offset: 0 };if (off < e.start + e.len) return { node: e.node, offset: off - e.start };}var last = map.nodes[map.nodes.length - 1];@@ -103,27 +137,37 @@ String readAlongBootstrap(int argb) {return r;};- RA.useHighlights = function(doc) {- var win = doc && doc.defaultView;- return !!(win && win.CSS && win.CSS.highlights && win.Highlight);+ RA.unwrapSpans = function(spans) {+ var parents = [];+ for (var i = 0; i < spans.length; i++) {+ var el = spans[i], p = el.parentNode;+ if (!p) continue;+ while (el.firstChild) p.insertBefore(el.firstChild, el);+ p.removeChild(el);+ if (parents.indexOf(p) === -1) parents.push(p);+ }+ for (var k = 0; k < parents.length; k++) {+ try { parents[k].normalize(); } catch (e) {}+ }};RA.unwrap = function(doc) {try {var els = doc.querySelectorAll('span.absorb-ra');- for (var i = 0; i < els.length; i++) {- var el = els[i], p = el.parentNode;- if (!p) continue;- while (el.firstChild) p.insertBefore(el.firstChild, el);- p.removeChild(el);- }- if (els.length) (doc.body || doc).normalize();+ var list = [];+ for (var i = 0; i < els.length; i++) list.push(els[i]);+ RA.unwrapSpans(list);} catch (e) {}};+ // Wrap [a, b) of the raw text in spans of class [cls]. Works from the last+ // text node backwards, so the offsets of anything earlier in the same node+ // stay valid without rebuilding the map - splitText keeps the head of the+ // node in place.RA.wrap = function(doc, map, a, b, cls) {- if (b <= a) return;- for (var i = 0; i < map.nodes.length; i++) {+ var made = [];+ if (b <= a) return made;+ for (var i = map.nodes.length - 1; i >= 0; i--) {var e = map.nodes[i];var s0 = Math.max(a, e.start), e0 = Math.min(b, e.start + e.len);if (e0 <= s0) continue;@@ -134,104 +178,118 @@ String readAlongBootstrap(int argb) {if (local > 0) target = target.splitText(local);if (localEnd - local < target.textContent.length) target.splitText(localEnd - local);var span = doc.createElement('span');- span.className = cls + ' absorb-ra';+ span.className = cls + ' absorb-ra absorb-ra-in';target.parentNode.insertBefore(span, target);span.appendChild(target);+ made.push(span);+ }+ return made.reverse();+ };++ RA.setState = function(spans, cls) {+ for (var i = 0; i < spans.length; i++) {+ var el = spans[i];+ el.classList.remove('absorb-ra-on');+ el.classList.remove('absorb-ra-done');+ if (cls) el.classList.add(cls);}};- /// Paint the current sentence, with [wordIndex] (page word, -1 for none)- /// carrying the full color and the rest of the sentence dimmed.+ /// Paint [wordIndex] (needle word, -1 for none) as the word being heard:+ /// earlier words in the sentence settle to full color, the current one+ /// fills, the rest stay dimmed.RA.paint = function(wordIndex) {var st = RA.cur;- if (!st) return;- var doc = st.doc;- var word = (wordIndex >= 0 && st.words.length)- ? st.words[Math.min(wordIndex, st.words.length - 1)] : null;- if (RA.useHighlights(doc)) {- var win = doc.defaultView, reg = win.CSS.highlights;- var map = st.map || (st.map = RA.nodeMap(doc));- reg.delete('absorbRaWord');- reg.delete('absorbRaDim');- var sentence = RA.range(doc, map, st.sStart, st.sEnd);- if (!sentence) return;- if (word) {- var wr = RA.range(doc, map, word[0], word[1]);- var dim = new win.Highlight(sentence);- dim.priority = 1;- reg.set('absorbRaDim', dim);- if (wr) {- var hi = new win.Highlight(wr);- hi.priority = 2;- reg.set('absorbRaWord', hi);- }- } else {- var whole = new win.Highlight(sentence);- whole.priority = 2;- reg.set('absorbRaWord', whole);- }- return;+ if (!st || !st.spans) return;+ if (!st.words.length) return;+ var j = wordIndex >= 0 ? Math.min(wordIndex + st.first, st.spans.length - 1) : -1;+ for (var k = 0; k < st.spans.length; k++) {+ RA.setState(st.spans[k], k < j ? 'absorb-ra-done' : (k === j ? 'absorb-ra-on' : null));}- RA.unwrap(doc);- var m2 = st.map = RA.nodeMap(doc);- if (word) {- RA.wrap(doc, m2, st.sStart, word[0], 'absorb-ra-dim');- m2 = st.map = RA.nodeMap(doc);- RA.wrap(doc, m2, word[0], word[1], 'absorb-ra-word');- m2 = st.map = RA.nodeMap(doc);- RA.wrap(doc, m2, word[1], st.sEnd, 'absorb-ra-dim');- } else {- RA.wrap(doc, m2, st.sStart, st.sEnd, 'absorb-ra-word');- }- st.map = null;};- RA.location = function() {- if (RA.loc) return RA.loc;- try { RA.loc = rendition.currentLocation(); } catch (e) { RA.loc = null; }- return RA.loc;+ // A sentence ends at . ! or ? only when what follows (after any closing+ // quotes or brackets) is whitespace or the end of the block - so "£8.99",+ // "e.g." and "U.S." stay inside one sentence.+ RA.isTerm = function(raw, i) {+ var ch = raw[i];+ if (ch !== '.' && ch !== '!' && ch !== '?') return false;+ var j = i + 1;+ while (j < raw.length && '"\'”’)]'.indexOf(raw[j]) !== -1) j++;+ return j >= raw.length || /\s/.test(raw[j]);};- /// Whether [range] sits on the page currently on screen, and its CFI so the- /// caller can turn to it when it doesn't.- RA.visibleAt = function(range) {- var out = { v: true };+ /// Whether [el] is on the page currently on screen, judged by where it+ /// sits in the iframe's viewport rather than by CFI arithmetic - the spans+ /// change the DOM under epub.js's own location CFIs, so those two never+ /// quite agree. dir is -1 when it lies before the page, 1 after. Paginated+ /// flow lays pages out sideways, scrolled flow downwards; whichever axis+ /// the page actually overflows on decides.+ RA.visibleEl = function(el) {+ var out = { v: true, dir: 0 };try {- var cfi = RA.cur.contents.cfiFromRange(range);- if (!cfi) return out;- out.cfi = cfi;- var loc = RA.location();- if (!loc || !loc.start || !loc.end) return out;- var cmp = new ePub.CFI();- out.v = cmp.compare(cfi, loc.start.cfi) >= 0 &&- cmp.compare(cfi, loc.end.cfi) <= 0;+ if (!el) return out;+ var doc = el.ownerDocument, win = doc.defaultView;+ var rect = el.getBoundingClientRect();+ if (!rect || (rect.width === 0 && rect.height === 0)) return out;+ // The section's iframe holds every page of the section side by side+ // (or the whole scroll), so a rect inside it says nothing on its own.+ // Offset by where the iframe sits in the reader page and judge+ // against the reader's viewport, which is what is actually on screen.+ var fe = win.frameElement;+ var fr = fe ? fe.getBoundingClientRect() : { left: 0, top: 0 };+ var W = window.innerWidth, H = window.innerHeight;+ var flow = '';+ try { flow = (rendition.settings && rendition.settings.flow) || ''; } catch (e0) {}+ var sideways = flow.indexOf('scrolled') === -1;+ if (sideways) {+ var mid = fr.left + (rect.left + rect.right) / 2;+ out.v = mid >= 0 && mid < W;+ out.dir = mid < 0 ? -1 : (mid >= W ? 1 : 0);+ out.x = Math.round(mid); out.w = W;+ } else {+ var midY = fr.top + (rect.top + rect.bottom) / 2;+ out.v = midY >= 0 && midY < H;+ out.dir = midY < 0 ? -1 : (midY >= H ? 1 : 0);+ out.x = Math.round(midY); out.w = H;+ }} catch (e) {}return out;};+ /// A CFI for the DOM as it is right now, spans included. It is only ever+ /// handed straight back to rendition.display(), which resolves it against+ /// the same DOM, so the spans being in the path is what makes it right.+ RA.cfiFor = function(c, firstEl, lastEl) {+ try {+ var r = firstEl.ownerDocument.createRange();+ r.setStartBefore(firstEl);+ r.setEndAfter(lastEl || firstEl);+ return c.cfiFromRange(r) || '';+ } catch (e) { return ''; }+ };+// held:false means the anchor is gone (the page turned into another// section) and the caller should locate the sentence again. visible:false- // means this word is on the next page - following word by word, that is- // where the page should turn, not at the end of the sentence.+ // means this word is on another page, dir says which way.RA.word = function(i) {if (!RA.cur) return JSON.stringify({ held: false });if (RA.cur.painted !== i) {RA.cur.painted = i;RA.paint(i);}- var out = { held: true, visible: true };+ var out = { held: true, visible: true, dir: 0 };try {var st = RA.cur;- var w = (i >= 0 && st.words.length)- ? st.words[Math.min(i, st.words.length - 1)] : null;- if (w) {- var map = st.map || (st.map = RA.nodeMap(st.doc));- var r = RA.range(st.doc, map, w[0], w[1]);- if (r) {- var vis = RA.visibleAt(r);- out.visible = vis.v;- if (vis.cfi) out.cfi = vis.cfi;- }+ var j = (i >= 0 && st.spans.length) ? Math.min(i + st.first, st.spans.length - 1) : -1;+ var group = j >= 0 ? st.spans[j] : null;+ if (group && group.length) {+ if (!group[0].isConnected) return JSON.stringify({ held: false });+ var vis = RA.visibleEl(group[0]);+ out.visible = vis.v;+ out.dir = vis.dir;+ out.x = vis.x; out.w = vis.w;+ if (!vis.v) out.cfi = RA.cfiFor(st.contents, group[0], group[group.length - 1]);}} catch (e) {}return JSON.stringify(out);@@ -239,12 +297,6 @@ String readAlongBootstrap(int argb) {RA.clearDoc = function(doc) {if (!doc) return;- try {- if (RA.useHighlights(doc)) {- doc.defaultView.CSS.highlights.delete('absorbRaWord');- doc.defaultView.CSS.highlights.delete('absorbRaDim');- }- } catch (e) {}RA.unwrap(doc);};@@ -287,7 +339,8 @@ String readAlongBootstrap(int argb) {/// Find [needle] in the rendered pages, snap it out to sentence bounds, and/// paint it. Returns whether it was found, whether it sits on the visible- /// page, and how many words the matched span holds.+ /// page (and which way it lies otherwise), and how many words the matched+ /// span holds.RA.locate = function(needle, wordMode, minOffset) {var out = { found: false };try {@@ -300,13 +353,13 @@ String readAlongBootstrap(int argb) {var normChars = [], idx = [], prevSpace = true;for (var k = 0; k < lower.length; k++) {var ch = lower[k];- if (/\\s/.test(ch)) {+ if (/\s/.test(ch)) {if (!prevSpace) { normChars.push(' '); idx.push(k); }prevSpace = true;} else { normChars.push(ch); idx.push(k); prevSpace = false; }}var hay = normChars.join('');- var q = needle.toLowerCase().replace(/\\s+/g, ' ').trim();+ var q = needle.toLowerCase().replace(/\s+/g, ' ').trim();// A phrase can occur more than once on a page ("he said", a repeated// refrain). Narration only moves forward, so prefer the first// occurrence at or after where the last sentence was, and fall back to@@ -323,59 +376,95 @@ String readAlongBootstrap(int argb) {// Snap the span to full sentence boundaries: Whisper segments cut// wherever they like, and mid-sentence spans read as glitches. A whole// sentence is also stable - consecutive segments inside one sentence- // resolve to the same range, so the coloring holds still.+ // resolve to the same range, so the coloring holds still. A paragraph+ // edge (virtual newline) is always a boundary.var sStart = rs;for (var bk = rs - 1; bk >= 0 && rs - bk < 400; bk--) {- var cb = raw[bk];- if (cb === '.' || cb === '!' || cb === '?' || cb === '\\n') { sStart = bk + 1; break; }+ if (raw[bk] === '\n' || RA.isTerm(raw, bk)) { sStart = bk + 1; break; }if (bk === 0) sStart = 0;}- while (sStart < rs && /\\s/.test(raw[sStart])) sStart++;+ while (sStart < rs && (/\s/.test(raw[sStart]) || '"\'”’)]'.indexOf(raw[sStart]) !== -1)) sStart++;// End at the FIRST sentence terminator after the needle's start, so// the span is always exactly one sentence - even when an older cached// line covers several.var sEnd = reEnd;for (var f = rs; f < raw.length && f - rs < 400; f++) {- var cf = raw[f];- if (cf === '.' || cf === '!' || cf === '?') {+ if (RA.isTerm(raw, f)) {var j2 = f + 1;- while (j2 < raw.length && (raw[j2] === '"' || raw[j2] === "'" || raw[j2] === '”' || raw[j2] === '’')) j2++;+ while (j2 < raw.length && '"\'”’)]'.indexOf(raw[j2]) !== -1) j2++;sEnd = j2; break;}- if (cf === '\\n') { sEnd = f; break; }+ if (raw[f] === '\n') { sEnd = f; break; }}if (sEnd <= sStart) sEnd = reEnd;- var words = [], wre = /\\S+/g, sub = raw.slice(rs, reEnd), wm;- while ((wm = wre.exec(sub))) words.push([rs + wm.index, rs + wm.index + wm[0].length]);+ // Every word of the sentence gets a span; the needle's words are the+ // ones the narration walks, starting at [first].+ var words = [], wre = /\S+/g, sub = raw.slice(sStart, sEnd), wm;+ while ((wm = wre.exec(sub))) words.push([sStart + wm.index, sStart + wm.index + wm[0].length]);+ var first = 0, count = 0;+ for (var wi = 0; wi < words.length; wi++) {+ if (words[wi][1] <= rs) first = wi + 1;+ if (words[wi][0] < reEnd && words[wi][1] > rs) count++;+ }+ if (first >= words.length) first = Math.max(0, words.length - 1);+ if (count <= 0) count = Math.max(1, words.length - first);out.found = true;- out.words = words.length;+ out.words = count;out.visible = true;+ out.dir = 0;out.at = sStart;- out.sentence = raw.slice(sStart, Math.min(sEnd, sStart + 90)).replace(/\\s+/g, ' ');- // Work the CFI out before painting: on the span fallback, painting- // splits text nodes, and a CFI taken from that DOM would not survive- // the unwrap.+ out.sentence = raw.slice(sStart, Math.min(sEnd, sStart + 90)).replace(/\s+/g, ' ');+ // The old sentence only goes once the new one is found, so a miss+ // leaves the last sentence lit. Unwrapping merges text nodes, so the+ // map is rebuilt before wrapping; the raw text and every offset in+ // it are unchanged.+ if (RA.cur) {+ RA.clearDoc(RA.cur.doc);+ RA.cur = null;+ map = RA.nodeMap(doc);+ }+ RA.style(doc);+ var spans = [];+ if (wordMode && words.length) {+ for (var wk = words.length - 1; wk >= 0; wk--) {+ spans[wk] = RA.wrap(doc, map, words[wk][0], words[wk][1], 'absorb-ra-w');+ }+ } else {+ spans = [RA.wrap(doc, map, sStart, sEnd, 'absorb-ra-s')];+ words = [[sStart, sEnd]];+ first = 0;+ }+ RA.cur = { doc: doc, contents: c, sStart: sStart, sEnd: sEnd, words: words,+ first: first, spans: spans, painted: -2 };+ // Where the sentence sits is judged from the spans themselves, now+ // that they are in the page.try {- var r = RA.range(doc, map, sStart, sEnd);- var cfi = r ? c.cfiFromRange(r) : null;- out.cfi = cfi || '';- var loc = RA.location();- if (cfi && loc && loc.start && loc.end) {- var cmp = new ePub.CFI();- out.visible = cmp.compare(cfi, loc.start.cfi) >= 0 && cmp.compare(cfi, loc.end.cfi) <= 0;+ var flat = [];+ for (var fa = 0; fa < spans.length; fa++) {+ for (var fb = 0; fb < spans[fa].length; fb++) flat.push(spans[fa][fb]);+ }+ if (flat.length) {+ var vis = RA.visibleEl(flat[0]);+ out.visible = vis.v;+ out.dir = vis.dir;+ out.cfi = vis.v ? '' : RA.cfiFor(c, flat[0], flat[flat.length - 1]);}} catch (e1) {}- if (RA.cur && RA.cur.doc !== doc) RA.clearDoc(RA.cur.doc);- RA.style(doc);- RA.cur = { doc: doc, contents: c, sStart: sStart, sEnd: sEnd, words: words, map: map, painted: -2 };- var first = (wordMode && words.length) ? 0 : -1;- RA.paint(first);- RA.cur.painted = first;+ var start = (wordMode && count) ? 0 : -1;+ RA.paint(start);+ RA.cur.painted = start;+ // The spans arrive in their "in" state (page color); dropping it on+ // the next frame lets the tint fade in rather than snap.+ var fresh = spans;+ var win = doc.defaultView || window;+ (win.requestAnimationFrame || function(f) { setTimeout(f, 16); })(function() {+ for (var a = 0; a < fresh.length; a++) {+ for (var b2 = 0; b2 < fresh[a].length; b2++) fresh[a][b2].classList.remove('absorb-ra-in');+ }+ });break;}} catch (e) { out.err = String(e); }return JSON.stringify(out);};-})();''';-}diff --git a/lib/widgets/ebook_reader_view.dart b/lib/widgets/ebook_reader_view.dartindex 686467a0..17a81207 100644--- a/lib/widgets/ebook_reader_view.dart+++ b/lib/widgets/ebook_reader_view.dart@@ -13,6 +13,7 @@ import '../l10n/app_localizations.dart';import '../providers/auth_provider.dart';import '../providers/library_provider.dart';import '../screens/app_shell.dart';+import '../services/api_service.dart';import '../services/audio_player_service.dart';import '../services/ebook_annotation_service.dart';import '../services/ebook_cache.dart';@@ -161,6 +162,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsbool _readAlongOn = false;Timer? _readAlongTimer;double? _readAlongLineStart;+ double _readAlongLineLastWord = 0;int _readAlongColor = PlayerSettings.defaultReadAlongColor;String _readAlongMode = 'word';// Words in the sentence as the page spells it, and as the transcript line@@ -174,10 +176,17 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsdouble _readAlongLastPos = 0;DateTime _readAlongLastScan = DateTime.fromMillisecondsSinceEpoch(0);// Guards against turning the page twice for the same spot.- String? _readAlongTurnedTo;DateTime _readAlongLastTurn = DateTime.fromMillisecondsSinceEpoch(0);bool _readAlongStartedPipeline = false;bool _readAlongLocating = false;+ bool _readAlongAllowBack = false;+ DateTime? _readAlongTurnPending;+ DateTime? _readAlongMissSince;+ bool _readAlongStepped = false;+ DateTime? _readAlongSeekAt;+ DateTime? _readAlongLastMatch;+ bool _readAlongLost = false;+ DateTime _readAlongOffPageLog = DateTime.fromMillisecondsSinceEpoch(0);// Reader settingsint _fontSize = 16;@@ -258,8 +267,8 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs// Volume-key turns are ignored while auto scroll runs: the blind is already// showing the next page, and a turn underneath it leaves that page unread.late final EreaderVolumeNav _volumeNav = EreaderVolumeNav(- onPrev: () { if (!_autoScroll) _epubController?.prev(); },- onNext: () { if (!_autoScroll) _epubController?.next(); },+ onPrev: () { if (!_autoScroll && !_readAlongOn) _epubController?.prev(); },+ onNext: () { if (!_autoScroll && !_readAlongOn) _epubController?.next(); },);@override@@ -618,7 +627,12 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsreturn;}_lastReaderTap = now;- final action = frac < 0.25 ? 'prev' : (frac > 0.75 ? 'next' : 'menu');+ // Read along owns the page: a turn underneath it would only be pulled+ // back to the narration. Every tap reaches the controls instead, so the+ // button to switch it off is always one tap away.+ final action = _readAlongOn+ ? 'menu'+ : (frac < 0.25 ? 'prev' : (frac > 0.75 ? 'next' : 'menu'));debugPrint('[ReaderTap] frac=${frac.toStringAsFixed(2)} src=$source -> $action ctrl=${_epubController != null}');final hasHighlights =_annotations.any((a) => a.type == AnnotationType.highlight);@@ -767,18 +781,55 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs}}+ DateTime _ebookPushAt = DateTime.fromMillisecondsSinceEpoch(0);+ (String, double)? _ebookPushPending;+ Timer? _ebookPushTimer;+ ApiService? _ebookPushApi;+void _syncProgress(String cfi, double progress) {final auth = context.read<AuthProvider>();final api = auth.apiService;if (api == null) return;+ _ebookPushApi = api;+ context.read<LibraryProvider>().applyLocalEbookProgress(+ widget.itemId, location: cfi, progress: progress);+ // Read along turns the pages itself, several times a minute and in+ // bursts while a page settles. One server write every 15s is plenty for+ // that; the latest position wins and whatever is pending goes out when+ // read along stops.+ if (_readAlongOn) {+ _ebookPushPending = (cfi, progress);+ final since = DateTime.now().difference(_ebookPushAt);+ if (since < const Duration(seconds: 15)) {+ _ebookPushTimer ??=+ Timer(const Duration(seconds: 15) - since, _flushEbookPush);+ return;+ }+ _ebookPushPending = null;+ }+ _ebookPushAt = DateTime.now();ProgressSyncService().pushEbookProgress(api,widget.itemId,location: cfi,progress: progress,);- context.read<LibraryProvider>().applyLocalEbookProgress(- widget.itemId, location: cfi, progress: progress);+ }++ void _flushEbookPush() {+ _ebookPushTimer?.cancel();+ _ebookPushTimer = null;+ final pending = _ebookPushPending;+ final api = _ebookPushApi;+ if (pending == null || api == null) return;+ _ebookPushPending = null;+ _ebookPushAt = DateTime.now();+ ProgressSyncService().pushEbookProgress(+ api,+ widget.itemId,+ location: pending.$1,+ progress: pending.$2,+ );}Future<void> _loadAnnotations() async {@@ -1333,6 +1384,8 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs// 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(context: context,backgroundColor: cs.surface,@@ -1526,6 +1579,57 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs),const SizedBox(height: 16),+ // Read along, mirrored from the transcription settings so the+ // reader can change them without leaving the book.+ if (_transcriptionOn) ...[+ Row(children: [+ Icon(Icons.graphic_eq_rounded, size: 20, color: cs.onSurfaceVariant),+ const SizedBox(width: 12),+ Expanded(child: Text(l.readAlong, style: tt.bodyMedium)),+ ]),+ const SizedBox(height: 8),+ SizedBox(+ width: double.infinity,+ child: SegmentedButton<String>(+ segments: [+ ButtonSegment(value: 'word', label: Text(l.readAlongFollowWord)),+ ButtonSegment(value: 'sentence', label: Text(l.readAlongFollowSentence)),+ ],+ selected: {sheetRaMode},+ showSelectedIcon: false,+ onSelectionChanged: (sel) async {+ setSheetState(() => sheetRaMode = sel.first);+ await PlayerSettings.setReadAlongMode(sel.first);+ await LyricsService.instance.reloadDisplayPrefs();+ },+ ),+ ),+ const SizedBox(height: 12),+ Wrap(spacing: 10, runSpacing: 10, children: [+ for (final c in PlayerSettings.readAlongPalette)+ GestureDetector(+ onTap: () async {+ setSheetState(() => sheetRaColor = c);+ await PlayerSettings.setReadAlongColor(c);+ await LyricsService.instance.reloadDisplayPrefs();+ },+ child: Container(+ width: 32,+ height: 32,+ decoration: BoxDecoration(+ color: Color(c),+ shape: BoxShape.circle,+ border: Border.all(+ color: sheetRaColor == c ? cs.onSurface : Colors.transparent,+ width: 2,+ ),+ ),+ ),+ ),+ ]),+ const SizedBox(height: 16),+ ],+// Volume keys turn pages (normal: up = previous, down = next)Row(children: [Icon(Icons.swap_vert_rounded, size: 20, color: cs.onSurfaceVariant),@@ -1681,6 +1785,8 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs});return;}+ // Read along and the blind both move the page; only one runs at a time.+ if (_readAlongOn) _stopReadAlong();// The blind can't start before the book is displayed. Flagging auto// scroll on regardless left the reader with its taps swallowed and no// bars to reach this button again.@@ -3318,10 +3424,20 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs}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;+ });+ }if (!LyricsService.instance.isOn) {await LyricsService.instance.enableForCurrent();_readAlongStartedPipeline = true;}+ LyricsService.instance.readerOwns = true;_readAlongColor = LyricsService.instance.readAlongColor;_readAlongMode = LyricsService.instance.readAlongMode;_readAlongLastPos = player.position.inMilliseconds / 1000.0;@@ -3330,9 +3446,17 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsawait wc?.evaluateJavascript(source: 'window.__absorbRA && __absorbRA.start()');if (mounted) setState(() => _readAlongOn = true);+ // 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: 250), (_) => _readAlongTick());+ const Duration(milliseconds: 100), (_) => _readAlongTick());debugPrint('[ReadAlong] enabled for ${widget.itemId}');}@@ -3344,6 +3468,63 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsreturn 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)),+ ),+ ],+ ),+ );+ }+ final gate = svc.gateProgress;+ 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(+ '${AppLocalizations.of(context)!.lyricsListeningAhead} '+ '${(gate * 100).round()}%',+ style: TextStyle(+ fontSize: 12,+ fontWeight: FontWeight.w600,+ color: fg.withValues(alpha: 0.75)),+ ),+ ],+ ),+ );+ }final ms = svc.offsetMs;final label = ms == 0? '0'@@ -3401,6 +3582,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsvoid _stopReadAlong() {_readAlongTimer?.cancel();_readAlongTimer = null;+ _flushEbookPush();// Runs from dispose() too, when the WebView may already be on its way out.try {_epubController?.webViewController@@ -3412,7 +3594,12 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs_readAlongLineWords = 0;_readAlongWordIndex = -1;_readAlongAt = -1;- _readAlongTurnedTo = null;+ _readAlongAllowBack = false;+ _readAlongSeekAt = null;+ _readAlongLastMatch = null;+ _readAlongLost = false;+ LyricsService.instance.readerOwns = false;+ if (!_autoScroll) ScreenWake.keepOn(false);if (_readAlongStartedPipeline) {LyricsService.instance.disable();_readAlongStartedPipeline = false;@@ -3440,12 +3627,19 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs_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) return;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;- final line = TranscriptLineStore.instance- .lineNear(widget.itemId, heard + 0.35 * player.speed);+ // 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.@@ -3454,8 +3648,43 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsif (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@@ -3469,9 +3698,22 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs'${_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;_readAlongLocating = true;try {@@ -3497,7 +3739,15 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsfinal scaled = _readAlongLineWords > 0? (idx * _readAlongPageWords / _readAlongLineWords).floor(): idx;- final wordIndex = scaled.clamp(0, _readAlongPageWords - 1);+ 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(@@ -3521,15 +3771,53 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs// 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.- final cfi = d['cfi'];- if (d['visible'] == false && cfi is String && cfi.isNotEmpty) {- final since = DateTime.now().difference(_readAlongLastTurn);- if (cfi != _readAlongTurnedTo && since > const Duration(milliseconds: 500)) {- _readAlongTurnedTo = cfi;- _readAlongLastTurn = DateTime.now();- debugPrint('[ReadAlong] word $wordIndex ran onto the next page, turning');- _epubController?.display(cfi: cfi);+ _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();}}@@ -3562,6 +3850,13 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs}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;@@ -3570,9 +3865,8 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsdebugPrint('[ReadAlong] "$head" -> page@$_readAlongAt ''words=$_readAlongPageWords visible=${d['visible']} ''${watch.elapsedMilliseconds}ms | page: "${d['sentence']}"');- final cfi = d['cfi'];- if (d['visible'] == false && cfi is String && cfi.isNotEmpty) {- _epubController?.display(cfi: cfi);+ if (d['visible'] == false) {+ _readAlongTurn(d['cfi'], d['dir'], why: 'sentence is off the page');}return;}@@ -3582,15 +3876,32 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs// 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- // freezes tracking while it runs. One miss is usually just a sentence- // sitting off the current page, so don't pay for it on every miss.- final since = DateTime.now().difference(_readAlongLastScan);- if (since < const Duration(seconds: 10)) {- debugPrint('[ReadAlong] skipping the whole-book scan '- '(last one ${since.inSeconds}s ago)');+ // 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;+ // 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 (!_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 (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 = DateTime.now();+ _readAlongLastScan = now;final hres = await wc.callAsyncJavaScript(functionBody: r'''var sb = window.__absorbSearchBook;if (!sb) {@@ -3609,6 +3920,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObstext = 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; }}@@ -3626,6 +3938,9 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObswc.evaluateJavascript(source: 'window.__absorbRA && __absorbRA.clear()');_readAlongPageWords = 0;_readAlongAt = -1;+ _readAlongAllowBack = true;+ _readAlongLastTurn = DateTime.now();+ _readAlongMissSince = null;_epubController?.display(cfi: href);_readAlongLineStart = null;}@@ -4238,6 +4553,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs},onRelocated: (value) {if (!mounted) return;+ _readAlongTurnPending = null;// Ignore relocations while backgrounded: the recents/resize// re-paginate fires a stray one that would save the wrong page.// Note it so the resume path knows the page needs restoring.