lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Explicit document execution and publication settings.

use std::{
    io::Write,
    path::{Path, PathBuf},
};

use toml_edit::{Item, TableLike, Value};

use crate::{
    layout::LayoutReport,
    operation::{self, OperationOptions},
    output::{save_inner, Format},
    Output, Result,
};

use crate::recipe::schema::{self as grammar, Schema};

use super::{
    codec::{choice, invalid, Codec},
    source, Bindings, Recipe,
};

/// The implemented execution actions for a static recipe.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RunAction {
    /// Produce one complete image.
    Image,
    /// Prepare the editable native base's actual layout.
    Layout,
}

choice!(RunAction {Image=>"image",Layout=>"layout"});

impl std::str::FromStr for RunAction {
    type Err = crate::Error;

    fn from_str(value: &str) -> Result<Self> {
        Self::decode(&Item::Value(value.into()), None)
    }
}

/// The actual result of one successful document execution.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum RunResult {
    /// The complete scene frozen by the same execution that published the image.
    Image(Output),
    /// The actual accepted native layout.
    Layout(LayoutReport),
}

/// Call-local overrides. They never rewrite the document.
#[derive(Default)]
#[must_use]
pub struct RunOptions<'a> {
    bindings: Option<&'a Bindings<'a>>,
    action: Option<RunAction>,
    output: Option<PathBuf>,
    layout_writer: Option<&'a mut dyn Write>,
}

impl<'a> RunOptions<'a> {
    /// Substitute logical sources for the selected operation.
    pub fn bindings(mut self, bindings: &'a Bindings<'a>) -> Self {
        self.bindings = Some(bindings);
        self
    }

    /// Select the operation explicitly.
    pub const fn action(mut self, action: RunAction) -> Self {
        self.action = Some(action);
        self
    }

    /// Override just the selected action's destination, relative to the caller.
    pub fn output(mut self, path: impl Into<PathBuf>) -> Self {
        self.output = Some(path.into());
        self
    }

    /// Write the native layout JSON to this stream if the layout action has no
    /// declared or call-local file destination. Image actions do not use it.
    pub fn layout_writer(mut self, writer: &'a mut dyn Write) -> Self {
        self.layout_writer = Some(writer);
        self
    }
}

/// A requested default action and its independent destination and device.
#[derive(Debug, Clone)]
#[non_exhaustive]
#[expect(
    clippy::large_enum_variant,
    reason = "a single call-local publication declaration needs no heap indirection"
)]
pub enum OutputDeclaration {
    /// An image file and explicitly selected native format.
    Image {
        /// Local destination.
        path: PathBuf,
        /// Actual encoder and its publication settings.
        format: Format,
    },
    /// Native layout, optionally written as JSON.
    Layout {
        /// Local report destination, or no file.
        path: Option<PathBuf>,
    },
}

impl OutputDeclaration {
    /// Declare the image action with an explicit format.
    pub fn image(path: impl Into<PathBuf>, format: impl Into<Format>) -> Self {
        Self::Image {
            path: path.into(),
            format: format.into(),
        }
    }

    /// Declare the layout action and its optional report file.
    pub fn layout(path: Option<PathBuf>) -> Self {
        Self::Layout { path }
    }
}

#[derive(Default)]
struct Settings<'a> {
    action: Option<RunAction>,
    image: Option<PathBuf>,
    layout: Option<PathBuf>,
    image_options: Option<&'a Item>,
}

fn path_field(fields: &dyn TableLike, name: &str) -> Result<Option<PathBuf>> {
    fields
        .get(name)
        .map(|item| {
            let path = item
                .as_str()
                .filter(|path| !path.is_empty())
                .ok_or_else(|| invalid(format!("{name} requires a nonempty local path")))?;
            Ok(PathBuf::from(path))
        })
        .transpose()
}

const OUTPUT_FIELDS: &[grammar::Field] = &[
    grammar::optional::<RunAction>("action"),
    grammar::custom(
        "image",
        false,
        |_| serde_json::json!({"type":"string","minLength":1}),
    ),
    grammar::custom(
        "layout",
        false,
        |_| serde_json::json!({"type":"string","minLength":1}),
    ),
    grammar::optional::<Format>("image_options"),
];
pub(super) fn schema(ctx: &mut Schema) -> serde_json::Value {
    grammar::record(ctx, OUTPUT_FIELDS)
}

impl<'a> Settings<'a> {
    fn read(item: Option<&'a Item>) -> Result<Self> {
        let Some(item) = item else {
            return Ok(Self::default());
        };
        let fields = grammar::record_fields(item, OUTPUT_FIELDS)?;
        let settings = Self {
            action: fields
                .get("action")
                .map(|item| RunAction::decode(item, None))
                .transpose()?,
            image: path_field(fields, "image")?,
            layout: path_field(fields, "layout")?,
            image_options: fields.get("image_options"),
        };
        if let Some(options) = settings.image_options {
            let inferred = settings
                .image
                .as_ref()
                .and_then(|path| Format::from_path(path).ok());
            let _ = Format::decode(options, inferred)
                .map_err(|error| error.with_prefix("image_options"))?;
        }
        Ok(settings)
    }

    fn destination(
        &self,
        action: RunAction,
        override_path: Option<PathBuf>,
        base: &Path,
    ) -> Result<Option<PathBuf>> {
        if override_path.is_some() {
            return Ok(override_path);
        }
        let path = match action {
            RunAction::Image => &self.image,
            RunAction::Layout => &self.layout,
        };
        path.as_ref()
            .map(|path| source::expand_path(path, base))
            .transpose()
    }

