lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Visual requests belonging to native and fixed composition content.

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

use crate::{
    builder::recipe::style::PlotStyle,
    canvas::style::{CanvasStyle, TextPanelStyle},
    recipe::codec::{field, invalid, table, Codec},
    Result,
};

use super::{placement::Source, FixedPanel, ImageRendering, ObjectFit, ObjectPosition, Placement};

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

const APPEARANCE_FIELDS: &[grammar::Field] = &[
    grammar::optional::<ObjectFit>("fit"),
    grammar::optional::<ObjectPosition>("position"),
    grammar::optional::<ImageRendering>("image_rendering"),
];

pub(crate) fn fixed_schema(ctx: &mut Schema) -> serde_json::Value {
    grammar::record(ctx, APPEARANCE_FIELDS)
}

const PLACEMENT_STYLE_FIELDS: &[grammar::Field] = &[
    grammar::optional::<Option<ObjectFit>>("fit"),
    grammar::optional::<Option<ObjectPosition>>("position"),
    grammar::optional::<Option<ImageRendering>>("image_rendering"),
];
pub(crate) fn schema(ctx: &mut Schema) -> serde_json::Value {
    ctx.named("PlacementStyle",|ctx|{
        let mut fields=CONTENT.iter().map(|&name|{
            let shape=match name{
                "plot"=>crate::builder::recipe::style::schema(ctx,false),
                "canvas"=>crate::canvas::style::schema(ctx,false),
                "text"=>crate::canvas::style::text_panel_schema(ctx),
                "asset"|"frozen"=>grammar::object([], &[]),
                _=>unreachable!("current style content"),
            };
            (name,shape)
        }).collect::<Vec<_>>();
        let appearance=grammar::record(ctx,PLACEMENT_STYLE_FIELDS);
        fields.extend(PLACEMENT_STYLE_FIELDS.iter().map(|field|(field.name,appearance["properties"][field.name].clone())));
        let shape=grammar::with(grammar::object(fields,&[]),grammar::exclusive(CONTENT));
        grammar::with(shape,serde_json::json!({
            "if":{"required":["image_rendering"],"properties":{"image_rendering":{"not":{"const":false}}}},
            "then":{"required":["asset"]}
        }))
    })
}

pub(crate) const CONTENT: &[&str] = &["plot", "canvas", "text", "asset", "frozen"];

pub(crate) struct FixedAppearance {
    frozen: bool,
    fit: ObjectFit,
    position: ObjectPosition,
    rendering: ImageRendering,
}
impl FixedAppearance {
    pub(crate) fn read(item: &Item, frozen: bool) -> Result<Self> {
        let fields = grammar::record_fields(item, APPEARANCE_FIELDS)?;
        Ok(Self {
            frozen,
            fit: field(fields, "fit", Some(ObjectFit::Contain))?,
            position: field(fields, "position", Some(ObjectPosition::default()))?,
            rendering: field(fields, "image_rendering", Some(ImageRendering::Auto))?,
        })
    }

    pub(crate) fn capture(panel: &FixedPanel) -> Value {
        let mut fields = InlineTable::new();
        fields.insert("fit", panel.fit.encode());
        fields.insert("position", panel.position.encode());
        fields.insert("image_rendering", panel.rendering.encode());
        fields.into()
    }

    pub(crate) fn apply(self, target: &mut FixedPanel) -> Result<()> {
        if self.frozen != target.is_frozen() {
            return Err(invalid("style requires the same actual fixed content type"));
        }
        target.fit = self.fit;
        target.position = self.position;
        target.rendering = self.rendering;
        Ok(())
    }
}

enum SourceAppearance {
    Plot(PlotStyle),
    Canvas(Box<CanvasStyle>),
    Text(TextPanelStyle),
    Fixed { frozen: bool },
}
impl SourceAppearance {
    fn read(fields: &dyn TableLike, path: &str) -> Result<Self> {
        let mut values = CONTENT
            .iter()
            .filter_map(|name| fields.get(name).map(|item| (*name, item)));
        let (kind, item) = values
            .next()
            .ok_or_else(|| invalid("placement style requires a source role"))?;
        if values.next().is_some() {
            return Err(invalid(
                "placement style source roles are mutually exclusive",
            ));
        }
        match kind {
            "plot" => PlotStyle::read(item, &format!("{path}.plot"), false).map(Self::Plot),
            "canvas" => CanvasStyle::read(item, &format!("{path}.canvas"), false)
                .map(Box::new)
                .map(Self::Canvas),
            "text" => TextPanelStyle::read(item).map(Self::Text),
            "asset" | "frozen" => {
                table(item, &[])?;
                Ok(Self::Fixed {
                    frozen: kind == "frozen",
                })
            }
            _ => unreachable!("closed style source roles"),
        }
    }

