lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! A data-independent visual declaration, applied to an existing native owner.

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

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

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

use super::{
    codec::{field, invalid, Codec},
    Recipe,
};

/// Borrow an existing style recipe or read one from a local path.
pub enum StyleSource<'a> {
    /// A previously extracted or read recipe.
    Recipe(&'a Recipe),
    /// A local recipe file.
    Path(PathBuf),
}

impl<'a> From<&'a Recipe> for StyleSource<'a> {
    fn from(recipe: &'a Recipe) -> Self {
        Self::Recipe(recipe)
    }
}

macro_rules! style_paths {
    ($($ty:ty),+ $(,)?) => {$(
        impl From<$ty> for StyleSource<'_> {
            fn from(path: $ty) -> Self {
                Self::Path(PathBuf::from(path))
            }
        }
    )+};
}
style_paths!(&str, String, &String, &Path, PathBuf, &PathBuf);

impl StyleSource<'_> {
    pub(crate) fn with_recipe<T>(self, apply: impl FnOnce(&Recipe) -> Result<T>) -> Result<T> {
        match self {
            Self::Recipe(recipe) => apply(recipe),
            Self::Path(path) => apply(&Recipe::read_document(&path)?),
        }
    }
}

pub(crate) fn is_style(item: &Item) -> bool {
    item.get("scope").and_then(Item::as_str) == Some("style")
}

pub(crate) fn style_theme(
    fields: &dyn TableLike,
    root: bool,
) -> Result<Option<std::sync::Arc<Theme>>> {
    let theme = fields
        .get("theme")
        .map(|item| Theme::decode(item, None))
        .transpose()?;
    if root && theme.is_none() {
        return Err(invalid(
            "a style root requires its effective complete theme",
        ));
    }
    Ok(theme.map(std::sync::Arc::new))
}

pub(crate) fn capture_text(text: &Text) -> Value {
    text.appearance_only().encode()
}

const STYLE_TEXT_FIELDS: &[super::schema::Field] = &[
    super::schema::optional::<crate::theme::TextTheme>("style"),
    super::schema::optional::<crate::text::TextLayout>("layout"),
];
pub(crate) fn text_schema(ctx: &mut super::schema::Schema) -> serde_json::Value {
    ctx.named("TextStyle", |ctx| {
        super::schema::record(ctx, STYLE_TEXT_FIELDS)
    })
}

pub(crate) fn read_text(item: &Item) -> Result<Text> {
    super::schema::record_fields(item, STYLE_TEXT_FIELDS)?;
    Text::decode(item, None)
}

pub(crate) fn text_field(fields: &dyn TableLike, name: &str) -> Result<Text> {
    fields
        .get(name)
        .map(read_text)
        .transpose()
        .map(|value| value.unwrap_or(Text::UNSET))
        .map_err(|error| error.with_prefix(name))
}

pub(crate) fn copy_fields(
    source: &dyn TableLike,
    target: &mut InlineTable,
    names: &[&str],
) -> Result<()> {
    for &name in names {
        if let Some(item) = source.get(name) {
            target.insert(
                name,
                item.clone()
                    .into_value()
                    .map_err(|_| invalid("empty declaration field"))?,
            );
        }
    }
    Ok(())
}

pub(crate) fn project_text(
    source: &dyn TableLike,
    target: &mut InlineTable,
    names: &[&str],
) -> Result<()> {
    for &name in names {
        if let Some(text) = source.get(name) {
            target.insert(name, capture_text(&Text::decode(text, None)?));
        }
    }
    Ok(())
}

pub(crate) fn effective_theme(fields: &dyn TableLike, parent: Option<&Theme>) -> Result<Theme> {
    if let Some(theme) = field::<Option<Theme>>(fields, "theme", Some(None))? {
        return Ok(theme);
    }
    if let Some(theme) = parent {
        return Ok(theme.clone());
    }
    Ok(field::<Option<Theme>>(fields, "default_theme", Some(None))?
        .unwrap_or_else(Theme::publication))
}

pub(crate) fn project_existing_style(
    item: &Item,
    parent: Option<&Theme>,
    root: bool,
) -> Result<InlineTable> {
    let fields = item
        .as_table_like()
        .ok_or_else(|| invalid("expected a style owner"))?;
    let Value::InlineTable(mut value) = item
        .clone()
        .into_value()
        .map_err(|_| invalid("invalid style owner"))?
    else {
        return Err(invalid("expected a style table"));
    };
    if root {
        value.insert("theme", effective_theme(fields, parent)?.encode());
    }
    Ok(value)
}

impl Recipe {
    /// Project the declared visual scope without resolving observation bindings.
    pub fn style(&self) -> Result<Self> {
        self.style_with_operation(&OperationOptions::default())
    }

