f-office-docx 0.1.0

DOCX model and Word's layout rules.
Documentation
//! One layer of a profile, as a profile's file or the development override writes it: the keys
//! at its top, and the tables `configuration`, `layout`, `writer`, `quirks` and `fonts`. Each
//! value is optional, so that a layer lists only what it changes; the reader merges the layers
//! in order and checks the merged values ([`super::Profile`]).

use std::collections::BTreeMap;
use std::fmt;

use super::fonts::Table;

use crate::configuration::Configuration;
use f_office_paint::Fraction;
use f_office_units::scale::TENTHS;
use serde::{Deserialize, Serialize};

/// One layer of a profile.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Layer {
    /// The profile's ID, such as `word-win`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// The ID of the profile that this one inherits from.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub inherits: Option<String>,
    /// The version of the profile's form.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<i64>,
    /// The product of a profile, such as its name and version.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub product: Option<String>,
    /// The builds of the product that a profile describes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub builds: Option<String>,
    /// The renderer of the PDFs that a profile describes.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub renderer: Option<String>,
    /// The defaults of the configuration, in the configuration's shape.
    #[serde(default, skip_serializing_if = "Configuration::is_empty")]
    pub configuration: Configuration,
    /// The values of the layout device.
    #[serde(default, skip_serializing_if = "Layout::is_empty")]
    pub layout: Layout,
    /// How the PDF writer writes numbers. Only the output stage reads it.
    #[serde(default, skip_serializing_if = "Writer::is_empty")]
    pub writer: Writer,
    /// The variant of each quirk, by the quirk's name.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub quirks: BTreeMap<String, Setting<String>>,
    /// The font environment.
    #[serde(default, skip_serializing_if = "is_empty_table")]
    pub fonts: Table,
}

/// Whether a font environment's table holds nothing.
fn is_empty_table(table: &Table) -> bool {
    *table == Table::default()
}

/// One value of the `layout`, `writer` or `quirks` table.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Setting<T> {
    /// The value.
    pub value: T,
}

/// A count that a profile can turn off: `"off"`, or a whole number.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum OffOr {
    /// `"off"`.
    Off(Off),
    /// A whole number.
    Number(i64),
}

/// The text `"off"`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Off {
    /// `"off"`.
    Off,
}

/// A decimal number, whole or with a point, as a fraction with a power of ten below it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Decimal(pub Fraction);

/// The text of a value as a profile's JSON writes it, which the checks of the target
/// rules compare.
#[cfg(any(test, feature = "development"))]
pub(super) trait Written {
    fn written(&self) -> String;
}

#[cfg(any(test, feature = "development"))]
impl Written for i64 {
    fn written(&self) -> String {
        self.to_string()
    }
}

#[cfg(any(test, feature = "development"))]
impl Written for String {
    fn written(&self) -> String {
        format!("{self:?}")
    }
}

#[cfg(any(test, feature = "development"))]
impl Written for OffOr {
    fn written(&self) -> String {
        match self {
            Self::Off(_) => "\"off\"".to_owned(),
            Self::Number(number) => number.to_string(),
        }
    }
}

#[cfg(any(test, feature = "development"))]
impl Written for Decimal {
    fn written(&self) -> String {
        self.to_string()
    }
}

impl fmt::Display for Decimal {
    /// The decimal number with as many digits after the point as its power of ten has zeros.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (value, scale) = self.0;
        let digits = scale
            .checked_ilog10()
            .and_then(|digits| usize::try_from(digits).ok())
            .unwrap_or(0);
        let sign = if value < 0 { "-" } else { "" };
        let (value, scale) = (value.unsigned_abs(), scale.unsigned_abs().max(1));
        let (whole, part) = (value / scale, value % scale);
        if digits == 0 {
            write!(f, "{sign}{whole}")
        } else {
            write!(f, "{sign}{whole}.{part:0digits$}")
        }
    }
}

