f-office-docx 0.2.1

DOCX model and Word's layout rules.
Documentation
//! The accent of an accent structure (`m:acc`): the glyph that its character draws over a
//! measured base, from the wider variants, the glyph assembly and the flattened forms of the
//! `MATH` table and the `flac` feature of its math font, and where that glyph stands.

use f_office_fonts::AssemblyPart;
use f_office_units::Length;

use super::{Glyph, MathRoom, Shaper, SpaceKind};
use crate::params;
use crate::props::RunProps;

/// The lengths of an accent at the size of the run of its character, from the `MATH` table of
/// its math font.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AccentLengths {
    /// The height of the base's ink above which the accent rises with it
    /// (`AccentBaseHeight`).
    pub base_height: Length,
    /// The height of the base's ink above which the accent takes its flattened form
    /// (`FlattenedAccentBaseHeight`).
    pub flattened_height: Length,
    /// The room of the line above the accent's ink: the `MathLeading` at the size of the
    /// equation.
    pub room_above: Length,
}

/// The lengths of a grouping character (`m:groupChr`) at the size of its control properties, from
/// the `MATH` table of its math font.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct StretchStackLengths {
    /// Minimum upward shift of the base above a bottom-aligned grouping character
    /// (`StretchStackTopShiftUp`).
    pub top_shift_up: Length,
    /// Minimum downward shift of the base below a top-aligned grouping character
    /// (`StretchStackBottomShiftDown`).
    pub bottom_shift_down: Length,
    /// Minimum gap above a grouping character (`StretchStackGapAboveMin`).
    pub gap_above_min: Length,
    /// Minimum gap below a grouping character (`StretchStackGapBelowMin`).
    pub gap_below_min: Length,
    /// Least overlap of two parts of a glyph assembly (`MinConnectorOverlap`), in font units.
    pub min_connector_overlap: i32,
    /// Room of the line beyond the structure's ink (`MathLeading`).
    pub leading: Length,
}

/// The base of an accent as measured: its width, where its accent is centered from its start,
/// and the top of its ink above the line's baseline, if it has ink.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AccentBase {
    /// The base's advance.
    pub width: Length,
    /// The base's top accent attachment from its start.
    pub attachment: Length,
    /// The top of the base's ink above the line's baseline.
    pub top: Option<Length>,
}

/// An accent as drawn: each of its glyphs with its origin's distance from the base's start.
/// An accent of one glyph has one; a glyph assembly has its parts, from the left.
pub type DrawnAccent = Vec<(Glyph, Length)>;

