lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! A typed, owned source and its independent placement declaration.

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

use super::fixed::FixedSource;
use super::{ImageAsset, ImageRendering, ObjectFit, ObjectPosition, PlacedContent};
use crate::builder::PlotDescription;
use crate::layout::{
    Anchor, BoundaryRef, BoxTarget, PlacePoint, Rect, RectRef, RootRequest, TextPanel,
};
use crate::{Canvas, Error, Output, Plot, Result};

/// A source accepted by final composition. Native declarations, retained
/// native outputs and sealed local images all retain their actual content.
#[derive(Clone)]
pub struct CompositionSource(
    pub(crate) Source,
    pub(crate) Option<crate::data::DataSourceInfo>,
);

#[derive(Clone)]
pub(crate) enum Source {
    Plot(Box<PlotDescription>),
    Canvas(Box<Canvas>),
    Text(TextPanel),
    Fixed(FixedSource),
}

impl<K: crate::kind::Marker> From<Plot<K>> for CompositionSource {
    fn from(plot: Plot<K>) -> Self {
        Self(Source::Plot(Box::new(plot.into_description())), None)
    }
}
impl<K: crate::kind::Marker> From<&Plot<K>> for CompositionSource {
    fn from(plot: &Plot<K>) -> Self {
        Self(Source::Plot(Box::new(plot.description().clone())), None)
    }
}
impl From<Canvas> for CompositionSource {
    fn from(canvas: Canvas) -> Self {
        Self(Source::Canvas(Box::new(canvas)), None)
    }
}
impl From<&Canvas> for CompositionSource {
    fn from(canvas: &Canvas) -> Self {
        Self::from(canvas.clone())
    }
}
impl From<TextPanel> for CompositionSource {
    fn from(text: TextPanel) -> Self {
        Self(Source::Text(text), None)
    }
}
impl From<&TextPanel> for CompositionSource {
    fn from(text: &TextPanel) -> Self {
        Self::from(text.clone())
    }
}
impl From<Output> for CompositionSource {
    fn from(output: Output) -> Self {
        Self(Source::Fixed(FixedSource::Frozen(output)), None)
    }
}
impl From<&Output> for CompositionSource {
    fn from(output: &Output) -> Self {
        Self::from(output.clone())
    }
}
impl From<ImageAsset> for CompositionSource {
    fn from(asset: ImageAsset) -> Self {
        Self(Source::Fixed(FixedSource::Image(asset)), None)
    }
}
impl From<&ImageAsset> for CompositionSource {
    fn from(asset: &ImageAsset) -> Self {
        Self::from(asset.clone())
    }
}

macro_rules! local_source {
    ($($ty:ty),+ $(,)?) => {$(
        impl TryFrom<$ty> for CompositionSource {
            type Error = Error;
            fn try_from(path: $ty) -> Result<Self> {
                Ok(ImageAsset::read_path(path.as_ref())?.into())
            }
        }
    )+};
}
local_source!(&str, String, &Path, PathBuf, &PathBuf);

impl CompositionSource {
    pub(super) fn prepare(
        self,
        constraint: Option<RootRequest>,
        parent_theme: Option<&crate::Theme>,
    ) -> Result<FixedSource> {
        use crate::orchestrator::root::RootSource;
        match self.0 {
            Source::Fixed(source) => Ok(source),
            Source::Plot(plot) => {
                let mut plot = *plot;
                if let Some(request) = constraint {
                    plot.set_sizing_request(request);
                }
                if let Some(parent) = parent_theme {
                    plot.inherit_composition_theme(parent);
                }
                Ok(FixedSource::Frozen(Output::new(
                    crate::orchestrator::render_scene(RootSource::Plot(&plot))?,
                )))
            }
            Source::Canvas(canvas) => {
                let mut canvas = *canvas;
                if let Some(request) = constraint {
                    canvas.set_sizing_request(request);
                }
                if let Some(parent) = parent_theme {
                    if canvas.get_theme().is_none() {
                        canvas = canvas.theme(parent.clone());
                    }
                }
                Ok(FixedSource::Frozen(Output::new(
                    crate::orchestrator::render_scene(RootSource::Canvas(&canvas))?,
                )))
            }
            Source::Text(text) => {
                // A standalone text panel reuses the real one-panel layout.
                // The internal wrapper has no construction-context default.
                let canvas = Canvas::grid(1, 1)?.default_theme(None).panel(0, 0, text)?;
                Self::from(canvas).prepare(constraint, parent_theme)
            }
        }
    }

    fn is_fixed(&self) -> bool {
        matches!(self.0, Source::Fixed(_))
    }

    fn is_image(&self) -> bool {
        matches!(self.0, Source::Fixed(FixedSource::Image(_)))
    }
}

#[derive(Clone)]
pub(super) enum Target {
    At(PlacePoint),
    Box(BoxTarget),
}

/// An owned item and a placement in the original base scene's CSS coordinates.
/// One placement chooses a point or a box; its optional boundary is independent
/// of its geometric target.
#[derive(Clone)]
#[must_use]
pub struct Placement {
    pub(super) source: CompositionSource,
    pub(super) target: Target,
    pub(super) fit: Option<ObjectFit>,
    pub(super) position: Option<ObjectPosition>,
    pub(super) anchor: Option<Anchor>,
    pub(super) requested: [Option<f64>; 2],
    pub(super) rendering: Option<ImageRendering>,
    pub(super) boundary: Option<BoundaryRef>,
}

impl Placement {
    pub(super) fn new(source: CompositionSource, target: Target) -> Self {
        Self {
            source,
            target,
            fit: None,
            position: None,
            anchor: None,
            requested: [None, None],
            rendering: None,
            boundary: None,
        }
    }

