Skip to content

Commit cfefccb

Browse files
authored
Merge pull request #4528 from Otzaria/palmoni5/fix-calendar-tikkun-shaper-ownership-20261108
fix(printing): release ShaperFont owners on partial PDF font setup failures
2 parents 4407197 + 2b50a59 commit cfefccb

5 files changed

Lines changed: 445 additions & 41 deletions

File tree

‎lib/tools/calendar/helpers/calendar_print_helpers.dart‎

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import 'package:pdf/pdf.dart';
66
import 'package:pdf/widgets.dart' as pw;
77
import 'package:opentype_shaper/opentype_shaper.dart';
88
import 'package:otzaria/printing/shaped_text/pdf_shaped_font.dart';
9+
import 'package:otzaria/printing/shaped_text/shaper_font_scope.dart';
910
import 'package:otzaria/printing/shaped_text/shaped_text_layout.dart';
1011
import 'package:otzaria/printing/shaped_text/shaped_text_widget.dart';
1112
import 'package:otzaria/tools/calendar/bloc/calendar_cubit.dart';
@@ -55,37 +56,36 @@ Future<Uint8List> createCalendarPdf(
5556
'fonts/NotoSerifHebrew-VariableFont_wdth,wght.ttf',
5657
);
5758
final fallbackBytes = await _loadFont('fonts/Tinos-Regular.ttf');
58-
final primaryShaper = ShaperFont.register(primaryBytes);
59-
final fallbackShaper = ShaperFont.register(fallbackBytes);
60-
try {
61-
final pdf = pw.Document();
62-
final font = _CalendarText([
63-
PdfShapedFont(
64-
pdf.document,
65-
shaper: primaryShaper,
66-
fontBytes: primaryBytes,
67-
),
68-
PdfShapedFont(
69-
pdf.document,
70-
shaper: fallbackShaper,
71-
fontBytes: fallbackBytes,
72-
),
73-
]);
74-
75-
switch (resolveCalendarPrintLayout(state.calendarView)) {
76-
case CalendarPrintLayout.month:
77-
await _addMonthPages(pdf, state, font, format, count);
78-
case CalendarPrintLayout.week:
79-
await _addWeekPages(pdf, state, font, format, count);
80-
case CalendarPrintLayout.day:
81-
await _addDayPages(pdf, state, font, format, count);
82-
}
83-
84-
return await pdf.save();
85-
} finally {
86-
primaryShaper.dispose();
87-
fallbackShaper.dispose();
88-
}
59+
return withShaperFontPair(
60+
createPrimary: () => ShaperFont.register(primaryBytes),
61+
createFallback: () => ShaperFont.register(fallbackBytes),
62+
action: (primaryShaper, fallbackShaper) async {
63+
final pdf = pw.Document();
64+
final font = _CalendarText([
65+
PdfShapedFont(
66+
pdf.document,
67+
shaper: primaryShaper,
68+
fontBytes: primaryBytes,
69+
),
70+
PdfShapedFont(
71+
pdf.document,
72+
shaper: fallbackShaper,
73+
fontBytes: fallbackBytes,
74+
),
75+
]);
76+
77+
switch (resolveCalendarPrintLayout(state.calendarView)) {
78+
case CalendarPrintLayout.month:
79+
await _addMonthPages(pdf, state, font, format, count);
80+
case CalendarPrintLayout.week:
81+
await _addWeekPages(pdf, state, font, format, count);
82+
case CalendarPrintLayout.day:
83+
await _addDayPages(pdf, state, font, format, count);
84+
}
85+
86+
return await pdf.save();
87+
},
88+
);
8989
}
9090

9191
Future<Uint8List> _loadFont(String path) async =>

‎lib/tools/tikkun_korim/export/tikkun_pdf_writer.dart‎

Lines changed: 39 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,27 @@ import 'package:pdf/pdf.dart';
2424
typedef TikkunFontLoader =
2525
Future<Uint8List?> Function(String family, {required bool bold});
2626

