A cross platform Audiobookshelf client for Android and iOS
Dart
Add a Translate button to the reader, sync highlights with BookOrbit both ways, jump read along straight to the sentence when you're far behind and stop the page wobble in paged mode
Barnabas96af4b51e755
diff --git a/lib/screens/bookmarks_screen.dart b/lib/screens/bookmarks_screen.dartindex fb775ba0..e66d5f13 100644--- a/lib/screens/bookmarks_screen.dart+++ b/lib/screens/bookmarks_screen.dart@@ -16,7 +16,7 @@ import '../widgets/bookmark_detail_dialog.dart';import '../widgets/card_buttons.dart';import '../services/download_service.dart';import '../services/ebook_annotation_service.dart';-import '../services/ebook_cache.dart';+import '../services/highlight_sync.dart';import '../utils/episode_key.dart';import '../widgets/absorb_page_header.dart';import '../widgets/adaptive_modal.dart';@@ -126,6 +126,15 @@ class _BookmarksScreenState extends State<BookmarksScreen>return out;}+ /// A server that keeps highlights too (BookOrbit) hears about deletes+ /// straight away; offline they wait for the next sync.+ void _sendHighlightChanges(String itemId) {+ final api = context.read<AuthProvider>().apiService;+ if (api != null && api.keepsEbookHighlights) {+ unawaited(HighlightSync.instance.push(api, itemId, null));+ }+ }+Future<void> _loadHighlights() async {final highlights = await EbookAnnotationService().getAllHighlights();if (!mounted) return;@@ -412,6 +421,7 @@ class _BookmarksScreenState extends State<BookmarksScreen>await EbookAnnotationService().delete(itemId: entry.key, annotationId: id);}+ _sendHighlightChanges(entry.key);}_exitSelection();@@ -638,35 +648,8 @@ class _BookmarksScreenState extends State<BookmarksScreen>/// Opens the book at the highlight. A downloaded ebook opens from the reader/// cache, so this still works offline.Future<void> _openHighlight(String itemId, EbookAnnotation highlight) async {- final l = AppLocalizations.of(context)!;- final api = context.read<AuthProvider>().apiService;- var title = _resolveTitle(itemId);- var ebookFile = await cachedEbookFileFor(itemId);- if (ebookFile == null && api != null) {- final item = await api.getLibraryItem(itemId);- ebookFile = resolveEbookFile(item);- if (title == null) {- final media = item?['media'] as Map<String, dynamic>? ?? {};- final metadata = media['metadata'] as Map<String, dynamic>? ?? {};- title = metadata['title'] as String?;- }- }- if (!mounted) return;- if (ebookFile == null) {- showOverlayToast(- context,- api == null ? l.bookmarksNotConnected : l.noEbookFileFound,- icon: Icons.menu_book_outlined,- );- return;- }- await openEbookReader(- context,- itemId: itemId,- title: title ?? '',- ebookFile: ebookFile,- openAtCfi: highlight.cfi,- );+ await openHighlightInReader(context,+ itemId: itemId, cfi: highlight.cfi, title: _resolveTitle(itemId));// Highlights added or removed while reading show up on the way back.if (mounted) await _loadHighlights();}@@ -728,6 +711,7 @@ class _BookmarksScreenState extends State<BookmarksScreen>} else if (action == 'delete') {await EbookAnnotationService().delete(itemId: itemId, annotationId: highlight.id);+ _sendHighlightChanges(itemId);await _loadHighlights();if (mounted) {showOverlayToast(context, l.highlightDeleted,diff --git a/lib/services/ebook_annotation_service.dart b/lib/services/ebook_annotation_service.dartindex cf97a2ea..adda47d7 100644--- a/lib/services/ebook_annotation_service.dart+++ b/lib/services/ebook_annotation_service.dart@@ -6,13 +6,19 @@ import 'settings_sync_service.dart';/// Types of ebook annotations.enum AnnotationType { highlight, bookmark }-/// Highlight color presets.+/// Highlight colors: BookOrbit's ten, so a highlight keeps its color there+/// and in every reader it syncs with.enum HighlightColor {- yellow('#FFEB3B'),- green('#66BB6A'),- blue('#42A5F5'),- pink('#EC407A'),- orange('#FFA726');+ yellow('#FACC15'),+ green('#4ADE80'),+ blue('#38BDF8'),+ pink('#F472B6'),+ orange('#FB923C'),+ red('#F87171'),+ olive('#84CC16'),+ cyan('#22D3EE'),+ purple('#C084FC'),+ gray('#9CA3AF');final String hex;const HighlightColor(this.hex);@@ -31,8 +37,9 @@ class EbookAnnotation {/// reopening the book.final String? chapter;final DateTime createdAt;- /// The bookmark's id on the server, for the readers that also keep it- /// there (a picture EPUB on BookOrbit). Null when it lives only here.+ /// The annotation's id on the server, for the ones also kept there (a+ /// picture EPUB's bookmarks and any book's highlights on BookOrbit). Null+ /// when it lives only here.String? serverId;EbookAnnotation({@@ -100,6 +107,8 @@ class EbookAnnotationService {EbookAnnotationService._();static const _keyPrefix = 'ebook_annotations_';+ // Highlight deletes and edits made here that the server hasn't had yet.+ static const _pendingPrefix = 'ebook_highlight_sync_';// Two annotations made in the same millisecond used to share an id, which// made them one row to anything that works by id - selecting, deleting,@@ -164,7 +173,7 @@ class EbookAnnotationService {SettingsSyncService().noteLocalChange();}- /// Add a highlight.+ /// Add a highlight. [fromServer] is one brought in from the server.Future<EbookAnnotation> addHighlight({required String itemId,required String cfi,@@ -172,6 +181,9 @@ class EbookAnnotationService {HighlightColor color = HighlightColor.yellow,String? note,String? chapter,+ String? serverId,+ DateTime? createdAt,+ bool fromServer = false,}) async {final annotation = EbookAnnotation(id: _newId(),@@ -181,6 +193,8 @@ class EbookAnnotationService {color: color,note: note,chapter: chapter,+ serverId: serverId,+ createdAt: createdAt,);final annotations = await getAnnotations(itemId);annotations.insert(0, annotation);@@ -212,29 +226,34 @@ class EbookAnnotationService {return annotation;}- /// Update a note on an annotation.+ /// Change a highlight's color. [fromServer] is a change brought in from+ /// the server, which has nothing to send back.Future<void> updateColor({required String itemId,required String annotationId,required HighlightColor color,+ bool fromServer = false,}) async {final annotations = await getAnnotations(itemId);final idx = annotations.indexWhere((a) => a.id == annotationId);if (idx == -1) return;annotations[idx].color = color;await _save(itemId, annotations);+ if (!fromServer) await _noteServerChange(itemId, annotations[idx], deleted: false);}Future<void> updateNote({required String itemId,required String annotationId,required String? note,+ bool fromServer = false,}) async {final annotations = await getAnnotations(itemId);final idx = annotations.indexWhere((a) => a.id == annotationId);if (idx == -1) return;annotations[idx].note = note;await _save(itemId, annotations);+ if (!fromServer) await _noteServerChange(itemId, annotations[idx], deleted: false);}Future<void> setServerId({@@ -249,17 +268,66 @@ class EbookAnnotationService {await _save(itemId, annotations);}- /// Delete an annotation.+ /// Delete an annotation. [fromServer] is one already gone from the server.Future<void> delete({required String itemId,required String annotationId,+ bool fromServer = false,}) async {final annotations = await getAnnotations(itemId);+ final gone = annotations.where((a) => a.id == annotationId).firstOrNull;annotations.removeWhere((a) => a.id == annotationId);await _save(itemId, annotations);+ if (gone != null && !fromServer) await _noteServerChange(itemId, gone, deleted: true);debugPrint('[EbookAnnotations] Deleted annotation $annotationId');}+ /// Highlight deletes and edits made here that the server hasn't had, by+ /// server id. A delete waiting here also keeps the next sync from bringing+ /// the highlight back.+ Future<({Set<String> deletes, Set<String> edits})> pendingServerChanges(String itemId) async {+ final raw = await ScopedPrefs.getString('$_pendingPrefix$itemId');+ if (raw == null) return (deletes: <String>{}, edits: <String>{});+ try {+ final j = jsonDecode(raw) as Map<String, dynamic>;+ return (+ deletes: {for (final v in (j['delete'] as List? ?? const [])) '$v'},+ edits: {for (final v in (j['edit'] as List? ?? const [])) '$v'},+ );+ } catch (_) {+ return (deletes: <String>{}, edits: <String>{});+ }+ }++ Future<void> _savePending(String itemId, Set<String> deletes, Set<String> edits) async {+ final key = '$_pendingPrefix$itemId';+ if (deletes.isEmpty && edits.isEmpty) {+ await ScopedPrefs.remove(key);+ } else {+ await ScopedPrefs.setString(key, jsonEncode({'delete': deletes.toList(), 'edit': edits.toList()}));+ }+ }++ Future<void> _noteServerChange(String itemId, EbookAnnotation a, {required bool deleted}) async {+ final id = a.serverId;+ if (a.type != AnnotationType.highlight || id == null) return;+ final p = await pendingServerChanges(itemId);+ if (deleted) {+ p.deletes.add(id);+ p.edits.remove(id);+ } else {+ p.edits.add(id);+ }+ await _savePending(itemId, p.deletes, p.edits);+ }++ /// The server has the change made here to the highlight [serverId].+ Future<void> serverChangeDone(String itemId, String serverId) async {+ final p = await pendingServerChanges(itemId);+ if (!p.deletes.remove(serverId) && !p.edits.remove(serverId)) return;+ await _savePending(itemId, p.deletes, p.edits);+ }+/// Check if a bookmark exists at the given CFI.Future<bool> hasBookmarkAt(String itemId, String cfi) async {final bookmarks = await getBookmarks(itemId);diff --git a/lib/services/highlight_sync.dart b/lib/services/highlight_sync.dartnew file mode 100644index 00000000..dc61e106--- /dev/null+++ b/lib/services/highlight_sync.dart@@ -0,0 +1,198 @@+import 'package:flutter/foundation.dart';++import 'api_service.dart';+import 'ebook_annotation_service.dart';++// KOReader's and Kobo's own shades, which BookOrbit can pass along from a+// highlight made there, by the name it gives each. Pale ones are too far+// from every color here to be matched by nearness.+const _deviceColors = {+ '#ff3300': HighlightColor.red,+ '#ff8800': HighlightColor.orange,+ '#ffff33': HighlightColor.yellow,+ '#00aa66': HighlightColor.green,+ '#88ff77': HighlightColor.olive,+ '#00ffee': HighlightColor.cyan,+ '#0066ff': HighlightColor.blue,+ '#ee00ff': HighlightColor.purple,+ '#808080': HighlightColor.gray,+ '#f6f3b3': HighlightColor.yellow,+ '#c6e09e': HighlightColor.green,+ '#b2e1e8': HighlightColor.blue,+ '#e8afcf': HighlightColor.pink,+};++String serverHighlightColor(HighlightColor color) => color.hex;++HighlightColor highlightColorFromServer(String? color) {+ final c = (color ?? '').trim().toLowerCase();+ for (final h in HighlightColor.values) {+ if (h.name == c || h.hex.toLowerCase() == c) return h;+ }+ final device = _deviceColors[c];+ if (device != null) return device;+ final hex = c.startsWith('#') ? c.substring(1) : c;+ final value = hex.length == 6 ? int.tryParse(hex, radix: 16) : null;+ if (value == null) return HighlightColor.yellow;+ int r(int v) => v >> 16 & 0xFF;+ int g(int v) => v >> 8 & 0xFF;+ int b(int v) => v & 0xFF;+ var best = HighlightColor.yellow;+ var bestDistance = 1 << 30;+ for (final h in HighlightColor.values) {+ final v = int.parse(h.hex.substring(1), radix: 16);+ final d = (r(v) - r(value)) * (r(v) - r(value)) ++ (g(v) - g(value)) * (g(v) - g(value)) ++ (b(v) - b(value)) * (b(v) - b(value));+ if (d < bestDistance) {+ bestDistance = d;+ best = h;+ }+ }+ return best;+}++/// Keeps ebook highlights in step with a server that holds them too+/// (BookOrbit). Highlights made, recolored, noted or deleted here go up, and+/// opening a book brings in what was done there. Changes that couldn't reach+/// the server wait in [EbookAnnotationService] until the next try.+class HighlightSync {+ HighlightSync._();+ static final instance = HighlightSync._();++ final Map<String, Future<bool>> _chains = {};++ /// Sends what changed here and brings in what changed on the server. True+ /// when the highlights here changed.+ Future<bool> sync(ApiService api, String itemId, String fileId) =>+ _queue(itemId, () => _run(api, itemId, fileId, pull: true));++ /// Sends what changed here, without asking the server for its own. With no+ /// [fileId] new highlights wait, since the server files them by book file.+ Future<void> push(ApiService api, String itemId, String? fileId) =>+ _queue(itemId, () => _run(api, itemId, fileId, pull: false));++ Future<bool> _queue(String itemId, Future<bool> Function() job) {+ final previous = _chains[itemId] ?? Future.value(false);+ final next = previous.then((_) => job()).catchError((Object e) {+ debugPrint('[HighlightSync] $itemId failed: $e');+ return false;+ });+ _chains[itemId] = next;+ return next;+ }++ Future<bool> _run(ApiService api, String itemId, String? fileId, {required bool pull}) async {+ if (!api.keepsEbookHighlights) return false;+ final store = EbookAnnotationService();+ var changed = false;+ var removed = 0;+ var added = 0;+ var sent = 0;++ // Deletes and edits made here that haven't reached the server yet.+ final pending = await store.pendingServerChanges(itemId);+ for (final id in pending.deletes) {+ if (await api.deleteEbookHighlight(itemId, id)) await store.serverChangeDone(itemId, id);+ }+ if (pending.edits.isNotEmpty) {+ final local = await store.getAnnotations(itemId);+ for (final id in pending.edits) {+ final a = local.where((x) => x.serverId == id).firstOrNull;+ if (a == null ||+ await api.updateEbookHighlight(itemId, id,+ color: serverHighlightColor(a.color ?? HighlightColor.yellow), note: a.note)) {+ await store.serverChangeDone(itemId, id);+ }+ }+ }++ if (pull && fileId != null) {+ final server = await api.ebookHighlights(itemId, fileId: fileId);+ if (server == null) return false;+ final waiting = await store.pendingServerChanges(itemId);+ var local = await store.getAnnotations(itemId);+ final seen = <String>{};+ for (final s in server) {+ final id = s['id'] as String;+ seen.add(id);+ if (waiting.deletes.contains(id)) continue;+ final cfi = s['cfi'];+ if (cfi is! String || cfi.isEmpty) continue;+ // Another file of the same book (an EPUB beside a narrated one).+ final file = s['fileId'];+ if (file != null && file != fileId) continue;+ final color = highlightColorFromServer(s['color'] as String?);+ final note = (s['note'] as String?)?.trim();+ final mine = local.where((a) => a.serverId == id).firstOrNull ??+ local+ .where((a) => a.type == AnnotationType.highlight && a.serverId == null && a.cfi == cfi)+ .firstOrNull;+ if (mine == null) {+ await store.addHighlight(+ itemId: itemId,+ cfi: cfi,+ selectedText: (s['text'] as String?) ?? '',+ color: color,+ note: note == null || note.isEmpty ? null : note,+ chapter: s['chapter'] as String?,+ serverId: id,+ createdAt: DateTime.tryParse('${s['at']}')?.toLocal(),+ fromServer: true,+ );+ added++;+ changed = true;+ continue;+ }+ if (mine.serverId == null) {+ await store.setServerId(itemId: itemId, annotationId: mine.id, serverId: id);+ }+ // An edit made here wins until it has been sent.+ if (waiting.edits.contains(id)) continue;+ if (mine.color != color) {+ await store.updateColor(itemId: itemId, annotationId: mine.id, color: color, fromServer: true);+ changed = true;+ }+ if ((mine.note ?? '') != (note ?? '')) {+ await store.updateNote(+ itemId: itemId, annotationId: mine.id, note: note == null || note.isEmpty ? null : note, fromServer: true);+ changed = true;+ }+ }+ // Deleted on the server since they were sent or brought in.+ local = await store.getAnnotations(itemId);+ for (final a in local) {+ if (a.type == AnnotationType.highlight && a.serverId != null && !seen.contains(a.serverId)) {+ await store.delete(itemId: itemId, annotationId: a.id, fromServer: true);+ removed++;+ changed = true;+ }+ }+ }++ // Made here and not on the server yet, including any from before.+ if (fileId != null) {+ for (final a in await store.getAnnotations(itemId)) {+ if (a.type != AnnotationType.highlight || a.serverId != null) continue;+ final text = a.selectedText ?? '';+ if (text.trim().isEmpty) continue;+ final id = await api.addEbookHighlight(itemId, fileId,+ cfi: a.cfi,+ text: text,+ color: serverHighlightColor(a.color ?? HighlightColor.yellow),+ note: a.note,+ chapter: a.chapter);+ // Offline or refused: the rest wait for the next try.+ if (id == null) break;+ await store.setServerId(itemId: itemId, annotationId: a.id, serverId: id);+ sent++;+ }+ }++ if (added + removed + sent > 0 || pending.deletes.isNotEmpty || pending.edits.isNotEmpty) {+ debugPrint('[HighlightSync] $itemId: $added from the server, $removed deleted there, $sent sent, '+ '${pending.deletes.length} deletes and ${pending.edits.length} edits caught up');+ }+ return changed;+ }+}diff --git a/lib/services/narration_script.dart b/lib/services/narration_script.dartindex 4e1fb6f8..7b79b84d 100644--- a/lib/services/narration_script.dart+++ b/lib/services/narration_script.dart@@ -74,6 +74,7 @@ const String _body = r'''var x = fr.left + (rect.left + rect.right) / 2;out.v = x >= 0 && x < window.innerWidth;out.dir = x < 0 ? -1 : (x >= window.innerWidth ? 1 : 0);+ out.far = x < -window.innerWidth || x >= window.innerWidth * 2;} else {var y = fr.top + (rect.top + rect.bottom) / 2;out.v = y >= 0 && y < window.innerHeight;@@ -104,8 +105,9 @@ const String _body = r'''};// 'on' when the sentence is on the page in view ('low' when that is near- // the bottom of a scroll), 'before' or 'after' when it is on another page- // of the loaded section, 'missing' when its section isn't loaded.+ // the bottom of a scroll), 'before' or 'after' when it is on the page next+ // to it, 'far-before' or 'far-after' when it is further along the section,+ // 'missing' when its section isn't loaded.MO.show = function(href, id) {var el = MO.find(href, id);if (!el) { MO.clear(); return 'missing'; }@@ -117,6 +119,15 @@ const String _body = r'''}var vis = MO.visible(el);if (vis.low) return 'low';+ if (vis.far) return vis.dir < 0 ? 'far-before' : 'far-after';+ return vis.v ? 'on' : (vis.dir < 0 ? 'before' : 'after');+ };++ // Where the sentence is, the same way, without lighting it.+ MO.where = function(href, id) {+ var el = MO.find(href, id);+ if (!el) return 'missing';+ var vis = MO.visible(el);return vis.v ? 'on' : (vis.dir < 0 ? 'before' : 'after');};diff --git a/lib/services/player_settings.dart b/lib/services/player_settings.dartindex b437d945..bb1c6cdd 100644--- a/lib/services/player_settings.dart+++ b/lib/services/player_settings.dart@@ -1105,6 +1105,11 @@ class PlayerSettings {static Future<bool> getEreaderVolumeNavWhilePlaying() => _get('ereaderVolumeNavWhilePlaying', false);static Future<void> setEreaderVolumeNavWhilePlaying(bool value) => _set('ereaderVolumeNavWhilePlaying', value, notify: true);+ // Ebook reader: where the Translate button sends a selection. Empty means+ // the first translator this device has (see TranslateService).+ static Future<String> getEreaderTranslateWith() => _get('ereaderTranslateWith', '');+ static Future<void> setEreaderTranslateWith(String value) => _set('ereaderTranslateWith', value);+static Future<double> getEreaderAutoScrollSpeed() => _get('ereaderAutoScrollSpeed', 40.0);static Future<void> setEreaderAutoScrollSpeed(double value) => _set('ereaderAutoScrollSpeed', value);static Future<int> getEreaderAutoScrollSleepMinutes() => _get('ereaderAutoScrollSleepMinutes', 30);diff --git a/lib/services/translate_service.dart b/lib/services/translate_service.dartnew file mode 100644index 00000000..e0c08172--- /dev/null+++ b/lib/services/translate_service.dart@@ -0,0 +1,106 @@+import 'dart:async';+import 'dart:io';+import 'dart:ui' show Locale, PlatformDispatcher;++import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';+import 'package:url_launcher/url_launcher.dart';++import 'player_settings.dart';++enum TranslatorKind { app, apple, web }++class Translator {+ final String id;+ final String label;+ final TranslatorKind kind;+ const Translator(this.id, this.label, this.kind);+}++/// Sends a reader selection to a translator: an installed translation app on+/// Android (Google Translate shows its card over the book), Apple's+/// translation sheet on iOS 17.4+, or Google Translate / DeepL on the web.+class TranslateService {+ static const google = 'google';+ static const deepl = 'deepl';+ static const apple = 'apple';+ static const _appPrefix = 'app:';+ static const _maxWebChars = 2000;++ static const _channel = MethodChannel('com.absorb.equalizer');+ @visibleForTesting+ static ProcessTextService processText = DefaultProcessTextService();+ @visibleForTesting+ static bool? appleOverride;++ static final _translatorApp = RegExp(r'translat|deepl|papago|reverso', caseSensitive: false);++ static bool get _apple => appleOverride ?? Platform.isIOS;++ static Future<List<Translator>> available() async {+ final apps = <Translator>[];+ for (final a in await processText.queryTextActions()) {+ if (!_translatorApp.hasMatch('${a.id} ${a.label}')) continue;+ apps.add(Translator('$_appPrefix${a.id}', a.label, TranslatorKind.app));+ }+ apps.sort((a, b) {+ final ga = a.id.contains('com.google.android.apps.translate') ? 0 : 1;+ final gb = b.id.contains('com.google.android.apps.translate') ? 0 : 1;+ return ga != gb ? ga - gb : a.label.toLowerCase().compareTo(b.label.toLowerCase());+ });+ return [+ ...apps,+ if (_apple) const Translator(apple, 'Apple Translate', TranslatorKind.apple),+ const Translator(google, 'Google Translate', TranslatorKind.web),+ const Translator(deepl, 'DeepL', TranslatorKind.web),+ ];+ }++ /// The saved choice if this device still has it, otherwise the first one.+ static Translator pick(List<Translator> options, String saved) =>+ options.firstWhere((t) => t.id == saved, orElse: () => options.first);++ static Future<void> translate(String text) async {+ text = text.trim();+ if (text.isEmpty) return;+ final choice = pick(await available(), await PlayerSettings.getEreaderTranslateWith());+ switch (choice.kind) {+ case TranslatorKind.app:+ // Completes when the translator closes; there is nothing to wait for.+ unawaited(processText+ .processTextAction(choice.id.substring(_appPrefix.length), text, true)+ .then((_) {}, onError: (Object e) {+ debugPrint('[Translate] ${choice.id} failed: $e');+ _openWeb(google, text);+ }));+ case TranslatorKind.apple:+ bool shown = false;+ try {+ shown = await _channel.invokeMethod<bool>('translateText', {'text': text}) ?? false;+ } catch (e) {+ debugPrint('[Translate] Apple translation failed: $e');+ }+ if (!shown) await _openWeb(google, text);+ case TranslatorKind.web:+ await _openWeb(choice.id, text);+ }+ }++ static Future<void> _openWeb(String service, String text) =>+ launchUrl(webUrl(service, text, PlatformDispatcher.instance.locale), mode: LaunchMode.externalApplication);++ @visibleForTesting+ static Uri webUrl(String service, String text, Locale into) {+ if (text.length > _maxWebChars) text = text.substring(0, _maxWebChars);+ final lang = into.languageCode.toLowerCase();+ if (service == deepl) {+ // DeepL reads source/target/text from the fragment and treats a bare+ // slash as a separator, so slashes in the text are escaped its own way.+ final to = lang == 'no' ? 'nb' : lang;+ return Uri.parse('https://www.deepl.com/translator#auto/$to/${Uri.encodeComponent(text.replaceAll('/', r'\/'))}');+ }+ final traditional = into.scriptCode == 'Hant' || const {'TW', 'HK', 'MO'}.contains(into.countryCode);+ final to = lang == 'zh' ? (traditional ? 'zh-TW' : 'zh-CN') : lang;+ return Uri.https('translate.google.com', '/', {'sl': 'auto', 'tl': to, 'text': text, 'op': 'translate'});+ }+}diff --git a/lib/widgets/ebook_reader_view.dart b/lib/widgets/ebook_reader_view.dartindex 94e4240f..a78b763b 100644--- a/lib/widgets/ebook_reader_view.dart+++ b/lib/widgets/ebook_reader_view.dart@@ -25,6 +25,7 @@ import '../services/download_service.dart';import '../services/ebook_annotation_service.dart';import '../services/ebook_cache.dart';import '../services/find_in_ebook.dart';+import '../services/highlight_sync.dart';import '../services/progress_sync_service.dart';import '../services/reader_font_service.dart';import '../services/scoped_prefs.dart';@@ -38,11 +39,13 @@ import '../services/media_overlay.dart';import '../services/narration_script.dart';import '../services/narration_service.dart';import '../services/screen_wake.dart';+import '../services/translate_service.dart';import '../services/sync_point_store.dart';import '../services/transcript_line_store.dart';import '../services/transcription_service.dart';import '../services/volume_key_service.dart';import '../utils/chapter_title_match.dart';+import '../utils/percent_escapes.dart';import 'overlay_toast.dart';import 'page_curl.dart';import 'reader_tap_zones.dart';@@ -310,12 +313,14 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs// Reader settingsint _fontSize = 16;double _lineHeight = 1.4;- // Books justify their text by default; on a narrow screen that opens wide- // gaps between words, so the reader can force a ragged right edge.+ // Justified evens out the book's paragraphs; on a narrow screen that opens+ // wide gaps between words, so the reader can force a ragged right edge.bool _alignLeft = false;int _marginH = 16; // left + rightString _volumeNavMode = 'off';bool _volumeNavWhilePlaying = false;+ List<Translator> _translators = const [];+ String _translateWith = '';// Auto scroll (rolling blind). Speed is px/sec of blind descent; the text// itself never moves, so this is how fast the next page paints over this one.@@ -432,8 +437,12 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsWidgetsBinding.instance.addObserver(this);ReadListenSync.instance.readerOpened(widget.itemId);_readingApi = context.read<AuthProvider>().apiService;+ // BookOrbit keeps reading time as reading, the way its own reader logs+ // it, so it's always counted there. Audiobookshelf has only listening+ // time to put it in, so there it waits for the setting.+ final bookOrbit = _readingApi?.isBookOrbit == true;ScopedPrefs.getBool(_kLogReading).then((on) {- if (on == true && mounted) {+ if ((bookOrbit || on == true) && mounted) {setState(() => _logReading = true);_startReadingClock();}@@ -630,6 +639,8 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsif (mounted) _syncScreenWake();_volumeNavMode = await PlayerSettings.getEreaderVolumeNav();_volumeNavWhilePlaying = await PlayerSettings.getEreaderVolumeNavWhilePlaying();+ _translateWith = await PlayerSettings.getEreaderTranslateWith();+ _translators = await TranslateService.available();_autoScrollSpeed = (await PlayerSettings.getEreaderAutoScrollSpeed()).clamp(_autoScrollMin, _autoScrollMax).toDouble();@@ -651,6 +662,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsif (id == _themeId) return;setState(() => _themeId = id);_applySettings();+ if (PlayerSettings.einkMode) _redrawHighlights();await ScopedPrefs.setString(_kTheme, id);}@@ -942,8 +954,11 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs// Contain keeps a narrowed picture's shape without resizing small// inline ones.'img': {'max-width': '100% !important', 'object-fit': 'contain'},+ // The viewer tags the book's paragraphs "absorb-p", <div>s included:+ // Calibre conversions often set their paragraphs in <div>s.if (_paragraphSpacing >= 0)- 'p': {'margin-top': '0 !important', 'margin-bottom': '${_paragraphSpacing}em !important'},+ 'p, div.absorb-p': {'margin-top': '0 !important', 'margin-bottom': '${_paragraphSpacing}em !important'},+ if (!_alignLeft) '.absorb-p': {'text-align': 'justify !important'},},);}@@ -1608,6 +1623,16 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs} else {unawaited(_rememberForOffline(api));await serverSpot;+ // Read while the book wrongly counted as another account's (its+ // account's address changed before downloads followed it): carry on+ // from the spot kept on the phone, which then goes to the server.+ if (_initialCfi == null && _progress <= 0) {+ final spot = await DownloadService().otherAccountReadingSpot(widget.itemId);+ if (spot != null && mounted) {+ debugPrint('[EbookReader] item=${widget.itemId}: carrying on from the place kept on this phone');+ _usePhoneSpot(spot);+ }+ }}final len = file.existsSync() ? await file.length() : 0;final locations = await loadCachedLocations(file);@@ -1638,6 +1663,10 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs'its place stays on this phone');final spot = await DownloadService().otherAccountReadingSpot(widget.itemId);if (spot == null || !mounted) return;+ _usePhoneSpot(spot);+ }++ void _usePhoneSpot(({String location, double progress}) spot) {_progress = spot.progress.clamp(0.0, 1.0);if (_initialCfi != null) return;if (spot.location.startsWith('epubcfi(')) {@@ -1707,6 +1736,73 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsif (mounted) setState(() {});}+ /// BookOrbit keeps highlights too. Opening the book brings them in step+ /// both ways ([pull]); a change made here only needs sending.+ Future<void> _syncHighlights({bool pull = false}) async {+ if (!mounted) return;+ final api = context.read<AuthProvider>().apiService;+ final fileId = widget.ebookFile['ino'] as String?;+ if (api == null || !api.keepsEbookHighlights || fileId == null) return;+ if (!pull) {+ await HighlightSync.instance.push(api, widget.itemId, fileId);+ return;+ }+ final before = List.of(_annotations);+ final changed = await HighlightSync.instance.sync(api, widget.itemId, fileId);+ if (!changed || !mounted) return;+ final after = await _annotationService.getAnnotations(widget.itemId);+ if (!mounted) return;+ _repaintChangedHighlights(before, after);+ setState(() => _annotations = after);+ _updateBookmarkState();+ }++ void _repaintChangedHighlights(List<EbookAnnotation> before, List<EbookAnnotation> after) {+ Map<String, EbookAnnotation> highlights(List<EbookAnnotation> list) =>+ {for (final a in list) if (a.type == AnnotationType.highlight) a.id: a};+ final was = highlights(before);+ final now = highlights(after);+ for (final a in was.values) {+ final b = now[a.id];+ if (b == null || b.color != a.color) _epubController?.removeHighlight(cfi: a.cfi);+ }+ for (final b in now.values) {+ final a = was[b.id];+ final color = b.color;+ if ((a == null || a.color != color) && color != null) _paintHighlight(b.cfi, color);+ }+ }++ /// Draws a highlight on the page. An e-ink panel turns colors into pale+ /// greys, some next to invisible, so there every highlight is one shade that+ /// stands out from the page: dark on a light one, light on a dark one.+ void _paintHighlight(String cfi, HighlightColor color) {+ if (PlayerSettings.einkMode) {+ final darkPage = _resolvePalette(context).bgColor.computeLuminance() < 0.3;+ _epubController?.addHighlight(+ cfi: cfi,+ color: darkPage ? Colors.white : Colors.black,+ opacity: darkPage ? 0.35 : 0.2,+ blend: darkPage ? 'normal' : 'multiply',+ );+ return;+ }+ _epubController?.addHighlight(+ cfi: cfi,+ color: Color(int.parse('FF${color.hex.substring(1)}', radix: 16)),+ opacity: 0.35,+ );+ }++ /// Draws every highlight again, for an e-ink page whose theme just changed.+ void _redrawHighlights() {+ for (final a in _annotations) {+ if (a.type != AnnotationType.highlight || a.color == null) continue;+ _epubController?.removeHighlight(cfi: a.cfi);+ _paintHighlight(a.cfi, a.color!);+ }+ }+void _restoreHighlights() {_epubController?.webViewController?.addJavaScriptHandler(handlerName: 'absorbCfiText',@@ -1730,11 +1826,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs);for (final a in _annotations) {if (a.type == AnnotationType.highlight && a.color != null) {- _epubController?.addHighlight(- cfi: a.cfi,- color: Color(int.parse('FF${a.color!.hex.substring(1)}', radix: 16)),- opacity: 0.35,- );+ _paintHighlight(a.cfi, a.color!);_probeHighlightCfi(a.cfi);}}@@ -1842,13 +1934,10 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObscolor: color,chapter: _currentChapterTitle,);- _epubController?.addHighlight(- cfi: annotation.cfi,- color: Color(int.parse('FF${color.hex.substring(1)}', radix: 16)),- opacity: 0.35,- );+ _paintHighlight(annotation.cfi, color);_annotations.insert(0, annotation);if (mounted) _dismissSelection();+ unawaited(_syncHighlights());}/// [onThisPage] is for a highlight tapped in the book: the reader is sitting@@ -1876,6 +1965,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs);_annotations.removeWhere((a) => a.id == annotation.id);if (mounted) setState(() {});+ unawaited(_syncHighlights());}Future<void> _changeHighlightColor(@@ -1888,12 +1978,9 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs);annotation.color = color;_epubController?.removeHighlight(cfi: annotation.cfi);- _epubController?.addHighlight(- cfi: annotation.cfi,- color: Color(int.parse('FF${color.hex.substring(1)}', radix: 16)),- opacity: 0.35,- );+ _paintHighlight(annotation.cfi, color);if (mounted) setState(() {});+ unawaited(_syncHighlights());}/// A highlight tapped on the page: cancel the pending page turn and open@@ -1951,30 +2038,35 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsstyle: tt.bodyMedium?.copyWith(color: cs.onSurfaceVariant, fontStyle: FontStyle.italic)),),- Row(mainAxisAlignment: MainAxisAlignment.center, children: [- for (final c in HighlightColor.values)- Padding(- padding: const EdgeInsets.symmetric(horizontal: 6),- child: GestureDetector(- onTap: () {- Navigator.pop(ctx);- _changeHighlightColor(annotation, c);- },- child: Container(- width: 34,- height: 34,- decoration: BoxDecoration(- color: Color(- int.parse('FF${c.hex.substring(1)}', radix: 16)),- shape: BoxShape.circle,- border: annotation.color == c- ? Border.all(color: cs.onSurface, width: 2.5)- : null,+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 24),+ child: Wrap(+ alignment: WrapAlignment.center,+ spacing: 12,+ runSpacing: 12,+ children: [+ for (final c in HighlightColor.values)+ GestureDetector(+ onTap: () {+ Navigator.pop(ctx);+ _changeHighlightColor(annotation, c);+ },+ child: Container(+ width: 34,+ height: 34,+ decoration: BoxDecoration(+ color: Color(+ int.parse('FF${c.hex.substring(1)}', radix: 16)),+ shape: BoxShape.circle,+ border: annotation.color == c+ ? Border.all(color: cs.onSurface, width: 2.5)+ : null,+ ),),),- ),- ),- ]),+ ],+ ),+ ),const SizedBox(height: 8),ListTile(leading: Icon(Icons.edit_note_rounded, color: cs.onSurfaceVariant),@@ -2067,11 +2159,6 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObssetState(() => _clearSelection());}- Widget _divider(ColorScheme cs) => Padding(- padding: const EdgeInsets.symmetric(horizontal: 2),- child: Container(width: 1, height: 24, color: cs.onSurface.withValues(alpha: 0.15)),- );-void _copySelection() {if (_selectionText == null) return;Clipboard.setData(ClipboardData(text: _selectionText!));@@ -2104,6 +2191,13 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsif (mounted) showDictionarySheet(context, word);}+ void _translateSelection() {+ final text = _selectionText;+ if (text == null) return;+ _dismissSelection();+ TranslateService.translate(text);+ }+void _onSelection(String text, String cfi, Rect selRect, Rect vRect) {if (text.trim().isEmpty) return;setState(() {@@ -2160,6 +2254,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs);annotation.note = result.isEmpty ? null : result;if (mounted) setState(() {});+ unawaited(_syncHighlights());}}@@ -2673,6 +2768,31 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsPlayerSettings.setEreaderVolumeNavWhilePlaying(v);},),+ if (_translators.isNotEmpty)+ InkWell(+ borderRadius: BorderRadius.circular(8),+ onTap: () async {+ await _showTranslatorSheet();+ setSheetState(() {});+ },+ child: Padding(+ padding: const EdgeInsets.symmetric(vertical: 8),+ child: Row(children: [+ Icon(Icons.translate_rounded, size: 20, color: cs.onSurfaceVariant),+ const SizedBox(width: 12),+ Text(l.readerTranslateWith, style: tt.bodyMedium),+ const SizedBox(width: 12),+ Expanded(+ child: Text(TranslateService.pick(_translators, _translateWith).label,+ textAlign: TextAlign.end,+ overflow: TextOverflow.ellipsis,+ style: tt.bodyMedium?.copyWith(fontWeight: FontWeight.w600)),+ ),+ const SizedBox(width: 4),+ Icon(Icons.chevron_right_rounded, size: 20, color: cs.onSurfaceVariant),+ ]),+ ),+ ),// Read along, mirrored from the transcription settings so the// reader can change them without leaving the book.@@ -2724,18 +2844,20 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsconst SizedBox(height: 16),],- section(l.readerSectionStats),- SwitchListTile(- contentPadding: EdgeInsets.zero,- title: Text(l.readerLogReading, style: tt.bodyMedium),- subtitle: Text(l.readerLogReadingHint,- style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),- value: _logReading,- onChanged: (v) {- _setLogReading(v);- setSheetState(() {});- },- ),+ if (_readingApi?.isBookOrbit != true) ...[+ section(l.readerSectionStats),+ SwitchListTile(+ contentPadding: EdgeInsets.zero,+ title: Text(l.readerLogReading, style: tt.bodyMedium),+ subtitle: Text(l.readerLogReadingHint,+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),+ value: _logReading,+ onChanged: (v) {+ _setLogReading(v);+ setSheetState(() {});+ },+ ),+ ],],),@@ -3009,6 +3131,85 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs);}+ Future<void> _showTranslatorSheet() async {+ final cs = Theme.of(context).colorScheme;+ final tt = Theme.of(context).textTheme;+ final l = AppLocalizations.of(context)!;+ _translators = await TranslateService.available();+ if (!mounted) return;+ final current = TranslateService.pick(_translators, _translateWith).id;+ await showModalBottomSheet(+ context: context,+ backgroundColor: cs.surface,+ isScrollControlled: true,+ shape: const RoundedRectangleBorder(+ borderRadius: BorderRadius.vertical(top: Radius.circular(20)),+ ),+ builder: (ctx) => SafeArea(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ const SizedBox(height: 8),+ Center(+ child: Container(+ width: 40, height: 4,+ decoration: BoxDecoration(+ color: cs.onSurface.withValues(alpha: 0.24),+ borderRadius: BorderRadius.circular(2),+ ),+ ),+ ),+ Padding(+ padding: const EdgeInsets.all(16),+ child: Align(+ alignment: Alignment.centerLeft,+ child: Text(l.readerTranslateWith,+ style: tt.titleMedium?.copyWith(fontWeight: FontWeight.w600, color: cs.onSurface)),+ ),+ ),+ Flexible(+ child: ListView(+ shrinkWrap: true,+ children: [+ for (final t in _translators)+ ListTile(+ dense: true,+ leading: Icon(+ t.id == current ? Icons.radio_button_checked_rounded : Icons.radio_button_unchecked_rounded,+ color: t.id == current ? cs.primary : cs.onSurfaceVariant,+ ),+ title: Text(t.label,+ style: TextStyle(+ color: cs.onSurface,+ fontWeight: t.id == current ? FontWeight.w700 : FontWeight.w400)),+ subtitle: Text(+ switch (t.kind) {+ TranslatorKind.app => l.readerTranslateApp,+ TranslatorKind.apple => l.readerTranslateApple,+ TranslatorKind.web => l.readerTranslateWeb,+ },+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant),+ ),+ onTap: () {+ setState(() => _translateWith = t.id);+ PlayerSettings.setEreaderTranslateWith(t.id);+ Navigator.of(ctx).pop();+ },+ ),+ Padding(+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 12),+ child: Text(l.readerTranslateHint,+ style: tt.bodySmall?.copyWith(color: cs.onSurfaceVariant)),+ ),+ ],+ ),+ ),+ ],+ ),+ ),+ );+ }+/// Maps a spine item href to its TOC chapter title. The spine href and the/// TOC href often differ by directory prefix or URL-encoding (e.g./// `OEBPS/Text/ch1.xhtml` vs `Text/ch1.xhtml` vs `ch1%20.xhtml`), so match on@@ -3017,11 +3218,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs/// label, which is fine for a search result subtitle.String? _chapterForHref(String href) {if (href.isEmpty || _chapters.isEmpty) return null;- String basename(String s) {- var p = s.split('#').first;- try { p = Uri.decodeFull(p); } catch (_) {}- return p.split('/').last.toLowerCase();- }+ String basename(String s) => undoPercentEscapes(s.split('#').first.split('/').last).toLowerCase();// TOC labels often carry the nav markup's indentation/newlines, so trim.String? label(String t) => t.trim().isEmpty ? null : t.trim();final base = basename(href);@@ -4283,8 +4480,8 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs/// Plays the narration from the sentence [from]: a seek when this book is/// already in the player, otherwise a start there. An Audiobookshelf book- /// gets its narration onto the phone first, with how far along that is.- /// Null when the download question took over and nothing more needs saying.+ /// streams it, or offline offers the download. Null when the download+ /// question took over and nothing more needs saying.Future<bool?> _playNarrationFrom(OverlayClip? from) async {final player = AudioPlayerService();final n = _narration;@@ -4298,7 +4495,9 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsfinal api = context.read<AuthProvider>().apiService;if (api == null) return false;final cover = context.read<LibraryProvider>().getCoverUrl(widget.itemId);- if (!api.isBookOrbit && !NarrationService.instance.hasLocalAudio(widget.itemId)) {+ if (!api.isBookOrbit &&+ context.read<LibraryProvider>().isOffline &&+ !NarrationService.instance.hasLocalAudio(widget.itemId)) {await showNarrationDownloadDialog(context,itemId: widget.itemId,title: widget.title,@@ -4388,8 +4587,21 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsdebugPrint('[ReadAlong] opened while the narration is at ${clip.textHref}#$id - going there');_rememberSpot(EbookSpotReason.beforeSync);await wc.evaluateJavascript(source: _narrationBootstrapSource());- await wc.evaluateJavascript(- source: 'window.__absorbMO && __absorbMO.go(${jsonEncode(clip.textHref)}, ${jsonEncode(id)})');+ final go = 'window.__absorbMO && __absorbMO.go(${jsonEncode(clip.textHref)}, ${jsonEncode(id)})';+ await wc.evaluateJavascript(source: go);+ // The font and the first re-displays can still reflow the book after the+ // jump and leave it a page or more off the sentence: look again, and go+ // back to it unless the page has been moved by hand since.+ final openedAt = DateTime.now();+ for (final wait in const [1500, 2000]) {+ await Future.delayed(Duration(milliseconds: wait));+ if (!mounted || _readAlongOn || _userMovedAt.isAfter(openedAt)) return;+ final where = await wc.evaluateJavascript(+ source: 'window.__absorbMO ? __absorbMO.where(${jsonEncode(clip.textHref)}, ${jsonEncode(id)}) : ""');+ if (where == 'on' || where == 'missing' || where == null || where == '') continue;+ debugPrint('[ReadAlong] the page settled $where of the narration - going there again');+ await wc.evaluateJavascript(source: go);+ }}// Where reading has got to in narration time, noted as pages turn, so@@ -4537,6 +4749,15 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs_narrationTurnAt = now;await wc.evaluateJavascript(source: 'window.__absorbMO && __absorbMO.reveal(${jsonEncode(clip.textHref)}, ${jsonEncode(id)})');+ } else if (where == 'far-after' || where == 'far-before') {+ // Pages away (the reader opened short of it, or it was left behind):+ // straight there, not a page at a time.+ _narrationTurnAt = now;+ _readAlongTurnPending = now;+ debugPrint('[ReadAlong] narration is pages ${where == 'far-after' ? 'ahead' : 'back'} - '+ 'going to ${clip.textHref}#$id');+ await wc.evaluateJavascript(+ source: 'window.__absorbMO && __absorbMO.go(${jsonEncode(clip.textHref)}, ${jsonEncode(id)})');} else if (where == 'after' || where == 'before') {_narrationTurnAt = now;_readAlongTurnPending = now;@@ -5297,8 +5518,11 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs/// A page turn, jump or scroll the reader asked for. From here on the/// place is the reader's own and gets saved.+ DateTime _userMovedAt = DateTime.fromMillisecondsSinceEpoch(0);+void _userMoved(String how) {_readingActiveAt = DateTime.now();+ _userMovedAt = DateTime.now();if (const {'chapter', 'highlight', 'bookmark', 'history'}.contains(how)) {_rememberSpot(EbookSpotReason.beforeJump);}@@ -5796,7 +6020,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs}void _readingTick() {- if (!_logReading || !_readerActive) return;+ if (!_logReading || !_readerActive || _otherAccount) return;// This book's audio playing at either end of the tick means the time// is listening (read along included), counted by that session alone.final player = AudioPlayerService();@@ -6581,6 +6805,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsaccent: accent,scrollController: sc,onChanged: () {},+ showHighlights: false,),),),@@ -7077,7 +7302,10 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs}if (!_didInitViewer) {_didInitViewer = true;- _loadAnnotations().then((_) => _restoreHighlights());+ _loadAnnotations().then((_) {+ _restoreHighlights();+ unawaited(_syncHighlights(pull: true));+ });_setupPageInfoHandler();_setupTapHandler();_applyTurnStyle();@@ -7278,65 +7506,78 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs),),- // Selection toolbar - appears when text is selected+ // Selection toolbar - appears when text is selected. It spans the+ // screen so ten colors get room to be a decent size.if (_selectionRect != null && _selectionCfi != null)Positioned(- left: 0,- right: 0,+ left: 12,+ right: 12,bottom: MediaQuery.of(context).padding.bottom + 16,child: Center(- child: Material(- elevation: 8,- borderRadius: BorderRadius.circular(28),- color: cs.surfaceContainer,- child: Padding(- padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- for (final color in HighlightColor.values)- _HighlightColorButton(- color: Color(int.parse('FF${color.hex.substring(1)}', radix: 16)),- onTap: () => _addHighlight(color),+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 520),+ child: Material(+ elevation: 8,+ borderRadius: BorderRadius.circular(28),+ color: cs.surfaceContainer,+ child: Padding(+ padding: const EdgeInsets.fromLTRB(10, 12, 10, 4),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ Row(+ children: [+ for (final color in HighlightColor.values)+ Expanded(+ child: _HighlightColorButton(+ color: Color(int.parse('FF${color.hex.substring(1)}', radix: 16)),+ onTap: () => _addHighlight(color),+ ),+ ),+ ],),- _divider(cs),- IconButton(- icon: Icon(Icons.copy_rounded, size: 20, color: cs.onSurfaceVariant),- onPressed: _copySelection,- tooltip: AppLocalizations.of(context)!.readerTooltipCopy,- visualDensity: VisualDensity.compact,- ),- IconButton(- icon: Icon(Icons.search_rounded, size: 20, color: cs.onSurfaceVariant),- onPressed: _searchSelection,- tooltip: AppLocalizations.of(context)!.readerTooltipSearch,- visualDensity: VisualDensity.compact,- ),- IconButton(- icon: Icon(Icons.menu_book_rounded, size: 20, color: cs.onSurfaceVariant),- onPressed: _defineSelection,- tooltip: AppLocalizations.of(context)!.readerTooltipDefine,- visualDensity: VisualDensity.compact,- ),- if (_transcriptionOn || _useNarration)- IconButton(- icon: Icon(- _useNarration ? Icons.play_arrow_rounded : Icons.headphones_rounded,- size: 20,- color: cs.onSurfaceVariant),- onPressed: _findInAudiobookFromSelection,- tooltip: _useNarration- ? AppLocalizations.of(context)!.narrationPlayFromHere- : AppLocalizations.of(context)!.findInAudiobook,- visualDensity: VisualDensity.compact,+ const SizedBox(height: 4),+ Row(+ mainAxisAlignment: MainAxisAlignment.spaceEvenly,+ children: [+ IconButton(+ icon: Icon(Icons.copy_rounded, color: cs.onSurfaceVariant),+ onPressed: _copySelection,+ tooltip: AppLocalizations.of(context)!.readerTooltipCopy,+ ),+ IconButton(+ icon: Icon(Icons.search_rounded, color: cs.onSurfaceVariant),+ onPressed: _searchSelection,+ tooltip: AppLocalizations.of(context)!.readerTooltipSearch,+ ),+ IconButton(+ icon: Icon(Icons.menu_book_rounded, color: cs.onSurfaceVariant),+ onPressed: _defineSelection,+ tooltip: AppLocalizations.of(context)!.readerTooltipDefine,+ ),+ IconButton(+ icon: Icon(Icons.translate_rounded, color: cs.onSurfaceVariant),+ onPressed: _translateSelection,+ tooltip: AppLocalizations.of(context)!.readerTooltipTranslate,+ ),+ if (_transcriptionOn || _useNarration)+ IconButton(+ icon: Icon(+ _useNarration ? Icons.play_arrow_rounded : Icons.headphones_rounded,+ color: cs.onSurfaceVariant),+ onPressed: _findInAudiobookFromSelection,+ tooltip: _useNarration+ ? AppLocalizations.of(context)!.narrationPlayFromHere+ : AppLocalizations.of(context)!.findInAudiobook,+ ),+ IconButton(+ icon: Icon(Icons.close_rounded, color: cs.onSurfaceVariant),+ onPressed: _dismissSelection,+ ),+ ],),- _divider(cs),- IconButton(- icon: Icon(Icons.close_rounded, size: 20, color: cs.onSurfaceVariant),- onPressed: _dismissSelection,- visualDensity: VisualDensity.compact,- ),- ],+ ],+ ),),),),@@ -7581,10 +7822,10 @@ class _HighlightColorButton extends StatelessWidget {return GestureDetector(onTap: onTap,child: Padding(- padding: const EdgeInsets.symmetric(horizontal: 4),- child: Container(- width: 32,- height: 32,+ padding: const EdgeInsets.symmetric(horizontal: 3),+ child: AspectRatio(+ aspectRatio: 1,+ child: Container(decoration: BoxDecoration(color: color,shape: BoxShape.circle,@@ -7594,6 +7835,7 @@ class _HighlightColorButton extends StatelessWidget {),),),+ ),),);}diff --git a/lib/widgets/ebook_router.dart b/lib/widgets/ebook_router.dartindex 722b21fc..72b65bbd 100644--- a/lib/widgets/ebook_router.dart+++ b/lib/widgets/ebook_router.dart@@ -31,6 +31,44 @@ bool canReadEbook(Map<String, dynamic>? ebookFile) {return readableEbookFormats.contains(ext);}+/// Opens a book's ebook at a highlight. A downloaded ebook opens from the+/// reader cache, so this works offline. [title] is looked up when not given.+Future<void> openHighlightInReader(+ BuildContext context, {+ required String itemId,+ required String cfi,+ String? title,+}) async {+ final l = AppLocalizations.of(context)!;+ final api = context.read<AuthProvider>().apiService;+ var ebookFile = await cachedEbookFileFor(itemId);+ if ((ebookFile == null || title == null) && api != null) {+ final item = await api.getLibraryItem(itemId);+ ebookFile ??= resolveEbookFile(item);+ if (title == null) {+ final media = item?['media'] as Map<String, dynamic>? ?? {};+ final metadata = media['metadata'] as Map<String, dynamic>? ?? {};+ title = metadata['title'] as String?;+ }+ }+ if (!context.mounted) return;+ if (ebookFile == null) {+ showOverlayToast(+ context,+ api == null ? l.bookmarksNotConnected : l.noEbookFileFound,+ icon: Icons.menu_book_outlined,+ );+ return;+ }+ await openEbookReader(+ context,+ itemId: itemId,+ title: title ?? '',+ ebookFile: ebookFile,+ openAtCfi: cfi,+ );+}+/// Routes an ebook to the right reader for its format, or toasts when the/// format isn't supported in-app. [openAtCfi] jumps an EPUB straight to a/// saved location (a highlight) instead of resuming where reading left off.diff --git a/packages/flutter_epub_viewer/lib/assets/webpage/html/epubView.js b/packages/flutter_epub_viewer/lib/assets/webpage/html/epubView.jsindex 96c3ed03..d930fff7 100644--- a/packages/flutter_epub_viewer/lib/assets/webpage/html/epubView.js+++ b/packages/flutter_epub_viewer/lib/assets/webpage/html/epubView.js@@ -190,6 +190,7 @@ function loadBook(data, cfi, initialXPath, manager, flow, spread, snap, allowScrrendition.hooks.content.register(function (contents) {attachTurnDrag(contents.document);});+ rendition.hooks.content.register(markParagraphs);// Absorb patch: scroll mode only moves up and down, down to each chapter's// own page, so a drag that drifts sideways can't nudge the text aside.@@ -2443,6 +2444,49 @@ function addHighlight(cfiRange, color, opacity) {}, "hl", { "fill": color, "fill-opacity": '0.3', "mix-blend-mode": "multiply" });}+// Absorb: a highlight drawn with its own opacity and blend. E-ink draws every+// highlight as one shade the panel can show, whatever its color.+// Absorb patch: tag the book's paragraphs with "absorb-p", so paragraph+// spacing and justified text reach books that set them in <div>s (Calibre+// conversions) as well as <p>s. A paragraph is a <p>, or a <div> holding+// text and no other blocks, that the book itself doesn't center or align+// right. <div>s only count in a chapter with next to no <p> paragraphs:+// where a book has them, its <div>s are headings, list entries and the+// like. The reader's own styles are switched off while looking, so the+// book's alignment is what's read, not the one the reader forces.+function markParagraphs(contents) {+ try {+ var doc = contents.document;+ var win = contents.window || doc.defaultView;+ if (!doc || !doc.body || !win) return;+ var injected = Array.prototype.slice.call(doc.querySelectorAll('style[id^="epubjs-inserted-css"]'));+ injected.forEach(function (st) { if (st.sheet) st.sheet.disabled = true; });+ try {+ var blocks = "p, div, h1, h2, h3, h4, h5, h6, ul, ol, table, blockquote, section, figure, pre, img, svg";+ var textParagraphs = 0;+ doc.body.querySelectorAll("p").forEach(function (el) {+ if (el.textContent && el.textContent.trim()) textParagraphs++;+ });+ var divsAreParagraphs = textParagraphs < 3;+ doc.body.querySelectorAll(divsAreParagraphs ? "p, div" : "p").forEach(function (el) {+ if (el.tagName === "DIV") {+ if (el.querySelector(blocks)) return;+ if (!el.textContent || !el.textContent.trim()) return;+ }+ var align = win.getComputedStyle(el).textAlign;+ if (align === "center" || align === "right" || align === "end" || align === "-webkit-center") return;+ el.classList.add("absorb-p");+ });+ } finally {+ injected.forEach(function (st) { if (st.sheet) st.sheet.disabled = false; });+ }+ } catch (e) {}+}++function addHighlightStyled(cfiRange, color, opacity, blend) {+ rendition.annotations.highlight(cfiRange, {}, () => {}, "hl", { "fill": color, "fill-opacity": opacity, "mix-blend-mode": blend });+}+function addUnderLine(cfiString) {rendition.annotations.underline(cfiString)}@@ -3187,6 +3231,7 @@ function autoScrollStart(speed) {blindRendition.hooks.content.register(function (contents) {if (window.__absorbApplyFontToDoc) window.__absorbApplyFontToDoc(contents.document);});+ blindRendition.hooks.content.register(markParagraphs);} catch (e) {}// renderTo points book.rendition at whatever it just made - epub.js internals// still expect the live one.diff --git a/packages/flutter_epub_viewer/lib/assets/webpage/html/swipe.html b/packages/flutter_epub_viewer/lib/assets/webpage/html/swipe.htmlindex 5f76e50f..60ca02b2 100644--- a/packages/flutter_epub_viewer/lib/assets/webpage/html/swipe.html+++ b/packages/flutter_epub_viewer/lib/assets/webpage/html/swipe.html@@ -19,6 +19,17 @@-webkit-justify-content: center;}+ /* Absorb patch: examples.css gives the body a min-height of 800px, so a+ shorter page (landscape, or under a pinned top bar) was taller than+ the screen and could be dragged up and down. The book scrolls inside+ epub.js's own container, never the page itself. */+ html,+ body {+ height: 100%;+ min-height: 0;+ overflow: hidden;+ }+#viewer {width: 100%;height: 100%;diff --git a/packages/flutter_epub_viewer/lib/src/epub_controller.dart b/packages/flutter_epub_viewer/lib/src/epub_controller.dartindex a92fc0c9..ae162b84 100644--- a/packages/flutter_epub_viewer/lib/src/epub_controller.dart+++ b/packages/flutter_epub_viewer/lib/src/epub_controller.dart@@ -121,12 +121,17 @@ class EpubController {///Opacity of the highlightdouble opacity = 0.3,++ ///Absorb: a blend mode, which also draws at [opacity] as given+ String? blend,}) {var colorHex = color.toHex();var opacityString = opacity.toString();checkEpubLoaded();webViewController?.evaluateJavascript(- source: 'addHighlight("$cfi", "$colorHex", "$opacityString")',+ source: blend == null+ ? 'addHighlight("$cfi", "$colorHex", "$opacityString")'+ : 'addHighlightStyled("$cfi", "$colorHex", "$opacityString", "$blend")',);}