crisol-plot-render 1.9.0

Headless SVG/PNG renderer for Crisol PlotSpec charts, with no window or GPU.
Documentation
//! Headless rendering for a [`PlotSpec`]: SVG and PNG without a window, GPU, or egui.

#![cfg_attr(docsrs, feature(doc_cfg))]

mod layout;
mod pdf;
mod png;
mod scene;
mod svg;
mod text;

use crisol_plot_core::spec::{PlotSpec, SpecError};

pub use scene::{Anchor, Prim};

/// The image format to render.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Format {
    /// Scalable vector graphics.
    Svg,
    /// A PNG raster.
    Png,
    /// A one-page vector PDF with the font embedded.
    Pdf,
}

/// Render `spec` as a PNG image.
///
/// # Errors
/// When the spec is invalid, the bundled font cannot load, or PNG encoding fails.
pub fn render_png(spec: &PlotSpec) -> Result<Vec<u8>, RenderError> {
    spec.validate().map_err(RenderError::Spec)?;
    let scene = layout::build(spec)?;
    png::render(&scene, spec.width, spec.height)
}

/// Render `spec` as an SVG document.
///
/// # Errors
/// When the spec is invalid or the bundled font cannot load.
pub fn render_svg(spec: &PlotSpec) -> Result<String, RenderError> {
    spec.validate().map_err(RenderError::Spec)?;
    let scene = layout::build(spec)?;
    Ok(svg::render(&scene, spec.width, spec.height))
}

/// Render `spec` as a one-page vector PDF with the bundled font embedded.
///
/// # Errors
/// When the spec is invalid or the bundled font cannot load.
pub fn render_pdf(spec: &PlotSpec) -> Result<Vec<u8>, RenderError> {
    spec.validate().map_err(RenderError::Spec)?;
    let scene = layout::build(spec)?;
    pdf::render(&scene, spec.width, spec.height)
}

/// Render in the requested format.
///
/// # Errors
/// The same errors as [`render_png`] and [`render_svg`].
pub fn render(spec: &PlotSpec, format: Format) -> Result<Vec<u8>, RenderError> {
    match format {
        Format::Png => render_png(spec),
        Format::Svg => render_svg(spec).map(String::into_bytes),
        Format::Pdf => render_pdf(spec),
    }
}

/// Why a chart could not be rendered.
#[derive(Debug)]
#[non_exhaustive]
pub enum RenderError {
    /// The declarative spec failed validation.
    Spec(SpecError),
    /// The bundled font could not be parsed.
    Font(String),
    /// PNG encoding failed.
    Png(String),
    /// The image has no pixels.
    Empty,
}

impl std::fmt::Display for RenderError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Spec(error) => write!(formatter, "invalid plot spec: {error}"),
            Self::Font(error) => write!(formatter, "font error: {error}"),
            Self::Png(error) => write!(formatter, "PNG error: {error}"),
            Self::Empty => write!(formatter, "the spec renders no pixels"),
        }
    }
}

impl std::error::Error for RenderError {}