f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
//! The delimiters of equations (`m:d`) that grow around content that is not line high: on a
//! target whose quirk variant is `GrownDelimiters::Variant`, once a delimiter's content is
//! measured, each of its characters draws the vertical variant of its glyph that reaches the
//! need of the content's ink about the math axis, and the thin spaces beside it keep their width
//! only when that content counts as a subformula.

use f_office_units::Length;

use super::gap_minimums;
use crate::body::GrownMark;
use crate::grid::Device;
use crate::lines::Piece;
use crate::params;
use crate::props::RunProps;
use crate::text::Shaper;

/// The grown delimiters of a paragraph so far: those whose end is still to come, the index of
/// the thin space before the next one's start, and whether the content of the last one that
/// ended counts as a subformula.
#[derive(Default)]
pub(in crate::layout) struct Grown {
    open: Vec<OpenGrown>,
    space: Option<usize>,
    sub_formula: bool,
}

/// A grown delimiter whose end is still to come: the index of its first piece among a
/// paragraph's pieces, its characters so far, the index of the thin space before it, the index
/// of the first piece of the nested delimiter that has started and not ended, and the ink of each
/// nested delimiter so far, from its lowest to its highest point.
struct OpenGrown {
    start: usize,
    characters: Vec<Character>,
    space: Option<usize>,
    nested_from: Option<usize>,
    nested: Vec<(Length, Length)>,
}

/// A character of a grown delimiter: the index of its glyph among a paragraph's pieces, the
/// character, and the `MathLeading` of its math font at the size of its equation.
struct Character {
    at: usize,
    ch: char,
    leading: Length,
}

/// Places a mark of a grown delimiter in a paragraph's `pieces`, with the properties `props`
/// of its run. At the delimiter's end, each of its characters draws its grown glyph
/// ([`Shaper::grow`]) for the ink of the delimiter's other pieces, its content, and the thin
/// spaces before and after it lose their width unless that content counts as a subformula.
pub(in crate::layout) fn mark(
    (shaper, device): (&mut Shaper, Device),
    (grown, pieces): (&mut Grown, &mut [Piece]),
    mark: GrownMark,
    props: &RunProps,
) {
    match mark {
        GrownMark::SpaceBefore => grown.space = pieces.len().checked_sub(1),
        GrownMark::Start => grown.open.push(OpenGrown {
            start: pieces.len(),
            characters: Vec::new(),
            space: grown.space.take(),
            nested_from: None,
            nested: Vec::new(),
        }),
        GrownMark::NestedStart | GrownMark::NestedEnd => {
            if let Some(open) = grown.open.last_mut() {
                nest((shaper, device), (open, pieces), mark);
            }
        }
        GrownMark::Character(ch) => {
            let leading = shaper.equation_leading(props);
            if let (Some(grown), Some(leading)) = (grown.open.last_mut(), leading) {
                grown.characters.push(Character {
                    at: pieces.len(),
                    ch,
                    leading,
                });
            }
        }
        GrownMark::End => {
            if let Some(open) = grown.open.pop() {
                grown.sub_formula = grow((shaper, device), pieces, &open);
                if !grown.sub_formula {
                    hide(pieces, open.space);
                }
            }
        }
        GrownMark::SpaceAfter => {
            if !grown.sub_formula {
                let last = pieces.len().checked_sub(1);
                hide(pieces, last);
            }
        }
    }
}

/// Places the start or the end (`mark`) of a delimiter nested in the grown delimiter `open`: at
/// its end, the nested delimiter's pieces since its start, its glyphs as drawn, give their box
/// on the line of `open`'s first character ([`gap_minimums::boxed_on_line`]).
fn nest(
    (shaper, device): (&Shaper, Device),
    (open, pieces): (&mut OpenGrown, &[Piece]),
    mark: GrownMark,
) {
    if mark == GrownMark::NestedStart {
        open.nested_from = Some(pieces.len());
        return;
    }
    let in_fraction = open
        .characters
        .first()
        .and_then(|c| match pieces.get(c.at) {
            Some(Piece::Glyph(glyph)) => shaper.faces().get(glyph.face),
            _ => None,
        })
        .is_some_and(|face| face.math.in_fraction);
    let nested = pieces.get(open.nested_from.take().unwrap_or(pieces.len())..);
    if let Some(extent) =
        gap_minimums::boxed_on_line(shaper, &device, nested.unwrap_or(&[]), in_fraction)
    {
        open.nested.push(extent);
    }
}

/// Takes the width from the thin space at `at` among `pieces`, which then draws nothing.
pub(in crate::layout) fn hide(pieces: &mut [Piece], at: Option<usize>) {
    if let Some(Piece::Glyph(glyph)) = at.and_then(|at| pieces.get_mut(at)) {
        glyph.advance = Length::ZERO;
    }
}

