f-office-docx 0.1.0

DOCX model and Word's layout rules.
Documentation
//! A footnote that goes on to the next page: when a footnote has no room whole on the page
//! of its reference, its lines up to an allowed break stay there, the body of the page ends
//! at the line of the reference, and the rest stands at the foot of the next page.

use f_office_units::Length;

use crate::body::{Block, Paragraph};
use crate::lines::{Line, NoteNumber};
use crate::params::WIDOW_LINES;
use crate::props::ParaProps;
use crate::text::FaceIndex;

use super::super::line::height::LineBox;
use super::super::{Layout, PlacedLine};
use super::Separator;

/// The first lines of a footnote that stay on the page of its reference.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in super::super) struct Part {
    /// The footnote's number.
    pub(super) number: NoteNumber,
    /// How many of its lines stay.
    pub(super) lines: usize,
    /// The height of the rest.
    pub(super) rest: Length,
    /// How many lines of the body paragraph still stay on the page below the line of the
    /// reference, because widow control binds them to it.
    pub(super) bound: usize,
}

/// The room that the lines after a line with a reference need on its page, when widow
/// control binds them to that line.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Reserve {
    /// The index of the line with the reference in its paragraph.
    index: usize,
    /// The number of lines bound to it.
    lines: usize,
    /// Their height.
    height: Length,
}

/// A place where a footnote may break between two pages.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Break {
    /// The lines before it.
    pub(super) lines: usize,
    /// Their height.
    pub(super) height: Length,
    /// The height of the lines after it.
    pub(super) rest: Length,
}

/// What a line does at the foot of its page.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(in super::super) enum Foot {
    /// It has room, with its footnotes whole.
    Stays,
    /// It stays with a part of its last footnote, which makes the footnotes of the line this
    /// high.
    Splits(Length, Part),
    /// It goes to the next column or page.
    Leaves,
}

/// The places where a footnote with the line records `lines` may break: after each line but
/// the last, and with the widow control of the line's paragraph (`widows`, by paragraph)
/// neither after the first line of the paragraph nor before its last one. `total` is the
/// footnote's height.
fn breaks_of(lines: &[PlacedLine], widows: &[bool], total: Length) -> Vec<Break> {
    let mut out = Vec::new();
    let mut paragraph = 0;
    for (at, pair) in lines.windows(2).enumerate() {
        let [line, next] = pair else { continue };
        if line.index == 0 && at > 0 {
            paragraph += 1;
        }
        let after = lines.get(at + 1..).unwrap_or_default();
        let left = after.iter().position(|l| l.last).map_or(0, |i| i + 1);
        let kept = line.index + 1;
        let widow = widows.get(paragraph).copied().unwrap_or(true);
        if line.last || !widow || (kept >= WIDOW_LINES && left >= WIDOW_LINES) {
            out.push(Break {
                lines: at + 1,
                height: line.top + line.height,
                rest: total - next.top,
            });
        }
    }
    out
}

