jubarte-render 0.21.0

The render product of the jubarte engine: DOCX to PDF and PNG, with Word-faithful layout
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
//
// SPDX-License-Identifier: Apache-2.0

//! Where a catalogue slot's face comes from, and what happens when no
//! source has one: a build without `embedded-fonts` (#196) on a machine
//! without the face. The catalogue is injected here, so each test states
//! its sources whatever this build embeds and whatever this machine has
//! installed.

use super::*;

/// A catalogue no source fills, for the scope of `f`.
fn without_catalogue_fonts<T>(f: impl FnOnce() -> T) -> T {
    font::with_slot_loader(|_| None, f)
}

/// No face from the machine, and none from the catalogue: a build
/// without `embedded-fonts` on a machine that has none of the faces,
/// whatever this one has installed.
fn without_any_font<T>(f: impl FnOnce() -> T) -> T {
    font::with_scope(font::FontScope::HERMETIC, || without_catalogue_fonts(f))
}

#[test]
fn a_slot_no_source_fills_hands_out_an_absent_face_instead_of_panicking() {
    without_catalogue_fonts(|| {
        let fonts = Fonts::new();
        for id in FaceId::all() {
            assert!(font::catalogue_face(id).is_none(), "{id:?} is not loaded");
            let face = fonts.get(id);
            assert!(face.is_absent(), "{id:?}");
            assert_eq!(face.pdf_name(), "", "{id:?} names no physical face");
            assert!(face.bytes().is_empty(), "{id:?} carries no program");
            // It measures like a plain text face, so a layout that reaches
            // it divides by nothing zero and indexes nothing empty.
            assert_eq!(
                face.width_1000('x'),
                500,
                "{id:?}: glyph 0 moves half an em"
            );
            assert!(face.single_line_pt(11.0) > 0.0, "{id:?}");
            assert!(face.ascent_pt(11.0) > 0.0, "{id:?}");
            assert!(face.width_pt("Hello", 11.0) > 0.0, "{id:?}");
            for text in ["Hello", "研究", "متن", "\u{F0B7}"] {
                assert_eq!(
                    face.glyphs(text).len(),
                    text.chars().count(),
                    "{id:?}: {text}"
                );
                assert_eq!(
                    face.glyph_texts(text, false).len(),
                    text.chars().count(),
                    "{id:?}: {text}"
                );
            }
        }
        // A document's own face still answers under its own name.
        let mut fonts = Fonts::new();
        fonts.insert_embedded("Memory", false, false, FaceId::MonoRegular.bytes());
        assert_eq!(
            fonts.get(fonts.resolve("Memory", false, false)).pdf_name(),
            "LiberationMono"
        );
    });
}

#[test]
fn the_injected_catalogue_reaches_every_slot_a_document_asks_for() {
    font::with_slot_loader(
        |id| (id == FaceId::CarlitoRegular).then(|| Face::bundled(id)),
        || {
            let fonts = Fonts::new();
            assert_eq!(fonts.get(FaceId::CarlitoRegular).pdf_name(), "Carlito");
            assert!(fonts.get(FaceId::CarlitoBold).is_absent());
            // An unknown family ends in the Cambria slot, which is empty.
            assert!(
                fonts
                    .get(fonts.resolve("No Such Family", true, true))
                    .is_absent()
            );
        },
    );
}

#[test]
fn an_injected_catalogue_ends_with_its_scope() {
    without_any_font(|| {
        assert!(font::catalogue_face(FaceId::SansRegular).is_none());
    });
    // A test build carries the embedded programs, so the process's own
    // catalogue serves the slot again.
    assert!(font::catalogue_face(FaceId::SansRegular).is_some());
}

#[test]
fn the_catalogue_keeps_faces_but_reprobes_missing_slots() {
    let catalogue = font::Catalogue::new(counting_loader);
    for _ in 0..3 {
        assert!(catalogue.get(FaceId::MonoBold).is_some());
        assert!(catalogue.get(FaceId::MonoItalic).is_none());
    }
    // Found faces stay stable; absence is retried so installation can recover.
    assert_eq!(ASKED.with(|asked| asked.get()), 4);
}

thread_local! {
    static ASKED: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
}

/// A loader that counts its asks and fills one slot.
fn counting_loader(id: FaceId) -> Option<Face<'static>> {
    ASKED.with(|asked| asked.set(asked.get() + 1));
    (id == FaceId::MonoBold).then(|| Face::bundled(id))
}

