f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
//! The configuration: the setup of Word's machine that changes its pages (its printer, its time
//! zone, the separators of its numbers and its fonts) and the user's choice of the family that
//! draws a family on this computer, and nothing else. Word's behaviors and numbers are the
//! target's profile, which no configuration sets.
//!
//! The type holds exactly the keys, with the same names in TOML and JSON, and refuses a key
//! that it does not know. It has no default values of its own: [`Configuration::of`] gives a
//! target's defaults, which the target's profile holds, and a value that a caller leaves out is
//! not set.

use std::collections::BTreeMap;
use std::fmt;
use std::num::NonZeroU32;
use std::str::FromStr;

use serde::{Deserialize, Serialize};

mod separators;

/// Why a target's ID names no target, or the configuration or the target's profile does not
/// read.
pub use crate::profile::Error;
pub use crate::profile::Target;
pub use separators::{NumberSeparators, NumberSeparatorsError};

/// The configuration of a layout: the target, and the setup of Word's machine and the fonts.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "development", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Configuration {
    /// The target whose pages the layout reproduces.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub target: Option<Target>,
    /// The printer that Word lays out for.
    #[serde(default, skip_serializing_if = "is_default")]
    pub printer: Printer,
    /// The time zone of Word's machine, in minutes east of UTC.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub zone_minutes: Option<i32>,
    /// The decimal and the group separator of the numbers of Word's machine, such as `".,"`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub number_separators: Option<NumberSeparators>,
    /// The fonts of Word's machine and of this computer.
    #[serde(default, skip_serializing_if = "is_default")]
    pub fonts: Fonts,
}

/// A value that a configuration of layers sets ([`Configuration::layered`]).
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct LayeredValue {
    /// Its path, each key bare or as a TOML string, such as `printer.dots_per_inch` or
    /// `fonts.installed."Comic Sans MS"`.
    pub path: String,
    /// The value as JSON text, such as `600`, `true` or `"none"`.
    pub value: String,
    /// The index of the layer that gave it, the last one that sets it.
    pub layer: usize,
}

/// The printer that Word lays out for.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "development", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Printer {
    /// The printer's resolution, the same across and down: Word places glyphs and baselines on
    /// its grid.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dots_per_inch: Option<NonZeroU32>,
    /// The printer's page offset. Without it, the target's printer has the target's offset, and
    /// a printer of another resolution has none.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub page_offset: Option<PageOffset>,
}

/// A printer's page offset.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[cfg_attr(feature = "development", derive(schemars::JsonSchema))]
pub enum PageOffset {
    /// No offset: each place lies at its place on the printer's grid (`"none"`).
    None,
}

impl FromStr for PageOffset {
    type Err = PageOffsetError;

    /// `none`.
    fn from_str(text: &str) -> Result<Self, PageOffsetError> {
        match text {
            "none" => Ok(Self::None),
            _ => Err(PageOffsetError(text.to_owned())),
        }
    }
}

impl fmt::Display for PageOffset {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::None => f.write_str("none"),
        }
    }
}

/// A text that is no page offset.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PageOffsetError(pub String);

impl fmt::Display for PageOffsetError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?} is no page offset: write none", self.0)
    }
}

impl std::error::Error for PageOffsetError {}

/// The fonts of Word's machine and of this computer, each by its family name.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "development", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Fonts {
    /// The families added to the fonts of Word's machine (`true`) or removed from them
    /// (`false`). Word has an added family for every use, as it has the family of a face that a
    /// document carries once it opens the document.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub installed: BTreeMap<String, bool>,
    /// The family that draws a family on this computer, by the family that it draws.
    #[serde(default, rename = "use", skip_serializing_if = "BTreeMap::is_empty")]
    pub uses: BTreeMap<String, String>,
}

/// The JSON Schema of the configuration, formatted as pretty JSON with a trailing newline.
#[cfg(feature = "development")]
#[must_use]
pub fn schema() -> String {
    let schema = schemars::schema_for!(Configuration);
    let mut text = serde_json::to_string_pretty(&schema).unwrap_or_default();
    text.push('\n');
    text
}

impl Configuration {
    /// The configuration of `target` with the target's defaults, which its profile holds.
    #[must_use]
    pub fn of(target: Target) -> Self {
        crate::profile::defaults(target)
    }

    /// The configuration that `layers` give, each laid over the ones before it key by key, and
    /// each value that it sets with the layer that gave it, in the order of the fields and of
    /// the family names.
    #[must_use]
    pub fn layered(layers: &[&Self]) -> (Self, Vec<LayeredValue>) {
        let mut merged = Self::default();
        let mut origins = BTreeMap::new();
        for (index, layer) in layers.iter().enumerate() {
            merged.merge(layer, &mut |path| {
                origins.insert(path, index);
            });
        }
        let values = (merged.values().into_iter())
            .map(|(path, value)| {
                let layer = origins.get(&path).copied().unwrap_or_default();
                LayeredValue {
                    path,
                    value: value.to_string(),
                    layer,
                }
            })
            .collect();
        (merged, values)
    }

