f-office-docx 0.2.4

DOCX model and Word's layout rules.
Documentation
//! What a layout adds to its pass and gives back.

use std::collections::HashMap;
use std::rc::Rc;

use f_office_paint::Page;
use f_office_units::Length;

use super::{PageInfo, PageWraps, PlacedLine, style_refs};
use crate::body::InlineDrawing;
use crate::lines::DrawingIndex;
use crate::picture::Picture;

/// The body's area on a page, down the page: from below a header that reaches past the top
/// margin to above a footer that reaches past the bottom margin, with the height of the page's
/// footnotes, which lie above that end.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct BodyArea {
    /// The top of the area.
    pub(super) top: Length,
    /// The end of the area, below the footnotes.
    pub(super) end: Length,
    /// The height of the page's footnotes.
    pub(super) notes: Length,
}

/// What a layout adds to its pass and gives back: its pages and their records, its line
/// records, the objects that its pieces name, what the next pass shows, the counters that run
/// through the whole flow, and the warnings. A body's layout makes the pages of the pass; a
/// story's layout has an output of its own ([`Self::for_story`]), whose warnings join those of
/// the layout that holds the story ([`Self::join_warnings_of`]).
#[derive(Default)]
pub(super) struct PassOutput {
    /// The pages filled so far.
    pub(super) pages: Vec<Page>,
    /// The section and number of each finished page.
    pub(super) page_infos: Vec<PageInfo>,
    /// The body's area on each finished page.
    pub(super) body_areas: Vec<BodyArea>,
    /// The page and the height of the footnotes that each floating drawing of the body that
    /// counts from the body's area took, which the end of the pass compares with the footnotes
    /// of that page.
    pub(super) margin_notes: Vec<(usize, Length)>,
    /// The indexes of the blank pages that put a section on the right side.
    pub(super) blank_pages: Vec<usize>,
    /// The lines placed so far.
    pub(super) placed: Vec<PlacedLine>,
    /// The story parts of the lines placed so far.
    pub(super) story_parts: StoryParts,
    /// The pictures of the inline objects measured so far, which object pieces name by index.
    pub(super) pictures: Vec<Picture>,
    /// The inline shapes and text boxes measured so far, which object pieces name by index. Each
    /// shares the paragraph's drawing, so that a measure copies no text box.
    pub(super) drawings: Vec<Rc<InlineDrawing>>,
    /// The endnotes in the order of their first references.
    pub(super) endnotes: Vec<super::notes::NumberedNote>,
    /// The wraps of the drawings placed from a page or its margins in this pass.
    pub(super) found: PageWraps,
    /// The later anchors found in this pass ([`super::LaterAnchors`]), each by its paragraph
    /// and its index among the paragraph's drawings, in the order of finding.
    pub(super) found_later: Vec<(crate::body::ParagraphId, usize)>,
    /// The page number text of each bookmark in this pass.
    pub(super) found_bookmarks: BookmarkRecord<String>,
    /// The paragraph number contexts of the bookmarks in this pass, which `REF` fields of the
    /// next pass show.
    pub(super) found_numbers: BookmarkRecord<crate::numbering::NumberContext>,
    /// The styled text of the pages, which a body layout records while it fills its pages.
    pub(super) styled: Option<style_refs::Record>,
    /// The styled text of the body's pages once they are filled.
    pub(super) style_pages: Option<std::rc::Rc<style_refs::StyledPages>>,
    /// The number of the last chapter heading of the body so far, for page numbers that
    /// start with a chapter number.
    pub(super) chapter_number: Option<i64>,
    /// The body lines counted for line numbers, and the page of the last one.
    pub(super) line_count: (i64, usize),
    /// The tables whose rows the layout of this story started so far, nested tables too,
    /// which number the cells of the line records.
    pub(super) tables: usize,
    /// The widths of the grid columns of each table whose rows the layout of this story
    /// started, by its number of [`Self::tables`], in the order of the starts: a table that a
    /// rewound trial starts again has a later entry of the same number.
    pub(super) table_columns: Vec<super::TableColumns>,
    /// The footnotes numbered so far.
    pub(super) notes: super::notes::NoteNumbers,
    /// The warnings of this layout and of the stories that it holds.
    pub(super) warnings: crate::Warnings,
    /// The warnings that the layouts of each story that warns once gave so far, by story, each
    /// with the largest count that one layout of the story gave ([`Self::join_story_warnings`],
    /// [`super::StoryKind::key`]); a story that gave none has no entry.
    pub(super) story_warnings: Vec<(StoryKey, crate::Warnings)>,
}