#[test]
fn the_embedded_programs_are_a_feature_and_a_test_fixture() {
    // A test build carries the statics as the fixtures the unit tests
    // measure, with or without the feature: a TrueType file's header.
    assert!(
        FaceId::CarlitoRegular
            .bytes()
            .starts_with(&[0x00, 0x01, 0x00, 0x00])
    );
    assert_eq!(font::EMBEDDED_FONTS, cfg!(feature = "embedded-fonts"));
}

/// A package of `parts` (name, XML), the minimum a conversion opens.
fn package(parts: &[(&str, &str)]) -> Vec<u8> {
    use std::io::{Cursor, Write};
    let mut buf = Vec::new();
    {
        let mut z = zip::ZipWriter::new(Cursor::new(&mut buf));
        let opt = zip::write::SimpleFileOptions::default();
        for (name, xml) in parts {
            z.start_file(*name, opt).unwrap();
            z.write_all(xml.as_bytes()).unwrap();
        }
        z.finish().unwrap();
    }
    buf
}

/// A document that paints the way real ones do: plain, bold and italic
/// runs, a table, a comment (a balloon), a numbered list, East Asian
/// text, a header with a PAGE field and a footer.
fn painted_docx() -> Vec<u8> {
    const W: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
    const R: &str = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
    package(&[
        (
            "[Content_Types].xml",
            r#"<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/><Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"/><Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/><Override PartName="/word/header1.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml"/><Override PartName="/word/footer1.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml"/><Override PartName="/word/comments.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"/></Types>"#,
        ),
        (
            "_rels/.rels",
            r#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#,
        ),
        (
            "word/_rels/document.xml.rels",
            r#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdN" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/><Relationship Id="rIdS" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/><Relationship Id="rIdH" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/><Relationship Id="rIdF" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer" Target="footer1.xml"/><Relationship Id="rIdC" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments" Target="comments.xml"/></Relationships>"#,
        ),
        (
            "word/document.xml",
            &format!(
                r#"<?xml version="1.0"?><w:document xmlns:w="{W}" xmlns:r="{R}"><w:body>
<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>Heading in Cambria</w:t></w:r></w:p>
<w:p><w:r><w:rPr><w:b/></w:rPr><w:t>Bold Arial</w:t></w:r><w:r><w:rPr><w:i/></w:rPr><w:t xml:space="preserve"> italic </w:t></w:r><w:r><w:t>研究 multiple scripts</w:t></w:r></w:p>
<w:tbl><w:tblPr><w:tblW w:w="0" w:type="auto"/><w:tblBorders><w:top w:val="single"/><w:bottom w:val="single"/></w:tblBorders></w:tblPr><w:tblGrid><w:gridCol w:w="4000"/><w:gridCol w:w="4000"/></w:tblGrid>
<w:tr><w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr><w:p><w:r><w:t>Cell A1</w:t></w:r></w:p></w:tc><w:tc><w:tcPr><w:tcW w:w="4000" w:type="dxa"/></w:tcPr><w:p><w:r><w:t>Cell B1</w:t></w:r></w:p></w:tc></w:tr>
<w:tr><w:tc><w:p><w:r><w:t>F2</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>A longer cell that needs to wrap across lines to measure</w:t></w:r></w:p></w:tc></w:tr></w:tbl>
<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>First numbered item</w:t></w:r></w:p>
<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>Second numbered item</w:t></w:r></w:p>
<w:p><w:commentRangeStart w:id="0"/><w:r><w:t>A noted phrase</w:t></w:r><w:commentRangeEnd w:id="0"/><w:r><w:commentReference w:id="0"/></w:r></w:p>
<w:p><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText xml:space="preserve"> NUMPAGES </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>1</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p>
<w:sectPr><w:headerReference w:type="default" r:id="rIdH"/><w:footerReference w:type="default" r:id="rIdF"/><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720" w:footer="720"/></w:sectPr>
</w:body></w:document>"#
            ),
        ),
        (
            "word/styles.xml",
            r#"<?xml version="1.0"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri" w:eastAsia="宋体"/><w:sz w:val="22"/></w:rPr></w:rPrDefault></w:docDefaults><w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:basedOn w:val="Normal"/><w:rPr><w:rFonts w:ascii="Cambria" w:hAnsi="Cambria"/><w:b/><w:sz w:val="32"/></w:rPr></w:style></w:styles>"#,
        ),
        (
            "word/numbering.xml",
            r#"<?xml version="1.0"?><w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:abstractNum w:abstractNumId="0"><w:multiLevelType w:val="hybridMultilevel"/><w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/><w:rPr><w:rFonts w:ascii="Courier New" w:hAnsi="Courier New"/></w:rPr></w:lvl></w:abstractNum><w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num></w:numbering>"#,
        ),
        (
            "word/header1.xml",
            &format!(
                r#"<?xml version="1.0"?><w:hdr xmlns:w="{W}"><w:p><w:pPr><w:jc w:val="right"/></w:pPr><w:r><w:rPr><w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman"/></w:rPr><w:t>Header </w:t></w:r><w:r><w:fldChar w:fldCharType="begin"/></w:r><w:r><w:instrText> PAGE </w:instrText></w:r><w:r><w:fldChar w:fldCharType="separate"/></w:r><w:r><w:t>1</w:t></w:r><w:r><w:fldChar w:fldCharType="end"/></w:r></w:p></w:hdr>"#
            ),
        ),
        (
            "word/footer1.xml",
            &format!(
                r#"<?xml version="1.0"?><w:ftr xmlns:w="{W}"><w:p><w:r><w:t>Footer text</w:t></w:r></w:p></w:ftr>"#
            ),
        ),
        (
            "word/comments.xml",
            &format!(
                r#"<?xml version="1.0"?><w:comments xmlns:w="{W}"><w:comment w:id="0" w:author="Reviewer" w:date="2026-01-02T03:04:05Z"><w:p><w:r><w:t>A remark on the phrase, long enough to wrap inside its balloon in the margin of the page.</w:t></w:r></w:p></w:comment></w:comments>"#
            ),
        ),
    ])
}

