f-office-docx 0.2.4

DOCX model and Word's layout rules.
Documentation
//! Border boxes of equations (`m:borderBox`): once a border box's content (`m:e`) is measured,
//! draws its visible border sides and horizontal, vertical, or diagonal strikes around the
//! content's ink using the math font's bar gap and rule thickness (`OverbarVerticalGap`,
//! `OverbarRuleThickness`, `UnderbarVerticalGap`, `UnderbarRuleThickness`, and `MathLeading`).

use f_office_units::Length;

use super::gap_minimums;
use super::structures::last_italic_correction;
use crate::body::{BarSide, BorderBoxFlags, MathBoxMark};
use crate::grid::{Device, LineRounding};
use crate::lines::{Piece, advance};
use crate::props::RunProps;
use crate::text::{BarLengths, FaceIndex, Shaper};

/// A border box whose end is still to come: its flags, control face, scaled top/bottom bar
/// lengths, leading, and the index of the left-padding shift before its content.
pub(in crate::layout) struct OpenBorderBox {
    flags: BorderBoxFlags,
    face: Option<FaceIndex>,
    top: Option<BarLengths>,
    bottom: Option<BarLengths>,
    leading: Length,
    before_base: usize,
}

/// Places a mark of a border box 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<OpenBorderBox>, &mut Vec<Piece>),
    mark: MathBoxMark,
    props: &RunProps,
) {
    match mark {
        MathBoxMark::BorderStart(flags) => {
            if props.hidden == Some(true) {
                return;
            }
            let face = shaper.face(props, true);
            let top = shaper.bar_lengths(props, BarSide::Top);
            let bottom = shaper.bar_lengths(props, BarSide::Bottom);
            let leading = shaper.equation_leading(props).unwrap_or(Length::ZERO);
            let before_base = pieces.len();
            pieces.push(Piece::Shift(Length::ZERO));
            open.push(OpenBorderBox {
                flags,
                face,
                top,
                bottom,
                leading,
                before_base,
            });
        }
        MathBoxMark::BorderEnd => {
            if props.hidden == Some(true) {
                return;
            }
            if let Some(box_open) = open.pop() {
                end(
                    (shaper, device),
                    pieces,
                    &box_open,
                    props.phantom == Some(true),
                );
            }
        }
    }
}

/// Draws the visible sides and strikes of `box_open` around its measured content and adds the
/// left and right border padding to the structure's advance.
fn end(
    (shaper, device): (&Shaper, Device),
    pieces: &mut Vec<Piece>,
    box_open: &OpenBorderBox,
    phantom: bool,
) {
    let (Some(face), Some(top_len), Some(bot_len)) = (box_open.face, box_open.top, box_open.bottom)
    else {
        return;
    };
    let base = pieces.get(box_open.before_base + 1..).unwrap_or(&[]);
    let base_adv: Length = base.iter().map(advance).sum();
    let base_ic = last_italic_correction(shaper, base);
    let base_w = base_adv + base_ic;
    let (low, high) = gap_minimums::ink(shaper, &device, base).unwrap_or_default();
    let rise = shaper
        .faces()
        .get(face)
        .map_or(Length::ZERO, |f| device.shift_dots(f.rise));
    let rule = device.line_thickness(top_len.rule, LineRounding::Nearest);
    let flags = box_open.flags;

    let pad = |present: bool| {
        if present {
            device.snap(top_len.gap) + rule
        } else {
            Length::ZERO
        }
    };
    let left_pad = pad(flags.has(BorderBoxFlags::LEFT));
    let right_pad = pad(flags.has(BorderBoxFlags::RIGHT));
    let width = left_pad + base_w + right_pad;

    let top = if flags.has(BorderBoxFlags::TOP) {
        device.snap(high - rise) + device.snap(top_len.gap) + rule
    } else {
        device.snap(high - rise)
    };
    let bottom = if flags.has(BorderBoxFlags::BOTTOM) {
        device.snap(low - rise) - device.snap(bot_len.gap) - rule
    } else {
        device.snap(low - rise)
    };
    let geom = BoxGeometry {
        face,
        width,
        bottom,
        top,
        rule,
        leading: box_open.leading,
    };
    let mut drawn = Vec::new();
    if !phantom {
        push_sides(&mut drawn, flags, geom);
        push_strikes(&mut drawn, &device, flags, geom);
    }

    if let Some(piece) = pieces.get_mut(box_open.before_base) {
        *piece = Piece::Shift(left_pad);
    }
    // Splice all box strokes right before the left-padding shift (at x = box start, zero advance).
    pieces.splice(box_open.before_base..box_open.before_base, drawn);
    pieces.push(Piece::Shift(base_ic + right_pad));
}

