f-office-docx 0.1.0

DOCX model and Word's layout rules.
Documentation
//! Sections: page size, margins, headers, footers and page numbers that change within a
//! body.

use crate::body::{Block, LineNumberRestart, Section, SectionStart};
use crate::styles::SideMargins;

use super::{Layout, PageInfo, SectionLayout};

/// The place of one section among the sections of a layout, from 0. Only [`Layout::adopt`]
/// makes one, after it found its section there, besides [`SectionIndex::FIRST`], and the
/// sections of a layout do not change, so that every index names one of them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct SectionIndex(usize);

impl SectionIndex {
    /// The first section, which every layout has.
    pub(super) const FIRST: Self = Self(0);
}

/// Whether a page number is odd or even. With different odd and even headers, the even
/// numbers take the even header and footer; mirrored margins swap the sides of an even page;
/// and a section that starts on an odd or even page starts on a page of that number.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Parity {
    /// An odd number, a right-hand page.
    Odd,
    /// An even number, a left-hand page.
    Even,
}

impl Parity {
    /// The parity of the page number `number`.
    pub(super) const fn of(number: i64) -> Self {
        if number % 2 == 0 {
            Self::Even
        } else {
            Self::Odd
        }
    }
}

impl Layout<'_> {
    /// Lays out the blocks of each section in turn.
    pub(super) fn sections_flow(&mut self, blocks: &[Block]) {
        let mut begin = 0;
        for index in 0..self.sections.count() {
            let Some((end, start)) = self.sections.get(index).map(|s| (s.end, s.start)) else {
                continue;
            };
            if index > 0 {
                self.start_section(index, start);
            }
            let end = end.clamp(begin, blocks.len());
            let part = blocks.get(begin..end).unwrap_or_default();
            self.section_end_paragraph = match part.last() {
                Some(Block::Paragraph(paragraph)) if index + 1 < self.sections.count() => {
                    Some(paragraph.id)
                }
                _ => None,
            };
            // Columns before a continuous section break share their text evenly.
            let continuous = self
                .sections
                .get(index + 1)
                .is_some_and(|s| s.start == SectionStart::Continuous);
            if continuous && self.columns.len() > 1 {
                self.balanced_blocks(part);
            } else {
                self.blocks(part);
                if continuous && matches!(blocks.get(end), Some(Block::Paragraph(_))) {
                    self.hidden_section_end(part);
                }
            }
            begin = end;
        }
    }

    /// The empty paragraph that ends a section of one column before a continuous section, when
    /// it shows nothing, stands between the paragraph before it and the next section's first
    /// paragraph without a line, as below balanced columns: the space after of the paragraph
    /// before it stays in the section, and the next paragraph has only the part of its space
    /// before beyond the empty paragraph's space after. The empty paragraph's space before has
    /// no effect.
    ///
    /// Where the target keeps those spaces ([`super::decisions::spaced_section_end`]).
    fn hidden_section_end(&mut self, blocks: &[Block]) {
        let Some(blocks) = super::decisions::spaced_section_end(&self.context.quirks, blocks)
        else {
            return;
        };
        if let Some((after, props)) = self.hidden_end(blocks) {
            self.y += after;
            self.section_previous = Some(super::Previous::of(&props));
        }
    }

    /// Starts a section on a new page, or on this page for a continuous section.
    fn start_section(&mut self, index: usize, start: SectionStart) {
        if start == SectionStart::Continuous {
            // The section before ends on this page with its columns.
            self.paint_column_separators();
            // The margins and the columns change at once, the page size and the headers on
            // the next page.
            if let Some(next) = self.sections.get(index).map(|s| s.section) {
                self.take_side_margins(&next);
                self.section.columns = next.columns;
                self.set_columns();
            }
            self.pending = Some(index);
            return;
        }
        // A section after a page break starts on the page that the break began, when nothing
        // but empty paragraphs has come onto it. Their line numbers and fills go with them,
        // and the count of numbered lines goes on from the break.
        let from_break = self.page_from_break == Some(self.output.pages.len());
        if from_break && self.items.count() == self.break_numbers.0 {
            self.items.cut(0);
            self.output.line_count = self.break_numbers.1;
            self.break_numbers.0 = 0;
        }
        if !(from_break && self.page_is_empty()) {
            self.new_page();
        }
        // The space after the last paragraph of the section stays on its page.
        self.section_previous = self.previous.take();
        self.adopt(index);
        let number = self.page_number(self.output.pages.len());
        // With different odd and even headers, a section that restarts its page numbers puts
        // an odd number on a right-hand page and an even number on a left-hand page.
        let restarts = self.sections.get(index).is_some_and(|s| s.restarts_numbers);
        let right_hand = self.right_hand_next();
        let other_side = self.settings.even_and_odd_headers
            && restarts
            && (Parity::of(number) == Parity::Odd) != right_hand;
        let wrong = other_side
            || match start {
                SectionStart::EvenPage => Parity::of(number) != Parity::Even,
                SectionStart::OddPage => Parity::of(number) != Parity::Odd,
                SectionStart::NextPage | SectionStart::Continuous => false,
            };
        if wrong {
            // Word leaves a blank page, without a header or a footer, to start the section on
            // the right side. The section starts on the page after it.
            self.output.blank_pages.push(self.output.pages.len());
            self.new_page();
            self.adopt(index);
        }
        self.move_to_body_top(self.output.pages.len());
        self.column_top = self.y;
    }

    /// Whether the page being filled is a right-hand page for a section that restarts its page
    /// numbers: by its place in the document, the odd places, or by the number of the page
    /// before it, after which it takes the other side; the first page is a right-hand page.
    fn right_hand_next(&self) -> bool {
        super::decisions::restart_side(
            &self.context.quirks,
            || self.output.pages.len().is_multiple_of(2),
            || {
                self.output
                    .page_infos
                    .last()
                    .is_none_or(|before| Parity::of(before.number) == Parity::Even)
            },
        )
    }

    /// Makes a section the current one from the page being filled on.
    pub(super) fn adopt(&mut self, index: usize) {
        let Some((section, restarts)) = self
            .sections
            .get(index)
            .map(|s| (s.section, s.restarts_numbers))
        else {
            return;
        };
        let next = self
            .output
            .page_infos
            .last()
            .map_or(section.first_page_number, |p| p.number.saturating_add(1));
        self.number_start = if restarts {
            section.first_page_number
        } else {
            next
        };
        let restart = section.line_numbers.map(|n| n.restart);
        if restart != Some(LineNumberRestart::Continuous) {
            self.output.line_count.0 = 0;
        }
        self.section = section;
        self.device = self.device.with_page(
            self.section.width,
            self.section.height,
            self.section.orientation,
        );
        self.section_index = SectionIndex(index);
        self.section_first_page = self.output.pages.len();
        self.section_title_page = Some(self.output.pages.len());
        self.take_side_margins(&section);
        self.set_columns();
        self.measure_body();
        self.start_wraps();
    }

    /// The section and the number of a page, finished or being filled.
    pub(super) fn page_info(&self, index: usize) -> PageInfo {
        if let Some(info) = self.output.page_infos.get(index) {
            return *info;
        }
        let offset = index.saturating_sub(self.section_first_page);
        PageInfo {
            section: self.section_index,
            number: self
                .number_start
                .saturating_add(f_office_units::count_factor(offset)),
            first: self.section_title_page == Some(index),
        }
    }

    /// The section `index` of the flow.
    pub(super) fn section_layout(&self, index: SectionIndex) -> &SectionLayout {
        // `get` finds every index that `adopt` made. A lookup by a number gives an `Option`,
        // and the workspace lints refuse `expect` and indexing, so a release build gives the
        // first section for the case that no index can reach; a debug build, as the tests
        // run, stops there.
        debug_assert!(
            index.0 < self.sections.count(),
            "a section index names a section of its layout"
        );
        self.sections
            .get(index.0)
            .unwrap_or_else(|| self.sections.first())
    }

    /// The page settings of a section, with its own side margins.
    pub(super) fn section_of(&self, index: SectionIndex) -> Section {
        self.section_layout(index).section
    }

    /// Whether the page with the number `number` swaps the side margins of its section: a page
    /// with an even number does when the settings mirror the margins.
    const fn mirrors(&self, number: i64) -> bool {
        matches!(self.settings.side_margins, SideMargins::Mirrored)
            && matches!(Parity::of(number), Parity::Even)
    }

    /// The section of the page `index`, with the side margins of its side.
    pub(super) fn page_section(&self, index: usize) -> Section {
        let info = self.page_info(index);
        let section = self.section_of(info.section);
        let (left, right) = section.side_margins(self.mirrors(info.number));
        Section {
            right,
            left,
            ..section
        }
    }

    /// Gives the page being filled the side margins of `section` for its side.
    pub(super) fn take_side_margins(&mut self, section: &Section) {
        let number = self.page_number(self.output.pages.len());
        (self.section.left, self.section.right) = section.side_margins(self.mirrors(number));
    }
}

