Skip to content

A cross platform Audiobookshelf client for Android and iOS

Dart

Stop ebooks from sometimes opening to a blank page

Barnabas8b2366aa79a2
diff --git a/lib/services/ebook_cache.dart b/lib/services/ebook_cache.dart
index 9e179963..55741ce3 100644
--- a/lib/services/ebook_cache.dart
+++ b/lib/services/ebook_cache.dart
@@ -1,4 +1,5 @@
import 'dart:io';
+import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:path_provider/path_provider.dart';
import 'api_service.dart';
@@ -43,7 +44,10 @@ Future<File> fetchEbookToCache(
String title,
) async {
final cachedFile = await ebookCacheFileFor(itemId, ebookFile);
- if (cachedFile.existsSync() && await cachedFile.length() > 0) return cachedFile;
+ if (cachedFile.existsSync() && await cachedFile.length() > 0) {
+ debugPrint('[EbookCache] cache hit item=$itemId bytes=${await cachedFile.length()}');
+ return cachedFile;
+ }
final ino = ebookFile['ino'] as String?;
if (ino == null) throw Exception('No ebook file found');
@@ -53,6 +57,8 @@ Future<File> fetchEbookToCache(
: api.baseUrl;
final url = '$cleanBase/api/items/$itemId/file/$ino';
+ debugPrint('[EbookCache] downloading item=$itemId url=$url');
+ final startedAt = DateTime.now();
final partFile = File('${cachedFile.path}.part');
final request = http.Request('GET', Uri.parse(url));
request.followRedirects = false;
@@ -84,6 +90,8 @@ Future<File> fetchEbookToCache(
}
if (cachedFile.existsSync()) await cachedFile.delete();
await partFile.rename(cachedFile.path);
+ final secs = DateTime.now().difference(startedAt).inMilliseconds / 1000.0;
+ debugPrint('[EbookCache] downloaded item=$itemId bytes=${await cachedFile.length()} in ${secs}s');
} finally {
client.close();
if (partFile.existsSync()) {
diff --git a/lib/widgets/ebook_reader_view.dart b/lib/widgets/ebook_reader_view.dart
index 6d303ea9..305fb3aa 100644
--- a/lib/widgets/ebook_reader_view.dart
+++ b/lib/widgets/ebook_reader_view.dart
@@ -92,6 +92,11 @@ class EbookReaderViewState extends State<EbookReaderView> {
// Key to force-rebuild EpubViewer when layout mode changes
int _viewerKey = 0;
+ // onEpubLoaded is wired to epub.js's "displayed" event, which re-fires on
+ // every display() - so the load-time rescue re-display must run at most once
+ // per mount, or it re-triggers itself into an endless display->displayed loop
+ // that freezes page-turn taps. Reset whenever the viewer remounts.
+ bool _didLoadRescue = false;
// Reader settings
int _fontSize = 16;
@@ -302,6 +307,7 @@ class EbookReaderViewState extends State<EbookReaderView> {
_spread = mode;
_locationsReady = false;
_viewerKey++; // force the viewer to remount with the new spread
+ _didLoadRescue = false; // let the remounted viewer rescue its first paint
});
await ScopedPrefs.setInt(_kSpread, index);
}
@@ -405,8 +411,14 @@ class EbookReaderViewState extends State<EbookReaderView> {
/// page. Debounced so the touch and injected-click paths can't double-fire.
void _readerTapAt(double frac, String source) {
final now = DateTime.now();
- if (now.difference(_lastReaderTap).inMilliseconds < 350) return;
+ final sinceMs = now.difference(_lastReaderTap).inMilliseconds;
+ if (sinceMs < 350) {
+ debugPrint('[ReaderTap] DEBOUNCED frac=${frac.toStringAsFixed(2)} src=$source since=${sinceMs}ms');
+ return;
+ }
_lastReaderTap = now;
+ final action = frac < 0.25 ? 'prev' : (frac > 0.75 ? 'next' : 'menu');
+ debugPrint('[ReaderTap] frac=${frac.toStringAsFixed(2)} src=$source -> $action ctrl=${_epubController != null}');
if (frac < 0.25) {
_epubController?.prev();
} else if (frac > 0.75) {
@@ -505,7 +517,12 @@ class EbookReaderViewState extends State<EbookReaderView> {
}
// Shared persistent cache - reuses a downloaded/previously-opened copy so
// the book reads offline.
+ final playing = AudioPlayerService().isPlaying;
+ debugPrint('[EbookReader] open item=${widget.itemId} ext=${ebookExtFromFile(widget.ebookFile)} '
+ 'cached=${await isEbookCached(widget.itemId, widget.ebookFile)} playing=$playing');
final file = await fetchEbookToCache(api, widget.itemId, widget.ebookFile, widget.title);
+ final len = file.existsSync() ? await file.length() : 0;
+ debugPrint('[EbookReader] file ready item=${widget.itemId} bytes=$len path=${file.path}');
if (mounted) {
setState(() { _cachedFile = file; _loading = false; });
}
@@ -1644,11 +1661,13 @@ class EbookReaderViewState extends State<EbookReaderView> {
theme: _buildTheme(palette),
),
onChaptersLoaded: (chapters) {
+ debugPrint('[EbookReader] onChaptersLoaded item=${widget.itemId} count=${chapters.length}');
if (mounted) setState(() => _chapters = _flattenChapters(chapters));
},
// Fires once the plugin finishes generating its location index;
// value.progress is only meaningful (and stable) after this.
onLocationLoaded: () {
+ debugPrint('[EbookReader] onLocationLoaded item=${widget.itemId}');
if (mounted) setState(() => _locationsReady = true);
},
suppressNativeContextMenu: true,
@@ -1663,15 +1682,27 @@ class EbookReaderViewState extends State<EbookReaderView> {
if (match != null) _addNoteToAnnotation(match);
},
onEpubLoaded: () {
- // Re-display the initial CFI once. The plugin already displays
- // it at load, but that first display can occasionally come up
- // blank; this second display is the rescue. Position-safe: font
- // size and theme are already in displaySettings, so nothing
- // reflows after this.
- final once = _initialCfi;
- if (once != null && once.isNotEmpty) {
- _initialCfi = null;
- _epubController?.display(cfi: once);
+ // Re-display once to rescue an occasionally-blank first paint.
+ // Guarded so it runs at most once per mount: onEpubLoaded fires
+ // on every epub.js "displayed" event, so an unguarded re-display
+ // would re-trigger itself forever (freezing taps and snapping
+ // back to the start). Position-safe: font size and theme are
+ // already in displaySettings, so nothing reflows after this.
+ if (!_didLoadRescue) {
+ _didLoadRescue = true;
+ final once = _initialCfi;
+ if (once != null && once.isNotEmpty) {
+ _initialCfi = null;
+ _epubController?.display(cfi: once);
+ } else {
+ // First open (no saved position) - the same blank-first-paint
+ // can happen here, but display(cfi:) needs a target, so force
+ // epub.js to re-display the start directly.
+ _epubController?.webViewController?.evaluateJavascript(
+ source: 'try{rendition.display();}catch(e){}');
+ }
+ debugPrint('[EbookReader] onEpubLoaded item=${widget.itemId} '
+ 'rescue=${once != null && once.isNotEmpty ? "cfi" : "start"}');
}
_loadAnnotations().then((_) => _restoreHighlights());
_setupPageInfoHandler();
diff --git a/lib/widgets/foliate_reader_view.dart b/lib/widgets/foliate_reader_view.dart
index 812b598e..99fd7bcd 100644
--- a/lib/widgets/foliate_reader_view.dart
+++ b/lib/widgets/foliate_reader_view.dart
@@ -7,6 +7,7 @@ import '../l10n/app_localizations.dart';
import '../providers/auth_provider.dart';
import '../providers/library_provider.dart';
import '../services/api_service.dart';
+import '../services/audio_player_service.dart';
import '../services/ebook_cache.dart';
import '../services/foliate_book_server.dart';
@@ -75,6 +76,9 @@ class _FoliateReaderViewState extends State<FoliateReaderView> {
// Progress sync throttling - matches the EPUB/PDF reader cadence.
DateTime _lastSync = DateTime.fromMillisecondsSinceEpoch(0);
String? _lastSyncedCfi;
+ bool _firstRelocate = true; // log only the first render position
+
+ void _log(String msg) => debugPrint('[Foliate] item=${widget.itemId} $msg');
@override
void initState() {
@@ -150,34 +154,50 @@ class _FoliateReaderViewState extends State<FoliateReaderView> {
setState(() { _error = 'Not connected to server'; _loading = false; });
return;
}
+ _log('prepare ext=$_ext playing=${AudioPlayerService().isPlaying}');
final file = await fetchEbookToCache(api, widget.itemId, widget.ebookFile, widget.title);
final ext = _ext.isEmpty ? '.epub' : _ext;
_bookUrlName = 'book$ext';
final port = await _server.start(bookFile: file, mime: _mimeFor(ext));
+ final len = file.existsSync() ? await file.length() : 0;
+ _log('server up port=$port bytes=$len mime=${_mimeFor(ext)}');
if (!mounted) return;
setState(() { _port = port; _loading = false; });
} catch (e) {
+ _log('prepare error $e');
if (mounted) setState(() { _error = '$e'; _loading = false; });
}
}
void _registerHandlers(InAppWebViewController c) {
c.addJavaScriptHandler(handlerName: 'onReady', callback: (args) {
+ _log('onReady');
_openBook();
return null;
});
c.addJavaScriptHandler(handlerName: 'onBookLoaded', callback: (args) {
final data = args.isNotEmpty ? args[0] as Map? : null;
final toc = (data?['toc'] as List?) ?? [];
+ _log('onBookLoaded toc=${toc.length}');
if (mounted) {
setState(() => _toc = toc.whereType<Map>().map(_TocItem.fromJson).toList());
}
+ // Rescue a blank first paint: re-apply the position after a tick so the
+ // renderer relays out (mirrors the EPUB reader's re-display rescue).
+ Future.delayed(const Duration(milliseconds: 120), () {
+ if (!mounted) return;
+ final cfi = _initialCfi;
+ _controller?.evaluateJavascript(source: (cfi != null && cfi.isNotEmpty)
+ ? 'window.AbsorbReader.goTo(${jsonEncode(cfi)});'
+ : 'window.AbsorbReader.goToFraction(0);');
+ });
return null;
});
c.addJavaScriptHandler(handlerName: 'onRelocate', callback: (args) {
final data = args.isNotEmpty ? args[0] as Map? : null;
if (data == null) return null;
final cfi = data['cfi'] as String?;
+ if (_firstRelocate) { _firstRelocate = false; _log('first onRelocate cfi=${cfi != null}'); }
final frac = (data['fraction'] as num?)?.toDouble();
final label = data['tocLabel'] as String?;
if (mounted) {
@@ -198,6 +218,7 @@ class _FoliateReaderViewState extends State<FoliateReaderView> {
});
c.addJavaScriptHandler(handlerName: 'onError', callback: (args) {
final msg = args.isNotEmpty ? '${args[0]}' : 'Unknown error';
+ _log('onError tocEmpty=${_toc.isEmpty} msg=$msg');
if (mounted && _toc.isEmpty) setState(() => _error = msg);
return null;
});
diff --git a/pubspec.yaml b/pubspec.yaml
index c4e35a88..f2a431cc 100644
--- a/pubspec.yaml
+++ b/pubspec.yaml
@@ -1,7 +1,7 @@
name: absorb
description: An Audiobookshelf Client
publish_to: 'none'
-version: 1.9.1+198
+version: 1.9.1+199
environment:
sdk: '>=3.10.0 <4.0.0'