diff --git a/.github/workflows/pdf_file_export.yml b/.github/workflows/pdf_file_export.yml new file mode 100644 index 0000000000..ce291c200e --- /dev/null +++ b/.github/workflows/pdf_file_export.yml @@ -0,0 +1,111 @@ +name: PDF file export (Windows and macOS) + +on: + pull_request: + paths: + - 'lib/printing/**' + - 'lib/utils/file/atomic_file_publication.dart' + - 'lib/utils/file/file_publication_permissions.dart' + - 'lib/utils/file/file_publication_rename.dart' + - 'lib/utils/file/desktop_save_target.dart' + - 'lib/utils/file/save_target_name.dart' + - 'lib/utils/file/file_picker_dialog_options.dart' + - 'lib/plugins/bridge/plugin_save_target.dart' + - 'test/printing/pdf_export_cancellation_test.dart' + - 'test/printing/pdf_file_*_test.dart' + - 'test/printing/print_pdf_*_test.dart' + - 'test/printing/pdf_sheet_*_test.dart' + - 'test/printing/printing_screen_file_export_test.dart' + - 'test/utils/file/atomic_file_publication_test.dart' + - 'test/utils/file/desktop_save_target_test.dart' + - 'test/utils/file/save_target_name_test.dart' + - 'test/helpers/printing_raster_idle.dart' + - 'fonts/Tinos-Regular.ttf' + - 'fonts/NotoSerifHebrew-VariableFont_wdth,wght.ttf' + - 'pubspec.yaml' + - 'pubspec.lock' + - '.github/workflows/pdf_file_export.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: pdf-file-export-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + gate: + uses: ./.github/workflows/ci_gate.yml + permissions: + contents: read + pull-requests: read + + export: + name: Native PDF files / ${{ matrix.platform }} + needs: gate + if: needs.gate.outputs.run == 'true' + strategy: + fail-fast: false + matrix: + include: + - platform: windows + runner: windows-2025 + - platform: macos + runner: macos-latest + runs-on: ${{ matrix.runner }} + timeout-minutes: 45 + env: + BOT: 'true' + CI: 'true' + FLUTTER_SUPPRESS_ANALYTICS: 'true' + DART_SUPPRESS_ANALYTICS: 'true' + OTZARIA_REQUIRE_SEARCH_ENGINE: '1' + CARGO_BUILD_JOBS: '2' + steps: + - uses: actions/checkout@v7.0.1 + - uses: subosito/flutter-action@v2 + with: + channel: stable + flutter-version: 3.47.7 + cache: false + - uses: dtolnay/rust-toolchain@stable + - name: Allow long dependency paths on Windows + if: runner.os == 'Windows' + shell: pwsh + run: git config --global core.longpaths true + - name: Resolve the locked dependencies + run: flutter pub get --enforce-lockfile + - name: Record the actual Flutter SDK + run: flutter --version --machine > pdf-file-export-flutter.json + - name: Record the tested source and tree + run: git rev-parse HEAD 'HEAD^{tree}' > pdf-file-export-source.txt + - name: Test file ownership, publication, native content and export UI + timeout-minutes: 25 + run: >- + flutter test --no-pub --concurrency=1 --reporter expanded + --file-reporter json:pdf-file-export-tests.jsonl + test/printing/pdf_export_cancellation_test.dart + test/printing/pdf_file_cleanup_test.dart + test/printing/pdf_file_stream_test.dart + test/printing/print_pdf_file_cache_test.dart + test/printing/print_pdf_source_io_test.dart + test/printing/pdf_file_native_test.dart + test/printing/print_pdf_source_test.dart + test/printing/pdf_sheet_composer_test.dart + test/printing/pdf_sheet_file_output_test.dart + test/printing/printing_screen_file_export_test.dart + test/utils/file/atomic_file_publication_test.dart + test/utils/file/desktop_save_target_test.dart + test/utils/file/save_target_name_test.dart + - name: Preserve test results and toolchain identity + if: always() + uses: actions/upload-artifact@v7.0.2 + with: + name: pdf-file-export-${{ matrix.platform }} + if-no-files-found: warn + retention-days: 14 + path: | + pdf-file-export-flutter.json + pdf-file-export-source.txt + pdf-file-export-tests.jsonl diff --git a/lib/printing/view/printing_screen.dart b/lib/printing/view/printing_screen.dart index 7ed16521ff..d365dbf5e3 100644 --- a/lib/printing/view/printing_screen.dart +++ b/lib/printing/view/printing_screen.dart @@ -5,7 +5,8 @@ import 'dart:isolate'; import 'dart:math'; import 'package:flutter/material.dart'; -import 'package:flutter/foundation.dart' show mapEquals, visibleForTesting; +import 'package:flutter/foundation.dart' + show listEquals, mapEquals, visibleForTesting; import 'package:fluentui_system_icons/fluentui_system_icons.dart'; import 'package:flutter/services.dart'; import 'package:otzaria/settings/engine/app_settings_store.dart'; @@ -30,6 +31,10 @@ import 'package:otzaria/printing/serial_latest_runner.dart'; import 'package:otzaria/printing/printing_helpers.dart'; import 'package:otzaria/printing/pdf_sheet_composer.dart'; import 'package:otzaria/printing/print_pdf_source.dart'; +import 'package:otzaria/printing/pdf_file_stream.dart'; +import 'package:otzaria/printing/pdf_file_cleanup.dart'; +import 'package:otzaria/printing/print_pdf_file_cache.dart'; +import 'package:otzaria/printing/pdf_export_cancellation.dart'; import 'package:otzaria/printing/print_preview_controller.dart'; import 'package:opentype_shaper/opentype_shaper.dart'; import 'package:otzaria/printing/shaped_text/pdf_shaped_font.dart'; @@ -45,6 +50,8 @@ import 'package:otzaria/printing/safer_print_service.dart'; import 'package:otzaria/printing/view/slow_preview_hint.dart'; import 'package:otzaria/printing/word_export_service.dart'; import 'package:otzaria/utils/file/save_file_with_extension.dart'; +import 'package:otzaria/utils/file/desktop_save_target.dart'; +import 'package:otzaria/utils/file/atomic_file_publication.dart'; import 'package:otzaria/utils/text/text_manipulation.dart'; import 'package:otzaria/widgets/controls/action_buttons.dart'; import 'package:otzaria/widgets/dialogs/app_dialog_frame.dart'; @@ -65,6 +72,29 @@ import 'package:otzaria/widgets/feedback/loading_indicator.dart'; enum _AnchorKind { header, altHeader, line } +/// A source borrowed by one preview or output operation. Generated files stay +/// alive until their final borrower has closed all native documents. +class _PrintBaseLease { + const _PrintBaseLease(this.source, [this._release]); + + final PrintPdfSource source; + final Future Function()? _release; + + Future dispose() => _release?.call() ?? Future.value(); +} + +/// Captured before opening the target chooser; preview metadata arriving later +/// must not change the requested range or sheet arrangement. +typedef _PdfFileExport = ({ + PdfPageFormat format, + PdfPageFormat sheetFormat, + int pagesPerSheet, + int startPage, + int? endPage, + bool hasPageRange, + String signature, +}); + /// פריסת מסך ההדפסה: התצוגה המקדימה, ולצידה חלונית ההגדרות ברוחב קבוע עם /// שורת הפעולות. במסך צר החלונית היא החצי התחתון, כדי שהתצוגה לא תתכווץ. class _PrintLayout extends StatelessWidget { @@ -73,12 +103,14 @@ class _PrintLayout extends StatelessWidget { required this.preview, required this.settings, required this.footer, + required this.settingsEnabled, }); final bool narrow; final Widget preview; final List settings; final Widget footer; + final bool settingsEnabled; @override Widget build(BuildContext context) { @@ -86,11 +118,17 @@ class _PrintLayout extends StatelessWidget { crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Expanded( - child: SingleChildScrollView( - padding: const EdgeInsets.all(16), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: settings, + child: IgnorePointer( + ignoring: !settingsEnabled, + child: ExcludeFocus( + excluding: !settingsEnabled, + child: SingleChildScrollView( + padding: const EdgeInsets.all(16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: settings, + ), + ), ), ), ), @@ -202,8 +240,12 @@ class PrintingScreen extends StatefulWidget { /// Completes after currently queued native printing work, including disposal. /// Widget tests must unmount their screens before awaiting this barrier. @visibleForTesting - static Future get debugRasterIdle => - _PrintingScreenState._rasterLock ?? Future.value(); + static Future get debugRasterIdle async { + await Future.wait([ + ?_PrintingScreenState._rasterLock, + ..._PrintingScreenState._fileCleanups, + ]); + } @override State createState() => _PrintingScreenState(); @@ -255,6 +297,9 @@ class _PrintingScreenState extends State { int _renderGeneration = 0; // מונה שביטול renders ישנים // נעילה סדרתית של פעולות pdfrx: שני openData במקביל תוקעים את הספרייה. static Future? _rasterLock; + static final _fileCleanups = >{}; + final _basePdfFiles = PrintPdfFileCache(); + _PrintBaseLease? _previewBaseLease; // הסדרת התצוגות המקדימות: render כבד אחד בכל רגע, ודילוג על render שהתיישן // בזמן ההמתנה בתור, כדי ששינויי פרמטרים עוקבים לא יריצו במקביל מספר יצירות // base PDF / רסטור ניקוד / isolate שמציפים את המעבד. @@ -276,6 +321,8 @@ class _PrintingScreenState extends State { /// עבודת הדפסה בתהליך: ציור והעברה למדפסת יכולים לקחת דקות. String? _printProgress; bool get _isPrinting => _printProgress != null; + bool _destinationActionPending = false; + PdfExportCancellationToken? _exportCancellation; Timer? _previewRefreshTimer; // נקודות הקצה של טווח ההדפסה — כל אחת עצמאית בסוגה (כותרת/כותרת משנה/שורה). @@ -476,17 +523,26 @@ class _PrintingScreenState extends State { @override void didUpdateWidget(covariant PrintingScreen oldWidget) { super.didUpdateWidget(oldWidget); - if (oldWidget.activeCommentators != widget.activeCommentators) { + final commentatorsChanged = !listEquals( + oldWidget.activeCommentators, + widget.activeCommentators, + ); + if (commentatorsChanged) { _selectedCommentators = List.of(widget.activeCommentators); } if (oldWidget.pdfFilePath != widget.pdfFilePath || oldWidget.createPdfOverride != widget.createPdfOverride || (!_isPdfSource && oldWidget.data != widget.data) || - oldWidget.prebuiltBlocks != widget.prebuiltBlocks) { + oldWidget.prebuiltBlocks != widget.prebuiltBlocks || + oldWidget.bookId != widget.bookId || + oldWidget.documentTitle != widget.documentTitle || + commentatorsChanged) { _dataFuture = widget.data; _cachedBasePdf = null; _cachedBaseKey = null; _pendingBasePdfs.clear(); + _basePdfFiles.invalidate(); + _exportCancellation?.cancel(); _anchorEntries = null; _totalPdfPages = 0; if (_isPdfSource) { @@ -498,6 +554,7 @@ class _PrintingScreenState extends State { } else { _renderGeneration++; _preview.reset(pagesPerSheet: _pagesPerSheet); + _releasePreviewBase(); _initPreviewRange(); } } @@ -651,11 +708,46 @@ class _PrintingScreenState extends State { _onThumbnailScroll, ); _preview.dispose(); + _releasePreviewBase(); + _exportCancellation?.dispose(); + _trackFileCleanup(_basePdfFiles.dispose()); _cachedBasePdf = null; _pendingBasePdfs.clear(); super.dispose(); } + static void _trackFileCleanup(Future cleanup) { + _fileCleanups.add(cleanup); + unawaited( + cleanup.then( + (_) { + _fileCleanups.remove(cleanup); + }, + onError: (Object error, StackTrace stack) { + _fileCleanups.remove(cleanup); + FlutterError.reportError( + FlutterErrorDetails( + exception: error, + stack: stack, + library: 'printing', + context: ErrorDescription('while releasing a temporary PDF'), + ), + ); + }, + ), + ); + } + + void _releasePreviewBase() { + final previous = _previewBaseLease; + _previewBaseLease = null; + if (previous != null) { + // stop/reset has already removed the source from the controller. Work + // queued earlier must finish closing PDFium before its file is removed. + _trackFileCleanup(_withRasterLock(previous.dispose, 'source-release')); + } + } + Set _visibleSheets(ItemPositionsListener listener) => listener .itemPositions .value @@ -705,8 +797,13 @@ class _PrintingScreenState extends State { void _refreshPreview({bool immediate = false}) { if (!mounted || _preview.isStopped) return; + // A text generator reads settings while preparing asynchronous content. + // Even A -> B -> A must start a new owner generation after a real edit; + // callers requesting the same unchanged settings still share one producer. + if (!_isPdfSource) _basePdfFiles.invalidate(); _renderGeneration++; _preview.reset(pagesPerSheet: _pagesPerSheet); + _releasePreviewBase(); _previewRefreshTimer?.cancel(); if (immediate) { _renderPreview(); @@ -722,6 +819,7 @@ class _PrintingScreenState extends State { final generation = ++_renderGeneration; _currentPreviewItem = 0; _preview.reset(pagesPerSheet: _pagesPerSheet); + _releasePreviewBase(); _previewRunner.run( isStale: () => !mounted || generation != _renderGeneration, task: () => _renderPreviewTask(generation), @@ -734,9 +832,13 @@ class _PrintingScreenState extends State { if (stale()) return false; try { final base = await _createBasePdf(format); - if (stale()) return false; + if (stale()) { + await base.dispose(); + return false; + } + _previewBaseLease = base; await _preview.load( - base, + base.source, startPage: _isPdfSource ? _pdfStartPage : 1, endPage: computePdfPrintEndPage( isPdfMode: _isPdfSource, @@ -791,31 +893,129 @@ class _PrintingScreenState extends State { ); final base = await _createBasePdf(format); - if (pagesPerSheet <= 1 && !hasPageRange) { - return base.readBytes(); - } + return withPdfFileCleanup(() async { + if (pagesPerSheet <= 1 && !hasPageRange) { + return base.source.readBytes(); + } + try { + return await _createNUpPdf( + base.source, + sheetFormat: sheetFormat, + pagesPerSheet: pagesPerSheet, + startPage: startPage, + endPage: endPage, + ); + } catch (e, st) { + debugPrint('[PRINT] N-up failed: $e\n$st'); + if (mounted) { + UiSnack.showError( + hasPageRange + ? PdfMessages.pageRangeRenderFailed + : PdfMessages.multiPageSheetRenderFailed, + ); + } + rethrow; + } + }, base.dispose); + } - try { - return await _createNUpPdf( - base, - sheetFormat: sheetFormat, - pagesPerSheet: pagesPerSheet, + String _exportSignature(PdfPageFormat format) => + '${widget.pdfFilePath}|${_baseCacheKey(format)}'; + + _PdfFileExport _captureFileExport() { + final isPdfMode = _isPdfSource; + final startPage = isPdfMode ? _pdfStartPage : 1; + final endPage = computePdfPrintEndPage( + isPdfMode: isPdfMode, + pdfEndPage: _pdfEndPage, + totalPdfPages: _totalPdfPages, + ); + return ( + format: format, + sheetFormat: _effectivePageFormat(format), + pagesPerSheet: _pagesPerSheet, + startPage: startPage, + endPage: endPage, + hasPageRange: hasPdfPageRange( startPage: startPage, endPage: endPage, - ); - } catch (e, st) { - debugPrint('[PRINT] N-up failed: $e\n$st'); - if (mounted) { - UiSnack.showError( - hasPageRange - ? PdfMessages.pageRangeRenderFailed - : PdfMessages.multiPageSheetRenderFailed, - ); - } - rethrow; + totalPages: _totalPdfPages, + ), + signature: _exportSignature(format), + ); + } + + bool _fileExportCancelled( + _PdfFileExport plan, + PdfExportCancellationToken cancellation, + ) => + !mounted || + cancellation.isCancelled || + _exportSignature(plan.format) != plan.signature; + + void _checkFileExport( + _PdfFileExport plan, + PdfExportCancellationToken cancellation, + ) { + if (_fileExportCancelled(plan, cancellation)) { + throw const PdfExportCancelledException(); } } + Future _writeOutputPdfToFile( + _PdfFileExport plan, + PdfExportCancellationToken cancellation, + String stagingPath, + ) async { + _checkFileExport(plan, cancellation); + final base = await _createBasePdf(plan.format); + await withPdfFileCleanup(() async { + _checkFileExport(plan, cancellation); + if (plan.pagesPerSheet <= 1 && !plan.hasPageRange) { + final lease = cancellation.acquire(); + try { + await base.source.writeToFile( + stagingPath, + cancellationAddress: lease.address, + ); + } finally { + lease.dispose(); + } + } else { + await _withRasterLock(() async { + _checkFileExport(plan, cancellation); + final doc = await base.source.open(useProgressiveLoading: true); + await withPdfFileCleanup(() async { + _checkFileExport(plan, cancellation); + final pageCount = doc.pages.length; + final firstIndex = max(0, min(plan.startPage - 1, pageCount - 1)); + final lastIndex = max( + firstIndex, + min((plan.endPage ?? pageCount) - 1, pageCount - 1), + ); + final (rows, cols) = switch (plan.pagesPerSheet) { + 2 => (1, 2), + 4 => (2, 2), + _ => (1, 1), + }; + await composePdfSheetsToFile( + doc, + outputPath: stagingPath, + firstIndex: firstIndex, + lastIndex: lastIndex, + rows: rows, + cols: cols, + sheetWidth: plan.sheetFormat.width, + sheetHeight: plan.sheetFormat.height, + cancellationToken: cancellation, + ); + }, doc.dispose); + }, 'export-file'); + } + _checkFileExport(plan, cancellation); + }, base.dispose); + } + PdfPageFormat _effectivePageFormat(PdfPageFormat format) { return orientation == pw.PageOrientation.landscape ? format.landscape @@ -849,6 +1049,8 @@ class _PrintingScreenState extends State { return [ identityHashCode(_dataFuture), identityHashCode(widget.prebuiltBlocks), + widget.bookId, + widget.documentTitle, source.width, source.height, pageMargin, @@ -872,26 +1074,31 @@ class _PrintingScreenState extends State { ].join('|'); } - Future _createBasePdf(PdfPageFormat format) async { + Future<_PrintBaseLease> _createBasePdf(PdfPageFormat format) async { final path = widget.pdfFilePath; - if (path != null) return PrintPdfSource.file(path); + if (path != null) return _PrintBaseLease(PrintPdfSource.file(path)); // כיוון עמוד המקור חייב להתאים למשימה גם כשההגדרות משתנות בזמן הטעינה. final sourceFormat = _sourcePageFormat(format); await _divineNamesReady; final key = _baseCacheKey(format, sourceFormat: sourceFormat); + final override = widget.createPdfOverride; + if (override == null) { + final lease = await _basePdfFiles.acquire(key, (path) async { + await _createTextPdf( + format, + sourceFormat: sourceFormat, + outputPath: path, + ); + }); + return _PrintBaseLease(lease.source, lease.dispose); + } + final effectiveFormat = _effectivePageFormat(format); final cached = _cachedBasePdf; if (cached != null && _cachedBaseKey == key) { - return PrintPdfSource.data(cached); + return _PrintBaseLease(PrintPdfSource.data(cached)); } final pending = _pendingBasePdfs.putIfAbsent(key, () async { - final override = widget.createPdfOverride; - if (override != null) { - final effectiveFormat = orientation == pw.PageOrientation.landscape - ? format.landscape - : format; - return override(effectiveFormat); - } - return createPdf(format, sourceFormat: sourceFormat); + return override(effectiveFormat); }); try { final bytes = await pending; @@ -902,7 +1109,7 @@ class _PrintingScreenState extends State { _cachedBasePdf = bytes; _cachedBaseKey = key; } - return PrintPdfSource.data(bytes); + return _PrintBaseLease(PrintPdfSource.data(bytes)); } finally { if (identical(_pendingBasePdfs[key], pending)) { _pendingBasePdfs.remove(key); @@ -1004,10 +1211,16 @@ class _PrintingScreenState extends State { Future createPdf( PdfPageFormat format, { PdfPageFormat? sourceFormat, + }) async => (await _createTextPdf(format, sourceFormat: sourceFormat))!; + + Future _createTextPdf( + PdfPageFormat format, { + PdfPageFormat? sourceFormat, + String? outputPath, }) async { format = sourceFormat ?? _sourcePageFormat(format); if (widget.prebuiltBlocks != null) { - return _createPrebuiltPdf(format); + return _createPrebuiltPdf(format, outputPath: outputPath); } String dataString = await _dataFuture; @@ -1046,11 +1259,15 @@ class _PrintingScreenState extends State { bookName: bookName, pageMargin: pageMargin, fontSize: fontSize, + outputPath: outputPath, ); } /// יוצר PDF מבלוקים מוכנים מראש (כרטיסיית מפרשים). - Future _createPrebuiltPdf(PdfPageFormat format) async { + Future _createPrebuiltPdf( + PdfPageFormat format, { + String? outputPath, + }) async { final bookName = widget.documentTitle ?? widget.bookId; final blocks = _mapPrebuiltBlocks(widget.prebuiltBlocks ?? const []); return _renderBlocksToPdf( @@ -1059,6 +1276,7 @@ class _PrintingScreenState extends State { bookName: bookName, pageMargin: pageMargin, fontSize: fontSize, + outputPath: outputPath, ); } @@ -1196,12 +1414,13 @@ class _PrintingScreenState extends State { /// מרנדר רשימת בלוקים (ייצוג פנימי) ל-PDF — משותף למצב הרגיל ולמצב הבלוקים /// המוכנים מראש. - Future _renderBlocksToPdf({ + Future _renderBlocksToPdf({ required List> blocks, required PdfPageFormat format, required String bookName, required double pageMargin, required double fontSize, + String? outputPath, }) async { final primaryBytes = await _loadPrintFont(fontName); final fallbackBytes = (await rootBundle.load( @@ -1380,6 +1599,10 @@ class _PrintingScreenState extends State { ), ); + if (outputPath != null) { + await writePdfDocumentToFile(pdfData, outputPath); + return null; + } return await pdfData.save(); }, ), @@ -1720,19 +1943,43 @@ class _PrintingScreenState extends State { /// מבצע את הפעולה לפי היעד הנבחר: הדפסה למדפסת, או שמירה ל-PDF/Word. Future _performDestinationAction(BuildContext context) async { + // Guard before the first await, including the protection/password dialogs. + if (_destinationActionPending) return; + final requested = _destination; + final route = ModalRoute.of(context); + if (route != null) dismissAnchoredAppMenus(route); + final cancellation = requested == _PrintDestination.printer + ? null + : PdfExportCancellationToken(); + setState(() { + _destinationActionPending = true; + _exportCancellation = cancellation; + }); + try { + await _performDestinationActionChecked(context, requested); + } finally { + cancellation?.dispose(); + _exportCancellation = null; + if (mounted) setState(() => _destinationActionPending = false); + } + } + + Future _performDestinationActionChecked( + BuildContext context, + _PrintDestination requested, + ) async { try { await _protectionReady; } catch (error) { debugPrint('Print protection lookup failed: $error'); } - if (!mounted || !context.mounted) return; - final requested = _destination; + if (!mounted || !context.mounted || _preview.isStopped) return; if (_includeCommentaries && widget.prebuiltBlocks == null) { await _loadCommentaryProtection( await _loadLinksForPrintRange(startLine, endLine), ); } - if (!mounted || !context.mounted) return; + if (!mounted || !context.mounted || _preview.isStopped) return; setState(_syncDestinationWithProtection); // יעד שנחסם אחרי הבחירה — הרשימה התעדכנה, והמשתמש יבחר שוב. if (_destination != requested) { @@ -1813,10 +2060,38 @@ class _PrintingScreenState extends State { } Future _saveToFile(_ExportFormat selectedFormat) async { + final cancellation = _exportCancellation!; if (!await verifySaferModePassword(context)) return false; - if (!mounted) return false; + if (!mounted || cancellation.isCancelled) return false; try { final selectedExtension = selectedFormat.extension; + final fileName = '${_sanitizeFileName(widget.bookId)}.$selectedExtension'; + if (selectedFormat == _ExportFormat.pdf && + (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) { + await _divineNamesReady; + if (!mounted || cancellation.isCancelled) return false; + final plan = _captureFileExport(); + final target = await chooseDesktopSaveTarget( + context: context, + dialogTitle: 'ייצוא קובץ', + fileName: fileName, + extension: selectedExtension, + isCancelled: () => _fileExportCancelled(plan, cancellation), + ); + if (target == null || _fileExportCancelled(plan, cancellation)) { + return false; + } + final saved = await publishFileAtomically( + target: target, + isCancelled: () => _fileExportCancelled(plan, cancellation), + producer: (path) => _writeOutputPdfToFile(plan, cancellation, path), + ); + if (saved && mounted) UiSnack.showSuccess(PdfMessages.pdfFileSaved); + return saved; + } + + // Printing.onLayout, Word and mobile file-provider APIs still require + // complete bytes. Keep those public contracts on their existing path. final Uint8List bytes; final String successMessage; if (selectedFormat == _ExportFormat.word) { @@ -1835,18 +2110,21 @@ class _PrintingScreenState extends State { bytes = await _createOutputPdf(format); successMessage = PdfMessages.pdfFileSaved; } - if (!mounted) return false; + if (!mounted || cancellation.isCancelled) return false; final path = await saveFileWithExtension( context: context, dialogTitle: 'ייצוא קובץ', - fileName: '${_sanitizeFileName(widget.bookId)}.$selectedExtension', + fileName: fileName, extension: selectedExtension, bytes: bytes, ); if (path == null) return false; - UiSnack.showSuccess(successMessage); + if (mounted) UiSnack.showSuccess(successMessage); return true; + } on PdfExportCancelledException { + return false; } on FileSystemException catch (e) { + if (!mounted || cancellation.isCancelled) return false; if (_isLockedFileException(e)) { UiSnack.showError(PdfMessages.fileLockedByAnotherApp); return false; @@ -1854,6 +2132,7 @@ class _PrintingScreenState extends State { UiSnack.showError(PdfMessages.fileExportFailed(e.message)); return false; } catch (e) { + if (!mounted || cancellation.isCancelled) return false; UiSnack.showError(PdfMessages.fileExportFailed(e)); return false; } @@ -2103,6 +2382,7 @@ class _PrintingScreenState extends State { if (isCustomPdfMode) { return _PrintLayout( narrow: _isNarrowLayout(context), + settingsEnabled: _exportCancellation == null, preview: _buildImagePreview(colorScheme), settings: _buildCustomPdfSettings(colorScheme), footer: _buildPrintExportFooter(context), @@ -2113,6 +2393,7 @@ class _PrintingScreenState extends State { final totalLines = _lineCounts.of(snapshot.data!); return _PrintLayout( narrow: _isNarrowLayout(context), + settingsEnabled: _exportCancellation == null, preview: _buildImagePreview(colorScheme), settings: _buildTextSettings( colorScheme, @@ -2139,6 +2420,8 @@ class _PrintingScreenState extends State { _renderGeneration++; _previewRefreshTimer?.cancel(); _preview.stop(); + _releasePreviewBase(); + _exportCancellation?.cancel(); }, child: dialog, ); @@ -2546,9 +2829,13 @@ class _PrintingScreenState extends State { ), const SizedBox(width: 8), Expanded( - child: _isPrinting + child: _destinationActionPending ? ActionButton.recommended( - text: _printProgress!, + text: + _printProgress ?? + (_exportCancellation != null + ? 'שומר קובץ...' + : PdfMessages.printPreparing), iconWidget: SizedBox.square( dimension: 16, child: CircularProgressIndicator(strokeWidth: 2), diff --git a/test/printing/printing_screen_file_export_test.dart b/test/printing/printing_screen_file_export_test.dart new file mode 100644 index 0000000000..bbab9f1f5e --- /dev/null +++ b/test/printing/printing_screen_file_export_test.dart @@ -0,0 +1,634 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:bloc_test/bloc_test.dart'; +import 'package:file_picker/file_picker.dart'; +import 'package:fluentui_system_icons/fluentui_system_icons.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:otzaria/book_protection/repository/book_protection_repository.dart'; +import 'package:otzaria/core/windowing/dialog_owner.dart'; +import 'package:otzaria/migration/database/repository/seforim_repository.dart'; +import 'package:otzaria/models/books.dart'; +import 'package:otzaria/printing/view/printing_screen.dart'; +import 'package:otzaria/printing/view/widgets/printing_widgets.dart'; +import 'package:otzaria/settings/engine/app_settings_store.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'; +import 'package:otzaria/settings/engine/settings_state.dart'; +import 'package:otzaria/widgets/controls/action_buttons.dart'; +import 'package:otzaria/widgets/dialogs/input_dialog.dart'; +import 'package:pdf/pdf.dart' show PdfPageFormat; +import 'package:pdf/widgets.dart' as pw; +import 'package:pdfrx/pdfrx.dart'; +import 'package:printing/printing.dart'; +// ignore: implementation_imports +import 'package:printing/src/interface.dart'; +// ignore: depend_on_referenced_packages +import 'package:plugin_platform_interface/plugin_platform_interface.dart'; + +import '../helpers/memory_settings_cache.dart'; +import '../helpers/printing_raster_idle.dart'; + +class _MockSettingsBloc extends MockBloc + implements SettingsBloc {} + +class _SettingsRepository extends Fake implements SettingsRepository { + @override + bool hasProtectedModePassword() => false; +} + +class _ProtectedBookRepository extends Fake implements SeforimRepository { + @override + Future getBookProtectionTables() async => ( + levels: {1: 2}, + banners: {}, + booksByTitle: >{ + 'stream-output': [(id: 1, categoryId: null)], + }, + ); +} + +class _RecordingPrinter extends PrintingPlatform { + int requests = 0; + Future Function(LayoutCallback, PdfPageFormat)? runLayout; + + @override + Future layoutPdf( + Printer? printer, + LayoutCallback onLayout, + String name, + PdfPageFormat format, + bool dynamicLayout, + bool usePrinterSettings, + OutputType outputType, + bool forceCustomPrintPaper, + bool windowsModernDialog, + ) async { + requests++; + await runLayout?.call(onLayout, format); + return false; + } + + @override + dynamic noSuchMethod(Invocation invocation) { + requests++; + throw UnsupportedError( + 'Unexpected printing call: ${invocation.memberName}', + ); + } +} + +class _FolderPicker extends FilePickerPlatform with MockPlatformInterfaceMixin { + _FolderPicker(this.select); + Future Function() select; + int selections = 0; + int byteSaves = 0; + + @override + Future getDirectoryPath({ + String? dialogTitle, + String? initialDirectory, + AndroidOptions androidOptions = const AndroidOptions(), + WindowsOptions windowsOptions = const WindowsOptions(), + LinuxOptions linuxOptions = const LinuxOptions(), + WebOptions webOptions = const WebOptions(), + }) { + selections++; + return select(); + } + + @override + Future saveFile({ + required String fileName, + required Uint8List bytes, + String mimeType = 'application/octet-stream', + String? dialogTitle, + String? initialDirectory, + Function(FilePickerStatus)? onFileSaving, + WindowsOptions windowsOptions = const WindowsOptions(), + LinuxOptions linuxOptions = const LinuxOptions(), + WebOptions webOptions = const WebOptions(), + }) async { + byteSaves++; + throw StateError('Desktop PDF export must not use the byte save API.'); + } +} + +Future _waitFor(WidgetTester tester, bool Function() done) async { + for (var i = 0; i < 600 && !done(); i++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 10)), + ); + await tester.pump(const Duration(milliseconds: 10)); + } + expect(done(), isTrue, reason: 'The PDF export did not settle.'); +} + +Future _settle(WidgetTester tester, Future future) async { + var done = false; + future.then( + (_) => done = true, + onError: (Object _, StackTrace _) => done = true, + ); + await _waitFor(tester, () => done); + return future; +} + +void main() { + const pathProvider = MethodChannel('plugins.flutter.io/path_provider'); + const filePicker = MethodChannel('miguelruivo.flutter.plugins.filepicker'); + final originalModule = Pdfrx.pdfiumModulePath; + late FilePickerPlatform originalPicker; + int? originalOwner; + late Directory directory; + late Directory output; + late File input; + late Uint8List inputBytes; + late _FolderPicker picker; + late bool closed; + bool? saved; + + setUpAll(() async { + await Settings.init(cacheProvider: MemorySettingsCache()); + final module = Platform.isWindows + ? 'pdfium.dll' + : Platform.isMacOS + ? 'libpdfium_dart.dylib' + : 'libpdfium.so'; + Pdfrx.pdfiumModulePath = File( + 'build/native_assets/${Platform.operatingSystem}/$module', + ).absolute.path; + final document = pw.Document(); + for (var page = 1; page <= 5; page++) { + document.addPage(pw.Page(build: (_) => pw.Text('page $page'))); + } + inputBytes = await document.save(); + }); + + setUp(() async { + await Settings.setValue('key-print-destination', 0); + directory = Directory.systemTemp.createTempSync('otzaria-file-export-'); + output = Directory('${directory.path}/output')..createSync(); + input = File('${directory.path}/input.pdf')..writeAsBytesSync(inputBytes); + picker = _FolderPicker(() async => output.path); + originalPicker = FilePickerPlatform.instance; + FilePickerPlatform.instance = picker; + originalOwner = DialogOwner.hwnd(); + DialogOwner.mainWindowHwnd = 101; + closed = false; + saved = null; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(pathProvider, (_) async => directory.path); + if (Platform.isMacOS) { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(filePicker, (call) async { + if (call.method == 'dir') return picker.getDirectoryPath(); + throw StateError('Unexpected byte picker: ${call.method}'); + }); + } + }); + + tearDown(() { + PrintingScreen.debugOnPrintBlocks = null; + FilePickerPlatform.instance = originalPicker; + DialogOwner.mainWindowHwnd = originalOwner; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(pathProvider, null); + if (Platform.isMacOS) { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(filePicker, null); + } + directory.deleteSync(recursive: true); + }); + + tearDownAll(() => Pdfrx.pdfiumModulePath = originalModule); + + Future dispose(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox()); + await drainPrintingRasterQueue(tester); + expect(tester.takeException(), isNull); + } + + Future open( + WidgetTester tester, { + Future Function()? create, + int? initialPage, + bool isBookView = false, + bool text = false, + TextBook? book, + }) async { + tester.view.physicalSize = const Size(1600, 1200); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + addTearDown(() => dispose(tester)); + await tester.runAsync(pdfrxFlutterInitialize); + final settings = _MockSettingsBloc(); + whenListen( + settings, + const Stream.empty(), + initialState: SettingsState.initial(), + ); + final data = Future.value('ספר בדיקה\nשלום עולם\nשורה נוספת'); + final Future Function(PdfPageFormat)? createOverride = + create == null ? null : (_) => create(); + var path = input.path; + late StateSetter replace; + await tester.pumpWidget( + RepositoryProvider.value( + value: _SettingsRepository(), + child: BlocProvider.value( + value: settings, + child: MaterialApp( + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: const TextScaler.linear(0.5)), + child: child!, + ), + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + child: const Text('open'), + onPressed: () async { + saved = await showDialog( + context: context, + barrierDismissible: false, + builder: (_) => StatefulBuilder( + builder: (context, setState) { + replace = setState; + return PrintingScreen( + data: data, + bookId: 'stream-output', + book: book, + pdfFilePath: create != null || text ? null : path, + createPdfOverride: createOverride, + initialPage: initialPage, + isBookView: isBookView, + startLine: 1, + endLine: 3, + ); + }, + ), + ); + closed = true; + }, + ), + ), + ), + ), + ), + ), + ); + await tester.tap(find.text('open')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + return (replacement) => replace(() => path = replacement); + } + + Future chooseName(WidgetTester tester) async { + await _waitFor( + tester, + () => find.byType(InputDialog).evaluate().isNotEmpty, + ); + expect( + tester.widget(find.byType(TextField)).controller!.text, + 'stream-output.pdf', + ); + await tester.tap(find.text('שמור')); + await tester.pump(); + } + + testWidgets('late protection never turns Save into a print request', ( + tester, + ) async { + final pending = Completer(); + BookProtectionRepository.instance.debugRepositoryFor = (_) => + pending.future; + final previousPrinter = PrintingPlatform.instance; + final printer = _RecordingPrinter(); + PrintingPlatform.instance = printer; + addTearDown(() { + BookProtectionRepository.instance.debugReset(); + PrintingPlatform.instance = previousPrinter; + }); + try { + await open(tester, book: TextBook(title: 'stream-output')); + await tester.tap(find.text('שמירה')); + await tester.pump(); + expect(find.text('שומר קובץ...'), findsOneWidget); + + pending.complete(_ProtectedBookRepository()); + await _waitFor( + tester, + () => find.text('שומר קובץ...').evaluate().isEmpty, + ); + expect(find.text('הדפסה'), findsWidgets); + expect(printer.requests, 0); + expect(picker.selections, 0); + expect(picker.byteSaves, 0); + expect(closed, isFalse); + await dispose(tester); + } finally { + if (!pending.isCompleted) pending.complete(null); + } + }); + + testWidgets('one-up printer read failure is not reported as N-up failure', ( + tester, + ) async { + final logging = debugPrint; + final previousPrinter = PrintingPlatform.instance; + final messages = []; + Object? layoutError; + debugPrint = (message, {wrapWidth}) { + if (message != null) messages.add(message); + }; + PrintingPlatform.instance = _RecordingPrinter() + ..runLayout = (layout, format) async { + try { + await layout(format); + } catch (error) { + layoutError = error; + rethrow; + } + }; + try { + await Settings.setValue('key-print-destination', 2); + input.deleteSync(); + await open(tester); + + await tester.tap(find.widgetWithText(ActionButton, 'הדפסה')); + await _waitFor(tester, () => layoutError != null); + expect(layoutError, isA()); + expect(messages, isNot(contains(startsWith('[PRINT] N-up failed:')))); + await dispose(tester); + } finally { + debugPrint = logging; + PrintingPlatform.instance = previousPrinter; + } + }); + + testWidgets('an unchanged file is copied without the byte save API', ( + tester, + ) async { + await open(tester); + await tester.tap(find.text('שמירה')); + await chooseName(tester); + await _waitFor(tester, () => closed); + expect(saved, isTrue); + expect(picker.selections, 1); + expect(picker.byteSaves, 0); + expect(output.listSync(), hasLength(1)); + expect( + File('${output.path}/stream-output.pdf').readAsBytesSync(), + inputBytes, + ); + expect(input.readAsBytesSync(), inputBytes); + await dispose(tester); + }); + + for (final pagesPerSheet in [1, 2, 4]) { + testWidgets('file export preserves range 2–3 with $pagesPerSheet-up', ( + tester, + ) async { + await open(tester, initialPage: 2, isBookView: true); + tester + .widget( + find.byType(PrintingPagesPerSheetDropdownRow), + ) + .onChanged(pagesPerSheet); + await tester.pump(); + await tester.tap(find.text('שמירה')); + await chooseName(tester); + await _waitFor(tester, () => closed); + expect(saved, isTrue); + await dispose(tester); + final document = await _settle( + tester, + PdfDocument.openFile('${output.path}/stream-output.pdf'), + ); + try { + expect(document.pages, hasLength(pagesPerSheet == 1 ? 2 : 1)); + final extracted = []; + for (final page in document.pages) { + extracted.add((await _settle(tester, page.loadText()))!.fullText); + } + expect(extracted.join(' '), contains('page 2')); + expect(extracted.join(' '), contains('page 3')); + expect(extracted.join(' '), isNot(contains('page 1'))); + expect(extracted.join(' '), isNot(contains('page 4'))); + } finally { + await _settle(tester, document.dispose()); + } + expect(picker.byteSaves, 0); + expect(output.listSync(), hasLength(1)); + }); + } + + testWidgets('text preview and Save reuse one generated file with Hebrew', ( + tester, + ) async { + var generated = 0; + PrintingScreen.debugOnPrintBlocks = (_) => generated++; + await open(tester, text: true); + await _waitFor(tester, () => find.byType(RawImage).evaluate().isNotEmpty); + expect(generated, 1); + await tester.tap(find.text('שמירה')); + await chooseName(tester); + await _waitFor(tester, () => closed); + expect(saved, isTrue); + expect(generated, 1, reason: 'Saving must reuse the preview base file.'); + await dispose(tester); + final document = await _settle( + tester, + PdfDocument.openFile('${output.path}/stream-output.pdf'), + ); + try { + expect( + (await _settle(tester, document.pages.first.loadText()))!.fullText, + contains('שלום עולם'), + ); + } finally { + await _settle(tester, document.dispose()); + } + expect(picker.byteSaves, 0); + }); + + testWidgets('a generation failure leaves the old target and allows retry', ( + tester, + ) async { + final target = File('${output.path}/stream-output.pdf') + ..writeAsStringSync('original'); + final pending = Completer(); + var calls = 0; + await open( + tester, + create: () { + calls++; + return switch (calls) { + 1 => Future.error(StateError('Synthetic preview failure')), + 2 => pending.future, + _ => Future.value(inputBytes), + }; + }, + ); + try { + // Let the initial preview finish failing. The second generation then + // belongs to Save, independently of native permission setup timing. + await _waitFor( + tester, + () => find + .byIcon(FluentIcons.error_circle_24_regular) + .evaluate() + .isNotEmpty, + ); + await tester.tap(find.text('שמירה')); + await chooseName(tester); + await _waitFor(tester, () => find.text('החלפה').evaluate().isNotEmpty); + await tester.tap(find.text('החלפה')); + await _waitFor(tester, () => calls == 2); + expect(target.readAsStringSync(), 'original'); + expect(output.listSync(), hasLength(2)); + pending.completeError(StateError('Synthetic PDF generation failure')); + await _waitFor(tester, () => find.text('שמירה').evaluate().isNotEmpty); + expect(target.readAsStringSync(), 'original'); + expect(output.listSync(), hasLength(1)); + expect(closed, isFalse); + await tester.tap(find.text('שמירה')); + await chooseName(tester); + await _waitFor(tester, () => find.text('החלפה').evaluate().isNotEmpty); + await tester.tap(find.text('החלפה')); + await _waitFor(tester, () => closed); + expect(saved, isTrue); + expect(calls, 3); + expect(target.readAsBytesSync(), inputBytes); + expect(output.listSync(), hasLength(1)); + expect(picker.byteSaves, 0); + } finally { + if (!pending.isCompleted) pending.complete(inputBytes); + await dispose(tester); + } + }); + + testWidgets('cancelling with a pending preview preserves the target', ( + tester, + ) async { + final target = File('${output.path}/stream-output.pdf') + ..writeAsStringSync('original'); + final pending = Completer(); + var calls = 0; + await open( + tester, + create: () { + calls++; + return pending.future; + }, + ); + try { + await tester.tap(find.text('שמירה')); + await chooseName(tester); + await _waitFor(tester, () => find.text('החלפה').evaluate().isNotEmpty); + expect(target.readAsStringSync(), 'original'); + await tester.tap(find.text('החלפה')); + await _waitFor(tester, () => output.listSync().length == 2); + expect(calls, 1); + await tester.tap(find.text('ביטול')); + pending.complete(inputBytes); + await _waitFor(tester, () => closed && output.listSync().length == 1); + expect(saved, isNull); + expect(target.readAsStringSync(), 'original'); + expect(picker.byteSaves, 0); + } finally { + if (!pending.isCompleted) pending.complete(inputBytes); + await dispose(tester); + } + }); + + testWidgets('a second Save is ignored while target selection is pending', ( + tester, + ) async { + final folder = Completer(); + picker.select = () => folder.future; + await open(tester); + try { + await tester.tap(find.text('שמירה')); + await tester.tap(find.text('שמירה')); + // Both taps deliberately happen before a frame, then render the busy UI. + await tester.pump(); + await _waitFor(tester, () => picker.selections == 1); + expect(find.text('שומר קובץ...'), findsOneWidget); + final settings = find.byType(PrintingPagesPerSheetDropdownRow); + final blockers = find.ancestor( + of: settings, + matching: find.byType(IgnorePointer), + ); + expect( + blockers.evaluate().any((e) => (e.widget as IgnorePointer).ignoring), + isTrue, + ); + folder.complete(null); + await _waitFor(tester, () => find.text('שמירה').evaluate().isNotEmpty); + expect(picker.selections, 1); + expect(picker.byteSaves, 0); + expect(output.listSync(), isEmpty); + } finally { + if (!folder.isCompleted) folder.complete(null); + await dispose(tester); + } + }); + + testWidgets('source A–B–A while choosing a target cancels the old Save', ( + tester, + ) async { + final folder = Completer(); + picker.select = () => folder.future; + final replacement = File('${directory.path}/other.pdf') + ..writeAsBytesSync(inputBytes); + final replace = await open(tester); + try { + await tester.tap(find.text('שמירה')); + await _waitFor(tester, () => picker.selections == 1); + replace(replacement.path); + await tester.pump(); + replace(input.path); + await tester.pump(); + folder.complete(output.path); + await _waitFor(tester, () => find.text('שמירה').evaluate().isNotEmpty); + expect(find.byType(InputDialog), findsNothing); + expect(output.listSync(), isEmpty); + expect(closed, isFalse); + expect(picker.byteSaves, 0); + } finally { + if (!folder.isCompleted) folder.complete(null); + await dispose(tester); + } + }); + + testWidgets('closing the owner while the folder picker waits cancels Save', ( + tester, + ) async { + final folder = Completer(); + picker.select = () => folder.future; + await open(tester); + try { + await tester.tap(find.text('שמירה')); + await _waitFor(tester, () => picker.selections == 1); + await tester.tap(find.text('ביטול')); + await _waitFor(tester, () => closed); + // The route is still mounted during its closing animation. + folder.complete(output.path); + await _settle(tester, folder.future); + await tester.pump(); + expect(find.byType(InputDialog), findsNothing); + expect(output.listSync(), isEmpty); + expect(picker.byteSaves, 0); + } finally { + if (!folder.isCompleted) folder.complete(null); + await dispose(tester); + } + }); +}