Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .github/workflows/pdf_file_export.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@ on:
- 'test/printing/print_pdf_*_test.dart'
- 'test/printing/pdf_sheet_*_test.dart'
- 'test/printing/printing_screen_file_export_test.dart'
- 'test/printing/printing_screen_mobile_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/utils/file/mobile_pdf_export_*_test.dart'
- 'test/helpers/printing_raster_idle.dart'
- 'fonts/Tinos-Regular.ttf'
- 'fonts/NotoSerifHebrew-VariableFont_wdth,wght.ttf'
Expand Down Expand Up @@ -65,6 +67,7 @@ jobs:
DART_SUPPRESS_ANALYTICS: 'true'
OTZARIA_REQUIRE_SEARCH_ENGINE: '1'
CARGO_BUILD_JOBS: '2'
OTZARIA_MOBILE_PDF_UI_ARTIFACT_DIR: mobile-pdf-ui
steps:
- uses: actions/checkout@v7.0.1
- uses: subosito/flutter-action@v2
Expand Down Expand Up @@ -99,9 +102,13 @@ jobs:
test/printing/pdf_sheet_composer_test.dart
test/printing/pdf_sheet_file_output_test.dart
test/printing/printing_screen_file_export_test.dart
test/printing/printing_screen_mobile_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/utils/file/mobile_pdf_export_core_test.dart
test/utils/file/mobile_pdf_export_models_test.dart
test/utils/file/mobile_pdf_export_service_test.dart
- name: Preserve test results and toolchain identity
if: always()
uses: actions/upload-artifact@v7.0.2
Expand All @@ -113,3 +120,4 @@ jobs:
pdf-file-export-flutter.json
pdf-file-export-source.txt
pdf-file-export-tests.jsonl
mobile-pdf-ui/*.png
2 changes: 2 additions & 0 deletions lib/core/messages/pdf_messages.dart
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ abstract class PdfMessages {
static const String pageRangeRenderFailed = 'עיבוד טווח העמודים שנבחר נכשל';
static const String multiPageSheetRenderFailed =
'עיבוד עמודים מרובים בגיליון נכשל';
static String pdfFileSavedAs(String fileName) =>
'קובץ PDF נשמר בשם "$fileName"';
static const String wordFileSaved = 'קובץ Word נשמר בהצלחה';
static const String pdfFileSaved = 'קובץ PDF נשמר בהצלחה';
static const String mobilePdfSaveFailed =
Expand Down
141 changes: 113 additions & 28 deletions lib/printing/view/printing_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import 'package:otzaria/settings/engine/settings_repository.dart';
import 'package:otzaria/settings/services/safer_mode_guard.dart';
import 'package:otzaria/core/messages/pdf_messages.dart';
import 'package:otzaria/core/ui_snack.dart';
import 'package:otzaria/core/windowing/app_window_keys.dart';
import 'package:otzaria/theme/theme_exports.dart';
import 'package:otzaria/models/links.dart';
import 'package:otzaria/personal_notes/models/personal_note.dart';
Expand Down Expand Up @@ -52,6 +53,7 @@ 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/file/mobile_pdf_export_service.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';
Expand Down Expand Up @@ -169,6 +171,7 @@ class PrintingScreen extends StatefulWidget {

/// קובץ קיים נפתח ישירות; בתים מלאים נקראים רק כשיעד הפלט דורש אותם.
final String? pdfFilePath;
final MobilePdfExportService? mobileExportService;
final String bookId;
final TextBook? book;
final List<Link> links;
Expand Down Expand Up @@ -212,6 +215,7 @@ class PrintingScreen extends StatefulWidget {
required this.data,
this.createPdfOverride,
this.pdfFilePath,
this.mobileExportService,
required this.bookId,
this.book,
this.links = const [],
Expand Down Expand Up @@ -323,6 +327,9 @@ class _PrintingScreenState extends State<PrintingScreen> {
bool get _isPrinting => _printProgress != null;
bool _destinationActionPending = false;
PdfExportCancellationToken? _exportCancellation;
MobilePdfExportOperation? _mobileExport;
MobilePdfExportService get _mobileExports =>
widget.mobileExportService ?? MobilePdfExportService.instance;
Timer? _previewRefreshTimer;

// נקודות הקצה של טווח ההדפסה — כל אחת עצמאית בסוגה (כותרת/כותרת משנה/שורה).
Expand Down Expand Up @@ -542,7 +549,7 @@ class _PrintingScreenState extends State<PrintingScreen> {
_cachedBaseKey = null;
_pendingBasePdfs.clear();
_basePdfFiles.invalidate();
_exportCancellation?.cancel();
_cancelFileExport();
_anchorEntries = null;
_totalPdfPages = 0;
if (_isPdfSource) {
Expand Down Expand Up @@ -709,6 +716,7 @@ class _PrintingScreenState extends State<PrintingScreen> {
);
_preview.dispose();
_releasePreviewBase();
_cancelFileExport();
_exportCancellation?.dispose();
_trackFileCleanup(_basePdfFiles.dispose());
_cachedBasePdf = null;
Expand Down Expand Up @@ -2061,37 +2069,42 @@ class _PrintingScreenState extends State<PrintingScreen> {

Future<bool> _saveToFile(_ExportFormat selectedFormat) async {
final cancellation = _exportCancellation!;
if (!mounted || cancellation.isCancelled) return false;
if (!await verifySaferModePassword(context)) 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)) {
if (selectedFormat == _ExportFormat.pdf) {
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 mobile = _mobileExports;
if (mobile.isSupported) {
return await _saveMobilePdf(mobile, plan, cancellation, fileName);
}
if (Platform.isWindows || Platform.isLinux || Platform.isMacOS) {
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;
}
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.
// The remaining output contracts still require complete bytes.
final Uint8List bytes;
final String successMessage;
if (selectedFormat == _ExportFormat.word) {
Expand Down Expand Up @@ -2138,6 +2151,82 @@ class _PrintingScreenState extends State<PrintingScreen> {
}
}

void _cancelFileExport() {
_exportCancellation?.cancel();
final operation = _mobileExport;
if (operation != null) unawaited(_cancelMobileExport(operation));
}

Future<void> _cancelMobileExport(MobilePdfExportOperation operation) async {
try {
await operation.cancel();
} catch (error, stack) {
debugPrint('Mobile PDF cancellation request failed: $error\n$stack');
}
}

Future<bool> _saveMobilePdf(
MobilePdfExportService service,
_PdfFileExport plan,
PdfExportCancellationToken cancellation,
String fileName,
) async {
final window = AppWindowKeys.of(context);
MobilePdfExportOperation? operation;
try {
operation = service.start(
fileName: fileName,
producer: (path) => _writeOutputPdfToFile(plan, cancellation, path),
onCancelRequested: cancellation.cancel,
);
_mobileExport = operation;
final pending = operation.result;
// Only the original result releases staging; cancel merely requests it.
// The idle barrier observes completion; the await below reports errors.
_trackFileCleanup(
pending.then<void>((_) {}, onError: (Object _, StackTrace _) {}),
);
final result = await pending;
if (result.cleanupError != null) {
debugPrint('Mobile PDF export cleanup: ${result.cleanupError}');
}
if (result.residualDocument != null) {
UiSnack.showWarning(
PdfMessages.mobilePdfExportResidual(result.residualDisplayName),
window: window,
);
return false;
}
if (result.status == MobilePdfExportStatus.saved) {
final name = result.displayName;
UiSnack.showSuccess(
name != null && name != fileName
? PdfMessages.pdfFileSavedAs(name)
: PdfMessages.pdfFileSaved,
window: window,
);
return !_fileExportCancelled(plan, cancellation);
}
if (result.status == MobilePdfExportStatus.failed) {
debugPrint(
'Mobile PDF export failed: ${result.errorCode}: ${result.errorMessage}',
);
if (mounted && !cancellation.isCancelled) {
UiSnack.showError(PdfMessages.mobilePdfSaveFailed, window: window);
}
}
return false;
} catch (error, stack) {
debugPrint('Mobile PDF export failed: $error\n$stack');
if (mounted && !cancellation.isCancelled) {
UiSnack.showError(PdfMessages.mobilePdfSaveFailed, window: window);
}
return false;
} finally {
if (identical(_mobileExport, operation)) _mobileExport = null;
}
}

String _sanitizeFileName(String value) {
final sanitized = value.replaceAll(RegExp(r'[<>:"/\\|?*]'), '_').trim();
return sanitized.isEmpty ? 'output' : sanitized;
Expand Down Expand Up @@ -2421,7 +2510,7 @@ class _PrintingScreenState extends State<PrintingScreen> {
_previewRefreshTimer?.cancel();
_preview.stop();
_releasePreviewBase();
_exportCancellation?.cancel();
_cancelFileExport();
},
child: dialog,
);
Expand Down Expand Up @@ -2829,13 +2918,9 @@ class _PrintingScreenState extends State<PrintingScreen> {
),
const SizedBox(width: 8),
Expanded(
child: _destinationActionPending
child: _isPrinting
? ActionButton.recommended(
text:
_printProgress ??
(_exportCancellation != null
? 'שומר קובץ...'
: PdfMessages.printPreparing),
text: _printProgress!,
iconWidget: SizedBox.square(
dimension: 16,
child: CircularProgressIndicator(strokeWidth: 2),
Expand Down
31 changes: 16 additions & 15 deletions test/printing/printing_screen_file_export_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,15 @@ void main() {
return (replacement) => replace(() => path = replacement);
}

bool settingsBlocked(WidgetTester tester) => tester
.widgetList<IgnorePointer>(
find.ancestor(
of: find.byType(PrintingPagesPerSheetDropdownRow),
matching: find.byType(IgnorePointer),
),
)
.any((widget) => widget.ignoring);

Future<void> chooseName(WidgetTester tester) async {
await _waitFor(
tester,
Expand Down Expand Up @@ -319,12 +328,12 @@ void main() {
await open(tester, book: TextBook(title: 'stream-output'));
await tester.tap(find.text('שמירה'));
await tester.pump();
expect(find.text('שומר קובץ...'), findsOneWidget);
expect(find.text('שמירה'), findsOneWidget);

pending.complete(_ProtectedBookRepository());
await _waitFor(
tester,
() => find.text('שומר קובץ...').evaluate().isEmpty,
() => find.text('הדפסה').evaluate().isNotEmpty,
);
expect(find.text('הדפסה'), findsWidgets);
expect(printer.requests, 0);
Expand Down Expand Up @@ -494,7 +503,7 @@ void main() {
expect(target.readAsStringSync(), 'original');
expect(output.listSync(), hasLength(2));
pending.completeError(StateError('Synthetic PDF generation failure'));
await _waitFor(tester, () => find.text('שמירה').evaluate().isNotEmpty);
await _waitFor(tester, () => !settingsBlocked(tester));
expect(target.readAsStringSync(), 'original');
expect(output.listSync(), hasLength(1));
expect(closed, isFalse);
Expand Down Expand Up @@ -560,18 +569,10 @@ void main() {
// 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,
);
expect(find.text('שמירה'), findsOneWidget);
expect(settingsBlocked(tester), isTrue);
folder.complete(null);
await _waitFor(tester, () => find.text('שמירה').evaluate().isNotEmpty);
await _waitFor(tester, () => !settingsBlocked(tester));
expect(picker.selections, 1);
expect(picker.byteSaves, 0);
expect(output.listSync(), isEmpty);
Expand All @@ -597,7 +598,7 @@ void main() {
replace(input.path);
await tester.pump();
folder.complete(output.path);
await _waitFor(tester, () => find.text('שמירה').evaluate().isNotEmpty);
await _waitFor(tester, () => !settingsBlocked(tester));
expect(find.byType(InputDialog), findsNothing);
expect(output.listSync(), isEmpty);
expect(closed, isFalse);
Expand Down
Loading
Loading