    /// Project the visual scope under one cancellable operation.
    pub fn style_with_operation(&self, options: &OperationOptions) -> Result<Self> {
        crate::operation::run(options, || self.project_style_root())
    }

    fn project_style_root(&self) -> Result<Self> {
        let registry = super::resolve::Registry::read(self.document.get("bindings"))?;
        let document = self.expanded_document(&registry)?;
        let (root, value) = if let Some(plot) = document.get("plot") {
            (
                "plot",
                crate::builder::recipe::style::project(plot, None, true)?,
            )
        } else if let Some(canvas) = document.get("canvas") {
            ("canvas", crate::canvas::style::project(canvas, None, true)?)
        } else {
            return Err(invalid("recipe has no native Plot or Canvas style root"));
        };
        Self::from_capture(root, value, super::capture::Capture::new())
    }

    /// Project one actual native grid panel's style, including its effective
    /// inherited theme. The address may be its name or its original anchor.
    pub fn style_in(&self, owner: impl Into<crate::layout::PanelPath>) -> Result<Self> {
        self.style_in_with_operation(owner, &OperationOptions::default())
    }

    /// Project a selected visual owner under one cancellable operation.
    pub fn style_in_with_operation(
        &self,
        owner: impl Into<crate::layout::PanelPath>,
        options: &OperationOptions,
    ) -> Result<Self> {
        crate::operation::run(options, || {
            let owner = owner.into();
            if owner.is_root() {
                return self.project_style_root();
            }
            let registry = super::resolve::Registry::read(self.document.get("bindings"))?;
            let document = self.expanded_document(&registry)?;
            let canvas = document
                .get("canvas")
                .and_then(Item::as_table_like)
                .ok_or_else(|| invalid("a selected grid style requires a Canvas declaration"))?;
            let panel = style_panel(canvas, &owner)?;
            let plot = panel.get("plot").ok_or_else(|| {
                invalid("selected panel has no independently declared Plot style")
            })?;
            let parent = effective_theme(canvas, None)?;
            let value = crate::builder::recipe::style::project(plot, Some(&parent), true)?;
            Self::from_capture("plot", value, super::capture::Capture::new())
        })
    }

    pub(crate) fn style_root(&self, root: &str) -> Result<&Item> {
        self.document
            .get(root)
            .filter(|item| is_style(item))
            .ok_or_else(|| {
                invalid(format!(
                    "apply_style requires a {root} recipe with scope=\"style\""
                ))
            })
    }

    pub(crate) fn has_style_root(&self) -> bool {
        ["plot", "canvas"]
            .iter()
            .filter_map(|root| self.document.get(root))
            .any(is_style)
    }
}

fn style_panel(canvas: &dyn TableLike, owner: &crate::layout::PanelPath) -> Result<Item> {
    use crate::layout::PanelStep;
    let [step] = owner.steps() else {
        return Err(invalid("style selection requires a direct Canvas panel"));
    };
    let Some(panels) = canvas.get("panels") else {
        return Err(invalid("Canvas has no declared panel styles"));
    };
    let mut matched = None;
    for item in super::codec::array_items(panels)? {
        crate::operation::check()?;
        let equal = match step {
            PanelStep::Named(name) => {
                item.get("name").and_then(Item::as_str) == Some(name.as_str())
            }
            PanelStep::Cell(row, column) => {
                let coordinate = |key: &str| {
                    item.get(key)
                        .and_then(Item::as_integer)
                        .and_then(|value| usize::try_from(value).ok())
                };
                coordinate("row") == Some(*row) && coordinate("column") == Some(*column)
            }
            _ => return Err(invalid("style selection requires a direct Canvas panel")),
        };
        if equal && matched.replace(item.clone()).is_some() {
            return Err(invalid("ambiguous style panel address"));
        }
    }
    matched.ok_or_else(|| invalid(format!("no declared style owner at {owner:?}")))
}

impl<K: crate::kind::Marker> crate::Plot<K> {
    /// Apply a compatible visual declaration while retaining this plot's data,
    /// authored text, scientific configuration and construction default.
    pub fn apply_style<'a>(self, source: impl Into<StyleSource<'a>>) -> Result<Self> {
        self.apply_style_with_operation(source, &OperationOptions::default())
    }

    /// Apply a style under the caller's cancellation options.
    pub fn apply_style_with_operation<'a>(
        mut self,
        source: impl Into<StyleSource<'a>>,
        options: &OperationOptions,
    ) -> Result<Self> {
        crate::operation::run(options, || {
            source.into().with_recipe(|recipe| {
                crate::builder::recipe::style::apply_plot_recipe(&mut self, recipe)
            })?;
            crate::operation::checkpoint()?;
            Ok(self)
        })
    }
}