lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Portable native declarations stored in versioned TOML documents.
//! Reading and extracting declarations never prepares a rendered scene.

mod address;
mod bindings;
pub(crate) mod capture;
pub(crate) mod codec;
pub(crate) mod collection;
mod composition;
pub(crate) mod declaration;
mod definitions;
mod document;
pub(crate) mod figure;
mod keys;
pub(crate) mod plot_input;
mod readers;
pub(crate) mod resolve;
mod run;
pub(crate) mod schema;
mod source;
pub(crate) mod style;
mod template;
mod text;
pub(crate) mod theme;

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

pub use crate::data::BindingSelector;
pub use bindings::{
    BindingArguments, BindingColumnType, BindingField, BindingInput, BindingObject, Bindings,
};
pub use composition::RecipeDocument;
pub use declaration::{BindingRequirement, BindingValueType};
pub use figure::RecipeFigure;
pub use run::{OutputDeclaration, RunAction, RunOptions, RunResult};
pub use source::{BindingSource, BindingSourceInput};
pub use style::StyleSource;

use toml_edit::{DocumentMut, InlineTable, Item, Table, Value};

use crate::{
    operation::{self, OperationOptions},
    Result, Theme,
};

use codec::{invalid, Codec};

/// Initial stable recipe grammar version. Compatible declaration additions
/// do not depend on the package's patch version.
pub const RECIPE_VERSION: &str = "0.3.0";

/// The authored range of a Plot recipe.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum PlotRecipeScope {
    /// Complete editable native declaration.
    #[default]
    Full,
    /// The complete effective visual requests for a compatible target.
    Style,
}

/// The authored range of a Canvas recipe.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum CanvasRecipeScope {
    /// Complete editable content and composition.
    #[default]
    Full,
    /// The effective root appearance and actual child visual requests.
    Style,
    /// The actual fillable grid and independent reservations.
    Layout,
}

/// One independent, validated native declaration document.
///
/// A Recipe retains the authored TOML rather than a rendered image. Reading
/// and writing it never looks up fonts or prepares scientific layout.
#[derive(Debug, Clone)]
pub struct Recipe {
    document: DocumentMut,
    base: PathBuf,
    bindings: Vec<BindingInfo>,
    warnings: Vec<RecipeWarning>,
}

/// One logical source and the actual declarations consuming it.
#[derive(Debug, Clone)]
pub struct BindingInfo {
    name: String,
    source: Option<BindingSource>,
    requirements: Vec<BindingRequirement>,
}
impl BindingInfo {
    /// Logical binding name.
    pub fn name(&self) -> &str {
        &self.name
    }
    /// Authored default source, if any.
    pub fn source(&self) -> Option<&BindingSource> {
        self.source.as_ref()
    }
    /// Actual role requirements across the document.
    pub fn requirements(&self) -> &[BindingRequirement] {
        &self.requirements
    }
}

/// A recoverable unresolved original key in a declaration.
#[derive(Debug, Clone)]
pub struct RecipeWarning {
    field: String,
    binding: String,
    reason: String,
}
impl RecipeWarning {
    pub(crate) fn new(field: &str, binding: &str, reason: &str) -> Self {
        Self {
            field: field.to_owned(),
            binding: binding.to_owned(),
            reason: reason.to_owned(),
        }
    }
    /// Actual authored field.
    pub fn field(&self) -> &str {
        &self.field
    }
    /// Logical binding consuming the original key.
    pub fn binding(&self) -> &str {
        &self.binding
    }
    /// Reason the key is still required.
    pub fn reason(&self) -> &str {
        &self.reason
    }
}

impl Recipe {
    fn from_theme(theme: &Theme) -> Self {
        let mut document = DocumentMut::new();
        document["recipe_version"] = toml_edit::value(RECIPE_VERSION);
        let toml_edit::Value::InlineTable(value) = theme.encode() else {
            unreachable!("complete theme table")
        };
        document["theme"] = Item::Table(section(value));
        Self {
            document,
            base: PathBuf::new(),
            bindings: Vec::new(),
            warnings: Vec::new(),
        }
    }

    /// Read a versioned recipe from a real local TOML file.
    pub fn read(path: impl AsRef<Path>) -> Result<Self> {
        Self::read_with_operation(path, &OperationOptions::default())
    }

    /// Read and validate declarations under one cancellable operation.
    pub fn read_with_operation(path: impl AsRef<Path>, options: &OperationOptions) -> Result<Self> {
        operation::run(options, || Self::read_document(path.as_ref()))
    }

    pub(crate) fn read_document(path: &Path) -> Result<Self> {
        let source = operation::external(|| std::fs::read_to_string(path))?;
        operation::checkpoint()?;
        let document = source
            .parse::<DocumentMut>()
            .map_err(|error| invalid(format!("recipe {}: {error}", path.display())))?;
        let (bindings, warnings) = Self::inventory(&document)
            .map_err(|error| error.with_prefix(&format!("recipe {}", path.display())))?;
        let absolute = std::path::absolute(path)?;
        let base = absolute
            .parent()
            .ok_or_else(|| invalid("recipe path has no directory"))?
            .to_owned();
        Ok(Self {
            document,
            base,
            bindings,
            warnings,
        })
    }

    /// Restore the independent Theme declaration. No construction context
    /// or installed font can change the result.
    pub fn theme(&self) -> Result<Theme> {
        let value = self
            .document
            .get("theme")
            .ok_or_else(|| invalid("recipe has no independent theme"))?;
        Theme::decode(value, None).map_err(|error| error.with_prefix("theme"))
    }

    /// Write this declaration to the supplied local TOML path atomically.
    pub fn write(&self, path: impl AsRef<Path>) -> Result<()> {
        self.write_with_operation(path, &OperationOptions::default())
    }

    /// Write a complete recipe under one cancellable operation.
    pub fn write_with_operation(
        &self,
        path: impl AsRef<Path>,
        options: &OperationOptions,
    ) -> Result<()> {
        operation::run(options, || self.write_document(path.as_ref()))
    }

    pub(crate) fn write_document(&self, path: &Path) -> Result<()> {
        let document = self.document_for_path(path)?;
        let source = document.to_string();
        operation::checkpoint()?;
        crate::orchestrator::write_atomic(path, source.as_bytes())
    }
}

// Keep scalar compound values inline while giving the author's complete
// role groups their own ordinary TOML sections.
fn section(value: InlineTable) -> Table {
    let mut table = Table::new();
    for (key, value) in value {
        let item = match value {
            Value::InlineTable(value) if !atomic_table(&value) => Item::Table(section(value)),
            value => Item::Value(value),
        };
        table.insert(&key, item);
    }
    table
}

fn atomic_table(value: &InlineTable) -> bool {
    value.contains_key("rgb")
        || value.contains_key("numerator")
        || ["em", "px", "short_side"]
            .iter()
            .any(|name| value.contains_key(name))
}

impl Theme {
    /// Capture this complete immutable Theme as a portable native declaration.
    pub fn get_recipe(&self) -> Result<Recipe> {
        self.get_recipe_with_operation(&OperationOptions::default())
    }

    /// Capture the Theme under one declaration operation.
    pub fn get_recipe_with_operation(&self, options: &OperationOptions) -> Result<Recipe> {
        operation::run(options, || {
            let recipe = Recipe::from_theme(self);
            operation::checkpoint()?;
            Ok(recipe)
        })
    }

    /// Write a Theme recipe to a local file and return that same declaration.
    pub fn recipe(&self, path: impl AsRef<Path>) -> Result<Recipe> {
        self.recipe_with_operation(path, &OperationOptions::default())
    }

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