impl Shaper<'_> {
    /// The lengths of an accent whose character has the properties `props`, at its size; none
    /// for a font without the accent's constants of a `MATH` table.
    pub fn accent_lengths(&mut self, props: &RunProps) -> Option<AccentLengths> {
        let face = self.face(props, true)?;
        let f = self.faces().get(face).copied()?;
        let accent = self.fonts.math_accent(f.font)?;
        let em = i64::from(f.metrics.units_per_em.max(1));
        Some(AccentLengths {
            base_height: f.scale(i64::from(accent.accent_base_height)),
            flattened_height: f.scale(i64::from(accent.flattened_accent_base_height)),
            room_above: self.math_leading(props, f.font, em)?,
        })
    }

    /// The lengths of a grouping character whose properties are `props`, at its size; none for a
    /// font without the stretch-stack constants of a `MATH` table.
    pub fn stretch_stack_lengths(&mut self, props: &RunProps) -> Option<StretchStackLengths> {
        let face = self.face(props, true)?;
        let f = self.faces().get(face).copied()?;
        let stack = self.fonts.math_stretch_stack(f.font)?;
        let em = i64::from(f.metrics.units_per_em.max(1));
        Some(StretchStackLengths {
            top_shift_up: f.scale(i64::from(stack.top_shift_up)),
            bottom_shift_down: f.scale(i64::from(stack.bottom_shift_down)),
            gap_above_min: f.scale(i64::from(stack.gap_above_min)),
            gap_below_min: f.scale(i64::from(stack.gap_below_min)),
            min_connector_overlap: stack.min_connector_overlap,
            leading: self.math_leading(props, f.font, em)?,
        })
    }

    /// Stretches `glyph`, a grouping character (`m:groupChr`), across `target_width` using the
    /// font's horizontal variants or glyph assembly (starting at 0 extender repeats when the
    /// non-extender parts already reach `target_width`), giving each drawn glyph ink-based line
    /// room with `leading`. Returns the parts with their horizontal offsets and total advance.
    pub fn stretched_glyph(
        &mut self,
        glyph: &Glyph,
        target_width: Length,
        overlap: i32,
        leading: Length,
    ) -> Option<(DrawnAccent, Length)> {
        let f = self.faces().get(glyph.face).copied()?;
        let em = i64::from(f.metrics.units_per_em.max(1));
        let size = f.size.units().max(1);
        let target_units = i32::try_from((target_width.units() * em).div_euclid(size)).ok()?;
        let construction = self.fonts.horizontal_construction(f.font, glyph.id);
        let own = self.fonts.advance(f.font, glyph.id).unwrap_or(0);
        let (variants, assembly) = construction.map_or_else(
            || (vec![(glyph.id, i32::from(own))], Vec::new()),
            |c| (c.variants, c.assembly),
        );
        let mut drawn = f;
        drawn.math.room = MathRoom::Ink { leading };
        let widest = variants.last().map_or(0, |&(_, measure)| measure);
        if target_units > widest && !assembly.is_empty() {
            let min_repeat = usize::from(!assembly.iter().any(|p| !p.extender));
            let parts = assembled_from(&assembly, target_units, overlap, min_repeat);
            let mut out = Vec::with_capacity(parts.len());
            let mut total = Length::ZERO;
            for (index, (part, at)) in parts.into_iter().enumerate() {
                let mut drawn_part = *glyph;
                if index > 0 {
                    drawn_part.ch = ' ';
                    drawn_part.space = SpaceKind::Assembly;
                }
                self.draw_variant(&mut drawn_part, (f, drawn), part);
                let place = (f.size * at).div_round(em);
                total = total.max(place + drawn_part.advance);
                out.push((drawn_part, place));
            }
            return Some((out, total));
        }
        let pick = variants
            .iter()
            .rev()
            .find(|&&(_, measure)| measure <= target_units)
            .or(variants.first())
            .map_or(glyph.id, |&(variant, _)| variant);
        let mut single = *glyph;
        self.draw_variant(&mut single, (f, drawn), pick);
        let width = single.advance;
        Some((vec![(single, Length::ZERO)], width))
    }

    /// Puts the dotless form of a letter in the place of `glyph`, a glyph of an accent's base,
    /// when its font's `dtls` feature has one: a base of `i` or `j` draws without its dot.
    pub fn dotless(&mut self, glyph: &mut Glyph) {
        let Some(f) = self.faces().get(glyph.face).copied() else {
            return;
        };
        if let Some(id) = self.fonts.dotless_form(f.font, glyph.id) {
            self.draw_variant(glyph, (f, f), id);
        }
    }

    /// The top accent attachment of a base's only glyph from its origin: the font's `MATH`
    /// table's, or else half its advance.
    pub fn top_accent_attachment(&self, glyph: &Glyph) -> Length {
        let units = self
            .faces()
            .get(glyph.face)
            .and_then(|face| Some((face, self.fonts.top_accent_attachment(face.font, glyph.id)?)));
        units.map_or(glyph.advance.div_toward_zero(2), |(face, units)| {
            face.scale(i64::from(units))
        })
    }

    /// Draws `glyph`, an accent's character, over `base`. The room for the accent is twice the
    /// smaller distance from the base's attachment to either end of its advance. The accent
    /// draws the widest horizontal variant of its glyph in the font's `MATH` table whose
    /// advance measurement fits that room, or else its first variant; when the room is wider
    /// than the widest variant and the glyph's assembly fits it, the assembly over the base's
    /// advance from its start. A base whose ink reaches above `flattened_height` takes the
    /// flattened form of the variant (`flac`). The variant's attachment, or half its advance,
    /// stands at the base's; and the accent rises by what the base's ink reaches above
    /// `base_height`, to the nearest dot, with the room of its ink and `room_above` over it.
    /// Returns the accent's glyphs and places; none when the glyph's font has no `MATH` table.
    pub fn accent(
        &mut self,
        glyph: &Glyph,
        base: AccentBase,
        lengths: &AccentLengths,
    ) -> Option<DrawnAccent> {
        let f = self.faces().get(glyph.face).copied()?;
        let em = i64::from(f.metrics.units_per_em.max(1));
        let size = f.size.units().max(1);
        let units = |length: Length| i32::try_from((length.units() * em).div_euclid(size)).ok();
        let room = base
            .attachment
            .min(base.width - base.attachment)
            .max(Length::ZERO)
            * 2;
        let room = units(room)?;
        let construction = self.fonts.horizontal_construction(f.font, glyph.id);
        let own = self.fonts.advance(f.font, glyph.id).unwrap_or(0);
        let (variants, assembly) = construction.map_or_else(
            || (vec![(glyph.id, i32::from(own))], Vec::new()),
            |c| (c.variants, c.assembly),
        );
        let height = base.top.map_or(Length::ZERO, |top| top - f.rise);
        let lift = (height - lengths.base_height).max(Length::ZERO);
        let mut drawn = f;
        drawn.rise = self.settings.dot.snap(f.rise + lift);
        drawn.raised = drawn.rise;
        drawn.math.room = MathRoom::Ink {
            leading: lengths.room_above,
        };
        let widest = variants.last().map_or(0, |&(_, measure)| measure);
        let minimum = self.fonts.math_accent(f.font)?.min_connector_overlap;
        if room > widest && shortest(&assembly, minimum).is_some_and(|least| least <= room) {
            let width = units(base.width)?;
            return Some(
                assembled(&assembly, width, minimum)
                    .into_iter()
                    .enumerate()
                    .map(|(index, (part, at))| {
                        let mut drawn_part = *glyph;
                        if index > 0 {
                            drawn_part.ch = ' ';
                            drawn_part.space = SpaceKind::Assembly;
                        }
                        self.draw_variant(&mut drawn_part, (f, drawn), part);
                        (drawn_part, (f.size * at).div_round(em))
                    })
                    .collect(),
            );
        }
        let mut pick = variants
            .iter()
            .rev()
            .find(|&&(_, measure)| measure <= room)
            .or(variants.first())
            .map_or(glyph.id, |&(variant, _)| variant);
        if height > lengths.flattened_height {
            pick = self.fonts.flattened_accent(f.font, pick).unwrap_or(pick);
        }
        let mut accent = *glyph;
        self.draw_variant(&mut accent, (f, drawn), pick);
        let attachment = self
            .fonts
            .top_accent_attachment(f.font, pick)
            .map_or(accent.advance.div_toward_zero(2), |units| {
                (f.size * i64::from(units)).div_round(em)
            });
        Some(vec![(accent, base.attachment - attachment)])
    }
}

