From ad48a8dca6aaee2e698cabf2c22e884344c88e83 Mon Sep 17 00:00:00 2001 From: yom-chadash Date: Sun, 22 Nov 2026 13:45:45 -0500 Subject: [PATCH 1/3] =?UTF-8?q?PDF:=20=D7=94=D7=A2=D7=AA=D7=A7=D7=AA=20?= =?UTF-8?q?=D7=91=D7=97=D7=99=D7=A8=D7=94=20=D7=90=D7=A8=D7=95=D7=9B=D7=94?= =?UTF-8?q?=20=D7=91=D7=9C=D7=99=20=D7=A9=D7=99=D7=9E=D7=95=D7=A8=20=D7=92?= =?UTF-8?q?=D7=90=D7=95=D7=9E=D7=98=D7=A8=D7=99=D7=99=D7=AA=20=D7=9B=D7=9C?= =?UTF-8?q?=20=D7=94=D7=A2=D7=9E=D7=95=D7=93=D7=99=D7=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../utils/pdf_text_selection_actions.dart | 102 ++++++- lib/pdf_book/view/pdf_book_screen.dart | 19 +- .../pdf_streaming_copy_native_test.dart | 265 ++++++++++++++++++ .../pdf_text_selection_actions_test.dart | 197 ++++++++++++- 4 files changed, 565 insertions(+), 18 deletions(-) create mode 100644 test/pdf_book/pdf_streaming_copy_native_test.dart diff --git a/lib/pdf_book/utils/pdf_text_selection_actions.dart b/lib/pdf_book/utils/pdf_text_selection_actions.dart index 969142846e..a3e53f0bb3 100644 --- a/lib/pdf_book/utils/pdf_text_selection_actions.dart +++ b/lib/pdf_book/utils/pdf_text_selection_actions.dart @@ -30,6 +30,36 @@ class PdfTextSelectionActions { current?.end == range?.end; } + bool Function() _selectedTextGuard( + int generation, + PdfDocument document, + PdfTextSelectionRange range, + ) { + final originalPages = document.pages; + var checkedPages = originalPages; + final start = range.start.text.pageNumber - 1; + final end = range.end.text.pageNumber - 1; + return () { + if (!_isCurrent(generation, document, range) || + !controller.textSelectionDelegate.isCopyAllowed) { + return false; + } + final currentPages = document.pages; + if (start < 0 || + end >= currentPages.length || + end >= originalPages.length) { + return false; + } + if (!identical(currentPages, checkedPages)) { + for (var i = start; i <= end; i++) { + if (!identical(currentPages[i], originalPages[i])) return false; + } + checkedPages = currentPages; + } + return true; + }; + } + Future copy({bool keepSelection = false}) async { final generation = ++_generation; if (!isActive() || !controller.isReady) return PdfTextActionResult.none; @@ -39,7 +69,7 @@ class PdfTextSelectionActions { if (range == null || !selection.isCopyAllowed) { return PdfTextActionResult.none; } - bool isCurrent() => _isCurrent(generation, document, range); + final isCurrent = _selectedTextGuard(generation, document, range); try { if (!isCurrent()) return PdfTextActionResult.none; if (document.pages @@ -48,8 +78,8 @@ 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); + if (!isCurrent() || text == null || text.isEmpty) { return PdfTextActionResult.none; } // pdfrx's copy helper does not await the platform clipboard response. @@ -69,6 +99,68 @@ class PdfTextSelectionActions { } } + /// קורא את הבחירה בלי להכניס גאומטריה של עמודי ביניים למטמון המשותף. + Future readSelectedText() async { + final generation = ++_generation; + if (!isActive() || !controller.isReady) return ''; + final document = controller.document; + final selection = controller.textSelectionDelegate; + final range = selection.textSelectionPointRange; + if (range == null || !selection.isCopyAllowed) return ''; + final isCurrent = _selectedTextGuard(generation, document, range); + try { + final text = await _readText(document, range, isCurrent); + return isCurrent() ? text ?? '' : ''; + } catch (_) { + if (!isCurrent()) return ''; + rethrow; + } + } + + Future _readText( + PdfDocument document, + PdfTextSelectionRange range, + bool Function() isCurrent, + ) async { + 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(); + for ( + var number = first.text.pageNumber; + number <= last.text.pageNumber; + number++ + ) { + if (!isCurrent()) return null; + final page = pages[number - 1]; + if (!page.isLoaded) return null; + // 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, + ); + } + return result.toString(); + } + Future selectAll() async { final generation = ++_generation; if (!isActive() || !controller.isReady) return PdfTextActionResult.none; @@ -105,8 +197,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), diff --git a/lib/pdf_book/view/pdf_book_screen.dart b/lib/pdf_book/view/pdf_book_screen.dart index 611e128cb1..b13142f9cb 100644 --- a/lib/pdf_book/view/pdf_book_screen.dart +++ b/lib/pdf_book/view/pdf_book_screen.dart @@ -1168,7 +1168,6 @@ class _PdfBookScreenState extends State required String? loadedText, }) { if (!hasPluginContextMenuItems) return const []; - final controller = widget.tab.pdfViewerController; final pageNumber = _menuPageNumber(tapPosition, hasSelection: hasSelection); return buildPdfPluginMenuEntries( book: widget.tab.book, @@ -1176,8 +1175,7 @@ class _PdfBookScreenState extends State currentRef: pdfPageRef(widget.tab, pageNumber), hasSelection: hasSelection, loadedText: loadedText, - readSelectedText: () => - controller.textSelectionDelegate.getSelectedText(), + readSelectedText: _readPdfTextSelection, copyAllowed: _isPdfCopyAllowed(), menuContext: menuContext, ); @@ -1221,6 +1219,17 @@ class _PdfBookScreenState extends State errorMessage: CommonMessages.textCopyError, ); + Future _readPdfTextSelection() async { + try { + return await _pdfTextSelectionActions.readSelectedText(); + } catch (_) { + if (mounted && _isPdfVisible) { + UiSnack.showError(PdfMessages.textSelectionFailed); + } + return ''; + } + } + Future _selectAllPdfText() => _showPdfTextActionResult( _pdfTextSelectionActions.selectAll(), errorMessage: PdfMessages.textSelectionFailed, @@ -1305,9 +1314,9 @@ class _PdfBookScreenState extends State final selection = loadedSelection ?? ReaderMenuSelection( - await controller.textSelectionDelegate.getSelectedText(), + await _readPdfTextSelection(), ); - if (!mounted) return; + if (!mounted || !_isPdfVisible || selection.cleaned.isEmpty) return; openGlobalSearch(context, selection.cleaned, insertAdjacent: true); } diff --git a/test/pdf_book/pdf_streaming_copy_native_test.dart b/test/pdf_book/pdf_streaming_copy_native_test.dart new file mode 100644 index 0000000000..76c97927f8 --- /dev/null +++ b/test/pdf_book/pdf_streaming_copy_native_test.dart @@ -0,0 +1,265 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:crypto/crypto.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/pdf_book/utils/pdf_text_selection_actions.dart'; +import 'package:pdf/widgets.dart' as pw; +import 'package:pdfrx/pdfrx.dart'; + +import '../test_helpers/pdf_document_dispose.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + final originalModulePath = Pdfrx.pdfiumModulePath; + final originalCacheDirectory = Pdfrx.cacheDirectoryPath; + late Directory cacheDirectory; + final clipboard = []; + + setUp(() { + cacheDirectory = Directory.systemTemp.createTempSync('pdf-streaming-copy-'); + Pdfrx.cacheDirectoryPath = cacheDirectory.path; + final module = Platform.isWindows + ? 'pdfium.dll' + : Platform.isMacOS + ? 'libpdfium_dart.dylib' + : 'libpdfium.so'; + Pdfrx.pdfiumModulePath = File( + 'build/native_assets/${Platform.operatingSystem}/$module', + ).absolute.path; + clipboard.clear(); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, (call) async { + if (call.method == 'Clipboard.setData') { + clipboard.add((call.arguments as Map)['text'] as String); + } + return null; + }); + }); + + tearDown(() { + Pdfrx.pdfiumModulePath = originalModulePath; + Pdfrx.cacheDirectoryPath = originalCacheDirectory; + cacheDirectory.deleteSync(recursive: true); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(SystemChannels.platform, null); + }); + + testWidgets( + '1001-page native Copy keeps geometry bounded and preserves text', + ( + tester, + ) async { + const pageCount = 1001; + final bytes = _largePdf(pageCount); + final document = (await tester.runAsync(() async { + await pdfrxFlutterInitialize(); + return PdfDocument.openData(bytes); + }))!; + try { + final controller = await _show(tester, document); + final actions = PdfTextSelectionActions( + controller, + isActive: () => true, + ); + expect( + await tester.runAsync(actions.selectAll), + PdfTextActionResult.none, + ); + final selection = controller.textSelectionDelegate; + final range = selection.textSelectionPointRange!; + expect(range.start.text.pageNumber, 1); + expect(range.end.text.pageNumber, pageCount); + final cache = PdfPageTextCache.forDocument(document); + final before = _cacheCounters(cache); + + expect( + await tester.runAsync(() => actions.copy(keepSelection: true)), + PdfTextActionResult.copied, + ); + expect(clipboard, hasLength(1)); + expect(selection.textSelectionPointRange!.start, range.start); + expect(selection.textSelectionPointRange!.end, range.end); + final after = _cacheCounters(cache); + expect(cache.length, lessThanOrEqualTo(cache.maximumPages)); + expect(cache.estimatedBytes, lessThanOrEqualTo(cache.maximumBytes)); + expect(clipboard.single, contains('Page 1 line 0')); + expect(clipboard.single, contains('Page 1001 line 4')); + + final reference = await tester.runAsync(selection.getSelectedText); + expect(clipboard.single, reference); + debugPrint( + 'PDF_STREAMING_COPY ${jsonEncode({ + 'pages': pageCount, + 'fixtureBytes': bytes.length, + 'fixtureSha256': sha256.convert(bytes).toString(), + 'outputCharacters': clipboard.single.length, + 'before': before, + 'afterApplicationCopy': after, + 'afterLibraryReferenceRead': _cacheCounters(cache), + 'scope': 'Dart text-cache counters; not native allocations or RSS', + })}', + ); + expect(tester.takeException(), isNull); + } finally { + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump( + const PdfViewerBehaviorControlParams().trailingPageLoadingDelay, + ); + await disposePdfDocument(tester, document); + } + }, + timeout: const Timeout(Duration(minutes: 2)), + ); + + testWidgets( + 'native backward Hebrew selection matches library text across a blank page', + ( + tester, + ) async { + final document = (await tester.runAsync(() async { + await pdfrxFlutterInitialize(); + final font = pw.Font.ttf( + File( + 'fonts/FrankRuehlCLM-Medium.ttf', + ).readAsBytesSync().buffer.asByteData(), + ); + final pdf = pw.Document(); + for (final content in [ + 'התחלה שָׁלוֹם שלום ABC 123', + '', + 'סוף שלום XYZ 456', + ]) { + pdf.addPage( + pw.Page( + build: (_) => content.isEmpty + ? pw.SizedBox() + : pw.Text( + content, + style: pw.TextStyle(font: font), + textDirection: pw.TextDirection.rtl, + ), + ), + ); + } + return PdfDocument.openData(await pdf.save()); + }))!; + try { + final controller = await _show(tester, document); + final first = (await tester.runAsync( + document.pages.first.loadStructuredText, + ))!; + final last = (await tester.runAsync( + document.pages.last.loadStructuredText, + ))!; + final selection = controller.textSelectionDelegate; + final range = PdfTextSelectionRange.fromPoints( + PdfTextSelectionPoint(last, last.charRects.length - 3), + PdfTextSelectionPoint(first, 2), + ); + await selection.setTextSelectionPointRange(range); + final reference = await tester.runAsync(selection.getSelectedText); + final actions = PdfTextSelectionActions( + controller, + isActive: () => true, + ); + expect( + await tester.runAsync(() => actions.copy(keepSelection: true)), + PdfTextActionResult.copied, + ); + expect(clipboard.single, reference); + expect(clipboard.single, contains('שלום')); + expect(clipboard.single, contains('ABC')); + expect(selection.textSelectionPointRange!.start, range.start); + expect(selection.textSelectionPointRange!.end, range.end); + expect(tester.takeException(), isNull); + } finally { + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump( + const PdfViewerBehaviorControlParams().trailingPageLoadingDelay, + ); + await disposePdfDocument(tester, document); + } + }, + ); +} + +Future _show( + WidgetTester tester, + PdfDocument document, +) async { + final controller = PdfViewerController(); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: PdfViewer( + PdfDocumentRefDirect(document, autoDispose: false), + controller: controller, + params: PdfViewerParams( + textSelectionParams: PdfTextSelectionParams( + showContextMenuAutomatically: false, + ), + ), + ), + ), + ), + ); + final clock = Stopwatch()..start(); + while (!controller.isReady || + controller.visibleRenderState.value != PdfVisibleRenderState.ready) { + if (clock.elapsed > const Duration(seconds: 30)) { + fail('The native PDF viewer did not become ready'); + } + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 10)), + ); + await tester.pump(const Duration(milliseconds: 20)); + } + return controller; +} + +Map _cacheCounters(PdfPageTextCache cache) => { + 'pages': cache.length, + 'estimatedBytes': cache.estimatedBytes, +}; + +Uint8List _largePdf(int count) { + final ids = [for (var i = 0; i < count; i++) 4 + i * 2]; + final objects = [ + '<< /Type /Catalog /Pages 2 0 R >>', + '<< /Type /Pages /Count $count /Kids [${ids.map((id) => '$id 0 R').join(' ')}] >>', + '<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>', + ]; + for (var i = 0; i < count; i++) { + final content = StringBuffer(); + for (var line = 0; line < 5; line++) { + content.writeln( + 'BT /F1 10 Tf 20 ${780 - line * 20} Td ' + '(Page ${i + 1} line $line: ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789) Tj ET', + ); + } + objects.add( + '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] ' + '/Resources << /Font << /F1 3 0 R >> >> /Contents ${ids[i] + 1} 0 R >>', + ); + objects.add('<< /Length ${content.length} >>\nstream\n${content}endstream'); + } + final output = StringBuffer('%PDF-1.4\n'); + final offsets = []; + for (var i = 0; i < objects.length; i++) { + offsets.add(output.length); + output.write('${i + 1} 0 obj\n${objects[i]}\nendobj\n'); + } + final xref = output.length; + output.write('xref\n0 ${objects.length + 1}\n0000000000 65535 f \n'); + for (final offset in offsets) { + output.write('${offset.toString().padLeft(10, '0')} 00000 n \n'); + } + output.write( + 'trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\n' + 'startxref\n$xref\n%%EOF\n', + ); + return Uint8List.fromList(ascii.encode(output.toString())); +} diff --git a/test/pdf_book/pdf_text_selection_actions_test.dart b/test/pdf_book/pdf_text_selection_actions_test.dart index df1d7f97af..d025439ac0 100644 --- a/test/pdf_book/pdf_text_selection_actions_test.dart +++ b/test/pdf_book/pdf_text_selection_actions_test.dart @@ -48,7 +48,7 @@ void main() { return result; }); await _flush(); - expect(writes, ['selected text']); + expect(writes, ['Page textPage textPag']); expect(completed, isFalse); expect(selection.hasSelectedText, isTrue); clipboardWrite!.complete(); @@ -70,7 +70,7 @@ void main() { final range = selection.range; expect(await actions.copy(keepSelection: true), PdfTextActionResult.copied); expect(selection.range, same(range)); - expect(writes, ['selected text']); + expect(writes, ['Page textPage textPag']); }); test( @@ -103,6 +103,8 @@ void main() { 'detached', 'document', 'selection', + 'permission', + 'page-content', ]) { void invalidate() { switch (change) { @@ -116,21 +118,27 @@ void main() { controller.document = _Document(2); case 'selection': selection.range = _range(2, 2); + case 'permission': + selection.isCopyAllowed = false; + case 'page-content': + document.pages = [...document.pages]..[1] = _Page(2); } } test('copy stops after a pending text read when $change changes', () async { - final text = Completer(); - selection.readText = () => text.future; + final text = Completer(); + document.pages[1].load = () => text.future; final copy = actions.copy(); await _flush(); invalidate(); - text.complete('stale text'); + text.complete(_text(2, 'stale text')); expect(await copy, PdfTextActionResult.none); expect(writes, isEmpty); expect(selection.clears, 0); }); + if (change == 'permission' || change == 'page-content') continue; + test( 'pending select-all stops before another page or mutation on $change', () async { @@ -214,12 +222,182 @@ void main() { document.pages.first.load = () => Future.error(StateError('closed PDF')); expect(await actions.selectAll(), PdfTextActionResult.failed); expect(selection.updates, 0); - selection.readText = () => Future.error(StateError('closed PDF')); + document.pages[1].load = () => Future.error(StateError('closed PDF')); expect(await actions.copy(), PdfTextActionResult.failed); expect(writes, isEmpty); expect(selection.clears, 0); }, ); + + test( + 'same-page backward selection preserves Hebrew, accents and spaces', + () async { + const content = 'אבג שָׁלוֹם ABC\nדהו'; + final page = _text(1, content); + selection.range = PdfTextSelectionRange.fromPoints( + PdfTextSelectionPoint(page, content.length - 3), + PdfTextSelectionPoint(page, 2), + ); + expect( + await actions.readSelectedText(), + content.substring(2, content.length - 2), + ); + expect( + await actions.copy(keepSelection: true), + PdfTextActionResult.copied, + ); + expect(writes.single, content.substring(2, content.length - 2)); + expect(document.pages.every((page) => page.reads == 0), true); + expect(selection.reads, 0); + }, + ); + + test( + 'page order and blank middle pages match the inclusive selection', + () async { + controller.document = document = _Document(5); + selection.range = PdfTextSelectionRange.fromPoints( + PdfTextSelectionPoint(_text(5, 'END suffix'), 2), + PdfTextSelectionPoint(_text(1, 'prefix START\n'), 7), + ); + document.pages[1].load = () async => _text(2, 'אבג\n'); + document.pages[2].load = () async => _text(3, ''); + document.pages[3].load = () async => _text(4, 'שָׁלוֹם ABC '); + // Keep the library's existing normalization of raw-page whitespace. + final formatted = await (_Page( + 4, + )..load = document.pages[3].load).loadStructuredText(); + expect( + await actions.readSelectedText(), + 'START\nאבג\n${formatted.fullText}END', + ); + expect(document.pages.map((page) => page.reads), [0, 1, 1, 1, 0]); + expect(PdfPageTextCache.forDocument(document).length, 0); + expect(selection.reads, 0); + }, + ); + + test( + 'a stale cached middle page is neither reused nor replaced by a read', + () async { + final cache = PdfPageTextCache.forDocument(document); + document.pages[1].load = () async => _text(2, 'old content'); + final stale = await cache.load(document.pages[1]); + final lease = cache.createLease()..updatePinnedPages([2]); + addTearDown(lease.dispose); + final bytes = cache.estimatedBytes; + document.pages = [...document.pages] + ..[1] = (_Page(2)..load = () async => _text(2, 'new content')); + expect(await actions.readSelectedText(), 'Page textnew contentPag'); + expect(cache.length, 1); + expect(cache.estimatedBytes, bytes); + expect(cache.get(2), same(stale)); + expect(document.pages[1].reads, 1); + }, + ); + + test('read cancellation stops before another middle page', () async { + controller.document = document = _Document(5); + selection.range = _range(1, 5); + final pending = Completer(); + document.pages[1].load = () => pending.future; + final read = actions.readSelectedText(); + await _flush(); + actions.cancel(); + pending.complete(_text(2)); + expect(await read, ''); + expect(document.pages.map((page) => page.reads), [0, 1, 0, 0, 0]); + expect(selection.range, isNotNull); + expect(writes, isEmpty); + }); + + test( + 'a replacement during a pending read cannot reach its consumer', + () async { + final pending = Completer(); + document.pages[1].load = () => pending.future; + final read = actions.readSelectedText(); + await _flush(); + document.pages = [...document.pages]..[1] = _Page(2); + pending.complete(_text(2)); + expect(await read, ''); + expect(writes, isEmpty); + }, + ); + + test( + 'metadata updates outside the selection do not cancel its read', + () async { + controller.document = document = _Document(20); + final pending = Completer(); + document.pages[1].load = () => pending.future; + final read = actions.readSelectedText(); + await _flush(); + document.pages = [...document.pages]..[19] = _Page(20); + pending.complete(_text(2, 'current text')); + expect(await read, 'Page textcurrent textPag'); + expect(document.pages[1].reads, 1); + expect(document.pages[19].reads, 0); + }, + ); + + test('metadata updates outside the selection do not cancel Copy', () async { + controller.document = document = _Document(20); + final pending = Completer(); + document.pages[1].load = () => pending.future; + final copy = actions.copy(keepSelection: true); + await _flush(); + document.pages = [...document.pages]..[19] = _Page(20); + pending.complete(_text(2, 'current text')); + expect(await copy, PdfTextActionResult.copied); + expect(writes, ['Page textcurrent textPag']); + }); + + test( + 'a late extraction failure after cancellation is not sent to consumers', + () async { + final pending = Completer(); + document.pages[1].load = () => pending.future; + final read = actions.readSelectedText(); + await _flush(); + actions.cancel(); + pending.completeError(StateError('document closed')); + expect(await read, ''); + expect(writes, isEmpty); + }, + ); + + test('a newer read supersedes an older pending copy', () async { + final pending = Completer(); + document.pages[1].load = () => pending.future; + final copy = actions.copy(); + await _flush(); + selection.range = _range(1, 1); + expect(await actions.readSelectedText(), 'Pag'); + pending.complete(_text(2)); + expect(await copy, PdfTextActionResult.none); + expect(writes, isEmpty); + expect(selection.clears, 0); + }); + + test( + 'unloaded or forbidden selected text is not returned to consumers', + () async { + document.pages[1].isLoaded = false; + expect(await actions.readSelectedText(), ''); + document.pages[1].isLoaded = true; + selection.isCopyAllowed = false; + expect(await actions.readSelectedText(), ''); + expect(document.pages.every((page) => page.reads == 0), true); + }, + ); + + test('failed text extraction remains an error for the consumer', () async { + document.pages[1].load = () => Future.error(StateError('closed PDF')); + await expectLater(actions.readSelectedText(), throwsStateError); + expect(writes, isEmpty); + expect(selection.clears, 0); + }); } Future _flush() => Future.delayed(Duration.zero); @@ -281,12 +459,15 @@ class _Selection extends Fake implements PdfTextSelectionDelegate { } class _Document extends Fake implements PdfDocument { - _Document(int count) : pages = List.generate(count, (i) => _Page(i + 1)) { + _Document(int count) : _pages = List.generate(count, (i) => _Page(i + 1)) { addTearDown(_events.close); } final _events = StreamController.broadcast(); + List<_Page> _pages; + @override + List<_Page> get pages => _pages; @override - final List<_Page> pages; + set pages(List value) => _pages = value.cast<_Page>(); @override Stream get events => _events.stream; } From 876df41cf6b19882626ab6d48651b677cb639fd9 Mon Sep 17 00:00:00 2001 From: ypl <7353755@gmail.com> Date: Sun, 22 Nov 2026 20:58:46 +0200 Subject: [PATCH 2/3] =?UTF-8?q?PDF:=20=D7=A9=D7=99=D7=9E=D7=95=D7=A8=20?= =?UTF-8?q?=D7=97=D7=99=D7=A4=D7=95=D7=A9=20=D7=9E=D7=91=D7=97=D7=99=D7=A8?= =?UTF-8?q?=D7=94=20=D7=95=D7=A9=D7=99=D7=9E=D7=95=D7=A9=20=D7=97=D7=95?= =?UTF-8?q?=D7=96=D7=A8=20=D7=91=D7=98=D7=A7=D7=A1=D7=98=20=D7=A9=D7=94?= =?UTF-8?q?=D7=95=D7=A2=D7=AA=D7=A7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../utils/pdf_text_selection_actions.dart | 98 ++++++++++++++----- lib/pdf_book/view/pdf_book_screen.dart | 48 ++++++--- .../pdf_text_selection_actions_test.dart | 72 ++++++++++++-- 3 files changed, 169 insertions(+), 49 deletions(-) diff --git a/lib/pdf_book/utils/pdf_text_selection_actions.dart b/lib/pdf_book/utils/pdf_text_selection_actions.dart index a3e53f0bb3..1e2b84a9e1 100644 --- a/lib/pdf_book/utils/pdf_text_selection_actions.dart +++ b/lib/pdf_book/utils/pdf_text_selection_actions.dart @@ -9,6 +9,18 @@ class PdfTextSelectionActions { final PdfViewerController controller; final bool Function() isActive; int _generation = 0; + ({String text, bool Function() selectionIsCurrent})? _snapshot; + + String? get selectedTextSnapshot { + discardStaleSnapshot(); + return _snapshot?.text; + } + + void discardStaleSnapshot() { + if (_snapshot?.selectionIsCurrent() == false) _snapshot = null; + } + + void releaseSelectedTextSnapshot() => _snapshot = null; void cancel() => _generation++; @@ -16,9 +28,10 @@ class PdfTextSelectionActions { 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; @@ -31,28 +44,23 @@ class PdfTextSelectionActions { } bool Function() _selectedTextGuard( - int generation, PdfDocument document, PdfTextSelectionRange range, ) { - final originalPages = document.pages; - var checkedPages = originalPages; + var checkedPages = document.pages; final start = range.start.text.pageNumber - 1; final end = range.end.text.pageNumber - 1; return () { - if (!_isCurrent(generation, document, range) || - !controller.textSelectionDelegate.isCopyAllowed) { - return false; - } + if (!_matchesSelection(document, range)) return false; final currentPages = document.pages; if (start < 0 || end >= currentPages.length || - end >= originalPages.length) { + end >= checkedPages.length) { return false; } if (!identical(currentPages, checkedPages)) { for (var i = start; i <= end; i++) { - if (!identical(currentPages[i], originalPages[i])) return false; + if (!identical(currentPages[i], checkedPages[i])) return false; } checkedPages = currentPages; } @@ -69,7 +77,11 @@ class PdfTextSelectionActions { if (range == null || !selection.isCopyAllowed) { return PdfTextActionResult.none; } - final isCurrent = _selectedTextGuard(generation, document, range); + final selectionIsCurrent = _selectedTextGuard(document, range); + bool isCurrent() => + generation == _generation && + selectionIsCurrent() && + selection.isCopyAllowed; try { if (!isCurrent()) return PdfTextActionResult.none; if (document.pages @@ -78,7 +90,12 @@ class PdfTextSelectionActions { .any((page) => !page.isLoaded)) { return PdfTextActionResult.loading; } - final text = await _readText(document, range, isCurrent); + final text = await _readText( + document, + range, + isCurrent: isCurrent, + selectionIsCurrent: selectionIsCurrent, + ); if (!isCurrent() || text == null || text.isEmpty) { return PdfTextActionResult.none; } @@ -87,6 +104,7 @@ class PdfTextSelectionActions { if (!isCurrent()) return PdfTextActionResult.none; if (!keepSelection) { await selection.clearTextSelection(); + discardStaleSnapshot(); if (!_isCurrent(generation, document, null)) { return PdfTextActionResult.none; } @@ -100,28 +118,45 @@ class PdfTextSelectionActions { } /// קורא את הבחירה בלי להכניס גאומטריה של עמודי ביניים למטמון המשותף. - Future readSelectedText() async { + Future readSelectedText({bool requireCopyPermission = true}) async { final generation = ++_generation; - if (!isActive() || !controller.isReady) return ''; + if (!isActive() || !controller.isReady) return null; final document = controller.document; final selection = controller.textSelectionDelegate; final range = selection.textSelectionPointRange; - if (range == null || !selection.isCopyAllowed) return ''; - final isCurrent = _selectedTextGuard(generation, document, range); + 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); - return isCurrent() ? text ?? '' : ''; + final text = await _readText( + document, + range, + isCurrent: isCurrent, + selectionIsCurrent: selectionIsCurrent, + skipUnloadedPages: true, + ); + return isCurrent() ? text : null; } catch (_) { - if (!isCurrent()) return ''; + if (!isCurrent()) return null; rethrow; } } Future _readText( PdfDocument document, - PdfTextSelectionRange range, - bool Function() isCurrent, - ) async { + 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; @@ -129,6 +164,7 @@ class PdfTextSelectionActions { return null; } final result = StringBuffer(); + var complete = true; for ( var number = first.text.pageNumber; number <= last.text.pageNumber; @@ -136,7 +172,13 @@ class PdfTextSelectionActions { ) { if (!isCurrent()) return null; final page = pages[number - 1]; - if (!page.isLoaded) return null; + 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 @@ -158,7 +200,11 @@ class PdfTextSelectionActions { .text, ); } - return result.toString(); + final text = result.toString(); + if (complete) { + _snapshot = (text: text, selectionIsCurrent: selectionIsCurrent); + } + return text; } Future selectAll() async { diff --git a/lib/pdf_book/view/pdf_book_screen.dart b/lib/pdf_book/view/pdf_book_screen.dart index b13142f9cb..16ecdc3a3d 100644 --- a/lib/pdf_book/view/pdf_book_screen.dart +++ b/lib/pdf_book/view/pdf_book_screen.dart @@ -1117,11 +1117,12 @@ class _PdfBookScreenState extends State final hasTextSelection = _hasPdfTextSelection(); final selectedText = hasTextSelection - ? widget - .tab - .pdfViewerController - .textSelectionDelegate - .selectedTextIfLoaded + ? _pdfTextSelectionActions.selectedTextSnapshot ?? + widget + .tab + .pdfViewerController + .textSelectionDelegate + .selectedTextIfLoaded : null; final selection = selectedText == null ? null @@ -1175,7 +1176,7 @@ class _PdfBookScreenState extends State currentRef: pdfPageRef(widget.tab, pageNumber), hasSelection: hasSelection, loadedText: loadedText, - readSelectedText: _readPdfTextSelection, + readSelectedText: () async => await _readPdfTextSelection() ?? '', copyAllowed: _isPdfCopyAllowed(), menuContext: menuContext, ); @@ -1219,17 +1220,24 @@ class _PdfBookScreenState extends State errorMessage: CommonMessages.textCopyError, ); - Future _readPdfTextSelection() async { + Future _readPdfTextSelection({ + bool requireCopyPermission = true, + }) async { try { - return await _pdfTextSelectionActions.readSelectedText(); + return await _pdfTextSelectionActions.readSelectedText( + requireCopyPermission: requireCopyPermission, + ); } catch (_) { if (mounted && _isPdfVisible) { UiSnack.showError(PdfMessages.textSelectionFailed); } - return ''; + return null; } } + void _onPdfTextSelectionChanged(PdfTextSelection _) => + _pdfTextSelectionActions.discardStaleSnapshot(); + Future _selectAllPdfText() => _showPdfTextActionResult( _pdfTextSelectionActions.selectAll(), errorMessage: PdfMessages.textSelectionFailed, @@ -1311,13 +1319,18 @@ class _PdfBookScreenState extends State ) async { final controller = widget.tab.pdfViewerController; if (!controller.isReady) return; - final selection = - loadedSelection ?? - ReaderMenuSelection( - await _readPdfTextSelection(), - ); - if (!mounted || !_isPdfVisible || selection.cleaned.isEmpty) 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]. @@ -1376,6 +1389,7 @@ class _PdfBookScreenState extends State scrollByMouseWheel: 1.0, textSelectionParams: PdfTextSelectionParams( enabled: !_isHandMode && !_isChoosingPersonalNotePoint, + onTextSelectionChange: _onPdfTextSelectionChanged, ), // נעילת הציר מתבצעת ב-TrackpadPanRecognizer; PanAxis נועל גם אלכסונים. panAxis: PanAxis.free, @@ -4185,6 +4199,7 @@ class _PdfBookScreenState extends State @override void didHaveMemoryPressure() { + _pdfTextSelectionActions.releaseSelectedTextSnapshot(); _pageTurnController.stop(canceled: false); _abortInteractivePageTurn(); _pendingPageTurns.clear(); @@ -4199,6 +4214,7 @@ class _PdfBookScreenState extends State void _releaseImagesWhileHidden() { _pdfTextSelectionActions.cancel(); + _pdfTextSelectionActions.releaseSelectedTextSnapshot(); _trackpadFling.stop(); _scrollPhysicsProvider.stop(); _stopContinuousScroll(); diff --git a/test/pdf_book/pdf_text_selection_actions_test.dart b/test/pdf_book/pdf_text_selection_actions_test.dart index d025439ac0..def26c9064 100644 --- a/test/pdf_book/pdf_text_selection_actions_test.dart +++ b/test/pdf_book/pdf_text_selection_actions_test.dart @@ -305,7 +305,7 @@ void main() { await _flush(); actions.cancel(); pending.complete(_text(2)); - expect(await read, ''); + expect(await read, isNull); expect(document.pages.map((page) => page.reads), [0, 1, 0, 0, 0]); expect(selection.range, isNotNull); expect(writes, isEmpty); @@ -320,7 +320,7 @@ void main() { await _flush(); document.pages = [...document.pages]..[1] = _Page(2); pending.complete(_text(2)); - expect(await read, ''); + expect(await read, isNull); expect(writes, isEmpty); }, ); @@ -362,7 +362,7 @@ void main() { await _flush(); actions.cancel(); pending.completeError(StateError('document closed')); - expect(await read, ''); + expect(await read, isNull); expect(writes, isEmpty); }, ); @@ -381,14 +381,72 @@ void main() { }); test( - 'unloaded or forbidden selected text is not returned to consumers', + 'lazy search ignores missing middle pages and retries them later', () async { document.pages[1].isLoaded = false; - expect(await actions.readSelectedText(), ''); + expect( + await actions.readSelectedText(requireCopyPermission: false), + 'Page textPag', + ); + expect(actions.selectedTextSnapshot, isNull); + expect(document.pages[1].reads, 0); + document.pages[1].isLoaded = true; + expect( + await actions.readSelectedText(requireCopyPermission: false), + 'Page textPage textPag', + ); + expect(actions.selectedTextSnapshot, 'Page textPage textPag'); + expect(document.pages[1].reads, 1); + }, + ); + + test( + 'restricted documents retain search but withhold text from plugins and Copy', + () async { selection.isCopyAllowed = false; - expect(await actions.readSelectedText(), ''); - expect(document.pages.every((page) => page.reads == 0), true); + expect(await actions.readSelectedText(), isNull); + expect(await actions.copy(), PdfTextActionResult.none); + expect(document.pages[1].reads, 0); + + expect( + await actions.readSelectedText(requireCopyPermission: false), + 'Page textPage textPag', + ); + expect(actions.selectedTextSnapshot, 'Page textPage textPag'); + expect(await actions.readSelectedText(), isNull); + expect(await actions.copy(), PdfTextActionResult.none); + expect(writes, isEmpty); + }, + ); + + test( + 'repeat Copy reuses plain text until the selection or page changes', + () async { + expect( + await actions.copy(keepSelection: true), + PdfTextActionResult.copied, + ); + expect(actions.selectedTextSnapshot, writes.single); + actions.cancel(); + expect( + await actions.copy(keepSelection: true), + PdfTextActionResult.copied, + ); + expect(writes, ['Page textPage textPag', 'Page textPage textPag']); + expect(document.pages[1].reads, 1); + + document.pages = [...document.pages] + ..[1] = (_Page(2)..load = () async => _text(2, 'new content')); + expect(actions.selectedTextSnapshot, isNull); + expect(await actions.readSelectedText(), 'Page textnew contentPag'); + + selection.range = _range(1, 1); + expect(actions.selectedTextSnapshot, isNull); + expect(await actions.readSelectedText(), 'Pag'); + + controller.document = _Document(3); + expect(actions.selectedTextSnapshot, isNull); }, ); From fc940bb84a2c0d506aa7526b1846146375566977 Mon Sep 17 00:00:00 2001 From: yom-chadash Date: Sun, 22 Nov 2026 14:43:17 -0500 Subject: [PATCH 3/3] =?UTF-8?q?PDF:=20=D7=A9=D7=97=D7=A8=D7=95=D7=A8=20?= =?UTF-8?q?=D7=9E=D7=98=D7=9E=D7=95=D7=9F=20=D7=94=D7=91=D7=97=D7=99=D7=A8?= =?UTF-8?q?=D7=94=20=D7=A2=D7=9D=20=D7=A9=D7=99=D7=A0=D7=95=D7=99=20=D7=94?= =?UTF-8?q?=D7=9E=D7=A1=D7=9E=D7=9A=20=D7=95=D7=94=D7=AA=D7=95=D7=9B=D7=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../utils/pdf_text_selection_actions.dart | 17 ++- lib/pdf_book/view/pdf_book_screen.dart | 2 + .../pdf_text_selection_actions_test.dart | 130 +++++++++++++++++- 3 files changed, 146 insertions(+), 3 deletions(-) diff --git a/lib/pdf_book/utils/pdf_text_selection_actions.dart b/lib/pdf_book/utils/pdf_text_selection_actions.dart index 1e2b84a9e1..31b6b57ef6 100644 --- a/lib/pdf_book/utils/pdf_text_selection_actions.dart +++ b/lib/pdf_book/utils/pdf_text_selection_actions.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flutter/services.dart'; import 'package:pdfrx/pdfrx.dart'; @@ -10,6 +12,7 @@ class PdfTextSelectionActions { final bool Function() isActive; int _generation = 0; ({String text, bool Function() selectionIsCurrent})? _snapshot; + StreamSubscription? _snapshotEvents; String? get selectedTextSnapshot { discardStaleSnapshot(); @@ -17,10 +20,14 @@ class PdfTextSelectionActions { } void discardStaleSnapshot() { - if (_snapshot?.selectionIsCurrent() == false) _snapshot = null; + if (_snapshot?.selectionIsCurrent() == false) releaseSelectedTextSnapshot(); } - void releaseSelectedTextSnapshot() => _snapshot = null; + void releaseSelectedTextSnapshot() { + _snapshot = null; + unawaited(_snapshotEvents?.cancel()); + _snapshotEvents = null; + } void cancel() => _generation++; @@ -202,7 +209,13 @@ class PdfTextSelectionActions { } final text = result.toString(); if (complete) { + releaseSelectedTextSnapshot(); _snapshot = (text: text, selectionIsCurrent: selectionIsCurrent); + // ניקוי בחירה בעקבות אירועי מסמך אינו תמיד מפעיל onTextSelectionChange. + _snapshotEvents = document.events.listen( + (_) => discardStaleSnapshot(), + onDone: releaseSelectedTextSnapshot, + ); } return text; } diff --git a/lib/pdf_book/view/pdf_book_screen.dart b/lib/pdf_book/view/pdf_book_screen.dart index 16ecdc3a3d..c3b9e96f3a 100644 --- a/lib/pdf_book/view/pdf_book_screen.dart +++ b/lib/pdf_book/view/pdf_book_screen.dart @@ -1514,6 +1514,7 @@ class _PdfBookScreenState extends State if (mounted) setState(() {}); }); } + _pdfTextSelectionActions.releaseSelectedTextSnapshot(); _pdfTextSelectionActions.cancel(); if (document == null) { widget.tab.documentRef.value = null; @@ -3876,6 +3877,7 @@ class _PdfBookScreenState extends State widget.tab.personalNoteNavigationRequests.removeListener( _onPersonalNoteNavigationRequested, ); + _pdfTextSelectionActions.releaseSelectedTextSnapshot(); _pdfTextSelectionActions.cancel(); WidgetsBinding.instance.removeObserver(this); _nextFitIsPage.dispose(); diff --git a/test/pdf_book/pdf_text_selection_actions_test.dart b/test/pdf_book/pdf_text_selection_actions_test.dart index def26c9064..4a25d49e8b 100644 --- a/test/pdf_book/pdf_text_selection_actions_test.dart +++ b/test/pdf_book/pdf_text_selection_actions_test.dart @@ -13,6 +13,7 @@ void main() { late PdfTextSelectionActions actions; late List writes; late bool active; + late int activeChecks; Completer? clipboardWrite; setUp(() { @@ -20,7 +21,15 @@ void main() { selection = _Selection()..range = _range(1, 3); controller = _Controller(document, selection); active = true; - actions = PdfTextSelectionActions(controller, isActive: () => active); + activeChecks = 0; + actions = PdfTextSelectionActions( + controller, + isActive: () { + activeChecks++; + return active; + }, + ); + addTearDown(actions.releaseSelectedTextSnapshot); writes = []; clipboardWrite = null; TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger @@ -390,6 +399,7 @@ void main() { ); expect(actions.selectedTextSnapshot, isNull); expect(document.pages[1].reads, 0); + expect(document._events.hasListener, isFalse); document.pages[1].isLoaded = true; expect( @@ -420,6 +430,124 @@ void main() { }, ); + test( + 'document events discard a silently cleared snapshot before another read', + () async { + expect(await actions.readSelectedText(), 'Page textPage textPag'); + selection.range = null; + document._events.add( + PdfDocumentPageStatusChangedEvent( + document, + changes: {2: PdfPageStatusModified(page: document.pages[1])}, + ), + ); + await _flush(); + + activeChecks = 0; + expect(actions.selectedTextSnapshot, isNull); + expect(activeChecks, 0, reason: 'the event already released the guard'); + expect(document._events.hasListener, isFalse); + }, + ); + + test('page replacement eagerly drops the retained snapshot', () async { + expect(await actions.readSelectedText(), 'Page textPage textPag'); + document.pages = [...document.pages]..[1] = _Page(2); + document._events.add( + PdfDocumentPageStatusChangedEvent( + document, + changes: {2: PdfPageStatusModified(page: document.pages[1])}, + ), + ); + await _flush(); + + activeChecks = 0; + expect(actions.selectedTextSnapshot, isNull); + expect(activeChecks, 0, reason: 'the event already released the guard'); + expect(document._events.hasListener, isFalse); + expect(await actions.readSelectedText(), 'Page textPage textPag'); + expect(document.pages[1].reads, 1); + }); + + test('old document events release its snapshot after replacement', () async { + expect(await actions.readSelectedText(), 'Page textPage textPag'); + controller.document = _Document(3); + document._events.add(PdfDocumentLoadCompleteEvent(document)); + await _flush(); + + activeChecks = 0; + expect(actions.selectedTextSnapshot, isNull); + expect(activeChecks, 0, reason: 'the event already released the guard'); + expect(document._events.hasListener, isFalse); + }); + + test( + 'explicit release detaches the old document before a new read', + () async { + expect(await actions.readSelectedText(), 'Page textPage textPag'); + expect(document._events.hasListener, isTrue); + final oldDocument = document; + actions.cancel(); + actions.releaseSelectedTextSnapshot(); + actions.releaseSelectedTextSnapshot(); + expect(oldDocument._events.hasListener, isFalse); + + controller.document = document = _Document(3); + expect(await actions.readSelectedText(), 'Page textPage textPag'); + oldDocument._events.add(PdfDocumentLoadCompleteEvent(oldDocument)); + await oldDocument._events.close(); + expect(actions.selectedTextSnapshot, 'Page textPage textPag'); + expect(document._events.hasListener, isTrue); + expect(document.pages[1].reads, 1); + }, + ); + + test( + 'replayed events and metadata outside the selection keep text reusable', + () async { + controller.document = document = _Document(20); + document._events.onListen = () => document._events.add( + PdfDocumentPageStatusChangedEvent( + document, + changes: {2: PdfPageStatusModified(page: document.pages[1])}, + ), + ); + expect(await actions.readSelectedText(), 'Page textPage textPag'); + await _flush(); + expect(actions.selectedTextSnapshot, 'Page textPage textPag'); + + document.pages = [...document.pages]..[19] = _Page(20); + document._events.add( + PdfDocumentPageStatusChangedEvent( + document, + changes: {20: PdfPageStatusModified(page: document.pages[19])}, + ), + ); + await _flush(); + actions.cancel(); + expect( + await actions.copy(keepSelection: true), + PdfTextActionResult.copied, + ); + expect(writes, ['Page textPage textPag']); + expect(document.pages[1].reads, 1); + expect(document.pages[19].reads, 0); + expect(document._events.hasListener, isTrue); + + selection.range = _range(1, 1); + actions.discardStaleSnapshot(); + expect(document._events.hasListener, isFalse); + }, + ); + + test('closing the document releases its retained snapshot', () async { + expect(await actions.readSelectedText(), 'Page textPage textPag'); + await document._events.close(); + activeChecks = 0; + expect(actions.selectedTextSnapshot, isNull); + expect(activeChecks, 0); + }); + test( 'repeat Copy reuses plain text until the selection or page changes', () async {