f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
//! Tests of the kept heights of the footnote separators.

use f_office_fonts::{FamilyName, FontId};
use f_office_paint::Item;
use f_office_units::Length;
use f_office_warnings::Name;
use f_office_xml::{Document, Limits};

use super::Separator;
use crate::body::{Notes, Section, Sections};
use crate::layout::testing::base_context;
use crate::layout::{Context, Layout, SectionLayout};
use crate::ns::W;
use crate::quirks::{Quirks, SeparatorSpaceAfter};
use crate::reader::PartReader;
use crate::styles::{FontTable, NoteSeparators, Settings, Styles, Theme};
use crate::text::{Shaper, ShaperSettings};
use crate::{ChosenFace, FaceMetrics, Fonts, Warning};

/// One face of 1000 units to the em, which stands in for every family, so that each run of
/// a family gives a font note.
struct StandIn;

impl Fonts for StandIn {
    fn face(&self, _family: &FamilyName, _bold: bool, _italic: bool) -> Option<ChosenFace> {
        Some(ChosenFace {
            font: FontId::from_index(0),
            metrics: FaceMetrics {
                units_per_em: 1000,
                hhea_ascender: 800,
                hhea_descender: -200,
                hhea_line_gap: 0,
                descent: 200,
                underline_position: -100,
                underline_thickness: 50,
                strikeout_position: 250,
                strikeout_thickness: 50,
                superscript_offset: 0,
                subscript_offset: 0,
                superscript_size: 0,
                subscript_size: 0,
                line_top: 800,
                script_top: 800,
                east_asian: false,
                average_width: 500,
            },
            synthetic_bold: false,
            synthetic_italic: false,
            stands_in: true,
        })
    }

    fn glyph(&self, _font: FontId, ch: char) -> Option<u32> {
        Some(u32::from(ch))
    }

    fn advance(&self, _font: FontId, _glyph: u32) -> Option<u16> {
        Some(500)
    }
}

/// A separator of two paragraphs, whose runs ask for a family that the fonts stand in for.
fn separator() -> Notes {
    notes_of(
        r#"<w:p><w:r><w:rPr><w:rFonts w:ascii="Asked" w:hAnsi="Asked"/><w:sz w:val="20"/></w:rPr><w:t>x</w:t></w:r></w:p><w:p><w:r><w:rPr><w:rFonts w:ascii="Asked" w:hAnsi="Asked"/></w:rPr><w:t>x</w:t></w:r></w:p>"#,
    )
}

