lichtung-plot 0.2.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Immutable canonical SVG scenes and optional format conversion.

use std::fmt;
use std::sync::OnceLock;

use crate::layout::RootSize;
use crate::render::svg_backend::{FinalizedSvgOutput, SvgOutlinePlan};
use crate::{output::PngOptions, Error};

const MAX_EXPORT_DIMENSION: u32 = 32_768;
const MAX_EXPORT_PIXELS: u32 = 100_000_000;
const MAX_CONVERSION_SCENE_BYTES: usize = 64 * 1024 * 1024;

#[cfg(test)]
thread_local! {
    pub(crate) static SCENE_CONSTRUCTION_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
    pub(crate) static PNG_TARGET_VALIDATION_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// One internal fully rendered SVG scene shared by terminal outputs.
pub(crate) struct RenderedScene {
    size: RootSize,
    svg: Vec<u8>,
    outline_plan: SvgOutlinePlan,
    outlined_svg: OnceLock<Vec<u8>>,
}

impl fmt::Debug for RenderedScene {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("RenderedScene")
            .field("size", &self.size)
            .field("svg_bytes", &self.svg.len())
            .field(
                "outline_replacements",
                &self.outline_plan.replacement_count(),
            )
            .field("outlined_svg_cached", &self.outlined_svg.get().is_some())
            .finish()
    }
}

impl RenderedScene {
    pub(crate) fn new(size: RootSize, output: Option<FinalizedSvgOutput>) -> Result<Self, Error> {
        #[cfg(test)]
        SCENE_CONSTRUCTION_CALLS.with(|calls| calls.set(calls.get() + 1));
        size.dimensions()?;
        let output = output.ok_or_else(|| {
            Error::Render("in-memory SVG backend did not finish rendering".into())
        })?;
        let (output_size, svg, outline_plan) = output.into_parts();
        if output_size != size {
            return Err(Error::Render(
                "finalized SVG geometry does not match the frozen root".into(),
            ));
        }
        Ok(Self {
            size,
            svg,
            outline_plan,
            outlined_svg: OnceLock::new(),
        })
    }

    pub(crate) const fn size(&self) -> RootSize {
        self.size
    }

    /// Borrow the exact canonical SVG bytes.
    #[must_use]
    pub(crate) fn svg_bytes(&self) -> &[u8] {
        &self.svg
    }

    /// Return SVG bytes with every text element converted to vector paths.
    ///
    /// The returned bytes are derived from immutable planned glyphs and the
    /// scene's retained font faces and contain no selectable text.
    ///
    /// # Errors
    ///
    /// Returns a render failure if immutable planned glyph outlining cannot be
    /// completed from the retained scene state.
    #[cfg(test)]
    pub(crate) fn svg_with_text_as_paths(&self) -> Result<Vec<u8>, Error> {
        let outlined = self.outlined_svg_bytes()?;
        let mut bytes = Vec::new();
        bytes.try_reserve_exact(outlined.len()).map_err(|error| {
            Error::Render(format!("outlined SVG copy reservation: {error}").into())
        })?;
        bytes.extend_from_slice(outlined);
        Ok(bytes)
    }

    /// Rasterize the scene to deterministic PNG bytes with explicit options.
    ///
    /// # Errors
    ///
    /// Returns an error for invalid or excessive sizing, planned-glyph failures,
    /// SVG parsing failures, allocation failure, or PNG encoding failure.
    pub(crate) fn png_bytes(&self, options: &PngOptions) -> Result<Vec<u8>, Error> {
        self.png_bytes_with_parser_limit(options, MAX_CONVERSION_SCENE_BYTES)
    }

    fn png_bytes_with_parser_limit(
        &self,
        options: &PngOptions,
        parser_limit: usize,
    ) -> Result<Vec<u8>, Error> {
        crate::render::svg_backend::validate_png_options(options)?;
        self.validate_png_source_limits()?;
        let target = crate::render::svg_backend::PngTargetPlan::new(self.size, options)?;
        let outlined = if let Some(bytes) = self.outlined_svg.get() {
            validate_parser_bytes(bytes.len(), parser_limit)?;
            bytes
        } else {
            let count = self
                .outline_plan
                .count_parser_bytes(self.size, parser_limit)?;
            validate_parser_bytes(count, parser_limit)?;
            self.retain_outline(count)?
        };
        crate::render::svg_backend::rasterize_svg_bytes_to_png(outlined, target, options)
    }

    fn validate_png_source_limits(&self) -> Result<(), Error> {
        self.size
            .validate_raster_source(MAX_EXPORT_DIMENSION, MAX_EXPORT_PIXELS)
    }

    pub(crate) fn outlined_svg_bytes(&self) -> Result<&[u8], Error> {
        if let Some(bytes) = self.outlined_svg.get() {
            return Ok(bytes);
        }
        let count = self.outline_plan.count_bytes(self.size)?;
        self.retain_outline(count).map(Vec::as_slice)
    }

