// 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")
);
}