lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! The common single-image publication lifecycle.

use std::{
    io::{self, Write},
    path::Path,
    sync::Arc,
};

use crate::{
    composition::Composite,
    errors::{ErrorContext, OperationEffect, OperationFailure, OperationPhase},
    operation::{self, OperationOptions},
    Canvas, Error, Output, Plot, Result,
};

use super::{
    format::Encoding, value::complete_suffix, Format, PixelBuffer, PixelOptions, PixelTarget,
    PngOptions, PngSizing,
};

pub(crate) trait Source {
    fn frozen(&self) -> Result<Output>;
    fn png_default(&self) -> PngSizing {
        PngOptions::default().sizing
    }
}

impl<K: crate::kind::Marker> Source for Plot<K> {
    fn frozen(&self) -> Result<Output> {
        self.freeze()
    }
}
impl Source for Canvas {
    fn frozen(&self) -> Result<Output> {
        self.freeze()
    }
}
impl Source for crate::recipe::RecipeFigure {
    fn frozen(&self) -> Result<Output> {
        self.freeze()
    }
}
impl Source for Output {
    fn frozen(&self) -> Result<Output> {
        Ok(self.clone())
    }
}
impl Source for Composite {
    fn frozen(&self) -> Result<Output> {
        Ok(self.output().clone())
    }
    fn png_default(&self) -> PngSizing {
        self.default_png_sizing()
    }
}

fn encode(output: &Output, format: &Format, default: PngSizing) -> Result<Arc<[u8]>> {
    operation::phase(OperationPhase::Write)?;
    let scene = output.scene();
    match format.encoding {
        Encoding::Svg => scene.publication_svg(
            format.region.resolve(scene)?,
            !format.retains_text(),
            format.transparent,
            format.matte,
            None,
        ),
        Encoding::Png => Ok(scene
            .encode_png(
                &format.pixel_options(default),
                format.png_options(default).compression,
            )?
            .into()),
    }
}

fn save(
    source: &impl Source,
    path: impl AsRef<Path>,
    format: &Format,
    options: &OperationOptions,
) -> Result<Output> {
    operation::run(options, || save_inner(source, path, format))
}

pub(crate) fn save_inner(
    source: &impl Source,
    path: impl AsRef<Path>,
    format: &Format,
) -> Result<Output> {
    format.validate()?;
    let output = source.frozen()?;
    let bytes = encode(&output, format, source.png_default())?;
    operation::checkpoint()?;
    let path = operation::external(|| complete_suffix(path.as_ref(), format.suffix()))?;
    crate::orchestrator::write_atomic(&path, &bytes)?;
    Ok(output)
}

/// A host write failed after it might have had an external side effect.
/// Ordinary Rust `Write` failures guarantee no bytes on the failed call.
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
struct UnconfirmedWrite(io::Error);

/// Mark an I/O error from a foreign writer whose failed call may already have
/// written bytes. Bindings use this for native host exceptions, not ordinary
/// conforming Rust `Write` implementations.
#[doc(hidden)]
pub fn unconfirmed_stream_write(cause: io::Error) -> io::Error {
    io::Error::other(UnconfirmedWrite(cause))
}

fn stream_failure(cause: Error, confirmed: usize, uncertain: bool) -> Error {
    if confirmed == 0 && !uncertain {
        return cause;
    }
    Error::Operation(Box::new(OperationFailure::new(
        OperationPhase::Write,
        ErrorContext::new().with_operation(OperationPhase::Write),
        OperationEffect::StreamPrefix {
            confirmed_bytes: u64::try_from(confirmed).expect("addressable stream length"),
            may_have_more: uncertain,
        },
        cause,
    )))
}

pub(crate) fn write_stream(writer: &mut dyn Write, bytes: &[u8]) -> Result<()> {
    const CHUNK_BYTES: usize = 64 * 1024;
    let mut confirmed = 0;
    while confirmed < bytes.len() {
        operation::checkpoint().map_err(|error| stream_failure(error, confirmed, false))?;
        let remaining = &bytes[confirmed..];
        let chunk = &remaining[..remaining.len().min(CHUNK_BYTES)];
        match operation::external(|| writer.write(chunk)) {
            Ok(0) => {
                return Err(stream_failure(
                    io::Error::from(io::ErrorKind::WriteZero).into(),
                    confirmed,
                    false,
                ))
            }
            Ok(count) if count <= chunk.len() => confirmed += count,
            Ok(_) => {
                return Err(stream_failure(
                    io::Error::new(
                        io::ErrorKind::InvalidData,
                        "writer reported more bytes than supplied",
                    )
                    .into(),
                    confirmed,
                    true,
                ))
            }
            Err(error)
                if error
                    .get_ref()
                    .is_some_and(<dyn std::error::Error + Send + Sync>::is::<UnconfirmedWrite>) =>
            {
                let cause = error
                    .into_inner()
                    .expect("checked host I/O cause")
                    .downcast::<UnconfirmedWrite>()
                    .expect("checked host write failure");
                return Err(stream_failure(cause.0.into(), confirmed, true));
            }
            Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
            Err(error) => return Err(stream_failure(error.into(), confirmed, false)),
        }
    }
    // The complete stream is committed. Do not ask the host to flush, seek,
    // truncate or repeat the write, and do not turn a completed write into
    // cancellation at a final checkpoint.
    Ok(())
}

