f-office-docx 0.2.3

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 an aligned line's pieces share, from which each face's place follows
/// ([`Self::shift`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in crate::layout) enum CenteredMiddle {
    /// Pieces' win lines share one middle: the baseline of `face` moves by
    /// `(tallest + face.win_top() - face.win_descent()) / 2 - top`.
    Middle {
        /// The tallest win line of the line's pieces (or the exact line's alignment box height).
        tallest: Length,
        /// The highest win top above the line's baseline (or the exact line's alignment box top).
        top: Length,
    },
    /// Pieces' win tops share one line `top` above the line's baseline: the baseline of `face`
    /// moves by `face.win_top() - top`.
    Top {
        /// How far above the line's baseline the shared top line lies.
        top: Length,
    },
}

impl CenteredMiddle {
    /// How far below the line's baseline the baseline of a piece of `face` goes, negative
    /// above it.
    pub(in crate::layout) fn shift(self, face: &Face) -> Length {
        match self {
            Self::Middle { tallest, top } => {
                (tallest + face.win_top() - face.win_descent()).div_round(2) - top
            }
            Self::Top { top } => face.win_top() - top,
        }
    }
}

/// A line whose pieces shift from the line's baseline under `w:textAlignment`, and its optional
/// descent override 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 a single-spaced centered 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. `None` on exact lines, which keep their exact box.
    pub(in crate::layout) descent: Option<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 aligned 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`):
    ///
    /// - For exact line spacing (`LineSpacing::Exact(h)`) with `textAlignment` `center` or `top`,
    ///   each run aligns its win middle or win top to the exact line's reference box, which sits
    ///   at the exact baseline without `w:spaceForUL` and spans `baseline - (h - baseline)` above
    ///   the exact baseline when `w:spaceForUL` is set.
    /// - For automatic single spacing without a document grid and `textAlignment` `center`, a
    ///   line whose non-blank pieces are glyphs of at least two win lines (not East Asian,
    ///   raised, lowered, a script, or a part of an equation) shares one middle.
    ///
    /// `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> {
        let alignment = props.text_alignment.as_ref().map(|set| set.value)?;
        let rule = props.line.unwrap_or(LineSpacing::Auto(LINE));
        if matches!(rule, LineSpacing::Exact(_))
            && !matches!(alignment, TextAlignment::Center | TextAlignment::Top)
        {
            return None;
        }
        if !matches!(rule, LineSpacing::Exact(_))
            && (alignment != TextAlignment::Center
                || rule != LineSpacing::Auto(LINE)
                || self.grid_pitch.is_some())
        {
            return None;
        }
        decisions::shared_middles(&self.context.quirks, || {
            if let LineSpacing::Exact(height) = rule {
                return self.exact_centered(alignment, height);
            }
            self.single_centered(line)
        })
    }

    /// Alignment shift for an exact-height line of `height` under `center` or `top`
    /// `w:textAlignment`.
    fn exact_centered(&self, alignment: TextAlignment, height: Length) -> Option<Centered> {
        let top = if self.settings.space_for_ul == crate::styles::SpaceForUl::On {
            let (part, whole) = crate::params::EXACT_BASELINE;
            let baseline = (height * part).div_round(whole);
            baseline - (height - baseline)
        } else {
            Length::ZERO
        };
        let middle = match alignment {
            TextAlignment::Center => CenteredMiddle::Middle { tallest: top, top },
            TextAlignment::Top => CenteredMiddle::Top { top },
            _ => return None,
        };
        Some(Centered {
            middle,
            descent: None,
        })
    }

    /// Shared-middle alignment for a single-spaced line with two or more distinct win heights.
    fn single_centered(&self, line: &Line) -> Option<Centered> {
        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::Middle { tallest, top },
            descent: Some((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;