@@ -17,6 +17,7 @@ import 'package:otzaria/settings/engine/settings_repository.dart';
1717import 'package:otzaria/settings/services/safer_mode_guard.dart' ;
1818import 'package:otzaria/core/messages/pdf_messages.dart' ;
1919import 'package:otzaria/core/ui_snack.dart' ;
20+ import 'package:otzaria/core/windowing/app_window_keys.dart' ;
2021import 'package:otzaria/theme/theme_exports.dart' ;
2122import 'package:otzaria/models/links.dart' ;
2223import 'package:otzaria/personal_notes/models/personal_note.dart' ;
@@ -52,6 +53,7 @@ import 'package:otzaria/printing/word_export_service.dart';
5253import 'package:otzaria/utils/file/save_file_with_extension.dart' ;
5354import 'package:otzaria/utils/file/desktop_save_target.dart' ;
5455import 'package:otzaria/utils/file/atomic_file_publication.dart' ;
56+ import 'package:otzaria/utils/file/mobile_pdf_export_service.dart' ;
5557import 'package:otzaria/utils/text/text_manipulation.dart' ;
5658import 'package:otzaria/widgets/controls/action_buttons.dart' ;
5759import 'package:otzaria/widgets/dialogs/app_dialog_frame.dart' ;
@@ -169,6 +171,7 @@ class PrintingScreen extends StatefulWidget {
169171
170172 /// קובץ קיים נפתח ישירות; בתים מלאים נקראים רק כשיעד הפלט דורש אותם.
171173 final String ? pdfFilePath;
174+ final MobilePdfExportService ? mobileExportService;
172175 final String bookId;
173176 final TextBook ? book;
174177 final List <Link > links;
@@ -212,6 +215,7 @@ class PrintingScreen extends StatefulWidget {
212215 required this .data,
213216 this .createPdfOverride,
214217 this .pdfFilePath,
218+ this .mobileExportService,
215219 required this .bookId,
216220 this .book,
217221 this .links = const [],
@@ -323,6 +327,9 @@ class _PrintingScreenState extends State<PrintingScreen> {
323327 bool get _isPrinting => _printProgress != null ;
324328 bool _destinationActionPending = false ;
325329 PdfExportCancellationToken ? _exportCancellation;
330+ MobilePdfExportOperation ? _mobileExport;
331+ MobilePdfExportService get _mobileExports =>
332+ widget.mobileExportService ?? MobilePdfExportService .instance;
326333 Timer ? _previewRefreshTimer;
327334
328335 // נקודות הקצה של טווח ההדפסה — כל אחת עצמאית בסוגה (כותרת/כותרת משנה/שורה).
@@ -542,7 +549,7 @@ class _PrintingScreenState extends State<PrintingScreen> {
542549 _cachedBaseKey = null ;
543550 _pendingBasePdfs.clear ();
544551 _basePdfFiles.invalidate ();
545- _exportCancellation ? . cancel ();
552+ _cancelFileExport ();
546553 _anchorEntries = null ;
547554 _totalPdfPages = 0 ;
548555 if (_isPdfSource) {
@@ -709,6 +716,7 @@ class _PrintingScreenState extends State<PrintingScreen> {
709716 );
710717 _preview.dispose ();
711718 _releasePreviewBase ();
719+ _cancelFileExport ();
712720 _exportCancellation? .dispose ();
713721 _trackFileCleanup (_basePdfFiles.dispose ());
714722 _cachedBasePdf = null ;
@@ -2061,37 +2069,42 @@ class _PrintingScreenState extends State<PrintingScreen> {
20612069
20622070 Future <bool > _saveToFile (_ExportFormat selectedFormat) async {
20632071 final cancellation = _exportCancellation! ;
2072+ if (! mounted || cancellation.isCancelled) return false ;
20642073 if (! await verifySaferModePassword (context)) return false ;
20652074 if (! mounted || cancellation.isCancelled) return false ;
20662075 try {
20672076 final selectedExtension = selectedFormat.extension ;
20682077 final fileName = '${_sanitizeFileName (widget .bookId )}.$selectedExtension ' ;
2069- if (selectedFormat == _ExportFormat .pdf &&
2070- (Platform .isWindows || Platform .isLinux || Platform .isMacOS)) {
2078+ if (selectedFormat == _ExportFormat .pdf) {
20712079 await _divineNamesReady;
20722080 if (! mounted || cancellation.isCancelled) return false ;
20732081 final plan = _captureFileExport ();
2074- final target = await chooseDesktopSaveTarget (
2075- context: context,
2076- dialogTitle: 'ייצוא קובץ' ,
2077- fileName: fileName,
2078- extension : selectedExtension,
2079- isCancelled: () => _fileExportCancelled (plan, cancellation),
2080- );
2081- if (target == null || _fileExportCancelled (plan, cancellation)) {
2082- return false ;
2082+ final mobile = _mobileExports;
2083+ if (mobile.isSupported) {
2084+ return await _saveMobilePdf (mobile, plan, cancellation, fileName);
2085+ }
2086+ if (Platform .isWindows || Platform .isLinux || Platform .isMacOS) {
2087+ final target = await chooseDesktopSaveTarget (
2088+ context: context,
2089+ dialogTitle: 'ייצוא קובץ' ,
2090+ fileName: fileName,
2091+ extension : selectedExtension,
2092+ isCancelled: () => _fileExportCancelled (plan, cancellation),
2093+ );
2094+ if (target == null || _fileExportCancelled (plan, cancellation)) {
2095+ return false ;
2096+ }
2097+ final saved = await publishFileAtomically (
2098+ target: target,
2099+ isCancelled: () => _fileExportCancelled (plan, cancellation),
2100+ producer: (path) => _writeOutputPdfToFile (plan, cancellation, path),
2101+ );
2102+ if (saved && mounted) UiSnack .showSuccess (PdfMessages .pdfFileSaved);
2103+ return saved;
20832104 }
2084- final saved = await publishFileAtomically (
2085- target: target,
2086- isCancelled: () => _fileExportCancelled (plan, cancellation),
2087- producer: (path) => _writeOutputPdfToFile (plan, cancellation, path),
2088- );
2089- if (saved && mounted) UiSnack .showSuccess (PdfMessages .pdfFileSaved);
2090- return saved;
20912105 }
20922106
2093- // Printing.onLayout, Word and mobile file-provider APIs still require
2094- // complete bytes. Keep those public contracts on their existing path.
2107+ // The remaining output contracts still require complete bytes.
20952108 final Uint8List bytes;
20962109 final String successMessage;
20972110 if (selectedFormat == _ExportFormat .word) {
@@ -2138,6 +2151,82 @@ class _PrintingScreenState extends State<PrintingScreen> {
21382151 }
21392152 }
21402153
2154+ void _cancelFileExport () {
2155+ _exportCancellation? .cancel ();
2156+ final operation = _mobileExport;
2157+ if (operation != null ) unawaited (_cancelMobileExport (operation));
2158+ }
2159+
2160+ Future <void > _cancelMobileExport (MobilePdfExportOperation operation) async {
2161+ try {
2162+ await operation.cancel ();
2163+ } catch (error, stack) {
2164+ debugPrint ('Mobile PDF cancellation request failed: $error \n $stack ' );
2165+ }
2166+ }
2167+
2168+ Future <bool > _saveMobilePdf (
2169+ MobilePdfExportService service,
2170+ _PdfFileExport plan,
2171+ PdfExportCancellationToken cancellation,
2172+ String fileName,
2173+ ) async {
2174+ final window = AppWindowKeys .of (context);
2175+ MobilePdfExportOperation ? operation;
2176+ try {
2177+ operation = service.start (
2178+ fileName: fileName,
2179+ producer: (path) => _writeOutputPdfToFile (plan, cancellation, path),
2180+ onCancelRequested: cancellation.cancel,
2181+ );
2182+ _mobileExport = operation;
2183+ final pending = operation.result;
2184+ // Only the original result releases staging; cancel merely requests it.
2185+ // The idle barrier observes completion; the await below reports errors.
2186+ _trackFileCleanup (
2187+ pending.then <void >((_) {}, onError: (Object _, StackTrace _) {}),
2188+ );
2189+ final result = await pending;
2190+ if (result.cleanupError != null ) {
2191+ debugPrint ('Mobile PDF export cleanup: ${result .cleanupError }' );
2192+ }
2193+ if (result.residualDocument != null ) {
2194+ UiSnack .showWarning (
2195+ PdfMessages .mobilePdfExportResidual (result.residualDisplayName),
2196+ window: window,
2197+ );
2198+ return false ;
2199+ }
2200+ if (result.status == MobilePdfExportStatus .saved) {
2201+ final name = result.displayName;
2202+ UiSnack .showSuccess (
2203+ name != null && name != fileName
2204+ ? PdfMessages .pdfFileSavedAs (name)
2205+ : PdfMessages .pdfFileSaved,
2206+ window: window,
2207+ );
2208+ return ! _fileExportCancelled (plan, cancellation);
2209+ }
2210+ if (result.status == MobilePdfExportStatus .failed) {
2211+ debugPrint (
2212+ 'Mobile PDF export failed: ${result .errorCode }: ${result .errorMessage }' ,
2213+ );
2214+ if (mounted && ! cancellation.isCancelled) {
2215+ UiSnack .showError (PdfMessages .mobilePdfSaveFailed, window: window);
2216+ }
2217+ }
2218+ return false ;
2219+ } catch (error, stack) {
2220+ debugPrint ('Mobile PDF export failed: $error \n $stack ' );
2221+ if (mounted && ! cancellation.isCancelled) {
2222+ UiSnack .showError (PdfMessages .mobilePdfSaveFailed, window: window);
2223+ }
2224+ return false ;
2225+ } finally {
2226+ if (identical (_mobileExport, operation)) _mobileExport = null ;
2227+ }
2228+ }
2229+
21412230 String _sanitizeFileName (String value) {
21422231 final sanitized = value.replaceAll (RegExp (r'[<>:"/\\|?*]' ), '_' ).trim ();
21432232 return sanitized.isEmpty ? 'output' : sanitized;
@@ -2421,7 +2510,7 @@ class _PrintingScreenState extends State<PrintingScreen> {
24212510 _previewRefreshTimer? .cancel ();
24222511 _preview.stop ();
24232512 _releasePreviewBase ();
2424- _exportCancellation ? . cancel ();
2513+ _cancelFileExport ();
24252514 },
24262515 child: dialog,
24272516 );
@@ -2829,13 +2918,9 @@ class _PrintingScreenState extends State<PrintingScreen> {
28292918 ),
28302919 const SizedBox (width: 8 ),
28312920 Expanded (
2832- child: _destinationActionPending
2921+ child: _isPrinting
28332922 ? ActionButton .recommended (
2834- text:
2835- _printProgress ??
2836- (_exportCancellation != null
2837- ? 'שומר קובץ...'
2838- : PdfMessages .printPreparing),
2923+ text: _printProgress! ,
28392924 iconWidget: SizedBox .square (
28402925 dimension: 16 ,
28412926 child: CircularProgressIndicator (strokeWidth: 2 ),
0 commit comments