    fn capture(source: &Source, fields: &mut InlineTable) -> Result<()> {
        let (name, value) = match source {
            Source::Plot(plot) => ("plot", plot.capture_style(false)?),
            Source::Canvas(canvas) => ("canvas", canvas.capture_style(false)?),
            Source::Text(text) => ("text", TextPanelStyle::capture(text)),
            Source::Fixed(source) => (
                if source.is_frozen() {
                    "frozen"
                } else {
                    "asset"
                },
                InlineTable::new().into(),
            ),
        };
        fields.insert(name, value);
        Ok(())
    }

    fn apply(self, source: &mut super::CompositionSource) -> Result<()> {
        match (self, &mut source.0) {
            (Self::Plot(style), Source::Plot(plot)) => style.apply(plot)?,
            (Self::Canvas(style), Source::Canvas(canvas)) => style.apply(canvas)?,
            (Self::Text(style), Source::Text(text)) => style.apply(text),
            (Self::Fixed { frozen }, Source::Fixed(target)) if frozen == target.is_frozen() => {
                return Ok(())
            }
            _ => return Err(invalid("incompatible placement style content role")),
        }
        // The edited native snapshot is now its own declaration rather than
        // the complete object previously adopted from a native binding.
        source.1 = None;
        Ok(())
    }
}

pub(crate) struct PlacementStyle {
    source: SourceAppearance,
    fit: Option<ObjectFit>,
    position: Option<ObjectPosition>,
    rendering: Option<ImageRendering>,
}

impl PlacementStyle {
    pub(crate) fn read(item: &Item, path: &str) -> Result<Self> {
        let mut allowed = CONTENT.to_vec();
        allowed.extend(grammar::names(PLACEMENT_STYLE_FIELDS));
        let fields = table(item, &allowed)?;
        let source = SourceAppearance::read(fields, path)?;
        let rendering = field(fields, "image_rendering", Some(None))?;
        if rendering.is_some() && !matches!(source, SourceAppearance::Fixed { frozen: false }) {
            return Err(invalid("image rendering style requires an image source"));
        }
        Ok(Self {
            source,
            fit: field(fields, "fit", Some(None))?,
            position: field(fields, "position", Some(None))?,
            rendering,
        })
    }

    pub(crate) fn capture(placement: &Placement) -> Result<Value> {
        let mut fields = InlineTable::new();
        SourceAppearance::capture(&placement.source.0, &mut fields)?;
        if let Some(fit) = placement.fit {
            fields.insert("fit", fit.encode());
        }
        if let Some(position) = placement.position {
            fields.insert("position", position.encode());
        }
        if let Some(rendering) = placement.rendering {
            fields.insert("image_rendering", rendering.encode());
        }
        Ok(fields.into())
    }

    pub(crate) fn apply(self, target: &mut Placement) -> Result<()> {
        self.source.apply(&mut target.source)?;
        target.fit = self.fit;
        target.position = self.position;
        target.rendering = self.rendering;
        target.validate()
    }
}

pub(crate) fn project_placement(item: &Item) -> Result<Value> {
    use crate::recipe::style::copy_fields;
    let source = item
        .as_table_like()
        .ok_or_else(|| invalid("expected a placement declaration"))?;
    let mut style = InlineTable::new();
    if let Some(plot) = source.get("plot") {
        style.insert(
            "plot",
            crate::builder::recipe::style::project(plot, None, false)?,
        );
    } else if let Some(canvas) = source.get("canvas") {
        style.insert(
            "canvas",
            crate::canvas::style::project(canvas, None, false)?,
        );
    } else if let Some(text) = source.get("text") {
        style.insert(
            "text",
            TextPanelStyle::capture(&crate::layout::TextPanel::decode(text, None)?),
        );
    } else if let Some(kind) = ["asset", "frozen"]
        .into_iter()
        .find(|name| source.contains_key(name))
    {
        style.insert(kind, InlineTable::new().into());
    } else {
        return Err(invalid(
            "a bound native placement has no visual declaration without its supplied content",
        ));
    }
    copy_fields(source, &mut style, &["fit", "position", "image_rendering"])?;
    Ok(style.into())
}