lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Explicit selection of a currently implemented publication device.

use super::{ExportRegion, PixelOptions, PngCompression, PngOptions, PngSizing};
use crate::style::OpaqueColor;
use crate::{Error, Result};
mod recipe;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Encoding {
    Svg,
    Png,
}

/// One single-image device and its call-local options. An omitted PNG size
/// is resolved by the actual receiver at publication time.
#[derive(Debug, Clone, PartialEq)]
#[must_use]
pub struct Format {
    pub(crate) encoding: Encoding,
    preserve_text: Option<bool>,
    sizing: Option<PngSizing>,
    compression: Option<PngCompression>,
    pub(crate) region: ExportRegion,
    pub(crate) transparent: bool,
    pub(crate) matte: Option<OpaqueColor>,
}

impl Format {
    /// Infer a currently supported single-image encoder from a filename's
    /// conventional suffix, independently of the actual output destination.
    pub fn from_path(path: impl AsRef<std::path::Path>) -> Result<Self> {
        let extension = path.as_ref().extension().and_then(std::ffi::OsStr::to_str);
        match extension {
            Some(extension) if extension.eq_ignore_ascii_case("svg") => Ok(Self::svg()),
            Some(extension) if extension.eq_ignore_ascii_case("png") => Ok(Self::png()),
            _ => Err(Error::Data(
                "image output requires an explicit device or an SVG/PNG filename".into(),
            )),
        }
    }
    /// Outlined SVG by default.
    pub const fn svg() -> Self {
        Self {
            encoding: Encoding::Svg,
            preserve_text: None,
            sizing: None,
            compression: None,
            region: ExportRegion::full(),
            transparent: false,
            matte: None,
        }
    }

    /// PNG with balanced compression and receiver-dependent default sizing.
    pub const fn png() -> Self {
        let mut format = Self::svg();
        format.encoding = Encoding::Png;
        format
    }

    /// Select actual retained text instead of frozen glyph outlines in SVG.
    pub const fn preserve_text(mut self, preserve: bool) -> Self {
        self.preserve_text = Some(preserve);
        self
    }

    /// Explicit PNG sampling, independent of the receiver's default.
    pub const fn sizing(mut self, sizing: PngSizing) -> Self {
        self.sizing = Some(sizing);
        self
    }

    /// Set PNG compression independently of sampling.
    pub const fn compression(mut self, compression: PngCompression) -> Self {
        self.compression = Some(compression);
        self
    }

    /// Select the publication-only output frame.
    pub fn region(mut self, region: ExportRegion) -> Self {
        self.region = region;
        self
    }

    /// Remove semantically identifiable native structural paper.
    pub const fn transparent(mut self, transparent: bool) -> Self {
        self.transparent = transparent;
        self
    }

    /// Place the completed picture over an opaque sRGB background.
    pub const fn matte(mut self, matte: OpaqueColor) -> Self {
        self.matte = Some(matte);
        self
    }

    pub(crate) fn pixel_options(&self, default: PngSizing) -> PixelOptions {
        let mut options = PixelOptions::default()
            .sizing(self.sizing.unwrap_or(default))
            .region(self.region.clone())
            .transparent(self.transparent);
        if let Some(matte) = self.matte {
            options = options.matte(matte);
        }
        options
    }

    /// Conventional extension of the selected encoder, including its dot.
    pub const fn suffix(&self) -> &'static str {
        match self.encoding {
            Encoding::Svg => ".svg",
            Encoding::Png => ".png",
        }
    }

    /// Internet media type of the resulting complete byte stream.
    pub const fn mime_type(&self) -> &'static str {
        match self.encoding {
            Encoding::Svg => "image/svg+xml",
            Encoding::Png => "image/png",
        }
    }

    /// Validate compatibility of the options with the chosen native device.
    pub fn validate(&self) -> Result<()> {
        match self.encoding {
            Encoding::Svg if self.sizing.is_some() || self.compression.is_some() => Err(
                Error::Data("PNG sizing and compression require Format::png()".into()),
            ),
            Encoding::Png if self.preserve_text.is_some() => {
                Err(Error::Data("preserve_text requires Format::svg()".into()))
            }
            _ => Ok(()),
        }
    }

    pub(crate) fn retains_text(&self) -> bool {
        self.preserve_text.unwrap_or(false)
    }

    pub(crate) fn png_options(&self, default: PngSizing) -> PngOptions {
        PngOptions {
            sizing: self.sizing.unwrap_or(default),
            compression: self.compression.unwrap_or_default(),
        }
    }
}

impl From<PngOptions> for Format {
    fn from(options: PngOptions) -> Self {
        Self::png()
            .sizing(options.sizing)
            .compression(options.compression)
    }
}