/// Every way a conversion hands pages to a caller refuses the document
/// with the same typed error: no PDF, no PNG, no report, no page facts.
#[test]
fn a_document_no_source_can_draw_is_refused_before_a_page_is_written() {
    let docx = painted_docx();
    // The control: with the embedded faces the same document lays out.
    assert!(docx_to_pdf(&docx).is_ok());
    without_any_font(|| {
        for (name, error) in [
            ("pdf", docx_to_pdf(&docx).err()),
            (
                "report",
                docx_render_report(&docx, PdfOptions::default()).err(),
            ),
            ("png", docx_to_png(&docx, PdfOptions::default(), 72.0).err()),
            ("fields", layout_facts(&docx).err()),
            (
                "word style",
                docx_to_pdf_with(
                    &docx,
                    PdfOptions {
                        revisions: RevisionStyle::Word,
                        ..PdfOptions::default()
                    },
                )
                .err(),
            ),
        ] {
            let error =
                error.unwrap_or_else(|| panic!("{name}: a page was written without a face"));
            assert!(
                matches!(error, ConvertError::FontUnavailable { .. }),
                "{name}: {error:?}"
            );
            assert!(
                error.to_string().starts_with("FONT_UNAVAILABLE: "),
                "{name}: {error}"
            );
        }
        let rendered = render(
            &docx,
            PdfOptions::default(),
            RenderRequest {
                pdf: true,
                png_dpi: Some(72.0),
                pages: None,
            },
        )
        .err()
        .unwrap_or_else(|| panic!("no face, no PDF and no PNG"));
        assert!(matches!(rendered, ConvertError::FontUnavailable { .. }));
    });
}

/// A one-paragraph document whose every run, paragraph mark and default
/// is `family`, `bold` and `italic`.
fn docx_in(family: &str, bold: bool, italic: bool) -> Vec<u8> {
    let style = format!(
        r#"<w:rFonts w:ascii="{family}" w:hAnsi="{family}" w:eastAsia="{family}" w:cs="{family}"/>{}{}"#,
        if bold { "<w:b/>" } else { "" },
        if italic { "<w:i/>" } else { "" }
    );
    let document = format!(
        r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:pPr><w:rPr>{style}</w:rPr></w:pPr><w:r><w:rPr>{style}</w:rPr><w:t>HELLO</w:t></w:r></w:p><w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/></w:sectPr></w:body></w:document>"#
    );
    package(&[
        (
            "[Content_Types].xml",
            r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/><Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/></Types>"#,
        ),
        (
            "_rels/.rels",
            r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#,
        ),
        (
            "word/_rels/document.xml.rels",
            r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>"#,
        ),
        ("word/document.xml", document.as_str()),
        (
            "word/styles.xml",
            &format!(
                r#"<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:docDefaults><w:rPrDefault><w:rPr>{style}<w:sz w:val="22"/></w:rPr></w:rPrDefault></w:docDefaults></w:styles>"#
            ),
        ),
    ])
}

