f-office-docx 0.1.0

DOCX model and Word's layout rules.
Documentation
//! The matrices of equations (`m:m`): once every cell of a matrix is measured, its cells stand
//! in columns, each as wide as its widest cell, and its rows stand one under another.

use std::ops::Range;

use f_office_units::Length;

use super::gap_minimums::{ink, lift_part};
use super::structures::last_italic_correction;
use crate::body::{CellJustification, MatrixBase, MatrixMark, MatrixSettings, RowSpacing};
use crate::grid::Device;
use crate::lines::{Piece, advance};
use crate::params;
use crate::props::RunProps;
use crate::text::{FaceIndex, Shaper};

/// A matrix whose end is still to come: its settings, the face of its marks, which gives its
/// size and its font's line, the `MathLeading` of its font at its size, its cells so far, and
/// the row and the column of the next cell.
pub(in crate::layout) struct OpenMatrix {
    settings: MatrixSettings,
    face: Option<FaceIndex>,
    leading: Option<Length>,
    cells: Vec<Cell>,
    row: usize,
    column: usize,
}

/// A cell of a matrix: its row, its column, its column's justification, and the index of the
/// shift before its first piece among a paragraph's pieces.
struct Cell {
    row: usize,
    column: usize,
    justification: CellJustification,
    at: usize,
}

/// Places a mark of a matrix in a paragraph's `pieces`, with the properties `props` of its run.
/// Each cell starts with a shift, which the matrix's end sets.
pub(in crate::layout) fn mark(
    (shaper, device): (&mut Shaper, Device),
    (open, pieces): (&mut Vec<OpenMatrix>, &mut Vec<Piece>),
    mark: MatrixMark,
    props: &RunProps,
) {
    match mark {
        MatrixMark::Start(settings) => open.push(OpenMatrix {
            settings,
            face: shaper.face(props, true),
            leading: shaper.equation_leading(props),
            cells: Vec::new(),
            row: 0,
            column: 0,
        }),
        MatrixMark::Row => {
            if let Some(matrix) = open.last_mut() {
                matrix.row += 1;
                matrix.column = 0;
            }
        }
        MatrixMark::Cell(justification) => {
            if let Some(matrix) = open.last_mut() {
                matrix.cells.push(Cell {
                    row: matrix.row,
                    column: matrix.column,
                    justification,
                    at: pieces.len(),
                });
                matrix.column += 1;
                pieces.push(Piece::Shift(Length::ZERO));
            }
        }
        MatrixMark::End => {
            if let Some(matrix) = open.pop() {
                end((shaper, device), pieces, &matrix);
            }
        }
    }
}

/// Places the cells of the matrix `matrix`, which are the last of `pieces`, and ends the matrix
/// after its widest row. A centered matrix in a raised or lowered part, such as a numerator,
/// stands on the axis above that part's baseline.
fn end((shaper, device): (&mut Shaper, Device), pieces: &mut Vec<Piece>, matrix: &OpenMatrix) {
    let Some(face) = matrix.face.and_then(|face| shaper.faces().get(face)) else {
        return;
    };
    let (size, line, base) = (face.size, face.line_height(), device.shift_dots(face.rise));
    let gap =
        face.scale(i64::from(face.metrics.hhea_line_gap)) + matrix.leading.unwrap_or(Length::ZERO);
    let ranges: Vec<Range<usize>> = matrix
        .cells
        .iter()
        .enumerate()
        .map(|(k, cell)| {
            let next = matrix.cells.get(k + 1).map_or(pieces.len(), |next| next.at);
            cell.at + 1..next
        })
        .collect();
    place_columns(shaper, pieces, (matrix, &ranges), size);
    let rows = row_ranges(&matrix.cells, &ranges);
    let inks: Vec<Option<(Length, Length)>> = rows
        .iter()
        .map(|range| ink(shaper, &device, pieces.get(range.clone()).unwrap_or(&[])))
        .collect();
    let baselines = baselines(&matrix.settings.rows, (line, gap), &inks);
    let by = match matrix.settings.base {
        MatrixBase::Top => Length::ZERO,
        MatrixBase::Bottom => -baselines.last().copied().unwrap_or(Length::ZERO),
        MatrixBase::Center => base + centered(size, &baselines, &inks),
    };
    for (range, baseline) in rows.into_iter().zip(baselines) {
        if let Some(row) = pieces.get_mut(range) {
            lift_part((shaper, device), row, by + baseline);
        }
    }
}