    /// Each value that the configuration sets, by its path, such as `printer.dots_per_inch`
    /// or `fonts.installed."Comic Sans MS"`, with the value as its JSON writes it, in the order of
    /// the fields and of the family names.
    pub(crate) fn values(&self) -> Vec<(String, serde_json::Value)> {
        (self.leaves().into_iter())
            .map(|(keys, value)| (key_path(&keys), value))
            .collect()
    }

    /// Takes in each value that `later` sets, and tells `set` its path, as
    /// [`Configuration::values`] writes it.
    pub(crate) fn merge(&mut self, later: &Self, set: &mut dyn FnMut(String)) {
        let mut merged: BTreeMap<Keys, serde_json::Value> = self.leaves().into_iter().collect();
        for (keys, value) in later.leaves() {
            set(key_path(&keys));
            merged.insert(keys, value);
        }
        *self = Self::of_leaves(merged);
    }

    /// The values of this configuration that differ from those of `base`, without the target.
    pub(crate) fn changes_from(&self, base: &Self) -> Self {
        let base: BTreeMap<Keys, serde_json::Value> = base.leaves().into_iter().collect();
        Self::of_leaves(
            (self.leaves().into_iter())
                .filter(|(keys, _)| keys.as_slice() != ["target"])
                .filter(|(keys, value)| base.get(keys) != Some(value)),
        )
    }

    /// Each value that the configuration sets, by its keys, in the order of [`KEYS`] and of the
    /// family names.
    fn leaves(&self) -> Vec<(Keys, serde_json::Value)> {
        fn walk(
            keys: &mut Keys,
            value: serde_json::Value,
            out: &mut Vec<(Keys, serde_json::Value)>,
        ) {
            match value {
                serde_json::Value::Object(table) => {
                    for (key, value) in table {
                        keys.push(key);
                        walk(keys, value, out);
                        keys.pop();
                    }
                }
                value => out.push((keys.clone(), value)),
            }
        }
        let mut out = Vec::new();
        if let Ok(value) = serde_json::to_value(self) {
            walk(&mut Vec::new(), value, &mut out);
        }
        out.sort_by_cached_key(|(keys, _)| (rank(keys), keys.clone()));
        out
    }

    /// The configuration that sets `leaves`, each by its keys. Each leaf comes from the walk of
    /// a configuration ([`Configuration::leaves`]), so the configuration reads.
    fn of_leaves(leaves: impl IntoIterator<Item = (Keys, serde_json::Value)>) -> Self {
        fn insert(
            table: &mut serde_json::Map<String, serde_json::Value>,
            keys: &[String],
            value: serde_json::Value,
        ) {
            match keys {
                [] => {}
                [last] => {
                    table.insert(last.clone(), value);
                }
                [first, rest @ ..] => {
                    let next = (table.entry(first.clone()))
                        .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
                    if let serde_json::Value::Object(inner) = next {
                        insert(inner, rest, value);
                    }
                }
            }
        }
        let mut root = serde_json::Map::new();
        for (keys, value) in leaves {
            insert(&mut root, &keys, value);
        }
        serde_json::from_value(serde_json::Value::Object(root)).unwrap_or_default()
    }

    /// Whether the configuration sets no value.
    pub(crate) fn is_empty(&self) -> bool {
        is_default(self)
    }
}

/// Whether `value` sets no value: it equals its type's default.
fn is_default<T: Default + PartialEq>(value: &T) -> bool {
    *value == T::default()
}

/// A path of keys from the top of a configuration, such as `["printer", "dots_per_inch"]`.
type Keys = Vec<String>;

/// The keys of the configuration in the order of its fields: each the path of a value, or of a
/// table of values by family name, such as `fonts.installed`.
const KEYS: [&str; 7] = [
    "target",
    "printer.dots_per_inch",
    "printer.page_offset",
    "zone_minutes",
    "number_separators",
    "fonts.installed",
    "fonts.use",
];

/// The place of `keys` in [`KEYS`]: that of the key that `keys` is, or whose table holds it, and
/// after them all for a key that [`KEYS`] lacks.
fn rank(keys: &[String]) -> usize {
    let joined = keys.join(".");
    (KEYS.iter())
        .position(|key| {
            joined == *key
                || joined
                    .strip_prefix(key)
                    .is_some_and(|rest| rest.starts_with('.'))
        })
        .unwrap_or(KEYS.len())
}

/// `keys` as one path, each key as [`path_key`](crate::profile::path_key) writes it, joined by
/// dots.
fn key_path(keys: &[String]) -> String {
    let keys: Vec<String> = keys
        .iter()
        .map(|key| crate::profile::path_key(key))
        .collect();
    keys.join(".")
}

#[cfg(test)]
mod tests;