f-office-docx 0.2.4

DOCX model and Word's layout rules.
Documentation
//! The lower- and upper-limit structures of equations (`m:limLow` and `m:limUpp`): once a
//! structure's base (`m:e`) and limit (`m:lim`) are measured, the limit shifts vertically below
//! or above the base's ink and both center horizontally over the wider of the two, with the
//! limit shifted horizontally by half the base's italic correction (left when lower, right when
//! upper).

use f_office_units::Length;

use super::gap_minimums;
use super::structures::last_italic_correction;
use crate::body::{LimitMark, LimitSide};
use crate::grid::Device;
use crate::lines::{Piece, advance};
use crate::props::RunProps;
use crate::text::Shaper;

/// A lower- or upper-limit structure whose end is still to come: the side of its limit, the
/// scaled `(baseline_min, gap_min, base_rise)` of its control face, and the indices of the
/// shifts before its base and before its limit.
pub(in crate::layout) struct OpenLimit {
    side: LimitSide,
    lengths: Option<(Length, Length, Length)>,
    leading: Length,
    before_base: usize,
    before_limit: Option<usize>,
}

/// Places a mark of a lower- or upper-limit 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<OpenLimit>, &mut Vec<Piece>),
    mark: LimitMark,
    props: &RunProps,
) {
    match mark {
        LimitMark::Start(side) => {
            let lengths = shaper.limit_lengths(props, side == LimitSide::Lower);
            let leading = shaper.equation_leading(props).unwrap_or(Length::ZERO);
            let before_base = pieces.len();
            pieces.push(Piece::Shift(Length::ZERO));
            open.push(OpenLimit {
                side,
                lengths,
                leading,
                before_base,
                before_limit: None,
            });
        }
        LimitMark::Limit => {
            if let Some(limit) = open.last_mut() {
                limit.before_limit = Some(pieces.len());
                pieces.push(Piece::Shift(Length::ZERO));
            }
        }
        LimitMark::End { .. } => {
            if let Some(limit) = open.pop() {
                end((shaper, device), pieces, &limit);
            }
        }
    }
}

/// Finishes `limit` once its base and limit are measured: shifts the limit vertically below or
/// above the base's ink, centers base and limit horizontally, and advances to the right edge of
/// the wider part.
fn end((shaper, device): (&mut Shaper, Device), pieces: &mut Vec<Piece>, limit: &OpenLimit) {
    let Some(before_limit) = limit.before_limit else {
        return;
    };
    let end = pieces.len();
    let base_range = (limit.before_base + 1)..before_limit;
    let lim_range = (before_limit + 1)..end;

    if let Some((baseline_min, gap_min, rise)) = limit.lengths {
        shift_limit(
            (shaper, device),
            pieces,
            (base_range.clone(), lim_range.clone()),
            (limit.side, baseline_min, gap_min, rise, limit.leading),
        );
    }

    let base_span = pieces.get(base_range).unwrap_or(&[]);
    let lim_span = pieces.get(lim_range).unwrap_or(&[]);
    let base_adv: Length = base_span.iter().map(advance).sum();
    let lim_adv: Length = lim_span.iter().map(advance).sum();
    let base_ic = last_italic_correction(shaper, base_span);
    let lim_ic = last_italic_correction(shaper, lim_span);
    let base_w = base_adv + base_ic;
    let lim_w = lim_adv + lim_ic;
    let wide = base_w.max(lim_w);

    let slant = match limit.side {
        LimitSide::Upper => base_ic.div_toward_zero(2),
        LimitSide::Lower => -base_ic.div_toward_zero(2),
    };
    let mut base_x = (wide - base_w).div_toward_zero(2);
    let mut lim_x = base_x + (base_adv - lim_adv).div_toward_zero(2) + slant;
    if lim_x < Length::ZERO {
        base_x -= lim_x;
        lim_x = Length::ZERO;
    }
    let total_end = (base_x + base_w).max(lim_x + lim_w);

    if let Some(piece) = pieces.get_mut(limit.before_base) {
        *piece = Piece::Shift(base_x);
    }
    if let Some(piece) = pieces.get_mut(before_limit) {
        *piece = Piece::Shift(lim_x - base_x - base_adv);
    }
    pieces.push(Piece::Shift(total_end - lim_x - lim_adv));
}

/// Shifts the limit pieces vertically below or above the base's ink and sets their line room to
/// their drawn ink plus `MathLeading`.
fn shift_limit(
    (shaper, device): (&mut Shaper, Device),
    pieces: &mut [Piece],
    (base_range, lim_range): (std::ops::Range<usize>, std::ops::Range<usize>),
    (side, baseline_min, gap_min, rise, leading): (LimitSide, Length, Length, Length, Length),
) {
    let base_ink = gap_minimums::ink(shaper, &device, pieces.get(base_range).unwrap_or(&[]));
    let lim_ink = gap_minimums::ink(
        shaper,
        &device,
        pieces.get(lim_range.clone()).unwrap_or(&[]),
    );
    let (Some((base_low, base_high)), Some((lim_low, lim_high))) = (base_ink, lim_ink) else {
        return;
    };
    let base_rise = device.shift_dots(rise);
    let by = match side {
        LimitSide::Lower => {
            let drop = baseline_min.max((lim_high - base_rise) + gap_min);
            (base_low - drop) - base_rise
        }
        LimitSide::Upper => (base_high + baseline_min) - lim_low,
    };
    if let Some(part) = pieces.get_mut(lim_range) {
        gap_minimums::lift_part_with_leading((shaper, device), part, by, leading);
    }
}

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

    fn limit_glyphs(tag: &str) -> Vec<(char, i64, MathRoom)> {
        let xml = format!(
            r#"<w:hdr xmlns:w="{W}" xmlns:m="{M}"><w:p><m:oMath><m:{tag}><m:e><m:r><m:t>x</m:t></m:r></m:e><m:lim><m:r><m:t>i</m:t></m:r></m:lim></m:{tag}></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 lower_limit_drops_limit_below_base_and_takes_ink_room() {
        let glyphs = limit_glyphs("limLow");
        assert_eq!(glyphs.len(), 2, "{glyphs:?}");
        assert_eq!(glyphs[0].1, 0);
        assert!(glyphs[1].1 < 0, "lower limit drops below base: {glyphs:?}");
        assert!(matches!(glyphs[1].2, MathRoom::Ink { .. }));
    }

    #[test]
    fn upper_limit_raises_limit_above_base_and_takes_ink_room() {
        let glyphs = limit_glyphs("limUpp");
        assert_eq!(glyphs.len(), 2, "{glyphs:?}");
        assert_eq!(glyphs[0].1, 0);
        assert!(glyphs[1].1 > 0, "upper limit rises above base: {glyphs:?}");
        assert!(matches!(glyphs[1].2, MathRoom::Ink { .. }));
    }
}