/// Sets the shift before each cell of `matrix`, whose pieces lie in `ranges`, so that the cell
/// stands in its column by its justification, and ends the matrix where the widest cell of its
/// last column ends, which leaves out the room of a wider last column after its cells. A
/// cell is as wide as its advances and the italic correction of its last glyph, and a column
/// as its widest cell, at least the matrix's least width; the columns stand an em of the
/// matrix's `size` apart.
fn place_columns(
    shaper: &Shaper,
    pieces: &mut Vec<Piece>,
    (matrix, ranges): (&OpenMatrix, &[Range<usize>]),
    size: Length,
) {
    let advances: Vec<Length> = ranges
        .iter()
        .map(|range| sum(pieces.get(range.clone()).unwrap_or(&[])))
        .collect();
    let widths: Vec<Length> = ranges
        .iter()
        .zip(&advances)
        .map(|(range, advance)| {
            *advance + last_italic_correction(shaper, pieces.get(range.clone()).unwrap_or(&[]))
        })
        .collect();
    let (starts, columns) = columns(matrix, &widths, size);
    let last = columns.len().checked_sub(1);
    let mut end = Length::ZERO;
    let mut pen = Length::ZERO;
    for ((cell, width), advance) in matrix.cells.iter().zip(&widths).zip(&advances) {
        let (Some(&start), Some(&column)) = (starts.get(cell.column), columns.get(cell.column))
        else {
            continue;
        };
        let place = start
            + match cell.justification {
                CellJustification::Left => Length::ZERO,
                CellJustification::Center => (column - *width).div_toward_zero(2),
                CellJustification::Right => column - *width,
            };
        if let Some(piece) = pieces.get_mut(cell.at) {
            *piece = Piece::Shift(place - pen);
        }
        pen = place + *advance;
        if Some(cell.column) == last {
            end = end.max(place + *width);
        }
    }
    pieces.push(Piece::Shift(end - pen));
}

/// The start and the width of each column of `matrix`, whose cells are `widths` wide, at its
/// `size`.
fn columns(matrix: &OpenMatrix, widths: &[Length], size: Length) -> (Vec<Length>, Vec<Length>) {
    let count = matrix
        .cells
        .iter()
        .map(|cell| cell.column + 1)
        .max()
        .unwrap_or(0);
    let mut columns = vec![matrix.settings.column_width; count];
    for (cell, width) in matrix.cells.iter().zip(widths) {
        if let Some(column) = columns.get_mut(cell.column) {
            *column = (*column).max(*width);
        }
    }
    let gap = size;
    let mut starts = Vec::with_capacity(count);
    let mut x = Length::ZERO;
    for width in &columns {
        starts.push(x);
        x += *width + gap;
    }
    (starts, columns)
}

/// The sum of the advances of `pieces`.
fn sum(pieces: &[Piece]) -> Length {
    pieces.iter().map(advance).sum()
}

/// `size` times the share `(units, em)`, to the nearest half-EMU.
fn at(size: Length, (units, em): (i64, i64)) -> Length {
    (size * units).div_round(em)
}

/// The range of the pieces of each row of a matrix, from the shift before its first cell to the
/// end of its last cell, given the cells and the range of each cell's pieces.
fn row_ranges(cells: &[Cell], ranges: &[Range<usize>]) -> Vec<Range<usize>> {
    let mut rows: Vec<Range<usize>> = Vec::new();
    for (cell, range) in cells.iter().zip(ranges) {
        match rows.get_mut(cell.row) {
            Some(row) => row.end = range.end,
            None => rows.push(cell.at..range.end),
        }
    }
    rows
}

