@@ -16,7 +16,10 @@ import 'package:otzaria/book_protection/utils/copy_guard.dart';
1616import 'package:otzaria/models/book_source.dart' ;
1717import 'package:otzaria/utils/file/file_picker_dialog_options.dart' ;
1818import 'package:otzaria/utils/file/desktop_save_target.dart' ;
19+ import 'package:otzaria/utils/file/atomic_file_publication.dart' ;
20+ import 'package:otzaria/utils/file/mobile_pdf_export_service.dart' ;
1921import 'package:flutter/material.dart' ;
22+ import 'package:otzaria/core/messages/pdf_messages.dart' ;
2023import 'package:otzaria/core/windowing/app_window_keys.dart' ;
2124import 'package:flutter_bloc/flutter_bloc.dart' show BlocProvider;
2225import 'package:otzaria/core/windowing/window_fullscreen_cubit.dart' ;
@@ -692,6 +695,8 @@ class PluginBridgeAdapter {
692695 final PluginDatabaseService _databaseService;
693696 final PluginHighlightRegistry _highlightRegistry;
694697 final PluginSearchFieldSessionService _searchFieldSessions;
698+ final MobilePdfExportService ? _mobilePdfExportService;
699+ MobilePdfExportOperation ? _mobilePdfExport;
695700
696701 PluginBridgeAdapter (
697702 this .plugin, {
@@ -714,6 +719,7 @@ class PluginBridgeAdapter {
714719 PluginBookCorrectionService ? bookCorrectionService,
715720 DirectErrorReportService ? directReportService,
716721 PluginSearchFieldSessionService ? searchFieldSessions,
722+ this ._mobilePdfExportService,
717723 }) : _pluginRepo = pluginRepository ?? PluginRegistryRepository (),
718724 _pluginReportService = reportService,
719725 _pluginBookCorrectionService = bookCorrectionService,
@@ -964,6 +970,8 @@ class PluginBridgeAdapter {
964970 /// משחרר תרומות ופעולות ממתינות של הדף; המתאם משמש גם את הדף הבא.
965971 void releaseRuntime ({bool removeRegistrations = true }) {
966972 _fileAccessGeneration++ ;
973+ final export = _mobilePdfExport;
974+ if (export != null ) unawaited (_cancelMobilePdfExport (export));
967975 // מסיר רק את תרומות המופע הזה — מופע אחר של אותו תוסף ממשיך לתפקד,
968976 // וה-dedup בציור חושף את העותקים שלו.
969977 final key = (pluginId: plugin.pluginId, instanceId: instanceId);
@@ -5256,34 +5264,53 @@ class PluginBridgeAdapter {
52565264 case 'exportPdf' :
52575265 final capture =
52585266 _dependencies.capturePluginPagePdf ?? _defaultCapturePagePdf;
5259- final saver =
5260- _dependencies.pickSaveLocation ?? _defaultPickSaveLocation;
52615267 final suggested = pluginSaveFileName (
52625268 args['fileName' ] as String ? ,
52635269 'pdf' ,
52645270 );
52655271 final layout = _parsePdfLayout (args);
52665272 return await _runUserGatedDialog (() async {
5273+ _checkFileAccess ();
52675274 final pdf = await capture (
52685275 plugin.pluginId,
52695276 instanceId,
52705277 layout: layout,
52715278 );
5272- final chosen = await saver (
5279+ _checkFileAccess ();
5280+ final mobile =
5281+ _mobilePdfExportService ?? MobilePdfExportService .instance;
5282+ if (mobile.isSupported) {
5283+ return _exportMobilePdf (mobile, pdf, suggested);
5284+ }
5285+ final target = await _pickPdfExportTarget (
52735286 suggestedName: suggested,
5274- allowedExtensions: const ['pdf' ],
52755287 title: args['title' ] as String ? ,
52765288 );
5277- if (chosen == null || chosen.isEmpty ) {
5289+ if (target == null ) {
52785290 return {'saved' : false , 'name' : null };
52795291 }
5280- // בורר המיקום ניתן להזרקה, וחוזהו אינו מבטיח שהסיומת תושלם.
5281- final target = chosen.toLowerCase ().endsWith ('.pdf' )
5282- ? chosen
5283- : '$chosen .pdf' ;
5284- await File (target).writeAsBytes (pdf, flush: true );
5292+ final saved = await publishFileAtomically (
5293+ target: target,
5294+ producer: (stagingPath) async {
5295+ _checkFileAccess ();
5296+ await File (stagingPath).writeAsBytes (pdf);
5297+ _checkFileAccess ();
5298+ },
5299+ isCancelled: () {
5300+ // Recheck the RPC's original lifetime and authorization before
5301+ // publication, including while another save owns the target.
5302+ _checkFileAccess ();
5303+ return false ;
5304+ },
5305+ );
52855306 // הנתיב עצמו אינו מוחזר — התוסף אינו מקבל גישה למה שנשמר.
5286- return {'saved' : true , 'name' : p.basename (target)};
5307+ return {
5308+ 'saved' : saved,
5309+ 'name' : saved ? p.basename (target.path) : null ,
5310+ };
5311+ }).onError <FileSystemException >((_, _) {
5312+ // הגשר מחזיר לתוסף את הודעת השגיאה, וחריגת קבצים כוללת נתיב מלא.
5313+ throw Exception ('error.internal: failed to save the PDF' );
52875314 });
52885315 default :
52895316 throw Exception ("error.unknown_method: Unknown action in ui: $action " );
@@ -6266,30 +6293,148 @@ class PluginBridgeAdapter {
62666293 required String suggestedName,
62676294 List <String >? allowedExtensions,
62686295 String ? title,
6296+ }) async => (await _defaultPickSaveTarget (
6297+ suggestedName: suggestedName,
6298+ allowedExtensions: allowedExtensions,
6299+ title: title,
6300+ ))? .path;
6301+
6302+ Future <DesktopSaveTarget ?> _defaultPickSaveTarget ({
6303+ required String suggestedName,
6304+ List <String >? allowedExtensions,
6305+ String ? title,
62696306 }) async {
6307+ _checkFileAccess ();
62706308 final context = rpcWindowContext;
62716309 if (context == null || ! context.mounted) return null ;
62726310 if (! await verifySaferModePassword (context)) {
62736311 return null ;
62746312 }
62756313 if (! context.mounted) return null ;
6314+ _checkFileAccess ();
62766315 final target = await chooseDesktopSaveTarget (
62776316 context: context,
62786317 fileName: suggestedName,
62796318 extension : allowedExtensions? .firstOrNull,
62806319 dialogTitle: title,
6281- confirmOverwrite: (fileName) {
6320+ confirmOverwrite: _confirmSaveOverwrite,
6321+ isCancelled: () {
62826322 _checkFileAccess ();
6283- return _dependencies.showWarningDialog (
6284- title: 'הקובץ כבר קיים' ,
6285- content: 'הקובץ „$fileName ” כבר קיים בתיקייה שנבחרה.' ,
6286- subtitle: 'התוכן הקיים יוחלף.' ,
6287- );
6323+ return false ;
62886324 },
62896325 );
62906326 if (target == null ) return null ;
62916327 _checkFileAccess ();
6292- return target.path;
6328+ return target;
6329+ }
6330+
6331+ Future <DesktopSaveTarget ?> _pickPdfExportTarget ({
6332+ required String suggestedName,
6333+ String ? title,
6334+ }) async {
6335+ final picker = _dependencies.pickSaveLocation;
6336+ if (picker == null ) {
6337+ return _defaultPickSaveTarget (
6338+ suggestedName: suggestedName,
6339+ allowedExtensions: const ['pdf' ],
6340+ title: title,
6341+ );
6342+ }
6343+ final chosen = await picker (
6344+ suggestedName: suggestedName,
6345+ allowedExtensions: const ['pdf' ],
6346+ title: title,
6347+ );
6348+ _checkFileAccess ();
6349+ if (chosen == null || chosen.isEmpty) return null ;
6350+ // The injected picker chooses a location; it promises neither a suffix
6351+ // nor approval to replace a file that already occupies that location.
6352+ final path = chosen.toLowerCase ().endsWith ('.pdf' ) ? chosen : '$chosen .pdf' ;
6353+ final exists =
6354+ await FileSystemEntity .type (path, followLinks: false ) !=
6355+ FileSystemEntityType .notFound;
6356+ _checkFileAccess ();
6357+ if (exists && ! await _confirmSaveOverwrite (p.basename (path))) return null ;
6358+ return DesktopSaveTarget (path: path, overwriteApproved: exists);
6359+ }
6360+
6361+ Future <Map <String , dynamic >> _exportMobilePdf (
6362+ MobilePdfExportService service,
6363+ Uint8List pdf,
6364+ String fileName,
6365+ ) async {
6366+ _checkFileAccess ();
6367+ final context = rpcWindowContext;
6368+ if (context == null || ! context.mounted) {
6369+ return {'saved' : false , 'name' : null };
6370+ }
6371+ if (! await verifySaferModePassword (context)) {
6372+ return {'saved' : false , 'name' : null };
6373+ }
6374+ if (! context.mounted) return {'saved' : false , 'name' : null };
6375+ _checkFileAccess ();
6376+ final window = AppWindowKeys .of (context);
6377+ final operation = service.start (
6378+ fileName: fileName,
6379+ producer: (path) async {
6380+ _checkFileAccess ();
6381+ await File (path).writeAsBytes (pdf, flush: true );
6382+ _checkFileAccess ();
6383+ },
6384+ );
6385+ _mobilePdfExport = operation;
6386+ try {
6387+ // Cancel acknowledgement cannot release a file still held by UIKit.
6388+ final result = await operation.result;
6389+ if (result.cleanupError != null ) {
6390+ debugPrint ('Plugin PDF export cleanup: ${result .cleanupError }' );
6391+ }
6392+ if (result.residualDocument != null ) {
6393+ UiSnack .showWarning (
6394+ PdfMessages .mobilePdfExportResidual (result.residualDisplayName),
6395+ window: window,
6396+ );
6397+ } else if (result.status == MobilePdfExportStatus .saved) {
6398+ return {'saved' : true , 'name' : result.displayName};
6399+ } else if (result.status == MobilePdfExportStatus .failed) {
6400+ debugPrint (
6401+ 'Plugin PDF export failed: ${result .errorCode }: ${result .errorMessage }' ,
6402+ );
6403+ if (! _disposed && ! operation.isCancellationRequested) {
6404+ UiSnack .showError (PdfMessages .mobilePdfSaveFailed, window: window);
6405+ }
6406+ }
6407+ return {'saved' : false , 'name' : null };
6408+ } catch (error, stack) {
6409+ debugPrint ('Plugin PDF export failed: $error \n $stack ' );
6410+ if (! _disposed && ! operation.isCancellationRequested) {
6411+ UiSnack .showError (PdfMessages .mobilePdfSaveFailed, window: window);
6412+ }
6413+ return {'saved' : false , 'name' : null };
6414+ } finally {
6415+ if (identical (_mobilePdfExport, operation)) _mobilePdfExport = null ;
6416+ }
6417+ }
6418+
6419+ Future <void > _cancelMobilePdfExport (
6420+ MobilePdfExportOperation operation,
6421+ ) async {
6422+ try {
6423+ await operation.cancel ();
6424+ } catch (error, stack) {
6425+ debugPrint ('Plugin PDF export cancellation failed: $error \n $stack ' );
6426+ }
6427+ }
6428+
6429+ Future <bool > _confirmSaveOverwrite (String fileName) async {
6430+ _checkFileAccess ();
6431+ final approved = await _dependencies.showWarningDialog (
6432+ title: 'הקובץ כבר קיים' ,
6433+ content: 'הקובץ „$fileName ” כבר קיים בתיקייה שנבחרה.' ,
6434+ subtitle: 'התוכן הקיים יוחלף.' ,
6435+ );
6436+ _checkFileAccess ();
6437+ return approved;
62936438 }
62946439
62956440 /// מעתיק את ההעלאה ליעד: staging באותה תיקייה, ואז rename.
0 commit comments