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};
pub(in crate::layout) struct OpenMatrix {
settings: MatrixSettings,
face: Option<FaceIndex>,
leading: Option<Length>,
cells: Vec<Cell>,
row: usize,
column: usize,
}
struct Cell {
row: usize,
column: usize,
justification: CellJustification,
at: usize,
}
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);
}
}
}
}
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);
}
}
}
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));
}
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)
}
fn sum(pieces: &[Piece]) -> Length {
pieces.iter().map(advance).sum()
}
fn at(size: Length, (units, em): (i64, i64)) -> Length {
(size * units).div_round(em)
}
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
}
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
}
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));
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);
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)]);
}
}