Skip to main content

f_office_docx/
profile.rs

1//! Targets and their profiles. A target is the product whose pages a layout reproduces, and its
2//! profile is a versioned data file in `profiles/`: Word's behaviors and numbers, and in its
3//! table `configuration` the defaults of the configuration. The base profile is the root, every
4//! other profile inherits from it along `inherits` and lists only what differs, and the caller's
5//! configuration and, in a development build, the override's layers come after the chain
6//! ([`Overrides`]). A later layer wins, tables merge key by key, and the merged profile records
7//! which layer set each value (`Profile::origin`).
8//!
9//! Only this module reads the target: its value is private here, so no other code can ask
10//! which product it draws for, and no other library source names a target by its ID. Each
11//! kind of difference has one home: a behavior is a quirk variant, a number of the layout
12//! device is a layout value, and how the PDF writer writes numbers is the writer, which only
13//! the output stage reads.
14//!
15//! The build turns each file of `profiles/` into JSON, which this module reads with serde
16//! ([`Layer`]), so that the library carries no TOML reader.
17
18use std::collections::BTreeMap;
19use std::fmt::{self, Write as _};
20use std::num::NonZeroU32;
21use std::str::FromStr;
22use std::sync::{Arc, OnceLock};
23
24use crate::font_choice::SymbolFonts;
25use f_office_fonts::environment::{EnvironmentError, FontEnvironment};
26use f_office_paint::{
27    AlphaMix, JpegQuality, JpegSample, JpegShare, LinearLimit, PaletteDensity, PictureCrop,
28    PictureDensity, Writer, WriterOffset,
29};
30use f_office_units::Length;
31
32use crate::configuration::{Configuration, PageOffset};
33
34#[cfg(any(test, feature = "development"))]
35mod facts;
36#[cfg(feature = "development")]
37pub mod fonts;
38#[cfg(not(feature = "development"))]
39pub(crate) mod fonts;
40mod layer;
41mod overrides;
42
43#[cfg(feature = "development")]
44pub use facts::{Entry, Facts, Section};
45#[cfg(all(test, not(feature = "development")))]
46use facts::{Facts, Section};
47use fonts::Table;
48pub(crate) use layer::{Decimal, Layer, Layout, OffOr, Setting, Writer as WriterTable};
49#[cfg(feature = "development")]
50pub use overrides::Overrides;
51#[cfg(not(feature = "development"))]
52pub(crate) use overrides::Overrides;
53
54use layer::decimal_fraction;
55
56/// The product whose pages a layout reproduces. The default target is Word for Windows
57/// (`word-win`). Preview targets (`word-mac`, `word-web`) are gated behind the
58/// `preview-targets` feature.
59#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
60pub struct Target(Id);
61
62/// The Word product of a target: Word for Windows by default, plus preview Word for Mac
63/// and Word for the web when `preview-targets` is enabled.
64#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
65enum Id {
66    #[cfg(any(test, feature = "preview-targets"))]
67    Mac,
68    #[cfg(any(test, feature = "preview-targets"))]
69    Web,
70    #[default]
71    Win,
72}
73
74/// One cell for each target, in which a value that depends on the target only is made once in a
75/// process: the profiles and the font environments are part of the binary, so each reading
76/// gives the same value.
77type PerTarget<T> = [OnceLock<T>; TARGETS.len()];
78
79impl Id {
80    /// The cell of this target in `cells`.
81    #[cfg(any(test, feature = "preview-targets"))]
82    const fn cell<T>(self, cells: &PerTarget<T>) -> &OnceLock<T> {
83        let [mac, web, win] = cells;
84        match self {
85            Self::Mac => mac,
86            Self::Web => web,
87            Self::Win => win,
88        }
89    }
90
91    /// The cell of this target in `cells`.
92    #[cfg(not(any(test, feature = "preview-targets")))]
93    const fn cell<T>(self, cells: &PerTarget<T>) -> &OnceLock<T> {
94        let [win] = cells;
95        match self {
96            Self::Win => win,
97        }
98    }
99}
100
101/// The ID of each enabled target's profile.
102#[cfg(any(test, feature = "preview-targets"))]
103const TARGETS: [(Id, &str); 3] = [
104    (Id::Mac, "word-mac"),
105    (Id::Web, "word-web"),
106    (Id::Win, "word-win"),
107];
108
109/// The ID of each enabled target's profile.
110#[cfg(not(any(test, feature = "preview-targets")))]
111const TARGETS: [(Id, &str); 1] = [(Id::Win, "word-win")];
112
113/// A file of the profiles by its name, with the JSON that the build makes of it, `$json` in
114/// the build's output folder.
115macro_rules! built {
116    ($name:literal, $json:literal) => {
117        ($name, include_str!(concat!(env!("OUT_DIR"), "/", $json)))
118    };
119}
120
121/// The profiles by their IDs. Even when `preview-targets` is off, `word-mac` stays
122/// embedded as the inheritance root of `word-win`.
123#[cfg(any(test, feature = "preview-targets"))]
124const BUILT_IN: [(&str, &str); 3] = [
125    built!("word-mac", "word-mac.json"),
126    built!("word-web", "word-web.json"),
127    built!("word-win", "word-win.json"),
128];
129
130/// The profiles by their IDs (`word-mac` is kept solely as the inheritance root of `word-win`).
131#[cfg(not(any(test, feature = "preview-targets")))]
132const BUILT_IN: [(&str, &str); 2] = [
133    built!("word-mac", "word-mac.json"),
134    built!("word-win", "word-win.json"),
135];
136
137/// The font environments that a profile can name (`fonts.environment`), by their paths in the
138/// folder of the profiles.
139#[cfg(any(test, feature = "preview-targets"))]
140const FONT_ENVIRONMENTS: [(&str, &str); 3] = [
141    built!("fonts/word-mac.toml", "fonts-word-mac.json"),
142    built!("fonts/word-web.toml", "fonts-word-web.json"),
143    built!("fonts/word-win.toml", "fonts-word-win.json"),
144];
145
146/// The font environments for enabled targets only.
147#[cfg(not(any(test, feature = "preview-targets")))]
148const FONT_ENVIRONMENTS: [(&str, &str); 1] = [built!("fonts/word-win.toml", "fonts-word-win.json")];
149
150impl Target {
151    /// Every enabled target. When `preview-targets` is enabled, the inheritance root comes
152    /// first.
153    pub fn all() -> impl Iterator<Item = Self> {
154        TARGETS.iter().map(|(id, _)| Self(*id))
155    }
156
157    /// The base profile target from which other profiles inherit (`word-mac`).
158    #[cfg(any(test, feature = "development"))]
159    #[must_use]
160    pub const fn base() -> Self {
161        Self(Id::Mac)
162    }
163
164    /// The ID of the target's profile.
165    fn name(self) -> &'static str {
166        TARGETS
167            .iter()
168            .find(|(id, _)| *id == self.0)
169            .map_or("", |(_, name)| name)
170    }
171}
172
173impl FromStr for Target {
174    type Err = Error;
175
176    /// The target whose profile has the ID `name`.
177    fn from_str(name: &str) -> Result<Self, Error> {
178        Self::all()
179            .find(|target| target.name() == name)
180            .ok_or_else(|| Error::UnknownTarget(name.to_owned()))
181    }
182}
183
184impl fmt::Display for Target {
185    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186        f.write_str(self.name())
187    }
188}
189
190impl serde::Serialize for Target {
191    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
192        serializer.serialize_str(self.name())
193    }
194}
195
196impl<'de> serde::Deserialize<'de> for Target {
197    /// The target by its ID, such as `"word-win"`.
198    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
199        let name = String::deserialize(deserializer)?;
200        name.parse().map_err(serde::de::Error::custom)
201    }
202}
203
204#[cfg(feature = "development")]
205impl schemars::JsonSchema for Target {
206    fn schema_name() -> std::borrow::Cow<'static, str> {
207        "Target".into()
208    }
209
210    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
211        let ids: Vec<String> = Self::all().map(|target| target.to_string()).collect();
212        schemars::json_schema!({
213            "description": "The Word whose pages the layout reproduces, by its ID.",
214            "type": "string",
215            "enum": ids
216        })
217    }
218}
219
220/// The profiles of [`BUILT_IN`], each read once in a process.
221static PROFILES_READ: [OnceLock<Result<Layer, Error>>; BUILT_IN.len()] =
222    [const { OnceLock::new() }; BUILT_IN.len()];
223
224/// The font environments of [`FONT_ENVIRONMENTS`], each read once in a process.
225static ENVIRONMENTS_READ: [OnceLock<Result<Table, Error>>; FONT_ENVIRONMENTS.len()] =
226    [const { OnceLock::new() }; FONT_ENVIRONMENTS.len()];
227
228/// The profile `name`, read once in a process.
229fn built_in(name: &str) -> Result<&'static Layer, Error> {
230    let layer = read_once((&BUILT_IN, &PROFILES_READ), name, Error::UnknownProfile)?;
231    if layer.id.as_deref() != Some(name) {
232        return Err(Error::Missing("id"));
233    }
234    Ok(layer)
235}
236
237/// The font environment `name` that a profile names, read once in a process.
238fn environment_table(name: &str) -> Result<&'static Table, Error> {
239    read_once(
240        (&FONT_ENVIRONMENTS, &ENVIRONMENTS_READ),
241        name,
242        Error::UnknownEnvironment,
243    )
244}
245
246/// The cells of the files of one kind, by the order of the files, each read once in a process.
247type ReadOnce<T> = [OnceLock<Result<T, Error>>];
248
249/// The value of the file `name` of `files`, read from its JSON once in a process into its cell
250/// of `cells`; `unknown` is the error of a name that `files` lacks.
251fn read_once<T: serde::de::DeserializeOwned>(
252    (files, cells): (&[(&str, &str)], &'static ReadOnce<T>),
253    name: &str,
254    unknown: fn(String) -> Error,
255) -> Result<&'static T, Error> {
256    let at = files
257        .iter()
258        .position(|(own, _)| *own == name)
259        .ok_or_else(|| unknown(name.to_owned()))?;
260    let (cell, (own, json)) = cells
261        .get(at)
262        .zip(files.get(at))
263        .ok_or_else(|| unknown(name.to_owned()))?;
264    cell.get_or_init(|| {
265        serde_json::from_str(json).map_err(|error| Error::Read {
266            profile: (*own).to_owned(),
267            message: error.to_string(),
268        })
269    })
270    .as_ref()
271    .map_err(Clone::clone)
272}
273
274/// The chain of the profile `name`: the profiles along `inherits`, the root first.
275fn chain(name: &str) -> Result<Vec<(&'static str, &'static Layer)>, Error> {
276    let mut chain = Vec::new();
277    let mut next = Some(name.to_owned());
278    while let Some(name) = next.take() {
279        if chain.len() == BUILT_IN.len() {
280            return Err(Error::Inherits(name));
281        }
282        let layer = built_in(&name)?;
283        let id = BUILT_IN
284            .iter()
285            .find(|(own, _)| *own == name)
286            .map_or("", |(own, _)| own);
287        chain.push((id, layer));
288        next.clone_from(&layer.inherits);
289    }
290    chain.reverse();
291    Ok(chain)
292}
293
294/// The configuration of `target` with the defaults that its profile's chain gives in its tables
295/// `configuration`. A profile that does not read gives the target alone, and the profile's
296/// error comes when a layout reads the configuration ([`Profile::resolve`]).
297pub(crate) fn defaults(target: Target) -> Configuration {
298    let mut configuration =
299        Merged::of(target).map_or_default(|merged| merged.layer.configuration.clone());
300    configuration.target = Some(target);
301    configuration
302}
303
304/// The layers merged in order, with the layer that set each value.
305#[derive(Clone, Debug, Default, PartialEq, Eq)]
306struct Merged {
307    layer: Layer,
308    /// The index in `names` of the layer that set each value, by its path, such as
309    /// `layout.leader_steps_per_inch`, `configuration.printer.dots_per_inch` or
310    /// `fonts.available.Aptos`.
311    origins: BTreeMap<String, usize>,
312    /// The name of each layer, in order.
313    names: Vec<Arc<str>>,
314}
315
316/// A key of a path as TOML writes it: bare when it holds only letters, digits, `_` and `-`, else
317/// a basic string in double quotes, with `\"`, `\\` and `\uXXXX` for a quote, a backslash and
318/// a control character.
319pub(crate) fn path_key(key: &str) -> String {
320    if !key.is_empty()
321        && key
322            .bytes()
323            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
324    {
325        return key.to_owned();
326    }
327    let mut out = String::with_capacity(key.len() + 2);
328    out.push('"');
329    for ch in key.chars() {
330        match ch {
331            '"' => out.push_str("\\\""),
332            '\\' => out.push_str("\\\\"),
333            ch if ch.is_control() => {
334                let _ = write!(out, "\\u{:04X}", u32::from(ch));
335            }
336            ch => out.push(ch),
337        }
338    }
339    out.push('"');
340    out
341}
342
343impl Merged {
344    /// The chain of `target`'s profile merged, once in a process.
345    fn of(target: Target) -> Result<&'static Self, Error> {
346        static MERGED: PerTarget<Result<Merged, Error>> =
347            [const { OnceLock::new() }; TARGETS.len()];
348        target
349            .0
350            .cell(&MERGED)
351            .get_or_init(|| {
352                let layers = chain(target.name())?;
353                let last_env = layers
354                    .iter()
355                    .rposition(|(_, layer)| layer.fonts.environment.is_some());
356                let mut merged = Self::default();
357                for (index, (name, layer)) in layers.into_iter().enumerate() {
358                    let load_env = last_env == Some(index);
359                    merged.take_with_env(name, layer, load_env)?;
360                }
361                Ok(merged)
362            })
363            .as_ref()
364            .map_err(Clone::clone)
365    }
366
367    /// Takes in the layer `layer`, named `name`, after the others.
368    fn take(&mut self, name: &str, layer: &Layer) -> Result<(), Error> {
369        self.take_with_env(name, layer, true)
370    }
371
372    /// Takes in `layer`, loading its `fonts.environment` table only when `load_env` is true
373    /// (skipped for ancestor layers whose environment is completely replaced by a descendant).
374    fn take_with_env(&mut self, name: &str, layer: &Layer, load_env: bool) -> Result<(), Error> {
375        let at = self.names.len();
376        self.names.push(name.into());
377        if load_env && let Some(environment) = &layer.fonts.environment {
378            let table = environment_table(environment)?;
379            self.origins.retain(|path, _| !path.starts_with("fonts."));
380            self.layer.fonts = Table {
381                environment: Some(environment.clone()),
382                ..Table::default()
383            };
384            self.origins.insert("fonts.environment".to_owned(), at);
385            let origins = &mut self.origins;
386            self.layer.fonts.merge(table, &mut |path| {
387                origins.insert(fonts_path(path), at);
388            });
389        }
390        let (own, origins) = (&mut self.layer, &mut self.origins);
391        let mut set = |path: String| {
392            origins.insert(path, at);
393        };
394        for (key, own, later) in [
395            ("id", &mut own.id, &layer.id),
396            ("inherits", &mut own.inherits, &layer.inherits),
397            ("product", &mut own.product, &layer.product),
398            ("builds", &mut own.builds, &layer.builds),
399            ("renderer", &mut own.renderer, &layer.renderer),
400        ] {
401            if let Some(value) = later {
402                *own = Some(value.clone());
403                set(key.to_owned());
404            }
405        }
406        if let Some(version) = layer.version {
407            own.version = Some(version);
408            set("version".to_owned());
409        }
410        own.configuration.merge(&layer.configuration, &mut |path| {
411            set(format!("configuration.{path}"));
412        });
413        own.layout
414            .merge(&layer.layout, &mut |key| set(format!("layout.{key}")));
415        own.writer
416            .merge(&layer.writer, &mut |key| set(format!("writer.{key}")));
417        for (quirk, setting) in &layer.quirks {
418            own.quirks.insert(quirk.clone(), setting.clone());
419            set(format!("quirks.{}", path_key(quirk)));
420        }
421        own.fonts
422            .merge(&layer.fonts, &mut |path| set(fonts_path(path)));
423        Ok(())
424    }
425
426    /// The name of the layer that set the value at `path`.
427    #[cfg(any(test, feature = "development"))]
428    fn origin(&self, path: &str) -> Option<&str> {
429        let at = *self.origins.get(path)?;
430        self.names.get(at).map(|name| &**name)
431    }
432
433    /// Whether a layer after the first `built_in`, the profile's chain, set the value at `path`.
434    fn caller_set(&self, path: &str, built_in: usize) -> bool {
435        self.origins.get(path).is_some_and(|at| *at >= built_in)
436    }
437}
438
439/// The path of a value of the font environment's table, from `fonts` on.
440fn fonts_path(path: &[&str]) -> String {
441    let mut out = "fonts".to_owned();
442    for key in path {
443        out.push('.');
444        out.push_str(&path_key(key));
445    }
446    out
447}
448
449/// The value of `key`, or the error that the merged configuration lacks it.
450fn get<T: Clone>(setting: Option<&Setting<T>>, key: &'static str) -> Result<T, Error> {
451    setting
452        .map(|setting| setting.value.clone())
453        .ok_or(Error::Missing(key))
454}
455
456/// A whole number that `accepts` takes, as a `T` that holds it.
457fn number<T: TryFrom<i64>>(
458    value: i64,
459    key: &'static str,
460    accepts: fn(i64) -> bool,
461) -> Result<T, Error> {
462    if !accepts(value) {
463        return Err(Error::Value(key));
464    }
465    T::try_from(value).map_err(|_| Error::Value(key))
466}
467
468/// A whole number above 0, such as a count of steps per inch.
469fn positive(setting: Option<&Setting<i64>>, key: &'static str) -> Result<i64, Error> {
470    number(get(setting, key)?, key, |number| number > 0)
471}
472
473/// A whole number, 0 or more, such as the bias of the writer's start offset.
474fn whole(setting: Option<&Setting<i64>>, key: &'static str) -> Result<i64, Error> {
475    number(get(setting, key)?, key, |number| number >= 0)
476}
477
478/// A setting that a configuration can turn off: `None` for `"off"`, and for a positive whole
479/// number the value that `make` gives. Zero, a negative number and a number that `make` refuses
480/// are errors, so that each meaning has one spelling.
481fn off_or<T>(
482    setting: Option<&Setting<OffOr>>,
483    key: &'static str,
484    make: impl FnOnce(i64) -> Option<T>,
485) -> Result<Option<T>, Error> {
486    match get(setting, key)? {
487        OffOr::Off(_) => Ok(None),
488        OffOr::Number(number) if number > 0 => make(number).map(Some).ok_or(Error::Value(key)),
489        OffOr::Number(_) => Err(Error::Value(key)),
490    }
491}
492
493/// A count that a configuration can turn off, such as the significant digits of the writer:
494/// `"off"`, or a positive whole number of 32 bits.
495fn count_or_off(
496    setting: Option<&Setting<OffOr>>,
497    key: &'static str,
498) -> Result<Option<NonZeroU32>, Error> {
499    off_or(setting, key, |number| {
500        u32::try_from(number).ok().and_then(NonZeroU32::new)
501    })
502}
503
504/// A step to which a value rounds, from the number of steps per inch that the configuration
505/// gives as `key`, which divides an inch into whole units, or `None` for "off", which keeps the
506/// exact value: the step of a tab leader's advance (`layout.leader_steps_per_inch`) and of a
507/// glyph's stretch (`writer.glyph_stretch_steps_per_inch`).
508fn step_per_inch(
509    setting: Option<&Setting<OffOr>>,
510    key: &'static str,
511) -> Result<Option<Length>, Error> {
512    let per_inch = Length::UNITS_PER_INCH;
513    off_or(setting, key, |steps| {
514        (per_inch % steps == 0).then(|| Length::from_units(per_inch / steps))
515    })
516}
517
518/// The value of the variant that `key` names, from `variants`.
519fn variant<T: Copy>(
520    setting: Option<&Setting<String>>,
521    key: &'static str,
522    variants: &[(&str, T)],
523) -> Result<T, Error> {
524    let name = get(setting, key)?;
525    variants
526        .iter()
527        .find(|(variant, _)| *variant == name)
528        .map(|(_, value)| *value)
529        .ok_or(Error::Value(key))
530}
531
532/// Whether a time zone of `minutes` east of UTC lies less than a day from it either way.
533fn in_a_day(minutes: i32) -> bool {
534    minutes.unsigned_abs()
535        < u32::from(crate::params::HOURS_PER_DAY) * u32::from(crate::params::MINUTES_PER_HOUR)
536}
537
538/// The merged values that a layout takes from a target's profile, the caller's configuration
539/// and the development override, and the layer that set each.
540#[derive(Clone, Debug, PartialEq, Eq)]
541pub struct Profile {
542    target: Target,
543    configuration: Configuration,
544    overrides: Overrides,
545    id: String,
546    version: i64,
547    product: String,
548    builds: String,
549    renderer: String,
550    environment_name: String,
551    device: crate::grid::Device,
552    writer: Writer,
553    reader: crate::reader::settings::ReaderSettings,
554    quirks: crate::quirks::Quirks,
555    environment: Arc<FontEnvironment>,
556    /// Word's numbers of the symbol fonts, from the font environment's `symbol_font` tables.
557    symbol_fonts: Arc<SymbolFonts>,
558    /// The time zone of the machine in minutes east of UTC (`zone_minutes`), or none when no
559    /// layer gives one.
560    zone_minutes: Option<i32>,
561    merged: Arc<Merged>,
562}
563
564impl Profile {
565    /// The profile of a target with its own defaults, merged along its chain, once in a process.
566    ///
567    /// # Errors
568    ///
569    /// Returns an error when a profile does not read, or sets a value that F-Office does not
570    /// read yet.
571    pub fn of(target: Target) -> Result<Self, Error> {
572        static RESOLVED: PerTarget<Result<Profile, Error>> =
573            [const { OnceLock::new() }; TARGETS.len()];
574        target
575            .0
576            .cell(&RESOLVED)
577            .get_or_init(|| {
578                let merged = Merged::of(target)?.clone();
579                let built_in = merged.names.len();
580                Self::read(
581                    target,
582                    (defaults(target), Overrides::default()),
583                    merged,
584                    built_in,
585                )
586            })
587            .clone()
588    }
589
590    /// The profile of the target that `configuration` names, with the values of
591    /// `configuration` that differ from the target's defaults in a layer after its chain, named
592    /// `configuration` in the origins, and the layers of `overrides` after that.
593    ///
594    /// # Errors
595    ///
596    /// Returns an error when the configuration names no target, when a profile does not read,
597    /// when the configuration sets a value that F-Office does not read yet, when an override's
598    /// layer sets a key that only a profile sets or a key, quirk or variant that F-Office does
599    /// not know, and when a merged value is missing or wrong.
600    pub(crate) fn resolve(
601        configuration: &Configuration,
602        overrides: &Overrides,
603    ) -> Result<Self, Error> {
604        let target = configuration.target.ok_or(Error::Missing("target"))?;
605        let changes = configuration.changes_from(&defaults(target));
606        if changes.is_empty() && overrides.is_empty() {
607            return Self::of(target);
608        }
609        let mut merged = Merged::of(target)?.clone();
610        let built_in = merged.names.len();
611        let configured = Layer {
612            configuration: changes,
613            ..Layer::default()
614        };
615        merged.take("configuration", &configured)?;
616        for (name, layer) in overrides.layers() {
617            if layer
618                .inherits
619                .as_deref()
620                .is_some_and(|id| id != target.name())
621            {
622                return Err(Error::Inherits(name.to_owned()));
623            }
624            for (key, set) in [
625                ("product", layer.product.is_some()),
626                ("builds", layer.builds.is_some()),
627                ("renderer", layer.renderer.is_some()),
628                ("fonts.environment", layer.fonts.environment.is_some()),
629                ("configuration", !layer.configuration.is_empty()),
630            ] {
631                if set {
632                    return Err(Error::BuiltInKey(key));
633                }
634            }
635            merged.take(name, layer)?;
636        }
637        let configuration = Configuration {
638            target: Some(target),
639            ..merged.layer.configuration.clone()
640        };
641        Self::read(target, (configuration, overrides.clone()), merged, built_in)
642    }
643
644    /// Reads the values of `merged`, whose first `built_in` layers are the chain of `target`'s
645    /// profile, with the configuration and the override that it merges: the quirks first,
646    /// then everything built from them.
647    fn read(
648        target: Target,
649        (configuration, overrides): (Configuration, Overrides),
650        merged: Merged,
651        built_in: usize,
652    ) -> Result<Self, Error> {
653        let own = &merged.layer;
654        let (layout, writer) = (&own.layout, &own.writer);
655        let quirks = quirks(own)?;
656        let printer = own.configuration.printer;
657        let dots = printer
658            .dots_per_inch
659            .ok_or(Error::Missing("printer.dots_per_inch"))?;
660        let device = crate::grid::Device::of(i64::from(dots.get()), &quirks)
661            .ok_or(Error::Value("printer.dots_per_inch"))?
662            .with_leader_step(step_per_inch(
663                layout.leader_steps_per_inch.as_ref(),
664                "leader_steps_per_inch",
665            )?)
666            .with_bold_stroke(count_or_off(
667                layout.bold_stroke_parts.as_ref(),
668                "bold_stroke_parts",
669            )?)
670            .with_italic_slant(count_or_off(
671                layout.italic_slant_parts.as_ref(),
672                "italic_slant_parts",
673            )?);
674        let offsets = page_offsets(target, &merged, built_in, (device, quirks))?;
675        let device = match advances(layout, &quirks, offsets.0)? {
676            Some(advances) => device.with_advances(advances),
677            None => device,
678        };
679        let number_separators = own.configuration.number_separators;
680        // A target that writes chart labels in their number formats writes the separators of
681        // its machine.
682        if quirks.chart_label_formats == crate::quirks::ChartLabelFormats::Codes
683            && number_separators.is_none()
684        {
685            return Err(Error::Missing("number_separators"));
686        }
687        let zone_minutes = own.configuration.zone_minutes;
688        if zone_minutes.is_some_and(|minutes| !in_a_day(minutes)) {
689            return Err(Error::Value("zone_minutes"));
690        }
691        let environment_name = own
692            .fonts
693            .environment
694            .clone()
695            .ok_or(Error::Missing("fonts.environment"))?;
696        let environment = environment(target, &merged, built_in, &environment_name)?;
697        let symbol_fonts = Arc::new(SymbolFonts::of(&own.fonts.symbol_font).map_err(Error::Value)?);
698        let text = |value: &Option<String>, key| value.clone().ok_or(Error::Missing(key));
699        Ok(Self {
700            id: text(&own.id, "id")?,
701            version: match own.version {
702                Some(version) if version > 0 => version,
703                Some(_) => return Err(Error::Value("version")),
704                None => return Err(Error::Missing("version")),
705            },
706            product: text(&own.product, "product")?,
707            builds: text(&own.builds, "builds")?,
708            renderer: text(&own.renderer, "renderer")?,
709            environment_name,
710            device,
711            writer: profile_writer(writer, offsets)?,
712            reader: crate::reader::settings::ReaderSettings::of(&quirks)
713                .with_number_separators(number_separators),
714            quirks,
715            environment,
716            symbol_fonts,
717            zone_minutes,
718            target,
719            configuration,
720            overrides,
721            merged: Arc::new(merged),
722        })
723    }
724
725    /// The base target's profile, for tests.
726    #[cfg(test)]
727    pub(crate) fn base() -> Self {
728        Self::of(Target::base()).expect("the base profile reads")
729    }
730
731    /// The profile with the quirk `Q` at `variant`, in an override's layer after this one's,
732    /// for a test that names the variant that it means.
733    #[cfg(test)]
734    #[must_use]
735    pub(crate) fn with_variant<Q: crate::quirks::Quirk + PartialEq>(&self, variant: Q) -> Self {
736        let (name, _) = (Q::VARIANTS.iter())
737            .find(|(_, own)| *own == variant)
738            .expect("every variant has a name");
739        Self::resolve(
740            &self.configuration,
741            &self
742                .overrides
743                .with_layer("test", Layer::default().with_quirk(Q::NAME, name)),
744        )
745        .expect("the profile reads with the variant")
746    }
747
748    /// The target of the profile.
749    #[cfg(feature = "development")]
750    #[must_use]
751    pub const fn target(&self) -> Target {
752        self.target
753    }
754
755    /// The configuration that the profile merges, with the target's defaults where the caller
756    /// sets no value.
757    #[cfg(any(test, feature = "development"))]
758    #[must_use]
759    pub const fn configuration(&self) -> &Configuration {
760        &self.configuration
761    }
762
763    /// The development override that the profile merges after the configuration.
764    #[cfg(test)]
765    #[must_use]
766    pub(crate) const fn overrides(&self) -> &Overrides {
767        &self.overrides
768    }
769
770    /// The name of the layer that set the value at `path`, such as
771    /// `configuration.zone_minutes` or `quirks.NoteMarkPlace`: a profile's ID, `configuration`
772    /// for a value that the caller's configuration changes, or the name of an override's layer.
773    #[cfg(any(test, feature = "development"))]
774    #[must_use]
775    pub fn origin(&self, path: &str) -> Option<&str> {
776        self.merged.origin(path)
777    }
778
779    /// The variant of every quirk for the target, which only the decision modules read. See
780    /// `src/quirks.rs`.
781    #[must_use]
782    pub(crate) const fn quirks(&self) -> crate::quirks::Quirks {
783        self.quirks
784    }
785
786    /// The variant that the profile takes of each quirk, as the quirk's name and the variant's
787    /// name in a profile, in the order of `src/quirks.rs`: a list for tools, which read the
788    /// target's choices without naming the quirks' types.
789    #[cfg(any(test, feature = "development"))]
790    #[must_use]
791    pub fn variants(&self) -> Vec<(&'static str, &'static str)> {
792        self.quirks
793            .variants()
794            .iter()
795            .map(|chosen| (chosen.quirk, chosen.variant))
796            .collect()
797    }
798
799    /// Whether the profile takes the quirk variant `variant`, written `Quirk::Variant`, or
800    /// `None` when the registry has no such variant.
801    #[cfg(any(test, feature = "development"))]
802    #[must_use]
803    pub fn chooses(&self, variant: &str) -> Option<bool> {
804        let (quirk, name) = variant.split_once("::")?;
805        self.quirks
806            .variants()
807            .iter()
808            .find(|chosen| chosen.quirk == quirk && chosen.has(name))
809            .map(|chosen| chosen.variant == name)
810    }
811
812    /// The target's rule for the line metrics of stand-ins, which only the font choice reads.
813    #[must_use]
814    pub(crate) const fn stand_in_lines(&self) -> crate::text::StandInLines {
815        crate::text::StandInLines::of(&self.quirks)
816    }
817
818    /// How the target's PDF writer writes the page size. Only the output stage reads it.
819    #[must_use]
820    pub const fn writer(&self) -> Writer {
821        self.writer
822    }
823
824    /// The reader's settings, which only the reader reads. See `src/reader/settings.rs`.
825    #[must_use]
826    pub(crate) const fn reader_settings(&self) -> crate::reader::settings::ReaderSettings {
827        self.reader
828    }
829
830    /// The time zone of the machine, in minutes east of UTC, which only the layout reads. A
831    /// target that writes date properties in UTC needs none and takes 0 without one.
832    ///
833    /// # Errors
834    ///
835    /// Returns an error when the target writes a date property as its local date and no layer
836    /// gives the zone.
837    pub(crate) fn zone_minutes(&self) -> Result<i32, Error> {
838        match self.quirks.property_date_zone {
839            crate::quirks::PropertyDateZone::Utc => Ok(self.zone_minutes.unwrap_or(0)),
840            crate::quirks::PropertyDateZone::LocalDate => {
841                self.zone_minutes.ok_or(Error::Missing("zone_minutes"))
842            }
843        }
844    }
845
846    /// The layout device, which only the layout reads. See `src/grid.rs`.
847    #[must_use]
848    pub(crate) const fn device(&self) -> crate::grid::Device {
849        self.device
850    }
851
852    /// One dot of the layout device, to the nearest half-EMU, for tools that split a glyph's
853    /// offset from the target's place into whole dots and the rest that the PDF writer adds.
854    #[cfg(any(test, feature = "development"))]
855    #[must_use]
856    pub fn device_dot(&self) -> Length {
857        self.device.dots(1)
858    }
859
860    /// The path of the font environment that the profile takes (`fonts.environment`), in the
861    /// folder of the profiles.
862    #[cfg(any(test, feature = "development"))]
863    #[must_use]
864    pub fn font_environment_path(&self) -> &str {
865        &self.environment_name
866    }
867
868    /// The font environment, which the font choice reads.
869    #[cfg(any(test, feature = "development"))]
870    #[must_use]
871    pub fn font_environment(&self) -> &FontEnvironment {
872        &self.environment
873    }
874
875    /// The font environment of `Profile::font_environment`, shared.
876    pub(crate) fn shared_font_environment(&self) -> Arc<FontEnvironment> {
877        Arc::clone(&self.environment)
878    }
879
880    /// Word's numbers of the symbol fonts that the font environment holds, shared.
881    pub(crate) fn symbol_fonts(&self) -> Arc<SymbolFonts> {
882        Arc::clone(&self.symbol_fonts)
883    }
884
885    /// The font families that the configuration adds to the fonts of Word's machine
886    /// (`fonts.installed`), as Word has the family of a face that a document carries once it
887    /// opens the document. The font choice takes a face of such a family as the target's own,
888    /// whatever its PostScript name.
889    pub fn added_families(&self) -> impl Iterator<Item = &str> {
890        (self.merged.layer.configuration.fonts.installed.iter())
891            .filter(|(_, installed)| **installed)
892            .map(|(family, _)| family.as_str())
893    }
894
895    /// The families that draw families on this computer by the configuration (`fonts.use`),
896    /// each with the family that it draws: the font choice draws a family that this computer
897    /// has no face of with the named family, and that one as it draws any family.
898    pub fn used_families(&self) -> impl Iterator<Item = (&str, &str)> {
899        (self.merged.layer.configuration.fonts.uses.iter())
900            .map(|(family, uses)| (family.as_str(), uses.as_str()))
901    }
902}
903
904impl fmt::Display for Profile {
905    /// The ID, the version, the product, its builds and its renderer.
906    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
907        write!(
908            f,
909            "{} {} ({}, builds {}, {})",
910            self.id, self.version, self.product, self.builds, self.renderer
911        )
912    }
913}
914
915/// The writer's offsets across and down of `merged`, the profile of `target` after its first
916/// `built_in` layers, on the layout device `device` with the quirks `quirks`. A configuration
917/// that sets the page offset `none` gives no offset. The target's page offset belongs to the
918/// target's printer: on a printer of another resolution, the writer writes each place at its
919/// place on the device, unless the configuration sets the page offset or an override the
920/// writer's offset.
921fn page_offsets(
922    target: Target,
923    merged: &Merged,
924    built_in: usize,
925    (device, quirks): (crate::grid::Device, crate::quirks::Quirks),
926) -> Result<(WriterOffset, WriterOffset), Error> {
927    let none = (WriterOffset::NONE, WriterOffset::NONE);
928    if merged.layer.configuration.printer.page_offset == Some(PageOffset::None) {
929        return Ok(none);
930    }
931    let offsets = writer_offsets(
932        target.0,
933        (quirks.page_offset_sizes, quirks.page_offset_product),
934        &merged.layer.writer,
935    )?;
936    if merged.caller_set("configuration.printer.dots_per_inch", built_in)
937        && !merged.caller_set("configuration.printer.page_offset", built_in)
938        && !merged.caller_set("writer.offset", built_in)
939    {
940        let own_dots = Merged::of(target)?
941            .layer
942            .configuration
943            .printer
944            .dots_per_inch;
945        let own_device =
946            own_dots.and_then(|dots| crate::grid::Device::of(i64::from(dots.get()), &quirks));
947        if own_device.is_none_or(|own| own.dot_size() != device.dot_size()) {
948            return Ok(none);
949        }
950    }
951    Ok(offsets)
952}
953
954/// The font environment of `merged`, the profile of `target` whose environment file is
955/// `name`, after its first `built_in` layers: the chain's, made once in a process, while no
956/// later layer changes it. The families that the configuration adds to the fonts of Word's
957/// machine join its full font listing, and those that it removes leave it; without a full
958/// listing, a target takes every name, so an added family changes nothing there and a removed
959/// one becomes a family that it lacks.
960fn environment(
961    target: Target,
962    merged: &Merged,
963    built_in: usize,
964    name: &str,
965) -> Result<Arc<FontEnvironment>, Error> {
966    let installed = &merged.layer.configuration.fonts.installed;
967    let unchanged = installed.is_empty()
968        && !(merged.origins.iter()).any(|(path, at)| *at >= built_in && path.starts_with("fonts."));
969    if unchanged {
970        static ENVIRONMENTS: PerTarget<Result<Arc<FontEnvironment>, Error>> =
971            [const { OnceLock::new() }; TARGETS.len()];
972        return target
973            .0
974            .cell(&ENVIRONMENTS)
975            .get_or_init(|| {
976                let merged = Merged::of(target)?;
977                fonts::environment(&merged.layer.fonts)
978                    .map(Arc::new)
979                    .map_err(Error::Environment)
980            })
981            .clone();
982    }
983    let mut table = merged.layer.fonts.clone();
984    if environment_table(name)?.available.is_empty() {
985        table.available.clear();
986        for (family, _) in installed.iter().filter(|(_, installed)| !**installed) {
987            table.lacking.entry(family.clone()).or_default();
988        }
989    } else {
990        table.available.extend(
991            installed
992                .iter()
993                .map(|(family, installed)| (family.clone(), *installed)),
994        );
995    }
996    fonts::environment(&table)
997        .map(Arc::new)
998        .map_err(Error::Environment)
999}
1000
1001/// The advances of the rule of glyph steps that `quirks` names, with their numbers from
1002/// `layout`, which a configuration gives only for the variant that uses them, or `None` for the
1003/// device's own; `start` is the writer's offset across.
1004fn advances(
1005    layout: &Layout,
1006    quirks: &crate::quirks::Quirks,
1007    start: WriterOffset,
1008) -> Result<Option<crate::grid::Advances>, Error> {
1009    Ok(match quirks.grid_advances {
1010        crate::quirks::GridAdvances::RoundToPdfSteps => None,
1011        crate::quirks::GridAdvances::RightEdgeSteps => Some(crate::grid::Advances::RightEdge {
1012            bias: Length::from_units(positive(
1013                layout.glyph_step_bias_half_emus.as_ref(),
1014                "glyph_step_bias_half_emus",
1015            )?),
1016            limit: Length::from_units(positive(
1017                layout.glyph_edge_limit_half_emus.as_ref(),
1018                "glyph_edge_limit_half_emus",
1019            )?),
1020            segment: Length::from_units(positive(
1021                layout.glyph_segment_length_half_emus.as_ref(),
1022                "glyph_segment_length_half_emus",
1023            )?),
1024            point_steps: count_or_off(layout.glyph_point_steps.as_ref(), "glyph_point_steps")?,
1025            start,
1026        }),
1027    })
1028}
1029
1030/// The quirks of a merged layer. A profile names quirks of the registry only. See
1031/// `src/quirks.rs`.
1032fn quirks(layer: &Layer) -> Result<crate::quirks::Quirks, Error> {
1033    if let Some(name) = layer
1034        .quirks
1035        .keys()
1036        .find(|name| !crate::quirks::NAMES.contains(&name.as_str()))
1037    {
1038        return Err(Error::UnknownQuirk(name.clone()));
1039    }
1040    crate::quirks::Quirks::read(&|name| {
1041        layer.quirks.get(name).map(|setting| setting.value.as_str())
1042    })
1043    .map_err(|error| match error {
1044        crate::quirks::QuirkError::Missing(name) => Error::Missing(name),
1045        crate::quirks::QuirkError::Variant(name) => Error::Value(name),
1046    })
1047}
1048
1049/// The names of the ways in which a writer writes a cropped picture (`writer.picture_crop`,
1050/// [`PictureCrop`]).
1051const PICTURE_CROPS: [(&str, PictureCrop); 3] = [
1052    ("whole_file_under_clip", PictureCrop::WholeFileUnderClip),
1053    ("visible_part", PictureCrop::VisiblePart),
1054    ("visible_part_at_scale", PictureCrop::VisiblePartAtScale),
1055];
1056
1057/// The names of the ways in which a writer mixes the colors of a picture with an alpha when it
1058/// resamples it (`writer.alpha_mix`, [`AlphaMix`]).
1059const ALPHA_MIXES: [(&str, AlphaMix); 2] =
1060    [("plain", AlphaMix::Plain), ("weighted", AlphaMix::Weighted)];
1061
1062/// A linear limit of one measure, from its count.
1063type LinearLimitOf = fn(NonZeroU32) -> LinearLimit;
1064
1065/// The names of the measures of a writer's linear limit (`writer.linear_limit_of`): the count of
1066/// a picture's source pixels, or its larger side ([`LinearLimit`]).
1067const LINEAR_LIMIT_MEASURES: [(&str, LinearLimitOf); 2] =
1068    [("pixels", LinearLimit::Pixels), ("side", LinearLimit::Side)];
1069
1070/// The pictures that a writer's filter resamples by the linear interpolation: those whose
1071/// measure (`writer.linear_limit_of`) is at most `writer.linear_limit`.
1072fn linear_limit(writer: &WriterTable) -> Result<LinearLimit, Error> {
1073    let measure = variant(
1074        writer.linear_limit_of.as_ref(),
1075        "linear_limit_of",
1076        &LINEAR_LIMIT_MEASURES,
1077    )?;
1078    let count: u32 = number(
1079        get(writer.linear_limit.as_ref(), "linear_limit")?,
1080        "linear_limit",
1081        |count| count > 0,
1082    )?;
1083    NonZeroU32::new(count)
1084        .map(measure)
1085        .ok_or(Error::Value("linear_limit"))
1086}
1087
1088/// The densities from which and below which a writer resamples a picture
1089/// (`writer.picture_limit_ppi` and `writer.picture_ppi`), or `None` when both are "off". A
1090/// profile that sets only one of them gives an error that names both.
1091fn picture_density(writer: &WriterTable) -> Result<Option<PictureDensity>, Error> {
1092    let keys = ("picture_limit_ppi", "picture_ppi");
1093    match (
1094        count_or_off(writer.picture_limit_ppi.as_ref(), keys.0)?,
1095        count_or_off(writer.picture_ppi.as_ref(), keys.1)?,
1096    ) {
1097        (Some(limit_ppi), Some(ppi)) => Ok(Some(PictureDensity { limit_ppi, ppi })),
1098        (None, None) => Ok(None),
1099        _ => Err(Error::Pair(keys.0, keys.1)),
1100    }
1101}
1102
1103/// The keys of a writer's palette density, which are "off" or set together: the limits of a
1104/// palette of 1 bit, the density of 1 bit, and the limits of 4 and 8 bits, in pixels per inch.
1105const PALETTE_DENSITY_KEYS: [&str; 4] = [
1106    "palette_one_bit_limit_ppi",
1107    "palette_one_bit_ppi",
1108    "palette_four_bits_limit_ppi",
1109    "palette_eight_bits_limit_ppi",
1110];
1111
1112/// The limits and the density with which a writer resamples a PNG picture of a palette of a
1113/// class ([`PALETTE_DENSITY_KEYS`]), or `None` when all four keys are "off". A configuration
1114/// that sets some of them and leaves others "off" gives an error that names them all.
1115fn palette_density(writer: &WriterTable) -> Result<Option<PaletteDensity>, Error> {
1116    let [one_bit_limit, one_bit, four_bits_limit, eight_bits_limit] = PALETTE_DENSITY_KEYS;
1117    let values = (
1118        count_or_off(writer.palette_one_bit_limit_ppi.as_ref(), one_bit_limit)?,
1119        count_or_off(writer.palette_one_bit_ppi.as_ref(), one_bit)?,
1120        count_or_off(writer.palette_four_bits_limit_ppi.as_ref(), four_bits_limit)?,
1121        count_or_off(
1122            writer.palette_eight_bits_limit_ppi.as_ref(),
1123            eight_bits_limit,
1124        )?,
1125    );
1126    match values {
1127        (
1128            Some(one_bit_limit_ppi),
1129            Some(one_bit_ppi),
1130            Some(four_bits_limit_ppi),
1131            Some(eight_bits_limit_ppi),
1132        ) => Ok(Some(PaletteDensity {
1133            one_bit_limit_ppi,
1134            one_bit_ppi,
1135            four_bits_limit_ppi,
1136            eight_bits_limit_ppi,
1137        })),
1138        (None, None, None, None) => Ok(None),
1139        _ => Err(Error::Group(&PALETTE_DENSITY_KEYS)),
1140    }
1141}
1142
1143/// The keys of a writer's second test of JPEG pictures, which are "off" or set together: the
1144/// sample share and the whole share in thousandths, and the floor in bytes.
1145const JPEG_SAMPLE_KEYS: [&str; 3] = ["jpeg_sample_share", "jpeg_sample_floor", "jpeg_whole_share"];
1146
1147/// The second test of a writer that writes PNG pictures as JPEG files ([`JPEG_SAMPLE_KEYS`]), or
1148/// `None` when all three keys are "off". A profile that sets some of them and leaves others
1149/// "off", or gives a share above 1,000, gives an error that names them all.
1150fn jpeg_sample(writer: &WriterTable) -> Result<Option<JpegSample>, Error> {
1151    let [share, floor, whole] = JPEG_SAMPLE_KEYS;
1152    let values = (
1153        count_or_off(writer.jpeg_sample_share.as_ref(), share)?,
1154        count_or_off(writer.jpeg_sample_floor.as_ref(), floor)?,
1155        count_or_off(writer.jpeg_whole_share.as_ref(), whole)?,
1156    );
1157    match values {
1158        (Some(share), Some(floor), Some(whole)) => {
1159            let (Ok(share), Ok(whole)) = (u16::try_from(share.get()), u16::try_from(whole.get()))
1160            else {
1161                return Err(Error::Group(&JPEG_SAMPLE_KEYS));
1162            };
1163            JpegSample::new(share, floor.get(), whole)
1164                .map(Some)
1165                .ok_or(Error::Group(&JPEG_SAMPLE_KEYS))
1166        }
1167        (None, None, None) => Ok(None),
1168        _ => Err(Error::Group(&JPEG_SAMPLE_KEYS)),
1169    }
1170}
1171
1172/// The writer that the profile's `writer.*` keys give, with its offsets across and down
1173/// ([`writer_offsets`]).
1174fn profile_writer(
1175    writer: &WriterTable,
1176    (horizontal_offset, vertical_offset): (WriterOffset, WriterOffset),
1177) -> Result<Writer, Error> {
1178    // A count of decimals: any number that its type holds.
1179    let any: fn(i64) -> bool = |_| true;
1180    let steps = positive(writer.page_steps_per_inch.as_ref(), "page_steps_per_inch")?;
1181    let stretch = whole(
1182        writer.vertical_stretch_steps.as_ref(),
1183        "vertical_stretch_steps",
1184    )?;
1185    // The writer rounds how far its stretch moves a glyph's baseline to whole steps of this
1186    // many to the inch, or moves it by the exact stretch for "off".
1187    let glyph_step = step_per_inch(
1188        writer.glyph_stretch_steps_per_inch.as_ref(),
1189        "glyph_stretch_steps_per_inch",
1190    )?;
1191    let Decimal(stretch_offset) = get(writer.stretch_offset.as_ref(), "stretch_offset")?;
1192    let stretch_factors =
1193        stretch_factors(&get(writer.stretch_factors.as_ref(), "stretch_factors")?)?;
1194    let digits = count_or_off(writer.digits.as_ref(), "digits")?;
1195    let least_decimals = number(
1196        get(writer.least_decimals.as_ref(), "least_decimals")?,
1197        "least_decimals",
1198        any,
1199    )?;
1200    let picture_digits = count_or_off(writer.picture_digits.as_ref(), "picture_digits")?;
1201    let rectangle_steps = count_or_off(
1202        writer.rectangle_steps_per_inch.as_ref(),
1203        "rectangle_steps_per_inch",
1204    )?;
1205    let baseline_steps = count_or_off(
1206        writer.baseline_steps_per_inch.as_ref(),
1207        "baseline_steps_per_inch",
1208    )?;
1209    let jpeg_quality = off_or(writer.jpeg_quality.as_ref(), "jpeg_quality", |quality| {
1210        u8::try_from(quality).ok().and_then(JpegQuality::new)
1211    })?;
1212    let jpeg_share = off_or(writer.jpeg_share.as_ref(), "jpeg_share", |share| {
1213        u16::try_from(share).ok().and_then(JpegShare::new)
1214    })?;
1215    let jpeg_sample = jpeg_sample(writer)?;
1216    let density = picture_density(writer)?;
1217    let palettes = palette_density(writer)?;
1218    let crop = variant(writer.picture_crop.as_ref(), "picture_crop", &PICTURE_CROPS)?;
1219    let alpha_mix = variant(writer.alpha_mix.as_ref(), "alpha_mix", &ALPHA_MIXES)?;
1220    let linear_limit = linear_limit(writer)?;
1221    Ok(writer_of(steps)?
1222        .with_vertical_stretch(stretch)
1223        .with_glyph_stretch_step(glyph_step)
1224        .ok_or(Error::Value("glyph_stretch_steps_per_inch"))?
1225        .with_stretch_factors(stretch_offset, &stretch_factors)
1226        .ok_or(Error::Value("stretch_factors"))?
1227        .with_digits(digits)
1228        .with_least_decimals(least_decimals)
1229        .with_rectangle_steps(rectangle_steps)
1230        .with_baseline_steps(baseline_steps)
1231        .with_picture_digits(picture_digits)
1232        .with_horizontal_offset(horizontal_offset)
1233        .with_vertical_offset(vertical_offset)
1234        .with_jpeg_quality(jpeg_quality)
1235        .with_jpeg_share(jpeg_share)
1236        .with_jpeg_sample(jpeg_sample)
1237        .with_picture_density(density)
1238        .with_palette_density(palettes)
1239        .with_picture_crop(crop)
1240        .with_alpha_mix(alpha_mix)
1241        .with_linear_limit(linear_limit))
1242}
1243
1244/// The stretch factors of `writer.stretch_factors`: a list, empty or of entries `height factor`
1245/// split by commas, each a written page height in points and its factor as decimal numbers, such
1246/// as `"792 1.003165, 842 0.982394"`.
1247fn stretch_factors(list: &str) -> Result<Vec<(Length, f_office_paint::Fraction)>, Error> {
1248    let wrong = || Error::Value("stretch_factors");
1249    list.split(',')
1250        .map(str::trim)
1251        .filter(|entry| !entry.is_empty())
1252        .map(|entry| {
1253            let mut parts = entry.split_whitespace();
1254            let (Some(height), Some(factor), None) = (parts.next(), parts.next(), parts.next())
1255            else {
1256                return Err(wrong());
1257            };
1258            let (points, scale) = decimal_fraction(height).ok_or_else(wrong)?;
1259            let units = points
1260                .checked_mul(Length::UNITS_PER_POINT)
1261                .filter(|units| *units > 0 && units % scale == 0)
1262                .ok_or_else(wrong)?;
1263            let factor = decimal_fraction(factor)
1264                .filter(|(value, _)| *value > 0)
1265                .ok_or_else(wrong)?;
1266            Ok((Length::from_units(units / scale), factor))
1267        })
1268        .collect()
1269}
1270
1271/// The writer that rounds the page size to `steps` per inch.
1272fn writer_of(steps: i64) -> Result<Writer, Error> {
1273    let per_inch = Length::UNITS_PER_INCH;
1274    if per_inch % steps != 0 {
1275        return Err(Error::Value("page_steps_per_inch"));
1276    }
1277    Writer::new(Length::from_units(per_inch / steps)).ok_or(Error::Value("page_steps_per_inch"))
1278}
1279
1280/// The form of the writer's offset of a place (`writer.offset`), each of which reads only its
1281/// own keys.
1282#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1283enum OffsetForm {
1284    /// The writer writes each place where the layout puts it (`"off"`).
1285    Off,
1286    /// The place across divided by the share, plus the bias, rounded to the step, across only
1287    /// (`"share_of_place"`, the keys `start_offset_*`).
1288    ShareOfPlace,
1289    /// Whole steps as if the page were larger, across and down (`"page_steps"`, the keys
1290    /// `offset_page_*`).
1291    PageSteps,
1292}
1293
1294/// The names of the forms of the writer's offset (`writer.offset`, [`OffsetForm`]).
1295const OFFSET_FORMS: [(&str, OffsetForm); 3] = [
1296    ("off", OffsetForm::Off),
1297    ("share_of_place", OffsetForm::ShareOfPlace),
1298    ("page_steps", OffsetForm::PageSteps),
1299];
1300
1301/// The writer's offsets across and down the page for the target `id`, in the form that
1302/// `writer.offset` names ([`OffsetForm`]), from the keys of that form: none; the place divided
1303/// by the share, plus the bias, rounded to the step, across only; or whole steps as if the page
1304/// were larger, across and down, with the steps that a page's paper form gives when the quirk
1305/// `sizes` asks for them ([`page_sizes`]) and the product that the quirk `product` names. It
1306/// moves a text object's start, a glyph's baseline (down) and a filled rectangle's edges.
1307fn writer_offsets(
1308    id: Id,
1309    (sizes, product): (
1310        crate::quirks::PageOffsetSizes,
1311        crate::quirks::PageOffsetProduct,
1312    ),
1313    writer: &WriterTable,
1314) -> Result<(WriterOffset, WriterOffset), Error> {
1315    match variant(writer.offset.as_ref(), "offset", &OFFSET_FORMS)? {
1316        OffsetForm::Off => Ok((WriterOffset::NONE, WriterOffset::NONE)),
1317        OffsetForm::ShareOfPlace => {
1318            let across = WriterOffset::EveryPage(f_office_paint::Offset::Share {
1319                share: positive(writer.start_offset_share.as_ref(), "start_offset_share")?,
1320                bias: whole(
1321                    writer.start_offset_bias_half_emus.as_ref(),
1322                    "start_offset_bias_half_emus",
1323                )?,
1324                step: positive(
1325                    writer.start_offset_step_half_emus.as_ref(),
1326                    "start_offset_step_half_emus",
1327                )?,
1328            });
1329            Ok((across, WriterOffset::NONE))
1330        }
1331        OffsetForm::PageSteps => {
1332            let per_inch = positive(
1333                writer.offset_page_steps_per_inch.as_ref(),
1334                "offset_page_steps_per_inch",
1335            )?;
1336            let parts = positive(
1337                writer.offset_page_parts_per_step.as_ref(),
1338                "offset_page_parts_per_step",
1339            )?;
1340            let steps = positive(
1341                writer.offset_page_steps_hundred_thousandths.as_ref(),
1342                "offset_page_steps_hundred_thousandths",
1343            )?;
1344            let product = match product {
1345                crate::quirks::PageOffsetProduct::Exact => f_office_paint::OffsetProduct::Exact,
1346                crate::quirks::PageOffsetProduct::Binary32 => {
1347                    f_office_paint::OffsetProduct::Binary32 {
1348                        dots_per_inch: positive(
1349                            writer.page_steps_per_inch.as_ref(),
1350                            "page_steps_per_inch",
1351                        )?,
1352                    }
1353                }
1354            };
1355            let offset = match sizes {
1356                crate::quirks::PageOffsetSizes::OneFactor => {
1357                    WriterOffset::EveryPage(f_office_paint::Offset::Page {
1358                        steps: in_hundred_thousandths(steps),
1359                        parts,
1360                        per_inch,
1361                        product,
1362                    })
1363                }
1364                crate::quirks::PageOffsetSizes::PaperForms => {
1365                    WriterOffset::Sizes(page_sizes(id, writer, (steps, parts, per_inch), product)?)
1366                }
1367            };
1368            Ok((offset, offset))
1369        }
1370    }
1371}
1372
1373/// `steps` hundred-thousandths of a step, the unit of the registry and of the profile's
1374/// `writer.offset_page_steps_hundred_thousandths`.
1375const fn in_hundred_thousandths(steps: i64) -> f_office_paint::Fraction {
1376    (steps, f_office_paint::STEP_PARTS)
1377}
1378
1379/// The page sizes of the writer's page offset for the target `id`, built once for each target and product,
1380/// each in the configuration's `parts` of a step, steps of 1/`per_inch` inch and the written dots
1381/// per inch of `writer.page_steps_per_inch`: the measured sizes of the parameter registry
1382/// (`params::PAGE_4961_7016_STEPS` and the others), each in the orientation of the sections that
1383/// measured it; a Letter page in every orientation, with the steps across of
1384/// `params::PAGE_5100_6600_ACROSS_STEPS` and the profile's steps, Letter's factor `letter`,
1385/// down; a page of Letter across with Letter's factor on both axes; and the class rule
1386/// (`params::PAPER_FORM_CLASS_RULE`) for every other page; each offset with the product `product`.
1387fn page_sizes(
1388    id: Id,
1389    writer: &WriterTable,
1390    (letter, parts, per_inch): (i64, i64, i64),
1391    product: f_office_paint::OffsetProduct,
1392) -> Result<&'static f_office_paint::PageSizes, Error> {
1393    use f_office_paint::{GivenSize, OffsetProduct, Orientation};
1394    // One set of sizes for each target and product: a caller may choose the target's other
1395    // product (`PageOffsetProduct`), and the target's own profile keeps its sizes.
1396    static EXACT: PerTarget<Result<f_office_paint::PageSizes, Error>> =
1397        [const { OnceLock::new() }; TARGETS.len()];
1398    static BINARY32: PerTarget<Result<f_office_paint::PageSizes, Error>> =
1399        [const { OnceLock::new() }; TARGETS.len()];
1400    let sizes = match product {
1401        OffsetProduct::Exact => &EXACT,
1402        OffsetProduct::Binary32 { .. } => &BINARY32,
1403    };
1404    id.cell(sizes)
1405        .get_or_init(|| {
1406            let measured = |orientation, (dots, (across, down))| GivenSize {
1407                dots,
1408                orientation: Some(orientation),
1409                steps: (
1410                    Some(in_hundred_thousandths(across)),
1411                    Some(in_hundred_thousandths(down)),
1412                ),
1413            };
1414            // The near-A4 sizes were measured on sections that set no orientation, A4 across
1415            // on sections that set the landscape orientation.
1416            let mut sizes: Vec<GivenSize> = [
1417                crate::params::PAGE_4961_7016_STEPS,
1418                crate::params::PAGE_4960_7015_STEPS,
1419            ]
1420            .into_iter()
1421            .map(|size| measured(Orientation::Portrait, size))
1422            .collect();
1423            sizes.push(measured(
1424                Orientation::Landscape,
1425                crate::params::PAGE_7016_4961_STEPS,
1426            ));
1427            let ((width, height), letter_across) = crate::params::PAGE_5100_6600_ACROSS_STEPS;
1428            let letter = in_hundred_thousandths(letter);
1429            sizes.push(GivenSize {
1430                dots: (width, height),
1431                orientation: None,
1432                steps: (Some(in_hundred_thousandths(letter_across)), Some(letter)),
1433            });
1434            // Letter across in a landscape section takes Letter's steps with the sides swapped:
1435            // Letter's factor across and the steps across a Letter page down. In any other
1436            // section it takes Letter's factor across, and down the page entry of its paper form.
1437            sizes.push(GivenSize {
1438                dots: (height, width),
1439                orientation: Some(Orientation::Landscape),
1440                steps: (Some(letter), Some(in_hundred_thousandths(letter_across))),
1441            });
1442            sizes.push(GivenSize {
1443                dots: (height, width),
1444                orientation: None,
1445                steps: (Some(letter), None),
1446            });
1447            let dots_per_inch =
1448                positive(writer.page_steps_per_inch.as_ref(), "page_steps_per_inch")?;
1449            Ok(f_office_paint::PageSizes::new(
1450                (parts, per_inch, dots_per_inch),
1451                product,
1452                sizes,
1453                &crate::params::PAPER_FORM_CLASS_RULE,
1454            ))
1455        })
1456        .as_ref()
1457        .map_err(Clone::clone)
1458}
1459
1460#[cfg(any(test, feature = "development"))]
1461impl Layer {
1462    /// The layer with the quirk `name` at its variant `variant`, by their names in a
1463    /// configuration, in place of any variant of it that the layer sets already.
1464    #[must_use]
1465    pub fn with_quirk(mut self, name: &str, variant: &str) -> Self {
1466        self.quirks.insert(
1467            name.to_owned(),
1468            Setting {
1469                value: variant.to_owned(),
1470            },
1471        );
1472        self
1473    }
1474}
1475
1476/// An error in a target's name, a profile or a configuration.
1477#[derive(Clone, Debug, PartialEq, Eq)]
1478#[non_exhaustive]
1479pub enum Error {
1480    /// No target has this name.
1481    UnknownTarget(String),
1482    /// No profile has this name, as `inherits` names it.
1483    UnknownProfile(String),
1484    /// No font environment has this name, as `fonts.environment` names it.
1485    UnknownEnvironment(String),
1486    /// A profile does not read as a profile, with what is wrong.
1487    Read {
1488        /// The profile's or the font environment's name.
1489        profile: String,
1490        /// What is wrong, and where.
1491        message: String,
1492    },
1493    /// The chain of `inherits` from this profile does not end, or an override's layer named
1494    /// this inherits from another profile than its target's.
1495    Inherits(String),
1496    /// An override's layer sets a key that only a profile or the configuration sets.
1497    BuiltInKey(&'static str),
1498    /// The merged profile or the configuration lacks a key.
1499    Missing(&'static str),
1500    /// A value has the wrong kind, or a number is not positive.
1501    Value(&'static str),
1502    /// The configuration sets a key that F-Office does not read yet.
1503    NotRead(&'static str),
1504    /// A profile sets one key of a pair that is "off" or set together, such as the two
1505    /// densities of a resampled picture, and leaves the other "off".
1506    Pair(&'static str, &'static str),
1507    /// A profile sets some keys of a group that are "off" or set together, such as the keys
1508    /// of a palette density, and leaves others "off".
1509    Group(&'static [&'static str]),
1510    /// A profile sets a quirk that the registry lacks.
1511    UnknownQuirk(String),
1512    /// The merged font environment does not build.
1513    Environment(EnvironmentError),
1514}
1515
1516impl fmt::Display for Error {
1517    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1518        match self {
1519            Self::UnknownTarget(name) => write!(f, "no target is named {name:?}"),
1520            Self::UnknownProfile(name) => write!(f, "no profile is named {name:?}"),
1521            Self::UnknownEnvironment(name) => {
1522                write!(f, "no font environment is named {name:?}")
1523            }
1524            Self::Read { profile, message } => {
1525                write!(f, "the profile {profile} does not read: {message}")
1526            }
1527            Self::Inherits(name) => write!(
1528                f,
1529                "the profile {name} inherits from a profile that it cannot inherit from"
1530            ),
1531            Self::BuiltInKey(key) => {
1532                write!(
1533                    f,
1534                    "an override sets {key}, which only a profile or the configuration sets"
1535                )
1536            }
1537            Self::Missing(key) => write!(f, "a profile has no {key}"),
1538            Self::Value(key) => write!(f, "a profile has a wrong value for {key}"),
1539            Self::NotRead(key) => write!(
1540                f,
1541                "the configuration sets {key}, which F-Office does not read yet"
1542            ),
1543            Self::Pair(one, other) => write!(
1544                f,
1545                "a profile sets only one of {one} and {other}, which are \"off\" or set together"
1546            ),
1547            Self::Group(keys) => write!(
1548                f,
1549                "a profile sets only some of {}, which are \"off\" or set together",
1550                keys.join(", ")
1551            ),
1552            Self::UnknownQuirk(name) => write!(f, "no quirk of the registry is named {name:?}"),
1553            Self::Environment(error) => write!(f, "{error}"),
1554        }
1555    }
1556}
1557
1558impl std::error::Error for Error {
1559    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1560        match self {
1561            Self::Environment(error) => Some(error),
1562            _ => None,
1563        }
1564    }
1565}
1566
1567#[cfg(test)]
1568mod tests;