/// The first value that a layout pass records for each bookmark (a bookmark
/// record), such as its page number text, with the names in the order of their first
/// record, so that the rewind of a trial layout takes back what the trial recorded
/// ([`super::columns::RowMark`]). A bookmark keeps the value of its first record in the
/// layout that the pass keeps.
pub(super) struct BookmarkRecord<V> {
    /// The value of each bookmark, by its name.
    values: HashMap<String, V>,
    /// The names, in the order of their first record.
    names: Vec<String>,
}

impl<V> Default for BookmarkRecord<V> {
    fn default() -> Self {
        Self {
            values: HashMap::new(),
            names: Vec::new(),
        }
    }
}

impl<V> BookmarkRecord<V> {
    /// Records the value that `value` gives for the bookmark `name`, unless the bookmark has
    /// one.
    pub(super) fn record(&mut self, name: &str, value: impl FnOnce() -> V) {
        if self.values.contains_key(name) {
            return;
        }
        self.values.insert(name.to_owned(), value());
        self.names.push(name.to_owned());
    }

    /// The number of the bookmarks recorded, which a mark keeps.
    pub(super) fn count(&self) -> usize {
        self.names.len()
    }

    /// Takes back the records after the first `count`.
    pub(super) fn take_back(&mut self, count: usize) {
        while self.names.len() > count {
            if let Some(name) = self.names.pop() {
                self.values.remove(&name);
            }
        }
    }

    /// The value of each bookmark, by its name, for the next pass.
    pub(super) fn into_values(self) -> HashMap<String, V> {
        self.values
    }
}

/// The name of a story whose warnings count once among the stories of a pass
/// ([`super::StoryKind::key`]), so that each layout of the story, on any page or to measure
/// it, has the same key, whatever blocks the layout reads it from.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) enum StoryKey {
    /// A header or a footer, by the name of its part ([`super::PartStory`]). The name is the
    /// whole one that the package reader gives: the shortened name that a warning keeps
    /// (`f_office_warnings::Name`) could give two parts one key.
    Part(std::rc::Rc<str>),
    /// A footnote, by its ID in the footnotes part.
    Footnote(crate::body::NoteId),
    /// A separator of the footnotes, by its kind. It needs no note kind: the endnotes and
    /// their separator flow in the body and are no story.
    Separator(super::notes::Separator),
}

/// The warnings of a layout before a trial layout that the layout may take back and lay out
/// again, such as a table row where it may not fit ([`PassOutput::start_trial`]).
pub(super) struct WarningsTrial {
    /// The warnings before the trial, which the trial's layout does not touch.
    before: crate::Warnings,
    /// The warnings of each story that warns once before the trial.
    story_warnings: Vec<(StoryKey, crate::Warnings)>,
}

impl PassOutput {
    /// Starts a trial layout: the warnings that come from here on are the trial's until
    /// [`Self::end_trial`].
    pub(super) fn start_trial(&mut self) -> WarningsTrial {
        WarningsTrial {
            before: std::mem::take(&mut self.warnings),
            story_warnings: self.story_warnings.clone(),
        }
    }

    /// Ends a trial layout: its warnings follow those from before it when the layout keeps
    /// it, and go when the layout takes it back to lay its blocks out again, which gives them
    /// again.
    pub(super) fn end_trial(&mut self, trial: WarningsTrial, kept: bool) {
        let warnings = std::mem::replace(&mut self.warnings, trial.before);
        if kept {
            self.warnings.extend(warnings, std::convert::identity);
        } else {
            self.story_warnings = trial.story_warnings;
        }
    }

    /// The output of a story that a layout makes: its own pages, lines, objects, counters,
    /// footnote numbering and warnings.
    pub(super) fn for_story() -> Self {
        Self::default()
    }

    /// Takes the warnings of the output of a story that this layout holds, when the story's
    /// layout ends, so that each of them counts once here.
    pub(super) fn join_warnings_of(&mut self, story: &mut Self) {
        let warnings = std::mem::take(&mut story.warnings);
        self.warnings.extend(warnings, std::convert::identity);
    }

