f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
//! The grouping characters of equations (`m:groupChr`): once the base (`m:e`) is measured, the
//! grouping character stretches across the base's width via the math font's horizontal variants or
//! glyph assembly, both center over the wider of the two, and either the character shifts below
//! or above the base's ink (`pos != vertJc`) or the character stays on the baseline and the base
//! shifts above or below it (`pos == vertJc`).

use f_office_units::Length;

use super::gap_minimums;
use super::structures::last_italic_correction;
use crate::body::{BarSide, GroupChrMark, GroupChrPlacement};
use crate::grid::Device;
use crate::lines::{Piece, advance};
use crate::props::RunProps;
use crate::text::{Shaper, StretchStackLengths};

/// A grouping character structure whose end is still to come: its placement, its scaled
/// stretch-stack lengths, the index of the centering shift before its base, and the index of the
/// shift before its character's template glyph.
pub(in crate::layout) struct OpenGroupChr {
    placement: GroupChrPlacement,
    lengths: Option<StretchStackLengths>,
    before_base: usize,
    character: Option<usize>,
}

/// Places a mark of a grouping character structure in a paragraph's `pieces`, with the properties
/// `props` of its run.
pub(in crate::layout) fn mark(
    (shaper, device): (&mut Shaper, Device),
    (open, pieces): (&mut Vec<OpenGroupChr>, &mut Vec<Piece>),
    mark: GroupChrMark,
    props: &RunProps,
) {
    match mark {
        GroupChrMark::Start(placement) => {
            let lengths = shaper.stretch_stack_lengths(props);
            let before_base = pieces.len();
            pieces.push(Piece::Shift(Length::ZERO));
            open.push(OpenGroupChr {
                placement,
                lengths,
                before_base,
                character: None,
            });
        }
        GroupChrMark::Character => {
            if let Some(group) = open.last_mut() {
                group.character = Some(pieces.len());
                pieces.push(Piece::Shift(Length::ZERO));
            }
        }
        GroupChrMark::End { .. } => {
            if let Some(group) = open.pop() {
                end((shaper, device), pieces, &group);
            }
        }
    }
}

/// Stretches and places `group` once its base and template character glyph are measured.
fn end((shaper, device): (&mut Shaper, Device), pieces: &mut Vec<Piece>, group: &OpenGroupChr) {
    let (Some(lengths), Some(at)) = (group.lengths, group.character) else {
        return;
    };
    let Some(&Piece::Glyph(glyph)) = pieces.get(at + 1) else {
        return;
    };
    let base_range = (group.before_base + 1)..at;
    let base_span = pieces.get(base_range.clone()).unwrap_or(&[]);
    let base_adv: Length = base_span.iter().map(advance).sum();
    let base_ic = last_italic_correction(shaper, base_span);
    let base_width = base_adv + base_ic;
    let base_ink = gap_minimums::ink(shaper, &device, base_span);

    let Some((drawn, chr_width)) = shaper.stretched_glyph(
        &glyph,
        base_width,
        lengths.min_connector_overlap,
        lengths.leading,
    ) else {
        return;
    };

    let mut chr_pieces = Vec::with_capacity(2 * drawn.len());
    let mut pen = Length::ZERO;
    for (part_glyph, place) in drawn {
        chr_pieces.push(Piece::Shift(place - pen));
        pen = place + part_glyph.advance;
        chr_pieces.push(Piece::Glyph(part_glyph));
    }
    let chr_ink = gap_minimums::ink(shaper, &device, &chr_pieces);

    if let (Some((base_low, base_high)), Some((chr_low, chr_high))) = (base_ink, chr_ink) {
        let p = group.placement;
        if p.position == p.vertical_align {
            let by = match p.position {
                BarSide::Bottom => lengths
                    .top_shift_up
                    .max((chr_high + lengths.gap_above_min) - base_low),
                BarSide::Top => -lengths
                    .bottom_shift_down
                    .max((base_high + lengths.gap_below_min) - chr_low),
            };
            if let Some(base_mut) = pieces.get_mut(base_range) {
                gap_minimums::lift_part_with_leading(
                    (shaper, device),
                    base_mut,
                    by,
                    lengths.leading,
                );
            }
        } else {
            let by = match p.position {
                BarSide::Bottom => {
                    -((chr_high - base_low) + lengths.gap_above_min).max(Length::ZERO)
                }
                BarSide::Top => ((base_high - chr_low) + lengths.gap_below_min).max(Length::ZERO),
            };
            gap_minimums::lift_part_with_leading(
                (shaper, device),
                &mut chr_pieces,
                by,
                lengths.leading,
            );
        }
    }

    let wide = base_width.max(chr_width);
    let base_x = (wide - base_width).div_toward_zero(2);
    let chr_x = (wide - chr_width).div_toward_zero(2);

    if let Some(piece) = pieces.get_mut(group.before_base) {
        *piece = Piece::Shift(base_x);
    }
    pieces.truncate(at);
    pieces.push(Piece::Shift(chr_x - base_x - base_adv));
    pieces.extend(chr_pieces);
    pieces.push(Piece::Shift(wide - chr_x - pen));
}

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

    fn group_glyphs(pr: &str) -> Vec<(char, i64, MathRoom)> {
        let xml = format!(
            r#"<w:hdr xmlns:w="{W}" xmlns:m="{M}"><w:p><m:oMath><m:groupChr>{pr}<m:e><m:r><m:t>x</m:t></m:r></m:e></m:groupChr></m:oMath></w:p></w:hdr>"#
        );
        super::super::tests::measured(&xml, &FakeMath, Clone::clone, |layout, pieces| {
            pieces
                .iter()
                .filter_map(|piece| match piece {
                    Piece::Glyph(glyph) => {
                        let face = layout.shaper.faces().get(glyph.face)?;
                        Some((glyph.ch, face.rise.units(), face.math.room))
                    }
                    _ => None,
                })
                .collect()
        })
    }

    #[test]
    fn default_group_chr_places_underbrace_below_base() {
        let glyphs = group_glyphs("");
        assert_eq!(glyphs.len(), 2, "{glyphs:?}");
        assert_eq!(glyphs[0].1, 0);
        assert_eq!(glyphs[1].0, '\u{23DF}');
        assert!(glyphs[1].1 < 0, "underbrace drops below base: {glyphs:?}");
        assert!(matches!(glyphs[1].2, MathRoom::Ink { .. }));
    }

    #[test]
    fn matching_pos_and_vert_jc_keeps_character_on_baseline_and_shifts_base() {
        let up = group_glyphs(
            r#"<m:groupChrPr><m:chr m:val="→"/><m:pos m:val="bot"/><m:vertJc m:val="bot"/></m:groupChrPr>"#,
        );
        assert_eq!(up.len(), 2, "{up:?}");
        assert!(up[0].1 > 0, "base rises above arrow: {up:?}");
        assert_eq!(up[1].1, 0);

        let down = group_glyphs(
            r#"<m:groupChrPr><m:chr m:val="→"/><m:pos m:val="top"/><m:vertJc m:val="top"/></m:groupChrPr>"#,
        );
        assert_eq!(down.len(), 2, "{down:?}");
        assert!(down[0].1 < 0, "base drops below arrow: {down:?}");
        assert_eq!(down[1].1, 0);
    }
}