macro_rules! terminals {
    () => {
        /// Publish one complete image atomically, according to the selected
        /// device. The returned Output is the complete immutable scene.
        pub fn save_with(
            &self,
            path: impl AsRef<Path>,
            format: impl Into<Format>,
        ) -> Result<Output> {
            self.save_with_operation(path, format, &OperationOptions::default())
        }

        /// Publish a file under one operation, from preparation through install.
        pub fn save_with_operation(
            &self,
            path: impl AsRef<Path>,
            format: impl Into<Format>,
            options: &OperationOptions,
        ) -> Result<Output> {
            save(self, path, &format.into(), options)
        }

        /// Encode a complete device artifact in immutable owned memory.
        pub fn encode(&self, format: impl Into<Format>) -> Result<Arc<[u8]>> {
            self.encode_with_operation(format, &OperationOptions::default())
        }

        /// Encode in memory under this call's operation options.
        pub fn encode_with_operation(
            &self,
            format: impl Into<Format>,
            options: &OperationOptions,
        ) -> Result<Arc<[u8]>> {
            let format = format.into();
            operation::run(options, || {
                format.validate()?;
                encode(&self.frozen()?, &format, self.png_default())
            })
        }

        /// Write one complete artifact at the writer's current position.
        /// A failed external write may report a confirmed prefix.
        pub fn write_to(
            &self,
            writer: &mut dyn Write,
            format: impl Into<Format>,
        ) -> Result<Output> {
            self.write_to_with_operation(writer, format, &OperationOptions::default())
        }

        /// Write to a borrowed stream under one operation.
        pub fn write_to_with_operation(
            &self,
            writer: &mut dyn Write,
            format: impl Into<Format>,
            options: &OperationOptions,
        ) -> Result<Output> {
            let format = format.into();
            operation::run(options, || {
                format.validate()?;
                let output = self.frozen()?;
                let bytes = encode(&output, &format, self.png_default())?;
                write_stream(writer, &bytes)?;
                Ok(output)
            })
        }

        /// Read source-sized, straight RGBA8 samples of the complete scene.
        pub fn pixels(&self) -> Result<PixelBuffer> {
            self.pixels_with_options(PixelOptions::default())
        }

        /// Read immutable samples with explicit sampling and representation.
        pub fn pixels_with_options(&self, options: PixelOptions) -> Result<PixelBuffer> {
            self.pixels_with_options_with_operation(options, &OperationOptions::default())
        }

        /// Read immutable samples using this call's operation options.
        pub fn pixels_with_options_with_operation(
            &self,
            options: PixelOptions,
            operation_options: &OperationOptions,
        ) -> Result<PixelBuffer> {
            operation::run(operation_options, || {
                let output = self.frozen()?;
                operation::phase(OperationPhase::Write)?;
                output.scene().pixels(&options, None)
            })
        }

        /// Fill the actual logical pixels of a caller-owned buffer.
        pub fn pixels_into(&self, target: PixelTarget<'_>) -> Result<()> {
            self.pixels_into_with_options(target, PixelOptions::default())
        }

        /// Fill a caller-owned target using the requested pixel options.
        pub fn pixels_into_with_options(
            &self,
            target: PixelTarget<'_>,
            options: PixelOptions,
        ) -> Result<()> {
            self.pixels_into_with_options_with_operation(
                target,
                options,
                &OperationOptions::default(),
            )
        }

        /// Fill a caller-owned target in one cancellable operation.
        pub fn pixels_into_with_options_with_operation(
            &self,
            target: PixelTarget<'_>,
            options: PixelOptions,
            operation_options: &OperationOptions,
        ) -> Result<()> {
            let options = options.for_target(&target)?;
            operation::run(operation_options, || {
                let output = self.frozen()?;
                operation::phase(OperationPhase::Write)?;
                let pixels = output.scene().pixels(&options, Some(target.dimensions()))?;
                target.copy(&pixels)
            })
        }
    };
}

impl<K: crate::kind::Marker> Plot<K> {
    terminals!();
}
impl Canvas {
    terminals!();
}
impl crate::recipe::RecipeFigure {
    terminals!();
}
impl Output {
    terminals!();
}
impl Composite {
    terminals!();
}