f-office-docx 0.2.4

DOCX model and Word's layout rules.
Documentation
//! The HTML divs of the web settings part (`w:divs` of `w:webSettings`, ECMA-376 Part 1,
//! 17.15.2), which a document that was a web page keeps: blocks of paragraphs, one inside
//! another, with margins and borders that Word adds to the paragraphs that name them
//! (`w:divId`, 17.3.1.10).

use std::collections::BTreeSet;
use std::sync::OnceLock;

use f_office_opc::Package;
use f_office_units::Length;
use f_office_xml::NodeId;

use crate::body::ParagraphIds;
use crate::ns::W;
use crate::numbers;
use crate::parts::{self, Role};
use crate::reader::PartReader;
use crate::reader::settings::ReaderSettings;
use crate::{Error, Warnings};

/// The margins of a div (`w:marLeft`, `w:marRight`, `w:marTop` and `w:marBottom`, 17.15.2.21
/// to 17.15.2.24).
const MARGINS: [&str; 4] = ["marLeft", "marRight", "marTop", "marBottom"];

/// The sides of a div's borders (`w:divBdr`, 17.15.2.7).
const SIDES: [&str; 4] = ["top", "left", "bottom", "right"];

/// The divs of a document that change their paragraphs: those with a margin other than 0 or a
/// border line, and every div inside one. Word adds the margins and borders of a div and of the
/// divs around it to its paragraphs; F-Office lays the paragraphs out without them, and the layout
/// warns of each paragraph of such a div.
///
/// The divs are read from the web settings part on the first question about a div, as the
/// package reads a relationships part on its first use. Few paragraphs name a div, and a
/// document saved from HTML can carry a large `webSettings.xml` part that no paragraph references,
/// so parsing it lazily avoids unnecessary work.
#[derive(Debug, Default)]
pub struct HtmlDivs<'p> {
    /// The package and the name of its web settings part, when it has one, with the
    /// document's source of paragraph IDs and its reader's settings, which every part reader
    /// takes.
    part: Option<(&'p Package, String, &'p ParagraphIds, ReaderSettings)>,
    /// The divs that shape their paragraphs, with the warnings of the part's values, once a
    /// question has read the part.
    read: OnceLock<Result<(BTreeSet<i64>, Warnings), Error>>,
}

/// Cached result of lazily reading `webSettings.xml`, preserved across incremental steps.
pub(crate) type HtmlDivsCache = Option<Result<(BTreeSet<i64>, Warnings), Error>>;

