f-office-docx 0.2.3

DOCX model and Word's layout rules.
Documentation
//! The parts that the reader reads, and one policy for a part that does not read.
//!
//! Only the main document part is required: when it is not XML that the reader takes, the
//! document stops with an error. Every other part that does not read is skipped with a warning,
//! and the layout goes on as if the package lacked it, with the default of a missing part: the
//! styles of Word's own template for the styles part, the theme fonts of the target's template
//! for the theme, and the defaults of ECMA-376 for the others. A picture, chart or SmartArt
//! graphic that does not read is left out with its own warning ([`Warning::DrawingSkipped`]).
//! Word answers a broken part with a repair dialog and no page, so no page of Word decides this:
//! it is F-Office's policy, not a rule of Word.

use f_office_opc::{Package, Relationship};
use f_office_warnings::Name;
use f_office_xml::{Document, NodeId};

use crate::body::ParagraphIds;
use crate::reader::PartReader;
use crate::reader::settings::ReaderSettings;
use crate::styles::Styles;
use crate::warnings::{Reason, Warning, Warnings};
use crate::{Error, ns};

/// The name that [`relationships`] takes for the package itself, whose relationships part is
/// `_rels/.rels`.
pub(crate) const PACKAGE: &str = "";

/// A part that the reader reads, by its role in the package.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Role {
    /// The main document part, which holds the body.
    Main,
    /// The relationships part of a part or of the package.
    Relationships,
    /// The document settings.
    Settings,
    /// The web settings, which hold the HTML divs of a document that was a web page.
    WebSettings,
    /// The style definitions.
    Styles,
    /// The theme.
    Theme,
    /// The font table.
    FontTable,
    /// The numbering definitions.
    Numbering,
    /// The footnotes or the endnotes.
    Notes,
    /// The comments, or the part that links their replies.
    Comments,
    /// A header or a footer.
    Story,
    /// The package's custom properties.
    CustomProperties,
}

/// What a part that does not read does to the document.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum WhenBad {
    /// The document stops with an error.
    Stops,
    /// The part is skipped with a warning, and the layout goes on as if the package lacked it.
    Skipped,
}

impl Role {
    /// The policy: what a part of this role does to the document when it does not read.
    pub(crate) const fn when_bad(self) -> WhenBad {
        match self {
            Self::Main => WhenBad::Stops,
            Self::Relationships
            | Self::Settings
            | Self::WebSettings
            | Self::Styles
            | Self::Theme
            | Self::FontTable
            | Self::Numbering
            | Self::Notes
            | Self::Comments
            | Self::Story
            | Self::CustomProperties => WhenBad::Skipped,
        }
    }
}

/// Parses the bytes of the XML part `name` of `package`, within the package's limits, with the
/// strict namespaces read as the transitional ones, and finds its root element. It warns of
/// each namespace prefix that the part uses without a declaration.
pub(crate) fn xml(
    package: &Package,
    (name, bytes): (&str, &[u8]),
    warnings: &mut Warnings,
) -> Result<(Document, NodeId), f_office_xml::Error> {
    let doc = Document::parse_with_aliases(bytes, &package.limits().xml, ns::STRICT_ALIASES)?;
    let root = doc.root()?;
    undeclared_prefixes(name, doc.undeclared_prefixes(), warnings);
    Ok((doc, root))
}

/// Warns of each namespace prefix that the part `name` uses without a declaration.
pub(crate) fn undeclared_prefixes(name: &str, prefixes: &[String], warnings: &mut Warnings) {
    for prefix in prefixes {
        warnings.push(Warning::UndeclaredPrefix {
            part: Name::new(name),
            prefix: Name::new(prefix),
        });
    }
}

/// Parses already-read `bytes` of a part that holds text, with tracked revisions accepted
/// according to `settings`.
pub(crate) fn parse_text_bytes(
    package: &Package,
    (role, name): (Role, &str),
    bytes: &[u8],
    settings: ReaderSettings,
    warnings: &mut Warnings,
) -> Result<Option<(Document, NodeId)>, Error> {
    let mut read = match (xml(package, (name, bytes), warnings), role.when_bad()) {
        (Ok(read), _) => Some(read),
        (Err(error), WhenBad::Stops) => return Err(Error::Xml(error)),
        (Err(_), WhenBad::Skipped) => {
            warnings.push(Warning::PartSkipped {
                part: Name::new(name),
                reason: Reason::NotXml,
            });
            None
        }
    };
    if let Some((doc, _)) = &mut read {
        settings.accept_revisions(doc);
    }
    Ok(read)
}

/// The part `name` of the package, parsed, with its root element: `None` when the package has
/// no such part, or when the part does not read and its role skips it, with a warning.
///
/// # Errors
///
/// When the part does not read and its role stops the document.
pub(crate) fn parse(
    package: &Package,
    role: Role,
    name: &str,
    warnings: &mut Warnings,
) -> Result<Option<(Document, NodeId)>, Error> {
    let Some(bytes) = package.read_part(name).ok().flatten() else {
        return Ok(None);
    };
    match (xml(package, (name, &bytes), warnings), role.when_bad()) {
        (Ok(read), _) => Ok(Some(read)),
        (Err(error), WhenBad::Stops) => Err(Error::Xml(error)),
        (Err(_), WhenBad::Skipped) => {
            warnings.push(Warning::PartSkipped {
                part: Name::new(name),
                reason: Reason::NotXml,
            });
            Ok(None)
        }
    }
}

