//! Layout tests of the text map: the story text of a body paragraph and of headers, footers,
//! footnotes, endnotes, frames, text boxes and table cells, and the clusters of drawn glyphs, ligatures, right-to-left text
//! and automatic and soft hyphens.
use std::fmt::Write as _;
use f_office_paint::Item;
use super::{
CARLITO_FONTS, CARLITO_RUN, Document, Options, RELATIONSHIPS, SECTION, carlito,
compatibility_mode, docx, para,
};
use crate::{EndHyphen, Length, LineTextEnd, Target, TextBlockKind, TextLine, TextStory};
fn open(docx: &[u8]) -> Document {
Document::open(docx, &carlito(), &Options::base())
.unwrap()
.value
}
/// The texts of the paragraphs of `story`.
fn story(document: &Document, story: TextStory) -> Vec<String> {
document
.story_text(story)
.into_iter()
.map(|paragraph| paragraph.text)
.collect()
}
/// The addresses of the paragraphs of `story`.
fn addresses(document: &Document, story: TextStory) -> Vec<Option<String>> {
document
.story_text(story)
.iter()
.map(|paragraph| paragraph.address.as_ref().map(ToString::to_string))
.collect()
}
/// The text that the clusters of `line` show, in visual order, from the paragraph's `text`.
fn clusters<'a>(line: &TextLine, text: &'a str) -> Vec<&'a str> {
line.clusters
.iter()
.map(|cluster| {
text.get(cluster.start as usize..cluster.end as usize)
.unwrap()
})
.collect()
}
#[test]
fn reads_a_header_and_a_footer_as_a_story_of_each_page() {
let next_page = "<w:p><w:pPr><w:pageBreakBefore/></w:pPr>";
let body = format!(
r#"{}{}<w:sectPr xmlns:r="{RELATIONSHIPS}"><w:headerReference w:type="default" r:id="h1"/><w:footerReference w:type="default" r:id="f1"/>{SECTION}</w:sectPr>"#,
para("One"),
para("Two").replacen("<w:p>", next_page, 1),
);
let document = open(&docx(
&body,
&[("h1", ¶("Head")), ("f1", ¶("Foot"))],
"",
));
for page in 0..2 {
reads_the_header_body_and_footer_of(&document, page);
}
assert_eq!(story(&document, TextStory::Body), ["One", "Two"]);
let body = document.story_text(TextStory::Body);
let addresses: Vec<String> = body
.iter()
.map(|paragraph| paragraph.address.as_ref().unwrap().to_string())
.collect();
assert_eq!(addresses, ["p1", "p2"]);
let second = document.text_map(1);
assert_eq!(second.get(1).map(|line| line.paragraph), Some(1));
assert_eq!(document.text_map(2), Vec::new());
// The text maps of several pages from one read of each story are those of each page.
let maps = document.text_maps(&[1, 0, 2]);
assert_eq!(maps, [second, document.text_map(0), Vec::new()]);
}
/// Checks that page `page` of `document` reads its header, its body and its footer in turn.
fn reads_the_header_body_and_footer_of(document: &Document, page: usize) {
let stories: Vec<TextStory> = document.text_map(page).iter().map(|l| l.story).collect();
let expected = [
TextStory::Header { page },
TextStory::Body,
TextStory::Footer { page },
];
assert_eq!(stories, expected);
assert_eq!(story(document, TextStory::Header { page }), ["Head"]);
assert_eq!(story(document, TextStory::Footer { page }), ["Foot"]);
let header = addresses(document, TextStory::Header { page });
assert_eq!(header, [Some("h1/p1".to_owned())]);
let footer = addresses(document, TextStory::Footer { page });
assert_eq!(footer, [Some("f1/p1".to_owned())]);
}
#[test]
fn numbers_the_header_parts_in_the_order_in_which_the_sections_name_them() {
let header = |id: &str| format!(r#"<w:headerReference w:type="default" r:id="{id}"/>"#);
let body = format!(
r#"<w:p><w:pPr><w:sectPr xmlns:r="{RELATIONSHIPS}">{}{SECTION}</w:sectPr></w:pPr></w:p>{}<w:sectPr xmlns:r="{RELATIONSHIPS}">{}{SECTION}</w:sectPr>"#,
header("h2"),
para("Two"),
header("h1"),
);
let document = open(&docx(
&body,
&[("h1", ¶("Last")), ("h2", ¶("First"))],
"",
));
let first = TextStory::Header { page: 0 };
let last = TextStory::Header { page: 1 };
assert_eq!(story(&document, first), ["First"]);
assert_eq!(addresses(&document, first), [Some("h1/p1".to_owned())]);
assert_eq!(story(&document, last), ["Last"]);
assert_eq!(addresses(&document, last), [Some("h2/p1".to_owned())]);
}
#[test]
fn reads_the_footnotes_as_one_story_after_the_body() {
let body = format!(
r#"<w:p><w:r>{CARLITO_RUN}<w:t>Body</w:t></w:r><w:r>{CARLITO_RUN}<w:footnoteReference w:id="1"/></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"#
);
let note = format!(
r#"<w:footnote w:type="separator" w:id="-1"><w:p><w:r>{CARLITO_RUN}<w:separator/></w:r></w:p></w:footnote><w:footnote w:id="1"><w:p><w:r>{CARLITO_RUN}<w:footnoteRef/></w:r><w:r>{CARLITO_RUN}<w:t xml:space="preserve"> Note</w:t></w:r></w:p></w:footnote>"#
);
let document = open(&docx(&body, &[("n1", ¬e)], ""));
let stories: Vec<TextStory> = document.text_map(0).iter().map(|l| l.story).collect();
assert_eq!(stories, [TextStory::Body, TextStory::Footnotes]);
assert_eq!(story(&document, TextStory::Body), ["Body1"]);
assert_eq!(story(&document, TextStory::Footnotes), ["1 Note"]);
let notes = addresses(&document, TextStory::Footnotes);
assert_eq!(notes, [Some("n1/p1".to_owned())]);
}
#[test]
fn reads_the_endnotes_as_a_story_of_their_own() {
let body = format!(
r#"<w:p><w:r>{CARLITO_RUN}<w:t>Body</w:t></w:r><w:r>{CARLITO_RUN}<w:endnoteReference w:id="1"/></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"#
);
let note = format!(
r#"<w:endnote w:type="separator" w:id="-1"><w:p><w:r>{CARLITO_RUN}<w:separator/></w:r></w:p></w:endnote><w:endnote w:id="1"><w:p><w:r>{CARLITO_RUN}<w:endnoteRef/></w:r><w:r>{CARLITO_RUN}<w:t xml:space="preserve"> Note</w:t></w:r></w:p></w:endnote>"#
);
let document = open(&docx(&body, &[("e1", ¬e)], ""));
let stories: Vec<TextStory> = document.text_map(0).iter().map(|l| l.story).collect();
let endnotes = TextStory::Endnotes;
assert_eq!(stories, [TextStory::Body, endnotes, endnotes]);
assert_eq!(story(&document, TextStory::Body), ["Bodyi"]);
assert_eq!(story(&document, endnotes), ["", "i Note"]);
let notes = addresses(&document, endnotes);
assert_eq!(notes, [None, Some("e1/p1".to_owned())]);
}
#[test]
fn reads_a_frame_as_a_story_of_its_own() {
let frame = r#"<w:p><w:pPr><w:framePr w:wrap="none" w:vAnchor="text" w:hAnchor="margin" w:xAlign="right"/></w:pPr>"#;
let body = format!(
"{}{}{}<w:sectPr>{SECTION}</w:sectPr>",
para("Before"),
para("Framed").replacen("<w:p>", frame, 1),
para("After"),
);
let document = open(&docx(&body, &[], ""));
let framed = TextStory::Frame { page: 0, number: 0 };
let stories: Vec<TextStory> = document.text_map(0).iter().map(|l| l.story).collect();
assert_eq!(stories, [TextStory::Body, TextStory::Body, framed]);
assert_eq!(story(&document, TextStory::Body), ["Before", "After"]);
assert_eq!(story(&document, framed), ["Framed"]);
assert_eq!(addresses(&document, framed), [Some("p2".to_owned())]);
}
/// A text box anchored to the page at `top` EMUs that holds `text`.
fn anchored_text_box(top: u32, text: &str) -> String {
format!(
r#"<w:r><w:drawing xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:wps="http://schemas.microsoft.com/office/word/2010/wordprocessingShape"><wp:anchor behindDoc="0"><wp:positionH relativeFrom="page"><wp:posOffset>1270000</wp:posOffset></wp:positionH><wp:positionV relativeFrom="page"><wp:posOffset>{top}</wp:posOffset></wp:positionV><wp:extent cx="1270000" cy="635000"/><wp:wrapNone/><a:graphic><a:graphicData><wps:wsp><wps:txbx><w:txbxContent><w:p><w:r>{CARLITO_RUN}<w:t>{text}</w:t></w:r></w:p></w:txbxContent></wps:txbx><wps:bodyPr/></wps:wsp></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r>"#
)
}
#[test]
fn reads_each_text_box_as_a_story_of_its_own() {
let boxes = anchored_text_box(5_080_000, "Two") + &anchored_text_box(3_810_000, "One");
let body = format!(
"<w:p><w:r>{CARLITO_RUN}<w:t>Body</w:t></w:r>{boxes}</w:p><w:sectPr>{SECTION}</w:sectPr>"
);
let document = open(&docx(&body, &[], ""));
let first = TextStory::TextBox { page: 0, number: 0 };
let second = TextStory::TextBox { page: 0, number: 1 };
let stories: Vec<TextStory> = document.text_map(0).iter().map(|l| l.story).collect();
assert_eq!(stories, [TextStory::Body, first, second]);
assert_eq!(story(&document, first), ["Two"]);
assert_eq!(story(&document, second), ["One"]);
assert_eq!(addresses(&document, first), [Some("p1/b1/p1".to_owned())]);
assert_eq!(addresses(&document, second), [Some("p1/b2/p1".to_owned())]);
}
#[test]
fn ends_the_last_line_of_each_cell_at_the_cell() {
let cell = |texts: &[&str]| {
let paragraphs: String = texts.iter().map(|text| para(text)).collect();
format!("<w:tc>{paragraphs}</w:tc>")
};
let body = format!(
r#"<w:tbl><w:tblGrid><w:gridCol w:w="2000"/><w:gridCol w:w="2000"/></w:tblGrid><w:tr>{}{}</w:tr></w:tbl>{}"#,
cell(&["a"]),
cell(&["b", "c"]),
para("after"),
);
let document = open(&docx(&body, &[], ""));
assert_eq!(story(&document, TextStory::Body), ["a", "b", "c", "after"]);
let ends: Vec<LineTextEnd> = document.text_map(0).iter().map(|line| line.ends).collect();
let expected = [
LineTextEnd::Cell,
LineTextEnd::Paragraph,
LineTextEnd::Cell,
LineTextEnd::Paragraph,
];
assert_eq!(ends, expected);
let cells: Vec<Option<usize>> = document
.story_text(TextStory::Body)
.iter()
.map(|paragraph| paragraph.cell.map(|cell| cell.column))
.collect();
assert_eq!(cells, [Some(1), Some(2), Some(2), None]);
}
#[test]
fn reads_a_turned_cell_in_the_order_of_its_row() {
let cell = |direction: &str, text: &str| {
let turned = format!(r#"<w:tcPr><w:textDirection w:val="{direction}"/></w:tcPr>"#);
let properties = if direction.is_empty() { "" } else { &turned };
format!("<w:tc>{properties}{}</w:tc>", para(text))
};
let body = format!(
r#"<w:tbl><w:tblGrid><w:gridCol w:w="1500"/><w:gridCol w:w="1500"/><w:gridCol w:w="1500"/></w:tblGrid><w:tr><w:trPr><w:trHeight w:val="2000"/></w:trPr>{}{}{}</w:tr></w:tbl>{}"#,
cell("", "left"),
cell("btLr", "up"),
cell("", "right"),
para("after"),
);
let document = open(&docx(&body, &[], ""));
assert_eq!(
story(&document, TextStory::Body),
["left", "up", "right", "after"]
);
let lines = document.text_map(0);
let turned: Vec<&TextLine> = lines.iter().filter(|line| line.turn.is_some()).collect();
let [line] = turned.as_slice() else {
panic!("{lines:?}");
};
assert_eq!(line.paragraph, 1);
// The first cluster's origin in the frame lands where the page draws its glyph.
let turn = line.turn.unwrap();
let (x, y) = (line.clusters[0].left, line.top + line.baseline);
let (dx, dy) = (x - turn.from.0, y - turn.from.1);
let scale = i64::from(f_office_paint::Turn::SCALE);
let landed = (
turn.to.0
+ (dx * i64::from(turn.turn.xx) + dy * i64::from(turn.turn.xy)).div_toward_zero(scale),
turn.to.1
+ (dx * i64::from(turn.turn.yx) + dy * i64::from(turn.turn.yy)).div_toward_zero(scale),
);
let drawn = drawn_places(&document, 0);
let (place, _) = drawn.iter().find(|(_, text)| text == "u").unwrap();
let near = Length::UNITS_PER_POINT;
assert!(
(landed.0 - place.0).units().abs() < near && (landed.1 - place.1).units().abs() < near,
"{landed:?} {place:?}"
);
}
#[test]
fn gives_a_ligature_one_cluster_for_its_characters() {
let w14 = "http://schemas.microsoft.com/office/word/2010/wordml";
let body = format!(
r#"<w:p><w:r><w:rPr>{CARLITO_FONTS}<w14:ligatures xmlns:w14="{w14}" w14:val="standard"/></w:rPr><w:t>office</w:t></w:r></w:p>"#
);
let document = open(&docx(&body, &[], &compatibility_mode(15)));
let text = &story(&document, TextStory::Body)[0];
let lines = document.text_map(0);
assert_eq!(clusters(&lines[0], text), ["o", "ffi", "c", "e"]);
}
#[test]
fn gives_the_clusters_of_right_to_left_text_in_visual_order() {
let document = open(&docx(¶("abc \u{5D0}\u{5D1}\u{5D2}"), &[], ""));
let text = &story(&document, TextStory::Body)[0];
let lines = document.text_map(0);
assert_eq!(
clusters(&lines[0], text),
["a", "b", "c", " ", "\u{5D2}", "\u{5D1}", "\u{5D0}"]
);
for pair in lines[0].clusters.windows(2) {
assert!(pair[0].left < pair[1].left, "{pair:?}");
}
}
#[test]
fn leaves_an_automatic_hyphen_out_of_the_text() {
let words = "Characterization internationalization interdisciplinary \
telecommunications representativeness incomprehensibility";
let body = format!(
r#"<w:p><w:r><w:rPr>{CARLITO_FONTS}<w:lang w:val="en-US"/></w:rPr><w:t>{words}</w:t></w:r></w:p><w:sectPr>{SECTION}</w:sectPr>"#
);
let options = Options {
overrides: crate::suite::profile::Overrides::default()
.with_quirk("AutomaticHyphenation", "EnglishFrenchSpanish"),
..Options::base()
};
let docx = docx(&body, &[], "<w:autoHyphenation/>");
let document = Document::open(&docx, &carlito(), &options).unwrap().value;
let lines: Vec<TextLine> = (0..document.page_count())
.flat_map(|page| document.text_map(page))
.collect();
let automatic = lines
.iter()
.filter(|line| line.hyphen == Some(EndHyphen::Automatic));
assert_ne!(automatic.count(), 0, "{lines:?}");
assert_eq!(story(&document, TextStory::Body), [words]);
}
#[test]
fn places_an_empty_line_where_it_starts_after_its_alignment() {
let empty =
|alignment: &str| format!(r#"<w:p><w:pPr><w:jc w:val="{alignment}"/></w:pPr></w:p>"#);
let body = format!(
"{}{}{}{}{}<w:sectPr>{SECTION}</w:sectPr>",
para("Text"),
empty("left"),
empty("center"),
empty("right"),
paragraph(&["<w:br/>"]),
);
let document = open(&docx(&body, &[], ""));
let lines = document.text_map(0);
let [text, left, center, right, broken, ..] = lines.as_slice() else {
panic!("{lines:?}");
};
assert_eq!(text.left, text.clusters[0].left);
assert!(
left.clusters.is_empty() && center.clusters.is_empty(),
"{lines:?}"
);
assert_eq!(left.left, text.left);
let off_middle = (center.left * 2 - left.left - right.left).units().abs();
assert!(
off_middle <= Length::from_points(2).unwrap().units(),
"{lines:?}"
);
assert!(
left.left < center.left && center.left < right.left,
"{lines:?}"
);
assert_eq!(broken.left, text.left);
assert_eq!(broken.clusters[0].left, text.left);
}
#[test]
fn leaves_a_soft_hyphen_at_a_wrap_out_of_the_text() {
let word = r#"<w:t>inter</w:t><w:softHyphen/><w:t>nation</w:t><w:softHyphen/><w:t xml:space="preserve">alization </w:t>"#;
let body = paragraph(&[&word.repeat(12)]) + &format!("<w:sectPr>{SECTION}</w:sectPr>");
let document = open(&docx(&body, &[], ""));
let lines = document.text_map(0);
let soft = lines
.iter()
.filter(|line| line.hyphen == Some(EndHyphen::Soft))
.count();
assert_ne!(soft, 0, "{lines:?}");
let drawn = drawn_glyphs(&document, 0);
let hyphens = drawn.iter().filter(|(_, text)| text == "-").count();
assert_eq!(hyphens, soft, "{drawn:?}");
assert_eq!(
story(&document, TextStory::Body),
["internationalization ".repeat(12)]
);
}
/// A paragraph of Carlito runs, one for each of `runs`, each the content of its run after
/// its properties.
fn paragraph(runs: &[&str]) -> String {
let mut paragraph = String::from("<w:p>");
for content in runs {
write!(paragraph, "<w:r>{CARLITO_RUN}{content}</w:r>").unwrap();
}
paragraph + "</w:p>"
}
/// The content of a run of the text `text`.
fn text(text: &str) -> String {
format!(r#"<w:t xml:space="preserve">{text}</w:t>"#)
}
/// `count` words, enough for several lines.
fn words(count: usize) -> String {
let names = ["alpha", "beta", "gamma", "delta", "epsilon"];
(0..count)
.map(|n| names.get(n % names.len()).copied().unwrap_or_default())
.collect::<Vec<_>>()
.join(" ")
}
#[test]
fn loses_no_character_of_a_body_paragraph() {
// Paragraphs of the default page, the first of several lines with a tab, the others with
// a line break and a page break.
let body = format!(
"{}{}{}",
paragraph(&[&text(&words(30)), "<w:tab/>", &text(&words(30))]),
paragraph(&[&text("after"), "<w:br/>", &text("the break")]),
paragraph(&[
&text("before"),
r#"<w:br w:type="page"/>"#,
&text("the page")
]),
);
let document = open(&docx(&body, &[], ""));
let lines = document.text_map(0);
let first: Vec<&TextLine> = lines.iter().filter(|line| line.paragraph == 0).collect();
assert!(first.len() > 2, "{first:?}");
let mut ends = vec![LineTextEnd::Wrap; first.len() - 1];
ends.push(LineTextEnd::Paragraph);
assert_eq!(first.iter().map(|line| line.ends).collect::<Vec<_>>(), ends);
for pair in first.windows(2) {
assert_eq!(pair[0].end, pair[1].start);
}
let story = document.story_text(TextStory::Body);
assert_eq!(story.len(), 3);
for paragraph in &story {
let block = document
.text_blocks()
.iter()
.find(|block| Some(&block.address) == paragraph.address.as_ref())
.unwrap();
let TextBlockKind::Paragraph { text, .. } = &block.kind else {
panic!("{block:?}");
};
assert_eq!(¶graph.text, text);
}
}
/// The x of each glyph that the page at `index` draws, with the text that it shows.
fn drawn_glyphs(document: &Document, index: usize) -> Vec<(Length, String)> {
drawn_places(document, index)
.into_iter()
.map(|((x, _), text)| (x, text))
.collect()
}
/// The origin of each glyph that the page at `index` draws, with the text that it shows.
fn drawn_places(document: &Document, index: usize) -> Vec<((Length, Length), String)> {
let mut glyphs = Vec::new();
add_glyphs(document.page(index).unwrap().items(), &mut glyphs);
glyphs
}
/// Adds the origin of each glyph that `items` and their groups draw, with the text that it
/// shows.
fn add_glyphs(items: &[Item], glyphs: &mut Vec<((Length, Length), String)>) {
for item in items {
match item {
Item::Glyphs(run) => {
for glyph in &run.glyphs {
let text = run.glyph_text(glyph).unwrap_or_default().to_owned();
glyphs.push(((glyph.x, glyph.y), text));
}
}
Item::Group(group) => add_glyphs(&group.items, glyphs),
Item::Rect(_) | Item::Path(_) | Item::Gradient(_) | Item::Image(_) => {}
}
}
}
#[test]
fn puts_each_cluster_where_the_page_draws_its_glyph() {
let body = paragraph(&[&text("Water and fire."), "<w:tab/>", &text("Yes")]);
let docx = docx(&body, &[], "");
for target in Target::all() {
let options = Options {
configuration: crate::Configuration::of(target),
..Options::base()
};
let document = Document::open(&docx, &carlito(), &options).unwrap().value;
check_clusters_on_drawn_glyphs(&document);
}
}
/// Checks that the clusters of the one line of `document` lie where its page draws their
/// glyphs, and that each reaches to the next.
fn check_clusters_on_drawn_glyphs(document: &Document) {
let lines = document.text_map(0);
let [line] = lines.as_slice() else {
panic!("{lines:?}");
};
let own = &story(document, TextStory::Body)[0];
let shown = clusters(line, own);
let mut glyph_clusters = line
.clusters
.iter()
.zip(&shown)
.filter(|(_, shown)| **shown != "\t");
for (x, glyph_text) in drawn_glyphs(document, 0) {
let (cluster, shown) = glyph_clusters.next().unwrap();
assert_eq!(*shown, glyph_text);
assert_eq!(cluster.left, x, "{glyph_text}");
}
assert!(glyph_clusters.next().is_none());
for pair in line.clusters.windows(2) {
assert_eq!(pair[0].right, pair[1].left);
assert!(pair[0].left < pair[0].right, "{pair:?}");
}
}