/// Draws the grown glyph of each character of the delimiter `grown`, whose pieces end at the
/// end of `pieces`. The need of each character is twice the larger of the content's ink above
/// and below the math axis at the character's size and drawn baseline, the content being the
/// delimiter's pieces other than its characters, each glyph at its drawn baseline; the largest
/// such need of a delimiter nested in it, by its box, goes with it ([`Shaper::grow`]). A
/// delimiter whose content has no ink keeps its glyphs. Returns whether the content counts as a
/// subformula for a character of the delimiter.
fn grow((shaper, device): (&mut Shaper, Device), pieces: &mut [Piece], grown: &OpenGrown) -> bool {
    // A character whose glyph is not the next piece, such as one in a hidden run, is none.
    let characters: Vec<&Character> = grown
        .characters
        .iter()
        .filter(|c| matches!(pieces.get(c.at), Some(Piece::Glyph(g)) if g.ch == c.ch))
        .collect();
    let mut ink: Option<(Length, Length)> = None;
    let mut from = grown.start;
    let ends = characters.iter().map(|c| c.at).chain([pieces.len()]);
    for end in ends {
        let part = gap_minimums::ink(shaper, &device, pieces.get(from..end).unwrap_or(&[]));
        ink = match (ink, part) {
            (Some((low, high)), Some((l, h))) => Some((low.min(l), high.max(h))),
            (found, None) | (None, found) => found,
        };
        from = end + 1;
    }
    let Some((low, high)) = ink else {
        return false;
    };
    let (axis, axis_em) = params::MATH_AXIS_HEIGHT;
    let mut sub_formula = false;
    for character in characters {
        let Some(Piece::Glyph(glyph)) = pieces.get_mut(character.at) else {
            continue;
        };
        let Some(face) = shaper.faces().get(glyph.face) else {
            continue;
        };
        let axis = device.shift_dots(face.rise) + (face.size * axis).div_round(axis_em);
        let need = (high - axis).max(axis - low) * 2;
        let nested = grown
            .nested
            .iter()
            .map(|&(low, high)| (high - axis).max(axis - low) * 2)
            .fold(Length::ZERO, Length::max);
        sub_formula |= shaper.grow(glyph, (need, nested), character.leading);
    }
    sub_formula
}

#[cfg(test)]
mod tests {
    use crate::layout::testing::FakeMath;
    use crate::lines::Piece;
    use crate::ns::{M, W};
    use crate::quirks::GrownDelimiters;
    use crate::text::MathRoom;

    /// The glyph ID, the rise and the room of each parenthesis of the equation `math`, alone in
    /// a paragraph, on the base target with the quirk variant `grown`.
    fn parentheses(math: &str, grown: GrownDelimiters) -> Vec<(u32, i64, MathRoom)> {
        let xml = format!(
            r#"<w:hdr xmlns:w="{W}" xmlns:m="{M}"><w:p><m:oMath>{math}</m:oMath></w:p></w:hdr>"#
        );
        super::super::tests::measured(
            &xml,
            &FakeMath,
            |p| p.with_variant(grown),
            |layout, pieces| {
                pieces
                    .iter()
                    .filter_map(|piece| match piece {
                        Piece::Glyph(glyph) if matches!(glyph.ch, '(' | ')') => {
                            let face = layout.shaper.faces().get(glyph.face)?;
                            Some((glyph.id, face.rise.units(), face.math.room))
                        }
                        _ => None,
                    })
                    .collect()
            },
        )
    }

    /// Parentheses around x over y.
    const AROUND_A_FRACTION: &str = "<m:d><m:e><m:f><m:num><m:r><m:t>x</m:t></m:r></m:num><m:den><m:r><m:t>y</m:t></m:r></m:den></m:f></m:e></m:d>";

    #[test]
    fn grows_the_parentheses_around_a_fraction_on_a_target_that_grows_them() {
        // The base glyphs stay on the content's baseline in the room of their lines.
        let base = parentheses(AROUND_A_FRACTION, GrownDelimiters::BaseGlyph);
        assert_eq!(
            base,
            [(0x28, 0, MathRoom::Lines), (0x29, 0, MathRoom::Lines)]
        );
        // Grown, both draw one variant taller than the base glyph, stand at one height, and
        // take the room of their ink.
        let grown = parentheses(AROUND_A_FRACTION, GrownDelimiters::Variant);
        let ids: Vec<u32> = grown.iter().map(|p| p.0).collect();
        assert!(ids == [8000, 8000] || ids == [8001, 8001], "{grown:?}");
        assert_eq!(grown[0].1, grown[1].1);
        assert!(grown.iter().all(|p| matches!(p.2, MathRoom::Ink { .. })));
    }

    #[test]
    fn keeps_the_base_glyphs_around_line_high_content() {
        // Around line-high content the delimiter is no grown one, and keeps its base glyphs.
        let letter = "<m:d><m:e><m:r><m:t>x</m:t></m:r></m:e></m:d>";
        let plain = parentheses(letter, GrownDelimiters::Variant);
        assert_eq!(plain, parentheses(letter, GrownDelimiters::BaseGlyph));
        assert_eq!(plain.iter().map(|p| p.0).collect::<Vec<_>>(), [0x28, 0x29]);
    }

    #[test]
    fn grows_parentheses_around_parentheses_of_line_high_content() {
        // The inner parentheses keep their base glyphs around the letter, and the outer ones,
        // which count the inner ones with more than their ink, draw a variant.
        let nested = "<m:d><m:e><m:d><m:e><m:r><m:t>x</m:t></m:r></m:e></m:d></m:e></m:d>";
        let ids: Vec<u32> = parentheses(nested, GrownDelimiters::Variant)
            .iter()
            .map(|p| p.0)
            .collect();
        assert_eq!(ids.get(1..3), Some(&[0x28, 0x29][..]), "{ids:?}");
        assert!(matches!(ids.first(), Some(8000 | 8001)), "{ids:?}");
        assert_eq!(ids.first(), ids.last());
    }
}