Skip to content
Merged
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
10 changes: 6 additions & 4 deletions lib/indexing/repository/indexing_repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1642,9 +1642,7 @@ class IndexingRepository {
extraFacets: _bookExtraFacets(book),
sourceHash: _dbSourceHash(book, sourceHashes),
// טביעת הטקסט הריק: כך ספר שנשאר ריק נמצא תואם בבדיקה הבאה.
textHash: book is PdfBook
? null
: await contentFingerprint(text: const []),
textHash: await contentFingerprint(text: const []),
),
],
);
Expand Down Expand Up @@ -3014,7 +3012,11 @@ class StampChangeDetector implements IndexChangeDetector {
topics: _repository._bookTopics(book),
extraFacets: _repository._bookExtraFacets(book),
);
if (stamp.metadataHash == BigInt.zero || stamp.metadataHash != metadata) {
// חותם אפס מזהה PDF שאונדקס בשורות וצריך להיכתב מחדש בעמודים.
if (book is PdfBook && stamp.textHash == BigInt.zero) {
changed.add(book);
} else if (stamp.metadataHash == BigInt.zero ||
stamp.metadataHash != metadata) {
changed.add(book);
final sourceHash = IndexingRepository._dbSourceHash(book, sourceHashes);
if (sourceHash == null ||
Expand Down
4 changes: 2 additions & 2 deletions lib/pdf_book/utils/pdf_user_regex_pattern.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ class PdfUserRegexPattern implements RegExp {

final UserRegexMatcher _matcher;

/// An edge `^`/`$` (`\A`/`\z` in the engine's pattern) means a text line, as
/// in the index where each PDF line is a document: such a pattern runs per line.
/// An edge `^`/`$` (`\A`/`\z` in the engine's pattern) belongs to a layout
/// line, even when the index stores the whole page as one document.
final bool _lineAnchored;

/// The query as typed, which also tells pdfrx whether a search repeats.
Expand Down
37 changes: 37 additions & 0 deletions lib/pdf_book/utils/pdf_word_highlight_pattern.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import 'package:otzaria/pdf_book/utils/proximity_highlight_pattern.dart';
import 'package:otzaria_search_engine/otzaria_search_engine.dart';

class PdfWordHighlightPattern implements Pattern {
const PdfWordHighlightPattern(
this.matcher,
this.boundaries,
this.wordMatchMode,
this.wordMatchCount,
);

final HighlightMatcher matcher;
final List<bool> boundaries;
final WordMatchMode wordMatchMode;
final int wordMatchCount;

@override
Iterable<Match> allMatches(String string, [int start = 0]) sync* {
RangeError.checkValueInInterval(start, 0, string.length, 'start');
for (final match in matcher.findPdfWordMatches(
data: string,
requireTokenBoundaries: boundaries,
wordMatchMode: wordMatchMode,
wordMatchCount: wordMatchCount,
)) {
if (match.start >= start) {
yield PdfSpanMatch(this, string, match.start, match.end);
}
}
}

@override
Match? matchAsPrefix(String string, [int start = 0]) {
final match = allMatches(string, start).firstOrNull;
return match?.start == start ? match : null;
}
}
3 changes: 1 addition & 2 deletions lib/pdf_book/utils/result_lines_highlight_pattern.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ import 'dart:convert';

import 'package:otzaria/pdf_book/utils/proximity_highlight_pattern.dart';

/// המונחים שהמנוע סימן, רק בשורות העמוד שמכילות את כל המונחים של קטע תוצאה
/// אחד: כל שורת PDF היא מסמך באינדקס, וכשההתאמה אינה רצף היא השורה כולה.
/// הדגשה מתקצירים של אינדקס לפי שורות, כשאין מתאם לעמוד שלם.
class ResultLinesHighlightPattern implements Pattern {
ResultLinesHighlightPattern._(this._terms, this._termSets, this.key);

Expand Down
88 changes: 81 additions & 7 deletions lib/pdf_book/view/pdf_search_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,15 @@ import 'package:otzaria/search/book_facet.dart';
import 'package:otzaria/search/in_book_search_preferences.dart';
import 'package:otzaria/search/view/whole_word_search_action.dart';
import 'package:otzaria/search/models/search_configuration.dart';
import 'package:otzaria/search/search_query_builder.dart';
import 'package:otzaria/search/search_repository.dart';
import 'package:otzaria/search/utils/literal_search_pattern.dart';
import 'package:otzaria/search/utils/user_regex_query.dart';
import 'package:otzaria/pdf_book/utils/centered_text_search_session.dart';
import 'package:otzaria/pdf_book/utils/pdf_engine_result_ordinals.dart';
import 'package:otzaria/pdf_book/utils/pdf_search_result_list.dart';
import 'package:otzaria/pdf_book/utils/pdf_user_regex_pattern.dart';
import 'package:otzaria/pdf_book/utils/pdf_word_highlight_pattern.dart';
import 'package:otzaria/pdf_book/utils/proximity_highlight_pattern.dart';
import 'package:otzaria/pdf_book/utils/result_lines_highlight_pattern.dart';
import 'package:otzaria/search/utils/snippet_builder.dart';
Expand Down Expand Up @@ -231,14 +233,25 @@ class PdfBookSearchView extends StatefulWidget {
/// תקרת מונחים ייחודיים לתבנית ההדגשה, כדי שהרגקס לא יתנפח.
static const int _maxHighlightTerms = 50;

/// תבנית הדגשה לעמודים: המתאם של הקורא הטקסטואלי כשהוא מוצא את [resultHtmls],
/// ואחרת המונחים שהמנוע סימן, בשורות שהוא התאים. null כשאין מה להדגיש.
/// תבנית הדגשה מהמתאם לעמוד, מהתאמת המרווח או מהסימונים ב-[resultHtmls].
@visibleForTesting
static Pattern? buildAdvancedHighlightPattern(
Iterable<String> resultHtmls, {
String query = '',
InBookSearchSettings settings = const InBookSearchSettings(),
HighlightPattern? indexPattern,
}) {
if (indexPattern?.matcher case final matcher?) {
final policy = settings.matchPolicy;
return PdfWordHighlightPattern(
matcher,
indexPattern!.wordBoundaryEligible,
settings.searchMode == SearchMode.fuzzy
? WordMatchMode.all
: policy.wordMatchMode,
policy.wordMatchCount,
);
}
final proximity = _proximityPattern(resultHtmls, query, settings);
if (proximity != null) return proximity;

Expand Down Expand Up @@ -286,7 +299,7 @@ class PdfBookSearchView extends StatefulWidget {
String query,
InBookSearchSettings settings,
) {
// במקורב, בטווח פסקה/כותרת וב"לפחות N מילים" המנוע מתאים שורה ולא רצף.
// במקורב, בטווח פסקה/כותרת וב"לפחות N מילים" אין דרישה לרצף.
if (query.isEmpty || settings.searchMode == SearchMode.fuzzy) return null;
final policy = settings.matchPolicy;
if (policy.proximityScope != SearchScope.wordDistance ||
Expand Down Expand Up @@ -397,7 +410,7 @@ class PdfBookSearchViewState extends State<PdfBookSearchView>
int get _searchDistance => _settings.distance;
SearchMatchPolicy get _matchPolicy => _settings.matchPolicy;

String _lastPdfHighlightSource = '';
Object _lastPdfHighlightSource = '';
int _searchGeneration = 0;
late final _engineSearch = InBookEngineSearchCancellation(
widget.searchRepository,
Expand Down Expand Up @@ -475,6 +488,7 @@ class PdfBookSearchViewState extends State<PdfBookSearchView>
RegExp regExp => regExp.pattern,
ProximityHighlightPattern proximity => proximity.key,
ResultLinesHighlightPattern lines => lines.key,
PdfWordHighlightPattern words => words,
_ => '',
};
final searcher = widget.textSearcher;
Expand Down Expand Up @@ -715,16 +729,67 @@ class PdfBookSearchViewState extends State<PdfBookSearchView>
}

/// מדגיש על העמוד את מה שהמנוע מצא בפועל (כולל fuzzy/מילים חלופיות).
void _updateAdvancedHighlight(List<SearchResult> results, String query) {
void _updateAdvancedHighlight(
List<SearchResult> results,
String query, {
HighlightPattern? indexPattern,
}) {
final pattern = PdfBookSearchView.buildAdvancedHighlightPattern(
results.map((r) => r.text),
query: query,
settings: _settings,
indexPattern: indexPattern,
);
_lastAdvancedHighlightPattern = pattern;
_schedulePdfHighlight(pattern);
}

static final _phraseQuotes = RegExp(r'(?<![א-ת])["״“”„]|["״“”„](?![א-ת])');

static bool _hasQuotedFuzzyPhrase(String query) {
final segments = query.split(_phraseQuotes);
for (var i = 1; i + 1 < segments.length; i += 2) {
if (SearchQueryBuilder.hasMultipleWords(segments[i])) return true;
}
return false;
}

Future<HighlightPattern?> _preparePageWordHighlights(
String query,
int requestId,
) async {
final policy = _settings.matchPolicy;
final needsWordMatcher = switch (_settings.searchMode) {
SearchMode.exact => false,
SearchMode.fuzzy =>
policy.querySemantics == SearchQuerySemantics.regular &&
!_hasQuotedFuzzyPhrase(query),
SearchMode.advanced =>
policy.proximityScope != SearchScope.wordDistance ||
policy.wordMatchMode != WordMatchMode.all,
};
final options = _settings.searchOptions;
if (!needsWordMatcher ||
SearchQueryBuilder.optionsRequestVocalized(options) ||
options.values.any((word) => word['תרגום ארמי'] == true)) {
return null;
}
try {
return await widget.searchRepository.preparePdfWordHighlightPattern(
inBookSearchRequest(
query: query,
bookPath: _bookPath!,
settings: _settings,
cancelRequestId: requestId,
),
indexedFilePath: _indexedFilePath,
);
} catch (error) {
debugPrint('[PdfSearch] page word highlights unavailable: $error');
return null;
}
}

@override
void initState() {
super.initState();
Expand Down Expand Up @@ -1304,13 +1369,14 @@ class PdfBookSearchViewState extends State<PdfBookSearchView>
}

try {
final requestId = _engineSearch.next();
final rawResults = await searchBookWithEngine(
widget.searchRepository,
query: query,
bookPath: _bookPath!,
limit: kInBookEngineFetchLimit,
settings: _settings,
cancelRequestId: _engineSearch.next(),
cancelRequestId: requestId,
);

final indexedFilePath = _indexedFilePath;
Expand Down Expand Up @@ -1347,7 +1413,11 @@ class PdfBookSearchViewState extends State<PdfBookSearchView>
);
}
});
_updateAdvancedHighlight(results, query);
final indexPattern = results.isEmpty
? null
: await _preparePageWordHighlights(query, requestId);
if (!mounted || generation != _searchGeneration) return;
_updateAdvancedHighlight(results, query, indexPattern: indexPattern);
_centerOpenTargetMatch();
_scheduleScrollToCurrentPage();
} catch (e, st) {
Expand Down Expand Up @@ -1540,6 +1610,10 @@ class PdfBookSearchViewState extends State<PdfBookSearchView>
final result = await showInBookAdvancedSearchDialog(
context,
bookTitle: widget.bookTitle,
book: switch (pdfBookBloc.state) {
PdfBookLoaded(:final book) => book,
_ => null,
},
query: widget.searchController.text,
settings: _settings,
);
Expand Down
48 changes: 32 additions & 16 deletions lib/search/in_book_search_settings.dart
Original file line number Diff line number Diff line change
Expand Up @@ -215,30 +215,46 @@ Future<List<SearchResult>> searchBookWithEngine(
),
);
}
final parameters = settings.activeParameters;
final policy = settings.requestedMatchPolicy.forQuery(query);
return repository.searchTexts(
SearchEngineRequest(
inBookSearchRequest(
query: query,
facets: [bookPath],
bookPath: bookPath,
limit: limit,
searchOptions: parameters.searchOptions,
alternativeWords: parameters.alternativeWords,
customSpacing: parameters.customSpacing,
distance: settings.distance,
negativeDistance: settings.distance,
searchMode: settings.searchMode,
scope: policy.proximityScope,
negativeScope: policy.proximityScope,
wordMatchMode: policy.wordMatchMode,
wordMatchCount: policy.wordMatchCount,
anyOrder: policy.anyOrder,
order: ResultsOrder.catalogue,
settings: settings,
cancelRequestId: cancelRequestId,
),
);
}

SearchEngineRequest inBookSearchRequest({
required String query,
required String bookPath,
int limit = 0,
required InBookSearchSettings settings,
int? cancelRequestId,
}) {
final parameters = settings.activeParameters;
final policy = settings.requestedMatchPolicy.forQuery(query);
return SearchEngineRequest(
query: query,
facets: [bookPath],
limit: limit,
searchOptions: parameters.searchOptions,
alternativeWords: parameters.alternativeWords,
customSpacing: parameters.customSpacing,
distance: settings.distance,
negativeDistance: settings.distance,
searchMode: settings.searchMode,
scope: policy.proximityScope,
negativeScope: policy.proximityScope,
wordMatchMode: policy.wordMatchMode,
wordMatchCount: policy.wordMatchCount,
anyOrder: policy.anyOrder,
order: ResultsOrder.catalogue,
cancelRequestId: cancelRequestId,
);
}

/// מזהה הביטול של חיפוש המנוע האחרון בחלונית חיפוש בתוך ספר.
/// חיפוש חדש או סגירת החלונית עוצרים במנוע את הקודם, שאחרת ממשיך לרוץ ברקע.
class InBookEngineSearchCancellation {
Expand Down
53 changes: 38 additions & 15 deletions lib/search/search_engine_gateway.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1118,6 +1118,43 @@ class RustSearchEngineOperations
void primeSmartHighlightPattern(SearchEngineRequest request) =>
_primeHighlightPattern(request, SearchQuerySemantics.smart);

Future<HighlightPattern?> preparePdfWordHighlightPattern(
SearchEngineRequest request, {
required String indexedFilePath,
}) async {
final indexed = indexHighlightRequest(request);
if (indexed == null ||
await _engine.getBookTextFingerprint(filePath: indexedFilePath) ==
BigInt.zero) {
return null;
}
return _generateIndexHighlightPattern(
indexed,
cancelRequestId: indexed.cancelRequestId,
);
}

Future<HighlightPattern?> _generateIndexHighlightPattern(
SearchEngineRequest request, {
int? cancelRequestId,
}) => switch (request.searchMode) {
SearchMode.advanced => _engine.generateIndexHighlightPattern(
query: request.query,
distance: request.distance < 0 ? 0 : request.distance,
customSpacing: request.customSpacing,
alternativeWords: request.alternativeWords,
searchOptions: request.searchOptions,
anyOrder: request.anyOrder,
cancelRequestId: cancelRequestId,
),
SearchMode.fuzzy => _engine.generateIndexFuzzyHighlightPattern(
query: request.query,
maxDistance: _fuzzyDistance(request.distance),
cancelRequestId: cancelRequestId,
),
SearchMode.exact => Future.value(null),
};

void _primeHighlightPattern(
SearchEngineRequest request,
SearchQuerySemantics semantics,
Expand Down Expand Up @@ -1146,21 +1183,7 @@ class RustSearchEngineOperations
: SemanticLexicalMode.fuzzy,
maxDistance: _fuzzyDistance(request.distance),
)
: switch (request.searchMode) {
SearchMode.advanced => _engine.generateIndexHighlightPattern(
query: request.query,
distance: request.distance < 0 ? 0 : request.distance,
customSpacing: request.customSpacing,
alternativeWords: request.alternativeWords,
searchOptions: request.searchOptions,
anyOrder: request.anyOrder,
),
SearchMode.fuzzy => _engine.generateIndexFuzzyHighlightPattern(
query: request.query,
maxDistance: _fuzzyDistance(request.distance),
),
SearchMode.exact => Future.value(null),
},
: _generateIndexHighlightPattern(request),
),
);
}
Expand Down
Loading
Loading