f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
//! The gap minimums of fractions: a part of a fraction whose ink comes closer to the bar than
//! the `MATH` table's gap minimum moves away from the bar, with all that it holds.

use std::collections::HashMap;
use std::ops::Range;

use f_office_units::Length;

use crate::body::GapMinimum;
use crate::grid::Device;
use crate::lines::Piece;
use crate::params;
use crate::text::{FaceIndex, Shaper};

/// The top and the bottom edge of the bar of a fraction of this size, above the fraction's own
/// baseline: its middle lies at the math axis and it is the fraction rule thickness thick, and
/// each edge lies on the nearest dot.
pub(in crate::layout) fn bar_edges(device: &Device, size: Length) -> (Length, Length) {
    let at = |(units, em): (i64, i64)| (size * units).div_round(em);
    let (axis, thickness) = (
        at(params::MATH_AXIS_HEIGHT),
        at(params::MATH_FRACTION_RULE_THICKNESS),
    );
    let half = thickness.div_toward_zero(2);
    (device.snap(axis + half), device.snap(axis - half))
}

/// A fraction whose parts are measured: the index of its bar among a paragraph's pieces, the
/// gap minimum that its parts keep from the bar, and the ranges of the pieces of its numerator
/// and of its denominator.
pub(in crate::layout) struct Stacked {
    pub(in crate::layout) bar: usize,
    pub(in crate::layout) minimum: GapMinimum,
    pub(in crate::layout) numerator: Range<usize>,
    pub(in crate::layout) denominator: Range<usize>,
}

/// Moves each part of the fraction `stacked` whose ink comes closer to the bar's edge than the
/// fraction's gap minimum away from the bar, until its ink keeps the gap, at the fraction's
/// size. The ink is that of the glyphs that the part draws, each at its drawn
/// baseline. The glyphs and the bars of the fractions inside the part move with it, to the
/// nearest dot.
pub(in crate::layout) fn keep(
    (shaper, device): (&mut Shaper, Device),
    pieces: &mut [Piece],
    stacked: &Stacked,
) {
    let Some(&Piece::Bar { face, .. }) = pieces.get(stacked.bar) else {
        return;
    };
    let Some(bar) = shaper.faces().get(face) else {
        return;
    };
    let base = device.shift_dots(bar.rise);
    let (top, bottom) = bar_edges(&device, bar.size);
    let (units, em) = match stacked.minimum {
        GapMinimum::Display => params::MATH_FRACTION_DISPLAY_GAP_MIN,
        GapMinimum::Line => params::MATH_FRACTION_GAP_MIN,
    };
    let minimum = (bar.size * units).div_round(em);
    let numerator = stacked.numerator.clone();
    if let Some((low, _)) = ink(
        shaper,
        &device,
        pieces.get(numerator.clone()).unwrap_or(&[]),
    ) {
        let short = minimum - (low - base - top);
        if short > Length::ZERO
            && let Some(part) = pieces.get_mut(numerator)
        {
            move_part((shaper, device), part, short);
        }
    }
    let denominator = stacked.denominator.clone();
    if let Some((_, high)) = ink(
        shaper,
        &device,
        pieces.get(denominator.clone()).unwrap_or(&[]),
    ) {
        let short = minimum - (base + bottom - high);
        if short > Length::ZERO
            && let Some(part) = pieces.get_mut(denominator)
        {
            move_part((shaper, device), part, -short);
        }
    }
}

/// The lowest and the highest point of the ink of the glyphs and the drawn bars over or under
/// an expression among `pieces` above the line's baseline, each at its drawn baseline; none
/// when nothing among them has ink.
pub(super) fn ink(shaper: &Shaper, device: &Device, pieces: &[Piece]) -> Option<(Length, Length)> {
    extent(shaper, device, pieces, Clear::Never)
}

/// The lowest and the highest point of the box of `pieces` above the line's baseline: their ink
/// ([`ink`]), with the white space above a bar that the box of its structure holds, as a
/// radical's does; none when nothing among them has ink.
pub(super) fn boxed(
    shaper: &Shaper,
    device: &Device,
    pieces: &[Piece],
) -> Option<(Length, Length)> {
    extent(shaper, device, pieces, Clear::Every)
}

