f-office-docx 0.1.0

DOCX model and Word's layout rules.
Documentation
//! What the trial layout of a table row leaves when the layout takes the row back and lays it
//! out again (**Row mark**): F-Office
//! holds a note, a drawing or a number only for the page where its reference or its anchor is
//! drawn. A page holds 64 lines of 200 twips, so a row after 64 lines moves to the next page. The
//! footnote of such a row stays on both pages.

use f_office_paint::DisplayList;

use crate::body::Body;
use crate::layout::style_refs::Record;
use crate::layout::testing::{
    AnchoredShape, Fake, NORMAL, SQUARE_WRAP, ShapeText, base_context, filler, find_all, p, parse,
    pass_with_header, sections_of, table, with_layout,
};
use crate::layout::{Layout, LineStory, PlacedLine, Stories};
use crate::ns::{A, PIC, R, W, WP, WPS};
use crate::quirks::BodyFieldResults;
use crate::reader::PartReader;
use crate::styles::{FontTable, Settings, Styles, Theme};
use crate::testing::{WordParts, docx};
use crate::text::{Shaper, ShaperSettings};

/// Lays out `body` with plain styles and the parts `parts`, each as the type of its
/// relationship, its file in `word/`, its root element and its content, and gives the pages
/// and the placed lines.
fn laid_out(body: &str, parts: &[(&str, &str, &str, &str)]) -> (DisplayList, Vec<PlacedLine>) {
    let builder =
        parts
            .iter()
            .enumerate()
            .fold(docx(body).plain_styles(), |builder, (index, part)| {
                let (kind, target, root, content) = *part;
                builder.word_part(&format!("t{index}"), kind, target, root, content)
            });
    let bytes = builder.zip().unwrap();
    let package = f_office_opc::Package::open(&bytes, &f_office_opc::Limits::default()).unwrap();
    let laid_out = crate::layout_with_fonts(
        &package,
        (&Fake, &crate::ArtPictures::new()),
        &crate::Options::base(),
    )
    .unwrap()
    .value;
    (laid_out.list, laid_out.lines)
}

/// The page of each glyph of `ch`.
fn pages_of(list: &DisplayList, ch: char) -> Vec<usize> {
    find_all(list, ch)
        .into_iter()
        .map(|(page, ..)| page)
        .collect()
}

/// A table of one row that holds `cell`, after 64 lines that fill the first page, so that the
/// row moves to the next page. The row cannot split, so it moves whole.
fn moved_row(cell: &str) -> String {
    filler(64) + &table("", &[2000], &[("<w:cantSplit/>", &[cell])])
}

/// The numbers of the tables that the placed lines lie in, each once, in order.
fn table_numbers(lines: &[PlacedLine]) -> Vec<usize> {
    let mut numbers: Vec<usize> = lines
        .iter()
        .filter_map(|line| line.cell.map(|cell| cell.table))
        .collect();
    numbers.sort_unstable();
    numbers.dedup();
    numbers
}

/// A paragraph with the text "a" and a run that holds `run`.
fn after_a(run: &str) -> String {
    format!("<w:p><w:r><w:t>a</w:t></w:r><w:r>{run}</w:r></w:p>")
}

#[test]
fn gives_a_bookmark_of_a_moved_row_the_page_where_the_row_stands() {
    // The row's trial on the first page records the bookmark there, and the row mark takes
    // the record back, so the bookmark has the
    // page where the row is drawn.
    let cell = r#"<w:p><w:bookmarkStart w:id="0" w:name="mark"/><w:r><w:t>b</w:t></w:r><w:bookmarkEnd w:id="0"/></w:p>"#;
    let pass = pass_with_header(&moved_row(cell), NORMAL, None, None);
    assert_eq!(pages_of(&pass.list, 'b'), [1]);
    assert_eq!(pass.bookmarks.get("mark").map(String::as_str), Some("2"));
}