    fn retain_outline(&self, count: usize) -> Result<&Vec<u8>, Error> {
        // No initializer locks around outlining or interruptible callbacks.
        // Racing publications may derive privately, but keep only one successful
        // immutable outline. A refused operation can never cache its failure.
        if let Some(bytes) = self.outlined_svg.get() {
            return Ok(bytes);
        }
        let bytes = self.outline_plan.derive_counted(self.size, count)?;
        crate::operation::checkpoint()?;
        let _ = self.outlined_svg.set(bytes);
        Ok(self
            .outlined_svg
            .get()
            .expect("successful outline initialization"))
    }
}

pub(crate) fn validate_png_parser_bytes(bytes: usize) -> Result<(), Error> {
    validate_parser_bytes(bytes, MAX_CONVERSION_SCENE_BYTES)
}

fn validate_parser_bytes(bytes: usize, limit: usize) -> Result<(), Error> {
    if bytes > limit {
        use crate::errors::{
            BudgetResource, Diagnostic, DiagnosticKind, ErrorContext, OperationPhase,
        };
        return Err(Error::Render(
            Diagnostic::new(
                DiagnosticKind::BudgetExceeded {
                    resource: BudgetResource::Bytes,
                    required: bytes as u128,
                    limit: limit as u128,
                },
                format!("PNG SVG parser input size exceeds the {limit}-byte conversion limit"),
            )
            .with_context(ErrorContext::new().with_operation(OperationPhase::Write)),
        ));
    }
    Ok(())
}

pub(crate) fn validate_png_target_dimensions(width: u32, height: u32) -> Result<(), Error> {
    use crate::errors::{BudgetResource, Diagnostic, DiagnosticKind, ErrorContext, OperationPhase};
    #[cfg(test)]
    PNG_TARGET_VALIDATION_CALLS.with(|calls| calls.set(calls.get() + 1));
    if width == 0 || height == 0 {
        return Err(Error::Render(
            format!("computed PNG dimensions must be positive and finite; got {width}x{height}")
                .into(),
        ));
    }
    let budget = |resource, required, limit, message| {
        Error::Render(
            Diagnostic::new(
                DiagnosticKind::BudgetExceeded {
                    resource,
                    required,
                    limit,
                },
                message,
            )
            .with_context(ErrorContext::new().with_operation(OperationPhase::Write)),
        )
    };
    if width.max(height) > MAX_EXPORT_DIMENSION {
        return Err(budget(BudgetResource::RasterDimension, u128::from(width.max(height)), u128::from(MAX_EXPORT_DIMENSION),
            format!("computed PNG dimensions {width}x{height} exceed the {MAX_EXPORT_DIMENSION}-pixel conversion limit")));
    }
    let pixels = u128::from(width) * u128::from(height);
    if pixels > u128::from(MAX_EXPORT_PIXELS) {
        return Err(budget(
            BudgetResource::Pixels,
            pixels,
            u128::from(MAX_EXPORT_PIXELS),
            format!("computed PNG work exceeds the {MAX_EXPORT_PIXELS}-pixel conversion limit"),
        ));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn direct_scene(width: u32, height: u32, byte_count: usize) -> RenderedScene {
        RenderedScene {
            size: RootSize::new(width, height),
            svg: vec![0; byte_count],
            outline_plan: SvgOutlinePlan::Failed("not used by source-limit tests".into()),
            outlined_svg: OnceLock::new(),
        }
    }

    #[test]
    fn png_source_limits_keep_exact_axis_work_and_byte_boundaries() {
        assert!(
            direct_scene(MAX_EXPORT_DIMENSION, 1, MAX_CONVERSION_SCENE_BYTES)
                .validate_png_source_limits()
                .is_ok()
        );
        assert!(direct_scene(MAX_EXPORT_DIMENSION + 1, 1, 1)
            .validate_png_source_limits()
            .unwrap_err()
            .to_string()
            .contains("scene dimensions"));
        let invalid = PngOptions {
            sizing: crate::output::PngSizing::Scale(0.0),
            ..PngOptions::default()
        };
        assert!(direct_scene(MAX_EXPORT_DIMENSION + 1, 1, 1)
            .png_bytes(&invalid)
            .unwrap_err()
            .to_string()
            .contains("png scale must be positive"));
        assert!(direct_scene(10_000, 10_000, 1)
            .validate_png_source_limits()
            .is_ok());
        assert!(direct_scene(10_000, 10_001, 1)
            .validate_png_source_limits()
            .unwrap_err()
            .to_string()
            .contains("scene work"));
        assert!(direct_scene(1, 1, MAX_CONVERSION_SCENE_BYTES + 1)
            .validate_png_source_limits()
            .is_ok());
        assert!(validate_png_parser_bytes(MAX_CONVERSION_SCENE_BYTES).is_ok());
        assert!(validate_png_parser_bytes(MAX_CONVERSION_SCENE_BYTES + 1).is_err());
    }
}