/// The box of `pieces` as [`boxed`] measures it, where only the bars whose runs lie in a part
/// of a fraction when `in_fraction` is set, and outside one when it is not, hold the white
/// space above them: the box of the pieces on the line of a structure that `in_fraction` says.
pub(super) fn boxed_on_line(
    shaper: &Shaper,
    device: &Device,
    pieces: &[Piece],
    in_fraction: bool,
) -> Option<(Length, Length)> {
    extent(shaper, device, pieces, Clear::InFraction(in_fraction))
}

/// Which bars of an extent hold the white space above them that the box of their structure
/// holds: none, as the ink has it, every one, or those whose runs lie in a part of a fraction
/// or outside one, as the value says.
#[derive(Clone, Copy)]
enum Clear {
    Never,
    Every,
    InFraction(bool),
}

impl Clear {
    /// Whether a bar whose run has the face `face` holds the white space above it.
    fn holds(self, shaper: &Shaper, face: FaceIndex) -> bool {
        match self {
            Self::Never => false,
            Self::Every => true,
            Self::InFraction(inside) => shaper
                .faces()
                .get(face)
                .is_some_and(|f| f.math.in_fraction == inside),
        }
    }
}

/// The ink of `pieces`, with the white space above the bars that `clear` names.
fn extent(
    shaper: &Shaper,
    device: &Device,
    pieces: &[Piece],
    clear: Clear,
) -> Option<(Length, Length)> {
    pieces
        .iter()
        .filter_map(|piece| {
            let (face, (low, high)) = match piece {
                Piece::Glyph(glyph) => (glyph.face, shaper.ink(glyph)?),
                Piece::Vinculum {
                    face,
                    top,
                    thickness,
                    clear: above,
                    ..
                } if *thickness > Length::ZERO => {
                    let above = if clear.holds(shaper, *face) {
                        *above
                    } else {
                        Length::ZERO
                    };
                    (*face, (*top - *thickness, *top + above))
                }
                _ => return None,
            };
            let base = device.shift_dots(shaper.faces().get(face)?.rise);
            Some((base + low, base + high))
        })
        .reduce(|(low, high), (l, h)| (low.min(l), high.max(h)))
}

/// Raises `pieces` by `by`, or lowers them when it is negative, to the nearest dot: each glyph,
/// bar of a fraction or a radical and strut among them takes its face moved by as much.
pub(super) fn move_part((shaper, device): (&mut Shaper, Device), pieces: &mut [Piece], by: Length) {
    move_faces((shaper, device), pieces, by, Shaper::moved);
}

/// Raises `pieces` by `by`, or lowers them when it is negative, as [`move_part`] does, and moves
/// the room that their line needs with them ([`Shaper::lifted`]).
pub(super) fn lift_part((shaper, device): (&mut Shaper, Device), pieces: &mut [Piece], by: Length) {
    move_faces((shaper, device), pieces, by, Shaper::lifted);
}

/// As [`lift_part`], with `leading` as the room above the lifted ink.
pub(super) fn lift_part_with_leading(
    (shaper, device): (&mut Shaper, Device),
    pieces: &mut [Piece],
    by: Length,
    leading: Length,
) {
    let by = device.snap(by);
    if by == Length::ZERO {
        return;
    }
    let mut faces = HashMap::new();
    for piece in pieces {
        let face = match piece {
            Piece::Glyph(glyph) => &mut glyph.face,
            Piece::Bar { face, .. }
            | Piece::Vinculum { face, .. }
            | Piece::Diagonal { face, .. }
            | Piece::Strut(face) => face,
            _ => continue,
        };
        *face = *faces
            .entry(*face)
            .or_insert_with(|| shaper.lifted_with_leading(*face, by, leading));
    }
}

/// Gives each glyph, bar of a fraction or a radical and strut among `pieces` its face that
/// `mover` moves by `by`, to the nearest dot.
fn move_faces<'a>(
    (shaper, device): (&mut Shaper<'a>, Device),
    pieces: &mut [Piece],
    by: Length,
    mover: fn(&mut Shaper<'a>, FaceIndex, Length) -> FaceIndex,
) {
    let by = device.snap(by);
    if by == Length::ZERO {
        return;
    }
    let mut faces = HashMap::new();
    for piece in pieces {
        let face = match piece {
            Piece::Glyph(glyph) => &mut glyph.face,
            Piece::Bar { face, .. }
            | Piece::Vinculum { face, .. }
            | Piece::Diagonal { face, .. }
            | Piece::Strut(face) => face,
            _ => continue,
        };
        *face = *faces
            .entry(*face)
            .or_insert_with(|| mover(shaper, *face, by));
    }
}