Skip to content

Commit 0635dff

Browse files
committed
Merge pull request #5895 from yom-chadash/perf/pdf-mobile-printing-5538
הדפסה: ייצוא PDF מקובץ בנייד עם ביטול ובעלות עד סיום native (#5538)
2 parents 459d207 + 66901a5 commit 0635dff

5 files changed

Lines changed: 839 additions & 43 deletions

File tree

‎.github/workflows/pdf_file_export.yml‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,11 @@ on:
1919
- 'test/printing/print_pdf_*_test.dart'
2020
- 'test/printing/pdf_sheet_*_test.dart'
2121
- 'test/printing/printing_screen_file_export_test.dart'
22+
- 'test/printing/printing_screen_mobile_export_test.dart'
2223
- 'test/utils/file/atomic_file_publication_test.dart'
2324
- 'test/utils/file/desktop_save_target_test.dart'
2425
- 'test/utils/file/save_target_name_test.dart'
26+
- 'test/utils/file/mobile_pdf_export_*_test.dart'
2527
- 'test/helpers/printing_raster_idle.dart'
2628
- 'fonts/Tinos-Regular.ttf'
2729
- 'fonts/NotoSerifHebrew-VariableFont_wdth,wght.ttf'
@@ -65,6 +67,7 @@ jobs:
6567
DART_SUPPRESS_ANALYTICS: 'true'
6668
OTZARIA_REQUIRE_SEARCH_ENGINE: '1'
6769
CARGO_BUILD_JOBS: '2'
70+
OTZARIA_MOBILE_PDF_UI_ARTIFACT_DIR: mobile-pdf-ui
6871
steps:
6972
- uses: actions/checkout@v7.0.1
7073
- uses: subosito/flutter-action@v2
@@ -99,9 +102,13 @@ jobs:
99102
test/printing/pdf_sheet_composer_test.dart
100103
test/printing/pdf_sheet_file_output_test.dart
101104
test/printing/printing_screen_file_export_test.dart
105+
test/printing/printing_screen_mobile_export_test.dart
102106
test/utils/file/atomic_file_publication_test.dart
103107
test/utils/file/desktop_save_target_test.dart
104108
test/utils/file/save_target_name_test.dart
109+
test/utils/file/mobile_pdf_export_core_test.dart
110+
test/utils/file/mobile_pdf_export_models_test.dart
111+
test/utils/file/mobile_pdf_export_service_test.dart
105112
- name: Preserve test results and toolchain identity
106113
if: always()
107114
uses: actions/upload-artifact@v7.0.2
@@ -113,3 +120,4 @@ jobs:
113120
pdf-file-export-flutter.json
114121
pdf-file-export-source.txt
115122
pdf-file-export-tests.jsonl
123+
mobile-pdf-ui/*.png

‎lib/core/messages/pdf_messages.dart‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ abstract class PdfMessages {
2727
static const String pageRangeRenderFailed = 'עיבוד טווח העמודים שנבחר נכשל';
2828
static const String multiPageSheetRenderFailed =
2929
'עיבוד עמודים מרובים בגיליון נכשל';
30+
static String pdfFileSavedAs(String fileName) =>
31+
'קובץ PDF נשמר בשם "$fileName"';
3032
static const String wordFileSaved = 'קובץ Word נשמר בהצלחה';
3133
static const String pdfFileSaved = 'קובץ PDF נשמר בהצלחה';
3234
static const String mobilePdfSaveFailed =

‎lib/printing/view/printing_screen.dart‎

Lines changed: 113 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import 'package:otzaria/settings/engine/settings_repository.dart';
1717
import 'package:otzaria/settings/services/safer_mode_guard.dart';
1818
import 'package:otzaria/core/messages/pdf_messages.dart';
1919
import 'package:otzaria/core/ui_snack.dart';
20+
import 'package:otzaria/core/windowing/app_window_keys.dart';
2021
import 'package:otzaria/theme/theme_exports.dart';
2122
import 'package:otzaria/models/links.dart';
2223
import 'package:otzaria/personal_notes/models/personal_note.dart';
@@ -52,6 +53,7 @@ import 'package:otzaria/printing/word_export_service.dart';
5253
import 'package:otzaria/utils/file/save_file_with_extension.dart';
5354
import 'package:otzaria/utils/file/desktop_save_target.dart';
5455
import 'package:otzaria/utils/file/atomic_file_publication.dart';
56+
import 'package:otzaria/utils/file/mobile_pdf_export_service.dart';
5557
import 'package:otzaria/utils/text/text_manipulation.dart';
5658
import 'package:otzaria/widgets/controls/action_buttons.dart';
5759
import '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),

‎test/printing/printing_screen_file_export_test.dart‎

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,15 @@ void main() {
289289
return (replacement) => replace(() => path = replacement);
290290
}
291291

292+
bool settingsBlocked(WidgetTester tester) => tester
293+
.widgetList<IgnorePointer>(
294+
find.ancestor(
295+
of: find.byType(PrintingPagesPerSheetDropdownRow),
296+
matching: find.byType(IgnorePointer),
297+
),
298+
)
299+
.any((widget) => widget.ignoring);
300+
292301
Future<void> chooseName(WidgetTester tester) async {
293302
await _waitFor(
294303
tester,
@@ -319,12 +328,12 @@ void main() {
319328
await open(tester, book: TextBook(title: 'stream-output'));
320329
await tester.tap(find.text('שמירה'));
321330
await tester.pump();
322-
expect(find.text('שומר קובץ...'), findsOneWidget);
331+
expect(find.text('שמירה'), findsOneWidget);
323332

324333
pending.complete(_ProtectedBookRepository());
325334
await _waitFor(
326335
tester,
327-
() => find.text('שומר קובץ...').evaluate().isEmpty,
336+
() => find.text('הדפסה').evaluate().isNotEmpty,
328337
);
329338
expect(find.text('הדפסה'), findsWidgets);
330339
expect(printer.requests, 0);
@@ -494,7 +503,7 @@ void main() {
494503
expect(target.readAsStringSync(), 'original');
495504
expect(output.listSync(), hasLength(2));
496505
pending.completeError(StateError('Synthetic PDF generation failure'));
497-
await _waitFor(tester, () => find.text('שמירה').evaluate().isNotEmpty);
506+
await _waitFor(tester, () => !settingsBlocked(tester));
498507
expect(target.readAsStringSync(), 'original');
499508
expect(output.listSync(), hasLength(1));
500509
expect(closed, isFalse);
@@ -560,18 +569,10 @@ void main() {
560569
// Both taps deliberately happen before a frame, then render the busy UI.
561570
await tester.pump();
562571
await _waitFor(tester, () => picker.selections == 1);
563-
expect(find.text('שומר קובץ...'), findsOneWidget);
564-
final settings = find.byType(PrintingPagesPerSheetDropdownRow);
565-
final blockers = find.ancestor(
566-
of: settings,
567-
matching: find.byType(IgnorePointer),
568-
);
569-
expect(
570-
blockers.evaluate().any((e) => (e.widget as IgnorePointer).ignoring),
571-
isTrue,
572-
);
572+
expect(find.text('שמירה'), findsOneWidget);
573+
expect(settingsBlocked(tester), isTrue);
573574
folder.complete(null);
574-
await _waitFor(tester, () => find.text('שמירה').evaluate().isNotEmpty);
575+
await _waitFor(tester, () => !settingsBlocked(tester));
575576
expect(picker.selections, 1);
576577
expect(picker.byteSaves, 0);
577578
expect(output.listSync(), isEmpty);
@@ -597,7 +598,7 @@ void main() {
597598
replace(input.path);
598599
await tester.pump();
599600
folder.complete(output.path);
600-
await _waitFor(tester, () => find.text('שמירה').evaluate().isNotEmpty);
601+
await _waitFor(tester, () => !settingsBlocked(tester));
601602
expect(find.byType(InputDialog), findsNothing);
602603
expect(output.listSync(), isEmpty);
603604
expect(closed, isFalse);

0 commit comments

Comments
 (0)