lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Owned declarations for repeatable final composition.

use std::{path::Path, sync::Arc};

use crate::{
    operation::{self, OperationOptions},
    recipe::Recipe,
    Error, Result,
};

use super::{ComposeOptions, Composite, CompositionSource, Placement};

#[derive(Clone)]
pub(super) struct PlanStep {
    pub(super) items: Vec<Placement>,
    pub(super) options: ComposeOptions,
}

impl PlanStep {
    fn new(items: impl IntoIterator<Item = Placement>, options: ComposeOptions) -> Result<Self> {
        let items = crate::data::source::collect_source(items.into_iter().map(|item| {
            item.validate()?;
            Ok(item)
        }))?;
        Ok(Self { items, options })
    }
}

/// An independent base snapshot and its ordered, repeatable composition steps.
///
/// The native base and native placements remain editable declarations in this
/// plan. No layout or image is prepared until [`Self::compose`] is called.
#[derive(Clone)]
pub struct CompositionPlan {
    pub(super) base: CompositionSource,
    pub(super) steps: Arc<Vec<PlanStep>>,
}

impl CompositionPlan {
    /// Capture a base and the first ordered placement step.
    pub fn new(
        base: impl TryInto<CompositionSource, Error: Into<Error>>,
        items: impl IntoIterator<Item = Placement>,
    ) -> Result<Self> {
        Self::with_options(base, items, ComposeOptions::default())
    }

    /// Capture the actual first step's viewport policy.
    pub fn with_options(
        base: impl TryInto<CompositionSource, Error: Into<Error>>,
        items: impl IntoIterator<Item = Placement>,
        options: ComposeOptions,
    ) -> Result<Self> {
        Self::with_operation(base, items, options, &OperationOptions::default())
    }

    /// Capture the base and placements under one cancellable operation.
    pub fn with_operation(
        base: impl TryInto<CompositionSource, Error: Into<Error>>,
        items: impl IntoIterator<Item = Placement>,
        options: ComposeOptions,
        operation: &OperationOptions,
    ) -> Result<Self> {
        operation::run(operation, || {
            let base = base.try_into().map_err(Into::into)?;
            let step = PlanStep::new(items, options)?;
            Ok(Self::from_parts(base, vec![step]))
        })
    }

    pub(super) fn from_parts(base: CompositionSource, steps: Vec<PlanStep>) -> Self {
        debug_assert!(!steps.is_empty());
        Self {
            base,
            steps: Arc::new(steps),
        }
    }

    /// Append another actual placement operation in the original base frame.
    pub fn then(self, items: impl IntoIterator<Item = Placement>) -> Result<Self> {
        self.then_with_options(items, ComposeOptions::default())
    }

    /// Append one independent placement step with its own viewport policy.
    pub fn then_with_options(
        self,
        items: impl IntoIterator<Item = Placement>,
        options: ComposeOptions,
    ) -> Result<Self> {
        self.then_with_operation(items, options, &OperationOptions::default())
    }

    /// Append a step under the caller's cancellation options.
    pub fn then_with_operation(
        mut self,
        items: impl IntoIterator<Item = Placement>,
        options: ComposeOptions,
        operation: &OperationOptions,
    ) -> Result<Self> {
        operation::run(operation, || {
            let step = PlanStep::new(items, options)?;
            let steps = Arc::make_mut(&mut self.steps);
            crate::data::source::reserve_source(steps, 1)?;
            steps.push(step);
            Ok(self)
        })
    }

    /// Prepare the actual native or fixed base and freeze the ordered steps.
    pub fn compose(&self) -> Result<Composite> {
        self.compose_with_operation(&OperationOptions::default())
    }

    /// Compose the complete plan under one operation.
    pub fn compose_with_operation(&self, options: &OperationOptions) -> Result<Composite> {
        operation::run(options, || self.compose_inner())
    }

    pub(crate) fn compose_inner(&self) -> Result<Composite> {
        let mut steps = self.steps.iter();
        let first = steps.next().expect("actual first step");
        let mut composite = Composite::prepare(
            self.base.clone(),
            first.items.iter().cloned(),
            first.options,
            None,
        )?;
        for step in steps {
            operation::checkpoint()?;
            composite = Composite::prepare(
                composite.into(),
                step.items.iter().cloned(),
                step.options,
                None,
            )?;
        }
        Ok(composite)
    }

    pub(crate) fn check_recipe_science(&self) -> Result<()> {
        self.base.check_recipe_science(None)?;
        for step in self.steps.iter() {
            for item in &step.items {
                operation::check()?;
                item.check_recipe_science(None)?;
            }
        }
        Ok(())
    }

    /// Capture the complete plan without rendering its base or placements.
    pub fn get_recipe(&self) -> Result<Recipe> {
        self.get_recipe_with_operation(&OperationOptions::default())
    }

    /// Capture a plan under one cancellable declaration operation.
    pub fn get_recipe_with_operation(&self, options: &OperationOptions) -> Result<Recipe> {
        operation::run(options, || self.capture_declaration())
    }

    /// Write the complete plan and return that same independent Recipe.
    pub fn recipe(&self, path: impl AsRef<Path>) -> Result<Recipe> {
        self.recipe_with_operation(path, &OperationOptions::default())
    }

    /// Capture and atomically write the plan under one operation.
    pub fn recipe_with_operation(
        &self,
        path: impl AsRef<Path>,
        options: &OperationOptions,
    ) -> Result<Recipe> {
        operation::run(options, || {
            let recipe = self.capture_declaration()?;
            recipe.write_document(path.as_ref())?;
            Ok(recipe)
        })
    }
}