#[cfg(test)]
mod tests {
    use std::fmt::Write as _;

    use super::Parity;
    use crate::body::Body;
    use crate::layout::testing::{Fake, base_context, find, p, parse, sections_of};
    use crate::layout::{Context, Layout, Stories};
    use crate::ns::W;
    use crate::quirks::{BodyFieldResults, RestartSide};
    use crate::reader::PartReader;
    use crate::styles::{FontTable, Settings, Styles, Theme};
    use crate::text::{Shaper, ShaperSettings};

    /// The page, from 0, of the second section's first glyph in a body of two sections under
    /// different headers of odd and even pages: the first starts its page numbers at `first`
    /// and holds `pages` pages, and the second starts on the next page and restarts its
    /// numbers at `restart`, on the base target with the restart side `side`.
    fn second_section_page(side: RestartSide, first: u32, pages: usize, restart: u32) -> usize {
        let page = r#"<w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/>"#;
        let mut body = String::new();
        for _ in 1..pages {
            body.push_str(&p("A"));
            body.push_str(r#"<w:p><w:r><w:br w:type="page"/></w:r></w:p>"#);
        }
        write!(
            body,
            r#"<w:p><w:pPr><w:sectPr>{page}<w:pgNumType w:start="{first}"/></w:sectPr></w:pPr><w:r><w:t>A</w:t></w:r></w:p>"#
        )
        .unwrap();
        body.push_str(&p("B"));
        write!(
            body,
            r#"<w:sectPr>{page}<w:pgNumType w:start="{restart}"/></w:sectPr>"#
        )
        .unwrap();
        let doc = parse(&format!(r#"<w:body xmlns:w="{W}">{body}</w:body>"#));
        let quirks = crate::profile::Profile::base().with_variant(side).quirks();
        let settings = Settings {
            even_and_odd_headers: true,
            ..Settings::default()
        };
        let body = Body::read(
            &mut PartReader::new(&doc),
            doc.root().unwrap(),
            (
                crate::reader::settings::ReaderSettings::of(&quirks)
                    .with_body_results(BodyFieldResults::ComputesFields),
                settings.mode_rules,
            ),
        );
        let styles = Styles::default();
        let sections = sections_of(&body, &Stories::default());
        let context = Context {
            quirks,
            ..base_context(&styles, &settings)
        };
        let stories = context.for_stories();
        let (theme, fonts) = (Theme::default(), FontTable::default());
        let list = Layout::new(
            (&context, &stories),
            &sections,
            Shaper::new(&Fake, &theme, &fonts, &ShaperSettings::base()),
        )
        .run_with_wraps(&body)
        .list;
        find(&list, 'B').0
    }

    #[test]
    fn a_restarted_section_takes_its_side_from_the_number_of_the_page_before_where_the_target_does()
    {
        // The first number, the pages and the restart of each case. After a first page
        // numbered 1, both variants make the second page a left-hand page: a restart at 1 leaves
        // a blank page, one at 2 none. After a first page numbered 2, the second page is a
        // left-hand page by its place and a right-hand page by the number before it. After
        // pages 42 and 43, the third page is a right-hand page by its place and a left-hand page
        // by the number before it.
        let cases = [(1, 1, 1), (1, 1, 2), (2, 1, 1), (2, 1, 2), (42, 2, 1)];
        let pages = |side| {
            cases.map(|(first, count, restart)| second_section_page(side, first, count, restart))
        };
        assert_eq!(pages(RestartSide::Place), [2, 1, 2, 1, 2]);
        assert_eq!(pages(RestartSide::PreviousNumber), [2, 1, 1, 2, 3]);
    }

    #[test]
    fn tells_odd_and_even_page_numbers_apart_also_below_one() {
        let parities = [-3, -2, 0, 1, 2, 7].map(Parity::of);
        assert_eq!(
            parities,
            [
                Parity::Odd,
                Parity::Even,
                Parity::Even,
                Parity::Odd,
                Parity::Even,
                Parity::Odd
            ]
        );
    }
}