f-office-docx 0.2.1

DOCX model and Word's layout rules.
Documentation
//! The footnotes of a page in a section of text columns of one width from `NOTE_FLOW_MODE`:
//! they fill the columns of the footnote area in turn, each to the smallest height at which
//! all of them fit, and every column starts at the top of the area.

use f_office_units::Length;

use crate::lines::NoteNumber;

use super::super::Layout;
use super::splits::Break;

/// The lines of a footnote that stand in one column of the footnote area.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Run {
    /// The footnote's number.
    pub(super) number: NoteNumber,
    /// The column, from 0.
    pub(super) column: usize,
    /// The top of the first line below the top of the column.
    pub(super) top: Length,
    /// The first line and the line after the last, or `None` to the footnote's end.
    pub(super) lines: (usize, Option<usize>),
}

/// A footnote as the columns of the footnote area take it.
#[derive(Clone, Debug)]
struct Flowed {
    /// Its number.
    number: NoteNumber,
    /// Its height, without the space after its last paragraph.
    height: Length,
    /// The space between it and the next footnote in its column.
    after: Length,
    /// The places where it may break between two columns.
    breaks: Vec<Break>,
}

/// The runs of the footnotes `notes` in `columns` columns of the height `height`, each column
/// filled before the next starts, or `None` when they do not fit. A footnote that does not fit
/// whole in the rest of a column keeps there its lines up to the last break that fits, and the
/// next column takes its rest.
fn fill(notes: &[Flowed], columns: usize, height: Length) -> Option<Vec<Run>> {
    let mut runs = Vec::new();
    let (mut column, mut used) = (0, Length::ZERO);
    for note in notes {
        let (mut start, mut from) = (Length::ZERO, 0);
        loop {
            if used + note.height - start <= height {
                runs.push(Run {
                    number: note.number,
                    column,
                    top: used,
                    lines: (from, None),
                });
                used += note.height - start + note.after;
                break;
            }
            let fit = note
                .breaks
                .iter()
                .rev()
                .find(|at| at.lines > from && used + at.height - start <= height);
            if let Some(at) = fit {
                runs.push(Run {
                    number: note.number,
                    column,
                    top: used,
                    lines: (from, Some(at.lines)),
                });
                (start, from) = (note.height - at.rest, at.lines);
            } else if used == Length::ZERO {
                return None;
            }
            (column, used) = (column + 1, Length::ZERO);
            if column >= columns {
                return None;
            }
        }
    }
    Some(runs)
}

/// The heights that a column of the footnotes `notes` can have, from the smallest: each from
/// the start of a footnote or of the rest after a break to the end of a later footnote or a
/// later break.
fn heights(notes: &[Flowed]) -> Vec<Length> {
    let (mut starts, mut ends) = (Vec::new(), Vec::new());
    let mut offset = Length::ZERO;
    for note in notes {
        starts.push(offset);
        ends.push(offset + note.height);
        for at in &note.breaks {
            starts.push(offset + note.height - at.rest);
            ends.push(offset + at.height);
        }
        offset += note.height + note.after;
    }
    let mut out: Vec<Length> = starts
        .iter()
        .flat_map(|start| {
            ends.iter()
                .filter(|end| *end > start)
                .map(|end| *end - *start)
        })
        .collect();
    out.sort_unstable();
    out.dedup();
    out
}

impl Layout<'_> {
    /// The footnotes `numbers` as the columns of the footnote area take them.
    fn flowed(&mut self, numbers: &[NoteNumber]) -> Vec<Flowed> {
        numbers
            .iter()
            .enumerate()
            .map(|(index, &number)| Flowed {
                number,
                height: self.note_size(number).0,
                after: self.note_after(number, numbers.get(index + 1).copied()),
                breaks: self.note_breaks(number),
            })
            .collect()
    }

    /// The height of the columns of the footnote area that hold the footnotes `numbers` in
    /// `columns` columns, and the runs of their lines.
    pub(super) fn note_flow(
        &mut self,
        numbers: &[NoteNumber],
        columns: usize,
    ) -> (Length, Vec<Run>) {
        let notes = self.flowed(numbers);
        heights(&notes)
            .into_iter()
            .find_map(|height| fill(&notes, columns, height).map(|runs| (height, runs)))
            .unwrap_or_default()
    }
}

#[cfg(test)]
mod tests {
    use f_office_units::Length;

    use super::{Break, Flowed, fill, heights};
    use crate::lines::NoteNumber;

    const LINE: Length = match Length::from_twips(240) {
        Some(line) => line,
        None => Length::ZERO,
    };

    /// A footnote of `lines` lines of one height, with widow control when `widows`.
    fn note(number: usize, lines: usize, widows: bool) -> Flowed {
        let breaks = (1..lines)
            .filter(|&kept| !widows || (kept >= 2 && lines - kept >= 2))
            .map(|kept| Break {
                lines: kept,
                height: LINE * i64::try_from(kept).unwrap_or(0),
                rest: LINE * i64::try_from(lines - kept).unwrap_or(0),
            })
            .collect();
        Flowed {
            number: NoteNumber::of_index(number),
            height: LINE * i64::try_from(lines).unwrap_or(0),
            after: Length::ZERO,
            breaks,
        }
    }

    /// The lines in each column at the smallest height that holds footnotes of the line
    /// counts `lines`, with widow control when `widows`.
    fn split(lines: &[usize], widows: bool, columns: usize) -> Vec<usize> {
        let notes: Vec<Flowed> = lines
            .iter()
            .enumerate()
            .map(|(number, &count)| note(number, count, widows))
            .collect();
        let runs = heights(&notes)
            .into_iter()
            .find_map(|height| fill(&notes, columns, height))
            .unwrap_or_default();
        let mut out = vec![0; columns];
        for run in runs {
            let count = lines.get(run.number.index()).copied().unwrap_or(0);
            if let Some(slot) = out.get_mut(run.column) {
                *slot += run.lines.1.unwrap_or(count) - run.lines.0;
            }
        }
        out
    }

    #[test]
    fn fills_each_column_before_the_next() {
        assert_eq!(split(&[1; 7], true, 3), [3, 3, 1]);
        assert_eq!(split(&[1; 4], true, 3), [2, 2, 0]);
        assert_eq!(split(&[1; 5], true, 2), [3, 2]);
    }

    #[test]
    fn keeps_widow_control_across_columns() {
        let cases: [(&[usize], bool, usize, &[usize]); 8] = [
            (&[3], true, 2, &[3, 0]),
            (&[3], false, 2, &[2, 1]),
            (&[5], true, 2, &[3, 2]),
            (&[1, 3], true, 2, &[1, 3]),
            (&[1, 2], true, 2, &[1, 2]),
            (&[2, 2], true, 2, &[2, 2]),
            (&[4, 1], false, 2, &[3, 2]),
            (&[3, 1, 1], true, 3, &[3, 2, 0]),
        ];
        for (lines, widows, columns, expected) in cases {
            assert_eq!(
                split(lines, widows, columns),
                expected,
                "{lines:?} {widows}"
            );
        }
    }
}