Skip to main content

crisol_plot_render/
lib.rs

1//! Headless rendering for a [`PlotSpec`]: SVG and PNG without a window, GPU, or egui.
2
3#![cfg_attr(docsrs, feature(doc_cfg))]
4
5mod layout;
6mod pdf;
7mod png;
8mod scene;
9mod svg;
10mod text;
11
12use crisol_plot_core::spec::{PlotSpec, SpecError};
13
14pub use scene::{Anchor, Prim};
15
16/// The image format to render.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18pub enum Format {
19    /// Scalable vector graphics.
20    Svg,
21    /// A PNG raster.
22    Png,
23    /// A one-page vector PDF with the font embedded.
24    Pdf,
25}
26
27/// Render `spec` as a PNG image.
28///
29/// # Errors
30/// When the spec is invalid, the bundled font cannot load, or PNG encoding fails.
31pub fn render_png(spec: &PlotSpec) -> Result<Vec<u8>, RenderError> {
32    spec.validate().map_err(RenderError::Spec)?;
33    let scene = layout::build(spec)?;
34    png::render(&scene, spec.width, spec.height)
35}
36
37/// Render `spec` as an SVG document.
38///
39/// # Errors
40/// When the spec is invalid or the bundled font cannot load.
41pub fn render_svg(spec: &PlotSpec) -> Result<String, RenderError> {
42    spec.validate().map_err(RenderError::Spec)?;
43    let scene = layout::build(spec)?;
44    Ok(svg::render(&scene, spec.width, spec.height))
45}
46
47/// Render `spec` as a one-page vector PDF with the bundled font embedded.
48///
49/// # Errors
50/// When the spec is invalid or the bundled font cannot load.
51pub fn render_pdf(spec: &PlotSpec) -> Result<Vec<u8>, RenderError> {
52    spec.validate().map_err(RenderError::Spec)?;
53    let scene = layout::build(spec)?;
54    pdf::render(&scene, spec.width, spec.height)
55}
56
57/// Render in the requested format.
58///
59/// # Errors
60/// The same errors as [`render_png`] and [`render_svg`].
61pub fn render(spec: &PlotSpec, format: Format) -> Result<Vec<u8>, RenderError> {
62    match format {
63        Format::Png => render_png(spec),
64        Format::Svg => render_svg(spec).map(String::into_bytes),
65        Format::Pdf => render_pdf(spec),
66    }
67}
68
69/// Why a chart could not be rendered.
70#[derive(Debug)]
71#[non_exhaustive]
72pub enum RenderError {
73    /// The declarative spec failed validation.
74    Spec(SpecError),
75    /// The bundled font could not be parsed.
76    Font(String),
77    /// PNG encoding failed.
78    Png(String),
79    /// The image has no pixels.
80    Empty,
81}
82
83impl std::fmt::Display for RenderError {
84    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
85        match self {
86            Self::Spec(error) => write!(formatter, "invalid plot spec: {error}"),
87            Self::Font(error) => write!(formatter, "font error: {error}"),
88            Self::Png(error) => write!(formatter, "PNG error: {error}"),
89            Self::Empty => write!(formatter, "the spec renders no pixels"),
90        }
91    }
92}
93
94impl std::error::Error for RenderError {}