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
167 changes: 159 additions & 8 deletions lib/pdf_book/utils/pdf_text_selection_actions.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:pdfrx/pdfrx.dart';

Expand All @@ -9,16 +11,34 @@ class PdfTextSelectionActions {
final PdfViewerController controller;
final bool Function() isActive;
int _generation = 0;
({String text, bool Function() selectionIsCurrent})? _snapshot;
StreamSubscription<PdfDocumentEvent>? _snapshotEvents;

String? get selectedTextSnapshot {
discardStaleSnapshot();
return _snapshot?.text;
}

void discardStaleSnapshot() {
if (_snapshot?.selectionIsCurrent() == false) releaseSelectedTextSnapshot();
}

void releaseSelectedTextSnapshot() {
_snapshot = null;
unawaited(_snapshotEvents?.cancel());
_snapshotEvents = null;
}

void cancel() => _generation++;

bool _isCurrent(
int generation,
PdfDocument document,
PdfTextSelectionRange? range,
) {
if (generation != _generation ||
!isActive() ||
) => generation == _generation && _matchesSelection(document, range);

bool _matchesSelection(PdfDocument document, PdfTextSelectionRange? range) {
if (!isActive() ||
!controller.isReady ||
!identical(controller.document, document)) {
return false;
Expand All @@ -30,6 +50,31 @@ class PdfTextSelectionActions {
current?.end == range?.end;
}

bool Function() _selectedTextGuard(
PdfDocument document,
PdfTextSelectionRange range,
) {
var checkedPages = document.pages;
final start = range.start.text.pageNumber - 1;
final end = range.end.text.pageNumber - 1;
return () {
if (!_matchesSelection(document, range)) return false;
final currentPages = document.pages;
if (start < 0 ||
end >= currentPages.length ||
end >= checkedPages.length) {
return false;
}
if (!identical(currentPages, checkedPages)) {
for (var i = start; i <= end; i++) {
if (!identical(currentPages[i], checkedPages[i])) return false;
}
checkedPages = currentPages;
}
return true;
};
}

Future<PdfTextActionResult> copy({bool keepSelection = false}) async {
final generation = ++_generation;
if (!isActive() || !controller.isReady) return PdfTextActionResult.none;
Expand All @@ -39,7 +84,11 @@ class PdfTextSelectionActions {
if (range == null || !selection.isCopyAllowed) {
return PdfTextActionResult.none;
}
bool isCurrent() => _isCurrent(generation, document, range);
final selectionIsCurrent = _selectedTextGuard(document, range);
bool isCurrent() =>
generation == _generation &&
selectionIsCurrent() &&
selection.isCopyAllowed;
try {
if (!isCurrent()) return PdfTextActionResult.none;
if (document.pages
Expand All @@ -48,15 +97,21 @@ class PdfTextSelectionActions {
.any((page) => !page.isLoaded)) {
return PdfTextActionResult.loading;
}
final text = await selection.getSelectedText();
if (!isCurrent() || !selection.isCopyAllowed || text.isEmpty) {
final text = await _readText(
document,
range,
isCurrent: isCurrent,
selectionIsCurrent: selectionIsCurrent,
);
if (!isCurrent() || text == null || text.isEmpty) {
return PdfTextActionResult.none;
}
// pdfrx's copy helper does not await the platform clipboard response.
await Clipboard.setData(ClipboardData(text: text));
if (!isCurrent()) return PdfTextActionResult.none;
if (!keepSelection) {
await selection.clearTextSelection();
discardStaleSnapshot();
if (!_isCurrent(generation, document, null)) {
return PdfTextActionResult.none;
}
Expand All @@ -69,6 +124,102 @@ class PdfTextSelectionActions {
}
}

/// קורא את הבחירה בלי להכניס גאומטריה של עמודי ביניים למטמון המשותף.
Future<String?> readSelectedText({bool requireCopyPermission = true}) async {
final generation = ++_generation;
if (!isActive() || !controller.isReady) return null;
final document = controller.document;
final selection = controller.textSelectionDelegate;
final range = selection.textSelectionPointRange;
if (range == null || (requireCopyPermission && !selection.isCopyAllowed)) {
return null;
}
final selectionIsCurrent = _selectedTextGuard(document, range);
bool isCurrent() =>
generation == _generation &&
selectionIsCurrent() &&
(!requireCopyPermission || selection.isCopyAllowed);
try {
final text = await _readText(
document,
range,
isCurrent: isCurrent,
selectionIsCurrent: selectionIsCurrent,
skipUnloadedPages: true,
);
return isCurrent() ? text : null;
} catch (_) {
if (!isCurrent()) return null;
rethrow;
}
}

Future<String?> _readText(
PdfDocument document,
PdfTextSelectionRange range, {
required bool Function() isCurrent,
required bool Function() selectionIsCurrent,
bool skipUnloadedPages = false,
}) async {
if (!isCurrent()) return null;
final snapshot = selectedTextSnapshot;
if (snapshot != null) return snapshot;
final first = range.start;
final last = range.end;
final pages = document.pages;
if (first.text.pageNumber < 1 || last.text.pageNumber > pages.length) {
return null;
}
final result = StringBuffer();
var complete = true;
for (
var number = first.text.pageNumber;
number <= last.text.pageNumber;
number++
) {
if (!isCurrent()) return null;
final page = pages[number - 1];
if (!page.isLoaded &&
number != first.text.pageNumber &&
number != last.text.pageNumber) {
if (!skipUnloadedPages) return null;
complete = false;
continue;
}
// cache.get אינו מאמת זהות עמוד לפני שאירוע החלפת התוכן מופץ.
final text = number == first.text.pageNumber
? first.text
: number == last.text.pageNumber
? last.text
: await page.loadStructuredText(ensureLoaded: false);
if (!isCurrent() || !identical(document.pages[number - 1], page)) {
return null;
}
if (text.fullText.isEmpty) continue;
result.write(
text
.getRangeFromAB(
number == first.text.pageNumber ? first.index : 0,
number == last.text.pageNumber
? last.index
: text.charRects.length - 1,
)
.text,
);
}
final text = result.toString();
if (complete) {
releaseSelectedTextSnapshot();
_snapshot = (text: text, selectionIsCurrent: selectionIsCurrent);
// ניקוי בחירה בעקבות אירועי מסמך אינו תמיד מפעיל onTextSelectionChange.
_snapshotEvents = document.events.listen(
(_) => discardStaleSnapshot(),
onDone: releaseSelectedTextSnapshot,
);
}
return text;
}

Future<PdfTextActionResult> selectAll() async {
final generation = ++_generation;
if (!isActive() || !controller.isReady) return PdfTextActionResult.none;
Expand Down Expand Up @@ -105,8 +256,8 @@ class PdfTextSelectionActions {
if (document.pages.any((page) => !page.isLoaded)) {
return PdfTextActionResult.loading;
}
// This setter applies synchronously; native selectAllText awaits without
// checking whether the viewer or its selection has changed in the meantime.
// ה-setter סינכרוני; selectAllText של החבילה ממתין בלי לבדוק
// אם הצפיין או הבחירה הוחלפו בזמן ההמתנה.
await selection.setTextSelectionPointRange(
PdfTextSelectionRange.fromPoints(
PdfTextSelectionPoint(first, 0),
Expand Down
57 changes: 42 additions & 15 deletions lib/pdf_book/view/pdf_book_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1117,11 +1117,12 @@ class _PdfBookScreenState extends State<PdfBookScreen>

final hasTextSelection = _hasPdfTextSelection();
final selectedText = hasTextSelection
? widget
.tab
.pdfViewerController
.textSelectionDelegate
.selectedTextIfLoaded
? _pdfTextSelectionActions.selectedTextSnapshot ??
widget
.tab
.pdfViewerController
.textSelectionDelegate
.selectedTextIfLoaded
: null;
final selection = selectedText == null
? null
Expand Down Expand Up @@ -1168,16 +1169,14 @@ class _PdfBookScreenState extends State<PdfBookScreen>
required String? loadedText,
}) {
if (!hasPluginContextMenuItems) return const [];
final controller = widget.tab.pdfViewerController;
final pageNumber = _menuPageNumber(tapPosition, hasSelection: hasSelection);
return buildPdfPluginMenuEntries(
book: widget.tab.book,
pageNumber: pageNumber,
currentRef: pdfPageRef(widget.tab, pageNumber),
hasSelection: hasSelection,
loadedText: loadedText,
readSelectedText: () =>
controller.textSelectionDelegate.getSelectedText(),
readSelectedText: () async => await _readPdfTextSelection() ?? '',
copyAllowed: _isPdfCopyAllowed(),
menuContext: menuContext,
);
Expand Down Expand Up @@ -1221,6 +1220,24 @@ class _PdfBookScreenState extends State<PdfBookScreen>
errorMessage: CommonMessages.textCopyError,
);

Future<String?> _readPdfTextSelection({
bool requireCopyPermission = true,
}) async {
try {
return await _pdfTextSelectionActions.readSelectedText(
requireCopyPermission: requireCopyPermission,
);
} catch (_) {
if (mounted && _isPdfVisible) {
UiSnack.showError(PdfMessages.textSelectionFailed);
}
return null;
}
}

void _onPdfTextSelectionChanged(PdfTextSelection _) =>
_pdfTextSelectionActions.discardStaleSnapshot();

Future<void> _selectAllPdfText() => _showPdfTextActionResult(
_pdfTextSelectionActions.selectAll(),
errorMessage: PdfMessages.textSelectionFailed,
Expand Down Expand Up @@ -1302,13 +1319,18 @@ class _PdfBookScreenState extends State<PdfBookScreen>
) async {
final controller = widget.tab.pdfViewerController;
if (!controller.isReady) return;
final selection =
loadedSelection ??
ReaderMenuSelection(
await controller.textSelectionDelegate.getSelectedText(),
);
if (!mounted) return;
openGlobalSearch(context, selection.cleaned, insertAdjacent: true);
final selection = loadedSelection;
final rawText = selection == null
? await _readPdfTextSelection(requireCopyPermission: false)
: null;
if (!mounted || !_isPdfVisible || (selection == null && rawText == null)) {
return;
}
openGlobalSearch(
context,
(selection ?? ReaderMenuSelection(rawText)).cleaned,
insertAdjacent: true,
);
}

/// צבע הרקע שמועבר ל-[PdfViewerParams.backgroundColor].
Expand Down Expand Up @@ -1367,6 +1389,7 @@ class _PdfBookScreenState extends State<PdfBookScreen>
scrollByMouseWheel: 1.0,
textSelectionParams: PdfTextSelectionParams(
enabled: !_isHandMode && !_isChoosingPersonalNotePoint,
onTextSelectionChange: _onPdfTextSelectionChanged,
),
// נעילת הציר מתבצעת ב-TrackpadPanRecognizer; PanAxis נועל גם אלכסונים.
panAxis: PanAxis.free,
Expand Down Expand Up @@ -1491,6 +1514,7 @@ class _PdfBookScreenState extends State<PdfBookScreen>
if (mounted) setState(() {});
});
}
_pdfTextSelectionActions.releaseSelectedTextSnapshot();
_pdfTextSelectionActions.cancel();
if (document == null) {
widget.tab.documentRef.value = null;
Expand Down Expand Up @@ -3853,6 +3877,7 @@ class _PdfBookScreenState extends State<PdfBookScreen>
widget.tab.personalNoteNavigationRequests.removeListener(
_onPersonalNoteNavigationRequested,
);
_pdfTextSelectionActions.releaseSelectedTextSnapshot();
_pdfTextSelectionActions.cancel();
WidgetsBinding.instance.removeObserver(this);
_nextFitIsPage.dispose();
Expand Down Expand Up @@ -4176,6 +4201,7 @@ class _PdfBookScreenState extends State<PdfBookScreen>

@override
void didHaveMemoryPressure() {
_pdfTextSelectionActions.releaseSelectedTextSnapshot();
_pageTurnController.stop(canceled: false);
_abortInteractivePageTurn();
_pendingPageTurns.clear();
Expand All @@ -4190,6 +4216,7 @@ class _PdfBookScreenState extends State<PdfBookScreen>

void _releaseImagesWhileHidden() {
_pdfTextSelectionActions.cancel();
_pdfTextSelectionActions.releaseSelectedTextSnapshot();
_trackpadFling.stop();
_scrollPhysicsProvider.stop();
_stopContinuousScroll();
Expand Down
Loading
Loading