#[test]
fn the_unavailable_error_names_the_family_its_style_and_the_substitute_to_install() {
    // Families no machine has, each placed in a catalogue slot by its
    // name's class, so the answer is this test's whatever the host has
    // installed (a real Calibri would be found on the machine instead).
    for (family, bold, italic, slot_family, substitute) in [
        ("Fake Calibri", false, false, "Calibri", "Carlito"),
        ("Aptos Fake", true, false, "Aptos", "Carlito"),
        (
            "Aptos Fake Display",
            false,
            true,
            "Aptos Display",
            "Carlito",
        ),
        ("Fake Arial", true, true, "Arial", "Liberation Sans"),
        (
            "Fake Serif",
            false,
            true,
            "Times New Roman",
            "Liberation Serif",
        ),
        (
            "Fake Courier",
            true,
            false,
            "Courier New",
            "Liberation Mono",
        ),
    ] {
        let docx = docx_in(family, bold, italic);
        assert!(docx_to_pdf(&docx).is_ok(), "{family}: the control lays out");
        without_any_font(|| {
            let error = docx_to_pdf(&docx)
                .err()
                .unwrap_or_else(|| panic!("{family}: a PDF was written without a face"));
            assert!(
                matches!(
                    &error,
                    ConvertError::FontUnavailable {
                        family: missing,
                        bold: b,
                        italic: i,
                    } if missing == slot_family && *b == bold && *i == italic
                ),
                "{family}: {error:?}"
            );
            assert_eq!(ConvertError::FONT_UNAVAILABLE, "FONT_UNAVAILABLE");
            let text = error.to_string();
            let style = match (bold, italic) {
                (false, false) => "regular",
                (true, false) => "bold",
                (false, true) => "italic",
                (true, true) => "bold italic",
            };
            assert!(
                text.starts_with(&format!(
                    "FONT_UNAVAILABLE: no usable face for {slot_family} ({style})"
                )),
                "{text}"
            );
            assert!(
                text.contains(&format!("substitute {substitute},")),
                "{text}"
            );
            assert!(text.contains("JUBARTE_FONT_DIR"), "{text}");
        });
    }
}

/// A one-paragraph document whose only family, `family`, is the font it
/// embeds (an obfuscated `.odttf` of `ttf`).
fn docx_embedding(family: &str, ttf: &[u8]) -> Vec<u8> {
    docx_embedding_with_header(family, ttf, None)
}

