f-office-docx 0.3.0

DOCX model and Word's layout rules.
Documentation
//! The linear and skewed fractions of equations (`m:f` whose `m:type` is `lin` or `skw`):
//! once a fraction's numerator, fraction slash (`U+2044`) and denominator are measured, a
//! linear fraction centers the slash on the math axis after the numerator's italic correction,
//! and a skewed fraction lifts the numerator and drops the denominator by half of
//! `SkewedFractionVerticalGap` about the math axis, grows and places the slash proportionally
//! across their vertical span, and centers the slash horizontally in `SkewedFractionHorizontalGap`.

use f_office_units::Length;

use super::gap_minimums;
use super::structures::last_italic_correction;
use crate::body::{SlashKind, SlashMark};
use crate::grid::Device;
use crate::lines::Piece;
use crate::params;
use crate::props::RunProps;
use crate::text::Shaper;

/// A linear or skewed fraction whose end is still to come: its kind, the index of the first
/// piece of its numerator, the indices of the shifts before and after its slash and of its
/// slash glyph, and the `MathLeading` at the equation's size.
pub(in crate::layout) struct OpenSlash {
    kind: SlashKind,
    start: usize,
    shift_before: Option<usize>,
    slash: Option<usize>,
    shift_after: Option<usize>,
    leading: Length,
}

/// Places a mark of a linear or skewed fraction 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<OpenSlash>, &mut Vec<Piece>),
    mark: SlashMark,
    props: &RunProps,
) {
    match mark {
        SlashMark::Start(kind) => {
            let leading = shaper.equation_leading(props).unwrap_or(Length::ZERO);
            open.push(OpenSlash {
                kind,
                start: pieces.len(),
                shift_before: None,
                slash: None,
                shift_after: None,
                leading,
            });
        }
        SlashMark::Slash => {
            if let Some(fraction) = open.last_mut() {
                fraction.shift_before = Some(pieces.len());
                pieces.push(Piece::Shift(Length::ZERO));
                fraction.slash = Some(pieces.len());
            }
        }
        SlashMark::Denominator => {
            if let Some(fraction) = open.last_mut() {
                fraction.shift_after = Some(pieces.len());
                pieces.push(Piece::Shift(Length::ZERO));
            }
        }
        SlashMark::End => {
            if let Some(fraction) = open.pop() {
                end((shaper, device), pieces, &fraction);
            }
        }
    }
}