    /// Place a source by its own viewport anchor.
    pub fn at(
        item: impl TryInto<CompositionSource, Error: Into<Error>>,
        at: impl TryInto<PlacePoint, Error: Into<Error>>,
    ) -> Result<Self> {
        Ok(Self::new(
            item.try_into().map_err(Into::into)?,
            Target::At(at.try_into().map_err(Into::into)?),
        ))
    }

    /// Fit a source into a real CSS rectangle or a frozen layout reference.
    pub fn boxed(
        item: impl TryInto<CompositionSource, Error: Into<Error>>,
        target: impl TryInto<BoxTarget, Error: Into<Error>>,
    ) -> Result<Self> {
        Ok(Self::new(
            item.try_into().map_err(Into::into)?,
            Target::Box(target.try_into().map_err(Into::into)?),
        ))
    }

    /// Use the complete allocated footprint of an actual reserved anchor.
    pub fn in_slot(
        item: impl TryInto<CompositionSource, Error: Into<Error>>,
        row: usize,
        column: usize,
    ) -> Result<Self> {
        Self::boxed(item, RectRef::slot(row, column))
    }

    /// Set an explicit fixed-source fitting policy for this box.
    pub fn fit(mut self, fit: ObjectFit) -> Self {
        self.fit = Some(fit);
        self
    }
    /// Set the object's position within its box.
    pub fn position(mut self, position: ObjectPosition) -> Self {
        self.position = Some(position);
        self
    }
    /// Choose the source viewport point for an at-placement.
    pub fn anchor(mut self, anchor: Anchor) -> Self {
        self.anchor = Some(anchor);
        self
    }
    /// Request an at-placement width in CSS pixels.
    pub fn width(mut self, width: f64) -> Self {
        self.requested[0] = Some(width);
        self
    }
    /// Request an at-placement height in CSS pixels.
    pub fn height(mut self, height: f64) -> Self {
        self.requested[1] = Some(height);
        self
    }
    /// Request an at-placement size in CSS pixels.
    pub fn size(mut self, width: f64, height: f64) -> Self {
        self.requested = [Some(width), Some(height)];
        self
    }
    /// Set the sampling policy for an image source.
    pub fn image_rendering(mut self, rendering: ImageRendering) -> Self {
        self.rendering = Some(rendering);
        self
    }
    /// Use a real closed boundary of the original native base.
    pub fn at_boundary(mut self, boundary: BoundaryRef) -> Self {
        self.boundary = Some(boundary);
        self
    }

    pub(crate) fn boundary(&self) -> Option<&BoundaryRef> {
        self.boundary.as_ref()
    }

    /// Validate this placement's authored options without resolving a base.
    pub fn validate(&self) -> Result<()> {
        if self
            .requested
            .into_iter()
            .flatten()
            .any(|value| !value.is_finite() || value <= 0.)
        {
            return Err(Error::Data(
                "placement dimensions must be positive finite CSS pixels".into(),
            ));
        }
        match self.target {
            Target::At(_) if self.fit.is_some() || self.position.is_some() => {
                return Err(Error::Data(
                    "fit and position require a placement box".into(),
                ))
            }
            Target::Box(_)
                if self.anchor.is_some() || self.requested.iter().any(Option::is_some) =>
            {
                return Err(Error::Data(
                    "anchor, width and height require an at-placement".into(),
                ))
            }
            _ => {}
        }
        if self.rendering.is_some() && !self.source.is_image() {
            return Err(Error::Data(
                "image_rendering requires an image source".into(),
            ));
        }
        Ok(())
    }

    pub(crate) fn slot_borrow(&self) -> Result<(usize, usize)> {
        self.validate()?;
        if self.boundary.is_some() {
            return Err(Error::Data(
                "a paint boundary requires a frozen base scene".into(),
            ));
        }
        match &self.target {
            Target::Box(target) => target.reservation_anchor(),
            Target::At(_) => None,
        }
        .ok_or_else(|| {
            Error::Data("an editable Canvas placement must borrow a reserved slot".into())
        })
    }

    pub(crate) fn prepare(
        self,
        resolve: impl Fn(&RectRef) -> Result<Rect>,
        parent_theme: Option<&crate::Theme>,
    ) -> Result<PlacedContent> {
        self.validate()?;
        let fixed = self.source.is_fixed();
        let rendering = self.rendering.unwrap_or_default();
        let placed = match self.target {
            Target::Box(target) => {
                let frame = target.resolve(&resolve)?;
                let request = (!fixed && self.fit.is_none())
                    .then(|| RootRequest::size(frame.width(), frame.height()));
                let source = self.source.prepare(request, parent_theme)?;
                PlacedContent::boxed(
                    source,
                    frame,
                    if request.is_some() {
                        ObjectFit::Fill
                    } else {
                        self.fit.unwrap_or_default()
                    },
                    self.position.unwrap_or_default(),
                    rendering,
                )?
            }
            Target::At(target) => {
                let point = target.resolve(&resolve)?;
                let request = match self.requested {
                    [Some(w), Some(h)] => Some(RootRequest::size(w, h)),
                    [Some(w), None] => Some(RootRequest::width(w)),
                    [None, Some(h)] => Some(RootRequest::height(h)),
                    [None, None] => None,
                };
                let source = self
                    .source
                    .prepare(if fixed { None } else { request }, parent_theme)?;
                PlacedContent::at(
                    source,
                    point,
                    if fixed { self.requested } else { [None, None] },
                    self.anchor.unwrap_or_default(),
                    rendering,
                )?
            }
        };
        placed.prepare()?;
        Ok(placed)
    }
}