impl Serialize for Decimal {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let (value, scale) = self.0;
        if scale == 1 {
            serializer.serialize_i64(value)
        } else {
            let number: f64 = self
                .to_string()
                .parse()
                .map_err(serde::ser::Error::custom)?;
            serializer.serialize_f64(number)
        }
    }
}

impl<'de> Deserialize<'de> for Decimal {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct Visitor;
        impl serde::de::Visitor<'_> for Visitor {
            type Value = Decimal;
            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("a decimal number")
            }
            fn visit_i64<E: serde::de::Error>(self, value: i64) -> Result<Decimal, E> {
                Ok(Decimal((value, 1)))
            }
            fn visit_u64<E: serde::de::Error>(self, value: u64) -> Result<Decimal, E> {
                i64::try_from(value)
                    .map(|value| Decimal((value, 1)))
                    .map_err(E::custom)
            }
            // The shortest text that reads as the same number is the decimal as written.
            fn visit_f64<E: serde::de::Error>(self, value: f64) -> Result<Decimal, E> {
                decimal_fraction(&value.to_string())
                    .map(Decimal)
                    .ok_or_else(|| E::custom(format!("{value} is no decimal number")))
            }
        }
        deserializer.deserialize_any(Visitor)
    }
}

/// A decimal number as written, such as `0.031` or `-2`, as a fraction with a power of ten
/// below it, or `None` when it is not one.
pub(super) fn decimal_fraction(text: &str) -> Option<Fraction> {
    let (sign, digits) = text.strip_prefix('-').map_or((1, text), |rest| (-1, rest));
    let (whole, part) = digits.split_once('.').unwrap_or((digits, ""));
    if whole.is_empty() || !(whole.bytes().chain(part.bytes())).all(|b| b.is_ascii_digit()) {
        return None;
    }
    let scale = TENTHS.checked_pow(u32::try_from(part.len()).ok()?)?;
    let whole = whole.parse::<i64>().ok()?;
    let part = if part.is_empty() {
        0
    } else {
        part.parse::<i64>().ok()?
    };
    Some((sign * whole.checked_mul(scale)?.checked_add(part)?, scale))
}