/// [`docx_embedding`] with `header`, the body of a default header part,
/// when given.
fn docx_embedding_with_header(family: &str, ttf: &[u8], header: Option<&str>) -> Vec<u8> {
    use std::io::{Cursor, Write};
    let guid = "{00000000-0000-0000-0000-000000000001}";
    let key = font_table::parse_font_key(guid).expect("guid");
    let mut odttf = ttf.to_vec();
    font_table::deobfuscate_font(&mut odttf, &key);
    let reference = if header.is_some() {
        r#"<w:headerReference w:type="default" r:id="rIdH"/>"#
    } else {
        ""
    };
    let document = format!(
        r#"<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:body><w:p><w:pPr><w:rPr><w:rFonts w:ascii="{family}" w:hAnsi="{family}" w:eastAsia="{family}" w:cs="{family}"/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:ascii="{family}" w:hAnsi="{family}" w:eastAsia="{family}" w:cs="{family}"/></w:rPr><w:t>HELLO</w:t></w:r></w:p><w:sectPr>{reference}<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440" w:header="720"/></w:sectPr></w:body></w:document>"#
    );
    let font_table = format!(
        r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:font w:name="{family}"><w:embedRegular r:id="rId1" w:fontKey="{guid}"/></w:font></w:fonts>"#
    );
    let mut docx = Vec::new();
    {
        let mut z = zip::ZipWriter::new(Cursor::new(&mut docx));
        let opt = zip::write::SimpleFileOptions::default();
        for (name, xml) in [
            (
                "[Content_Types].xml",
                r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Default Extension="odttf" ContentType="application/vnd.openxmlformats-officedocument.obfuscatedFont"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/><Override PartName="/word/fontTable.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml"/></Types>"#,
            ),
            (
                "_rels/.rels",
                r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#,
            ),
            (
                "word/_rels/fontTable.xml.rels",
                r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/font" Target="fonts/font1.odttf"/></Relationships>"#,
            ),
            ("word/document.xml", document.as_str()),
            ("word/fontTable.xml", font_table.as_str()),
        ] {
            z.start_file(name, opt).unwrap();
            z.write_all(xml.as_bytes()).unwrap();
        }
        if let Some(header) = header {
            z.start_file("word/_rels/document.xml.rels", opt).unwrap();
            z.write_all(br#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdH" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/></Relationships>"#).unwrap();
            z.start_file("word/header1.xml", opt).unwrap();
            z.write_all(header.as_bytes()).unwrap();
        }
        z.start_file("word/fonts/font1.odttf", opt).unwrap();
        z.write_all(&odttf).unwrap();
        z.finish().unwrap();
    }
    docx
}

#[test]
fn a_document_that_embeds_its_own_face_renders_without_any_catalogue_face() {
    // The face a document carries is its own: no catalogue slot is asked
    // for, so none can be missing. The control names no catalogue family.
    let docx = docx_embedding("Body Face", FaceId::CarlitoRegular.bytes());
    let report = docx_render_report(&docx, PdfOptions::default()).expect("convert");
    assert_eq!(
        report
            .fonts
            .iter()
            .map(|f| f.requested.as_str())
            .collect::<Vec<_>>(),
        ["Body Face"],
        "{:?}",
        report.fonts
    );
    font::with_slot_loader(
        |_| None,
        || {
            let pdf = docx_to_pdf(&docx).expect("its own face draws it");
            assert!(pdf.starts_with(b"%PDF"));
        },
    );
}

// Review of #327 (CodeRabbit): a header's picture-only paragraph and a
// flat shape run are measured with the catalogue's faces, before the
// document's own exist. Those measures paint nothing, so a family only the
// document carries is no missing face there.
#[test]
fn a_header_measure_does_not_refuse_a_family_the_document_embeds() {
    let mark = r#"<w:rPr><w:rFonts w:ascii="Body Face" w:hAnsi="Body Face" w:eastAsia="Body Face" w:cs="Body Face"/></w:rPr>"#;
    let inline = r#"<wp:inline><wp:extent cx="914400" cy="457200"/><wp:docPr id="1" name="Logo"/></wp:inline>"#;
    let flat =
        r#"<wp:inline><wp:extent cx="914400" cy="0"/><wp:docPr id="2" name="Rule"/></wp:inline>"#;
    for (name, paragraphs) in [
        (
            "picture-only paragraph",
            format!(
                r#"<w:p><w:pPr>{mark}</w:pPr><w:r>{mark}<w:drawing>{inline}</w:drawing></w:r></w:p>"#
            ),
        ),
        (
            "flat shape run",
            format!(
                r#"<w:p><w:pPr>{mark}</w:pPr><w:r>{mark}<w:t>Title</w:t></w:r><w:r>{mark}<w:drawing>{flat}</w:drawing></w:r></w:p>"#
            ),
        ),
    ] {
        let header = format!(
            r#"<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing">{paragraphs}</w:hdr>"#
        );
        let docx =
            docx_embedding_with_header("Body Face", FaceId::CarlitoRegular.bytes(), Some(&header));
        without_any_font(|| {
            let pdf = docx_to_pdf(&docx).unwrap_or_else(|error| panic!("{name}: {error}"));
            assert!(pdf.starts_with(b"%PDF"), "{name}");
        });
    }
}

/// A host with Carlito regular and an italic face under two names.
fn sample_host() -> impl Fn(&str) -> Vec<((bool, bool), Vec<u8>)> {
    move |family: &str| {
        let (style, program): ((bool, bool), &[u8]) = match family {
            "Carlito" => ((false, false), FaceId::CarlitoRegular.bytes()),
            // "Arial" stands for a family's own installed face; the bytes
            // are Carlito Italic's so the name tells which face was taken.
            "Arial" => ((false, true), FaceId::CarlitoItalic.bytes()),
            "Liberation Sans" => ((false, true), FaceId::SansItalic.bytes()),
            _ => return Vec::new(),
        };
        vec![(style, program.to_vec())]
    }
}

#[test]
fn without_the_embedded_programs_an_installed_substitute_fills_the_slot() {
    let host = sample_host();
    let face = |id: FaceId| {
        font::face_from_sources(
            id,
            &font::Sources {
                system: &|_| None,
                embedded: &|_| None,
                host: &|id| font::host_program_with(id, &host),
            },
        )
        .map(|face| face.pdf_name().to_string())
    };
    // The slot's own style of its open substitute.
    assert_eq!(face(FaceId::CarlitoRegular).as_deref(), Some("Carlito"));
    assert_eq!(
        face(FaceId::VerdanaItalic).as_deref(),
        Some("LiberationSans-Italic")
    );
    // A style the substitute lacks is not filled with another of its
    // styles: nothing would fake the bold or the slant the run asks for.
    assert_eq!(face(FaceId::CarlitoBold), None);
    assert_eq!(face(FaceId::CarlitoItalic), None);
    assert_eq!(face(FaceId::SansRegular), None);
}

#[test]
fn a_slot_takes_the_familys_own_installed_face_before_its_substitute() {
    let host = sample_host();
    assert_eq!(
        font::host_program_with(FaceId::SansItalic, &host).map(|face| face.pdf_name().to_string()),
        Some("Carlito-Italic".to_string()),
        "Arial's own italic face stands behind the slot, not Liberation Sans's"
    );
}

#[test]
fn the_sources_answer_in_order_and_the_first_face_wins() {
    let none = |_: FaceId| None;
    let only = |id: FaceId| (id == FaceId::MonoBold).then(|| Face::bundled(id));
    let sources = font::Sources {
        system: &none,
        embedded: &only,
        host: &only,
    };
    assert!(font::face_from_sources(FaceId::MonoBold, &sources).is_some());
    assert!(font::face_from_sources(FaceId::MonoRegular, &sources).is_none());
    let sources = font::Sources {
        system: &only,
        embedded: &only,
        host: &|id| (id == FaceId::MonoBold).then(|| Face::bundled(FaceId::MonoRegular)),
    };
    assert_eq!(
        font::face_from_sources(FaceId::MonoBold, &sources).map(|face| face.pdf_name().to_string()),
        Some("LiberationMono-Bold".to_string()),
        "the system file, not the host's stand-in"
    );
}

#[test]
fn system_fonts_off_leaves_jubartes_own_folder_as_the_only_search() {
    font::with_scope(font::FontScope::USER_ONLY, || {
        let dirs = font::search_directories();
        let user = font::user_font_dir();
        assert_eq!(dirs, user.iter().cloned().collect::<Vec<_>>());
        assert!(font::system_override_uncached(FaceId::SansRegular).is_none());
        assert!(font::cloud_font_override(FaceId::AptosRegular).is_none());
    });
}

#[test]
fn a_hermetic_scope_lists_no_folder_and_finds_no_installed_face() {
    font::with_scope(font::FontScope::HERMETIC, || {
        assert!(font::search_directories().is_empty());
        assert!(font::user_font_dir_in_scope().is_none());
        for family in [
            "Arial",
            "Calibri",
            "Carlito",
            "Liberation Sans",
            "MS 明朝",
        ] {
            assert!(font::installed_family_faces(family).is_empty(), "{family}");
        }
        assert!(font::cjk_dirs().is_empty());
    });
    // The scope ends with it: the machine's folders are listed again.
    assert!(!font::cjk_dirs().is_empty());
}

// Review of #327 (CodeRabbit): `$JUBARTE_FONT_DIR` answers an East Asian
// family too, with the machine's folders on or off; a hermetic scope lists
// nothing.
#[test]
fn the_east_asian_search_reads_the_user_folder() {
    font::with_scope(font::FontScope::USER_ONLY, || {
        assert_eq!(
            font::cjk_search_dirs(),
            font::user_font_dir().into_iter().collect::<Vec<_>>()
        );
    });
    font::with_scope(font::FontScope::HERMETIC, || {
        assert!(font::cjk_search_dirs().is_empty());
    });
    let dirs = font::cjk_search_dirs();
    assert!(dirs.starts_with(&font::cjk_dirs()));
    assert_eq!(dirs.last().cloned(), font::user_font_dir());
}

// Review of #327 (CodeRabbit): Linux keeps its fonts in nested folders
// (`/usr/share/fonts/truetype/liberation2`); each one is searched.
#[test]
fn nested_font_folders_are_listed_under_their_root() {
    let temp = tempfile::tempdir().unwrap();
    let root = temp.path().join("fonts");
    let deep = root.join("truetype").join("liberation2");
    std::fs::create_dir_all(&deep).unwrap();
    std::fs::create_dir_all(root.join("opentype")).unwrap();
    std::fs::write(deep.join("LiberationSans-Regular.ttf"), b"font").unwrap();
    let missing = temp.path().join("missing");
    let dirs = font::nested_font_dirs(&[root.clone(), missing.clone()]);
    assert_eq!(
        dirs,
        [
            root.clone(),
            missing,
            root.join("opentype"),
            root.join("truetype"),
            deep
        ]
    );
}

#[test]
fn system_fonts_are_off_only_when_the_variable_says_so() {
    use std::ffi::OsString;
    let env = |value: &'static str| {
        move |key: &str| (key == "JUBARTE_SYSTEM_FONTS").then(|| OsString::from(value))
    };
    assert!(!font::scope_from(&env("off")).has_system());
    assert!(font::scope_from(&env("OFF")).has_system());
    assert!(font::scope_from(&env("on")).has_system());
    assert!(font::scope_from(&env("")).has_system());
    assert!(font::scope_from(&|_| None).has_system());
    assert!(font::scope_from(&env("off")).has_user());
}