/// The baseline of each row of a matrix above the first row's, with its font's `line`: each row
/// stands under the row before it by the rows' spacing, or by more when the ink below the upper
/// row's baseline, the ink above the lower row's baseline and the gap `gap` between them need
/// more. Rows with an exact spacing keep it.
fn baselines(
    spacing: &RowSpacing,
    (line, gap): (Length, Length),
    inks: &[Option<(Length, Length)>],
) -> Vec<Length> {
    let (pitch, by_ink) = match *spacing {
        RowSpacing::Single => (line, true),
        RowSpacing::OneAndAHalf => (at(line, params::MATH_MATRIX_ONE_AND_A_HALF_LINES), true),
        RowSpacing::Double => (line * 2, true),
        RowSpacing::Exactly(distance) => (distance, false),
        RowSpacing::HalfLines(halves) => ((line * halves).div_round(2), true),
    };
    let mut baseline = Length::ZERO;
    let mut out = Vec::with_capacity(inks.len());
    for (k, row) in inks.iter().enumerate() {
        if k > 0 {
            let above = inks.get(k - 1).copied().flatten();
            let need = match (above, *row) {
                (Some((low, _)), Some((_, high))) if by_ink => high - low + gap,
                _ => Length::ZERO,
            };
            baseline -= pitch.max(need);
        }
        out.push(baseline);
    }
    out
}

/// How far a matrix whose rows have the baselines `baselines` moves so that the middle of its
/// ink lies on the math axis at its `size`; with no ink, the middle of its first and last
/// baselines.
fn centered(size: Length, baselines: &[Length], inks: &[Option<(Length, Length)>]) -> Length {
    let drawn = baselines
        .iter()
        .zip(inks)
        .filter_map(|(baseline, row)| row.map(|(low, high)| (*baseline + low, *baseline + high)))
        .reduce(|(low, high), (l, h)| (low.min(l), high.max(h)));
    let (low, high) = drawn.unwrap_or_else(|| {
        let last = baselines.last().copied().unwrap_or(Length::ZERO);
        (last, Length::ZERO)
    });
    at(size, params::MATH_AXIS_HEIGHT) - (low + high).div_toward_zero(2)
}

#[cfg(test)]
mod tests {
    use super::{Cell, OpenMatrix, baselines, columns};
    use crate::body::{CellJustification, MatrixSettings, RowSpacing};
    use f_office_units::Length;

    fn pt(points: i64) -> Length {
        Length::from_points(points).unwrap()
    }

    #[test]
    fn stands_each_row_a_line_below_the_last_or_further_by_the_ink_and_the_gap() {
        let (line, gap) = (pt(14), pt(4));
        // Rows of short ink keep the line; a row reaching 6 pt below its baseline over one
        // reaching 9 pt above its own needs 6 + 9 + 4 pt.
        let inks = [
            Some((pt(-1), pt(5))),
            Some((pt(-6), pt(5))),
            Some((pt(-1), pt(9))),
            None,
        ];
        let want = [pt(0), pt(-14), pt(-33), pt(-47)];
        assert_eq!(baselines(&RowSpacing::Single, (line, gap), &inks), want);
        // The rules of more lines grow by the ink too; the exact rule keeps its distance.
        let double = baselines(&RowSpacing::Double, (line, gap), &inks);
        assert_eq!(double, [pt(0), pt(-28), pt(-56), pt(-84)]);
        let exact = baselines(&RowSpacing::Exactly(pt(10)), (line, gap), &inks);
        assert_eq!(exact, [pt(0), pt(-10), pt(-20), pt(-30)]);
        let halves = baselines(&RowSpacing::HalfLines(3), (line, gap), &inks);
        assert_eq!(halves, [pt(0), pt(-21), pt(-42), pt(-63)]);
    }

    #[test]
    fn makes_each_column_as_wide_as_its_widest_cell_and_its_least_width_an_em_apart() {
        let cell = |row, column| Cell {
            row,
            column,
            justification: CellJustification::Center,
            at: 0,
        };
        let matrix = OpenMatrix {
            settings: MatrixSettings {
                base: crate::body::MatrixBase::Center,
                rows: RowSpacing::Single,
                column_width: pt(8),
            },
            face: None,
            leading: None,
            cells: vec![cell(0, 0), cell(0, 1), cell(1, 0), cell(1, 1)],
            row: 0,
            column: 0,
        };
        let widths = [pt(5), pt(20), pt(12), pt(3)];
        let (starts, columns) = columns(&matrix, &widths, pt(10));
        assert_eq!(columns, [pt(12), pt(20)]);
        assert_eq!(starts, [pt(0), pt(22)]);
    }
}