lichtung-plot 0.2.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Opaque terminal output handle.

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

use crate::errors::OperationPhase;
use crate::operation::{self, OperationOptions};
use crate::scene::RenderedScene;
use crate::{
    output::{PngCompression, PngOptions, PngSizing},
    Error,
};

/// Opaque handle to one scene that has already been rendered.
///
/// Each output method borrows this handle, publishes its requested file immediately
/// and returns a shared handle to the same frozen scene for chaining. Publication
/// failure leaves the original handle usable; cloning never renders again.
///
/// Terminal methods complete the final native filename with their conventional
/// lowercase suffix. A filename already ending in the complete expected suffix
/// under ASCII case-insensitive comparison is preserved exactly; otherwise the
/// suffix is appended literally. Other filename text is never interpreted or
/// replaced, so `plot.v1` becomes `plot.v1.svg` and `plot.png` passed to
/// [`Output::svg`] becomes `plot.png.svg`.
///
/// Suffix completion happens only after format conversion succeeds. The caller
/// path must have a filename and must not currently identify a directory. Its
/// parent must already exist.
#[derive(Clone)]
pub struct Output {
    scene: Arc<RenderedScene>,
}

impl Output {
    pub(crate) fn new(scene: RenderedScene) -> Self {
        Self {
            scene: Arc::new(scene),
        }
    }

    /// Frozen canonical scene width in CSS pixels.
    ///
    /// This is the SVG root width, independent of PNG raster sizing. Inspecting
    /// it does not measure, render, or alter the retained scene.
    #[must_use]
    pub fn width(&self) -> f64 {
        self.scene
            .size()
            .dimensions()
            .expect("frozen scene geometry")
            .0
    }

    /// Frozen canonical scene height in CSS pixels.
    ///
    /// This is the SVG root height, independent of PNG raster sizing. All
    /// chained publications retain the same canonical dimensions.
    #[must_use]
    pub fn height(&self) -> f64 {
        self.scene
            .size()
            .dimensions()
            .expect("frozen scene geometry")
            .1
    }

    /// Original physical size request, if this root was explicitly sized in an
    /// absolute publication unit.
    pub fn physical_size(&self) -> Option<crate::layout::PhysicalSize> {
        self.scene.size().physical_size()
    }

    /// Publish a self-contained outlined SVG atomically.
    ///
    /// After text outlining succeeds, the final native filename is completed
    /// with `.svg`. A complete ASCII case-insensitive match such as `.SVG` is
    /// preserved exactly; otherwise `.svg` is appended without interpreting an
    /// existing extension.
    pub fn svg(&self, path: impl AsRef<Path>) -> Result<Self, Error> {
        self.svg_with_operation(path, &OperationOptions::default())
    }

    /// Publish outlined SVG under the supplied operation options.
    pub fn svg_with_operation(
        &self,
        path: impl AsRef<Path>,
        options: &OperationOptions,
    ) -> Result<Self, Error> {
        operation::run(options, || self.publish_svg(path, false))
    }

    /// Publish SVG with selectable and searchable text atomically.
    ///
    /// The final filename is completed with `.svg` using the literal
    /// suffix rule documented on [`Output`].
    pub fn svg_preserve_text(&self, path: impl AsRef<Path>) -> Result<Self, Error> {
        self.svg_preserve_text_with_operation(path, &OperationOptions::default())
    }

    /// Publish selectable-text SVG under the supplied operation options.
    pub fn svg_preserve_text_with_operation(
        &self,
        path: impl AsRef<Path>,
        options: &OperationOptions,
    ) -> Result<Self, Error> {
        operation::run(options, || self.publish_svg(path, true))
    }

    pub(crate) fn publish_svg(
        &self,
        path: impl AsRef<Path>,
        preserve_text: bool,
    ) -> Result<Self, Error> {
        operation::phase(OperationPhase::Write)?;
        let bytes = if preserve_text {
            self.scene.svg_bytes()
        } else {
            self.scene.outlined_svg_bytes()?
        };
        operation::checkpoint()?;
        let path = operation::external(|| complete_suffix(path.as_ref(), ".svg"))?;
        crate::orchestrator::write_atomic(&path, bytes)?;
        Ok(self.clone())
    }

    /// Publish a 300-DPI balanced-compression PNG atomically.
    ///
    /// The final native filename is completed with `.png` by
    /// [`Output::png_with_options`] after rasterization succeeds.
    pub fn png(&self, path: impl AsRef<Path>) -> Result<Self, Error> {
        self.png_with_operation(path, &OperationOptions::default())
    }

    /// Publish default PNG with the supplied operation options.
    pub fn png_with_operation(
        &self,
        path: impl AsRef<Path>,
        options: &OperationOptions,
    ) -> Result<Self, Error> {
        self.png_with_options_with_operation(path, PngOptions::default(), options)
    }

    /// Publish a source-sized balanced-compression PNG without density metadata.
    ///
    /// The final native filename is completed with `.png` by
    /// [`Output::png_with_options`] after rasterization succeeds.
    pub fn png_preview(&self, path: impl AsRef<Path>) -> Result<Self, Error> {
        self.png_preview_with_operation(path, &OperationOptions::default())
    }

    /// Publish source-sized PNG with the supplied operation options.
    pub fn png_preview_with_operation(
        &self,
        path: impl AsRef<Path>,
        options: &OperationOptions,
    ) -> Result<Self, Error> {
        self.png_with_options_with_operation(
            path,
            PngOptions {
                sizing: PngSizing::Source,
                compression: PngCompression::Balanced,
            },
            options,
        )
    }

    /// Publish a PNG atomically using the exact caller-provided options.
    ///
    /// After rasterization succeeds, the final native filename is completed
    /// with `.png`. A complete ASCII case-insensitive match such as `.PNG` is
    /// preserved exactly; otherwise `.png` is appended without interpreting an
    /// existing extension.
    pub fn png_with_options(
        &self,
        path: impl AsRef<Path>,
        options: PngOptions,
    ) -> Result<Self, Error> {
        self.png_with_options_with_operation(path, options, &OperationOptions::default())
    }

    /// Publish PNG under both device options and per-call resource limits.
    pub fn png_with_options_with_operation(
        &self,
        path: impl AsRef<Path>,
        options: PngOptions,
        operation: &OperationOptions,
    ) -> Result<Self, Error> {
        operation::run(operation, || self.publish_png(path, &options))
    }

    pub(crate) fn publish_png(
        &self,
        path: impl AsRef<Path>,
        options: &PngOptions,
    ) -> Result<Self, Error> {
        operation::phase(OperationPhase::Write)?;
        let bytes = self.scene.png_bytes(options)?;
        operation::checkpoint()?;
        let path = operation::external(|| complete_suffix(path.as_ref(), ".png"))?;
        crate::orchestrator::write_atomic(&path, &bytes)?;
        Ok(self.clone())
    }
}

fn complete_suffix(path: &Path, expected: &str) -> Result<PathBuf, Error> {
    if path.is_dir() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!(
                "render output path {} identifies a directory",
                path.display()
            ),
        )
        .into());
    }
    let file_name = path.file_name().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("render output path {} has no file name", path.display()),
        )
    })?;
    let encoded = file_name.as_encoded_bytes();
    if encoded
        .get(encoded.len().saturating_sub(expected.len())..)
        .is_some_and(|ending| ending.eq_ignore_ascii_case(expected.as_bytes()))
    {
        return Ok(path.to_path_buf());
    }

    let mut completed = OsString::from(file_name);
    completed.push(expected);
    Ok(path.with_file_name(completed))
}