f-office-docx 0.2.1

DOCX model and Word's layout rules.
Documentation
//! The pieces of a line whose paragraph's text alignment is `center` (`w:textAlignment`,
//! ECMA-376 Part 1, 17.3.1.39), on a target that puts the middles of their win lines on one line
//! (`CenteredLine::MiddlesShared`), and the face of such a line of multiple spacing, on a target
//! that rounds its middle (`CenteredMultiple::MiddleRounded`).

use f_office_units::Length;
use f_office_units::scale::LINE;

use crate::grid::Rounding;
use crate::layout::{Layout, decisions};
use crate::lines::{Line, Piece};
use crate::props::{LineSpacing, ParaProps, TextAlignment};
use crate::text::{Face, FaceIndex, MathFace};

/// What a centered line's pieces share, from which each face's place follows
/// ([`Self::shift`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) struct CenteredMiddle {
    /// The tallest win line of the line's pieces, a list label's included.
    tallest: Length,
    /// The highest win top of the line's pieces.
    top: Length,
}

impl CenteredMiddle {
    /// How far below the line's baseline the baseline of a piece of `face` goes, negative
    /// above it: the pieces' win lines have their middles on one line, and the highest win top
    /// lies where the highest win top of the line lies on the baseline.
    pub(in crate::layout) fn shift(self, face: &Face) -> Length {
        (self.tallest + face.win_top() - face.descent()).div_round(2) - self.top
    }
}

/// A centered line: what its pieces share, and its descent below the line's baseline.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) struct Centered {
    pub(in crate::layout) middle: CenteredMiddle,
    /// How far the line reaches below its baseline: to the lowest win bottom of its text, which
    /// lies half the tallest win line of its pieces and half the tallest of its text below their
    /// middles. A list label's descent stays out of it, as on a line without the alignment.
    pub(in crate::layout) descent: Length,
}

/// The face of a centered line of automatic multiple spacing above single spacing whose pieces
/// are glyphs of one win line and one pixel line, which places the line's baseline
/// (`CenteredMultiple::MiddleRounded`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) struct CenteredFace {
    /// How far the middle of the face's win line lies above its baseline: half its win top
    /// less its descent.
    pub(in crate::layout) middle: Length,
    /// Half the face's win line: half its win top plus its descent.
    pub(in crate::layout) half: Length,
    /// How far the baseline lies below the middle of the face's pixel line on the device: half
    /// its pixel ascent less its pixel descent at the pel height, rounded up to whole dots.
    pub(in crate::layout) pixels: Length,
}

/// The win line of one piece: its win top, its descent, and whether it is a list label.
struct WinLine {
    top: Length,
    descent: Length,
    label: bool,
}

impl WinLine {
    fn height(&self) -> Length {
        self.top + self.descent
    }
}

impl Layout<'_> {
    /// The centered line of `line` in a paragraph of the properties `props`, where the target
    /// shares the middles of the pieces of such a line (`CenteredLine::MiddlesShared`), the
    /// paragraph's text alignment is `center`, its spacing automatic single spacing without a
    /// document grid, and the line's pieces besides spaces and tabs are glyphs of at least two
    /// win lines, each of a face not made for East Asian text, neither raised, lowered, a script
    /// nor a part of an equation. `None` elsewhere: such a line keeps its pieces on one
    /// baseline.
    pub(in crate::layout) fn centered_line(
        &self,
        line: &Line,
        props: &ParaProps,
    ) -> Option<Centered> {
        if props.text_alignment.as_ref().map(|set| set.value) != Some(TextAlignment::Center)
            || props.line.unwrap_or(LineSpacing::Auto(LINE)) != LineSpacing::Auto(LINE)
            || self.grid_pitch.is_some()
        {
            return None;
        }
        decisions::shared_middles(&self.context.quirks, || {
            let mut lines = Vec::new();
            for placed in line.placed.iter().filter(|p| !super::height::is_blank(p)) {
                let Piece::Glyph(glyph) = placed.piece else {
                    return None;
                };
                let face = self.shaper.faces().get(glyph.face)?;
                if !plain(face) {
                    return None;
                }
                lines.push(WinLine {
                    top: face.win_top(),
                    descent: face.descent(),
                    label: glyph.label,
                });
            }
            let first = lines.first()?;
            if lines
                .iter()
                .all(|l| l.top == first.top && l.descent == first.descent)
            {
                return None;
            }
            let tallest = lines.iter().map(WinLine::height).max()?;
            let text = lines
                .iter()
                .filter(|l| !l.label)
                .map(WinLine::height)
                .max()
                .unwrap_or(tallest);
            let top = lines.iter().map(|l| l.top).max()?;
            Some(Centered {
                middle: CenteredMiddle { tallest, top },
                descent: (tallest + text).div_round(2) - top,
            })
        })
    }
}

