Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 65 additions & 0 deletions lib/data/data_providers/book_text_reader.dart
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,18 @@ class BookTextReader {
);

/// כמו [text], כבייטים גולמיים (UTF-8 כפי שמאוחסן) — מסלול האינדוקס.
/// The book's lines, one per row (see [readBookContentLines]).
static Future<List<String>?> lines(
SeforimRepository repository,
db_models.Book book,
) => _load(
repository,
book,
workerMethod: 'bookLines',
fromWorker: (result) => (result as List?)?.cast<String>(),
read: readBookContentLines,
);

static Future<BookContentBytes?> bytes(
SeforimRepository repository,
db_models.Book book,
Expand Down Expand Up @@ -291,3 +303,56 @@ Future<String?> readBookContentText(
);
return read == null ? null : utf8.decode(_concat(read.chunks));
}

/// Reads a book as its list of lines: one entry per row, in line order.
///
/// Gives the same lines as splitting [readBookContentText] on '\n' (a row
/// that itself holds '\n' becomes several lines, as the split would make it),
/// without building and re-splitting one joined string.
Future<List<String>?> readBookContentLines(
sqlite3.Database db,
BookTextKey book, {
ReadCheckpoint? checkpoint,
}) async {
final codec = LineContentCodec.of(db);
final lines = <String>[];
final encoding = db.select('PRAGMA encoding').first.values.first;
if (encoding != 'UTF-8') {
final rows = db.select(_contentSql(db, blob: false), [book.id, book.title]);
if (rows.isEmpty) return null;
for (final row in rows) {
_addRowLines(lines, codec.text(row.values.first) ?? '');
}
return lines;
}
final statement = db.prepare(_contentSql(db, blob: true));
try {
final raw = statement.raw
..bindInt64(1, book.id)
..bindText(2, book.title);
var rows = 0;
while (raw.step()) {
final bytes = raw.columnInt64(1) != 0
? codec.bytes(raw.columnBlob(0))
: raw.columnBlob(0);
// utf8.decode drops one leading BOM, as the joined read drops it
// from every row.
_addRowLines(lines, utf8.decode(bytes));
rows++;
if (checkpoint != null && rows % _rowsPerCheckpoint == 0) {
await checkpoint();
}
}
return rows == 0 ? null : lines;
} finally {
statement.close();
}
}