27+
/// Allows ownership tests to inject a failure during PDF font construction.
28+
typedef TikkunPdfFontBuilder =
29+
PdfShapedFont Function(PdfDocument document, ShaperFont shaper, Uint8List bytes);
30+
31+
/// Allows ownership tests to inject an asynchronous PDF save failure.
32+
typedef TikkunPdfSaver = Future<Uint8List> Function(PdfDocument document);
33+
34+
PdfShapedFont _buildTikkunPdfFont(
35+
PdfDocument document,
36+
ShaperFont shaper,
37+
Uint8List bytes,
38+
) => PdfShapedFont(
39+
document,
40+
shaper: shaper,
41+
fontBytes: bytes,
42+
textForExtraction: restoreTikkunVavKetiaText,
43+
);
44+
45+
Future<Uint8List> _saveTikkunPdf(PdfDocument document) =>
46+
document.save(enableEventLoopBalancing: true);
47+
2748
/// טוען גופן מוטמע (נכס) או גופן מערכת שהסריקה מכירה. בולד מוחזר רק כשקיים
2849
/// לו face אמיתי — אחרת הכותב מסנתז אותו ממשיחה.
2950
Future<Uint8List?> loadTikkunExportFont(
@@ -87,6 +108,11 @@ class TikkunVectorPdfWriter {
87108
final PdfPageFormat pageFormat;
88109
final TikkunFontLoader loadFont;
89110

111+
/// Default implementations produce the same PDF; overrides are for failure
112+
/// injection in ownership tests.
113+
final TikkunPdfFontBuilder buildPdfFont;
114+
final TikkunPdfSaver savePdf;
115+
90116
/// משפחות שמנסים כשגופן המילה חסר גליף — קודם גופן הטור השני, ואז גופן
91117
/// ברירת המחדל של התוכנה שמכסה ספרות ואותיות לטיניות.
92118
final List<String> fallbackFamilies;
@@ -98,6 +124,8 @@ class TikkunVectorPdfWriter {
98124
required this.pageFormat,
99125
this.loadFont = loadTikkunExportFont,
100126
this.fallbackFamilies = const [AppFonts.defaultFont],
127+
this.buildPdfFont = _buildTikkunPdfFont,
128+
this.savePdf = _saveTikkunPdf,
101129
});
102130

103131
double get _usableWidth => pageFormat.width - 2 * kTikkunExportMarginPt;
@@ -142,7 +170,7 @@ class TikkunVectorPdfWriter {
142170
);
143171
}
144172
throwIfCancelled?.call();
145-
return await _document.save(enableEventLoopBalancing: true);
173+
return await savePdf(_document);
146174
} finally {
147175
for (final font in _fonts.values) {
148176
font?.shaper.dispose();
@@ -362,15 +390,16 @@ class TikkunVectorPdfWriter {
362390
final bytes = await loadFont(family, bold: bold);
363391
if (bytes != null) {
364392
final shaper = ShaperFont.register(bytes);
365-
font = _ExportFont(
366-
shaper,
367-
PdfShapedFont(
368-
_document,
369-
shaper: shaper,
370-
fontBytes: bytes,
371-
textForExtraction: restoreTikkunVavKetiaText,
372-
),
373-
);
393+
try {
394+
font = _ExportFont(
395+
shaper,
396+
buildPdfFont(_document, shaper, bytes),
397+
);
398+
} catch (_) {
399+
// The map owns the shaper only after construction completes.
400+
shaper.dispose();
401+
rethrow;
402+
}
374403
}
375404
return _fonts[key] = font;
376405
}

‎test/printing/shaped_text/shaper_font_scope_test.dart‎

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
1+
// ignore_for_file: implementation_imports
2+
3+
import 'dart:ffi';
14
import 'dart:io';
25
import 'dart:isolate';
36
import 'dart:typed_data';
47

8+
import 'package:ffi/ffi.dart';
59
import 'package:flutter_test/flutter_test.dart';
610
import 'package:opentype_shaper/opentype_shaper.dart';
11+
import 'package:opentype_shaper/src/bindings.dart';
712
import 'package:otzaria/printing/shaped_text/shaper_font_scope.dart';
813

914
bool _isRegistered(int handle) {
@@ -34,6 +39,16 @@ Future<int> _shapeAfterResume(
3439
},
3540
);
3641

42+
43+
int _drainUnexpectedNativeReferences(int handle) {
44+
for (var count = 0; count < 32; count++) {
45+
final status = ShaperBindings.instance.releaseFont(handle);
46+
if (status == ShaperStatus.unknownHandle) return count;
47+
expect(status, ShaperStatus.ok);
48+
}
49+
throw StateError('Native font reference count exceeded 32');
50+
}
51+
3752
void main() {
3853
late Uint8List bytes;
3954

@@ -159,4 +174,101 @@ void main() {
159174
ready.close();
160175
}
161176
});
177+
178+
test('native refcount returns to baseline after fallback registration fails', () async {
179+
final anchor = ShaperFont.register(bytes);
180+
final handle = anchor.handle;
181+
try {
182+
await expectLater(
183+
withShaperFontPair<void>(
184+
createPrimary: () => ShaperFont.register(bytes),
185+
createFallback: () => ShaperFont.register(Uint8List(0)),
186+
action: (_, _) => fail('must not construct a PDF'),
187+
),
188+
throwsA(isA<ShaperException>()),
189+
);
190+
expect(anchor.shape('בדיקה').glyphCount, greaterThan(0));
191+
} finally {
192+
anchor.dispose();
193+
}
194+
expect(_drainUnexpectedNativeReferences(handle), 0);
195+
});
196+
197+
test('fallback constructor failure after native registration releases its ref', () async {
198+
// Parseable SFNT header with missing tables: native register succeeds,
199+
// but ShaperFont.register throws while reading metrics in _attach.
200+
final malformed = (ByteData(12)..setUint32(0, 0x10000))
201+
.buffer
202+
.asUint8List();
203+
final malformedHandle = using((arena) {
204+
final data = arena<Uint8>(malformed.length);
205+
data.asTypedList(malformed.length).setAll(0, malformed);
206+
return ShaperBindings.instance.registerFont(data, malformed.length, 0);
207+
});
208+
expect(malformedHandle, greaterThan(0));
209+
210+
final validAnchor = ShaperFont.register(bytes);
211+
final validHandle = validAnchor.handle;
212+
try {
213+
await expectLater(
214+
withShaperFontPair<void>(
215+
createPrimary: () => ShaperFont.register(bytes),
216+
createFallback: () => ShaperFont.register(malformed),
217+
action: (_, _) => fail('must not construct a PDF'),
218+
),
219+
throwsA(isA<ShaperException>()),
220+
);
221+
expect(validAnchor.shape('בדיקה').glyphCount, greaterThan(0));
222+
// Exactly one native reference should remain: our raw registration.
223+
expect(
224+
ShaperBindings.instance.releaseFont(malformedHandle),
225+
ShaperStatus.ok,
226+
);
227+
expect(
228+
ShaperBindings.instance.releaseFont(malformedHandle),
229+
ShaperStatus.unknownHandle,
230+
);
231+
} finally {
232+
validAnchor.dispose();
233+
while (ShaperBindings.instance.releaseFont(malformedHandle) ==
234+
ShaperStatus.ok) {}
235+
}
236+
expect(_drainUnexpectedNativeReferences(validHandle), 0);
237+
});
238+
239+
test('native registry is freed after repeated save failures and double dispose', () async {
240+
for (var cycle = 0; cycle < 16; cycle++) {
241+
final anchor = ShaperFont.register(bytes);
242+
final handle = anchor.handle;
243+
final failure = StateError('pdf.save failed $cycle');
244+
try {
245+
await expectLater(
246+
withShaperFontPair<void>(
247+
createPrimary: () => ShaperFont.register(bytes),
248+
createFallback: () => ShaperFont.register(bytes),
249+
action: (primary, fallback) async {
250+
expect(primary.handle, handle);
251+
expect(fallback.handle, handle);
252+
if (cycle.isEven) {
253+
// Both owners may already be disposed by a client.
254+
primary.dispose();
255+
fallback.dispose();
256+
}
257+
await Future<void>.delayed(Duration.zero);
258+
throw failure;
259+
},
260+
),
261+
throwsA(same(failure)),
262+
);
263+
expect(anchor.shape('בדיקה').glyphCount, greaterThan(0));
264+
} finally {
265+
anchor.dispose();
266+
}
267+
expect(
268+
_drainUnexpectedNativeReferences(handle),
269+
0,
270+
reason: 'native reference leak on failure cycle $cycle',
271+
);
272+
}
273+
});
162274
}