impl<'p> HtmlDivs<'p> {
    /// Rehydrates lazy web-settings state from a previously cached read result.
    pub(crate) fn from_cache(
        package: &'p Package,
        name: Option<String>,
        (ids, settings): (&'p ParagraphIds, ReaderSettings),
        cache: HtmlDivsCache,
    ) -> Self {
        let read = OnceLock::new();
        if let Some(value) = cache {
            let _ = read.set(value);
        }
        Self {
            part: name.map(|name| (package, name, ids, settings)),
            read,
        }
    }

    /// Extracts the cached read result without dropping it.
    pub(crate) fn into_cache(self) -> HtmlDivsCache {
        self.read.into_inner()
    }

    /// No div, as in a document without a web settings part: the context of the layout's
    /// tests.
    #[cfg(test)]
    #[must_use]
    pub(crate) const fn none() -> Self {
        Self {
            part: None,
            read: OnceLock::new(),
        }
    }

    /// The divs of the web settings part `name` of `package`, which the first question reads
    /// with the document's source of paragraph IDs `ids` and its reader's settings `settings`.
    pub(crate) fn of_part(
        package: &'p Package,
        name: Option<String>,
        (ids, settings): (&'p ParagraphIds, ReaderSettings),
    ) -> Self {
        Self {
            part: name.map(|name| (package, name, ids, settings)),
            read: OnceLock::new(),
        }
    }

    /// Whether the div `id`, or a div around it, has a margin other than 0 or a border line.
    #[must_use]
    pub fn shapes(&self, id: i64) -> bool {
        self.read()
            .as_ref()
            .is_ok_and(|(shaping, _)| shaping.contains(&id))
    }

    /// The divs that shape their paragraphs, read on the first call.
    fn read(&self) -> &Result<(BTreeSet<i64>, Warnings), Error> {
        self.read.get_or_init(|| {
            let mut warnings = Warnings::new();
            let Some((package, name, ids, settings)) = &self.part else {
                return Ok((BTreeSet::new(), warnings));
            };
            let role = (Role::WebSettings, Some(name.clone()));
            let mut reading = parts::Reading {
                warnings: &mut warnings,
                ids,
                settings: *settings,
                notes: None,
                colors: f_office_drawingml::color::SchemeColors::default(),
                styles: None,
                small_frac: crate::props::SmallFractions::Off,
            };
            parts::read(package, role, &mut reading, shaping).map(|divs| (divs, warnings))
        })
    }

    /// The warnings of the web settings part, when a question read it, and none otherwise.
    ///
    /// # Errors
    ///
    /// When a question read the part and it did not read, as for any part whose role stops
    /// the document.
    pub(crate) fn finish(self) -> Result<Warnings, Error> {
        self.read.into_inner().map_or_else(
            || Ok(Warnings::new()),
            |read| read.map(|(_, warnings)| warnings),
        )
    }
}

/// The IDs of the divs that shape their paragraphs, from the root element `w:webSettings`: each
/// div list (`w:divs`, and `w:divsChild` inside a div) with whether a div around it shapes it.
/// It walks the lists with a stack, so that the depth of the part's divs takes no depth of
/// calls; the part's parse limits the depth.
fn shaping(reader: &mut PartReader, root: NodeId) -> BTreeSet<i64> {
    let doc = reader.doc;
    let mut shaping = BTreeSet::new();
    let mut lists: Vec<(NodeId, bool)> = doc
        .child(root, W, "divs")
        .map(|list| (list, false))
        .into_iter()
        .collect();
    while let Some((list, outer)) = lists.pop() {
        for div in doc
            .child_elements(list)
            .filter(|&div| doc.is(div, W, "div"))
        {
            let shapes = outer || own_shape(reader, div);
            if shapes && let Some(id) = reader.number(div, "id", numbers::ANY) {
                shaping.insert(id);
            }
            if let Some(inner) = doc.child(div, W, "divsChild") {
                lists.push((inner, shapes));
            }
        }
    }
    shaping
}

/// Whether a div has a margin other than 0, or a border side with a line.
fn own_shape(reader: &mut PartReader, div: NodeId) -> bool {
    let doc = reader.doc;
    let margin = MARGINS.iter().any(|&name| {
        doc.child(div, W, name)
            .and_then(|margin| reader.twips(margin, "val"))
            .is_some_and(|length| length != Length::ZERO)
    });
    let border = doc.child(div, W, "divBdr").is_some_and(|borders| {
        SIDES.iter().any(|&name| {
            doc.child(borders, W, name)
                .and_then(|side| crate::props::read_border(reader, side))
                .is_some()
        })
    });
    margin || border
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeSet;

    use f_office_xml::{Document, Limits};

    use super::{HtmlDivs, shaping};
    use crate::ns::W;
    use crate::reader::PartReader;

    fn divs(inner: &str) -> BTreeSet<i64> {
        let xml =
            format!(r#"<w:webSettings xmlns:w="{W}"><w:divs>{inner}</w:divs></w:webSettings>"#);
        let doc = Document::parse(xml.as_bytes(), &Limits::default()).unwrap();
        let mut reader = PartReader::new(&doc);
        shaping(&mut reader, doc.root().unwrap())
    }

    #[test]
    fn a_div_with_a_margin_or_a_border_line_shapes_its_paragraphs_and_its_inner_divs() {
        let read = divs(concat!(
            r#"<w:div w:id="1"><w:marLeft w:val="0"/><w:marTop w:val="0"/>"#,
            r#"<w:divBdr><w:top w:val="none" w:sz="0" w:space="0" w:color="auto"/></w:divBdr>"#,
            r#"<w:divsChild><w:div w:id="2"><w:marLeft w:val="480"/>"#,
            r#"<w:divsChild><w:div w:id="3"/></w:divsChild></w:div></w:divsChild></w:div>"#,
            r#"<w:div w:id="4"><w:marTop w:val="250"/></w:div>"#,
            r#"<w:div w:id="5"><w:divBdr><w:left w:val="single" w:sz="4" w:space="0" w:color="auto"/></w:divBdr></w:div>"#,
            r#"<w:div w:id="6"/>"#,
        ));
        // The div of no margin and no line, and the one without them, shape nothing; the
        // div inside a div with a margin shapes its paragraphs with the outer margin.
        assert_eq!(read, BTreeSet::from([2, 3, 4, 5]));
    }

    #[test]
    fn no_web_settings_part_shapes_no_paragraph_and_gives_no_warning() {
        let none = HtmlDivs::none();
        assert!(!none.shapes(1));
        assert!(none.finish().unwrap().is_empty());
        assert!(divs("").is_empty());
    }
}