void _addRowLines(List<String> lines, String row) {
if (row.contains('\n')) {
lines.addAll(row.split('\n'));
} else {
lines.add(row);
}
}
52 changes: 37 additions & 15 deletions lib/data/data_providers/database_library_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1956,7 +1956,8 @@ Future<List<Map<String, dynamic>>> _runSelectableVersionKeysInIsolate({
}

/// Library provider that loads books from the SQLite database.
class DatabaseLibraryProvider implements LibraryProvider, LinkLinesProvider {
class DatabaseLibraryProvider
implements LibraryProvider, LinkLinesProvider, BookLinesProvider {
final SqliteDataProvider _sqliteProvider = SqliteDataProvider.instance;
final _cachedKeys = BookKeySet();
final Map<int, String> _categoryIdToPath = {};
Expand Down Expand Up @@ -3187,6 +3188,25 @@ class DatabaseLibraryProvider implements LibraryProvider, LinkLinesProvider {
int categoryId,
String fileType, {
BookSource preferSource = BookSource.official,
}) async {
final lines = await getBookLines(
title,
categoryId,
fileType,
preferSource: preferSource,
);
return lines?.join('\n');
}

static Future<List<String>?> _fileLines(String? text) async =>
text == null ? null : splitBookText(text);

@override
Future<List<String>?> getBookLines(
String title,
int categoryId,
String fileType, {
BookSource preferSource = BookSource.official,
}) async {
final source = _resolveSource(
title: title,
Expand All @@ -3195,7 +3215,7 @@ class DatabaseLibraryProvider implements LibraryProvider, LinkLinesProvider {
preferSource: preferSource,
);
if (source is AttachedBookSource) {
return _readAttachedBookText(title, categoryId, source);
return _readAttachedBookLines(title, categoryId, source);
}
// ספרים מתיקיות מותאמות אישית: לקרוא מ-user_books.db (תוכן מהקובץ
// עצמו אם isFileBacked, אחרת משורות ה-line).
Expand All @@ -3213,11 +3233,13 @@ class DatabaseLibraryProvider implements LibraryProvider, LinkLinesProvider {
if (await file.exists()) {
// PDF מוחזר null — הקוראים שלו עוברים בצנרת נפרדת. פורמט בינארי
// (ZIP/OLE) לעולם אינו נקרא כטקסט אלא מומר.
return await readFileBackedBookText(file, book.fileType, title);
return await _fileLines(
await readFileBackedBookText(file, book.fileType, title),
);
}
}
// נופל לטעינה מתוך ה-DB עצמו (טבלת `line`).
return await _readBookTextFromUserBooksDb(
return await _readBookLinesFromUserBooksDb(
repo,
book.id,
book.totalLines,
Expand All @@ -3236,12 +3258,14 @@ class DatabaseLibraryProvider implements LibraryProvider, LinkLinesProvider {
if (book != null && book.isFileBacked && book.filePath != null) {
final file = File(book.filePath!);
if (await file.exists()) {
return await readFileBackedBookText(file, book.fileType, title);
return await _fileLines(
await readFileBackedBookText(file, book.fileType, title),
);
}
}
// If not external or file not found, try DB text
if (book != null) {
return await _sqliteProvider.getBookTextFromDb(
return await _sqliteProvider.getBookLinesFromDb(
title,
categoryId,
fileType,
Expand All @@ -3259,7 +3283,7 @@ class DatabaseLibraryProvider implements LibraryProvider, LinkLinesProvider {

/// ספר ממסד מצורף נקרא תמיד משורות ה-`line` שלו — נתיב קובץ שבמסד אינו
/// נפתח (מסד שאינו בשליטת התוכנה).
Future<String?> _readAttachedBookText(
Future<List<String>?> _readAttachedBookLines(
String title,
int categoryId,
AttachedBookSource source,
Expand All @@ -3271,15 +3295,13 @@ class DatabaseLibraryProvider implements LibraryProvider, LinkLinesProvider {
preferSource: source,
);
if (record == null || record.source != source) return null;
final text = await BookTextReader.text(record.repository, record.book);
if (text != null) return text;
final lines = await BookTextReader.lines(record.repository, record.book);
if (lines != null) return lines;
// ספר מבוסס-קובץ: filePath כבר נפתר בתוך תיקיית המסד (או null).
final file = record.book.filePath;
if (file == null || !await File(file).exists()) return null;
return await readFileBackedBookText(
File(file),
record.book.fileType,
title,
return await _fileLines(
await readFileBackedBookText(File(file), record.book.fileType, title),
);
} catch (e) {
debugPrint('⚠️ Error reading attached book text: $e');
Expand Down Expand Up @@ -3310,7 +3332,7 @@ class DatabaseLibraryProvider implements LibraryProvider, LinkLinesProvider {
}

/// קורא את תוכן הספר משורות ה-`line` של `user_books.db` ומחזיר טקסט מאוחד.
Future<String?> _readBookTextFromUserBooksDb(
Future<List<String>?> _readBookLinesFromUserBooksDb(
SeforimRepository repo,
int bookId,
int totalLines,
Expand All @@ -3319,7 +3341,7 @@ class DatabaseLibraryProvider implements LibraryProvider, LinkLinesProvider {
if (totalLines <= 0) return null;
final lines = await repo.getLines(bookId, 0, totalLines - 1);
if (lines.isEmpty) return null;
return lines.map((l) => l.content).join('\n');
return rowsToBookLines(lines.map((l) => l.content));
} catch (e) {
debugPrint('⚠️ Error loading user_books lines for book $bookId: $e');
return null;
Expand Down
12 changes: 11 additions & 1 deletion lib/data/data_providers/db_read_worker.dart
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,10 @@ class DbReadWorker {
if (_suspendedForExternalWrite || _closedUntilReopen) {
throw const DbReadWorkerSuspended();
}
final slot = method == 'bookText' || method == 'bookTextBytes'
final slot =
method == 'bookText' ||
method == 'bookLines' ||
method == 'bookTextBytes'
? _books
: _ranges;
if (slot.stalled) throw const DbReadWorkerUnavailable('stalled');
Expand Down Expand Up @@ -1495,6 +1498,13 @@ void _workerMain(_Bootstrap bootstrap) {
_bookTextKey(args),
checkpoint: bookReadCheckpoint,
);
case 'bookLines':
final repo = await ensureRepo(args['dbPath'] as String);
return readBookContentLines(
await repo.database.database,
_bookTextKey(args),
checkpoint: bookReadCheckpoint,
);
case 'bookTextBytes':
final repo = await ensureRepo(args['dbPath'] as String);
return readBookContentTransferable(
Expand Down
20 changes: 19 additions & 1 deletion lib/data/data_providers/file_system_library_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ typedef _BookFileScan = ({
});

/// Library provider that loads books from the file system.
class FileSystemLibraryProvider implements LibraryProvider, LinkLinesProvider {
class FileSystemLibraryProvider
implements LibraryProvider, LinkLinesProvider, BookLinesProvider {
late String _libraryPath;
Map<String, String>? _keyToPath;
Map<String, String>? _catalogKeyToPath;
Expand Down Expand Up @@ -357,6 +358,23 @@ class FileSystemLibraryProvider implements LibraryProvider, LinkLinesProvider {
return readFileBackedBookText(file, fileType, title);
}

/// A text file is split into its lines once, when read.
@override
Future<List<String>?> getBookLines(
String title,
int categoryId,
String fileType, {
BookSource preferSource = BookSource.official,
}) async {
final text = await getBookText(
title,
categoryId,
fileType,
preferSource: preferSource,
);
return text == null ? null : splitBookText(text);
}

@override
Future<List<TocEntry>?> getBookToc(
String title,
Expand Down
45 changes: 45 additions & 0 deletions lib/data/data_providers/library_provider.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:isolate';

import 'package:otzaria/models/book_source.dart';
import 'package:otzaria/models/books.dart';
import 'package:otzaria/models/links.dart';
Expand Down Expand Up @@ -85,3 +87,46 @@ abstract class LibraryProvider {
abstract interface class LinkLinesProvider {
Future<List<LinkContentLine>> getLinkContentLines(Link link);
}

/// A provider that reads a book straight into its lines.
///
/// One format for every source: a database book hands its rows over as lines,
/// a text file is split once when read. The viewer and every consumer take
/// the list; a joined string is built only where one is genuinely needed.
abstract interface class BookLinesProvider {
/// The book's lines, or null when this provider has no text for it.
/// Equals splitting [LibraryProvider.getBookText] on '\n'.
Future<List<String>?> getBookLines(
String title,
int categoryId,
String fileType, {
BookSource preferSource = BookSource.official,
});
}

/// Splits a whole book text into its lines once (off the UI isolate).
/// An empty text has no lines.
Future<List<String>> splitBookText(String content) async {
if (content.isEmpty) return const [];
return Isolate.run(() => content.split('\n'));
}

/// Whether [lines] hold any text (the lines of an empty string do not).
bool bookLinesHaveText(List<String>? lines) =>
lines != null &&
lines.isNotEmpty &&
(lines.length > 1 || lines.first.isNotEmpty);

/// The lines of a book stored as rows: one line per row; a row that holds
/// '\n' gives several lines, as splitting the joined rows would.
List<String> rowsToBookLines(Iterable<String> rows) {
final lines = <String>[];
for (final row in rows) {
if (row.contains('\n')) {
lines.addAll(row.split('\n'));
} else {
lines.add(row);
}
}
return lines;
}
Loading
Loading