diff --git a/lib/printing/view/printing_screen.dart b/lib/printing/view/printing_screen.dart index 850e8c8fd2..ccb6edd686 100644 --- a/lib/printing/view/printing_screen.dart +++ b/lib/printing/view/printing_screen.dart @@ -759,8 +759,14 @@ class _PrintingScreenState extends State { } void _setPagesPerSheet(int value) { + final source = _sourcePageFormat(format); setState(() => _pagesPerSheet = value); - _preview.setPagesPerSheet(value); + // עמוד טקסט בכיוון אחר הוא מסמך אחר; אחרת משתנה רק סידור הגיליונות. + if (!_isPdfSource && _sourcePageFormat(format) != source) { + _refreshPreview(); + } else { + _preview.setPagesPerSheet(value); + } } Future _createOutputPdf(PdfPageFormat format) async { @@ -811,24 +817,34 @@ class _PrintingScreenState extends State { : format; } - // מטמון ה-base PDF: שינוי שמשפיע רק על שלב הרסטור (מספר עמודים בגיליון, - // טווח עמודים ב-PDF חיצוני) לא בונה מחדש את המסמך — רק מרסטר אותו שוב. + /// עמוד הטקסט שנוצר להדפסה. בשני עמודים בגיליון התא הוא חצי מרוחב הגיליון + /// ולכן לאורך, וגם על גיליון לרוחב העמוד לאורך וממלא אותו. + PdfPageFormat _sourcePageFormat(PdfPageFormat format) { + final sheet = _effectivePageFormat(format); + return _pagesPerSheet == 2 ? sheet.portrait : sheet; + } + + // מטמון ה-base PDF: שינוי שמשפיע רק על שלב הרסטור (מספר עמודים בגיליון + // באותו כיוון עמוד, טווח עמודים ב-PDF חיצוני) רק מרסטר את המסמך שוב. Uint8List? _cachedBasePdf; String? _cachedBaseKey; - /// חתימת כל הפרמטרים שמשפיעים על תוכן ה-base PDF. שדות שמשפיעים רק על - /// הרסטור (_pagesPerSheet, טווח עמודים ב-PDF חיצוני) בכוונה אינם נכללים. - String _baseCacheKey(PdfPageFormat format) { + /// חתימת כל הפרמטרים שמשפיעים על תוכן ה-base PDF. מספר העמודים בגיליון + /// נכלל רק דרך גודל עמוד הטקסט, וטווח עמודים ב-PDF חיצוני בכוונה אינו נכלל. + String _baseCacheKey( + PdfPageFormat format, { + PdfPageFormat? sourceFormat, + }) { if (_isPdfSource) { return 'override|${identityHashCode(widget.createPdfOverride)}|${orientation.name}|${format.width}x${format.height}'; } + final source = sourceFormat ?? _sourcePageFormat(format); final holyNames = _shouldReplaceHolyNames; return [ identityHashCode(_dataFuture), identityHashCode(widget.prebuiltBlocks), - orientation.name, - format.width, - format.height, + source.width, + source.height, pageMargin, fontSize, fontName, @@ -852,8 +868,10 @@ class _PrintingScreenState extends State { Future _createBasePdf(PdfPageFormat format) async { final path = widget.pdfFilePath; if (path != null) return PrintPdfSource.file(path); + // כיוון עמוד המקור חייב להתאים למשימה גם כשההגדרות משתנות בזמן הטעינה. + final sourceFormat = _sourcePageFormat(format); await _divineNamesReady; - final key = _baseCacheKey(format); + final key = _baseCacheKey(format, sourceFormat: sourceFormat); final cached = _cachedBasePdf; if (cached != null && _cachedBaseKey == key) { return PrintPdfSource.data(cached); @@ -866,7 +884,7 @@ class _PrintingScreenState extends State { : format; bytes = await override(effectiveFormat); } else { - bytes = await createPdf(format); + bytes = await createPdf(format, sourceFormat: sourceFormat); } if (mounted && !_preview.isStopped && _baseCacheKey(format) == key) { _cachedBasePdf = bytes; @@ -966,14 +984,15 @@ class _PrintingScreenState extends State { } } - Future createPdf(PdfPageFormat format) async { + Future createPdf( + PdfPageFormat format, { + PdfPageFormat? sourceFormat, + }) async { + format = sourceFormat ?? _sourcePageFormat(format); if (widget.prebuiltBlocks != null) { return _createPrebuiltPdf(format); } String dataString = await _dataFuture; - if (orientation == pw.PageOrientation.landscape) { - format = format.landscape; - } final shouldReplaceHolyNames = _shouldReplaceHolyNames; @@ -1015,9 +1034,6 @@ class _PrintingScreenState extends State { /// יוצר PDF מבלוקים מוכנים מראש (כרטיסיית מפרשים). Future _createPrebuiltPdf(PdfPageFormat format) async { - if (orientation == pw.PageOrientation.landscape) { - format = format.landscape; - } final bookName = widget.documentTitle ?? widget.bookId; final blocks = _mapPrebuiltBlocks(widget.prebuiltBlocks ?? const []); return _renderBlocksToPdf( diff --git a/test/printing/printing_screen_output_test.dart b/test/printing/printing_screen_output_test.dart index 703387d751..3388290423 100644 --- a/test/printing/printing_screen_output_test.dart +++ b/test/printing/printing_screen_output_test.dart @@ -1,13 +1,23 @@ import 'dart:async'; +import 'dart:ffi' hide Size; import 'dart:io'; import 'package:bloc_test/bloc_test.dart'; +import 'package:otzaria/book_protection/models/book_protection.dart'; +import 'package:otzaria/divine_names/models/divine_name_spans.dart'; +import 'package:otzaria/divine_names/repository/divine_names_repository.dart'; +import 'package:otzaria/models/books.dart'; +import 'package:otzaria/text_book/models/book_notes.dart'; +import 'package:otzaria/text_book/repository/book_notes_repository.dart'; +import 'package:ffi/ffi.dart' show using; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:otzaria/settings/engine/app_settings_store.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/printing/print_content_models.dart'; import 'package:otzaria/printing/view/printing_screen.dart'; +import 'package:otzaria/printing/view/widgets/printing_widgets.dart'; import 'package:otzaria/settings/engine/settings_bloc.dart'; import 'package:otzaria/settings/engine/settings_event.dart'; import 'package:otzaria/settings/engine/settings_repository.dart'; @@ -15,6 +25,7 @@ import 'package:otzaria/settings/engine/settings_state.dart'; import 'package:otzaria/widgets/misc/app_menu_exports.dart'; import 'package:pdf/pdf.dart' hide PdfDocument; import 'package:pdf/widgets.dart' as pw; +import 'package:pdfium_dart/pdfium_dart.dart' as pdfium_bindings; import 'package:pdfrx/pdfrx.dart'; import 'package:printing/printing.dart'; // ignore: implementation_imports @@ -94,6 +105,90 @@ Future _settle(WidgetTester tester, Future future) async { return result; } +typedef _Placement = ({Size page, Size cell}); + +/// גודל כל עמוד בגיליון הראשון של התצוגה המקדימה, ושל התא שהוא ממורכז בו. +List<_Placement> _previewFirstSheet(WidgetTester tester, int cells) => [ + for (var i = 0; i < cells; i++) + ( + page: tester.getSize(find.byType(RawImage).at(i)), + cell: tester.getSize( + find + .ancestor( + of: find.byType(RawImage).at(i), + matching: find.byType(Center), + ) + .first, + ), + ), +]; + +/// גודל כל עמוד בגיליון הראשון של [pdf]. PDFium ממרכז את העמוד בתאו, ולכן +/// היסט המטריצה מקצה התא הוא הרווח הריק משני צדי העמוד. +Future> _pdfFirstSheet( + Uint8List pdf, + int rows, + int cols, +) async { + final doc = await PdfDocument.openData(pdf); + try { + final sheet = doc.pages.first.size; + final cell = Size(sheet.width / cols, sheet.height / rows); + return await doc.useNativeDocumentHandle((handle) { + final pdfium = pdfium_bindings.getPdfium( + modulePath: Pdfrx.pdfiumModulePath, + ); + final page = pdfium.FPDF_LoadPage( + pdfium_bindings.FPDF_DOCUMENT.fromAddress(handle), + 0, + ); + try { + return using((arena) { + final matrix = arena(); + final left = arena(); + final bottom = arena(); + final right = arena(); + final top = arena(); + final placements = <_Placement>[]; + for (var i = 0; i < pdfium.FPDFPage_CountObjects(page); i++) { + final object = pdfium.FPDFPage_GetObject(page, i); + if (pdfium.FPDFPageObj_GetType(object) != + pdfium_bindings.FPDF_PAGEOBJ_FORM || + pdfium.FPDFPageObj_GetMatrix(object, matrix) == 0 || + pdfium.FPDFPageObj_GetBounds( + object, + left, + bottom, + right, + top, + ) == + 0) { + continue; + } + // התא לפי מרכז התוכן; הרווח מקצה התא נמדד ממטריצת העמוד. + final col = ((left.value + right.value) / 2 / cell.width).floor(); + final row = ((bottom.value + top.value) / 2 / cell.height).floor(); + final sideGap = matrix.ref.e - col * cell.width; + final verticalGap = matrix.ref.f - row * cell.height; + placements.add(( + page: Size( + cell.width - 2 * sideGap, + cell.height - 2 * verticalGap, + ), + cell: cell, + )); + } + return placements; + }); + } finally { + pdfium.FPDF_ClosePage(page); + } + }); + } finally { + await doc.dispose(); + } +} + void main() { const pathProviderChannel = MethodChannel('plugins.flutter.io/path_provider'); final originalModulePath = Pdfrx.pdfiumModulePath; @@ -284,4 +379,295 @@ void main() { await tester.pumpWidget(const SizedBox()); await drainPrintingRasterQueue(tester); }, timeout: const Timeout(Duration(minutes: 2))); + + // עמוד הטקסט נוצר בכיוון התא שלו בגיליון, ולא בכיוון הגיליון: בשני עמודים + // לרוחב התאים לאורך. בגיליון לאורך התא צר, ועמוד לאורך ממלא רק את רוחבו. + for (final (pagesPerSheet, orientation, expected, commentaryTab) in [ + (2, pw.PageOrientation.portrait, 'portrait 1.00x0.50', false), + (2, pw.PageOrientation.landscape, 'portrait 1.00x1.00', false), + (4, pw.PageOrientation.landscape, 'landscape 1.00x1.00', false), + (2, pw.PageOrientation.landscape, 'portrait 1.00x1.00', true), + ]) { + testWidgets( + '${commentaryTab ? 'כרטיסיית המפרשים, ' : ''}$pagesPerSheet עמודים בגיליון ${orientation == pw.PageOrientation.landscape ? 'לרוחב' : 'לאורך'}: ' + 'עמוד הטקסט בכיוון התא, בתצוגה המקדימה ובפלט (issue #3184)', + (tester) async { + tester.view.physicalSize = const Size(1600, 1200); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final platform = _CapturingPrintingPlatform(); + PrintingPlatform.instance = platform; + final settingsBloc = _MockSettingsBloc(); + whenListen( + settingsBloc, + const Stream.empty(), + initialState: SettingsState.initial(), + ); + await tester.runAsync(pdfrxFlutterInitialize); + final lines = ['ספר', for (var i = 1; i <= 200; i++) 'שורה $i בספר']; + bool previewShows(int pages) => + find.byType(RawImage).evaluate().length >= pages && + find.byType(CircularProgressIndicator).evaluate().isEmpty; + Future waitForPreview(int pages) async { + await tester.pump(const Duration(milliseconds: 300)); + for (var i = 0; i < 400 && !previewShows(pages); i++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 25)), + ); + await tester.pump(); + } + expect(previewShows(pages), isTrue); + } + + Future setPagesPerSheet(int value) { + tester + .widget( + find.byType(PrintingPagesPerSheetDropdownRow), + ) + .onChanged(value); + return waitForPreview(value); + } + + await tester.pumpWidget( + RepositoryProvider.value( + value: _FakeSettingsRepository(), + child: BlocProvider.value( + value: settingsBloc, + child: MaterialApp( + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: const TextScaler.linear(0.5)), + child: child!, + ), + home: PrintingScreen( + data: Future.value(commentaryTab ? '' : lines.join('\n')), + bookId: 'test', + startLine: 1, + endLine: lines.length, + prebuiltBlocks: commentaryTab + ? [ + for (final line in lines) + PrintBlock( + kind: PrintBlockKind.commentary, + text: line, + ), + ] + : null, + ), + ), + ), + ), + ); + await waitForPreview(1); + tester + .widget( + find.byType(PrintingOrientationDropdownRow), + ) + .onChanged(orientation); + await waitForPreview(1); + // מספר העמודים בגיליון משתנה אחרי שהתצוגה בכיוון הזה כבר מוכנה. + await setPagesPerSheet(pagesPerSheet); + final preview = _previewFirstSheet(tester, pagesPerSheet); + + await tester.tap(find.text('הדפסה')); + await tester.pump(); + final output = await _settle( + tester, + Future.value(platform.onLayout!(PdfPageFormat.a4)), + ); + platform.job.complete(false); + await tester.pump(); + final rows = pagesPerSheet == 4 ? 2 : 1; + final saved = await _settle( + tester, + _pdfFirstSheet(output, rows, pagesPerSheet ~/ rows), + ); + // כיוון העמוד, והחלק שהוא ממלא מרוחב התא ומגובהו. + String fit(_Placement p) => + '${p.page.width > p.page.height ? 'landscape' : 'portrait'} ' + '${(p.page.width / p.cell.width).toStringAsFixed(2)}x' + '${(p.page.height / p.cell.height).toStringAsFixed(2)}'; + expect( + { + 'preview': [...preview.map(fit)], + 'pdf': [...saved.map(fit)], + }, + { + 'preview': List.filled(pagesPerSheet, expected), + 'pdf': List.filled(pagesPerSheet, expected), + }, + ); + + // בחזרה לעמוד אחד בגיליון העמוד שוב בכיוון הגיליון. + await setPagesPerSheet(1); + final single = tester.getSize(find.byType(RawImage).first); + expect( + single.width > single.height, + orientation == pw.PageOrientation.landscape, + ); + + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpWidget(const SizedBox()); + await drainPrintingRasterQueue(tester); + }, + timeout: const Timeout(Duration(minutes: 2)), + ); + } + for (final prebuilt in [false, true]) { + for (final initialPages in [1, 2]) { + testWidgets( + 'שינוי מ-$initialPages ל-${3 - initialPages} עמודים בזמן טעינת נתוני ${prebuilt ? 'מפרשים' : 'טקסט'} שומר את כיוון המשימה', + (tester) async { + tester.view.physicalSize = const Size(1600, 1200); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final pendingNames = Completer(); + addTearDown(() { + if (!pendingNames.isCompleted) { + pendingNames.complete(DivineNameSpans.empty); + } + }); + final lines = ['ספר', for (var i = 1; i <= 100; i++) 'שורת בדיקה $i']; + DivineNamesRepository.instance.clear(); + BookNotesRepository.instance.clear(); + DivineNamesRepository.instance.debugLoader = + ( + title, { + categoryId, + required source, + }) => pendingNames.future; + BookNotesRepository.instance.debugLoader = + ( + title, { + categoryId, + required source, + }) async => BookNotes.empty; + addTearDown(() { + DivineNamesRepository.instance + ..debugLoader = null + ..clear(); + BookNotesRepository.instance + ..debugLoader = null + ..clear(); + }); + final platform = _CapturingPrintingPlatform(); + PrintingPlatform.instance = platform; + addTearDown(() async { + if (!platform.job.isCompleted) platform.job.complete(false); + await tester.pumpWidget(const SizedBox()); + await drainPrintingRasterQueue(tester); + }); + final settingsBloc = _MockSettingsBloc(); + whenListen( + settingsBloc, + const Stream.empty(), + initialState: SettingsState.initial(), + ); + await tester.runAsync(pdfrxFlutterInitialize); + await tester.pumpWidget( + RepositoryProvider.value( + value: _FakeSettingsRepository(), + child: BlocProvider.value( + value: settingsBloc, + child: MaterialApp( + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: const TextScaler.linear(0.5)), + child: child!, + ), + home: PrintingScreen( + data: Future.value(lines.join('\n')), + prebuiltBlocks: prebuilt + ? [ + for (final line in lines) + PrintBlock( + kind: PrintBlockKind.commentary, + text: line, + ), + ] + : null, + startLine: 1, + endLine: 101, + bookId: 'ספר בדיקה', + book: TextBook(title: 'ספר בדיקה'), + protection: BookProtection.none, + ), + ), + ), + ), + ); + await tester.pump(); + tester + .widget( + find.byType(PrintingOrientationDropdownRow), + ) + .onChanged(pw.PageOrientation.landscape); + void setPages(int value) => tester + .widget( + find.byType(PrintingPagesPerSheetDropdownRow), + ) + .onChanged(value); + setPages(initialPages); + await tester.pump(const Duration(milliseconds: 300)); + await tester.tap(find.text('הדפסה')); + await tester.pump(); + expect(platform.onLayout, isNotNull); + var outputReady = false; + final pendingOutput = Future.value( + platform.onLayout!(PdfPageFormat.a4), + )..then((_) => outputReady = true); + await tester.pump(const Duration(milliseconds: 50)); + expect( + outputReady, + isFalse, + reason: 'נתוני הספר עדיין ממתינים בזמן שינוי ההגדרות.', + ); + setPages(3 - initialPages); + await tester.pump(const Duration(milliseconds: 300)); + expect(outputReady, isFalse); + pendingNames.complete(DivineNameSpans.empty); + final output = await _settle(tester, pendingOutput); + platform.job.complete(false); + await tester.pump(); + Future expectGeometry(Uint8List bytes, int pages) async { + final document = await _settle(tester, PdfDocument.openData(bytes)); + final sheet = document.pages.first.size; + await _settle(tester, document.dispose()); + expect(sheet.width, closeTo(PdfPageFormat.a4.landscape.width, 0.1)); + expect( + sheet.height, + closeTo(PdfPageFormat.a4.landscape.height, 0.1), + ); + if (pages == 2) { + final placements = await _settle( + tester, + _pdfFirstSheet(bytes, 1, 2), + ); + expect(placements, hasLength(2)); + for (final placement in placements) { + expect( + placement.page.width, + closeTo(placement.cell.width, 0.1), + ); + expect( + placement.page.height, + closeTo(placement.cell.height, 0.1), + ); + } + } + } + + await expectGeometry(output, initialPages); + final nextOutput = await _settle( + tester, + Future.value(platform.onLayout!(PdfPageFormat.a4)), + ); + await expectGeometry(nextOutput, 3 - initialPages); + }, + timeout: const Timeout(Duration(minutes: 2)), + ); + } + } }