#[derive(Clone, Copy)]
struct BoxGeometry {
    face: FaceIndex,
    width: Length,
    bottom: Length,
    top: Length,
    rule: Length,
    leading: Length,
}

fn vinculum(
    face: FaceIndex,
    width: Length,
    top: Length,
    thickness: Length,
    above_room: Length,
) -> Piece {
    Piece::Vinculum {
        face,
        width,
        top,
        thickness,
        beyond: (above_room, Length::ZERO),
        clear: Length::ZERO,
    }
}

fn push_sides(drawn: &mut Vec<Piece>, flags: BorderBoxFlags, g: BoxGeometry) {
    let height = (g.top - g.bottom).max(g.rule);
    if flags.has(BorderBoxFlags::TOP) {
        drawn.push(vinculum(g.face, g.width, g.top, g.rule, g.leading));
    }
    if flags.has(BorderBoxFlags::BOTTOM) {
        drawn.push(vinculum(
            g.face,
            g.width,
            g.bottom + g.rule,
            g.rule,
            Length::ZERO,
        ));
    }
    if flags.has(BorderBoxFlags::LEFT) {
        drawn.push(vinculum(g.face, g.rule, g.top, height, Length::ZERO));
    }
    if flags.has(BorderBoxFlags::RIGHT) {
        let rx = (g.width - g.rule).max(Length::ZERO);
        drawn.push(Piece::Shift(rx));
        drawn.push(vinculum(g.face, g.rule, g.top, height, Length::ZERO));
        drawn.push(Piece::Shift(-rx));
    }
}

fn push_strikes(drawn: &mut Vec<Piece>, device: &Device, flags: BorderBoxFlags, g: BoxGeometry) {
    let height = (g.top - g.bottom).max(g.rule);
    if flags.has(BorderBoxFlags::STRIKE_H) {
        let mid_y = device.snap((g.top + g.bottom).div_toward_zero(2) + g.rule.div_toward_zero(2));
        drawn.push(vinculum(g.face, g.width, mid_y, g.rule, Length::ZERO));
    }
    if flags.has(BorderBoxFlags::STRIKE_V) {
        let vx = device.snap((g.width - g.rule).div_toward_zero(2));
        drawn.push(Piece::Shift(vx));
        drawn.push(vinculum(g.face, g.rule, g.top, height, Length::ZERO));
        drawn.push(Piece::Shift(-vx));
    }
    for (flag, rising) in [
        (BorderBoxFlags::STRIKE_BLTR, true),
        (BorderBoxFlags::STRIKE_TLBR, false),
    ] {
        if flags.has(flag) {
            drawn.push(Piece::Diagonal {
                face: g.face,
                width: g.width,
                bottom: g.bottom,
                top: g.top,
                thickness: g.rule,
                rising,
            });
        }
    }
}

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

    fn box_pieces(pr: &str) -> (usize, usize) {
        let xml = format!(
            r#"<w:hdr xmlns:w="{W}" xmlns:m="{M}"><w:p><m:oMath><m:borderBox>{pr}<m:e><m:r><m:t>x</m:t></m:r></m:e></m:borderBox></m:oMath></w:p></w:hdr>"#
        );
        super::super::tests::measured(&xml, &FakeScripts, Clone::clone, |_, pieces| {
            let vinc = pieces
                .iter()
                .filter(|p| matches!(p, Piece::Vinculum { .. }))
                .count();
            let diag = pieces
                .iter()
                .filter(|p| matches!(p, Piece::Diagonal { .. }))
                .count();
            (vinc, diag)
        })
    }

    #[test]
    fn border_box_draws_four_sides_by_default_and_respects_hide_and_strike_flags() {
        assert_eq!(box_pieces(""), (4, 0));
        let pr = r#"<m:borderBoxPr><m:hideTop m:val="1"/><m:hideBot m:val="1"/><m:hideLeft m:val="1"/><m:hideRight m:val="1"/><m:strikeH m:val="1"/><m:strikeBLTR m:val="1"/></m:borderBoxPr>"#;
        assert_eq!(box_pieces(pr), (1, 1));
    }
}