lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! The resource-owning side of fixed images.

mod css;
mod png;
mod raster_image;
mod resources;
mod svg;

use std::path::{Path, PathBuf};
use std::sync::Arc;

use crate::{Error, Result};
use base64::{engine::general_purpose::STANDARD, Engine};
pub(crate) use png::{png_samples, PngSamples};
pub(crate) fn png_alpha_ink(
    bytes: &[u8],
    object: crate::layout::Rect,
    clip: crate::layout::Rect,
    rendering: super::ImageRendering,
) -> Result<crate::layout::InkExtent> {
    super::ink::png_ink(&png::decode(bytes, false)?, object, clip, rendering)
}
pub(crate) use svg::raster_svg;
use svg::SvgAsset;

/// Validated, owned local image input. The source bytes and referenced resources
/// are retained independently of the caller's buffer or filesystem.
#[derive(Debug, Clone)]
pub struct ImageAsset(Arc<Asset>, Option<Arc<PathBuf>>);

/// An actual external SVG font substitution made while freezing glyphs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImageFontSubstitution {
    /// Authored family selection requesting the font or missing glyph.
    pub requested: String,
    /// Actual family used in the selected glyphs.
    pub selected: String,
    /// Missing source scalar for a glyph-level substitution, when applicable.
    pub scalar: Option<char>,
}

#[derive(Debug)]
enum Asset {
    Png {
        bytes: Arc<[u8]>,
        metadata: png::PngMetadata,
    },
    Svg(SvgAsset),
}

/// Intrinsic dimensions and aspect ratio are independent: a viewBox is not a
/// declaration of CSS-pixel width and height.
#[derive(Debug, Clone, Copy)]
pub(super) struct Intrinsics {
    pub size: [Option<f64>; 2],
    pub ratio: Option<f64>,
}

impl Intrinsics {
    pub(super) fn sized(width: f64, height: f64) -> Self {
        Self {
            size: [Some(width), Some(height)],
            ratio: Some(width / height),
        }
    }

    pub(super) fn complete(self) -> Option<(f64, f64)> {
        match (self.size, self.ratio) {
            ([Some(w), Some(h)], _) => Some((w, h)),
            ([Some(w), None], Some(ratio)) => Some((w, w / ratio)),
            ([None, Some(h)], Some(ratio)) => Some((h * ratio, h)),
            _ => None,
        }
    }
}

impl ImageAsset {
    /// Capture an already colored, immutable sRGB pixel buffer as an image.
    pub fn from_pixels(
        pixels: impl std::borrow::Borrow<crate::output::PixelBuffer>,
    ) -> Result<Self> {
        Self::from_pixels_with_operation(
            pixels.borrow(),
            &crate::operation::OperationOptions::default(),
        )
    }

    /// Capture existing pixel samples under this call's operation options.
    pub fn from_pixels_with_operation(
        pixels: &crate::output::PixelBuffer,
        options: &crate::operation::OperationOptions,
    ) -> Result<Self> {
        crate::operation::run(options, || {
            let size = resvg::tiny_skia::IntSize::from_wh(pixels.width(), pixels.height())
                .expect("admitted raster size");
            let density = pixels
                .dpi()
                .map(crate::layout::dpi_to_pixels_per_meter)
                .transpose()?;
            let straight = pixels.straight_rgba()?;
            let bytes = crate::render::svg_backend::encode_png(
                &straight,
                size,
                crate::output::PngCompression::Balanced,
                density,
            )?;
            Self::read_png(&bytes)
        })
    }

    /// Read a local PNG or SVG file and seal its actual drawing dependencies.
    pub fn from_path(path: impl AsRef<Path>) -> Result<Self> {
        Self::from_path_with_operation(path, &crate::operation::OperationOptions::default())
    }

    /// Seal a local image under this operation's cancellation options.
    pub fn from_path_with_operation(
        path: impl AsRef<Path>,
        options: &crate::operation::OperationOptions,
    ) -> Result<Self> {
        crate::operation::run(options, || Self::read_path(path.as_ref()))
    }

    pub(super) fn read_path(path: &Path) -> Result<Self> {
        let path = std::path::absolute(path)?;
        let bytes = crate::operation::external(|| std::fs::read(&path))?;
        crate::operation::checkpoint()?;
        let mut asset = if bytes.starts_with(b"\x89PNG\r\n\x1a\n") {
            Self::read_png(&bytes)?
        } else {
            let svg = SvgAsset::from_file(&bytes, &path)
                .map_err(|error| error.with_prefix(&format!("SVG asset {}", path.display())))?;
            Self(Arc::new(Asset::Svg(svg)), None)
        };
        asset.1 = Some(Arc::new(path));
        Ok(asset)
    }

    /// Capture the supplied PNG's original encoded bytes.
    pub fn from_png_bytes(bytes: &[u8]) -> Result<Self> {
        Self::from_png_bytes_with_operation(bytes, &crate::operation::OperationOptions::default())
    }

    /// Capture a PNG under this operation's cancellation options.
    pub fn from_png_bytes_with_operation(
        bytes: &[u8],
        options: &crate::operation::OperationOptions,
    ) -> Result<Self> {
        crate::operation::run(options, || Self::read_png(bytes))
    }

