A cross platform Audiobookshelf client for Android and iOS
Dart
Add auto scroll to the ebook reader, where the next page comes down over the current one
Barnabas4894a19f1d51
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arbindex ea2e1a16..929e9a57 100644--- a/lib/l10n/app_en.arb+++ b/lib/l10n/app_en.arb@@ -4650,6 +4650,16 @@"readerVolumeNavOff": "Off","readerVolumeNavNormal": "Normal","readerVolumeNavMirrored": "Mirrored",+ "readerAutoScroll": "Auto scroll",+ "readerAutoScrollSubtitle": "The next page paints over this one from the top down - drag the middle of the screen to change speed, tap to stop",+ "readerAutoScrollStarted": "Auto scroll started",+ "readerAutoScrollPaused": "Paused - press and hold to stop",+ "readerAutoScrollResumed": "Auto scroll resumed",+ "readerAutoScrollStopped": "Auto scroll off",+ "readerAutoScrollSpeed": "Speed {percent}%",+ "@readerAutoScrollSpeed": {+ "placeholders": { "percent": { "type": "int" } }+ },"readerVolumeNavWhilePlaying": "Even while audio is playing","readerMoreFonts": "Download more fonts","readerFontRemove": "Remove download",diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dartindex ff5c4445..263b0703 100644--- a/lib/l10n/app_localizations.dart+++ b/lib/l10n/app_localizations.dart@@ -13947,6 +13947,48 @@ abstract class AppLocalizations {/// **'Mirrored'**String get readerVolumeNavMirrored;+ /// No description provided for @readerAutoScroll.+ ///+ /// In en, this message translates to:+ /// **'Auto scroll'**+ String get readerAutoScroll;++ /// No description provided for @readerAutoScrollSubtitle.+ ///+ /// In en, this message translates to:+ /// **'The next page paints over this one from the top down - drag the middle of the screen to change speed, tap to stop'**+ String get readerAutoScrollSubtitle;++ /// No description provided for @readerAutoScrollStarted.+ ///+ /// In en, this message translates to:+ /// **'Auto scroll started'**+ String get readerAutoScrollStarted;++ /// No description provided for @readerAutoScrollPaused.+ ///+ /// In en, this message translates to:+ /// **'Paused - press and hold to stop'**+ String get readerAutoScrollPaused;++ /// No description provided for @readerAutoScrollResumed.+ ///+ /// In en, this message translates to:+ /// **'Auto scroll resumed'**+ String get readerAutoScrollResumed;++ /// No description provided for @readerAutoScrollStopped.+ ///+ /// In en, this message translates to:+ /// **'Auto scroll off'**+ String get readerAutoScrollStopped;++ /// No description provided for @readerAutoScrollSpeed.+ ///+ /// In en, this message translates to:+ /// **'Speed {percent}%'**+ String readerAutoScrollSpeed(int percent);+/// No description provided for @readerVolumeNavWhilePlaying.////// In en, this message translates to:diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dartindex 6be16ca5..76561ae0 100644--- a/lib/l10n/app_localizations_de.dart+++ b/lib/l10n/app_localizations_de.dart@@ -8190,6 +8190,30 @@ class AppLocalizationsDe extends AppLocalizations {@overrideString get readerVolumeNavMirrored => 'Gespiegelt';+ @override+ String get readerAutoScroll => 'Auto scroll';++ @override+ String get readerAutoScrollSubtitle =>+ 'The next page paints over this one from the top down - drag the middle of the screen to change speed, tap to stop';++ @override+ String get readerAutoScrollStarted => 'Auto scroll started';++ @override+ String get readerAutoScrollPaused => 'Paused - press and hold to stop';++ @override+ String get readerAutoScrollResumed => 'Auto scroll resumed';++ @override+ String get readerAutoScrollStopped => 'Auto scroll off';++ @override+ String readerAutoScrollSpeed(int percent) {+ return 'Speed $percent%';+ }+@overrideString get readerVolumeNavWhilePlaying =>'Selbst während Audio abgespielt wird';diff --git a/lib/l10n/app_localizations_el.dart b/lib/l10n/app_localizations_el.dartindex 57eb261d..11f5019a 100644--- a/lib/l10n/app_localizations_el.dart+++ b/lib/l10n/app_localizations_el.dart@@ -8073,6 +8073,30 @@ class AppLocalizationsEl extends AppLocalizations {@overrideString get readerVolumeNavMirrored => 'Mirrored';+ @override+ String get readerAutoScroll => 'Auto scroll';++ @override+ String get readerAutoScrollSubtitle =>+ 'The next page paints over this one from the top down - drag the middle of the screen to change speed, tap to stop';++ @override+ String get readerAutoScrollStarted => 'Auto scroll started';++ @override+ String get readerAutoScrollPaused => 'Paused - press and hold to stop';++ @override+ String get readerAutoScrollResumed => 'Auto scroll resumed';++ @override+ String get readerAutoScrollStopped => 'Auto scroll off';++ @override+ String readerAutoScrollSpeed(int percent) {+ return 'Speed $percent%';+ }+@overrideString get readerVolumeNavWhilePlaying => 'Even while audio is playing';diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dartindex b481aed3..dc6da75b 100644--- a/lib/l10n/app_localizations_en.dart+++ b/lib/l10n/app_localizations_en.dart@@ -8073,6 +8073,30 @@ class AppLocalizationsEn extends AppLocalizations {@overrideString get readerVolumeNavMirrored => 'Mirrored';+ @override+ String get readerAutoScroll => 'Auto scroll';++ @override+ String get readerAutoScrollSubtitle =>+ 'The next page paints over this one from the top down - drag the middle of the screen to change speed, tap to stop';++ @override+ String get readerAutoScrollStarted => 'Auto scroll started';++ @override+ String get readerAutoScrollPaused => 'Paused - press and hold to stop';++ @override+ String get readerAutoScrollResumed => 'Auto scroll resumed';++ @override+ String get readerAutoScrollStopped => 'Auto scroll off';++ @override+ String readerAutoScrollSpeed(int percent) {+ return 'Speed $percent%';+ }+@overrideString get readerVolumeNavWhilePlaying => 'Even while audio is playing';diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dartindex f667e384..f6b531bf 100644--- a/lib/l10n/app_localizations_es.dart+++ b/lib/l10n/app_localizations_es.dart@@ -8075,6 +8075,30 @@ class AppLocalizationsEs extends AppLocalizations {@overrideString get readerVolumeNavMirrored => 'Mirrored';+ @override+ String get readerAutoScroll => 'Auto scroll';++ @override+ String get readerAutoScrollSubtitle =>+ 'The next page paints over this one from the top down - drag the middle of the screen to change speed, tap to stop';++ @override+ String get readerAutoScrollStarted => 'Auto scroll started';++ @override+ String get readerAutoScrollPaused => 'Paused - press and hold to stop';++ @override+ String get readerAutoScrollResumed => 'Auto scroll resumed';++ @override+ String get readerAutoScrollStopped => 'Auto scroll off';++ @override+ String readerAutoScrollSpeed(int percent) {+ return 'Speed $percent%';+ }+@overrideString get readerVolumeNavWhilePlaying => 'Even while audio is playing';diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dartindex e9497fa0..d5ec7d25 100644--- a/lib/l10n/app_localizations_fr.dart+++ b/lib/l10n/app_localizations_fr.dart@@ -8124,6 +8124,30 @@ class AppLocalizationsFr extends AppLocalizations {@overrideString get readerVolumeNavMirrored => 'Inversé';+ @override+ String get readerAutoScroll => 'Auto scroll';++ @override+ String get readerAutoScrollSubtitle =>+ 'The next page paints over this one from the top down - drag the middle of the screen to change speed, tap to stop';++ @override+ String get readerAutoScrollStarted => 'Auto scroll started';++ @override+ String get readerAutoScrollPaused => 'Paused - press and hold to stop';++ @override+ String get readerAutoScrollResumed => 'Auto scroll resumed';++ @override+ String get readerAutoScrollStopped => 'Auto scroll off';++ @override+ String readerAutoScrollSpeed(int percent) {+ return 'Speed $percent%';+ }+@overrideString get readerVolumeNavWhilePlaying =>'Même lorsque l\'audio est en cours de lecture';diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dartindex 5b403f7f..cf79d100 100644--- a/lib/l10n/app_localizations_it.dart+++ b/lib/l10n/app_localizations_it.dart@@ -8073,6 +8073,30 @@ class AppLocalizationsIt extends AppLocalizations {@overrideString get readerVolumeNavMirrored => 'Mirrored';+ @override+ String get readerAutoScroll => 'Auto scroll';++ @override+ String get readerAutoScrollSubtitle =>+ 'The next page paints over this one from the top down - drag the middle of the screen to change speed, tap to stop';++ @override+ String get readerAutoScrollStarted => 'Auto scroll started';++ @override+ String get readerAutoScrollPaused => 'Paused - press and hold to stop';++ @override+ String get readerAutoScrollResumed => 'Auto scroll resumed';++ @override+ String get readerAutoScrollStopped => 'Auto scroll off';++ @override+ String readerAutoScrollSpeed(int percent) {+ return 'Speed $percent%';+ }+@overrideString get readerVolumeNavWhilePlaying => 'Even while audio is playing';diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dartindex 762ad9e0..6e1809dd 100644--- a/lib/l10n/app_localizations_ja.dart+++ b/lib/l10n/app_localizations_ja.dart@@ -8073,6 +8073,30 @@ class AppLocalizationsJa extends AppLocalizations {@overrideString get readerVolumeNavMirrored => 'Mirrored';+ @override+ String get readerAutoScroll => 'Auto scroll';++ @override+ String get readerAutoScrollSubtitle =>+ 'The next page paints over this one from the top down - drag the middle of the screen to change speed, tap to stop';++ @override+ String get readerAutoScrollStarted => 'Auto scroll started';++ @override+ String get readerAutoScrollPaused => 'Paused - press and hold to stop';++ @override+ String get readerAutoScrollResumed => 'Auto scroll resumed';++ @override+ String get readerAutoScrollStopped => 'Auto scroll off';++ @override+ String readerAutoScrollSpeed(int percent) {+ return 'Speed $percent%';+ }+@overrideString get readerVolumeNavWhilePlaying => 'Even while audio is playing';diff --git a/lib/l10n/app_localizations_no.dart b/lib/l10n/app_localizations_no.dartindex daa7ea8d..4641eb8b 100644--- a/lib/l10n/app_localizations_no.dart+++ b/lib/l10n/app_localizations_no.dart@@ -8073,6 +8073,30 @@ class AppLocalizationsNo extends AppLocalizations {@overrideString get readerVolumeNavMirrored => 'Mirrored';+ @override+ String get readerAutoScroll => 'Auto scroll';++ @override+ String get readerAutoScrollSubtitle =>+ 'The next page paints over this one from the top down - drag the middle of the screen to change speed, tap to stop';++ @override+ String get readerAutoScrollStarted => 'Auto scroll started';++ @override+ String get readerAutoScrollPaused => 'Paused - press and hold to stop';++ @override+ String get readerAutoScrollResumed => 'Auto scroll resumed';++ @override+ String get readerAutoScrollStopped => 'Auto scroll off';++ @override+ String readerAutoScrollSpeed(int percent) {+ return 'Speed $percent%';+ }+@overrideString get readerVolumeNavWhilePlaying => 'Even while audio is playing';diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dartindex b5b335af..269e83d9 100644--- a/lib/l10n/app_localizations_pt.dart+++ b/lib/l10n/app_localizations_pt.dart@@ -8073,6 +8073,30 @@ class AppLocalizationsPt extends AppLocalizations {@overrideString get readerVolumeNavMirrored => 'Mirrored';+ @override+ String get readerAutoScroll => 'Auto scroll';++ @override+ String get readerAutoScrollSubtitle =>+ 'The next page paints over this one from the top down - drag the middle of the screen to change speed, tap to stop';++ @override+ String get readerAutoScrollStarted => 'Auto scroll started';++ @override+ String get readerAutoScrollPaused => 'Paused - press and hold to stop';++ @override+ String get readerAutoScrollResumed => 'Auto scroll resumed';++ @override+ String get readerAutoScrollStopped => 'Auto scroll off';++ @override+ String readerAutoScrollSpeed(int percent) {+ return 'Speed $percent%';+ }+@overrideString get readerVolumeNavWhilePlaying => 'Even while audio is playing';diff --git a/lib/l10n/app_localizations_ro.dart b/lib/l10n/app_localizations_ro.dartindex b0008266..7d30ced0 100644--- a/lib/l10n/app_localizations_ro.dart+++ b/lib/l10n/app_localizations_ro.dart@@ -8073,6 +8073,30 @@ class AppLocalizationsRo extends AppLocalizations {@overrideString get readerVolumeNavMirrored => 'Mirrored';+ @override+ String get readerAutoScroll => 'Auto scroll';++ @override+ String get readerAutoScrollSubtitle =>+ 'The next page paints over this one from the top down - drag the middle of the screen to change speed, tap to stop';++ @override+ String get readerAutoScrollStarted => 'Auto scroll started';++ @override+ String get readerAutoScrollPaused => 'Paused - press and hold to stop';++ @override+ String get readerAutoScrollResumed => 'Auto scroll resumed';++ @override+ String get readerAutoScrollStopped => 'Auto scroll off';++ @override+ String readerAutoScrollSpeed(int percent) {+ return 'Speed $percent%';+ }+@overrideString get readerVolumeNavWhilePlaying => 'Even while audio is playing';diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dartindex 6714bb86..1a0a502b 100644--- a/lib/l10n/app_localizations_ru.dart+++ b/lib/l10n/app_localizations_ru.dart@@ -8078,6 +8078,30 @@ class AppLocalizationsRu extends AppLocalizations {@overrideString get readerVolumeNavMirrored => 'Mirrored';+ @override+ String get readerAutoScroll => 'Auto scroll';++ @override+ String get readerAutoScrollSubtitle =>+ 'The next page paints over this one from the top down - drag the middle of the screen to change speed, tap to stop';++ @override+ String get readerAutoScrollStarted => 'Auto scroll started';++ @override+ String get readerAutoScrollPaused => 'Paused - press and hold to stop';++ @override+ String get readerAutoScrollResumed => 'Auto scroll resumed';++ @override+ String get readerAutoScrollStopped => 'Auto scroll off';++ @override+ String readerAutoScrollSpeed(int percent) {+ return 'Speed $percent%';+ }+@overrideString get readerVolumeNavWhilePlaying => 'Even while audio is playing';diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dartindex 66c79a5e..1a48e44d 100644--- a/lib/l10n/app_localizations_zh.dart+++ b/lib/l10n/app_localizations_zh.dart@@ -7981,6 +7981,30 @@ class AppLocalizationsZh extends AppLocalizations {@overrideString get readerVolumeNavMirrored => 'Mirrored';+ @override+ String get readerAutoScroll => 'Auto scroll';++ @override+ String get readerAutoScrollSubtitle =>+ 'The next page paints over this one from the top down - drag the middle of the screen to change speed, tap to stop';++ @override+ String get readerAutoScrollStarted => 'Auto scroll started';++ @override+ String get readerAutoScrollPaused => 'Paused - press and hold to stop';++ @override+ String get readerAutoScrollResumed => 'Auto scroll resumed';++ @override+ String get readerAutoScrollStopped => 'Auto scroll off';++ @override+ String readerAutoScrollSpeed(int percent) {+ return 'Speed $percent%';+ }+@overrideString get readerVolumeNavWhilePlaying => 'Even while audio is playing';diff --git a/lib/services/player_settings.dart b/lib/services/player_settings.dartindex 77553e7e..783a6e98 100644--- a/lib/services/player_settings.dart+++ b/lib/services/player_settings.dart@@ -965,6 +965,9 @@ class PlayerSettings {static Future<bool> getEreaderVolumeNavWhilePlaying() => _get('ereaderVolumeNavWhilePlaying', false);static Future<void> setEreaderVolumeNavWhilePlaying(bool value) => _set('ereaderVolumeNavWhilePlaying', value, notify: true);+ static Future<double> getEreaderAutoScrollSpeed() => _get('ereaderAutoScrollSpeed', 40.0);+ static Future<void> setEreaderAutoScrollSpeed(double value) => _set('ereaderAutoScrollSpeed', value);+/// When on, the screen is locked to portrait (rotation disabled). Default off/// keeps the current behaviour where all orientations are allowed.static Future<bool> getLockPortrait() => _get('lockPortrait', false);diff --git a/lib/widgets/ebook_reader_view.dart b/lib/widgets/ebook_reader_view.dartindex 9ce192bd..2362e91a 100644--- a/lib/widgets/ebook_reader_view.dart+++ b/lib/widgets/ebook_reader_view.dart@@ -158,6 +158,13 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsint _marginH = 16; // left + rightString _volumeNavMode = 'off';bool _volumeNavWhilePlaying = false;++ // 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.+ bool _autoScroll = false;+ double _autoScrollSpeed = 40;+ bool _autoScrollPaused = false;+ LiveOverlayToast? _speedToast;int _marginV = 16; // top + bottom// Page layout: auto shows two pages on wide screens (tablets), single forces// one page, two forces a spread. Stored as index 0=auto/1=single/2=two.@@ -386,9 +393,18 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObss.textContent = window.__absorbFontFace;doc.head.appendChild(s);}+ // Exposed so the auto-scroll blind can stamp the same @font-face into+ // its own iframe - a downloadable font is a per-document declaration,+ // so a second rendition without this hook renders in a fallback face.+ window.__absorbApplyFontToDoc = applyTo;window.__absorbApplyFont = function(css){window.__absorbFontFace = css || '';try { rendition.getContents().forEach(function(c){ applyTo(c.document); }); } catch(e){}+ try {+ if (window.__absorbBlindRendition) {+ window.__absorbBlindRendition.getContents().forEach(function(c){ applyTo(c.document); });+ }+ } catch(e){}};try { rendition.hooks.content.register(function(contents){ applyTo(contents.document); }); } catch(e){}})();@@ -500,6 +516,8 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs@overridevoid dispose() {+ _speedToast?.dismiss();+ if (_autoScroll) _epubController?.autoScrollStop();_quietLib.setReaderQuiet(false);WidgetsBinding.instance.removeObserver(this);_volumeNav.detach();@@ -540,6 +558,10 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs/// the action commits after a short grace window that the highlight tap can/// cancel. No highlights, no added latency.void _readerTapAt(double frac, String source) {+ // While auto scroll runs, the in-WebView pad owns taps: pause, resume and+ // press-and-hold to stop. This Listener sees raw pointers regardless of the+ // platform view, so without this it turned pages under the blind.+ if (_autoScroll) return;final now = DateTime.now();final sinceMs = now.difference(_lastReaderTap).inMilliseconds;if (sinceMs < 350) {@@ -1495,6 +1517,96 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs);}+ static const double _autoScrollMin = 6;+ static const double _autoScrollMax = 220;++ int get _autoScrollPercent =>+ (((_autoScrollSpeed - _autoScrollMin) / (_autoScrollMax - _autoScrollMin)) * 100)+ .round()+ .clamp(1, 100);++ void _setupAutoScrollHandlers() {+ _epubController?.webViewController?.addJavaScriptHandler(+ handlerName: 'absorbAutoScrollSpeed',+ callback: (args) {+ final v = args.isNotEmpty ? (args[0] as num?)?.toDouble() : null;+ if (v == null || !mounted) return;+ setState(() => _autoScrollSpeed = v);+ PlayerSettings.setEreaderAutoScrollSpeed(v);+ final l = AppLocalizations.of(context)!;+ _speedToast ??= LiveOverlayToast.show(+ context,+ l.readerAutoScrollSpeed(_autoScrollPercent),+ icon: Icons.speed_rounded,+ );+ _speedToast?.update(+ l.readerAutoScrollSpeed(_autoScrollPercent),+ icon: Icons.speed_rounded,+ );+ },+ );+ _epubController?.webViewController?.addJavaScriptHandler(+ handlerName: 'absorbAutoScrollDragEnd',+ callback: (args) {+ _speedToast?.dismiss();+ _speedToast = null;+ },+ );+ _epubController?.webViewController?.addJavaScriptHandler(+ handlerName: 'absorbAutoScrollLongPress',+ callback: (args) {+ if (!mounted || !_autoScroll) return;+ _speedToast?.dismiss();+ _speedToast = null;+ _toggleAutoScroll();+ showOverlayToast(context, AppLocalizations.of(context)!.readerAutoScrollStopped,+ icon: Icons.stop_circle_outlined);+ },+ );+ _epubController?.webViewController?.addJavaScriptHandler(+ handlerName: 'absorbAutoScrollTap',+ callback: (args) {+ if (!mounted) return;+ // With the reader's bars up, a tap dismisses those - otherwise there is+ // no way to clear them without also interrupting the scroll.+ if (_showControls) {+ _toggleControls();+ _epubController?.autoScrollPause(_autoScrollPaused);+ return;+ }+ setState(() => _autoScrollPaused = !_autoScrollPaused);+ _epubController?.autoScrollPause(_autoScrollPaused);+ final l = AppLocalizations.of(context)!;+ showOverlayToast(+ context,+ _autoScrollPaused ? l.readerAutoScrollPaused : l.readerAutoScrollResumed,+ icon: _autoScrollPaused ? Icons.pause_rounded : Icons.play_arrow_rounded,+ );+ },+ );+ }++ Future<void> _toggleAutoScroll() async {+ if (_autoScroll) {+ await _epubController?.autoScrollStop();+ if (mounted) setState(() {+ _autoScroll = false;+ _autoScrollPaused = false;+ });+ return;+ }+ await _epubController?.autoScrollStart(speed: _autoScrollSpeed);+ if (mounted) {+ showOverlayToast(context, AppLocalizations.of(context)!.readerAutoScrollStarted,+ icon: Icons.swap_vert_rounded);+ }+ if (mounted) setState(() {+ _autoScroll = true;+ _autoScrollPaused = false;+ if (_showControls) _showControls = false;+ });+ }+Widget _themeSwatch(_ReaderPalette p, bool selected, VoidCallback onTap, ColorScheme cs) {return GestureDetector(onTap: onTap,@@ -3435,6 +3547,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs_loadAnnotations().then((_) => _restoreHighlights());_setupPageInfoHandler();_setupTapHandler();+ _setupAutoScrollHandlers();_setupFontInjector();_applyFontFace();}@@ -3491,7 +3604,8 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs},)),- // Top bar overlay+ // Top overlay: what you are reading and how far in. Controls live+ // at the bottom now, in thumb reach.AnimatedOpacity(opacity: _showControls ? 1.0 : 0.0,duration: const Duration(milliseconds: 200),@@ -3502,61 +3616,68 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsgradient: LinearGradient(begin: Alignment.topCenter,end: Alignment.bottomCenter,- colors: [bg.withValues(alpha: 1.0), bg.withValues(alpha: 0.6)],+ colors: [+ bg.withValues(alpha: 1.0),+ bg.withValues(alpha: 1.0),+ bg.withValues(alpha: 0.0),+ ],+ stops: const [0.0, 0.86, 1.0],),),child: SafeArea(bottom: false,child: Padding(- padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4),- child: Row(+ padding: const EdgeInsets.fromLTRB(20, 8, 20, 12),+ child: Column(+ mainAxisSize: MainAxisSize.min,children: [- IconButton(- icon: Icon(- Icons.arrow_back_rounded,+ Text(+ widget.title,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ textAlign: TextAlign.center,+ style: TextStyle(color: fg,+ fontWeight: FontWeight.w600,+ fontSize: 16,),- onPressed: _handleClose,),- Expanded(- child: Text(- widget.title,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: TextStyle(- color: fg,- fontWeight: FontWeight.w600,- fontSize: 16,- ),+ const SizedBox(height: 8),+ ClipRRect(+ borderRadius: BorderRadius.circular(2),+ child: LinearProgressIndicator(+ value: _progress.clamp(0.0, 1.0),+ minHeight: 3,+ backgroundColor: fg.withValues(alpha: 0.1),+ valueColor: AlwaysStoppedAnimation(accent),),),- IconButton(- icon: Icon(- _hasBookmarkAtCurrent- ? Icons.bookmark_rounded- : Icons.bookmark_border_rounded,- color: _hasBookmarkAtCurrent ? accent : fg,- ),- onPressed: _toggleBookmark,- ),- IconButton(- icon: Icon(Icons.search_rounded, color: fg),- tooltip: AppLocalizations.of(context)!.readerTooltipSearch,- onPressed: _openSearchScreen,- ),- IconButton(- icon: Icon(Icons.sticky_note_2_outlined, color: fg),- onPressed: _showAnnotationsSheet,- ),- IconButton(- icon: Icon(Icons.text_fields_rounded, color: fg),- onPressed: _showSettingsSheet,+ const SizedBox(height: 4),+ Row(+ children: [+ if (_chapterPageTotal > 0)+ Text(+ '$_chapterPage / $_chapterPageTotal',+ style: TextStyle(color: fgDim, fontSize: 11),+ ),+ Expanded(+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 8),+ child: Text(+ _currentChapterTitle ?? '',+ textAlign: TextAlign.center,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(color: fgDim, fontSize: 11),+ ),+ ),+ ),+ Text(+ '${(_progress * 100).toStringAsFixed(1)}%',+ style: TextStyle(color: fgDim, fontSize: 11),+ ),+ ],),- if (_chapters.isNotEmpty)- IconButton(- icon: Icon(Icons.list_rounded, color: fg),- onPressed: _showChapterList,- ),],),),@@ -3565,7 +3686,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs),),- // Bottom progress bar overlay+ // Bottom overlay: every control, centred and within thumb reach.Positioned(left: 0, right: 0, bottom: 0,child: AnimatedOpacity(@@ -3578,50 +3699,67 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObsgradient: LinearGradient(begin: Alignment.bottomCenter,end: Alignment.topCenter,- colors: [bg.withValues(alpha: 1.0), bg.withValues(alpha: 0.6)],+ colors: [+ bg.withValues(alpha: 1.0),+ bg.withValues(alpha: 1.0),+ bg.withValues(alpha: 0.0),+ ],+ stops: const [0.0, 0.86, 1.0],),),child: SafeArea(top: false,child: Padding(- padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),+ padding: const EdgeInsets.fromLTRB(4, 6, 4, 2),child: Column(mainAxisSize: MainAxisSize.min,children: [- _buildMediaBar(fg, accent),- ClipRRect(- borderRadius: BorderRadius.circular(2),- child: LinearProgressIndicator(- value: _progress.clamp(0.0, 1.0),- minHeight: 3,- backgroundColor: fg.withValues(alpha: 0.1),- valueColor: AlwaysStoppedAnimation(accent),- ),+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 16),+ child: _buildMediaBar(fg, accent),),- const SizedBox(height: 4),Row(+ mainAxisAlignment: MainAxisAlignment.spaceEvenly,children: [- if (_chapterPageTotal > 0)- Text(- '$_chapterPage / $_chapterPageTotal',- style: TextStyle(color: fgDim, fontSize: 11),+ IconButton(+ icon: Icon(Icons.arrow_back_rounded, color: fg),+ onPressed: _handleClose,+ ),+ IconButton(+ icon: Icon(+ _hasBookmarkAtCurrent+ ? Icons.bookmark_rounded+ : Icons.bookmark_border_rounded,+ color: _hasBookmarkAtCurrent ? accent : fg,),- Expanded(- child: Padding(- padding: const EdgeInsets.symmetric(horizontal: 8),- child: Text(- _currentChapterTitle ?? '',- textAlign: TextAlign.center,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: TextStyle(color: fgDim, fontSize: 11),- ),+ onPressed: _toggleBookmark,+ ),+ IconButton(+ icon: Icon(Icons.search_rounded, color: fg),+ tooltip: AppLocalizations.of(context)!.readerTooltipSearch,+ onPressed: _openSearchScreen,+ ),+ IconButton(+ icon: Icon(Icons.sticky_note_2_outlined, color: fg),+ onPressed: _showAnnotationsSheet,+ ),+ IconButton(+ icon: Icon(+ Icons.swap_vert_rounded,+ color: _autoScroll ? accent : fg,),+ tooltip: AppLocalizations.of(context)!.readerAutoScroll,+ onPressed: _toggleAutoScroll,),- Text(- '${(_progress * 100).toStringAsFixed(1)}%',- style: TextStyle(color: fgDim, fontSize: 11),+ IconButton(+ icon: Icon(Icons.text_fields_rounded, color: fg),+ onPressed: _showSettingsSheet,),+ if (_chapters.isNotEmpty)+ IconButton(+ icon: Icon(Icons.list_rounded, color: fg),+ onPressed: _showChapterList,+ ),],),],diff --git a/lib/widgets/overlay_toast.dart b/lib/widgets/overlay_toast.dartindex 5ce7256a..b4fb4386 100644--- a/lib/widgets/overlay_toast.dart+++ b/lib/widgets/overlay_toast.dart@@ -46,6 +46,93 @@ void _insertOverlayToast(overlay.insert(entry);}+/// A toast that stays up and can change its text, for something the user is+/// actively adjusting (auto-scroll speed, say). Call [update] as the value+/// changes and [dismiss] when done - it does not time out on its own.+class LiveOverlayToast {+ final ValueNotifier<({String message, IconData? icon})> _value;+ OverlayEntry? _entry;++ LiveOverlayToast._(this._value, this._entry);++ static LiveOverlayToast? show(BuildContext context, String message, {IconData? icon}) {+ final overlay = Overlay.maybeOf(context);+ if (overlay == null) return null;+ _currentToast?.remove();+ _currentToast = null;+ final value = ValueNotifier<({String message, IconData? icon})>(+ (message: message, icon: icon));+ final entry = OverlayEntry(builder: (_) => _LiveToast(value: value));+ overlay.insert(entry);+ return LiveOverlayToast._(value, entry);+ }++ void update(String message, {IconData? icon}) {+ if (_entry == null) return;+ _value.value = (message: message, icon: icon);+ }++ void dismiss() {+ _entry?.remove();+ _entry = null;+ _value.dispose();+ }+}++class _LiveToast extends StatelessWidget {+ final ValueNotifier<({String message, IconData? icon})> value;+ const _LiveToast({required this.value});++ @override+ Widget build(BuildContext context) {+ final cs = Theme.of(context).colorScheme;+ return Positioned(+ bottom: MediaQuery.of(context).viewInsets.bottom + 100,+ left: 32,+ right: 32,+ child: Center(+ child: ClipRRect(+ borderRadius: BorderRadius.circular(24),+ child: BackdropFilter(+ filter: ui.ImageFilter.blur(sigmaX: 20, sigmaY: 20),+ child: Container(+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),+ decoration: BoxDecoration(+ color: cs.surface.withValues(alpha: 0.7),+ borderRadius: BorderRadius.circular(24),+ border: Border.all(color: cs.primary.withValues(alpha: 0.25)),+ ),+ child: ValueListenableBuilder<({String message, IconData? icon})>(+ valueListenable: value,+ builder: (context, v, _) => Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ if (v.icon != null) ...[+ Icon(v.icon, size: 18, color: cs.primary),+ const SizedBox(width: 8),+ ],+ Flexible(+ child: Text(+ v.message,+ style: TextStyle(+ color: cs.onSurface,+ fontSize: 13,+ fontWeight: FontWeight.w500,+ decoration: TextDecoration.none,+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ ),+ );+ }+}+class _AnimatedToast extends StatefulWidget {final String message;final IconData? icon;diff --git a/packages/flutter_epub_viewer/lib/assets/webpage/html/epubView.js b/packages/flutter_epub_viewer/lib/assets/webpage/html/epubView.jsindex c07c7a06..fdcf0967 100644--- a/packages/flutter_epub_viewer/lib/assets/webpage/html/epubView.js+++ b/packages/flutter_epub_viewer/lib/assets/webpage/html/epubView.js@@ -82,6 +82,10 @@ function attachSnapGuard() {// Book bytes arrive from Flutter in base64 chunks so no single string ever// holds the whole file; loadBook(null, ...) assembles them.var bookParts = [];+// Settings the live rendition was built with. The blind has to be laid out+// identically or its page boundaries drift from the real ones.+var lastRenderOpts = null;+var lastTheme = {bg: null, fg: null, css: null, fontSize: null};var bookPartsLen = 0;function beginBookData() {bookParts = [];@@ -122,7 +126,7 @@ function loadBook(data, cfi, initialXPath, manager, flow, spread, snap, allowScrbookPartsLen = 0;}book.open(uint8Array,)- rendition = book.renderTo("viewer", {+ lastRenderOpts = {manager: manager,flow: flow,spread: spread,@@ -131,7 +135,12 @@ function loadBook(data, cfi, initialXPath, manager, flow, spread, snap, allowScrsnap: snap && !useCustomSwipe,allowScriptedContent: allowScriptedContent,defaultDirection: direction- });+ };+ lastTheme.bg = backgroundColor;+ lastTheme.fg = foregroundColor;+ lastTheme.css = customCss;+ lastTheme.fontSize = fontSize;+ rendition = book.renderTo("viewer", lastRenderOpts);// Apply initial themeupdateTheme(backgroundColor, foregroundColor, customCss);@@ -2234,9 +2243,494 @@ function setManager(manager) {rendition.manager(manager);}+// ══════════════════════════════════════════════════════════════+// Auto-scroll: rolling blind+//+// The text never moves. The next page is rendered into its own stacked+// rendition and revealed from the top down, so by the time the eye gets back+// to the top of the screen it is already reading the next page. Stopping+// retracts the blind, leaving the current page whole.+//+// The blind rendition is deliberately dumb: no selection wiring, no highlight+// forwarding, no location reporting. Only the live rendition below it owns+// reading position, or auto-scroll would quietly corrupt saved progress.+// ══════════════════════════════════════════════════════════════++var blindRendition = null;+var blindY = 0; // how far down the blind has come, px+var blindSpeed = 40; // px per second+var blindRaf = null;+var blindLastTs = 0;+var blindSwapping = false;+var blindPaused = false; // the reader asked for it, survives touches+var blindTouchHold = false; // finger is down, transient++function blindHeight() {+ var host = document.getElementById("viewerNext");+ if (host && host.offsetHeight) return host.offsetHeight;+ return window.innerHeight || document.documentElement.clientHeight || 0;+}++// The blind has to occupy the live viewer's exact box. #viewer sits in a+// centred flex body with margins, so a full-screen blind paginates at a+// different width and its "next page" is not the live rendition's next page.+function blindMatchViewerBox() {+ var live = document.getElementById("viewer");+ var host = document.getElementById("viewerNext");+ if (!live || !host) return;+ var r = live.getBoundingClientRect();+ host.style.left = r.left + "px";+ host.style.top = r.top + "px";+ host.style.width = r.width + "px";+ host.style.height = r.height + "px";+}++// The line has to read on white, black, grey and cream alike, so it borrows+// the page's own text colour - whatever contrasts with that theme's background+// by definition - rather than a fixed grey that washes out on the light ones.+var blindLineRgb = null;++function blindResolveLineColor() {+ blindLineRgb = null;+ try {+ var contents = rendition.getContents();+ if (contents && contents.length) {+ var doc = contents[0].document;+ var col = contents[0].window.getComputedStyle(doc.body).color;+ var m = col && col.match(/rgba?\((\d+)[,\s]+(\d+)[,\s]+(\d+)/);+ if (m) blindLineRgb = m[1] + ", " + m[2] + ", " + m[3];+ }+ } catch (e) {}+}++function blindLineColor(paused) {+ var rgb = blindLineRgb || "150, 150, 150";+ return "rgba(" + rgb + ", " + (paused ? 0.95 : 0.45) + ")";+}++function blindApply() {+ var host = document.getElementById("viewerNext");+ if (!host) return;+ var h = blindHeight();+ var y = Math.max(0, Math.min(h, blindY));+ host.style.clipPath = "inset(0px 0px " + (h - y) + "px 0px)";+ host.style.webkitClipPath = "inset(0px 0px " + (h - y) + "px 0px)";+ var line = document.getElementById("blindLine");+ if (line) {+ if (y <= 0.5 || y >= h - 0.5) {+ line.style.display = "none";+ } else {+ var box = host.getBoundingClientRect();+ line.style.display = "block";+ line.style.left = box.left + "px";+ line.style.width = box.width + "px";+ line.style.top = (box.top + y) + "px";+ // Frozen white while paused, so the stopped edge is unmistakable.+ line.style.height = blindPaused ? "3px" : "2px";+ line.style.background = blindLineColor(blindPaused);+ }+ }+}++// Mirror whatever the live rendition actually has, rather than rebuilding it+// from remembered arguments. Themes get registered, selected and overridden+// from several places (load, theme change, font size), so a reconstruction+// drifts - copying the live objects cannot.+function blindThemeApply(r) {+ if (!r || !rendition) return;+ try {+ var liveThemes = rendition.themes;+ var name = liveThemes._current;+ var defs = liveThemes._themes || {};+ Object.keys(defs).forEach(function (key) {+ var def = defs[key];+ if (def && def.rules) r.themes.register(key, def.rules);+ });+ if (name && defs[name]) r.themes.select(name);+ // font-size and friends live in overrides, not in the theme rules+ var ov = liveThemes._overrides || {};+ Object.keys(ov).forEach(function (key) {+ var o = ov[key];+ if (o && typeof o.value !== "undefined") r.themes.override(key, o.value, o.priority);+ });+ } catch (e) {}+ // A downloadable font is an @font-face inside each iframe's own document,+ // so it has to be stamped into the blind's document too.+ try {+ if (window.__absorbApplyFontToDoc) {+ r.getContents().forEach(function (c) { window.__absorbApplyFontToDoc(c.document); });+ }+ } catch (e) {}+}++// ── Auto-scroll touch handling ──+// Lives here rather than in Flutter because the WebView is a platform view:+// a Flutter overlay never wins these touches, so taps and drags fell straight+// through to the live page and turned pages or selected text under the blind.++var blindTouchY = 0;+var blindTouchStartAt = 0;+var blindSpeedAtTouch = 0;+var blindTouchMoved = 0;+var BLIND_DRAG_SLOP = 12; // px before a touch counts as a speed drag+var BLIND_LONG_PRESS_MS = 550; // hold this long to stop instead of pause+// A 200px drag moves the speed about a fifth of its range. It used to be two+// thirds, which made 5% to 12% a flick of the thumb.+var BLIND_DRAG_GAIN = 45;+// Android's gesture nav lives along the bottom edge. A swipe up from there is+// the system's, not ours - claiming it sent the speed to 100% and resumed.+var BLIND_SYS_GESTURE_PX = 56;+var blindLongPressTimer = null;+var blindTouchIgnored = false;+var blindLongPressFired = false;++function blindNotify(name, value) {+ try {+ if (window.flutter_inappwebview && window.flutter_inappwebview.callHandler) {+ window.flutter_inappwebview.callHandler(name, value);+ }+ } catch (e) {}+}++function blindTouchStart(e) {+ var t = e.touches ? e.touches[0] : e;+ // Leave the system gesture strip alone - no preventDefault, no speed change,+ // so swiping up for recents or home behaves like it does everywhere else.+ var h = window.innerHeight || document.documentElement.clientHeight || 0;+ if (h && t.clientY > h - BLIND_SYS_GESTURE_PX) {+ blindTouchIgnored = true;+ return;+ }+ blindTouchIgnored = false;+ blindTouchHold = true;+ blindTouchY = t.clientY;+ blindTouchStartAt = Date.now();+ blindSpeedAtTouch = blindSpeed;+ blindTouchMoved = 0;+ blindLongPressFired = false;+ if (blindLongPressTimer) clearTimeout(blindLongPressTimer);+ blindLongPressTimer = setTimeout(function () {+ if (blindTouchMoved < 8) {+ blindLongPressFired = true;+ blindNotify("absorbAutoScrollLongPress", true);+ }+ }, BLIND_LONG_PRESS_MS);+ e.preventDefault();+}++function blindTouchMove(e) {+ if (blindTouchIgnored) return;+ var t = e.touches ? e.touches[0] : e;+ var dy = blindTouchY - t.clientY;+ if (Math.abs(dy) > blindTouchMoved) blindTouchMoved = Math.abs(dy);+ if (blindTouchMoved >= BLIND_DRAG_SLOP && blindLongPressTimer) {+ clearTimeout(blindLongPressTimer);+ blindLongPressTimer = null;+ }+ if (blindLongPressFired) return;+ // Below the slop this is a tap being held, not a drag. Without this a+ // one-pixel wobble opened the speed toast and nudged the speed.+ if (blindTouchMoved < BLIND_DRAG_SLOP) {+ e.preventDefault();+ return;+ }+ // up = faster, and 200px of travel covers most of the range+ var next = blindSpeedAtTouch + (dy / 200) * BLIND_DRAG_GAIN;+ next = Math.max(6, Math.min(220, next));+ blindSpeed = next;+ blindNotify("absorbAutoScrollSpeed", next);+ blindNotify("absorbAutoScrollDragging", true);+ e.preventDefault();+}++function blindTouchEnd(e) {+ if (blindTouchIgnored) {+ blindTouchIgnored = false;+ blindTouchHold = false;+ return;+ }+ if (blindLongPressTimer) {+ clearTimeout(blindLongPressTimer);+ blindLongPressTimer = null;+ }+ if (blindLongPressFired) {+ blindLongPressFired = false;+ return;+ }+ var quick = Date.now() - blindTouchStartAt < BLIND_LONG_PRESS_MS;+ blindTouchHold = false;+ if (quick && blindTouchMoved < BLIND_DRAG_SLOP) {+ // Flutter decides what a tap means - with the reader's control bars up it+ // dismisses those instead of pausing.+ blindNotify("absorbAutoScrollTap", true);+ } else {+ blindNotify("absorbAutoScrollDragEnd", true);+ }+ if (e && e.preventDefault) e.preventDefault();+}++// The system stealing a gesture (nav swipe, notification shade) arrives here.+// Put the speed back where it was and just resume - it was never our gesture.+function blindTouchCancel(e) {+ if (blindLongPressTimer) {+ clearTimeout(blindLongPressTimer);+ blindLongPressTimer = null;+ }+ blindLongPressFired = false;+ blindTouchIgnored = false;+ if (blindTouchMoved >= BLIND_DRAG_SLOP) {+ blindSpeed = blindSpeedAtTouch;+ blindNotify("absorbAutoScrollSpeed", blindSpeed);+ }+ blindNotify("absorbAutoScrollDragEnd", true);+ blindTouchHold = false;+ blindApply();+}++function blindTouchAttach() {+ var pad = document.getElementById("autoScrollTouch");+ if (!pad) return;+ pad.style.display = "block";+ pad.addEventListener("touchstart", blindTouchStart, {passive: false});+ pad.addEventListener("touchmove", blindTouchMove, {passive: false});+ pad.addEventListener("touchend", blindTouchEnd, {passive: false});+ pad.addEventListener("touchcancel", blindTouchCancel, {passive: false});+ pad.addEventListener("mousedown", blindTouchStart);+ pad.addEventListener("mousemove", function (e) { if (blindTouchHold) blindTouchMove(e); });+ pad.addEventListener("mouseup", blindTouchEnd);+ pad.addEventListener("click", blindSwallow, true);+ pad.addEventListener("pointerdown", blindSwallow, true);+ pad.addEventListener("pointerup", blindSwallow, true);+}++function blindSwallow(e) {+ e.preventDefault();+ e.stopPropagation();+}++function blindTouchDetach() {+ var pad = document.getElementById("autoScrollTouch");+ if (!pad) return;+ pad.removeEventListener("touchstart", blindTouchStart);+ pad.removeEventListener("touchmove", blindTouchMove);+ pad.removeEventListener("touchend", blindTouchEnd);+ pad.removeEventListener("touchcancel", blindTouchCancel);+ pad.removeEventListener("click", blindSwallow, true);+ pad.removeEventListener("pointerdown", blindSwallow, true);+ pad.removeEventListener("pointerup", blindSwallow, true);+ pad.style.display = "none";+}++// epub.js resolves display() before its manager has finished laying the+// section out in columns, and next() on an unlaid-out manager quietly does+// nothing - which left the blind showing the live page. Give layout a couple+// of frames, then advance, then confirm it actually moved and retry if not.+function blindFrames(n) {+ return new Promise(function (resolve) {+ var left = n;+ (function step() {+ if (left-- <= 0) return resolve();+ requestAnimationFrame(step);+ })();+ });+}++function blindCfiOf(r) {+ try {+ var loc = r.currentLocation();+ return loc && loc.start ? loc.start.cfi : null;+ } catch (e) {+ return null;+ }+}++// "Different CFI" is too weak a test: the blind could move and still show the+// same text, because a page is a span and two different positions can sit+// inside one visible page. The real question is whether the blind starts at or+// after where the live page ends, which epub.js can answer positionally.+function blindIsAhead() {+ try {+ var live = rendition.currentLocation();+ var blind = blindRendition.currentLocation();+ if (!live || !live.end || !blind || !blind.start) return false;+ var cmp = new ePub.CFI().compare(blind.start.cfi, live.end.cfi);+ return cmp >= 0;+ } catch (e) {+ var a = blindCfiOf(blindRendition);+ var b = blindCfiOf(rendition);+ return !!(a && b && a !== b);+ }+}++// Advance the blind until its first visible position is past the live page's+// last one, confirming each step rather than trusting next() to have worked.+function blindAdvancePastLive(attempt) {+ attempt = attempt || 0;+ if (!blindRendition) return Promise.resolve();+ var before = blindCfiOf(blindRendition);+ return blindFrames(2)+ .then(function () { return blindRendition.next(); })+ .then(function () { return blindFrames(1); })+ .then(function () {+ var moved = blindCfiOf(blindRendition) !== before;+ if (blindIsAhead() || attempt >= 5) return;+ // Not moving at all means layout still is not ready; give it longer.+ return blindFrames(moved ? 0 : 3)+ .then(function () { return blindAdvancePastLive(attempt + 1); });+ });+}++function autoScrollStart(speed) {+ if (!rendition || blindRendition) return;+ if (typeof speed === "number" && speed > 0) blindSpeed = speed;+ var host = document.getElementById("viewerNext");+ if (!host) return;+ host.style.display = "block";+ blindMatchViewerBox();+ if (lastTheme.bg && lastTheme.bg !== "null") host.style.background = lastTheme.bg;+ // A live selection makes rendition.next() a no-op (setupRenditionBlocking),+ // which would leave the reader stuck on one page for the whole run.+ try { clearSelection(); } catch (e) {}+ blindY = 0;+ blindApply();+ blindTouchAttach();+ blindResolveLineColor();+ blindPaused = false;+ var liveRendition = rendition;+ blindRendition = book.renderTo("viewerNext", lastRenderOpts);+ window.__absorbBlindRendition = blindRendition;+ try {+ blindRendition.hooks.content.register(function (contents) {+ if (window.__absorbApplyFontToDoc) window.__absorbApplyFontToDoc(contents.document);+ });+ } catch (e) {}+ // renderTo points book.rendition at whatever it just made - epub.js internals+ // still expect the live one.+ book.rendition = liveRendition;+ blindThemeApply(blindRendition);+ var loc = rendition.currentLocation();+ var cfi = loc && loc.start ? loc.start.cfi : null;+ blindRendition.on("rendered", function () { blindThemeApply(blindRendition); });+ Promise.resolve(cfi ? blindRendition.display(cfi) : blindRendition.display())+ .then(function () { return blindAdvancePastLive(0); })+ .then(function () {+ blindThemeApply(blindRendition);+ blindLastTs = 0;+ blindRaf = requestAnimationFrame(blindTick);+ })+ .catch(function () { autoScrollStop(); });+}++function blindTick(ts) {+ if (!blindRendition) return;+ if (!blindLastTs) blindLastTs = ts;+ var dt = (ts - blindLastTs) / 1000;+ blindLastTs = ts;+ // rAF stops while the app is away; the first frame back carries the whole gap+ if (dt > 0.25) dt = 0;+ if (!blindPaused && !blindTouchHold && !blindSwapping) {+ blindY += blindSpeed * dt;+ var h = blindHeight();+ if (blindY >= h) {+ blindY = h;+ blindApply();+ blindSwap();+ } else {+ blindApply();+ }+ }+ blindRaf = requestAnimationFrame(blindTick);+}++// The blind is fully open here, so the screen is already showing the next page.+// Advancing the live rendition underneath it is therefore invisible, and the+// blind can snap back to zero before it fetches the page after that.+function blindSwap() {+ blindSwapping = true;+ try { clearSelection(); } catch (e) {}+ Promise.resolve(rendition.next())+ // next() resolving does not mean the live page has painted. Retracting the+ // blind on that promise showed the old page for a frame, which read as a+ // page turn. Hold the blind up until the live page is actually there.+ .then(function () { return blindFrames(2); })+ .then(function () {+ blindY = 0;+ blindApply();+ return blindAdvancePastLive(0);+ })+ .then(function () {+ blindThemeApply(blindRendition);+ blindSwapping = false;+ })+ .catch(function () { autoScrollStop(); });+}++window.addEventListener("resize", function () {+ if (blindRendition) {+ blindMatchViewerBox();+ autoScrollResync();+ }+});++function autoScrollSpeed(speed) {+ if (typeof speed === "number" && speed >= 0) blindSpeed = speed;+}++function autoScrollPause(paused) {+ blindPaused = !!paused;+ blindApply();+}++// Re-seat the blind on the page after the live one. Used when the live+// rendition moves for any reason other than our own swap - a font size change,+// a manual page turn, a jump from the table of contents.+function autoScrollResync() {+ if (!blindRendition || !rendition) return;+ blindSwapping = true;+ blindY = 0;+ blindApply();+ var loc = rendition.currentLocation();+ var cfi = loc && loc.start ? loc.start.cfi : null;+ Promise.resolve(cfi ? blindRendition.display(cfi) : blindRendition.display())+ .then(function () { return blindAdvancePastLive(0); })+ .then(function () { blindSwapping = false; })+ .catch(function () { autoScrollStop(); });+}++function autoScrollStop() {+ blindTouchHold = false;+ if (blindRaf) cancelAnimationFrame(blindRaf);+ blindRaf = null;+ blindLastTs = 0;+ blindSwapping = false;+ blindPaused = false;+ blindY = 0;+ var line = document.getElementById("blindLine");+ if (line) line.style.display = "none";+ var host = document.getElementById("viewerNext");+ if (host) {+ host.style.clipPath = "inset(0px 0px 100% 0px)";+ host.style.webkitClipPath = "inset(0px 0px 100% 0px)";+ host.style.display = "none";+ }+ if (blindRendition) {+ try { blindRendition.destroy(); } catch (e) {}+ blindRendition = null;+ }+ window.__absorbBlindRendition = null;+ if (host) host.innerHTML = "";+ blindTouchDetach();+}++function autoScrollActive() {+ return blindRendition !== null;+}+function setFontSize(fontSize) {+ lastTheme.fontSize = fontSize;rendition.themes.fontSize(`${fontSize}px`);rendition.reportLocation();+ if (blindRendition) autoScrollResync();}//get current page text@@ -2277,32 +2771,45 @@ function getTextFromCfi(startCfi, endCfi) {///update themefunction updateTheme(backgroundColor, foregroundColor, customCss) {+ lastTheme.bg = backgroundColor;+ lastTheme.fg = foregroundColor;+ lastTheme.css = customCss;+ var host = document.getElementById("viewerNext");+ if (host && backgroundColor && backgroundColor !== "null") {+ host.style.background = backgroundColor;+ }+ if (blindRendition) {+ blindThemeApply(blindRendition);+ blindResolveLineColor();+ }+ var rules = buildThemeRules(backgroundColor, foregroundColor, customCss);++ // Update theme if there are rules+ if (Object.keys(rules).length > 0) {+ rendition.themes.register("user-theme", rules);+ rendition.themes.select("user-theme");+ }+}++// Shared by the live rendition and the auto-scroll blind. The blind used to+// build its own cut-down version and lost customCss, which is where the+// reader's font lives - so the incoming page came in with the wrong typeface.+function buildThemeRules(backgroundColor, foregroundColor, customCss) {var rules = {};var themeObj = {};-- // Build theme object with available colors- // Only include properties that are provided and not emptyif (backgroundColor && backgroundColor !== "" && backgroundColor !== "null") {themeObj["background"] = backgroundColor;}if (foregroundColor && foregroundColor !== "" && foregroundColor !== "null") {themeObj["color"] = foregroundColor;}-if (Object.keys(themeObj).length > 0) {rules["body"] = themeObj;}-- // Merge custom CSS- if (customCss && customCss !== "null" && typeof customCss === 'object') {+ if (customCss && customCss !== "null" && typeof customCss === "object") {Object.assign(rules, customCss);}-- // Update theme if there are rules- if (Object.keys(rules).length > 0) {- rendition.themes.register("user-theme", rules);- rendition.themes.select("user-theme");- }+ return rules;}const makeRangeCfi = (a, b) => {diff --git a/packages/flutter_epub_viewer/lib/assets/webpage/html/swipe.html b/packages/flutter_epub_viewer/lib/assets/webpage/html/swipe.htmlindex 85dea93d..27ad717c 100644--- a/packages/flutter_epub_viewer/lib/assets/webpage/html/swipe.html+++ b/packages/flutter_epub_viewer/lib/assets/webpage/html/swipe.html@@ -30,6 +30,41 @@background: white;}+ #viewerNext {+ display: none;+ position: fixed;+ top: 0;+ left: 0;+ width: 100%;+ height: 100%;+ margin: 0;+ pointer-events: none;+ z-index: 2;+ }++ #blindLine {+ display: none;+ position: fixed;+ height: 2px;+ /* above the blind and the touch pad - nothing should cover it */+ z-index: 4;+ pointer-events: none;+ background: rgba(150, 150, 150, 0.9);+ box-shadow: 0 0 3px rgba(0, 0, 0, 0.35);+ }++ #autoScrollTouch {+ display: none;+ position: fixed;+ top: 0;+ left: 0;+ width: 100%;+ height: 100%;+ z-index: 3;+ background: transparent;+ touch-action: none;+ }+@media only screen and (min-device-width: 320px) and (max-device-width: 667px) {.arrow {position: inherit;@@ -40,6 +75,17 @@</head><body><div id="viewer"></div>+ <!-- Auto-scroll blind: the next page, stacked over the live one and+ revealed top-down. Never interactive - the live rendition below owns+ every touch, selection and highlight. -->+ <div id="viewerNext"></div>+ <!-- Swallows every touch while auto-scroll runs. A Flutter overlay cannot+ do this job: the WebView is a platform view and claims touches first,+ so taps fell through to the live page underneath the blind. -->+ <div id="autoScrollTouch"></div>+ <!-- Subtle rule at the blind's leading edge, so the boundary is findable+ once the incoming page matches the current one exactly. -->+ <div id="blindLine"></div><script src="epubView.js"></script></body></html>diff --git a/packages/flutter_epub_viewer/lib/src/epub_controller.dart b/packages/flutter_epub_viewer/lib/src/epub_controller.dartindex 349a7b30..bf5d98b4 100644--- a/packages/flutter_epub_viewer/lib/src/epub_controller.dart+++ b/packages/flutter_epub_viewer/lib/src/epub_controller.dart@@ -163,6 +163,34 @@ class EpubController {}///Set [EpubFlow] value+ /// Start the rolling-blind auto scroll at [speed] pixels per second. The+ /// next page is revealed top-down over the current one; the text itself+ /// never moves.+ Future<void> autoScrollStart({double speed = 40}) async {+ await webViewController?.evaluateJavascript(source: 'autoScrollStart($speed)');+ }++ /// Change the blind's descent speed while it is running.+ Future<void> autoScrollSpeed(double speed) async {+ await webViewController?.evaluateJavascript(source: 'autoScrollSpeed($speed)');+ }++ /// Hold the blind where it is without tearing it down.+ Future<void> autoScrollPause(bool paused) async {+ await webViewController?.evaluateJavascript(source: 'autoScrollPause($paused)');+ }++ /// Put the blind back on the page after the live one, after the reader+ /// moved for some other reason.+ Future<void> autoScrollResync() async {+ await webViewController?.evaluateJavascript(source: 'autoScrollResync()');+ }++ /// Retract the blind and drop the second rendition.+ Future<void> autoScrollStop() async {+ await webViewController?.evaluateJavascript(source: 'autoScrollStop()');+ }+setFlow({required EpubFlow flow}) async {await webViewController?.evaluateJavascript(source: 'setFlow("$flow")');}