    fn format(&self, destination: &Path) -> Result<Format> {
        // An explicit device wins; otherwise a known declared suffix selects
        // the encoder even when the destination was overridden for this run.
        let inferred = self
            .image
            .as_ref()
            .and_then(|path| Format::from_path(path).ok())
            .or_else(|| Format::from_path(destination).ok());
        if let Some(options) = self.image_options {
            if options.get("device").is_none() && inferred.is_none() {
                return Err(invalid(
                    "image output requires an explicit device or an SVG/PNG filename",
                ));
            }
            return Format::decode(options, inferred)
                .map_err(|error| error.with_prefix("image_options"));
        }
        inferred.ok_or_else(|| {
            invalid("image output requires an explicit device or an SVG/PNG filename")
        })
    }
}

pub(super) fn validate_output(item: Option<&Item>) -> Result<()> {
    Settings::read(item)
        .map(drop)
        .map_err(|error| error.with_prefix("output"))
}

pub(super) fn rebase_output(item: &mut Item, base: &Path) -> Result<()> {
    let fields = item
        .as_table_like_mut()
        .ok_or_else(|| invalid("output must be a table"))?;
    for name in ["image", "layout"] {
        if let Some(path) = fields.get_mut(name) {
            let rebased = source::rebase(
                Path::new(path.as_str().expect("validated destination")),
                base,
            );
            *path = path_item(&rebased)?;
        }
    }
    Ok(())
}

fn path_item(path: &Path) -> Result<Item> {
    let path = path
        .to_str()
        .filter(|path| !path.is_empty())
        .ok_or_else(|| invalid("output path requires nonempty Unicode"))?;
    Ok(toml_edit::value(path))
}

fn declared_path(path: &Path, base: &Path) -> Result<Item> {
    if path.as_os_str().is_empty() {
        return Err(invalid("output path must not be empty"));
    }
    path_item(&source::rebase(path, base))
}

impl Recipe {
    /// Set an explicit output declaration, retaining the other action's settings.
    pub fn set_output(&mut self, declaration: OutputDeclaration) -> Result<()> {
        let directory = std::env::current_dir()?;
        let mut document = self.document.clone();
        if document.get("output").is_none() {
            document["output"] = Item::Table(toml_edit::Table::new());
        }
        let fields = document["output"]
            .as_table_like_mut()
            .expect("validated output table");
        let action = match declaration {
            OutputDeclaration::Image { path, format } => {
                format.validate()?;
                fields.insert("image", declared_path(&path, &directory)?);
                fields.insert("image_options", Item::Value(format.encode()));
                RunAction::Image
            }
            OutputDeclaration::Layout { path } => {
                if let Some(path) = path {
                    fields.insert("layout", declared_path(&path, &directory)?);
                } else {
                    fields.remove("layout");
                }
                RunAction::Layout
            }
        };
        fields.insert("action", Item::Value(action.encode()));
        self.install(document)
    }

    /// Execute the explicitly declared action using local default inputs.
    pub fn run(&self) -> Result<RunResult> {
        self.run_with(RunOptions::default())
    }

    /// Execute one action with optional call-local source and destination overrides.
    pub fn run_with(&self, options: RunOptions<'_>) -> Result<RunResult> {
        self.run_with_operation(options, &OperationOptions::default())
    }

    /// Execute the selected action under one cancellable operation.
    pub fn run_with_operation(
        &self,
        options: RunOptions<'_>,
        operation: &OperationOptions,
    ) -> Result<RunResult> {
        operation::run(operation, || self.run_inner(options))
    }

    fn run_inner(&self, options: RunOptions<'_>) -> Result<RunResult> {
        let settings = Settings::read(self.document.get("output"))?;
        let action = options.action.or(settings.action).ok_or_else(|| {
            invalid("recipe execution requires an explicit action (image or layout)")
        })?;
        let destination = settings.destination(action, options.output, &self.base)?;
        let default = Bindings::new();
        let bindings = options.bindings.unwrap_or(&default);
        match action {
            RunAction::Layout => {
                let report = self.layout_source(bindings)?.recipe_layout_report()?;
                if destination.is_some() || options.layout_writer.is_some() {
                    operation::phase(crate::errors::OperationPhase::Write)?;
                    let mut json = report.to_json()?;
                    json.push('\n');
                    if let Some(path) = destination {
                        crate::orchestrator::write_atomic(&path, json.as_bytes())?;
                    } else if let Some(writer) = options.layout_writer {
                        crate::output::write_stream(writer, json.as_bytes())?;
                    }
                }
                Ok(RunResult::Layout(report))
            }
            RunAction::Image => {
                let destination = destination
                    .ok_or_else(|| invalid("image action requires an output destination"))?;
                let format = settings.format(&destination)?;
                let output = if self.document.get("base").is_some() {
                    let composite = self.composition_inner(bindings)?.compose_inner()?;
                    save_inner(&composite, &destination, &format)?
                } else {
                    if self.document.get("placements").is_some() {
                        return Err(invalid(
                            "image action for placement declarations requires an explicit base",
                        ));
                    }
                    let figure = self.build_inner(bindings)?;
                    save_inner(&figure, &destination, &format)?
                };
                Ok(RunResult::Image(output))
            }
        }
    }
}