impl Layout<'_> {
    /// The face of `line` in a paragraph of the properties `props`, where the target rounds the
    /// middle of a centered line of multiple spacing (`CenteredMultiple::MiddleRounded`), the
    /// paragraph's text alignment is `center`, its spacing automatic multiple spacing above
    /// single spacing without a document grid, no inline object is taller than the line's
    /// single line (`excess`), and the line's pieces besides spaces and tabs are glyphs of plain
    /// faces ([`plain`]) of one win line and one pixel line. `None` elsewhere, and on a line
    /// without such glyphs: the line keeps the baseline of its box.
    pub(in crate::layout) fn centered_face(
        &self,
        line: &Line,
        props: &ParaProps,
        excess: Length,
    ) -> Option<CenteredFace> {
        if props.text_alignment.as_ref().map(|set| set.value) != Some(TextAlignment::Center)
            || !matches!(props.line, Some(LineSpacing::Auto(n)) if n > LINE)
            || self.grid_pitch.is_some()
            || excess > Length::ZERO
        {
            return None;
        }
        decisions::rounded_middle(&self.context.quirks, || {
            let mut found = None;
            for placed in line.placed.iter().filter(|p| !super::height::is_blank(p)) {
                let Piece::Glyph(glyph) = placed.piece else {
                    return None;
                };
                let face = self.shaper.faces().get(glyph.face)?;
                if !plain(face) {
                    return None;
                }
                let own = (
                    face.win_top(),
                    face.descent(),
                    self.pixel_shift(glyph.face, face)?,
                );
                if found.is_some_and(|seen| seen != own) {
                    return None;
                }
                found = Some(own);
            }
            let (top, descent, pixels) = found?;
            Some(CenteredFace {
                middle: (top - descent).div_round(2),
                half: (top + descent).div_round(2),
                pixels: self.device.dots(pixels),
            })
        })
    }

    /// Half the pixel ascent less the pixel descent of `face`, the face `index`, rounded up to
    /// whole dots, at the device's pel height: the size in dots, rounded to the nearest. The
    /// pixel heights are the font's `VDMX` heights there, or else its win top and descent at
    /// that pel height, each rounded to the nearest pixel.
    fn pixel_shift(&self, index: FaceIndex, face: &Face) -> Option<i64> {
        let pels = self.device.count(face.size, Rounding::HalfUp);
        let (ascent, descent) = self
            .shaper
            .whole_pixel_heights(index, u16::try_from(pels).ok()?)?;
        Some((ascent - descent + 1).div_euclid(2))
    }
}

/// Whether a piece of `face` takes part in a centered line: a face not made for East Asian
/// text, at its own line size, neither raised nor lowered, outside equations.
fn plain(face: &Face) -> bool {
    !face.metrics.east_asian
        && face.size == face.line_size
        && face.rise == Length::ZERO
        && face.raised == Length::ZERO
        && face.math == MathFace::default()
}

#[cfg(test)]
mod tests;