Skip to content
Merged
62 changes: 31 additions & 31 deletions lib/tools/calendar/helpers/calendar_print_helpers.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -55,37 +56,36 @@ Future<Uint8List> 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<Uint8List> _loadFont(String path) async =>
Expand Down
49 changes: 39 additions & 10 deletions lib/tools/tikkun_korim/export/tikkun_pdf_writer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,27 @@ import 'package:pdf/pdf.dart';
typedef TikkunFontLoader =
Future<Uint8List?> 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<Uint8List> Function(PdfDocument document);

PdfShapedFont _buildTikkunPdfFont(
PdfDocument document,
ShaperFont shaper,
Uint8List bytes,
) => PdfShapedFont(
document,
shaper: shaper,
fontBytes: bytes,
textForExtraction: restoreTikkunVavKetiaText,
);

Future<Uint8List> _saveTikkunPdf(PdfDocument document) =>
document.save(enableEventLoopBalancing: true);

/// טוען גופן מוטמע (נכס) או גופן מערכת שהסריקה מכירה. בולד מוחזר רק כשקיים
/// לו face אמיתי — אחרת הכותב מסנתז אותו ממשיחה.
Future<Uint8List?> loadTikkunExportFont(
Expand Down Expand Up @@ -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<String> fallbackFamilies;
Expand All @@ -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;
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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;
}
Expand Down
112 changes: 112 additions & 0 deletions test/printing/shaped_text/shaper_font_scope_test.dart
Original file line number Diff line number Diff line change
@@ -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) {
Expand Down Expand Up @@ -34,6 +39,16 @@ Future<int> _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;

Expand Down Expand Up @@ -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<void>(
createPrimary: () => ShaperFont.register(bytes),
createFallback: () => ShaperFont.register(Uint8List(0)),
action: (_, _) => fail('must not construct a PDF'),
),
throwsA(isA<ShaperException>()),
);
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<Uint8>(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<void>(
createPrimary: () => ShaperFont.register(bytes),
createFallback: () => ShaperFont.register(malformed),
action: (_, _) => fail('must not construct a PDF'),
),
throwsA(isA<ShaperException>()),
);
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<void>(
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<void>.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',
);
}
});
}
53 changes: 53 additions & 0 deletions test/tools/calendar/helpers/calendar_print_pdf_test.dart
Original file line number Diff line number Diff line change
@@ -1,15 +1,29 @@
// 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';
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);
Expand Down Expand Up @@ -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',
);
}
});
}
Loading
Loading