f-office-docx 0.1.0

DOCX model and Word's layout rules.
Documentation
//! The address of each paragraph of every story that the text map reads: the body, the header
//! and footer parts that the sections name, the normal footnotes and endnotes, and the text
//! boxes of their paragraphs at any depth; with the hyperlinks and bookmarks of the paragraphs
//! that have some.

use std::collections::HashMap;
use std::num::NonZeroUsize;

use crate::body::{Block, Content, Notes, Paragraph, ParagraphId, Sections};
use crate::floating::Floating;
use crate::layout::{PartStory, SectionLayout, Stories};
use crate::text_blocks::{Address, AddressStep, number};
use crate::text_links::{OpenLink, RunMarks};

/// The address of each paragraph of every story, and the hyperlinks and bookmarks of each
/// paragraph that has some, by the paragraph's ID.
pub(crate) type StoryParagraphs = (
    HashMap<ParagraphId, Address>,
    HashMap<ParagraphId, RunMarks>,
);

/// The address of each paragraph of the body's `blocks`, of the header and footer parts of
/// `sections`, of the normal notes of `notes` and `endnotes`, and of the text boxes in them, by
/// the paragraph's ID, with the hyperlinks and bookmarks of those that have some. A header or
/// footer part that no section names has none, and neither has a note separator. The text of
/// a link that a field starts in one paragraph runs on in the next paragraphs of its story to
/// the field's end.
pub(crate) fn story_paragraphs(
    blocks: &[Block],
    sections: &Sections<SectionLayout>,
    (notes, endnotes): (&Notes, &Notes),
) -> StoryParagraphs {
    let mut walk = Walk::default();
    walk.blocks(blocks, None);
    walk.parts(
        &named_parts(sections, |section| &section.headers),
        AddressStep::Header,
    );
    walk.parts(
        &named_parts(sections, |section| &section.footers),
        AddressStep::Footer,
    );
    walk.notes(notes, AddressStep::Footnote);
    walk.notes(endnotes, AddressStep::Endnote);
    (walk.addresses, walk.marks)
}

/// The parts of the stories that `stories` gives of each of `sections`, each once, in the order
/// in which the sections first name them: in each section the one for most pages, then the one
/// for the first page and the one for even pages.
fn named_parts(
    sections: &Sections<SectionLayout>,
    stories: fn(&SectionLayout) -> &Stories,
) -> Vec<&PartStory> {
    let mut parts: Vec<&PartStory> = Vec::new();
    for section in sections {
        let Stories {
            default,
            first,
            even,
        } = stories(section);
        for part in [default, first, even].into_iter().flatten() {
            if !parts.iter().any(|named| named.part == part.part) {
                parts.push(part);
            }
        }
    }
    parts
}

/// The addresses and the marks found so far, with the hyperlinks open at the place of the walk
/// in its story.
#[derive(Default)]
struct Walk {
    addresses: HashMap<ParagraphId, Address>,
    marks: HashMap<ParagraphId, RunMarks>,
    open: Vec<OpenLink>,
}

/// The story step of a number, such as [`AddressStep::Header`].
type StoryStep = fn(NonZeroUsize) -> AddressStep;

impl Walk {
    /// Gives addresses to the paragraphs of `parts`, the part of each index the story that
    /// `step` names with the number after it.
    fn parts(&mut self, parts: &[&PartStory], step: StoryStep) {
        for (index, part) in parts.iter().enumerate() {
            self.story(&part.blocks, step(number(index + 1)));
        }
    }

    /// Gives addresses to the paragraphs of the normal notes of `notes`, the note of each place
    /// in their order the story that `step` names with the number of that place.
    fn notes(&mut self, notes: &Notes, step: StoryStep) {
        for (index, id) in notes.order.iter().enumerate() {
            if let Some(blocks) = notes.by_id.get(id) {
                self.story(blocks, step(number(index + 1)));
            }
        }
    }

    /// Gives addresses to the paragraphs of the story `story` of `blocks`.
    fn story(&mut self, blocks: &[Block], story: AddressStep) {
        self.open.clear();
        self.blocks(blocks, Some(&Address::top(story)));
    }

    /// Gives addresses to the paragraphs of `blocks`, of the body when `within` is none, or else
    /// of the story, the cell or the text box at that address.
    fn blocks(&mut self, blocks: &[Block], within: Option<&Address>) {
        let (mut paragraphs, mut tables) = (0, 0);
        for block in blocks {
            match block {
                Block::Paragraph(paragraph) => {
                    paragraphs += 1;
                    let address =
                        Address::within(within, AddressStep::Paragraph(number(paragraphs)));
                    let marks = RunMarks::of(paragraph, &mut self.open);
                    if !marks.is_empty() {
                        self.marks.insert(paragraph.id, marks);
                    }
                    self.text_boxes(paragraph, &address);
                    self.addresses.insert(paragraph.id, address);
                }
                Block::Table(table) => {
                    tables += 1;
                    let table_address = Address::within(within, AddressStep::Table(number(tables)));
                    for (row_index, row) in table.rows.iter().enumerate() {
                        let row_address =
                            table_address.then(AddressStep::Row(number(row_index + 1)));
                        for (cell_index, cell) in row.cells.iter().enumerate() {
                            let step = AddressStep::Cell(number(cell_index + 1));
                            self.blocks(&cell.blocks, Some(&row_address.then(step)));
                        }
                    }
                }
            }
        }
    }

    /// Gives addresses to the paragraphs of the text boxes of `paragraph`, whose address is
    /// `address`: each floating or inline drawing's text box and then those of the parts of its
    /// group, in the order of the paragraph.
    fn text_boxes(&mut self, paragraph: &Paragraph, address: &Address) {
        let mut count = 0;
        for content in paragraph.runs.iter().flat_map(|run| &run.content) {
            let drawing = match content {
                Content::Floating(floating) => floating.as_ref(),
                Content::Drawing(drawing) => &drawing.shape,
                _ => continue,
            };
            self.drawing(drawing, address, &mut count);
        }
    }

    /// Gives addresses to the paragraphs of the text box of `drawing` and of the parts of its
    /// group, in the paragraph at `paragraph` whose text boxes before it are `count`.
    fn drawing(&mut self, drawing: &Floating, paragraph: &Address, count: &mut usize) {
        if !drawing.blocks.is_empty() {
            *count += 1;
            let text_box = paragraph.then(AddressStep::TextBox(number(*count)));
            // A text box is a story of its own, whose links the paragraph's do not continue.
            let open = std::mem::take(&mut self.open);
            self.blocks(&drawing.blocks, Some(&text_box));
            self.open = open;
        }
        for (_, _, part) in &drawing.parts {
            self.drawing(part, paragraph, count);
        }
    }
}