/// Footnotes whose separator and continuation separator are the paragraphs `paragraphs`.
fn notes_of(paragraphs: &str) -> Notes {
    let xml = format!(r#"<w:footnote xmlns:w="{W}">{paragraphs}</w:footnote>"#);
    let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
    let blocks = crate::body::read_story(&mut PartReader::new(&doc), doc.root().unwrap());
    Notes {
        separator: blocks.clone(),
        continuation: blocks,
        ..Notes::default()
    }
}

/// Runs `check` on a layout of the body of a pass whose footnotes have the separators of
/// [`separator`].
fn with_layout(check: impl FnOnce(&mut Layout<'_>, &mut Layout<'_>)) {
    with_notes(separator(), check);
}

/// Runs `check` on two layouts of the body of a pass whose footnotes are `notes`.
fn with_notes(notes: Notes, check: impl FnOnce(&mut Layout<'_>, &mut Layout<'_>)) {
    with_notes_in(
        notes,
        (&Settings::default(), crate::grid::base_quirks()),
        check,
    );
}

/// Runs `check` on two layouts of the body of a pass whose footnotes are `notes`, under the
/// settings `settings` and with the quirks `quirks`.
fn with_notes_in(
    notes: Notes,
    (settings, quirks): (&Settings, Quirks),
    check: impl FnOnce(&mut Layout<'_>, &mut Layout<'_>),
) {
    let styles = Styles::default();
    let (theme, fonts) = (Theme::default(), FontTable::default());
    let context = Context {
        notes,
        quirks,
        ..base_context(&styles, settings)
    };
    let stories = context.for_stories();
    let sections = Sections::one(SectionLayout::plain(&Section::default(), 0));
    let layout = || {
        Layout::new(
            (&context, &stories),
            &sections,
            Shaper::new(&StandIn, &theme, &fonts, &ShaperSettings::base()),
        )
    };
    check(&mut layout(), &mut layout());
}

/// Lays out `separator` three times from 0 in `repeated`, and checks that each layout gives
/// the items and the end of the first, and that each of three uses of its kept height in
/// `kept` gives that end.
fn uses_three_times(separator: Separator, repeated: &mut Layout<'_>, kept: &mut Layout<'_>) {
    let first = repeated.separator(separator, Length::ZERO);
    assert!(first.1 > Length::ZERO);
    for _ in 0..2 {
        assert_eq!(repeated.separator(separator, Length::ZERO), first);
    }
    for _ in 0..3 {
        assert_eq!(kept.separator_height(separator), first.1);
    }
}

#[test]
fn one_layout_of_a_separator_gives_the_items_end_and_warnings_of_each_repeated_layout() {
    with_layout(|repeated, kept| {
        uses_three_times(Separator::Normal, repeated, kept);
        uses_three_times(Separator::Continuation, repeated, kept);
        assert_eq!(kept.output.warnings, repeated.output.warnings);
        let notes = repeated.shaper.take_notes();
        assert!(!notes.substituted.is_empty());
        assert_eq!(kept.shaper.take_notes(), notes);
        assert_eq!(kept.output.notes.separators.len(), 2);
    });
}

#[test]
fn each_use_of_a_kept_separator_adds_its_notes_and_its_warnings_once_until_a_story_input_changes() {
    with_layout(|_, layout| {
        let height = layout.separator_height(Separator::Normal);
        let kept = &mut layout
            .output
            .notes
            .separators
            .get_mut(&Separator::Normal)
            .unwrap()
            .1;
        // A kept height that differs from a new layout's shows which one a use takes.
        kept.height = height + Length::from_units(1);
        let warning = Warning::FontSubstituted {
            asked: Name::new("a"),
            used: Some(Name::new("b")),
            version: None,
            layout: crate::SubstituteLayout::Widths,
        };
        kept.warnings.push(warning.clone());
        let notes = layout.shaper.take_notes();
        let mark = layout.mark();
        // The warnings of a separator count once, whatever the number of its uses.
        for _ in 0..2 {
            assert_eq!(
                layout.separator_height(Separator::Normal),
                height + Length::from_units(1)
            );
            let warnings: Vec<_> = layout.output.warnings.clone().into_iter().collect();
            assert_eq!(warnings, [(warning.clone(), 1)]);
            assert_eq!(layout.shaper.take_notes(), notes);
        }
        // A rewind takes them back with the layout after the mark, and the next use gives
        // them again.
        layout.rewind(&mark);
        assert!(layout.output.warnings.is_empty());
        layout.separator_height(Separator::Normal);
        let warnings: Vec<_> = layout.output.warnings.clone().into_iter().collect();
        assert_eq!(warnings, [(warning.clone(), 1)]);
        // Another section is another story input, so the separator is laid out again.
        layout.section.left += Length::from_units(1);
        assert_eq!(layout.separator_height(Separator::Normal), height);
    });
}

#[test]
fn a_listed_separator_keeps_the_space_after_its_last_paragraph_where_the_target_keeps_it() {
    let paragraph =
        r#"<w:p><w:pPr><w:spacing w:after="200"/></w:pPr><w:r><w:separator/></w:r></w:p>"#;
    let mut ends = Vec::new();
    let mut dot = Length::ZERO;
    for space in [SeparatorSpaceAfter::Dropped, SeparatorSpaceAfter::Kept] {
        for footnote_separators in [NoteSeparators::Own, NoteSeparators::Listed] {
            let settings = Settings {
                footnote_separators,
                ..Settings::default()
            };
            let quirks = crate::layout::testing::on_base_with(|p| p.with_variant(space)).1;
            with_notes_in(notes_of(paragraph), (&settings, quirks), |layout, kept| {
                let (_, end) = layout.separator(Separator::Normal, Length::ZERO);
                // The page's room for the separator is where its layout ends.
                assert_eq!(kept.separator_height(Separator::Normal), end);
                dot = layout.device.dots(1);
                ends.push(end);
            });
        }
    }
    // Only the listed separator of a target that keeps the space gives it room: 10 pt, which
    // the layout takes to the device's dots.
    let line = ends[0];
    assert_eq!(ends[..3], [line, line, line]);
    let after = Length::from_units(10 * Length::UNITS_PER_POINT);
    let off = (ends[3] - line - after).units().abs();
    assert!(off < dot.units(), "{:?}", ends[3] - line);
}

#[test]
fn draws_a_separator_rule_whose_strikeout_rounds_to_no_dot_one_dot_thick() {
    // The stand-in's strikeout is 1/20 em: at 10 pt 0.5 pt, about two dots, and at 1 pt
    // 0.05 pt, which rounds to no dot. The rule is then one dot thick, as every line of the
    // text layout whose thickness comes from a font is (`Device::line_thickness`).
    for (half_points, at_points) in [(2, 1), (20, 10)] {
        let paragraph = format!(
            r#"<w:p><w:r><w:rPr><w:sz w:val="{half_points}"/></w:rPr><w:separator/></w:r></w:p>"#
        );
        with_notes(notes_of(&paragraph), |layout, _| {
            let (items, _) = layout.separator(Separator::Normal, Length::ZERO);
            let heights: Vec<_> = items
                .iter()
                .filter_map(|item| match item {
                    Item::Rect(rect) => Some(rect.height),
                    _ => None,
                })
                .collect();
            let device = layout.device;
            let strikeout = Length::from_units(at_points * Length::UNITS_PER_POINT / 20);
            let rule = device.snap(strikeout).max(device.dots(1));
            assert_eq!(heights, [rule], "{half_points}");
            assert_eq!(device.snap(strikeout) == Length::ZERO, at_points == 1);
        });
    }
}

/// The count of the warnings of note marks that show 1 which a layout gives for a text box, or
/// a frame when `frame`, whose one paragraph holds the element `mark`: a layout of a footnote
/// when `in_footnote`, and of an endnote when `in_endnote`.
fn box_mark_warnings((in_footnote, in_endnote): (bool, bool), frame: bool, mark: &str) -> u32 {
    let xml =
        format!(r#"<w:footnote xmlns:w="{W}"><w:p><w:r><w:{mark}/></w:r></w:p></w:footnote>"#);
    let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
    let blocks = crate::body::read_story(&mut PartReader::new(&doc), doc.root().unwrap());
    let mut count = 0;
    with_layout(|layout, _| {
        layout.story = in_footnote.then(|| crate::layout::Story {
            kind: crate::layout::StoryKind::Footnote {
                id: crate::body::NoteId::of(1),
            },
            numbers: crate::layout::StoryNumbers::PAGE_ONE,
        });
        layout.endnote = in_endnote.then_some(crate::note_setup::NoteLabel::FIRST);
        let paragraphs = crate::body::all_paragraphs(&blocks);
        layout.warn_of_box_note_marks(paragraphs.iter().copied(), frame, "word/notes.xml");
        count = layout
            .output
            .warnings
            .iter()
            .filter(|(warning, _)| {
                matches!(
                    warning,
                    Warning::FeatureNotSupported {
                        feature: crate::Feature::NoteMarkInBox,
                        ..
                    }
                )
            })
            .map(|(_, count)| count)
            .sum();
    });
    count
}

#[test]
fn warns_of_a_note_mark_that_a_text_box_or_a_frame_of_its_note_shows_as_one() {
    // A text box of a footnote shows its footnote mark as 1, and so does a text box or a frame
    // of an endnote with its endnote mark.
    assert_eq!(box_mark_warnings((true, false), false, "footnoteRef"), 1);
    assert_eq!(box_mark_warnings((false, true), false, "endnoteRef"), 1);
    assert_eq!(box_mark_warnings((false, true), true, "endnoteRef"), 1);
    // A frame of a footnote takes the footnote's number, and a mark of the other kind, or a
    // box outside a note, gives no warning.
    assert_eq!(box_mark_warnings((true, false), true, "footnoteRef"), 0);
    assert_eq!(box_mark_warnings((true, false), false, "endnoteRef"), 0);
    assert_eq!(box_mark_warnings((false, false), false, "footnoteRef"), 0);
}