    /// Adds the warnings of a layout of the story `key` that warns once, when the layout ends.
    /// The layout lays out such a story more than once, as a header on each page that shows it
    /// and to measure it, so each warning counts here only up to the largest count that one
    /// layout of the story gave: one warning for each paragraph of the story, whatever the
    /// number of pages and measures.
    pub(super) fn join_story_warnings(&mut self, key: StoryKey, warnings: crate::Warnings) {
        if warnings.is_empty() {
            return;
        }
        let found = self
            .story_warnings
            .iter()
            .position(|(seen, _)| *seen == key);
        let at = found.unwrap_or_else(|| {
            let at = self.story_warnings.len();
            self.story_warnings.push((key, crate::Warnings::new()));
            at
        });
        let Some((_, seen)) = self.story_warnings.get_mut(at) else {
            return;
        };
        for (warning, count) in warnings {
            let more = count.saturating_sub(seen.count(&warning));
            seen.add(warning.clone(), more);
            self.warnings.add(warning, more);
        }
    }

    /// Keeps an inline drawing that an object piece shows, and gives the index that the
    /// piece names.
    pub(super) fn add_drawing(&mut self, drawing: Rc<InlineDrawing>) -> DrawingIndex {
        let index = DrawingIndex::new(self.drawings.len());
        self.drawings.push(drawing);
        index
    }

    /// The inline drawing that an object piece names.
    pub(super) fn drawing(&self, index: DrawingIndex) -> Option<&Rc<InlineDrawing>> {
        self.drawings.get(index.get())
    }
}

#[cfg(test)]
mod tests {
    use super::{BookmarkRecord, PassOutput, StoryKey};
    use crate::Warning;
    use f_office_warnings::Name;

    #[test]
    fn keeps_the_first_record_of_a_bookmark_and_takes_back_the_later_ones() {
        let mut record = BookmarkRecord::default();
        record.record("a", || 1);
        record.record("a", || 2);
        let count = record.count();
        record.record("b", || 3);
        record.record("a", || 4);
        assert_eq!(record.count(), 2);
        record.take_back(count);
        record.record("c", || 5);
        let mut values: Vec<(String, i32)> = record.into_values().into_iter().collect();
        values.sort_unstable();
        assert_eq!(values, [("a".to_owned(), 1), ("c".to_owned(), 5)]);
    }

    fn substituted() -> Warning {
        Warning::FontSubstituted {
            asked: Name::new("a"),
            used: Some(Name::new("b")),
            version: None,
            layout: crate::SubstituteLayout::Widths,
        }
    }

    #[test]
    fn a_story_has_its_own_output_and_its_warnings_join_its_holder() {
        let mut body = PassOutput {
            tables: 2,
            line_count: (3, 1),
            ..PassOutput::default()
        };
        body.warnings.push(substituted());
        let mut story = PassOutput::for_story();
        assert_eq!((story.tables, story.line_count), (0, (0, 0)));
        assert!(story.warnings.is_empty());
        story.warnings.push(substituted());
        story.warnings.push(substituted());
        body.join_warnings_of(&mut story);
        assert!(story.warnings.is_empty());
        let warnings: Vec<_> = body.warnings.into_iter().collect();
        assert_eq!(warnings, [(substituted(), 3)]);
    }

    #[test]
    fn the_layouts_of_one_story_that_warns_once_warn_as_one_layout_of_it() {
        let header = StoryKey::Part("word/header1.xml".into());
        let footer = StoryKey::Part("word/footer1.xml".into());
        let mut body = PassOutput::default();
        // The story warns twice in one layout and once in another; the other story once.
        for (key, times) in [
            (&header, 2),
            (&header, 1),
            (&header, 2),
            (&footer, 1),
            (&footer, 1),
        ] {
            let mut warnings = crate::Warnings::new();
            warnings.add(substituted(), times);
            body.join_story_warnings(key.clone(), warnings);
        }
        // A layout without warnings keeps no entry: a third story, with a key of its own.
        let other = StoryKey::Footnote(crate::body::NoteId::of(1));
        body.join_story_warnings(other, crate::Warnings::new());
        assert_eq!(body.story_warnings.len(), 2);
        let warnings: Vec<_> = body.warnings.into_iter().collect();
        assert_eq!(warnings, [(substituted(), 3)]);
    }

    #[test]
    fn each_pass_starts_with_no_warnings() {
        let mut first = PassOutput::default();
        first.warnings.push(substituted());
        assert!(PassOutput::default().warnings.is_empty());
    }
}

/// The story parts of the lines that a layout places, which only their records read.
#[derive(Default)]
pub(super) struct StoryParts {
    /// The number of the frames and text boxes whose lines were placed so far, which numbers
    /// the next one's story part.
    pub(super) count: u32,
    /// The part of the lines that it places now: the endnotes while they flow, with their
    /// separator, and else the story's own text.
    pub(super) current: super::StoryPart,
}