#[test]
fn lists_the_endnote_of_a_moved_row_once() {
    let cell = after_a(r#"<w:endnoteReference w:id="1"/>"#);
    let notes = r#"<w:endnote w:id="1"><w:p><w:r><w:t>e</w:t></w:r></w:p></w:endnote>"#;
    let endnotes = ("endnotes", "endnotes.xml", "endnotes", notes);
    let (list, _) = laid_out(&moved_row(&cell), &[endnotes]);
    assert_eq!(pages_of(&list, 'a'), [1]);
    assert_eq!(pages_of(&list, 'e'), [1]);
}

/// The footnotes part with footnote 1, whose text is "n".
const FOOTNOTE_N: (&str, &str, &str, &str) = (
    "footnotes",
    "footnotes.xml",
    "footnotes",
    r#"<w:footnote w:id="1"><w:p><w:r><w:t>n</w:t></w:r></w:p></w:footnote>"#,
);

#[test]
fn keeps_the_footnote_records_of_the_page_where_a_row_splits_on_that_page() {
    // The footnote of the body's first line stands on the first page, where the row below
    // splits; the records of its lines name that page, as its glyphs do.
    let body = after_a(r#"<w:footnoteReference w:id="1"/>"#)
        + &filler(57)
        + &table("", &[2000], &[("", &[&p("b").repeat(8)])]);
    let (list, lines) = laid_out(&body, &[FOOTNOTE_N]);
    let b_pages = pages_of(&list, 'b');
    assert!(b_pages.contains(&0) && b_pages.contains(&1), "{b_pages:?}");
    assert_eq!(pages_of(&list, 'n'), [0]);
    let records: Vec<usize> = lines
        .iter()
        .filter(|line| line.story == LineStory::Footnote)
        .map(|line| line.page)
        .collect();
    assert_eq!(records, [0]);
}

#[test]
fn draws_an_anchored_shape_or_a_frame_of_a_moved_row_only_on_the_page_of_its_anchor() {
    let blocks = p("z");
    let shape = |wrap| AnchoredShape {
        across: ("column", 0),
        down: ("paragraph", 0),
        size: (635_000, 254_000),
        wrap,
        outline: None,
        text: Some(ShapeText {
            blocks: &blocks,
            body: "<wps:bodyPr/>",
        }),
    };
    for wrap in ["<wp:wrapNone/>", SQUARE_WRAP] {
        let cell = after_a(&shape(wrap).drawing());
        let (list, _) = laid_out(&moved_row(&cell), &[]);
        assert_eq!(pages_of(&list, 'a'), [1], "{wrap}");
        assert_eq!(pages_of(&list, 'z'), [1], "{wrap}");
    }
    let frame = r#"<w:p><w:pPr><w:framePr w:w="1000" w:hAnchor="text" w:vAnchor="text"/></w:pPr><w:r><w:t>f</w:t></w:r></w:p>"#;
    let (list, _) = laid_out(&moved_row(&(frame.to_owned() + &p("a"))), &[]);
    assert_eq!(
        (pages_of(&list, 'a'), pages_of(&list, 'f')),
        (vec![1], vec![1])
    );
}

#[test]
fn numbers_the_tables_of_a_moved_row_without_a_gap() {
    let nested = table("", &[1000], &[("", &[&p("b")])]);
    let after = table("", &[2000], &[("", &[&p("c")])]);
    let numbers = |body: &str| table_numbers(&laid_out(body, &[]).1);
    // The same row on the first page, where it fits, and after 64 lines, where it moves.
    let row = table(
        "",
        &[2000],
        &[("<w:cantSplit/>", &[&(nested.clone() + "<w:p/>")])],
    );
    let fits = numbers(&(row.clone() + &after));
    assert_eq!(fits.len(), 2);
    let moved = numbers(&(filler(64) + &row + &after));
    // A cell that moves down for its vertical alignment is laid out again.
    let beside = |align: &str| {
        let cell = format!(r#"<w:tcPr><w:vAlign w:val="{align}"/></w:tcPr>{nested}<w:p/>"#);
        let row = table("", &[2000, 2000], &[("", &[&p("x").repeat(4), &cell])]);
        numbers(&(row + &after))
    };
    assert_eq!((moved, beside("center")), (fits, beside("top")));
}

/// The pictures and the inline drawings that a layout of `body` keeps in its output, which
/// object pieces name by their index.
fn kept_objects(body: &str) -> (usize, usize) {
    let doc = parse(&format!(r#"<w:body xmlns:w="{W}">{body}</w:body>"#));
    let body = Body::read(
        &mut PartReader::new(&doc),
        doc.root().unwrap(),
        (
            crate::reader::settings::ReaderSettings::base()
                .with_body_results(BodyFieldResults::ComputesFields)
                .with_section_ends(crate::quirks::ContinuousSectionEnd::OnlyBlockKeepsLine),
            crate::mode::ModeRules::default(),
        ),
    );
    let (styles, settings) = (Styles::default(), Settings::default());
    let (theme, fonts) = (Theme::default(), FontTable::default());
    let context = base_context(&styles, &settings);
    let stories = context.for_stories();
    let sections = sections_of(&body, &Stories::default());
    let mut layout = Layout::new(
        (&context, &stories),
        &sections,
        Shaper::new(&Fake, &theme, &fonts, &ShaperSettings::base()),
    );
    // As `Layout::run_with_wraps` starts the body.
    layout.measure_body();
    layout.start_wraps();
    layout.y = layout.page_top(0);
    layout.column_top = layout.y;
    layout.sections_flow(&body.blocks);
    (layout.output.pictures.len(), layout.output.drawings.len())
}

#[test]
fn keeps_the_inline_picture_and_drawing_of_a_moved_row_once() {
    let inline = |data: &str| {
        format!(
            r#"<w:drawing><wp:inline xmlns:wp="{WP}" distT="0" distB="0" distL="0" distR="0"><wp:extent cx="127000" cy="127000"/><a:graphic xmlns:a="{A}"><a:graphicData>{data}</a:graphicData></a:graphic></wp:inline></w:drawing>"#
        )
    };
    let shape = format!(
        r#"<wps:wsp xmlns:wps="{WPS}"><wps:spPr><a:prstGeom prst="rect"/></wps:spPr><wps:bodyPr/></wps:wsp>"#
    );
    let picture = format!(
        r#"<pic:pic xmlns:pic="{PIC}"><pic:blipFill><a:blip xmlns:r="{R}" r:embed="rId1"/></pic:blipFill><pic:spPr/></pic:pic>"#
    );
    let runs = format!("{}</w:r><w:r>{}", inline(&picture), inline(&shape));
    let row = table("", &[2000], &[("<w:cantSplit/>", &[&after_a(&runs)])]);
    // The same row on the first page, where it fits, and after 64 lines, where it moves.
    let fits = kept_objects(&row);
    assert_eq!(fits, (1, 1));
    assert_eq!(kept_objects(&(filler(64) + &row)), fits);
}

#[test]
fn takes_back_at_a_rewind_to_a_mark_the_fields_that_a_trial_took_or_found() {
    // A rewind takes back the last paragraph of the previous section
    // and the keep chain of the table before, which the first paragraph after the mark takes,
    // and the wraps, bookmarks and number contexts that the trial found.
    let numbering = parse(&format!(
        r#"<w:numbering xmlns:w="{W}"><w:abstractNum w:abstractNumId="0"><w:lvl w:ilvl="0"><w:numFmt w:val="decimal"/><w:lvlText w:val="%1."/></w:lvl></w:abstractNum><w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num></w:numbering>"#
    ));
    let mut lists = crate::numbering::Numbering::read(
        &mut PartReader::new(&numbering),
        numbering.root().unwrap(),
        crate::reader::settings::ReaderSettings::with_built_in_list(
            crate::quirks::BuiltInList::WithoutPart,
        ),
    );
    let list = std::num::NonZeroU32::new(1).map(|list| (list, 0));
    let label = lists.next_label(list, None).unwrap();
    with_layout(|layout| {
        let previous = crate::layout::Previous::of(&crate::props::ParaProps::default());
        layout.section_previous = Some(previous);
        layout.table_chain = crate::layout::TableChain::GoesOn;
        let mark = layout.mark();
        layout.section_previous = None;
        layout.table_chain = crate::layout::TableChain::Ends;
        layout.output.found.bands.push((
            0,
            (f_office_units::Length::ZERO, f_office_units::Length::ZERO),
        ));
        layout
            .output
            .found_bookmarks
            .record("trial", || "1".to_owned());
        layout
            .output
            .found_numbers
            .record("trial", || label.reference.clone());
        layout.rewind(&mark);
        assert!(layout.section_previous.is_some());
        assert_eq!(layout.table_chain, crate::layout::TableChain::GoesOn);
        assert!(layout.output.found.is_empty());
        assert_eq!(layout.output.found_bookmarks.count(), 0);
        assert_eq!(layout.output.found_numbers.count(), 0);
    });
}

#[test]
fn takes_back_the_styled_text_and_the_chapter_number_of_a_row_trial() {
    with_layout(|layout| {
        layout.output.styled = Some(Record::default());
        layout.note_styled(&crate::body::Paragraph::empty(), None);
        let before = layout.output.styled.as_ref().map(Record::mark);
        let mark = layout.row_mark();
        // The trial places a chapter heading in a cell of the row on the page, and the layout
        // takes the row back to move it to the next page.
        layout.note_styled(&crate::body::Paragraph::empty(), None);
        layout.output.chapter_number = Some(2);
        layout.back_to_row_mark(&mark);
        assert_eq!(layout.output.styled.as_ref().map(Record::mark), before);
        assert_eq!(layout.output.chapter_number, None);
    });
}