f-office-docx 0.1.0

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};
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 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)?,
        })
    }

    /// 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()
                    .map(|(part, at)| {
                        let mut drawn_part = *glyph;
                        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 with joints of
/// `overlap`; none for no assembly.
fn shortest(parts: &[AssemblyPart], overlap: i32) -> Option<i32> {
    let joints = i32::try_from(parts.len().checked_sub(1)?).ok()?;
    Some(parts.iter().map(|part| part.full_advance).sum::<i32>() - joints * 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)> {
    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 = 1;
    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,
        full_advance: 601,
        extender: true,
    };
    const HEAD: AssemblyPart = AssemblyPart {
        glyph: 2,
        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_takes_each_part_once() {
        assert_eq!(shortest(&[EXTENDER, HEAD], 200), Some(1156));
        assert_eq!(shortest(&[], 200), None);
    }
}