use std::collections::BTreeMap;
use std::fmt::{self, Write as _};
use std::num::NonZeroU32;
use std::str::FromStr;
use std::sync::{Arc, OnceLock};
use crate::font_choice::SymbolFonts;
use f_office_fonts::environment::{EnvironmentError, FontEnvironment};
use f_office_paint::{
AlphaMix, JpegQuality, JpegSample, JpegShare, LinearLimit, PaletteDensity, PictureCrop,
PictureDensity, Writer, WriterOffset,
};
use f_office_units::Length;
use crate::configuration::{Configuration, PageOffset};
#[cfg(any(test, feature = "development"))]
mod facts;
#[cfg(feature = "development")]
pub mod fonts;
#[cfg(not(feature = "development"))]
pub(crate) mod fonts;
mod layer;
mod overrides;
#[cfg(feature = "development")]
pub use facts::{Entry, Facts, Section};
#[cfg(all(test, not(feature = "development")))]
use facts::{Facts, Section};
use fonts::Table;
pub(crate) use layer::{Decimal, Layer, Layout, OffOr, Setting, Writer as WriterTable};
#[cfg(feature = "development")]
pub use overrides::Overrides;
#[cfg(not(feature = "development"))]
pub(crate) use overrides::Overrides;
use layer::decimal_fraction;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Target(Id);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
enum Id {
#[cfg(any(test, feature = "preview-targets"))]
Mac,
#[cfg(any(test, feature = "preview-targets"))]
Web,
#[default]
Win,
}
type PerTarget<T> = [OnceLock<T>; TARGETS.len()];
impl Id {
#[cfg(any(test, feature = "preview-targets"))]
const fn cell<T>(self, cells: &PerTarget<T>) -> &OnceLock<T> {
let [mac, web, win] = cells;
match self {
Self::Mac => mac,
Self::Web => web,
Self::Win => win,
}
}
#[cfg(not(any(test, feature = "preview-targets")))]
const fn cell<T>(self, cells: &PerTarget<T>) -> &OnceLock<T> {
let [win] = cells;
match self {
Self::Win => win,
}
}
}
#[cfg(any(test, feature = "preview-targets"))]
const TARGETS: [(Id, &str); 3] = [
(Id::Mac, "word-mac"),
(Id::Web, "word-web"),
(Id::Win, "word-win"),
];
#[cfg(not(any(test, feature = "preview-targets")))]
const TARGETS: [(Id, &str); 1] = [(Id::Win, "word-win")];
macro_rules! built {
($name:literal, $json:literal) => {
($name, include_str!(concat!(env!("OUT_DIR"), "/", $json)))
};
}
#[cfg(any(test, feature = "preview-targets"))]
const BUILT_IN: [(&str, &str); 3] = [
built!("word-mac", "word-mac.json"),
built!("word-web", "word-web.json"),
built!("word-win", "word-win.json"),
];
#[cfg(not(any(test, feature = "preview-targets")))]
const BUILT_IN: [(&str, &str); 2] = [
built!("word-mac", "word-mac.json"),
built!("word-win", "word-win.json"),
];
#[cfg(any(test, feature = "preview-targets"))]
const FONT_ENVIRONMENTS: [(&str, &str); 3] = [
built!("fonts/word-mac.toml", "fonts-word-mac.json"),
built!("fonts/word-web.toml", "fonts-word-web.json"),
built!("fonts/word-win.toml", "fonts-word-win.json"),
];
#[cfg(not(any(test, feature = "preview-targets")))]
const FONT_ENVIRONMENTS: [(&str, &str); 1] = [built!("fonts/word-win.toml", "fonts-word-win.json")];
impl Target {
pub fn all() -> impl Iterator<Item = Self> {
TARGETS.iter().map(|(id, _)| Self(*id))
}
#[cfg(any(test, feature = "development"))]
#[must_use]
pub const fn base() -> Self {
Self(Id::Mac)
}
fn name(self) -> &'static str {
TARGETS
.iter()
.find(|(id, _)| *id == self.0)
.map_or("", |(_, name)| name)
}
}
impl FromStr for Target {
type Err = Error;
fn from_str(name: &str) -> Result<Self, Error> {
Self::all()
.find(|target| target.name() == name)
.ok_or_else(|| Error::UnknownTarget(name.to_owned()))
}
}
impl fmt::Display for Target {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
impl serde::Serialize for Target {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.name())
}
}
impl<'de> serde::Deserialize<'de> for Target {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let name = String::deserialize(deserializer)?;
name.parse().map_err(serde::de::Error::custom)
}
}
#[cfg(feature = "development")]
impl schemars::JsonSchema for Target {
fn schema_name() -> std::borrow::Cow<'static, str> {
"Target".into()
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
let ids: Vec<String> = Self::all().map(|target| target.to_string()).collect();
schemars::json_schema!({
"description": "The Word whose pages the layout reproduces, by its ID.",
"type": "string",
"enum": ids
})
}
}
static PROFILES_READ: [OnceLock<Result<Layer, Error>>; BUILT_IN.len()] =
[const { OnceLock::new() }; BUILT_IN.len()];
static ENVIRONMENTS_READ: [OnceLock<Result<Table, Error>>; FONT_ENVIRONMENTS.len()] =
[const { OnceLock::new() }; FONT_ENVIRONMENTS.len()];
fn built_in(name: &str) -> Result<&'static Layer, Error> {
let layer = read_once((&BUILT_IN, &PROFILES_READ), name, Error::UnknownProfile)?;
if layer.id.as_deref() != Some(name) {
return Err(Error::Missing("id"));
}
Ok(layer)
}
fn environment_table(name: &str) -> Result<&'static Table, Error> {
read_once(
(&FONT_ENVIRONMENTS, &ENVIRONMENTS_READ),
name,
Error::UnknownEnvironment,
)
}
type ReadOnce<T> = [OnceLock<Result<T, Error>>];
fn read_once<T: serde::de::DeserializeOwned>(
(files, cells): (&[(&str, &str)], &'static ReadOnce<T>),
name: &str,
unknown: fn(String) -> Error,
) -> Result<&'static T, Error> {
let at = files
.iter()
.position(|(own, _)| *own == name)
.ok_or_else(|| unknown(name.to_owned()))?;
let (cell, (own, json)) = cells
.get(at)
.zip(files.get(at))
.ok_or_else(|| unknown(name.to_owned()))?;
cell.get_or_init(|| {
serde_json::from_str(json).map_err(|error| Error::Read {
profile: (*own).to_owned(),
message: error.to_string(),
})
})
.as_ref()
.map_err(Clone::clone)
}
fn chain(name: &str) -> Result<Vec<(&'static str, &'static Layer)>, Error> {
let mut chain = Vec::new();
let mut next = Some(name.to_owned());
while let Some(name) = next.take() {
if chain.len() == BUILT_IN.len() {
return Err(Error::Inherits(name));
}
let layer = built_in(&name)?;
let id = BUILT_IN
.iter()
.find(|(own, _)| *own == name)
.map_or("", |(own, _)| own);
chain.push((id, layer));
next.clone_from(&layer.inherits);
}
chain.reverse();
Ok(chain)
}
pub(crate) fn defaults(target: Target) -> Configuration {
let mut configuration =
Merged::of(target).map_or_default(|merged| merged.layer.configuration.clone());
configuration.target = Some(target);
configuration
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
struct Merged {
layer: Layer,
origins: BTreeMap<String, usize>,
names: Vec<Arc<str>>,
}
pub(crate) fn path_key(key: &str) -> String {
if !key.is_empty()
&& key
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
{
return key.to_owned();
}
let mut out = String::with_capacity(key.len() + 2);
out.push('"');
for ch in key.chars() {
match ch {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
ch if ch.is_control() => {
let _ = write!(out, "\\u{:04X}", u32::from(ch));
}
ch => out.push(ch),
}
}
out.push('"');
out
}
impl Merged {
fn of(target: Target) -> Result<&'static Self, Error> {
static MERGED: PerTarget<Result<Merged, Error>> =
[const { OnceLock::new() }; TARGETS.len()];
target
.0
.cell(&MERGED)
.get_or_init(|| {
let layers = chain(target.name())?;
let last_env = layers
.iter()
.rposition(|(_, layer)| layer.fonts.environment.is_some());
let mut merged = Self::default();
for (index, (name, layer)) in layers.into_iter().enumerate() {
let load_env = last_env == Some(index);
merged.take_with_env(name, layer, load_env)?;
}
Ok(merged)
})
.as_ref()
.map_err(Clone::clone)
}
fn take(&mut self, name: &str, layer: &Layer) -> Result<(), Error> {
self.take_with_env(name, layer, true)
}
fn take_with_env(&mut self, name: &str, layer: &Layer, load_env: bool) -> Result<(), Error> {
let at = self.names.len();
self.names.push(name.into());
if load_env && let Some(environment) = &layer.fonts.environment {
let table = environment_table(environment)?;
self.origins.retain(|path, _| !path.starts_with("fonts."));
self.layer.fonts = Table {
environment: Some(environment.clone()),
..Table::default()
};
self.origins.insert("fonts.environment".to_owned(), at);
let origins = &mut self.origins;
self.layer.fonts.merge(table, &mut |path| {
origins.insert(fonts_path(path), at);
});
}
let (own, origins) = (&mut self.layer, &mut self.origins);
let mut set = |path: String| {
origins.insert(path, at);
};
for (key, own, later) in [
("id", &mut own.id, &layer.id),
("inherits", &mut own.inherits, &layer.inherits),
("product", &mut own.product, &layer.product),
("builds", &mut own.builds, &layer.builds),
("renderer", &mut own.renderer, &layer.renderer),
] {
if let Some(value) = later {
*own = Some(value.clone());
set(key.to_owned());
}
}
if let Some(version) = layer.version {
own.version = Some(version);
set("version".to_owned());
}
own.configuration.merge(&layer.configuration, &mut |path| {
set(format!("configuration.{path}"));
});
own.layout
.merge(&layer.layout, &mut |key| set(format!("layout.{key}")));
own.writer
.merge(&layer.writer, &mut |key| set(format!("writer.{key}")));
for (quirk, setting) in &layer.quirks {
own.quirks.insert(quirk.clone(), setting.clone());
set(format!("quirks.{}", path_key(quirk)));
}
own.fonts
.merge(&layer.fonts, &mut |path| set(fonts_path(path)));
Ok(())
}
#[cfg(any(test, feature = "development"))]
fn origin(&self, path: &str) -> Option<&str> {
let at = *self.origins.get(path)?;
self.names.get(at).map(|name| &**name)
}
fn caller_set(&self, path: &str, built_in: usize) -> bool {
self.origins.get(path).is_some_and(|at| *at >= built_in)
}
}
fn fonts_path(path: &[&str]) -> String {
let mut out = "fonts".to_owned();
for key in path {
out.push('.');
out.push_str(&path_key(key));
}
out
}
fn get<T: Clone>(setting: Option<&Setting<T>>, key: &'static str) -> Result<T, Error> {
setting
.map(|setting| setting.value.clone())
.ok_or(Error::Missing(key))
}
fn number<T: TryFrom<i64>>(
value: i64,
key: &'static str,
accepts: fn(i64) -> bool,
) -> Result<T, Error> {
if !accepts(value) {
return Err(Error::Value(key));
}
T::try_from(value).map_err(|_| Error::Value(key))
}
fn positive(setting: Option<&Setting<i64>>, key: &'static str) -> Result<i64, Error> {
number(get(setting, key)?, key, |number| number > 0)
}
fn whole(setting: Option<&Setting<i64>>, key: &'static str) -> Result<i64, Error> {
number(get(setting, key)?, key, |number| number >= 0)
}
fn off_or<T>(
setting: Option<&Setting<OffOr>>,
key: &'static str,
make: impl FnOnce(i64) -> Option<T>,
) -> Result<Option<T>, Error> {
match get(setting, key)? {
OffOr::Off(_) => Ok(None),
OffOr::Number(number) if number > 0 => make(number).map(Some).ok_or(Error::Value(key)),
OffOr::Number(_) => Err(Error::Value(key)),
}
}
fn count_or_off(
setting: Option<&Setting<OffOr>>,
key: &'static str,
) -> Result<Option<NonZeroU32>, Error> {
off_or(setting, key, |number| {
u32::try_from(number).ok().and_then(NonZeroU32::new)
})
}
fn step_per_inch(
setting: Option<&Setting<OffOr>>,
key: &'static str,
) -> Result<Option<Length>, Error> {
let per_inch = Length::UNITS_PER_INCH;
off_or(setting, key, |steps| {
(per_inch % steps == 0).then(|| Length::from_units(per_inch / steps))
})
}
fn variant<T: Copy>(
setting: Option<&Setting<String>>,
key: &'static str,
variants: &[(&str, T)],
) -> Result<T, Error> {
let name = get(setting, key)?;
variants
.iter()
.find(|(variant, _)| *variant == name)
.map(|(_, value)| *value)
.ok_or(Error::Value(key))
}
fn in_a_day(minutes: i32) -> bool {
minutes.unsigned_abs()
< u32::from(crate::params::HOURS_PER_DAY) * u32::from(crate::params::MINUTES_PER_HOUR)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Profile {
target: Target,
configuration: Configuration,
overrides: Overrides,
id: String,
version: i64,
product: String,
builds: String,
renderer: String,
environment_name: String,
device: crate::grid::Device,
writer: Writer,
reader: crate::reader::settings::ReaderSettings,
quirks: crate::quirks::Quirks,
environment: Arc<FontEnvironment>,
symbol_fonts: Arc<SymbolFonts>,
zone_minutes: Option<i32>,
merged: Arc<Merged>,
}
impl Profile {
pub fn of(target: Target) -> Result<Self, Error> {
static RESOLVED: PerTarget<Result<Profile, Error>> =
[const { OnceLock::new() }; TARGETS.len()];
target
.0
.cell(&RESOLVED)
.get_or_init(|| {
let merged = Merged::of(target)?.clone();
let built_in = merged.names.len();
Self::read(
target,
(defaults(target), Overrides::default()),
merged,
built_in,
)
})
.clone()
}
pub(crate) fn resolve(
configuration: &Configuration,
overrides: &Overrides,
) -> Result<Self, Error> {
let target = configuration.target.ok_or(Error::Missing("target"))?;
let changes = configuration.changes_from(&defaults(target));
if changes.is_empty() && overrides.is_empty() {
return Self::of(target);
}
let mut merged = Merged::of(target)?.clone();
let built_in = merged.names.len();
let configured = Layer {
configuration: changes,
..Layer::default()
};
merged.take("configuration", &configured)?;
for (name, layer) in overrides.layers() {
if layer
.inherits
.as_deref()
.is_some_and(|id| id != target.name())
{
return Err(Error::Inherits(name.to_owned()));
}
for (key, set) in [
("product", layer.product.is_some()),
("builds", layer.builds.is_some()),
("renderer", layer.renderer.is_some()),
("fonts.environment", layer.fonts.environment.is_some()),
("configuration", !layer.configuration.is_empty()),
] {
if set {
return Err(Error::BuiltInKey(key));
}
}
merged.take(name, layer)?;
}
let configuration = Configuration {
target: Some(target),
..merged.layer.configuration.clone()
};
Self::read(target, (configuration, overrides.clone()), merged, built_in)
}
fn read(
target: Target,
(configuration, overrides): (Configuration, Overrides),
merged: Merged,
built_in: usize,
) -> Result<Self, Error> {
let own = &merged.layer;
let (layout, writer) = (&own.layout, &own.writer);
let quirks = quirks(own)?;
let printer = own.configuration.printer;
let dots = printer
.dots_per_inch
.ok_or(Error::Missing("printer.dots_per_inch"))?;
let device = crate::grid::Device::of(i64::from(dots.get()), &quirks)
.ok_or(Error::Value("printer.dots_per_inch"))?
.with_leader_step(step_per_inch(
layout.leader_steps_per_inch.as_ref(),
"leader_steps_per_inch",
)?)
.with_bold_stroke(count_or_off(
layout.bold_stroke_parts.as_ref(),
"bold_stroke_parts",
)?)
.with_italic_slant(count_or_off(
layout.italic_slant_parts.as_ref(),
"italic_slant_parts",
)?);
let offsets = page_offsets(target, &merged, built_in, (device, quirks))?;
let device = match advances(layout, &quirks, offsets.0)? {
Some(advances) => device.with_advances(advances),
None => device,
};
let number_separators = own.configuration.number_separators;
if quirks.chart_label_formats == crate::quirks::ChartLabelFormats::Codes
&& number_separators.is_none()
{
return Err(Error::Missing("number_separators"));
}
let zone_minutes = own.configuration.zone_minutes;
if zone_minutes.is_some_and(|minutes| !in_a_day(minutes)) {
return Err(Error::Value("zone_minutes"));
}
let environment_name = own
.fonts
.environment
.clone()
.ok_or(Error::Missing("fonts.environment"))?;
let environment = environment(target, &merged, built_in, &environment_name)?;
let symbol_fonts = Arc::new(SymbolFonts::of(&own.fonts.symbol_font).map_err(Error::Value)?);
let text = |value: &Option<String>, key| value.clone().ok_or(Error::Missing(key));
Ok(Self {
id: text(&own.id, "id")?,
version: match own.version {
Some(version) if version > 0 => version,
Some(_) => return Err(Error::Value("version")),
None => return Err(Error::Missing("version")),
},
product: text(&own.product, "product")?,
builds: text(&own.builds, "builds")?,
renderer: text(&own.renderer, "renderer")?,
environment_name,
device,
writer: profile_writer(writer, offsets)?,
reader: crate::reader::settings::ReaderSettings::of(&quirks)
.with_number_separators(number_separators),
quirks,
environment,
symbol_fonts,
zone_minutes,
target,
configuration,
overrides,
merged: Arc::new(merged),
})
}
#[cfg(test)]
pub(crate) fn base() -> Self {
Self::of(Target::base()).expect("the base profile reads")
}
#[cfg(test)]
#[must_use]
pub(crate) fn with_variant<Q: crate::quirks::Quirk + PartialEq>(&self, variant: Q) -> Self {
let (name, _) = (Q::VARIANTS.iter())
.find(|(_, own)| *own == variant)
.expect("every variant has a name");
Self::resolve(
&self.configuration,
&self
.overrides
.with_layer("test", Layer::default().with_quirk(Q::NAME, name)),
)
.expect("the profile reads with the variant")
}
#[cfg(feature = "development")]
#[must_use]
pub const fn target(&self) -> Target {
self.target
}
#[cfg(any(test, feature = "development"))]
#[must_use]
pub const fn configuration(&self) -> &Configuration {
&self.configuration
}
#[cfg(test)]
#[must_use]
pub(crate) const fn overrides(&self) -> &Overrides {
&self.overrides
}
#[cfg(any(test, feature = "development"))]
#[must_use]
pub fn origin(&self, path: &str) -> Option<&str> {
self.merged.origin(path)
}
#[must_use]
pub(crate) const fn quirks(&self) -> crate::quirks::Quirks {
self.quirks
}
#[cfg(any(test, feature = "development"))]
#[must_use]
pub fn variants(&self) -> Vec<(&'static str, &'static str)> {
self.quirks
.variants()
.iter()
.map(|chosen| (chosen.quirk, chosen.variant))
.collect()
}
#[cfg(any(test, feature = "development"))]
#[must_use]
pub fn chooses(&self, variant: &str) -> Option<bool> {
let (quirk, name) = variant.split_once("::")?;
self.quirks
.variants()
.iter()
.find(|chosen| chosen.quirk == quirk && chosen.has(name))
.map(|chosen| chosen.variant == name)
}
#[must_use]
pub(crate) const fn stand_in_lines(&self) -> crate::text::StandInLines {
crate::text::StandInLines::of(&self.quirks)
}
#[must_use]
pub const fn writer(&self) -> Writer {
self.writer
}
#[must_use]
pub(crate) const fn reader_settings(&self) -> crate::reader::settings::ReaderSettings {
self.reader
}
pub(crate) fn zone_minutes(&self) -> Result<i32, Error> {
match self.quirks.property_date_zone {
crate::quirks::PropertyDateZone::Utc => Ok(self.zone_minutes.unwrap_or(0)),
crate::quirks::PropertyDateZone::LocalDate => {
self.zone_minutes.ok_or(Error::Missing("zone_minutes"))
}
}
}
#[must_use]
pub(crate) const fn device(&self) -> crate::grid::Device {
self.device
}
#[cfg(any(test, feature = "development"))]
#[must_use]
pub fn device_dot(&self) -> Length {
self.device.dots(1)
}
#[cfg(any(test, feature = "development"))]
#[must_use]
pub fn font_environment_path(&self) -> &str {
&self.environment_name
}
#[cfg(any(test, feature = "development"))]
#[must_use]
pub fn font_environment(&self) -> &FontEnvironment {
&self.environment
}
pub(crate) fn shared_font_environment(&self) -> Arc<FontEnvironment> {
Arc::clone(&self.environment)
}
pub(crate) fn symbol_fonts(&self) -> Arc<SymbolFonts> {
Arc::clone(&self.symbol_fonts)
}
pub fn added_families(&self) -> impl Iterator<Item = &str> {
(self.merged.layer.configuration.fonts.installed.iter())
.filter(|(_, installed)| **installed)
.map(|(family, _)| family.as_str())
}
pub fn used_families(&self) -> impl Iterator<Item = (&str, &str)> {
(self.merged.layer.configuration.fonts.uses.iter())
.map(|(family, uses)| (family.as_str(), uses.as_str()))
}
}
impl fmt::Display for Profile {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} {} ({}, builds {}, {})",
self.id, self.version, self.product, self.builds, self.renderer
)
}
}
fn page_offsets(
target: Target,
merged: &Merged,
built_in: usize,
(device, quirks): (crate::grid::Device, crate::quirks::Quirks),
) -> Result<(WriterOffset, WriterOffset), Error> {
let none = (WriterOffset::NONE, WriterOffset::NONE);
if merged.layer.configuration.printer.page_offset == Some(PageOffset::None) {
return Ok(none);
}
let offsets = writer_offsets(
target.0,
(quirks.page_offset_sizes, quirks.page_offset_product),
&merged.layer.writer,
)?;
if merged.caller_set("configuration.printer.dots_per_inch", built_in)
&& !merged.caller_set("configuration.printer.page_offset", built_in)
&& !merged.caller_set("writer.offset", built_in)
{
let own_dots = Merged::of(target)?
.layer
.configuration
.printer
.dots_per_inch;
let own_device =
own_dots.and_then(|dots| crate::grid::Device::of(i64::from(dots.get()), &quirks));
if own_device.is_none_or(|own| own.dot_size() != device.dot_size()) {
return Ok(none);
}
}
Ok(offsets)
}
fn environment(
target: Target,
merged: &Merged,
built_in: usize,
name: &str,
) -> Result<Arc<FontEnvironment>, Error> {
let installed = &merged.layer.configuration.fonts.installed;
let unchanged = installed.is_empty()
&& !(merged.origins.iter()).any(|(path, at)| *at >= built_in && path.starts_with("fonts."));
if unchanged {
static ENVIRONMENTS: PerTarget<Result<Arc<FontEnvironment>, Error>> =
[const { OnceLock::new() }; TARGETS.len()];
return target
.0
.cell(&ENVIRONMENTS)
.get_or_init(|| {
let merged = Merged::of(target)?;
fonts::environment(&merged.layer.fonts)
.map(Arc::new)
.map_err(Error::Environment)
})
.clone();
}
let mut table = merged.layer.fonts.clone();
if environment_table(name)?.available.is_empty() {
table.available.clear();
for (family, _) in installed.iter().filter(|(_, installed)| !**installed) {
table.lacking.entry(family.clone()).or_default();
}
} else {
table.available.extend(
installed
.iter()
.map(|(family, installed)| (family.clone(), *installed)),
);
}
fonts::environment(&table)
.map(Arc::new)
.map_err(Error::Environment)
}
fn advances(
layout: &Layout,
quirks: &crate::quirks::Quirks,
start: WriterOffset,
) -> Result<Option<crate::grid::Advances>, Error> {
Ok(match quirks.grid_advances {
crate::quirks::GridAdvances::RoundToPdfSteps => None,
crate::quirks::GridAdvances::RightEdgeSteps => Some(crate::grid::Advances::RightEdge {
bias: Length::from_units(positive(
layout.glyph_step_bias_half_emus.as_ref(),
"glyph_step_bias_half_emus",
)?),
limit: Length::from_units(positive(
layout.glyph_edge_limit_half_emus.as_ref(),
"glyph_edge_limit_half_emus",
)?),
segment: Length::from_units(positive(
layout.glyph_segment_length_half_emus.as_ref(),
"glyph_segment_length_half_emus",
)?),
point_steps: count_or_off(layout.glyph_point_steps.as_ref(), "glyph_point_steps")?,
start,
}),
})
}
fn quirks(layer: &Layer) -> Result<crate::quirks::Quirks, Error> {
if let Some(name) = layer
.quirks
.keys()
.find(|name| !crate::quirks::NAMES.contains(&name.as_str()))
{
return Err(Error::UnknownQuirk(name.clone()));
}
crate::quirks::Quirks::read(&|name| {
layer.quirks.get(name).map(|setting| setting.value.as_str())
})
.map_err(|error| match error {
crate::quirks::QuirkError::Missing(name) => Error::Missing(name),
crate::quirks::QuirkError::Variant(name) => Error::Value(name),
})
}
const PICTURE_CROPS: [(&str, PictureCrop); 3] = [
("whole_file_under_clip", PictureCrop::WholeFileUnderClip),
("visible_part", PictureCrop::VisiblePart),
("visible_part_at_scale", PictureCrop::VisiblePartAtScale),
];
const ALPHA_MIXES: [(&str, AlphaMix); 2] =
[("plain", AlphaMix::Plain), ("weighted", AlphaMix::Weighted)];
type LinearLimitOf = fn(NonZeroU32) -> LinearLimit;
const LINEAR_LIMIT_MEASURES: [(&str, LinearLimitOf); 2] =
[("pixels", LinearLimit::Pixels), ("side", LinearLimit::Side)];
fn linear_limit(writer: &WriterTable) -> Result<LinearLimit, Error> {
let measure = variant(
writer.linear_limit_of.as_ref(),
"linear_limit_of",
&LINEAR_LIMIT_MEASURES,
)?;
let count: u32 = number(
get(writer.linear_limit.as_ref(), "linear_limit")?,
"linear_limit",
|count| count > 0,
)?;
NonZeroU32::new(count)
.map(measure)
.ok_or(Error::Value("linear_limit"))
}
fn picture_density(writer: &WriterTable) -> Result<Option<PictureDensity>, Error> {
let keys = ("picture_limit_ppi", "picture_ppi");
match (
count_or_off(writer.picture_limit_ppi.as_ref(), keys.0)?,
count_or_off(writer.picture_ppi.as_ref(), keys.1)?,
) {
(Some(limit_ppi), Some(ppi)) => Ok(Some(PictureDensity { limit_ppi, ppi })),
(None, None) => Ok(None),
_ => Err(Error::Pair(keys.0, keys.1)),
}
}
const PALETTE_DENSITY_KEYS: [&str; 4] = [
"palette_one_bit_limit_ppi",
"palette_one_bit_ppi",
"palette_four_bits_limit_ppi",
"palette_eight_bits_limit_ppi",
];
fn palette_density(writer: &WriterTable) -> Result<Option<PaletteDensity>, Error> {
let [one_bit_limit, one_bit, four_bits_limit, eight_bits_limit] = PALETTE_DENSITY_KEYS;
let values = (
count_or_off(writer.palette_one_bit_limit_ppi.as_ref(), one_bit_limit)?,
count_or_off(writer.palette_one_bit_ppi.as_ref(), one_bit)?,
count_or_off(writer.palette_four_bits_limit_ppi.as_ref(), four_bits_limit)?,
count_or_off(
writer.palette_eight_bits_limit_ppi.as_ref(),
eight_bits_limit,
)?,
);
match values {
(
Some(one_bit_limit_ppi),
Some(one_bit_ppi),
Some(four_bits_limit_ppi),
Some(eight_bits_limit_ppi),
) => Ok(Some(PaletteDensity {
one_bit_limit_ppi,
one_bit_ppi,
four_bits_limit_ppi,
eight_bits_limit_ppi,
})),
(None, None, None, None) => Ok(None),
_ => Err(Error::Group(&PALETTE_DENSITY_KEYS)),
}
}
const JPEG_SAMPLE_KEYS: [&str; 3] = ["jpeg_sample_share", "jpeg_sample_floor", "jpeg_whole_share"];
fn jpeg_sample(writer: &WriterTable) -> Result<Option<JpegSample>, Error> {
let [share, floor, whole] = JPEG_SAMPLE_KEYS;
let values = (
count_or_off(writer.jpeg_sample_share.as_ref(), share)?,
count_or_off(writer.jpeg_sample_floor.as_ref(), floor)?,
count_or_off(writer.jpeg_whole_share.as_ref(), whole)?,
);
match values {
(Some(share), Some(floor), Some(whole)) => {
let (Ok(share), Ok(whole)) = (u16::try_from(share.get()), u16::try_from(whole.get()))
else {
return Err(Error::Group(&JPEG_SAMPLE_KEYS));
};
JpegSample::new(share, floor.get(), whole)
.map(Some)
.ok_or(Error::Group(&JPEG_SAMPLE_KEYS))
}
(None, None, None) => Ok(None),
_ => Err(Error::Group(&JPEG_SAMPLE_KEYS)),
}
}
fn profile_writer(
writer: &WriterTable,
(horizontal_offset, vertical_offset): (WriterOffset, WriterOffset),
) -> Result<Writer, Error> {
let any: fn(i64) -> bool = |_| true;
let steps = positive(writer.page_steps_per_inch.as_ref(), "page_steps_per_inch")?;
let stretch = whole(
writer.vertical_stretch_steps.as_ref(),
"vertical_stretch_steps",
)?;
let glyph_step = step_per_inch(
writer.glyph_stretch_steps_per_inch.as_ref(),
"glyph_stretch_steps_per_inch",
)?;
let Decimal(stretch_offset) = get(writer.stretch_offset.as_ref(), "stretch_offset")?;
let stretch_factors =
stretch_factors(&get(writer.stretch_factors.as_ref(), "stretch_factors")?)?;
let digits = count_or_off(writer.digits.as_ref(), "digits")?;
let least_decimals = number(
get(writer.least_decimals.as_ref(), "least_decimals")?,
"least_decimals",
any,
)?;
let picture_digits = count_or_off(writer.picture_digits.as_ref(), "picture_digits")?;
let rectangle_steps = count_or_off(
writer.rectangle_steps_per_inch.as_ref(),
"rectangle_steps_per_inch",
)?;
let baseline_steps = count_or_off(
writer.baseline_steps_per_inch.as_ref(),
"baseline_steps_per_inch",
)?;
let jpeg_quality = off_or(writer.jpeg_quality.as_ref(), "jpeg_quality", |quality| {
u8::try_from(quality).ok().and_then(JpegQuality::new)
})?;
let jpeg_share = off_or(writer.jpeg_share.as_ref(), "jpeg_share", |share| {
u16::try_from(share).ok().and_then(JpegShare::new)
})?;
let jpeg_sample = jpeg_sample(writer)?;
let density = picture_density(writer)?;
let palettes = palette_density(writer)?;
let crop = variant(writer.picture_crop.as_ref(), "picture_crop", &PICTURE_CROPS)?;
let alpha_mix = variant(writer.alpha_mix.as_ref(), "alpha_mix", &ALPHA_MIXES)?;
let linear_limit = linear_limit(writer)?;
Ok(writer_of(steps)?
.with_vertical_stretch(stretch)
.with_glyph_stretch_step(glyph_step)
.ok_or(Error::Value("glyph_stretch_steps_per_inch"))?
.with_stretch_factors(stretch_offset, &stretch_factors)
.ok_or(Error::Value("stretch_factors"))?
.with_digits(digits)
.with_least_decimals(least_decimals)
.with_rectangle_steps(rectangle_steps)
.with_baseline_steps(baseline_steps)
.with_picture_digits(picture_digits)
.with_horizontal_offset(horizontal_offset)
.with_vertical_offset(vertical_offset)
.with_jpeg_quality(jpeg_quality)
.with_jpeg_share(jpeg_share)
.with_jpeg_sample(jpeg_sample)
.with_picture_density(density)
.with_palette_density(palettes)
.with_picture_crop(crop)
.with_alpha_mix(alpha_mix)
.with_linear_limit(linear_limit))
}
fn stretch_factors(list: &str) -> Result<Vec<(Length, f_office_paint::Fraction)>, Error> {
let wrong = || Error::Value("stretch_factors");
list.split(',')
.map(str::trim)
.filter(|entry| !entry.is_empty())
.map(|entry| {
let mut parts = entry.split_whitespace();
let (Some(height), Some(factor), None) = (parts.next(), parts.next(), parts.next())
else {
return Err(wrong());
};
let (points, scale) = decimal_fraction(height).ok_or_else(wrong)?;
let units = points
.checked_mul(Length::UNITS_PER_POINT)
.filter(|units| *units > 0 && units % scale == 0)
.ok_or_else(wrong)?;
let factor = decimal_fraction(factor)
.filter(|(value, _)| *value > 0)
.ok_or_else(wrong)?;
Ok((Length::from_units(units / scale), factor))
})
.collect()
}
fn writer_of(steps: i64) -> Result<Writer, Error> {
let per_inch = Length::UNITS_PER_INCH;
if per_inch % steps != 0 {
return Err(Error::Value("page_steps_per_inch"));
}
Writer::new(Length::from_units(per_inch / steps)).ok_or(Error::Value("page_steps_per_inch"))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum OffsetForm {
Off,
ShareOfPlace,
PageSteps,
}
const OFFSET_FORMS: [(&str, OffsetForm); 3] = [
("off", OffsetForm::Off),
("share_of_place", OffsetForm::ShareOfPlace),
("page_steps", OffsetForm::PageSteps),
];
fn writer_offsets(
id: Id,
(sizes, product): (
crate::quirks::PageOffsetSizes,
crate::quirks::PageOffsetProduct,
),
writer: &WriterTable,
) -> Result<(WriterOffset, WriterOffset), Error> {
match variant(writer.offset.as_ref(), "offset", &OFFSET_FORMS)? {
OffsetForm::Off => Ok((WriterOffset::NONE, WriterOffset::NONE)),
OffsetForm::ShareOfPlace => {
let across = WriterOffset::EveryPage(f_office_paint::Offset::Share {
share: positive(writer.start_offset_share.as_ref(), "start_offset_share")?,
bias: whole(
writer.start_offset_bias_half_emus.as_ref(),
"start_offset_bias_half_emus",
)?,
step: positive(
writer.start_offset_step_half_emus.as_ref(),
"start_offset_step_half_emus",
)?,
});
Ok((across, WriterOffset::NONE))
}
OffsetForm::PageSteps => {
let per_inch = positive(
writer.offset_page_steps_per_inch.as_ref(),
"offset_page_steps_per_inch",
)?;
let parts = positive(
writer.offset_page_parts_per_step.as_ref(),
"offset_page_parts_per_step",
)?;
let steps = positive(
writer.offset_page_steps_hundred_thousandths.as_ref(),
"offset_page_steps_hundred_thousandths",
)?;
let product = match product {
crate::quirks::PageOffsetProduct::Exact => f_office_paint::OffsetProduct::Exact,
crate::quirks::PageOffsetProduct::Binary32 => {
f_office_paint::OffsetProduct::Binary32 {
dots_per_inch: positive(
writer.page_steps_per_inch.as_ref(),
"page_steps_per_inch",
)?,
}
}
};
let offset = match sizes {
crate::quirks::PageOffsetSizes::OneFactor => {
WriterOffset::EveryPage(f_office_paint::Offset::Page {
steps: in_hundred_thousandths(steps),
parts,
per_inch,
product,
})
}
crate::quirks::PageOffsetSizes::PaperForms => {
WriterOffset::Sizes(page_sizes(id, writer, (steps, parts, per_inch), product)?)
}
};
Ok((offset, offset))
}
}
}
const fn in_hundred_thousandths(steps: i64) -> f_office_paint::Fraction {
(steps, f_office_paint::STEP_PARTS)
}
fn page_sizes(
id: Id,
writer: &WriterTable,
(letter, parts, per_inch): (i64, i64, i64),
product: f_office_paint::OffsetProduct,
) -> Result<&'static f_office_paint::PageSizes, Error> {
use f_office_paint::{GivenSize, OffsetProduct, Orientation};
static EXACT: PerTarget<Result<f_office_paint::PageSizes, Error>> =
[const { OnceLock::new() }; TARGETS.len()];
static BINARY32: PerTarget<Result<f_office_paint::PageSizes, Error>> =
[const { OnceLock::new() }; TARGETS.len()];
let sizes = match product {
OffsetProduct::Exact => &EXACT,
OffsetProduct::Binary32 { .. } => &BINARY32,
};
id.cell(sizes)
.get_or_init(|| {
let measured = |orientation, (dots, (across, down))| GivenSize {
dots,
orientation: Some(orientation),
steps: (
Some(in_hundred_thousandths(across)),
Some(in_hundred_thousandths(down)),
),
};
let mut sizes: Vec<GivenSize> = [
crate::params::PAGE_4961_7016_STEPS,
crate::params::PAGE_4960_7015_STEPS,
]
.into_iter()
.map(|size| measured(Orientation::Portrait, size))
.collect();
sizes.push(measured(
Orientation::Landscape,
crate::params::PAGE_7016_4961_STEPS,
));
let ((width, height), letter_across) = crate::params::PAGE_5100_6600_ACROSS_STEPS;
let letter = in_hundred_thousandths(letter);
sizes.push(GivenSize {
dots: (width, height),
orientation: None,
steps: (Some(in_hundred_thousandths(letter_across)), Some(letter)),
});
sizes.push(GivenSize {
dots: (height, width),
orientation: Some(Orientation::Landscape),
steps: (Some(letter), Some(in_hundred_thousandths(letter_across))),
});
sizes.push(GivenSize {
dots: (height, width),
orientation: None,
steps: (Some(letter), None),
});
let dots_per_inch =
positive(writer.page_steps_per_inch.as_ref(), "page_steps_per_inch")?;
Ok(f_office_paint::PageSizes::new(
(parts, per_inch, dots_per_inch),
product,
sizes,
&crate::params::PAPER_FORM_CLASS_RULE,
))
})
.as_ref()
.map_err(Clone::clone)
}
#[cfg(any(test, feature = "development"))]
impl Layer {
#[must_use]
pub fn with_quirk(mut self, name: &str, variant: &str) -> Self {
self.quirks.insert(
name.to_owned(),
Setting {
value: variant.to_owned(),
},
);
self
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
UnknownTarget(String),
UnknownProfile(String),
UnknownEnvironment(String),
Read {
profile: String,
message: String,
},
Inherits(String),
BuiltInKey(&'static str),
Missing(&'static str),
Value(&'static str),
NotRead(&'static str),
Pair(&'static str, &'static str),
Group(&'static [&'static str]),
UnknownQuirk(String),
Environment(EnvironmentError),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UnknownTarget(name) => write!(f, "no target is named {name:?}"),
Self::UnknownProfile(name) => write!(f, "no profile is named {name:?}"),
Self::UnknownEnvironment(name) => {
write!(f, "no font environment is named {name:?}")
}
Self::Read { profile, message } => {
write!(f, "the profile {profile} does not read: {message}")
}
Self::Inherits(name) => write!(
f,
"the profile {name} inherits from a profile that it cannot inherit from"
),
Self::BuiltInKey(key) => {
write!(
f,
"an override sets {key}, which only a profile or the configuration sets"
)
}
Self::Missing(key) => write!(f, "a profile has no {key}"),
Self::Value(key) => write!(f, "a profile has a wrong value for {key}"),
Self::NotRead(key) => write!(
f,
"the configuration sets {key}, which F-Office does not read yet"
),
Self::Pair(one, other) => write!(
f,
"a profile sets only one of {one} and {other}, which are \"off\" or set together"
),
Self::Group(keys) => write!(
f,
"a profile sets only some of {}, which are \"off\" or set together",
keys.join(", ")
),
Self::UnknownQuirk(name) => write!(f, "no quirk of the registry is named {name:?}"),
Self::Environment(error) => write!(f, "{error}"),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Environment(error) => Some(error),
_ => None,
}
}
}
#[cfg(test)]
mod tests;