Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Tidy up auto scroll: keep the screen on, remember the speed, ignore volume keys, stop at the end of the book, never skip a chapter's first page, and fit the toolbar on narrow phones

Barnabasc4c8307d5adc
diff --git a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
index 890413d5..e1774c0b 100644
--- a/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
+++ b/android/app/src/main/kotlin/com/barnabas/absorb/MainActivity.kt
@@ -21,6 +21,7 @@ import android.os.StatFs
import android.util.Log
import android.view.KeyEvent
+import android.view.WindowManager
import com.ryanheise.audioservice.AudioService
import com.ryanheise.audioservice.AudioServiceActivity
import com.ryanheise.audioservice.AudioServicePlugin
@@ -123,6 +124,24 @@ class MainActivity : AudioServiceActivity() {
}
Log.d(TAG, "EQ method channel registered")
+ // Auto scroll in the ebook reader keeps the screen on for as long as it
+ // runs; the reader releases it when the scroll stops or it closes.
+ MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.absorb.screen_wake")
+ .setMethodCallHandler { call, result ->
+ when (call.method) {
+ "set" -> {
+ val on = call.argument<Boolean>("on") ?: false
+ if (on) {
+ window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ } else {
+ window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ }
+ result.success(true)
+ }
+ else -> result.notImplemented()
+ }
+ }
+
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "com.absorb.audio_diag")
.setMethodCallHandler { call, result ->
when (call.method) {
diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift
index d7d2d58b..0a8506a6 100644
--- a/ios/Runner/AppDelegate.swift
+++ b/ios/Runner/AppDelegate.swift
@@ -419,6 +419,22 @@ let flutterEngine = FlutterEngine(name: "SharedEngine", project: nil, allowHeadl
}
}
+ // Auto scroll in the ebook reader keeps the screen on for as long as it
+ // runs; the reader releases it when the scroll stops or it closes.
+ let screenWakeChannel = FlutterMethodChannel(name: "com.absorb.screen_wake",
+ binaryMessenger: messenger)
+ screenWakeChannel.setMethodCallHandler { (call, result) in
+ switch call.method {
+ case "set":
+ let args = call.arguments as? [String: Any]
+ let on = args?["on"] as? Bool ?? false
+ UIApplication.shared.isIdleTimerDisabled = on
+ result(true)
+ default:
+ result(FlutterMethodNotImplemented)
+ }
+ }
+
let storageChannel = FlutterMethodChannel(name: "com.absorb.storage",
binaryMessenger: messenger)
storageChannel.setMethodCallHandler { (call, result) in
diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb
index 929e9a57..ea057b87 100644
--- a/lib/l10n/app_en.arb
+++ b/lib/l10n/app_en.arb
@@ -4656,6 +4656,7 @@
"readerAutoScrollPaused": "Paused - press and hold to stop",
"readerAutoScrollResumed": "Auto scroll resumed",
"readerAutoScrollStopped": "Auto scroll off",
+ "readerAutoScrollEndOfBook": "End of book - auto scroll off",
"readerAutoScrollSpeed": "Speed {percent}%",
"@readerAutoScrollSpeed": {
"placeholders": { "percent": { "type": "int" } }
diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart
index 263b0703..9e122ceb 100644
--- a/lib/l10n/app_localizations.dart
+++ b/lib/l10n/app_localizations.dart
@@ -13983,6 +13983,12 @@ abstract class AppLocalizations {
/// **'Auto scroll off'**
String get readerAutoScrollStopped;
+ /// No description provided for @readerAutoScrollEndOfBook.
+ ///
+ /// In en, this message translates to:
+ /// **'End of book - auto scroll off'**
+ String get readerAutoScrollEndOfBook;
+
/// No description provided for @readerAutoScrollSpeed.
///
/// In en, this message translates to:
diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart
index 76561ae0..fb13f7f8 100644
--- a/lib/l10n/app_localizations_de.dart
+++ b/lib/l10n/app_localizations_de.dart
@@ -8209,6 +8209,9 @@ class AppLocalizationsDe extends AppLocalizations {
@override
String get readerAutoScrollStopped => 'Auto scroll off';
+ @override
+ String get readerAutoScrollEndOfBook => 'End of book - auto scroll off';
+
@override
String readerAutoScrollSpeed(int percent) {
return 'Speed $percent%';
diff --git a/lib/l10n/app_localizations_el.dart b/lib/l10n/app_localizations_el.dart
index 11f5019a..5ca1e916 100644
--- a/lib/l10n/app_localizations_el.dart
+++ b/lib/l10n/app_localizations_el.dart
@@ -8092,6 +8092,9 @@ class AppLocalizationsEl extends AppLocalizations {
@override
String get readerAutoScrollStopped => 'Auto scroll off';
+ @override
+ String get readerAutoScrollEndOfBook => 'End of book - auto scroll off';
+
@override
String readerAutoScrollSpeed(int percent) {
return 'Speed $percent%';
diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart
index dc6da75b..1a71532c 100644
--- a/lib/l10n/app_localizations_en.dart
+++ b/lib/l10n/app_localizations_en.dart
@@ -8092,6 +8092,9 @@ class AppLocalizationsEn extends AppLocalizations {
@override
String get readerAutoScrollStopped => 'Auto scroll off';
+ @override
+ String get readerAutoScrollEndOfBook => 'End of book - auto scroll off';
+
@override
String readerAutoScrollSpeed(int percent) {
return 'Speed $percent%';
diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart
index f6b531bf..631091a1 100644
--- a/lib/l10n/app_localizations_es.dart
+++ b/lib/l10n/app_localizations_es.dart
@@ -8094,6 +8094,9 @@ class AppLocalizationsEs extends AppLocalizations {
@override
String get readerAutoScrollStopped => 'Auto scroll off';
+ @override
+ String get readerAutoScrollEndOfBook => 'End of book - auto scroll off';
+
@override
String readerAutoScrollSpeed(int percent) {
return 'Speed $percent%';
diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart
index d5ec7d25..19f06f92 100644
--- a/lib/l10n/app_localizations_fr.dart
+++ b/lib/l10n/app_localizations_fr.dart
@@ -8143,6 +8143,9 @@ class AppLocalizationsFr extends AppLocalizations {
@override
String get readerAutoScrollStopped => 'Auto scroll off';
+ @override
+ String get readerAutoScrollEndOfBook => 'End of book - auto scroll off';
+
@override
String readerAutoScrollSpeed(int percent) {
return 'Speed $percent%';
diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart
index cf79d100..9586f8cb 100644
--- a/lib/l10n/app_localizations_it.dart
+++ b/lib/l10n/app_localizations_it.dart
@@ -8092,6 +8092,9 @@ class AppLocalizationsIt extends AppLocalizations {
@override
String get readerAutoScrollStopped => 'Auto scroll off';
+ @override
+ String get readerAutoScrollEndOfBook => 'End of book - auto scroll off';
+
@override
String readerAutoScrollSpeed(int percent) {
return 'Speed $percent%';
diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart
index 6e1809dd..d21b3ab0 100644
--- a/lib/l10n/app_localizations_ja.dart
+++ b/lib/l10n/app_localizations_ja.dart
@@ -8092,6 +8092,9 @@ class AppLocalizationsJa extends AppLocalizations {
@override
String get readerAutoScrollStopped => 'Auto scroll off';
+ @override
+ String get readerAutoScrollEndOfBook => 'End of book - auto scroll off';
+
@override
String readerAutoScrollSpeed(int percent) {
return 'Speed $percent%';
diff --git a/lib/l10n/app_localizations_no.dart b/lib/l10n/app_localizations_no.dart
index 4641eb8b..6201cf57 100644
--- a/lib/l10n/app_localizations_no.dart
+++ b/lib/l10n/app_localizations_no.dart
@@ -8092,6 +8092,9 @@ class AppLocalizationsNo extends AppLocalizations {
@override
String get readerAutoScrollStopped => 'Auto scroll off';
+ @override
+ String get readerAutoScrollEndOfBook => 'End of book - auto scroll off';
+
@override
String readerAutoScrollSpeed(int percent) {
return 'Speed $percent%';
diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart
index 269e83d9..8c532179 100644
--- a/lib/l10n/app_localizations_pt.dart
+++ b/lib/l10n/app_localizations_pt.dart
@@ -8092,6 +8092,9 @@ class AppLocalizationsPt extends AppLocalizations {
@override
String get readerAutoScrollStopped => 'Auto scroll off';
+ @override
+ String get readerAutoScrollEndOfBook => 'End of book - auto scroll off';
+
@override
String readerAutoScrollSpeed(int percent) {
return 'Speed $percent%';
diff --git a/lib/l10n/app_localizations_ro.dart b/lib/l10n/app_localizations_ro.dart
index 7d30ced0..2a412d40 100644
--- a/lib/l10n/app_localizations_ro.dart
+++ b/lib/l10n/app_localizations_ro.dart
@@ -8092,6 +8092,9 @@ class AppLocalizationsRo extends AppLocalizations {
@override
String get readerAutoScrollStopped => 'Auto scroll off';
+ @override
+ String get readerAutoScrollEndOfBook => 'End of book - auto scroll off';
+
@override
String readerAutoScrollSpeed(int percent) {
return 'Speed $percent%';
diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart
index 1a0a502b..91bb6f15 100644
--- a/lib/l10n/app_localizations_ru.dart
+++ b/lib/l10n/app_localizations_ru.dart
@@ -8097,6 +8097,9 @@ class AppLocalizationsRu extends AppLocalizations {
@override
String get readerAutoScrollStopped => 'Auto scroll off';
+ @override
+ String get readerAutoScrollEndOfBook => 'End of book - auto scroll off';
+
@override
String readerAutoScrollSpeed(int percent) {
return 'Speed $percent%';
diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart
index 1a48e44d..7bb8cf31 100644
--- a/lib/l10n/app_localizations_zh.dart
+++ b/lib/l10n/app_localizations_zh.dart
@@ -8000,6 +8000,9 @@ class AppLocalizationsZh extends AppLocalizations {
@override
String get readerAutoScrollStopped => 'Auto scroll off';
+ @override
+ String get readerAutoScrollEndOfBook => 'End of book - auto scroll off';
+
@override
String readerAutoScrollSpeed(int percent) {
return 'Speed $percent%';
diff --git a/lib/services/screen_wake.dart b/lib/services/screen_wake.dart
new file mode 100644
index 00000000..d0f4949c
--- /dev/null
+++ b/lib/services/screen_wake.dart
@@ -0,0 +1,17 @@
+import 'package:flutter/foundation.dart';
+import 'package:flutter/services.dart';
+
+/// Keeps the screen from timing out while something hands-free is on screen,
+/// like the ebook reader's auto scroll. FLAG_KEEP_SCREEN_ON on Android, the
+/// idle timer on iOS. Callers must release it: neither platform clears it.
+class ScreenWake {
+ static const _channel = MethodChannel('com.absorb.screen_wake');
+
+ static Future<void> keepOn(bool on) async {
+ try {
+ await _channel.invokeMethod('set', {'on': on});
+ } catch (e) {
+ debugPrint('[ScreenWake] keepOn($on) failed: $e');
+ }
+ }
+}
diff --git a/lib/widgets/ebook_reader_view.dart b/lib/widgets/ebook_reader_view.dart
index 2362e91a..c6ef89a2 100644
--- a/lib/widgets/ebook_reader_view.dart
+++ b/lib/widgets/ebook_reader_view.dart
@@ -20,6 +20,7 @@ import '../services/find_in_ebook.dart';
import '../services/progress_sync_service.dart';
import '../services/reader_font_service.dart';
import '../services/scoped_prefs.dart';
+import '../services/screen_wake.dart';
import '../services/transcription_service.dart';
import '../services/volume_key_service.dart';
import 'overlay_toast.dart';
@@ -228,9 +229,11 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs
});
}
+ // Volume-key turns are ignored while auto scroll runs: the blind is already
+ // showing the next page, and a turn underneath it leaves that page unread.
late final EreaderVolumeNav _volumeNav = EreaderVolumeNav(
- onPrev: () => _epubController?.prev(),
- onNext: () => _epubController?.next(),
+ onPrev: () { if (!_autoScroll) _epubController?.prev(); },
+ onNext: () { if (!_autoScroll) _epubController?.next(); },
);
@override
@@ -249,8 +252,11 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs
_bgCfi = null;
_bgDrifted = false;
if (drifted && cfi != null && cfi.isNotEmpty) {
- Future.delayed(const Duration(milliseconds: 350), () {
- if (mounted && _readerActive) _epubController?.display(cfi: cfi);
+ Future.delayed(const Duration(milliseconds: 350), () async {
+ if (!mounted || !_readerActive) return;
+ await _epubController?.display(cfi: cfi);
+ // The live page moved under the blind; re-seat it on the page after.
+ if (_autoScroll) await _epubController?.autoScrollResync();
});
}
} else {
@@ -346,6 +352,9 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs
_fontId = await ScopedPrefs.getString(_kFont) ?? 'original';
_volumeNavMode = await PlayerSettings.getEreaderVolumeNav();
_volumeNavWhilePlaying = await PlayerSettings.getEreaderVolumeNavWhilePlaying();
+ _autoScrollSpeed = (await PlayerSettings.getEreaderAutoScrollSpeed())
+ .clamp(_autoScrollMin, _autoScrollMax)
+ .toDouble();
if (mounted) setState(() {});
}
@@ -517,7 +526,10 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs
@override
void dispose() {
_speedToast?.dismiss();
- if (_autoScroll) _epubController?.autoScrollStop();
+ if (_autoScroll) {
+ _epubController?.autoScrollStop();
+ ScreenWake.keepOn(false);
+ }
_quietLib.setReaderQuiet(false);
WidgetsBinding.instance.removeObserver(this);
_volumeNav.detach();
@@ -1532,7 +1544,6 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs
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,
@@ -1545,11 +1556,40 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs
);
},
);
+ _epubController?.webViewController?.addJavaScriptHandler(
+ handlerName: 'absorbAutoScrollLog',
+ callback: (args) {
+ if (args.isNotEmpty) debugPrint('[AutoScroll] ${args[0]}');
+ },
+ );
_epubController?.webViewController?.addJavaScriptHandler(
handlerName: 'absorbAutoScrollDragEnd',
callback: (args) {
_speedToast?.dismiss();
_speedToast = null;
+ PlayerSettings.setEreaderAutoScrollSpeed(_autoScrollSpeed);
+ },
+ );
+ // The blind stopping on its own: the last page of the book, or a page
+ // that failed to load.
+ _epubController?.webViewController?.addJavaScriptHandler(
+ handlerName: 'absorbAutoScrollEnded',
+ callback: (args) {
+ if (!mounted || !_autoScroll) return;
+ final atEnd = args.isNotEmpty && args[0]?.toString() == 'end';
+ _speedToast?.dismiss();
+ _speedToast = null;
+ ScreenWake.keepOn(false);
+ setState(() {
+ _autoScroll = false;
+ _autoScrollPaused = false;
+ });
+ final l = AppLocalizations.of(context)!;
+ showOverlayToast(
+ context,
+ atEnd ? l.readerAutoScrollEndOfBook : l.readerAutoScrollStopped,
+ icon: atEnd ? Icons.menu_book_rounded : Icons.stop_circle_outlined,
+ );
},
);
_epubController?.webViewController?.addJavaScriptHandler(
@@ -1566,7 +1606,7 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs
_epubController?.webViewController?.addJavaScriptHandler(
handlerName: 'absorbAutoScrollTap',
callback: (args) {
- if (!mounted) return;
+ if (!mounted || !_autoScroll) 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) {
@@ -1589,18 +1629,23 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs
Future<void> _toggleAutoScroll() async {
if (_autoScroll) {
await _epubController?.autoScrollStop();
+ ScreenWake.keepOn(false);
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(() {
+ // The blind can't start before the book is displayed. Flagging auto
+ // scroll on regardless left the reader with its taps swallowed and no
+ // bars to reach this button again.
+ final started =
+ await _epubController?.autoScrollStart(speed: _autoScrollSpeed) ?? false;
+ if (!mounted || !started) return;
+ ScreenWake.keepOn(true);
+ showOverlayToast(context, AppLocalizations.of(context)!.readerAutoScrollStarted,
+ icon: Icons.swap_vert_rounded);
+ setState(() {
_autoScroll = true;
_autoScrollPaused = false;
if (_showControls) _showControls = false;
@@ -3718,47 +3763,62 @@ class EbookReaderViewState extends State<EbookReaderView> with WidgetsBindingObs
padding: const EdgeInsets.symmetric(horizontal: 16),
child: _buildMediaBar(fg, accent),
),
+ // Equal cells: on a narrow phone they shrink below
+ // the buttons' 48dp instead of overflowing the row.
Row(
- mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
- IconButton(
- icon: Icon(Icons.arrow_back_rounded, color: fg),
- onPressed: _handleClose,
+ Expanded(
+ child: 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: IconButton(
+ icon: Icon(
+ _hasBookmarkAtCurrent
+ ? Icons.bookmark_rounded
+ : Icons.bookmark_border_rounded,
+ color: _hasBookmarkAtCurrent ? accent : fg,
+ ),
+ onPressed: _toggleBookmark,
),
- onPressed: _toggleBookmark,
),
- IconButton(
- icon: Icon(Icons.search_rounded, color: fg),
- tooltip: AppLocalizations.of(context)!.readerTooltipSearch,
- onPressed: _openSearchScreen,
+ Expanded(
+ child: 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,
+ Expanded(
+ child: IconButton(
+ icon: Icon(Icons.sticky_note_2_outlined, color: fg),
+ onPressed: _showAnnotationsSheet,
+ ),
),
- IconButton(
- icon: Icon(
- Icons.swap_vert_rounded,
- color: _autoScroll ? accent : fg,
+ Expanded(
+ child: IconButton(
+ icon: Icon(
+ Icons.swap_vert_rounded,
+ color: _autoScroll ? accent : fg,
+ ),
+ tooltip: AppLocalizations.of(context)!.readerAutoScroll,
+ onPressed: _toggleAutoScroll,
),
- tooltip: AppLocalizations.of(context)!.readerAutoScroll,
- onPressed: _toggleAutoScroll,
),
- IconButton(
- icon: Icon(Icons.text_fields_rounded, color: fg),
- onPressed: _showSettingsSheet,
+ Expanded(
+ child: IconButton(
+ icon: Icon(Icons.text_fields_rounded, color: fg),
+ onPressed: _showSettingsSheet,
+ ),
),
if (_chapters.isNotEmpty)
- IconButton(
- icon: Icon(Icons.list_rounded, color: fg),
- onPressed: _showChapterList,
+ Expanded(
+ child: IconButton(
+ icon: Icon(Icons.list_rounded, color: fg),
+ onPressed: _showChapterList,
+ ),
),
],
),
diff --git a/lib/widgets/overlay_toast.dart b/lib/widgets/overlay_toast.dart
index b4fb4386..994d2dae 100644
--- a/lib/widgets/overlay_toast.dart
+++ b/lib/widgets/overlay_toast.dart
@@ -3,6 +3,18 @@ import 'package:flutter/material.dart';
OverlayEntry? _currentToast;
+// remove() is not idempotent, and a toast has two removers: its own exit
+// animation and any newer toast taking its place. When both landed in the
+// same frame (tap to pause, then hold to stop) the second call threw. Every
+// removal goes through here so the second one is a no-op.
+final Expando<bool> _removedToasts = Expando<bool>();
+
+void _removeToast(OverlayEntry entry) {
+ if (_removedToasts[entry] == true) return;
+ _removedToasts[entry] = true;
+ entry.remove();
+}
+
/// Show a styled toast that renders above modal sheets and overlays.
///
/// Pass [icon] for a leading icon (e.g. Icons.check_circle_rounded).
@@ -25,7 +37,8 @@ void _insertOverlayToast(
String message, {
IconData? icon,
}) {
- _currentToast?.remove();
+ final previous = _currentToast;
+ if (previous != null) _removeToast(previous);
_currentToast = null;
// No overlay (startup, account switch, background-triggered callers): drop
@@ -37,7 +50,7 @@ void _insertOverlayToast(
message: message,
icon: icon,
onDone: () {
- entry.remove();
+ _removeToast(entry);
if (_currentToast == entry) _currentToast = null;
},
),
@@ -58,7 +71,8 @@ class LiveOverlayToast {
static LiveOverlayToast? show(BuildContext context, String message, {IconData? icon}) {
final overlay = Overlay.maybeOf(context);
if (overlay == null) return null;
- _currentToast?.remove();
+ final previous = _currentToast;
+ if (previous != null) _removeToast(previous);
_currentToast = null;
final value = ValueNotifier<({String message, IconData? icon})>(
(message: message, icon: icon));
@@ -73,8 +87,10 @@ class LiveOverlayToast {
}
void dismiss() {
- _entry?.remove();
+ final entry = _entry;
+ if (entry == null) return;
_entry = null;
+ _removeToast(entry);
_value.dispose();
}
}
diff --git a/packages/flutter_epub_viewer/lib/assets/webpage/html/epubView.js b/packages/flutter_epub_viewer/lib/assets/webpage/html/epubView.js
index fdcf0967..bd8fdb64 100644
--- a/packages/flutter_epub_viewer/lib/assets/webpage/html/epubView.js
+++ b/packages/flutter_epub_viewer/lib/assets/webpage/html/epubView.js
@@ -2392,6 +2392,68 @@ function blindNotify(name, value) {
} catch (e) {}
}
+// Diagnostics for the app log (console output is dropped in release builds):
+// where a rendition thinks it is, how its manager has the section laid out,
+// and whether the section's images have loaded - the three things that can
+// put the blind on a different page from the one after the live page.
+function blindLog(msg) {
+ blindNotify("absorbAutoScrollLog", msg);
+}
+
+function blindLocSummary(r) {
+ try {
+ var loc = r.currentLocation();
+ if (!loc || !loc.start) return "loc=none";
+ var s = loc.start, e = loc.end || {};
+ var sd = s.displayed || {}, ed = e.displayed || {};
+ return "loc sec=" + s.index + " page=" + sd.page + "/" + sd.total +
+ " endPage=" + ed.page + " atEnd=" + !!loc.atEnd +
+ " start=" + (s.cfi || "?") + " end=" + (e.cfi || "?");
+ } catch (err) {
+ return "loc err " + err;
+ }
+}
+
+function blindLayoutSummary(r) {
+ try {
+ var m = r.manager;
+ var v = m.views.last();
+ var w = v ? v.width() : 0;
+ var c = m.layout.count(w);
+ return "layout sec=" + (v && v.section ? v.section.index : -1) +
+ " viewW=" + Math.round(w) + " pages=" + c.pages +
+ " scrollL=" + Math.round(m.container.scrollLeft) +
+ " scrollW=" + m.container.scrollWidth +
+ " delta=" + m.layout.delta + " W=" + m.layout.width + " H=" + m.layout.height;
+ } catch (err) {
+ return "layout err " + err;
+ }
+}
+
+function blindImageSummary(r) {
+ try {
+ var cs = r.getContents();
+ if (!cs || !cs.length) return "imgs none";
+ var doc = cs[cs.length - 1].document;
+ var imgs = doc.images;
+ var loaded = 0;
+ var first = "";
+ for (var i = 0; i < imgs.length; i++) {
+ if (imgs[i].complete && imgs[i].naturalWidth > 0) loaded++;
+ }
+ if (imgs.length) {
+ var b = imgs[0].getBoundingClientRect();
+ first = " first=" + Math.round(b.width) + "x" + Math.round(b.height) +
+ "@" + Math.round(b.left) + "," + Math.round(b.top) +
+ " natural=" + imgs[0].naturalWidth + "x" + imgs[0].naturalHeight;
+ }
+ return "imgs=" + imgs.length + " loaded=" + loaded + first +
+ " frame=" + doc.documentElement.clientWidth + "x" + doc.documentElement.clientHeight;
+ } catch (err) {
+ return "imgs err " + err;
+ }
+}
+
function blindTouchStart(e) {
var t = e.touches ? e.touches[0] : e;
// Leave the system gesture strip alone - no preventDefault, no speed change,
@@ -2535,56 +2597,101 @@ function blindFrames(n) {
});
}
-function blindCfiOf(r) {
+// The page a rendition is showing, as "section:column", read straight off the
+// manager's geometry: the view under the container's leading edge and how
+// many page widths into it that edge sits. Both renditions lay the book out
+// identically (same width, same sections), so the ids compare across them.
+// This replaces epub.js's reported location, which at a section boundary
+// names the previous section's tail as the page start (a zero-width edge
+// overlap) and so judged the image page that opens a chapter to be behind the
+// live page. Appended-but-unscrolled sections and the rebased scroll offsets
+// left by the manager trimming far sections don't change it either.
+function blindPageIdOf(r) {
try {
- var loc = r.currentLocation();
- return loc && loc.start ? loc.start.cfi : null;
- } catch (e) {
- return null;
- }
+ var m = r.manager;
+ var c = m.container.getBoundingClientRect();
+ var rtl = m.settings && m.settings.direction === "rtl";
+ var probe = rtl ? c.right - 1 : c.left + 1;
+ var views = m.views.all();
+ for (var i = 0; i < views.length; i++) {
+ var v = views[i];
+ if (!v || !v.element || !v.section) continue;
+ var b = v.element.getBoundingClientRect();
+ if (b.left <= probe && b.right > probe) {
+ var into = rtl ? b.right - probe : probe - b.left;
+ return v.section.index + ":" + Math.round(into / m.layout.delta);
+ }
+ }
+ } 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);
- }
+// 1 = the blind is past the live page, 0 = same page, -1 = behind it,
+// null = one of them has nothing laid out yet.
+function blindPageCmp() {
+ var a = blindPageIdOf(blindRendition);
+ var b = blindPageIdOf(rendition);
+ if (!a || !b) return null;
+ var pa = a.split(":").map(Number);
+ var pb = b.split(":").map(Number);
+ if (pa[0] !== pb[0]) return pa[0] > pb[0] ? 1 : -1;
+ if (pa[1] === pb[1]) return 0;
+ return pa[1] > pb[1] ? 1 : -1;
}
-// 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.
+var BLIND_ADVANCE_ATTEMPTS = 10;
+
+// Turn the blind one page at a time until it sits past the live page. A turn
+// that leaves the page id unchanged means the manager could not scroll yet
+// (the next section is still being appended), so give it a few frames and
+// turn again; the cap only trips at the end of the book.
function blindAdvancePastLive(attempt) {
attempt = attempt || 0;
if (!blindRendition) return Promise.resolve();
- var before = blindCfiOf(blindRendition);
- return blindFrames(2)
+ if (blindPageCmp() === 1) return Promise.resolve();
+ var before = blindPageIdOf(blindRendition);
+ return blindFrames(attempt === 0 ? 2 : 0)
.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)
+ if (!blindRendition) return;
+ var after = blindPageIdOf(blindRendition);
+ var moved = after !== null && after !== before;
+ var cmp = blindPageCmp();
+ var done = cmp === 1;
+ var last = attempt + 1 >= BLIND_ADVANCE_ATTEMPTS;
+ blindLog("advance#" + attempt + " page " + before + "->" + after +
+ " live=" + blindPageIdOf(rendition) + " cmp=" + cmp + " moved=" + moved +
+ (done ? " done" : last ? " giveup" : " retry") +
+ " | blind " + blindLocSummary(blindRendition) + " | " + blindLayoutSummary(blindRendition) +
+ " | " + blindImageSummary(blindRendition) + " | live " + blindLocSummary(rendition));
+ if (done) return;
+ if (last) {
+ // Nothing left to reveal: the live page is the book's last one.
+ if (blindLiveAtEnd()) autoScrollStop("end");
+ return;
+ }
+ return blindFrames(moved ? 0 : 6)
.then(function () { return blindAdvancePastLive(attempt + 1); });
});
}
+function blindLiveAtEnd() {
+ try {
+ var loc = rendition.currentLocation();
+ return !!(loc && loc.atEnd);
+ } catch (e) {
+ return false;
+ }
+}
+
+// Returns whether the blind started. It can't before the book is displayed,
+// and Flutter must not flag auto scroll on for a blind that never appeared.
function autoScrollStart(speed) {
- if (!rendition || blindRendition) return;
+ if (!rendition || blindRendition) return false;
if (typeof speed === "number" && speed > 0) blindSpeed = speed;
var host = document.getElementById("viewerNext");
- if (!host) return;
+ if (!host) return false;
host.style.display = "block";
blindMatchViewerBox();
if (lastTheme.bg && lastTheme.bg !== "null") host.style.background = lastTheme.bg;
@@ -2610,15 +2717,19 @@ function autoScrollStart(speed) {
blindThemeApply(blindRendition);
var loc = rendition.currentLocation();
var cfi = loc && loc.start ? loc.start.cfi : null;
+ blindLog("start live " + blindLocSummary(rendition) + " | " + blindLayoutSummary(rendition) +
+ " | " + blindImageSummary(rendition) + " | display=" + cfi);
blindRendition.on("rendered", function () { blindThemeApply(blindRendition); });
Promise.resolve(cfi ? blindRendition.display(cfi) : blindRendition.display())
.then(function () { return blindAdvancePastLive(0); })
.then(function () {
+ if (!blindRendition) return;
blindThemeApply(blindRendition);
blindLastTs = 0;
blindRaf = requestAnimationFrame(blindTick);
})
- .catch(function () { autoScrollStop(); });
+ .catch(function () { autoScrollStop("error"); });
+ return true;
}
function blindTick(ts) {
@@ -2648,12 +2759,15 @@ function blindTick(ts) {
function blindSwap() {
blindSwapping = true;
try { clearSelection(); } catch (e) {}
+ blindLog("swap live before " + blindLocSummary(rendition));
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 () {
+ blindLog("swap live after " + blindLocSummary(rendition) + " | " + blindLayoutSummary(rendition) +
+ " | " + blindImageSummary(rendition));
blindY = 0;
blindApply();
return blindAdvancePastLive(0);
@@ -2662,7 +2776,7 @@ function blindSwap() {
blindThemeApply(blindRendition);
blindSwapping = false;
})
- .catch(function () { autoScrollStop(); });
+ .catch(function () { autoScrollStop("error"); });
}
window.addEventListener("resize", function () {
@@ -2691,13 +2805,15 @@ function autoScrollResync() {
blindApply();
var loc = rendition.currentLocation();
var cfi = loc && loc.start ? loc.start.cfi : null;
+ blindLog("resync display=" + cfi + " live " + blindLocSummary(rendition));
Promise.resolve(cfi ? blindRendition.display(cfi) : blindRendition.display())
.then(function () { return blindAdvancePastLive(0); })
.then(function () { blindSwapping = false; })
- .catch(function () { autoScrollStop(); });
+ .catch(function () { autoScrollStop("error"); });
}
-function autoScrollStop() {
+function autoScrollStop(reason) {
+ var wasRunning = blindRendition !== null;
blindTouchHold = false;
if (blindRaf) cancelAnimationFrame(blindRaf);
blindRaf = null;
@@ -2720,6 +2836,11 @@ function autoScrollStop() {
window.__absorbBlindRendition = null;
if (host) host.innerHTML = "";
blindTouchDetach();
+ // Stops the blind decided on itself (last page, a page that failed to
+ // load) have to reach Flutter, or the reader keeps swallowing taps and
+ // holding the screen on for a scroll that is no longer running.
+ if (wasRunning) blindLog("stop reason=" + (reason || "user"));
+ if (wasRunning && reason) blindNotify("absorbAutoScrollEnded", reason);
}
function autoScrollActive() {
diff --git a/packages/flutter_epub_viewer/lib/src/epub_controller.dart b/packages/flutter_epub_viewer/lib/src/epub_controller.dart
index bf5d98b4..a69f19ce 100644
--- a/packages/flutter_epub_viewer/lib/src/epub_controller.dart
+++ b/packages/flutter_epub_viewer/lib/src/epub_controller.dart
@@ -165,9 +165,11 @@ 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)');
+ /// never moves. Returns whether the blind actually started - it can't
+ /// before the book is displayed.
+ Future<bool> autoScrollStart({double speed = 40}) async {
+ final r = await webViewController?.evaluateJavascript(source: 'autoScrollStart($speed)');
+ return r == true || r == 1 || r == 'true';
}
/// Change the blind's descent speed while it is running.