‎test/tools/calendar/helpers/calendar_print_pdf_test.dart‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,29 @@
1+
// ignore_for_file: implementation_imports
2+
13
import 'dart:convert';
24
import 'dart:io';
35
import 'dart:typed_data';
46

7+
import 'package:flutter/services.dart' show rootBundle;
58
import 'package:flutter_test/flutter_test.dart';
9+
import 'package:opentype_shaper/opentype_shaper.dart';
10+
import 'package:opentype_shaper/src/bindings.dart';
611
import 'package:kosher_dart/kosher_dart.dart';
712
import 'package:otzaria/tools/calendar/helpers/calendar_print_helpers.dart';
813
import 'package:otzaria/tools/calendar/helpers/zmanim_helpers.dart';
914
import 'package:otzaria/tools/calendar/bloc/calendar_cubit.dart';
1015
import 'package:pdf/pdf.dart';
1116
import 'package:timezone/data/latest_all.dart' as tz;
1217

18+
int _drainUnexpectedNativeReferences(int handle) {
19+
for (var count = 0; count < 32; count++) {
20+
final status = ShaperBindings.instance.releaseFont(handle);
21+
if (status == ShaperStatus.unknownHandle) return count;
22+
expect(status, ShaperStatus.ok);
23+
}
24+
throw StateError('Native font reference count exceeded 32');
25+
}
26+
1327
void main() {
1428
TestWidgetsFlutterBinding.ensureInitialized();
1529
setUpAll(tz.initializeTimeZones);
@@ -137,4 +151,43 @@ void main() {
137151
final bytes = await createCalendarPdf(state, PdfPageFormat.a4);
138152
expect(pageCount(bytes), greaterThan(1));
139153
});
154+
155+
test('calendar PDF releases two distinct native font allocations after save', () async {
156+
final primaryData = await rootBundle.load(
157+
'fonts/NotoSerifHebrew-VariableFont_wdth,wght.ttf',
158+
);
159+
final fallbackData = await rootBundle.load('fonts/Tinos-Regular.ttf');
160+
final primaryBytes = primaryData.buffer.asUint8List();
161+
final fallbackBytes = fallbackData.buffer.asUint8List();
162+
final state = CalendarState.initial().copyWith(
163+
calendarView: CalendarView.week,
164+
);
165+
166+
for (var cycle = 0; cycle < 3; cycle++) {
167+
final primary = ShaperFont.register(primaryBytes);
168+
final fallback = ShaperFont.register(fallbackBytes);
169+
final primaryHandle = primary.handle;
170+
final fallbackHandle = fallback.handle;
171+
expect(primaryHandle, isNot(fallbackHandle));
172+
try {
173+
final pdf = await createCalendarPdf(state, PdfPageFormat.a4);
174+
expect(latin1.decode(pdf, allowInvalid: true), startsWith('%PDF-'));
175+
expect(primary.shape('בדיקה').glyphCount, greaterThan(0));
176+
expect(fallback.shape('test').glyphCount, greaterThan(0));
177+
} finally {
178+
fallback.dispose();
179+
primary.dispose();
180+
}
181+
expect(
182+
_drainUnexpectedNativeReferences(fallbackHandle),
183+
0,
184+
reason: 'fallback native allocation retained in cycle $cycle',
185+
);
186+
expect(
187+
_drainUnexpectedNativeReferences(primaryHandle),
188+
0,
189+
reason: 'primary native allocation retained in cycle $cycle',
190+
);
191+
}
192+
});
140193
}

0 commit comments

Comments
 (0)