Skip to main content

f_office_docx/
configuration.rs

1//! The configuration: the setup of Word's machine that changes its pages (its printer, its time
2//! zone, the separators of its numbers and its fonts) and the user's choice of the family that
3//! draws a family on this computer, and nothing else. Word's behaviors and numbers are the
4//! target's profile, which no configuration sets.
5//!
6//! The type holds exactly the keys, with the same names in TOML and JSON, and refuses a key
7//! that it does not know. It has no default values of its own: [`Configuration::of`] gives a
8//! target's defaults, which the target's profile holds, and a value that a caller leaves out is
9//! not set.
10
11use std::collections::BTreeMap;
12use std::fmt;
13use std::num::NonZeroU32;
14use std::str::FromStr;
15
16use serde::{Deserialize, Serialize};
17
18mod separators;
19
20/// Why a target's ID names no target, or the configuration or the target's profile does not
21/// read.
22pub use crate::profile::Error;
23pub use crate::profile::Target;
24pub use separators::{NumberSeparators, NumberSeparatorsError};
25
26/// The configuration of a layout: the target, and the setup of Word's machine and the fonts.
27#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
28#[cfg_attr(feature = "development", derive(schemars::JsonSchema))]
29#[serde(deny_unknown_fields)]
30pub struct Configuration {
31    /// The target whose pages the layout reproduces.
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub target: Option<Target>,
34    /// The printer that Word lays out for.
35    #[serde(default, skip_serializing_if = "is_default")]
36    pub printer: Printer,
37    /// The time zone of Word's machine, in minutes east of UTC.
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub zone_minutes: Option<i32>,
40    /// The decimal and the group separator of the numbers of Word's machine, such as `".,"`.
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub number_separators: Option<NumberSeparators>,
43    /// The fonts of Word's machine and of this computer.
44    #[serde(default, skip_serializing_if = "is_default")]
45    pub fonts: Fonts,
46}
47
48/// A value that a configuration of layers sets ([`Configuration::layered`]).
49#[derive(Clone, Debug, PartialEq, Eq)]
50#[non_exhaustive]
51pub struct LayeredValue {
52    /// Its path, each key bare or as a TOML string, such as `printer.dots_per_inch` or
53    /// `fonts.installed."Comic Sans MS"`.
54    pub path: String,
55    /// The value as JSON text, such as `600`, `true` or `"none"`.
56    pub value: String,
57    /// The index of the layer that gave it, the last one that sets it.
58    pub layer: usize,
59}
60
61/// The printer that Word lays out for.
62#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
63#[cfg_attr(feature = "development", derive(schemars::JsonSchema))]
64#[serde(deny_unknown_fields)]
65pub struct Printer {
66    /// The printer's resolution, the same across and down: Word places glyphs and baselines on
67    /// its grid.
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub dots_per_inch: Option<NonZeroU32>,
70    /// The printer's page offset. Without it, the target's printer has the target's offset, and
71    /// a printer of another resolution has none.
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub page_offset: Option<PageOffset>,
74}
75
76/// A printer's page offset.
77#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
78#[serde(rename_all = "lowercase")]
79#[cfg_attr(feature = "development", derive(schemars::JsonSchema))]
80pub enum PageOffset {
81    /// No offset: each place lies at its place on the printer's grid (`"none"`).
82    None,
83}
84
85impl FromStr for PageOffset {
86    type Err = PageOffsetError;
87
88    /// `none`.
89    fn from_str(text: &str) -> Result<Self, PageOffsetError> {
90        match text {
91            "none" => Ok(Self::None),
92            _ => Err(PageOffsetError(text.to_owned())),
93        }
94    }
95}
96
97impl fmt::Display for PageOffset {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        match self {
100            Self::None => f.write_str("none"),
101        }
102    }
103}
104
105/// A text that is no page offset.
106#[derive(Clone, Debug, PartialEq, Eq)]
107pub struct PageOffsetError(pub String);
108
109impl fmt::Display for PageOffsetError {
110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111        write!(f, "{:?} is no page offset: write none", self.0)
112    }
113}
114
115impl std::error::Error for PageOffsetError {}
116
117/// The fonts of Word's machine and of this computer, each by its family name.
118#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
119#[cfg_attr(feature = "development", derive(schemars::JsonSchema))]
120#[serde(deny_unknown_fields)]
121pub struct Fonts {
122    /// The families added to the fonts of Word's machine (`true`) or removed from them
123    /// (`false`). Word has an added family for every use, as it has the family of a face that a
124    /// document carries once it opens the document.
125    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
126    pub installed: BTreeMap<String, bool>,
127    /// The family that draws a family on this computer, by the family that it draws.
128    #[serde(default, rename = "use", skip_serializing_if = "BTreeMap::is_empty")]
129    pub uses: BTreeMap<String, String>,
130}
131
132/// The JSON Schema of the configuration, formatted as pretty JSON with a trailing newline.
133#[cfg(feature = "development")]
134#[must_use]
135pub fn schema() -> String {
136    let schema = schemars::schema_for!(Configuration);
137    let mut text = serde_json::to_string_pretty(&schema).unwrap_or_default();
138    text.push('\n');
139    text
140}
141
142impl Configuration {
143    /// The configuration of `target` with the target's defaults, which its profile holds.
144    #[must_use]
145    pub fn of(target: Target) -> Self {
146        crate::profile::defaults(target)
147    }
148
149    /// The configuration that `layers` give, each laid over the ones before it key by key, and
150    /// each value that it sets with the layer that gave it, in the order of the fields and of
151    /// the family names.
152    #[must_use]
153    pub fn layered(layers: &[&Self]) -> (Self, Vec<LayeredValue>) {
154        let mut merged = Self::default();
155        let mut origins = BTreeMap::new();
156        for (index, layer) in layers.iter().enumerate() {
157            merged.merge(layer, &mut |path| {
158                origins.insert(path, index);
159            });
160        }
161        let values = (merged.values().into_iter())
162            .map(|(path, value)| {
163                let layer = origins.get(&path).copied().unwrap_or_default();
164                LayeredValue {
165                    path,
166                    value: value.to_string(),
167                    layer,
168                }
169            })
170            .collect();
171        (merged, values)
172    }
173
174    /// Each value that the configuration sets, by its path, such as `printer.dots_per_inch`
175    /// or `fonts.installed."Comic Sans MS"`, with the value as its JSON writes it, in the order of
176    /// the fields and of the family names.
177    pub(crate) fn values(&self) -> Vec<(String, serde_json::Value)> {
178        (self.leaves().into_iter())
179            .map(|(keys, value)| (key_path(&keys), value))
180            .collect()
181    }
182
183    /// Takes in each value that `later` sets, and tells `set` its path, as
184    /// [`Configuration::values`] writes it.
185    pub(crate) fn merge(&mut self, later: &Self, set: &mut dyn FnMut(String)) {
186        let mut merged: BTreeMap<Keys, serde_json::Value> = self.leaves().into_iter().collect();
187        for (keys, value) in later.leaves() {
188            set(key_path(&keys));
189            merged.insert(keys, value);
190        }
191        *self = Self::of_leaves(merged);
192    }
193
194    /// The values of this configuration that differ from those of `base`, without the target.
195    pub(crate) fn changes_from(&self, base: &Self) -> Self {
196        let base: BTreeMap<Keys, serde_json::Value> = base.leaves().into_iter().collect();
197        Self::of_leaves(
198            (self.leaves().into_iter())
199                .filter(|(keys, _)| keys.as_slice() != ["target"])
200                .filter(|(keys, value)| base.get(keys) != Some(value)),
201        )
202    }
203
204    /// Each value that the configuration sets, by its keys, in the order of [`KEYS`] and of the
205    /// family names.
206    fn leaves(&self) -> Vec<(Keys, serde_json::Value)> {
207        fn walk(
208            keys: &mut Keys,
209            value: serde_json::Value,
210            out: &mut Vec<(Keys, serde_json::Value)>,
211        ) {
212            match value {
213                serde_json::Value::Object(table) => {
214                    for (key, value) in table {
215                        keys.push(key);
216                        walk(keys, value, out);
217                        keys.pop();
218                    }
219                }
220                value => out.push((keys.clone(), value)),
221            }
222        }
223        let mut out = Vec::new();
224        if let Ok(value) = serde_json::to_value(self) {
225            walk(&mut Vec::new(), value, &mut out);
226        }
227        out.sort_by_cached_key(|(keys, _)| (rank(keys), keys.clone()));
228        out
229    }
230
231    /// The configuration that sets `leaves`, each by its keys. Each leaf comes from the walk of
232    /// a configuration ([`Configuration::leaves`]), so the configuration reads.
233    fn of_leaves(leaves: impl IntoIterator<Item = (Keys, serde_json::Value)>) -> Self {
234        fn insert(
235            table: &mut serde_json::Map<String, serde_json::Value>,
236            keys: &[String],
237            value: serde_json::Value,
238        ) {
239            match keys {
240                [] => {}
241                [last] => {
242                    table.insert(last.clone(), value);
243                }
244                [first, rest @ ..] => {
245                    let next = (table.entry(first.clone()))
246                        .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
247                    if let serde_json::Value::Object(inner) = next {
248                        insert(inner, rest, value);
249                    }
250                }
251            }
252        }
253        let mut root = serde_json::Map::new();
254        for (keys, value) in leaves {
255            insert(&mut root, &keys, value);
256        }
257        serde_json::from_value(serde_json::Value::Object(root)).unwrap_or_default()
258    }
259
260    /// Whether the configuration sets no value.
261    pub(crate) fn is_empty(&self) -> bool {
262        is_default(self)
263    }
264}
265
266/// Whether `value` sets no value: it equals its type's default.
267fn is_default<T: Default + PartialEq>(value: &T) -> bool {
268    *value == T::default()
269}
270
271/// A path of keys from the top of a configuration, such as `["printer", "dots_per_inch"]`.
272type Keys = Vec<String>;
273
274/// The keys of the configuration in the order of its fields: each the path of a value, or of a
275/// table of values by family name, such as `fonts.installed`.
276const KEYS: [&str; 7] = [
277    "target",
278    "printer.dots_per_inch",
279    "printer.page_offset",
280    "zone_minutes",
281    "number_separators",
282    "fonts.installed",
283    "fonts.use",
284];
285
286/// The place of `keys` in [`KEYS`]: that of the key that `keys` is, or whose table holds it, and
287/// after them all for a key that [`KEYS`] lacks.
288fn rank(keys: &[String]) -> usize {
289    let joined = keys.join(".");
290    (KEYS.iter())
291        .position(|key| {
292            joined == *key
293                || joined
294                    .strip_prefix(key)
295                    .is_some_and(|rest| rest.starts_with('.'))
296        })
297        .unwrap_or(KEYS.len())
298}
299
300/// `keys` as one path, each key as [`path_key`](crate::profile::path_key) writes it, joined by
301/// dots.
302fn key_path(keys: &[String]) -> String {
303    let keys: Vec<String> = keys
304        .iter()
305        .map(|key| crate::profile::path_key(key))
306        .collect();
307    keys.join(".")
308}
309
310#[cfg(test)]
311mod tests;