use f_office_paint::{DisplayList, Item};
use super::{
CARLITO, CARLITO_FONTS, CARLITO_RUN, SECTION, baseline_of, carlito, carlito_line,
compatibility_mode, docx, fills, lines, para, points, render,
};
#[test]
fn writes_a_non_breaking_hyphen_as_a_hyphen() {
let body = |hyphen: &str| {
format!(
r"<w:p><w:r>{CARLITO_RUN}<w:t>49</w:t>{hyphen}<w:t>28</w:t></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"
)
};
let glyphs = |list: &DisplayList| -> Vec<(String, Vec<u32>)> {
list.pages()[0]
.items()
.iter()
.filter_map(|item| match item {
Item::Glyphs(run) => {
Some((run.text.clone(), run.glyphs.iter().map(|g| g.id).collect()))
}
_ => None,
})
.collect()
};
let plain = glyphs(&render(&docx(&body("<w:t>-</w:t>"), &[], "")));
let kept = glyphs(&render(&docx(&body("<w:noBreakHyphen/>"), &[], "")));
assert_eq!(kept, plain);
assert_eq!(kept[0].0, "49-28");
let literal = glyphs(&render(&docx(&body("<w:t>\u{2011}</w:t>"), &[], "")));
assert_eq!(literal[0].0, "49\u{2011}28");
assert_eq!(literal[0].1, kept[0].1);
}
#[test]
fn draws_a_list_of_fonts_with_its_first_font() {
let body = |font: &str| {
format!(
r#"<w:p><w:r><w:rPr><w:rFonts w:ascii="{font}" w:hAnsi="{font}"/></w:rPr><w:t>Water</w:t></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"#
)
};
let plain = render(&docx(&body("Carlito"), &[], ""));
let listed = render(&docx(&body("Carlito, Geneva, sans-serif"), &[], ""));
assert_eq!(lines(&listed), lines(&plain));
assert_eq!(lines(&listed)[0].len(), 1);
}
#[test]
fn warns_of_a_font_that_a_stand_in_draws() {
let body = |font: &str| {
let fonts = format!(r#"<w:rPr><w:rFonts w:ascii="{font}" w:hAnsi="{font}"/></w:rPr>"#);
format!(
r"<w:p><w:pPr>{fonts}</w:pPr><w:r>{fonts}<w:t>Water</w:t></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"
)
};
let fonts = carlito();
let warnings = |font: &str| -> Vec<String> {
let laid_out =
super::Document::open(&docx(&body(font), &[], ""), &fonts, &super::Options::base())
.unwrap();
let warnings = laid_out.warnings.iter();
warnings.map(|(warning, _)| warning.to_string()).collect()
};
assert_eq!(warnings("Carlito"), Vec::<String>::new());
assert_eq!(warnings("Calibri"), ["font Calibri is drawn with Carlito"]);
}
#[test]
fn a_font_file_that_does_not_load_draws_no_glyph_and_warns_and_an_unchosen_file_is_not_read() {
let name = format!("f-office-font-files-{}", std::process::id());
let folder = std::env::temp_dir().join(name);
std::fs::create_dir_all(&folder).unwrap();
let (first, second) = (folder.join("a-carlito.ttf"), folder.join("b-carlito.ttf"));
std::fs::write(&first, CARLITO).unwrap();
std::fs::write(&second, CARLITO).unwrap();
let mut both = super::FontDb::new();
both.add_files(&[first.clone(), second.clone()]).unwrap();
assert_eq!(both.load(f_office_fonts::FontId::from_index(0)), Ok(()));
let mut only_first = super::FontDb::new();
std::fs::remove_file(&second).unwrap();
only_first.add_files(std::slice::from_ref(&first)).unwrap();
std::fs::remove_file(&first).unwrap();
std::fs::remove_dir(&folder).unwrap();
let docx = docx(
&format!(
r"<w:p><w:pPr>{CARLITO_RUN}</w:pPr><w:r>{CARLITO_RUN}<w:t>Water</w:t></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"
),
&[],
"",
);
let open = |fonts| super::Document::open(&docx, fonts, &super::Options::base()).unwrap();
let fonts_of = |list: &DisplayList| -> Vec<u32> {
let items = list.pages().iter().flat_map(f_office_paint::Page::items);
let runs = items.filter_map(|item| match item {
Item::Glyphs(run) => Some(run.font.index()),
_ => None,
});
runs.collect()
};
let laid_out = open(&both);
assert!(laid_out.warnings.is_empty());
assert_eq!(fonts_of(laid_out.value.display_list()), [0]);
let laid_out = open(&only_first);
assert_eq!(fonts_of(laid_out.value.display_list()), Vec::<u32>::new());
let warnings: Vec<_> = laid_out
.warnings
.iter()
.map(|(warning, _)| warning)
.collect();
let not_read = warnings
.iter()
.find(|warning| warning.kind() == "font-file-not-read")
.unwrap();
assert!(
not_read
.to_string()
.starts_with("font file a-carlito.ttf did not load"),
"{not_read}"
);
}
#[test]
fn lowers_text_in_a_line_with_other_text_but_not_a_line_lowered_as_a_whole() {
let run = |position: &str, text: &str| {
format!(
r#"<w:r><w:rPr>{CARLITO_FONTS}<w:position w:val="{position}"/></w:rPr><w:t>{text}</w:t></w:r>"#
)
};
let body = format!(
r"<w:p>{}{}</w:p><w:p>{}</w:p><w:p>{}</w:p><w:sectPr>{SECTION}</w:sectPr>",
run("-4", "Low"),
run("0", "Level"),
run("-4", "All"),
run("0", "Next"),
);
let list = render(&docx(&body, &[], ""));
let (ascent, line) = carlito_line();
let level = baseline_of(&list, "Level");
assert!((level - (36.0 + ascent)).abs() <= 0.12, "{level}");
assert!((baseline_of(&list, "Low") - (level + 2.0)).abs() <= 0.12);
let all = baseline_of(&list, "All");
assert!((all - (level + line + 2.0)).abs() <= 0.3, "{all} {level}");
let next = baseline_of(&list, "Next");
assert!((next - (all + line)).abs() <= 0.3, "{next} {all}");
}
#[test]
fn draws_small_capitals_smaller_except_the_capitals() {
let body = format!(
r#"<w:p><w:r><w:rPr>{CARLITO_FONTS}<w:smallCaps/><w:sz w:val="24"/></w:rPr><w:t>Ab c</w:t></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"#
);
let list = render(&docx(&body, &[], ""));
let runs: Vec<(String, f64)> = list.pages()[0]
.items()
.iter()
.filter_map(|item| match item {
Item::Glyphs(run) => Some((run.text.clone(), points(run.size.units()))),
_ => None,
})
.collect();
assert_eq!(
runs,
[("A".to_owned(), 12.0), ("B C".to_owned(), 9.6)],
"{runs:?}"
);
}
#[test]
fn a_phantom_that_is_not_shown_takes_its_room_and_draws_nothing() {
let math = "http://schemas.openxmlformats.org/officeDocument/2006/math";
let r =
|text: &str| format!("<m:r><m:rPr><m:nor/></m:rPr>{CARLITO_RUN}<m:t>{text}</m:t></m:r>");
let equation = |settings: &str| {
let body = format!(
r#"<w:p><m:oMath xmlns:m="{math}">{}<m:phant><m:phantPr>{settings}</m:phantPr><m:e>{}</m:e></m:phant>{}</m:oMath></w:p>"#,
r("1"),
r("23"),
r("4")
);
let list = render(&docx(&body, &[], ""));
let mut text = String::new();
let mut four = None;
for item in list.pages()[0].items() {
let Item::Glyphs(run) = item else { continue };
for g in &run.glyphs {
let ch = run.glyph_text(g).unwrap();
text.push_str(ch);
if ch == "4" {
four = Some(g.x.units());
}
}
}
(text, four.unwrap())
};
let (shown, at) = equation("");
assert_eq!(shown, "1234");
let (text, hidden) = equation(r#"<m:show m:val="0"/>"#);
assert_eq!(text, "14");
assert!((hidden - at).abs() < 254, "{hidden} {at}");
let (text, narrow) = equation(r#"<m:show m:val="0"/><m:zeroWid/>"#);
assert_eq!(text, "14");
assert!(narrow < at, "{narrow} {at}");
}
fn carlito_ink(ch: char) -> (f64, f64) {
let mut fonts = f_office_fonts::FontDb::new();
let id = fonts.add_font(CARLITO.to_vec()).unwrap()[0];
let em = f64::from(fonts.metrics(id).unwrap().units_per_em);
let outline = fonts.outline(id, fonts.glyph_id(id, ch).unwrap()).unwrap();
let heights: Vec<f32> = outline
.iter()
.flat_map(|command| match *command {
f_office_fonts::PathCommand::MoveTo(p) | f_office_fonts::PathCommand::LineTo(p) => {
vec![p.y]
}
f_office_fonts::PathCommand::QuadTo(c, p) => vec![c.y, p.y],
f_office_fonts::PathCommand::CubicTo(c, d, p) => vec![c.y, d.y, p.y],
f_office_fonts::PathCommand::Close => Vec::new(),
})
.collect();
let low = heights.iter().copied().fold(f32::MAX, f32::min);
let high = heights.iter().copied().fold(f32::MIN, f32::max);
(f64::from(low) / em, f64::from(high) / em)
}
fn fraction_line(num: &str, den: &str) -> (f64, f64) {
let math = "http://schemas.openxmlformats.org/officeDocument/2006/math";
let r =
|text: &str| format!(r"<m:r><m:rPr><m:nor/></m:rPr>{CARLITO_RUN}<m:t>{text}</m:t></m:r>");
let body = format!(
r#"<w:p><w:r>{CARLITO_RUN}<w:t>Top</w:t></w:r></w:p><w:p><w:r>{CARLITO_RUN}<w:t>A</w:t></w:r><m:oMath xmlns:m="{math}"><m:f><m:num>{}</m:num><m:den>{}</m:den></m:f></m:oMath></w:p><w:p><w:r>{CARLITO_RUN}<w:t>End</w:t></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"#,
r(num),
r(den)
);
let list = render(&docx(&body, &[], ""));
let line = baseline_of(&list, "A");
(
line - baseline_of(&list, "Top"),
baseline_of(&list, "End") - line,
)
}
#[test]
fn the_room_below_an_inline_fraction_follows_the_ink_of_its_denominator() {
let part = 7.0;
let (above, below) = fraction_line("x", "x");
let deep = fraction_line("x", "g");
let expected = (carlito_ink('x').0 - carlito_ink('g').0) * part;
assert!((deep.1 - below - expected).abs() < 0.25, "{deep:?} {below}");
assert!((deep.0 - above).abs() < 0.01, "{deep:?} {above}");
let (ascent, height) = super::carlito_line();
let reach = 10.0 * 1030.0 / 2048.0 - carlito_ink('x').0 * part;
assert!(
(below - ascent - reach).abs() < 0.25,
"{below} {ascent} {height} {reach}"
);
}
fn office_glyphs(extra: &str, mode: u32) -> Vec<(String, i64)> {
let body =
format!("<w:p><w:r><w:rPr>{CARLITO_FONTS}{extra}</w:rPr><w:t>office</w:t></w:r></w:p>");
let list = render(&docx(&body, &[], &compatibility_mode(mode)));
let Some(Item::Glyphs(run)) = list.pages()[0].items().first() else {
panic!("no glyph run");
};
run.glyphs
.iter()
.map(|g| {
let text = run.glyph_text(g).unwrap();
(text.to_owned(), g.x.units())
})
.collect()
}
#[test]
fn joins_standard_ligatures_only_when_the_run_turns_them_on() {
let texts = |glyphs: &[(String, i64)]| glyphs.iter().map(|g| g.0.clone()).collect::<Vec<_>>();
let plain = office_glyphs("", 15);
assert_eq!(texts(&plain), ["o", "f", "f", "i", "c", "e"]);
let w14 = "http://schemas.microsoft.com/office/word/2010/wordml";
let ligatures = format!(r#"<w14:ligatures xmlns:w14="{w14}" w14:val="standardContextual"/>"#);
let joined = office_glyphs(&ligatures, 15);
assert_eq!(texts(&joined), ["o", "ffi", "c", "e"]);
assert_eq!(texts(&office_glyphs(&ligatures, 12)), texts(&plain));
let ffi = joined[2].1 - joined[1].1;
assert!((ffi - 1654 * 254_000 / 2048).abs() <= 1, "{ffi}");
assert!(joined[3].1 < plain[5].1);
}
fn glyph_texts(runs: &str) -> Vec<String> {
let list = render(&docx(
&format!("<w:p>{runs}</w:p>"),
&[],
&compatibility_mode(15),
));
list.pages()[0]
.items()
.iter()
.filter_map(|item| match item {
Item::Glyphs(run) => Some(
run.glyphs
.iter()
.map(|g| run.glyph_text(g).unwrap().to_owned())
.collect::<Vec<_>>(),
),
_ => None,
})
.flatten()
.collect()
}
#[test]
fn joins_ligatures_across_runs_with_the_same_properties() {
let w14 = "http://schemas.microsoft.com/office/word/2010/wordml";
let run = |text: &str, extra: &str| {
format!(
r#"<w:r><w:rPr>{CARLITO_FONTS}<w14:ligatures xmlns:w14="{w14}" w14:val="standard"/>{extra}</w:rPr><w:t>{text}</w:t></w:r>"#
)
};
assert_eq!(
glyph_texts(&(run("of", "") + &run("fice", ""))),
["o", "ffi", "c", "e"]
);
let red = r#"<w:color w:val="FF0000"/>"#;
assert_eq!(
glyph_texts(&(run("of", "") + &run("fice", red))),
["o", "f", "fi", "c", "e"]
);
}
#[test]
fn outlines_the_glyphs_of_a_run_with_a_text_outline_in_yellow_for_a_theme_color() {
let w14 = "http://schemas.microsoft.com/office/word/2010/wordml";
let outlined = format!(
r#"<w:p><w:r><w:rPr>{CARLITO_FONTS}<w14:textOutline xmlns:w14="{w14}" w14:w="12700"><w14:solidFill><w14:schemeClr w14:val="accent2"/></w14:solidFill></w14:textOutline></w:rPr><w:t>Outlined</w:t></w:r></w:p>"#
);
let list = render(&docx(&(outlined + ¶("Plain")), &[], ""));
let runs: Vec<_> = list.pages()[0]
.items()
.iter()
.filter_map(|item| match item {
Item::Glyphs(run) => Some((
run.text.clone(),
run.outline.map(|line| (line.width.units(), line.color)),
)),
_ => None,
})
.collect();
let yellow = f_office_paint::Rgb {
r: 255,
g: 255,
b: 0,
};
assert_eq!(
runs,
vec![
(
"Outlined".to_owned(),
Some((crate::Length::UNITS_PER_POINT, yellow))
),
("Plain".to_owned(), None)
]
);
}
#[test]
fn fills_highlights_shaded_paragraphs_and_cells() {
let run = |props: &str, text: &str| {
format!("<w:r><w:rPr>{CARLITO_FONTS}{props}</w:rPr><w:t>{text}</w:t></w:r>")
};
let cell = |fill: &str, text: &str| {
format!(
r#"<w:tc><w:tcPr><w:shd w:val="clear" w:fill="{fill}"/></w:tcPr><w:p>{}</w:p></w:tc>"#,
run("", text)
)
};
let body = format!(
r#"<w:p>{}</w:p><w:p><w:pPr><w:shd w:val="clear" w:fill="00FF00"/><w:ind w:left="720"/></w:pPr>{}</w:p><w:tbl><w:tblGrid><w:gridCol w:w="2000"/><w:gridCol w:w="2000"/></w:tblGrid><w:tr>{}{}</w:tr></w:tbl><w:sectPr>{SECTION}</w:sectPr>"#,
run(r#"<w:highlight w:val="yellow"/>"#, "Marked"),
run("", "Shaded"),
cell("0000FF", "Blue"),
cell("FFFFFF", "White"),
);
let list = render(&docx(&body, &[], ""));
let rects = fills(&list);
let find = |color: [u8; 3]| rects.iter().find(|r| r.4 == color).copied();
let marked = find([255, 255, 0]).unwrap();
assert!(
(marked.0 - 36.0).abs() < 0.25 && marked.2 > 20.0,
"{rects:?}"
);
let shaded = find([0, 255, 0]).unwrap();
assert!(
(shaded.0 - 70.56).abs() < 0.01 && (shaded.2 - 194.88).abs() < 0.01,
"{rects:?}"
);
let blue = find([0, 0, 255]).unwrap();
assert!((blue.2 - 100.0).abs() < 0.25 && blue.3 > 10.0, "{rects:?}");
let white = find([255, 255, 255]).unwrap();
assert!(
(white.0 - blue.0 - 100.0).abs() < 0.25 && (white.2 - 100.0).abs() < 0.25,
"{rects:?}"
);
let items = list.pages()[0].items();
let index = |pick: &dyn Fn(&Item) -> bool| items.iter().position(pick).unwrap();
let blue_fill = index(&|i| matches!(i, Item::Rect(r) if r.color.b == 255 && r.color.r == 0));
let blue_text = index(&|i| matches!(i, Item::Glyphs(g) if g.text == "Blue"));
assert!(blue_fill < blue_text);
}