impl Layout<'_> {
    /// Whether a paragraph of a footnote has widow control.
    fn note_widow(&self, paragraph: &Paragraph) -> bool {
        self.styles
            .paragraph_properties_without_list_level(&paragraph.props, None)
            .flags()
            .widow_control
    }

    /// The places where the footnote `number` may break between two pages: none for a
    /// footnote that holds a table.
    pub(super) fn note_breaks(&mut self, number: NoteNumber) -> Vec<Break> {
        let Some(story) = self.note_story(number) else {
            return Vec::new();
        };
        let widows: Option<Vec<bool>> = story
            .blocks
            .iter()
            .map(|block| match block {
                Block::Paragraph(paragraph) => Some(self.note_widow(paragraph)),
                Block::Table(_) => None,
            })
            .collect();
        let section = self.note_section();
        let (_, _, lines) = self.placed_note(&section, story, Length::ZERO, number);
        let paragraphs = lines.iter().filter(|line| line.index == 0).count();
        match widows {
            Some(widows) if widows.len() == paragraphs => {
                breaks_of(&lines, &widows, self.note_size(number).0)
            }
            _ => Vec::new(),
        }
    }

    /// Whether a footnote may break on the page being filled. Text columns keep their
    /// footnotes whole, and so does a page that starts with the rest of a footnote.
    fn may_split(&self) -> bool {
        self.column.cell.is_none()
            && self.columns.len() <= 1
            && self.balance.is_none()
            && self.page_notes.part.is_none()
            && self.page_notes.rest.is_none()
    }

    /// Whether a line at `y` with the box `size` lacks room above footnotes of the height
    /// `room` of which the last goes on to the next page. The part of that footnote stands
    /// below the whole height of the line in every compatibility mode, although below mode
    /// 15 a line above whole footnotes needs only the room of its text. The space `after`
    /// counts where it counts above whole footnotes.
    fn part_lacks_room(&self, y: Length, (size, after): (&LineBox, Length), room: Length) -> bool {
        let notes = self.notes_height() + room;
        let after = if self.fitted_notes(notes) > Length::ZERO {
            after
        } else {
            Length::ZERO
        };
        y + size.height + after > self.page_bottom() - notes
    }

    /// The largest part of the last footnote of `numbers`, the new footnotes of a line at `y`
    /// with the box `size` and the space `after`, that leaves the line its room, and the
    /// height that the footnotes of the line then add to the page. The lines bound to the
    /// line need `reserve` below it. The rest of the footnote must have room on one page.
    pub(in super::super) fn split_part(
        &mut self,
        numbers: &[NoteNumber],
        (y, size, after): (Length, &LineBox, Length),
        reserve: Length,
    ) -> Option<(Length, Part)> {
        let number = *numbers.last()?;
        if !self.may_split() {
            return None;
        }
        let last = self.page_notes.page.last().copied();
        let space = self.note_after(number, None);
        let mut before = self.notes_span(last, numbers) - self.note_size(number).0 - space;
        if self.page_notes.page.is_empty() {
            before += self.separator_height(Separator::Normal);
        }
        let page = self.page_bottom() - self.page_top(self.output.pages.len());
        let limit = page - self.separator_height(Separator::Continuation) - space;
        self.note_breaks(number)
            .into_iter()
            .rev()
            .filter(|at| at.rest <= limit)
            .find(|at| !self.part_lacks_room(y + reserve, (size, after), before + at.height))
            .map(|at| {
                let part = Part {
                    number,
                    lines: at.lines,
                    rest: at.rest,
                    bound: 0,
                };
                (before + at.height, part)
            })
    }

    /// What a line at the current position does at the foot of its page. `numbers` are its
    /// new footnotes and `room` their height; `index` is the line's index in its paragraph.
    /// Below a footnote that goes on to the next page, only the lines that widow control
    /// binds to the line of the reference stay.
    pub(in super::super) fn foot(
        &mut self,
        (numbers, room): (&[NoteNumber], Length),
        (size, after): (&LineBox, Length),
        index: usize,
    ) -> Foot {
        if let Some(part) = self.page_notes.part {
            return if part.bound > 0 {
                Foot::Stays
            } else {
                Foot::Leaves
            };
        }
        if !self.lacks_room_at(self.y, size, after, room) {
            return Foot::Stays;
        }
        let reserve = self.page_notes.reserve.filter(|r| r.index == index);
        let height = reserve.map_or(Length::ZERO, |r| r.height);
        match self.split_part(numbers, (self.y, size, after), height) {
            Some((room, part)) => {
                let bound = reserve.map_or(0, |r| r.lines);
                Foot::Splits(room, Part { bound, ..part })
            }
            None => Foot::Leaves,
        }
    }

    /// Records the part of a footnote that stays on the page being filled.
    pub(in super::super) fn keep_part(&mut self, part: Part) {
        self.page_notes.part = Some(part);
    }

    /// Counts a line that stays below a footnote that goes on to the next page.
    pub(in super::super) fn count_bound_line(&mut self) {
        if let Some(part) = self.page_notes.part.as_mut() {
            part.bound = part.bound.saturating_sub(1);
        }
    }

    /// Whether the body of the page being filled has ended at a line whose footnote goes on
    /// to the next page.
    pub(in super::super) fn body_has_ended(&self) -> bool {
        self.page_notes.part.is_some_and(|part| part.bound == 0)
    }

    /// Whether the forecast of a paragraph's lines recorded a footnote that goes on to the
    /// next page, on a page that had none in its footnotes `before` the forecast.
    pub(in super::super) const fn forecast_splits(&self, before: &super::PageNotes) -> bool {
        before.part.is_none() && self.page_notes.part.is_some()
    }

    /// Forgets the lines that the paragraph before bound to a line with a reference.
    pub(in super::super) fn clear_reserve(&mut self) {
        self.page_notes.reserve = None;
    }

    /// Reserves room for the lines that widow control binds to the line with a reference
    /// whose footnote goes on to the next page. `first` is the first line after it, where
    /// the body of the page ends. A first line does not stay alone, so the second line stays
    /// with it; a last line does not go alone, so it stays too.
    pub(in super::super) fn reserve_bound_lines(
        &mut self,
        lines: &[Line],
        (props, mark): (&ParaProps, Option<FaceIndex>),
        first: usize,
    ) {
        let count = lines.len();
        let mut end = first;
        if end < WIDOW_LINES {
            end = WIDOW_LINES.min(count);
        }
        if end + 1 == count {
            end = count;
        }
        let bound = lines.get(first..end).unwrap_or_default();
        let height = bound
            .iter()
            .enumerate()
            .map(|(offset, line)| {
                let last = first + offset + 1 == count;
                self.line_box_of(line, (mark, last), props).height
            })
            .sum();
        self.page_notes.reserve = first.checked_sub(1).map(|index| Reserve {
            index,
            lines: bound.len(),
            height,
        });
    }

    /// Makes the rest of a footnote the first footnote of the next page, below the
    /// continuation separator.
    pub(super) fn carry_note_rest(&mut self, part: Part) {
        let height = self.separator_height(Separator::Continuation)
            + part.rest
            + self.note_after(part.number, None);
        self.page_notes.page = vec![part.number];
        self.page_notes.rest = Some((part.number, part.lines));
        self.page_notes.height = height;
    }

    /// Whether the rest of a footnote waits for a page.
    pub(in super::super) fn rest_waits(&self) -> bool {
        self.page_notes.rest.is_some()
    }
}