/// The length of the shortest form of a glyph assembly, each part once overlapping by up to
/// `min(left.end_connector_length, right.start_connector_length)` (at least `overlap`); none for
/// no assembly.
fn shortest(parts: &[AssemblyPart], overlap: i32) -> Option<i32> {
    if parts.is_empty() {
        return None;
    }
    let total: i32 = parts.iter().map(|part| part.full_advance).sum();
    let max_overlap: i32 = parts
        .windows(2)
        .filter_map(|pair| match pair {
            [left, right] => Some(
                left.end_connector_length
                    .min(right.start_connector_length)
                    .max(overlap),
            ),
            _ => None,
        })
        .sum();
    Some(total - max_overlap)
}

/// The parts of a glyph assembly `width` font units long, each with its origin's distance from
/// the first part's, in font units: each extender repeats the fewest times that reach `width`
/// with joints of `overlap`. The joints next to a part that is not an extender overlap by
/// `overlap`, and the joints between two extenders share the rest of the length; an assembly
/// without such joints shares it among all its joints.
fn assembled(parts: &[AssemblyPart], width: i32, overlap: i32) -> Vec<(u32, i64)> {
    assembled_from(parts, width, overlap, 1)
}

/// As [`assembled`], starting the extender repeat count at `min_repeat` (`0` allows omitting
/// extenders when the non-extender parts already reach `width`).
fn assembled_from(
    parts: &[AssemblyPart],
    width: i32,
    overlap: i32,
    min_repeat: usize,
) -> Vec<(u32, i64)> {
    let chain = |repeat: usize| -> Vec<AssemblyPart> {
        parts
            .iter()
            .flat_map(|part| std::iter::repeat_n(*part, if part.extender { repeat } else { 1 }))
            .collect()
    };
    let length = |chain: &[AssemblyPart]| {
        let joints = i64::try_from(chain.len().saturating_sub(1)).unwrap_or(0);
        chain
            .iter()
            .map(|part| i64::from(part.full_advance))
            .sum::<i64>()
            - joints * i64::from(overlap)
    };
    let mut repeat = min_repeat;
    let mut parts_drawn = chain(repeat);
    while length(&parts_drawn) < i64::from(width) && repeat < params::MATH_ASSEMBLY_REPEATS {
        repeat += 1;
        parts_drawn = chain(repeat);
    }
    let joints = parts_drawn.len().saturating_sub(1);
    let inner: Vec<bool> = parts_drawn
        .windows(2)
        .map(|pair| pair.iter().all(|part| part.extender))
        .collect();
    let shared = match inner.iter().filter(|&&inner| inner).count() {
        0 => vec![true; joints],
        _ => inner,
    };
    let sharing = i64::try_from(shared.iter().filter(|&&s| s).count())
        .unwrap_or(1)
        .max(1);
    let fixed = i64::try_from(joints).unwrap_or(0) - sharing;
    let rest = parts_drawn
        .iter()
        .map(|part| i64::from(part.full_advance))
        .sum::<i64>()
        - i64::from(width)
        - fixed * i64::from(overlap);
    // The places in units of 1/`sharing` font unit, so that the shared overlaps stay exact.
    let mut at = 0;
    let mut out = Vec::with_capacity(parts_drawn.len());
    for (k, part) in parts_drawn.iter().enumerate() {
        out.push((part.glyph, at));
        if let Some(&shares) = shared.get(k) {
            let overlap = if shares {
                rest
            } else {
                i64::from(overlap) * sharing
            };
            at += i64::from(part.full_advance) * sharing - overlap;
        }
    }
    out.into_iter()
        .map(|(glyph, at)| (glyph, at.div_euclid(sharing)))
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    const EXTENDER: AssemblyPart = AssemblyPart {
        glyph: 1,
        start_connector_length: 580,
        end_connector_length: 580,
        full_advance: 601,
        extender: true,
    };
    const HEAD: AssemblyPart = AssemblyPart {
        glyph: 2,
        start_connector_length: 400,
        end_connector_length: 0,
        full_advance: 755,
        extender: false,
    };

    #[test]
    fn an_assembly_repeats_its_extender_and_shares_the_inner_joints() {
        let parts = assembled(&[EXTENDER, HEAD], 2641, 200);
        let glyphs: Vec<u32> = parts.iter().map(|&(glyph, _)| glyph).collect();
        assert_eq!(glyphs, [1, 1, 1, 1, 1, 2]);
        // The head overlaps the last extender by the least overlap and ends at the width.
        let (_, head) = parts[5];
        let (_, last) = parts[4];
        assert_eq!(head - last, 401);
        assert_eq!(head + 755, 2641);
    }

    #[test]
    fn the_shortest_assembly_uses_connector_overlaps() {
        assert_eq!(shortest(&[EXTENDER, HEAD], 200), Some(956));
        assert_eq!(shortest(&[], 200), None);
    }
}