    fn read_png(bytes: &[u8]) -> Result<Self> {
        let metadata = png::metadata(bytes)?;
        Ok(Self(
            Arc::new(Asset::Png {
                bytes: Arc::from(bytes),
                metadata,
            }),
            None,
        ))
    }

    /// Capture a self-contained static SVG, without a filesystem base.
    pub fn from_svg_bytes(bytes: &[u8]) -> Result<Self> {
        Self::from_svg_bytes_with_operation(bytes, &crate::operation::OperationOptions::default())
    }

    /// Capture self-contained SVG under this operation's cancellation options.
    pub fn from_svg_bytes_with_operation(
        bytes: &[u8],
        options: &crate::operation::OperationOptions,
    ) -> Result<Self> {
        crate::operation::run(options, || {
            Ok(Self(
                Arc::new(Asset::Svg(SvgAsset::from_bytes(bytes)?)),
                None,
            ))
        })
    }

    pub(super) fn declared_path(&self) -> Option<&Path> {
        self.1.as_deref().map(PathBuf::as_path)
    }

    /// Intrinsic CSS width, if specified by this source.
    pub fn width(&self) -> Option<f64> {
        self.intrinsics().size[0]
    }

    /// Intrinsic CSS height, if specified by this source.
    pub fn height(&self) -> Option<f64> {
        self.intrinsics().size[1]
    }

    /// Intrinsic width-to-height ratio, when the source has one.
    pub fn aspect_ratio(&self) -> Option<f64> {
        self.intrinsics().ratio
    }

    pub(super) fn intrinsics(&self) -> Intrinsics {
        match &*self.0 {
            Asset::Png { metadata, .. } => {
                Intrinsics::sized(f64::from(metadata.size.0), f64::from(metadata.size.1))
            }
            Asset::Svg(svg) => svg.intrinsics(),
        }
    }

    pub(super) fn prepare(&self, viewport: (f64, f64)) -> Result<AssetView> {
        match &*self.0 {
            Asset::Png { bytes, .. } => Ok(AssetView {
                preserved: data_uri("image/png", bytes).into(),
                outlined: None,
                preserve_error: None,
                substitutions: Vec::new(),
            }),
            Asset::Svg(svg) => svg.prepare(viewport),
        }
    }

    pub(super) fn known_empty(&self) -> bool {
        matches!(&*self.0, Asset::Png { metadata, .. } if metadata.coverage == png::Coverage::Empty)
    }

    pub(super) fn exact_ink(
        &self,
        viewport: (f64, f64),
        object: crate::layout::Rect,
        clip: crate::layout::Rect,
        rendering: super::ImageRendering,
        view: Option<&AssetView>,
    ) -> Result<crate::layout::InkExtent> {
        use crate::layout::{InkExtent, Rect};
        let Some(clip) = object.intersection(clip) else {
            return Ok(InkExtent::Empty);
        };
        match &*self.0 {
            Asset::Png { bytes, metadata } => match metadata.coverage {
                png::Coverage::Empty => Ok(InkExtent::Empty),
                png::Coverage::Full => Ok(InkExtent::Bounds(clip)),
                png::Coverage::Partial => {
                    super::ink::png_ink(&png::decode(bytes, false)?, object, clip, rendering)
                }
            },
            Asset::Svg(asset) => {
                let source = Rect::new(0., 0., viewport.0, viewport.1)?;
                let local_clip = super::ink::map_rect(clip, object, source)?;
                let ink = if let Some(Ok(href)) = view.and_then(|view| view.outlined.as_ref()) {
                    let (_, bytes) = read_data_uri(href)?;
                    let svg = std::str::from_utf8(&bytes).map_err(|error| {
                        Error::Render(format!("retained outline SVG: {error}").into())
                    })?;
                    super::ink::svg_ink(svg, source, local_clip)?
                } else {
                    asset.exact_ink(source, local_clip)?
                };
                super::ink::map_ink(ink, source, object)
            }
        }
    }
}

/// An actual source viewport with a retained preserve-text representation and
/// its format-local outline result. Failure of outlining doesn't affect SVG
/// publication that preserves the author's text.
#[derive(Debug, Clone)]
pub(super) struct AssetView {
    pub preserved: Arc<str>,
    pub outlined: Option<std::result::Result<Arc<str>, crate::errors::Diagnostic>>,
    pub preserve_error: Option<crate::errors::Diagnostic>,
    pub substitutions: Vec<ImageFontSubstitution>,
}

impl AssetView {
    pub fn href(&self, outline: bool) -> Result<&str> {
        match (outline, &self.outlined) {
            (true, Some(Ok(href))) => Ok(href),
            (true, Some(Err(error))) => Err(Error::Render(error.clone())),
            _ => Ok(&self.preserved),
        }
    }
}

pub(crate) fn data_uri(mime: &str, bytes: &[u8]) -> String {
    format!("data:{mime};base64,{}", STANDARD.encode(bytes))
}

pub(crate) fn read_data_uri(value: &str) -> Result<(String, Vec<u8>)> {
    let url = data_url::DataUrl::process(value)
        .map_err(|error| Error::Data(format!("invalid image data URI: {error:?}").into()))?;
    let mime = format!("{}/{}", url.mime_type().type_, url.mime_type().subtype);
    let (bytes, _) = url
        .decode_to_vec()
        .map_err(|error| Error::Data(format!("invalid encoded image data: {error:?}").into()))?;
    Ok((mime, bytes))
}