diff --git a/lib/tools/calendar/helpers/calendar_print_helpers.dart b/lib/tools/calendar/helpers/calendar_print_helpers.dart index ab2b32871a..c0977599ba 100644 --- a/lib/tools/calendar/helpers/calendar_print_helpers.dart +++ b/lib/tools/calendar/helpers/calendar_print_helpers.dart @@ -6,6 +6,7 @@ import 'package:pdf/pdf.dart'; import 'package:pdf/widgets.dart' as pw; import 'package:opentype_shaper/opentype_shaper.dart'; import 'package:otzaria/printing/shaped_text/pdf_shaped_font.dart'; +import 'package:otzaria/printing/shaped_text/shaper_font_scope.dart'; import 'package:otzaria/printing/shaped_text/shaped_text_layout.dart'; import 'package:otzaria/printing/shaped_text/shaped_text_widget.dart'; import 'package:otzaria/tools/calendar/bloc/calendar_cubit.dart'; @@ -55,37 +56,36 @@ Future createCalendarPdf( 'fonts/NotoSerifHebrew-VariableFont_wdth,wght.ttf', ); final fallbackBytes = await _loadFont('fonts/Tinos-Regular.ttf'); - final primaryShaper = ShaperFont.register(primaryBytes); - final fallbackShaper = ShaperFont.register(fallbackBytes); - try { - final pdf = pw.Document(); - final font = _CalendarText([ - PdfShapedFont( - pdf.document, - shaper: primaryShaper, - fontBytes: primaryBytes, - ), - PdfShapedFont( - pdf.document, - shaper: fallbackShaper, - fontBytes: fallbackBytes, - ), - ]); - - switch (resolveCalendarPrintLayout(state.calendarView)) { - case CalendarPrintLayout.month: - await _addMonthPages(pdf, state, font, format, count); - case CalendarPrintLayout.week: - await _addWeekPages(pdf, state, font, format, count); - case CalendarPrintLayout.day: - await _addDayPages(pdf, state, font, format, count); - } - - return await pdf.save(); - } finally { - primaryShaper.dispose(); - fallbackShaper.dispose(); - } + return withShaperFontPair( + createPrimary: () => ShaperFont.register(primaryBytes), + createFallback: () => ShaperFont.register(fallbackBytes), + action: (primaryShaper, fallbackShaper) async { + final pdf = pw.Document(); + final font = _CalendarText([ + PdfShapedFont( + pdf.document, + shaper: primaryShaper, + fontBytes: primaryBytes, + ), + PdfShapedFont( + pdf.document, + shaper: fallbackShaper, + fontBytes: fallbackBytes, + ), + ]); + + switch (resolveCalendarPrintLayout(state.calendarView)) { + case CalendarPrintLayout.month: + await _addMonthPages(pdf, state, font, format, count); + case CalendarPrintLayout.week: + await _addWeekPages(pdf, state, font, format, count); + case CalendarPrintLayout.day: + await _addDayPages(pdf, state, font, format, count); + } + + return await pdf.save(); + }, + ); } Future _loadFont(String path) async => diff --git a/lib/tools/tikkun_korim/export/tikkun_pdf_writer.dart b/lib/tools/tikkun_korim/export/tikkun_pdf_writer.dart index 4e48961665..8ae1f5ef46 100644 --- a/lib/tools/tikkun_korim/export/tikkun_pdf_writer.dart +++ b/lib/tools/tikkun_korim/export/tikkun_pdf_writer.dart @@ -24,6 +24,27 @@ import 'package:pdf/pdf.dart'; typedef TikkunFontLoader = Future Function(String family, {required bool bold}); +/// Allows ownership tests to inject a failure during PDF font construction. +typedef TikkunPdfFontBuilder = + PdfShapedFont Function(PdfDocument document, ShaperFont shaper, Uint8List bytes); + +/// Allows ownership tests to inject an asynchronous PDF save failure. +typedef TikkunPdfSaver = Future Function(PdfDocument document); + +PdfShapedFont _buildTikkunPdfFont( + PdfDocument document, + ShaperFont shaper, + Uint8List bytes, +) => PdfShapedFont( + document, + shaper: shaper, + fontBytes: bytes, + textForExtraction: restoreTikkunVavKetiaText, +); + +Future _saveTikkunPdf(PdfDocument document) => + document.save(enableEventLoopBalancing: true); + /// טוען גופן מוטמע (נכס) או גופן מערכת שהסריקה מכירה. בולד מוחזר רק כשקיים /// לו face אמיתי — אחרת הכותב מסנתז אותו ממשיחה. Future loadTikkunExportFont( @@ -87,6 +108,11 @@ class TikkunVectorPdfWriter { final PdfPageFormat pageFormat; final TikkunFontLoader loadFont; + /// Default implementations produce the same PDF; overrides are for failure + /// injection in ownership tests. + final TikkunPdfFontBuilder buildPdfFont; + final TikkunPdfSaver savePdf; + /// משפחות שמנסים כשגופן המילה חסר גליף — קודם גופן הטור השני, ואז גופן /// ברירת המחדל של התוכנה שמכסה ספרות ואותיות לטיניות. final List fallbackFamilies; @@ -98,6 +124,8 @@ class TikkunVectorPdfWriter { required this.pageFormat, this.loadFont = loadTikkunExportFont, this.fallbackFamilies = const [AppFonts.defaultFont], + this.buildPdfFont = _buildTikkunPdfFont, + this.savePdf = _saveTikkunPdf, }); double get _usableWidth => pageFormat.width - 2 * kTikkunExportMarginPt; @@ -142,7 +170,7 @@ class TikkunVectorPdfWriter { ); } throwIfCancelled?.call(); - return await _document.save(enableEventLoopBalancing: true); + return await savePdf(_document); } finally { for (final font in _fonts.values) { font?.shaper.dispose(); @@ -362,15 +390,16 @@ class TikkunVectorPdfWriter { final bytes = await loadFont(family, bold: bold); if (bytes != null) { final shaper = ShaperFont.register(bytes); - font = _ExportFont( - shaper, - PdfShapedFont( - _document, - shaper: shaper, - fontBytes: bytes, - textForExtraction: restoreTikkunVavKetiaText, - ), - ); + try { + font = _ExportFont( + shaper, + buildPdfFont(_document, shaper, bytes), + ); + } catch (_) { + // The map owns the shaper only after construction completes. + shaper.dispose(); + rethrow; + } } return _fonts[key] = font; } diff --git a/test/printing/shaped_text/shaper_font_scope_test.dart b/test/printing/shaped_text/shaper_font_scope_test.dart index 7c09082bce..97eb9c6d17 100644 --- a/test/printing/shaped_text/shaper_font_scope_test.dart +++ b/test/printing/shaped_text/shaper_font_scope_test.dart @@ -1,9 +1,14 @@ +// ignore_for_file: implementation_imports + +import 'dart:ffi'; import 'dart:io'; import 'dart:isolate'; import 'dart:typed_data'; +import 'package:ffi/ffi.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:opentype_shaper/opentype_shaper.dart'; +import 'package:opentype_shaper/src/bindings.dart'; import 'package:otzaria/printing/shaped_text/shaper_font_scope.dart'; bool _isRegistered(int handle) { @@ -34,6 +39,16 @@ Future _shapeAfterResume( }, ); + +int _drainUnexpectedNativeReferences(int handle) { + for (var count = 0; count < 32; count++) { + final status = ShaperBindings.instance.releaseFont(handle); + if (status == ShaperStatus.unknownHandle) return count; + expect(status, ShaperStatus.ok); + } + throw StateError('Native font reference count exceeded 32'); +} + void main() { late Uint8List bytes; @@ -159,4 +174,101 @@ void main() { ready.close(); } }); + + test('native refcount returns to baseline after fallback registration fails', () async { + final anchor = ShaperFont.register(bytes); + final handle = anchor.handle; + try { + await expectLater( + withShaperFontPair( + createPrimary: () => ShaperFont.register(bytes), + createFallback: () => ShaperFont.register(Uint8List(0)), + action: (_, _) => fail('must not construct a PDF'), + ), + throwsA(isA()), + ); + expect(anchor.shape('בדיקה').glyphCount, greaterThan(0)); + } finally { + anchor.dispose(); + } + expect(_drainUnexpectedNativeReferences(handle), 0); + }); + + test('fallback constructor failure after native registration releases its ref', () async { + // Parseable SFNT header with missing tables: native register succeeds, + // but ShaperFont.register throws while reading metrics in _attach. + final malformed = (ByteData(12)..setUint32(0, 0x10000)) + .buffer + .asUint8List(); + final malformedHandle = using((arena) { + final data = arena(malformed.length); + data.asTypedList(malformed.length).setAll(0, malformed); + return ShaperBindings.instance.registerFont(data, malformed.length, 0); + }); + expect(malformedHandle, greaterThan(0)); + + final validAnchor = ShaperFont.register(bytes); + final validHandle = validAnchor.handle; + try { + await expectLater( + withShaperFontPair( + createPrimary: () => ShaperFont.register(bytes), + createFallback: () => ShaperFont.register(malformed), + action: (_, _) => fail('must not construct a PDF'), + ), + throwsA(isA()), + ); + expect(validAnchor.shape('בדיקה').glyphCount, greaterThan(0)); + // Exactly one native reference should remain: our raw registration. + expect( + ShaperBindings.instance.releaseFont(malformedHandle), + ShaperStatus.ok, + ); + expect( + ShaperBindings.instance.releaseFont(malformedHandle), + ShaperStatus.unknownHandle, + ); + } finally { + validAnchor.dispose(); + while (ShaperBindings.instance.releaseFont(malformedHandle) == + ShaperStatus.ok) {} + } + expect(_drainUnexpectedNativeReferences(validHandle), 0); + }); + + test('native registry is freed after repeated save failures and double dispose', () async { + for (var cycle = 0; cycle < 16; cycle++) { + final anchor = ShaperFont.register(bytes); + final handle = anchor.handle; + final failure = StateError('pdf.save failed $cycle'); + try { + await expectLater( + withShaperFontPair( + createPrimary: () => ShaperFont.register(bytes), + createFallback: () => ShaperFont.register(bytes), + action: (primary, fallback) async { + expect(primary.handle, handle); + expect(fallback.handle, handle); + if (cycle.isEven) { + // Both owners may already be disposed by a client. + primary.dispose(); + fallback.dispose(); + } + await Future.delayed(Duration.zero); + throw failure; + }, + ), + throwsA(same(failure)), + ); + expect(anchor.shape('בדיקה').glyphCount, greaterThan(0)); + } finally { + anchor.dispose(); + } + expect( + _drainUnexpectedNativeReferences(handle), + 0, + reason: 'native reference leak on failure cycle $cycle', + ); + } + }); } diff --git a/test/tools/calendar/helpers/calendar_print_pdf_test.dart b/test/tools/calendar/helpers/calendar_print_pdf_test.dart index cffc9e1162..c062c0f10a 100644 --- a/test/tools/calendar/helpers/calendar_print_pdf_test.dart +++ b/test/tools/calendar/helpers/calendar_print_pdf_test.dart @@ -1,8 +1,13 @@ +// ignore_for_file: implementation_imports + import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; +import 'package:flutter/services.dart' show rootBundle; import 'package:flutter_test/flutter_test.dart'; +import 'package:opentype_shaper/opentype_shaper.dart'; +import 'package:opentype_shaper/src/bindings.dart'; import 'package:kosher_dart/kosher_dart.dart'; import 'package:otzaria/tools/calendar/helpers/calendar_print_helpers.dart'; import 'package:otzaria/tools/calendar/helpers/zmanim_helpers.dart'; @@ -10,6 +15,15 @@ import 'package:otzaria/tools/calendar/bloc/calendar_cubit.dart'; import 'package:pdf/pdf.dart'; import 'package:timezone/data/latest_all.dart' as tz; +int _drainUnexpectedNativeReferences(int handle) { + for (var count = 0; count < 32; count++) { + final status = ShaperBindings.instance.releaseFont(handle); + if (status == ShaperStatus.unknownHandle) return count; + expect(status, ShaperStatus.ok); + } + throw StateError('Native font reference count exceeded 32'); +} + void main() { TestWidgetsFlutterBinding.ensureInitialized(); setUpAll(tz.initializeTimeZones); @@ -137,4 +151,43 @@ void main() { final bytes = await createCalendarPdf(state, PdfPageFormat.a4); expect(pageCount(bytes), greaterThan(1)); }); + + test('calendar PDF releases two distinct native font allocations after save', () async { + final primaryData = await rootBundle.load( + 'fonts/NotoSerifHebrew-VariableFont_wdth,wght.ttf', + ); + final fallbackData = await rootBundle.load('fonts/Tinos-Regular.ttf'); + final primaryBytes = primaryData.buffer.asUint8List(); + final fallbackBytes = fallbackData.buffer.asUint8List(); + final state = CalendarState.initial().copyWith( + calendarView: CalendarView.week, + ); + + for (var cycle = 0; cycle < 3; cycle++) { + final primary = ShaperFont.register(primaryBytes); + final fallback = ShaperFont.register(fallbackBytes); + final primaryHandle = primary.handle; + final fallbackHandle = fallback.handle; + expect(primaryHandle, isNot(fallbackHandle)); + try { + final pdf = await createCalendarPdf(state, PdfPageFormat.a4); + expect(latin1.decode(pdf, allowInvalid: true), startsWith('%PDF-')); + expect(primary.shape('בדיקה').glyphCount, greaterThan(0)); + expect(fallback.shape('test').glyphCount, greaterThan(0)); + } finally { + fallback.dispose(); + primary.dispose(); + } + expect( + _drainUnexpectedNativeReferences(fallbackHandle), + 0, + reason: 'fallback native allocation retained in cycle $cycle', + ); + expect( + _drainUnexpectedNativeReferences(primaryHandle), + 0, + reason: 'primary native allocation retained in cycle $cycle', + ); + } + }); } diff --git a/test/tools/tikkun_korim/export/tikkun_pdf_bytes_test.dart b/test/tools/tikkun_korim/export/tikkun_pdf_bytes_test.dart index f09c9bc324..ffcf24684c 100644 --- a/test/tools/tikkun_korim/export/tikkun_pdf_bytes_test.dart +++ b/test/tools/tikkun_korim/export/tikkun_pdf_bytes_test.dart @@ -2,12 +2,18 @@ /// משותף לעמודים מקוריים. library; +// ignore_for_file: implementation_imports + +import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'package:flutter/painting.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:opentype_shaper/opentype_shaper.dart'; +import 'package:opentype_shaper/src/bindings.dart'; +import 'package:otzaria/printing/shaped_text/pdf_shaped_font.dart'; import 'package:otzaria/tools/tikkun_korim/export/tikkun_pdf_exporter.dart'; import 'package:otzaria/tools/tikkun_korim/export/tikkun_pdf_writer.dart'; import 'package:otzaria/tools/tikkun_korim/export/tikkun_vector_ops.dart'; @@ -67,6 +73,24 @@ List _inflatedStreams(Uint8List bytes) { return streams; } +/// Number of native registry references left after the Dart owners dispose. +/// A nonzero result means the font's native entry was still allocated. +int _drainUnexpectedNativeReferences(int handle) { + for (var count = 0; count < 32; count++) { + final status = ShaperBindings.instance.releaseFont(handle); + if (status == ShaperStatus.unknownHandle) return count; + expect(status, ShaperStatus.ok); + } + throw StateError('Native font reference count exceeded 32'); +} + +TikkunVectorPage _ownershipPage() => TikkunVectorPage( + texts: [_text('בְּרֵאשִׁית')], + rects: const [], + width: 400, + height: 200, +); + void main() { TestWidgetsFlutterBinding.ensureInitialized(); for (final cff in [false, true]) { @@ -249,4 +273,190 @@ void main() { throwsA(isA()), ); }); + + test('failed PdfShapedFont construction rolls back the native owner', () async { + final fontBytes = File(_fontPath).readAsBytesSync(); + final anchor = ShaperFont.register(fontBytes); + final handle = anchor.handle; + final failure = StateError('injected PDF font construction failure'); + var builderCalls = 0; + try { + final writer = TikkunVectorPdfWriter( + pageFormat: PdfPageFormat.a4, + loadFont: (_, {required bool bold}) async => fontBytes, + fallbackFamilies: const [], + buildPdfFont: (document, shaper, bytes) { + builderCalls++; + expect(shaper.handle, handle); + expect(bytes, same(fontBytes)); + throw failure; + }, + ); + + await expectLater( + writer.write([_ownershipPage()], unifyScale: false), + throwsA(same(failure)), + ); + expect(builderCalls, 1); + expect(anchor.shape('בדיקה').glyphCount, greaterThan(0)); + } finally { + anchor.dispose(); + } + expect(_drainUnexpectedNativeReferences(handle), 0); + }); + + test('failed second PDF font rolls back while first font is cached', () async { + final fontBytes = File(_fontPath).readAsBytesSync(); + final anchor = ShaperFont.register(fontBytes); + final handle = anchor.handle; + final failure = StateError('second PDF font construction failed'); + var builderCalls = 0; + try { + final writer = TikkunVectorPdfWriter( + pageFormat: PdfPageFormat.a4, + loadFont: (_, {required bool bold}) async => fontBytes, + fallbackFamilies: const [], + buildPdfFont: (document, shaper, bytes) { + builderCalls++; + expect(shaper.handle, handle); + if (builderCalls == 2) throw failure; + return PdfShapedFont( + document, + shaper: shaper, + fontBytes: bytes, + textForExtraction: restoreTikkunVavKetiaText, + ); + }, + ); + final page = TikkunVectorPage( + texts: [ + _text('בְּרֵאשִׁית'), + TikkunTextOp( + text: 'בָּרָא', + style: const TextStyle(fontFamily: 'second-family', fontSize: 25), + left: 170, + width: 60, + baseline: 50, + rtl: true, + ), + ], + rects: const [], + width: 400, + height: 200, + ); + + await expectLater( + writer.write([page], unifyScale: false), + throwsA(same(failure)), + ); + expect(builderCalls, 2); + expect(anchor.shape('בדיקה').glyphCount, greaterThan(0)); + } finally { + anchor.dispose(); + } + expect(_drainUnexpectedNativeReferences(handle), 0); + }); + + test('native owner survives suspended save and is freed after save throws', () async { + final fontBytes = File(_fontPath).readAsBytesSync(); + final anchor = ShaperFont.register(fontBytes); + final handle = anchor.handle; + final enteredSave = Completer(); + final finishSave = Completer(); + final failure = StateError('injected asynchronous pdf.save failure'); + final writer = TikkunVectorPdfWriter( + pageFormat: PdfPageFormat.a4, + loadFont: (_, {required bool bold}) async => fontBytes, + fallbackFamilies: const [], + savePdf: (_) async { + enteredSave.complete(); + await finishSave.future; + throw failure; + }, + ); + + final pending = writer.write([_ownershipPage()], unifyScale: false); + try { + await enteredSave.future.timeout(const Duration(seconds: 15)); + // Drop the independent reference. The writer must now be the only owner + // keeping the native allocation available during the pending save. + anchor.dispose(); + final borrowed = ShaperFont.attach(handle); + try { + expect(borrowed.shape('בדיקה').glyphCount, greaterThan(0)); + } finally { + borrowed.dispose(); + } + finishSave.complete(); + await expectLater(pending, throwsA(same(failure))); + } finally { + if (!finishSave.isCompleted) finishSave.complete(); + anchor.dispose(); + } + expect(_drainUnexpectedNativeReferences(handle), 0); + }); + + test('cancellation after font loading releases every native reference', () async { + final fontBytes = File(_fontPath).readAsBytesSync(); + final anchor = ShaperFont.register(fontBytes); + final handle = anchor.handle; + var registered = false; + try { + final writer = TikkunVectorPdfWriter( + pageFormat: PdfPageFormat.a4, + loadFont: (_, {required bool bold}) async { + registered = true; + return fontBytes; + }, + fallbackFamilies: const [], + ); + await expectLater( + writer.write( + [_ownershipPage()], + unifyScale: false, + throwIfCancelled: () { + if (registered) throw const TikkunExportCancelled(); + }, + ), + throwsA(isA()), + ); + expect(registered, isTrue); + expect(anchor.shape('בדיקה').glyphCount, greaterThan(0)); + } finally { + anchor.dispose(); + } + expect(_drainUnexpectedNativeReferences(handle), 0); + }); + + test('repeated successful PDF exports leave no native font allocation', () async { + final fontBytes = File(_fontPath).readAsBytesSync(); + for (var cycle = 0; cycle < 8; cycle++) { + final anchor = ShaperFont.register(fontBytes); + final handle = anchor.handle; + var loaded = 0; + try { + final writer = TikkunVectorPdfWriter( + pageFormat: PdfPageFormat.a4, + loadFont: (_, {required bool bold}) async { + loaded++; + return fontBytes; + }, + fallbackFamilies: const [], + ); + final pdf = await writer.write( + [_ownershipPage()], + unifyScale: false, + ); + expect(latin1.decode(pdf, allowInvalid: true), startsWith('%PDF-')); + expect(loaded, 1, reason: 'registration cycle $cycle'); + } finally { + anchor.dispose(); + } + expect( + _drainUnexpectedNativeReferences(handle), + 0, + reason: 'native registry leak after cycle $cycle', + ); + } + }); }