/// A table of a layer whose keys are fixed, each with its kind: the struct with an optional
/// setting for each key, the merge of a later layer's table into it, and its entries as written.
macro_rules! keyed_table {
    ($(#[$doc:meta])* $name:ident { $($(#[$key_doc:meta])* $key:ident: $kind:ty,)* }) => {
        $(#[$doc])*
        #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
        #[serde(deny_unknown_fields)]
        pub struct $name {
            $(
                $(#[$key_doc])*
                #[serde(default, skip_serializing_if = "Option::is_none")]
                pub $key: Option<Setting<$kind>>,
            )*
        }

        impl $name {
            /// Whether the table sets no key.
            fn is_empty(&self) -> bool {
                *self == Self::default()
            }

            /// Takes in each key that `later` sets, and tells `set` its name.
            pub(super) fn merge(&mut self, later: &Self, set: &mut dyn FnMut(&'static str)) {
                $(
                    if let Some(setting) = &later.$key {
                        self.$key = Some(setting.clone());
                        set(stringify!($key));
                    }
                )*
            }

            /// The keys that the table sets, each with its value as written.
            #[cfg(any(test, feature = "development"))]
            pub(super) fn entries(&self) -> Vec<(&'static str, String)> {
                let mut entries = Vec::new();
                $(
                    if let Some(setting) = &self.$key {
                        entries.push((stringify!($key), setting.value.written()));
                    }
                )*
                entries
            }
        }
    };
}

keyed_table! {
    /// The values of the layout device.
    Layout {
        /// The steps to the inch of a tab leader's advance, or `"off"` for its exact advance.
        leader_steps_per_inch: OffOr,
        /// The parts of an em of the line along a bold's outlines that Word makes, or `"off"`.
        bold_stroke_parts: OffOr,
        /// The parts of an em of the slant of an italic that Word makes, or `"off"`.
        italic_slant_parts: OffOr,
        /// The bias of the glyph steps, in half-EMUs.
        glyph_step_bias_half_emus: i64,
        /// The limit of a glyph's right edge, in half-EMUs.
        glyph_edge_limit_half_emus: i64,
        /// The length of a segment of glyph steps, in half-EMUs.
        glyph_segment_length_half_emus: i64,
        /// The steps of a point of the glyph steps, or `"off"`.
        glyph_point_steps: OffOr,
    }
}

keyed_table! {
    /// How the PDF writer writes numbers.
    Writer {
        /// The page size rounds to this many steps to the inch.
        page_steps_per_inch: i64,
        /// The steps of the writer's vertical stretch.
        vertical_stretch_steps: i64,
        /// The steps to the inch of a glyph's stretch, or `"off"` for the exact stretch.
        glyph_stretch_steps_per_inch: OffOr,
        /// The offset of the stretch factors.
        stretch_offset: Decimal,
        /// The stretch factors: entries `height factor` split by commas.
        stretch_factors: String,
        /// The significant digits of a number, or `"off"`.
        digits: OffOr,
        /// The least decimals of a number.
        least_decimals: i64,
        /// The significant digits of a picture's numbers, or `"off"`.
        picture_digits: OffOr,
        /// The steps to the inch of a filled rectangle, or `"off"`.
        rectangle_steps_per_inch: OffOr,
        /// The steps to the inch of a baseline, or `"off"`.
        baseline_steps_per_inch: OffOr,
        /// The quality of a JPEG file that the writer writes again, or `"off"`.
        jpeg_quality: OffOr,
        /// The share of a picture's color under Flate, in thousandths, below which the writer
        /// writes a PNG picture as a JPEG file, or `"off"`.
        jpeg_share: OffOr,
        /// The sample share of the second test of a JPEG picture, in thousandths, or `"off"`.
        jpeg_sample_share: OffOr,
        /// The floor of the second test of a JPEG picture, in bytes, or `"off"`.
        jpeg_sample_floor: OffOr,
        /// The whole share of the second test of a JPEG picture, in thousandths, or `"off"`.
        jpeg_whole_share: OffOr,
        /// The density above which the writer resamples a picture, or `"off"`.
        picture_limit_ppi: OffOr,
        /// The density to which the writer resamples a picture, or `"off"`.
        picture_ppi: OffOr,
        /// The density limit of a palette of 1 bit, or `"off"`.
        palette_one_bit_limit_ppi: OffOr,
        /// The density of a palette of 1 bit, or `"off"`.
        palette_one_bit_ppi: OffOr,
        /// The density limit of a palette of 4 bits, or `"off"`.
        palette_four_bits_limit_ppi: OffOr,
        /// The density limit of a palette of 8 bits, or `"off"`.
        palette_eight_bits_limit_ppi: OffOr,
        /// How the writer writes a cropped picture.
        picture_crop: String,
        /// How the writer mixes the colors of a picture with an alpha.
        alpha_mix: String,
        /// The measure of the writer's linear limit.
        linear_limit_of: String,
        /// The pictures that the writer resamples by linear interpolation: those up to this.
        linear_limit: i64,
        /// The form of the writer's offset of a place.
        offset: String,
        /// The share of the place across of the writer's start offset.
        start_offset_share: i64,
        /// The bias of the writer's start offset, in half-EMUs.
        start_offset_bias_half_emus: i64,
        /// The step of the writer's start offset, in half-EMUs.
        start_offset_step_half_emus: i64,
        /// The steps to the inch of the writer's page offset.
        offset_page_steps_per_inch: i64,
        /// The parts of a step of the writer's page offset.
        offset_page_parts_per_step: i64,
        /// The steps of the writer's page offset, in hundred-thousandths.
        offset_page_steps_hundred_thousandths: i64,
    }
}