use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fmt;
use crate::stdlib::backends::pres::I48F16;
use super::convert::ConversionRule;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[derive(serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum Strategy {
#[default]
Reference,
Copy,
DataUri,
Content,
}
impl Strategy {
pub fn needs_content(self) -> bool {
!matches!(self, Strategy::Reference)
}
pub fn name(self) -> &'static str {
match self {
Strategy::Reference => "reference",
Strategy::Copy => "copy",
Strategy::DataUri => "data-uri",
Strategy::Content => "content",
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
#[derive(serde::Deserialize, schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct GraphicsRenderOptions {
pub strategy: BTreeMap<String, Strategy>,
pub convert: BTreeMap<String, Vec<ConversionRule>>,
pub magnification: BTreeMap<String, Magnification>,
}
impl GraphicsRenderOptions {
pub fn strategy_for(&self, output: &str) -> Strategy {
self.strategy.get(output).copied().unwrap_or_default()
}
pub fn rules_for(&self, output: &str) -> &[ConversionRule] {
self.convert.get(output).map(Vec::as_slice).unwrap_or_default()
}
pub fn magnification_for(&self, output: &str) -> Magnification {
self.magnification.get(output).copied().unwrap_or_default()
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[derive(serde::Deserialize, schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct Magnification {
pub raster: Factor,
pub vector: Factor,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[derive(serde::Deserialize)]
#[serde(try_from = "f64")]
pub struct Factor(I48F16);
impl Factor {
pub const ONE: Factor = Factor(I48F16::ONE);
pub fn new(value: I48F16) -> Option<Factor> {
(value > I48F16::ZERO).then_some(Factor(value))
}
pub fn value(self) -> I48F16 {
self.0
}
}
impl Default for Factor {
fn default() -> Factor {
Factor::ONE
}
}
impl TryFrom<f64> for Factor {
type Error = FactorError;
fn try_from(value: f64) -> Result<Factor, FactorError> {
if value.is_nan() || value <= 0.0 {
return Err(FactorError::NotPositive(value));
}
I48F16::checked_from_num(value)
.and_then(Factor::new)
.ok_or(FactorError::OutOfRange(value))
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum FactorError {
NotPositive(f64),
OutOfRange(f64),
}
impl fmt::Display for FactorError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
FactorError::NotPositive(value) => {
write!(f, "a magnification factor must be greater than zero, not `{value}`")
}
FactorError::OutOfRange(value) => write!(
f,
"a magnification factor must lie between 1/65536 and 2^47, not `{value}`"
),
}
}
}
impl std::error::Error for FactorError {}
impl schemars::JsonSchema for Factor {
fn schema_name() -> Cow<'static, str> {
Cow::Borrowed("Factor")
}
fn inline_schema() -> bool {
true
}
fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"type": "number",
"exclusiveMinimum": 0,
"default": 1,
"description": "A magnification factor, greater than zero.",
})
}
}
#[cfg(test)]
mod tests {
use super::{Factor, FactorError, GraphicsRenderOptions, I48F16, Magnification, Strategy};
#[test]
fn a_magnification_defaults_to_one_per_output_and_per_type() {
let options: GraphicsRenderOptions = serde_json::from_value(serde_json::json!({
"magnification": { "html": { "raster": 1.5 } },
}))
.expect("the settings read");
let html = options.magnification_for("html");
assert_eq!(html.raster.value(), I48F16::from_num(1.5));
assert_eq!(html.vector, Factor::ONE);
assert_eq!(options.magnification_for("text"), Magnification::default());
assert_eq!(Magnification::default().raster, Factor::ONE);
}
#[test]
fn a_factor_is_greater_than_zero() {
assert_eq!(Factor::try_from(0.0), Err(FactorError::NotPositive(0.0)));
assert_eq!(Factor::try_from(-2.0), Err(FactorError::NotPositive(-2.0)));
assert_eq!(Factor::try_from(1e-9), Err(FactorError::OutOfRange(1e-9)));
assert_eq!(Factor::try_from(1e20), Err(FactorError::OutOfRange(1e20)));
assert!(Factor::try_from(f64::NAN).is_err());
assert_eq!(Factor::try_from(1.25).map(Factor::value), Ok(I48F16::from_num(1.25)));
let refused = serde_json::from_value::<GraphicsRenderOptions>(serde_json::json!({
"magnification": { "html": { "vector": 0 } },
}));
assert!(refused.is_err());
}
#[test]
fn each_strategy_s_name_reads_back_as_the_same_strategy() {
for strategy in [Strategy::Reference, Strategy::Copy, Strategy::DataUri, Strategy::Content] {
let read: Strategy = serde_json::from_value(serde_json::Value::from(strategy.name()))
.expect("the name is the settings' spelling");
assert_eq!(read, strategy);
}
}
}