/// Parses a part that holds text, as [`parse`] does: the main document, a header, a footer or
/// the notes, with the tracked changes that the reader's `settings` accept
/// (`ReaderSettings::accept_revisions`).
pub(crate) fn parse_text(
    package: &Package,
    (role, name): (Role, &str),
    settings: ReaderSettings,
    warnings: &mut Warnings,
) -> Result<Option<(Document, NodeId)>, Error> {
    let mut read = parse(package, role, name, warnings)?;
    if let Some((doc, _)) = &mut read {
        settings.accept_revisions(doc);
    }
    Ok(read)
}

/// What every reader of a part takes besides the part (**Reading**): the
/// warnings of the document, where each part reader adds those of its part, and the one source
/// of the document's paragraph IDs, from which its paragraphs take theirs. A reader lends it to
/// the readers that it calls.
pub(crate) struct Reading<'a> {
    /// The warnings of the document.
    pub(crate) warnings: &'a mut Warnings,
    /// The document's source of paragraph IDs.
    pub(crate) ids: &'a ParagraphIds,
    /// The reader's settings of the document's target, which decide how some values read.
    pub(crate) settings: ReaderSettings,
    /// The IDs of the notes, once the reading has read the footnotes and the endnotes, against
    /// which the readers of the later parts check each note reference.
    pub(crate) notes: Option<crate::body::NoteIds>,
    /// The colors of the document's theme, once the reading has read the theme, which the
    /// readers of the later parts give a color that names a theme color.
    pub(crate) colors: f_office_drawingml::color::SchemeColors,
    /// The document's styles, once the reading has read them, in which the readers of the
    /// later parts look up the list of a paragraph's style.
    pub(crate) styles: Option<&'a Styles>,
    /// Whether display fractions step down in size (`m:mathPr/m:smallFrac`).
    pub(crate) small_frac: crate::props::SmallFractions,
}

/// Reads the part `name` with `read`, or gives `T::default()` when there is no name, when the
/// package lacks the part, or when the part does not read and its role skips it. The warnings
/// of the values in the part that do not read go to the reading's warnings with the part's
/// name, and its paragraphs take their IDs from the reading's source.
///
/// # Errors
///
/// When the part does not read and its role stops the document.
pub(crate) fn read<T: Default>(
    package: &Package,
    (role, name): (Role, Option<String>),
    reading: &mut Reading<'_>,
    read: impl Fn(&mut PartReader, NodeId) -> T,
) -> Result<T, Error> {
    let Some(name) = name else {
        return Ok(T::default());
    };
    let Some((doc, root)) = parse(package, role, &name, reading.warnings)? else {
        return Ok(T::default());
    };
    Ok(read_with(&doc, (&name, root), reading, read))
}

/// Reads the part `name`, whose XML is `doc`, from its root element `root` with `read`, and
/// adds the warnings of the values in it that do not read to the reading's warnings with the
/// part's name. Its paragraphs take their IDs from the reading's source.
pub(crate) fn read_with<T>(
    doc: &Document,
    (name, root): (&str, NodeId),
    reading: &mut Reading<'_>,
    read: impl FnOnce(&mut PartReader, NodeId) -> T,
) -> T {
    let mut reader = PartReader::of_part(doc, name, reading.ids)
        .with_list_levels(reading.settings.list_levels())
        .with_number_formats(reading.settings.number_formats())
        .with_vml_sizes(reading.settings.vml_sizes())
        .with_border_styles(reading.settings.border_styles())
        .with_turned_pictures(reading.settings.turned_pictures())
        .with_saved_date_picture(reading.settings.saved_date_picture())
        .with_note_ids(reading.notes.as_ref())
        .with_scheme(reading.colors)
        .with_small_frac(reading.small_frac)
        .with_styles(reading.styles);
    let value = read(&mut reader, root);
    reader.finish(reading.warnings);
    value
}

/// Reads a part that holds text as [`read`] does, parsed by [`parse_text`], with the links of
/// its table of contents prepared.
///
/// # Errors
///
/// When the part does not read and its role stops the document.
pub(crate) fn read_text<T: Default>(
    package: &Package,
    (role, name): (Role, Option<String>),
    styles: &Styles,
    reading: &mut Reading<'_>,
    read: impl Fn(&mut PartReader, NodeId) -> T,
) -> Result<T, Error> {
    let Some(name) = name else {
        return Ok(T::default());
    };
    let Some((mut doc, root)) =
        parse_text(package, (role, &name), reading.settings, reading.warnings)?
    else {
        return Ok(T::default());
    };
    reading
        .settings
        .prepare_toc_links(&mut doc, (&name, reading.ids), styles);
    Ok(read_with(&doc, (&name, root), reading, read))
}

/// The relationships of a part, or of the package for [`PACKAGE`]: none, with a warning, when
/// its relationships part does not read, so that the part shows nothing that they name. It
/// warns of each namespace prefix that the relationships part uses without a declaration.
///
/// # Errors
///
/// When the relationships part does not read and the policy stops the document.
pub(crate) fn relationships<'p>(
    package: &'p Package,
    part: &str,
    warnings: &mut Warnings,
) -> Result<&'p [Relationship], Error> {
    match (package.relationships(part), Role::Relationships.when_bad()) {
        (Ok(read), _) => {
            undeclared_prefixes(&read.name, &read.undeclared_prefixes, warnings);
            Ok(&read.relationships)
        }
        (Err(error), WhenBad::Stops) => Err(Error::Package(error)),
        (Err(_), WhenBad::Skipped) => {
            warnings.push(Warning::RelationshipsSkipped {
                part: Name::new(if part == PACKAGE { "/" } else { part }),
            });
            Ok(&[])
        }
    }
}