/// Finishes `fraction` once its numerator, slash and denominator are measured.
fn end((shaper, device): (&mut Shaper, Device), pieces: &mut [Piece], fraction: &OpenSlash) {
    let (Some(shift_before), Some(slash_at), Some(shift_after)) =
        (fraction.shift_before, fraction.slash, fraction.shift_after)
    else {
        return;
    };
    let num_range = fraction.start..shift_before;
    let den_range = (shift_after + 1)..pieces.len();
    let num_correction =
        last_italic_correction(shaper, pieces.get(num_range.clone()).unwrap_or(&[]));
    let Some(Piece::Glyph(slash)) = pieces.get(slash_at) else {
        return;
    };
    let slash_face = slash.face;
    let Some(face) = shaper.faces().get(slash_face).copied() else {
        return;
    };
    let (axis_num, axis_em) = params::MATH_AXIS_HEIGHT;
    let axis = device.shift_dots(face.rise) + (face.size * axis_num).div_round(axis_em);
    let skewed_gaps = match fraction.kind {
        SlashKind::Skewed => shaper.skewed_fraction_gaps(slash_face),
        SlashKind::Linear => None,
    };
    let (above, below) = if let Some((_, vgap)) = skewed_gaps {
        let half_vgap = vgap.div_toward_zero(2);
        if let Some((num_low, _)) = gap_minimums::ink(
            shaper,
            &device,
            pieces.get(num_range.clone()).unwrap_or(&[]),
        ) && let Some(part) = pieces.get_mut(num_range.clone())
        {
            gap_minimums::lift_part((shaper, device), part, (axis + half_vgap) - num_low);
        }
        if let Some((_, den_high)) = gap_minimums::ink(
            shaper,
            &device,
            pieces.get(den_range.clone()).unwrap_or(&[]),
        ) && let Some(part) = pieces.get_mut(den_range.clone())
        {
            gap_minimums::lift_part((shaper, device), part, (axis - half_vgap) - den_high);
        }
        let num_high = gap_minimums::ink(shaper, &device, pieces.get(num_range).unwrap_or(&[]))
            .map(|(_, h)| h);
        let den_low = gap_minimums::ink(shaper, &device, pieces.get(den_range).unwrap_or(&[]))
            .map(|(l, _)| l);
        (
            num_high.map_or(Length::ZERO, |h| (h - axis).max(Length::ZERO)),
            den_low.map_or(Length::ZERO, |l| (axis - l).max(Length::ZERO)),
        )
    } else {
        let num_ink = gap_minimums::ink(shaper, &device, pieces.get(num_range).unwrap_or(&[]));
        let den_ink = gap_minimums::ink(shaper, &device, pieces.get(den_range).unwrap_or(&[]));
        let combined = match (num_ink, den_ink) {
            (Some((l1, h1)), Some((l2, h2))) => Some((l1.min(l2), h1.max(h2))),
            (one, None) | (None, one) => one,
        };
        combined.map_or((Length::ZERO, Length::ZERO), |(low, high)| {
            (
                (high - axis).max(Length::ZERO),
                (axis - low).max(Length::ZERO),
            )
        })
    };
    let slash_adv = if let Some(Piece::Glyph(glyph)) = pieces.get_mut(slash_at) {
        shaper.place_fraction_slash(
            glyph,
            axis,
            (above, below),
            skewed_gaps.is_some(),
            fraction.leading,
        );
        glyph.advance
    } else {
        return;
    };
    let (before_shift, after_shift) = if let Some((hgap, _)) = skewed_gaps {
        let gap_diff = hgap - slash_adv;
        let left = gap_diff.div_toward_zero(2);
        (num_correction + left, gap_diff - left)
    } else {
        (num_correction, Length::ZERO)
    };
    if let Some(piece) = pieces.get_mut(shift_before) {
        *piece = Piece::Shift(before_shift);
    }
    if let Some(piece) = pieces.get_mut(shift_after) {
        *piece = Piece::Shift(after_shift);
    }
}

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

    fn fraction_glyphs(kind: &str) -> Vec<(char, u32, i64, MathRoom)> {
        let xml = format!(
            r#"<w:hdr xmlns:w="{W}" xmlns:m="{M}"><w:p><m:oMath><m:f><m:fPr><m:type m:val="{kind}"/></m:fPr><m:num><m:r><m:t>a</m:t></m:r></m:num><m:den><m:r><m:t>b</m:t></m:r></m:den></m:f></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, glyph.id, face.rise.units(), face.math.room))
                    }
                    _ => None,
                })
                .collect()
        })
    }

    #[test]
    fn linear_fraction_centers_slash_on_axis_and_keeps_parts_on_baseline() {
        let glyphs = fraction_glyphs("lin");
        assert_eq!(glyphs.len(), 3, "{glyphs:?}");
        assert_eq!(glyphs[0].2, 0);
        assert_eq!(glyphs[2].2, 0);
        assert_eq!(glyphs[1].0, '\u{2044}');
        assert_eq!(glyphs[1].1, 0x2044);
        assert!(
            glyphs[1].2 > 0,
            "base slash centers up onto axis: {glyphs:?}"
        );
        assert_eq!(glyphs[1].3, MathRoom::Lines);
    }

    #[test]
    fn skewed_fraction_lifts_numerator_drops_denominator_and_grows_slash() {
        let glyphs = fraction_glyphs("skw");
        let rises: Vec<i64> = glyphs.iter().map(|g| g.2).collect();
        assert_eq!(glyphs.len(), 3, "{glyphs:?}");
        assert!(rises[0] > 0 && rises[2] < 0, "{glyphs:?}");
        assert_eq!((glyphs[1].0, glyphs[1].1), ('\u{2044}', 8000));
        assert!(
            glyphs.iter().all(|g| matches!(g.3, MathRoom::Ink { .. })),
            "{glyphs:?}"
        );
    }
}