// The scan boundary is injected: these discovery-policy tests read no disk.
#[test]
fn a_family_without_a_latin_key_is_searched_in_its_whole_family_folder() {
    let cloud = std::path::PathBuf::from("CloudFonts/STFangsong");
    let user = std::path::Path::new("fonts");
    let called = std::cell::Cell::new(false);
    font::with_scope(font::FontScope::USER_ONLY, || {
        let (_, listed) = font::scan_family_faces_in(
            "华文仿宋",
            vec![(cloud.clone(), true)],
            Some(user),
            |family, dirs, own| {
                called.set(true);
                assert_eq!(family, "华文仿宋");
                assert_eq!(dirs, [(cloud.clone(), true)]);
                assert_eq!(own, Some(user));
                Vec::new()
            },
        );
        assert_eq!(listed, [cloud, user.to_path_buf()]);
    });
    assert!(
        called.get(),
        "localized names must reach the whole-family scanner"
    );
}

#[test]
fn jubartes_own_folder_is_searched_alone_when_the_system_folders_are_off() {
    let user = std::path::Path::new("fonts");
    let called = std::cell::Cell::new(false);
    font::with_scope(font::FontScope::USER_ONLY, || {
        let (_, listed) =
            font::scan_family_faces_in("Carlito", Vec::new(), Some(user), |family, dirs, own| {
                called.set(true);
                assert_eq!(family, "Carlito");
                assert!(dirs.is_empty());
                assert_eq!(own, Some(user));
                Vec::new()
            });
        assert_eq!(listed, [user.to_path_buf()]);
        let (faces, listed) =
            font::scan_family_faces_in("Carlito", Vec::new(), None, |_, _, _| Vec::new());
        assert!(faces.is_empty());
        assert!(listed.is_empty());
    });
    assert!(called.get(), "the user folder alone is a search source");
}

#[test]
fn the_renderer_enables_embedded_fonts_by_default() {
    let manifest = include_str!("../../../Cargo.toml");
    let features = manifest
        .split("[features]")
        .nth(1)
        .unwrap()
        .split("\n[")
        .next()
        .unwrap();
    let defaults = features.lines().find(|line| line.starts_with("default ="));
    assert!(
        defaults.is_some_and(|line| line.contains("\"embedded-fonts\"")),
        "direct renderer consumers retain embedded fonts by default"
    );
}

#[test]
fn a_missing_font_slot_recovers_in_the_same_catalogue_after_installation() {
    thread_local! { static INSTALLED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; }
    let catalogue =
        font::Catalogue::new(|id| INSTALLED.with(|v| v.get()).then(|| Face::bundled(id)));
    assert!(catalogue.get(FaceId::SansRegular).is_none());
    INSTALLED.with(|v| v.set(true));
    assert_eq!(
        catalogue.get(FaceId::SansRegular).map(|f| f.pdf_name()),
        Some("LiberationSans")
    );
}