lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Immutable guide chrome and exact local relationships.

use std::cmp::Ordering;

use crate::layout::{
    kernel::{FeedbackRound, SpatialRounding},
    GridGap, Insets, Length, ResolvedInsets,
};
use crate::{Error, Result};

use super::{component::validated_component, spacing::ExactLength};
use super::{Color, LocalMetric, OutlineTheme, RelativeSpacing};

fn positive(value: &RelativeSpacing, field: &str) -> Result<()> {
    if value.is_zero() {
        Err(Error::Data(
            format!("guide {field} must be positive").into(),
        ))
    } else {
        Ok(())
    }
}

validated_component!(LegendSpacing {
    borrow padding: Insets => get_padding,
    borrow key_width: RelativeSpacing => get_key_width,
    borrow key_label_gap: RelativeSpacing => get_key_label_gap,
    borrow outside_gap: RelativeSpacing => get_outside_gap,
    borrow shared_gap: RelativeSpacing => get_shared_gap,
    borrow entry_gap: GridGap => get_entry_gap,
    borrow title_gap: RelativeSpacing => get_title_gap,
    borrow glyph_edge_padding: RelativeSpacing => get_glyph_edge_padding,
    borrow inside_inset: Insets => get_inside_inset,
    borrow outside_inset: Insets => get_outside_inset,
} validate |value| {
    positive(value.get_key_width(), "key width")?;
    value.get_padding().validate_em_px()?;
    value.get_entry_gap().validate_em_px()?;
    value.get_outside_inset().validate_em_px()?;
});
impl Eq for LegendSpacing {}

impl LegendSpacing {
    fn observe_feedback(&self, round: &mut FeedbackRound) -> Result<()> {
        for value in [
            &self.key_width,
            &self.key_label_gap,
            &self.outside_gap,
            &self.shared_gap,
            &self.title_gap,
            &self.glyph_edge_padding,
        ] {
            value.observe_feedback(round)?;
        }
        for value in [&self.padding, &self.inside_inset, &self.outside_inset] {
            value.observe_feedback(round)?;
        }
        self.entry_gap.get_row().observe_feedback(round)?;
        self.entry_gap.get_column().observe_feedback(round)
    }
}

#[derive(Debug, Clone)]
pub(crate) struct LegendLengths {
    pub(crate) padding: ResolvedInsets,
    pub(crate) key_width: ExactLength,
    pub(crate) key_label_gap: ExactLength,
    pub(crate) outside_gap: ExactLength,
    pub(crate) shared_gap: ExactLength,
    pub(crate) row_gap: ExactLength,
    pub(crate) column_gap: ExactLength,
    pub(crate) title_gap: ExactLength,
    pub(crate) glyph_edge_padding: ExactLength,
    pub(crate) outside_inset: ResolvedInsets,
    pub(crate) minimum: ExactLength,
    pub(crate) preferred: ExactLength,
    pub(crate) radius: Option<ExactLength>,
}

impl LegendTheme {
    pub(crate) fn lengths(&self, label_size: f64, title_size: f64) -> Result<LegendLengths> {
        let em = LocalMetric::css_pixels(label_size)?;
        let title = LocalMetric::css_pixels(title_size)?;
        let spacing = self.get_spacing();
        Ok(LegendLengths {
            padding: spacing.get_padding().resolve(em, None)?,
            key_width: spacing.get_key_width().product(em),
            key_label_gap: spacing.get_key_label_gap().product(em),
            outside_gap: spacing.get_outside_gap().product(em),
            shared_gap: spacing.get_shared_gap().product(em),
            row_gap: spacing.get_entry_gap().get_row().resolve(em, None)?,
            column_gap: spacing.get_entry_gap().get_column().resolve(em, None)?,
            title_gap: spacing.get_title_gap().product(title),
            glyph_edge_padding: spacing.get_glyph_edge_padding().product(em),
            outside_inset: spacing.get_outside_inset().resolve(em, None)?,
            minimum: self.get_gradient_lengths().get_minimum().product(em),
            preferred: self.get_gradient_lengths().get_preferred().product(em),
            radius: self.get_frame().map(|frame| frame.get_radius().product(em)),
        })
    }
}

/// Positive minimum and at-least-minimum preferred continuous-guide lengths.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GradientLengths {
    minimum: RelativeSpacing,
    preferred: RelativeSpacing,
}

impl GradientLengths {
    /// Construct positive lengths with preferred at least minimum under exact comparison.
    pub fn new(minimum: RelativeSpacing, preferred: RelativeSpacing) -> Result<Self> {
        let value = Self { minimum, preferred };
        value.validate_in()?;
        Ok(value)
    }
    fn validate_in(&self) -> Result<()> {
        positive(self.get_minimum(), "gradient minimum")?;
        positive(self.get_preferred(), "gradient preference")?;
        if self.get_minimum().compare(self.get_preferred()) == Ordering::Greater {
            return Err(Error::Data(
                "guide gradient preference must be at least its minimum".into(),
            ));
        }
        Ok(())
    }
    /// Borrow the exact minimum relationship.
    pub fn get_minimum(&self) -> &RelativeSpacing {
        &self.minimum
    }
    /// Borrow the exact preferred relationship.
    pub fn get_preferred(&self) -> &RelativeSpacing {
        &self.preferred
    }
    /// Replace minimum, preserving the positive ordered length invariant.
    pub fn minimum(self, minimum: RelativeSpacing) -> Result<Self> {
        Self::new(minimum, self.preferred)
    }
    /// Replace preference, preserving the positive ordered length invariant.
    pub fn preferred(self, preferred: RelativeSpacing) -> Result<Self> {
        Self::new(self.minimum, preferred)
    }
}

/// Complete guide-container paint, optional independent outline and local corner radius.
#[derive(Clone, Debug, PartialEq)]
pub struct LegendFrameTheme {
    fill: Color,
    outline: Option<OutlineTheme>,
    radius: RelativeSpacing,
}

impl LegendFrameTheme {
    /// Construct a complete container with a nonnegative local corner radius.
    pub fn new(
        fill: Color,
        outline: Option<OutlineTheme>,
        radius: RelativeSpacing,
    ) -> Result<Self> {
        let value = Self {
            fill,
            outline,
            radius,
        };
        value.validate()?;
        Ok(value)
    }
    fn validate(&self) -> Result<()> {
        if let Some(outline) = self.get_outline() {
            outline.validate()?;
        }
        Ok(())
    }
    /// Inspect the complete container fill.
    pub fn get_fill(&self) -> Color {
        self.fill
    }
    /// Borrow the optional independent outline.
    pub fn get_outline(&self) -> Option<&OutlineTheme> {
        self.outline.as_ref()
    }
    /// Borrow the nonnegative legend-label-em corner-radius relationship.
    pub fn get_radius(&self) -> &RelativeSpacing {
        &self.radius
    }
    /// Replace only the container fill.
    pub fn fill(self, fill: Color) -> Result<Self> {
        Self::new(fill, self.outline, self.radius)
    }
    /// Replace only the optional independent outline.
    pub fn outline(self, outline: Option<OutlineTheme>) -> Result<Self> {
        Self::new(self.fill, outline, self.radius)
    }
    /// Replace only the nonnegative local corner-radius relationship.
    pub fn radius(self, radius: RelativeSpacing) -> Result<Self> {
        Self::new(self.fill, self.outline, radius)
    }
}

/// Complete measured guide chrome, independent of guide content or placement policy.
#[derive(Clone, Debug, PartialEq)]
pub struct LegendTheme {
    spacing: LegendSpacing,
    gradient_lengths: GradientLengths,
    frame: Option<LegendFrameTheme>,
}

impl LegendTheme {
    pub(crate) fn builtin() -> Result<Self> {
        let spacing = LegendSpacing::new(
            Insets::all(Length::Em(RelativeSpacing::from_pixels(8.8, 11)?)),
            RelativeSpacing::ratio(1, 1)?,
            RelativeSpacing::from_pixels(8.8, 11)?,
            RelativeSpacing::from_pixels(8.8, 11)?,
            RelativeSpacing::from_pixels(17.6, 11)?,
            GridGap::zero()
                .row(Length::Em(RelativeSpacing::from_pixels(3.3, 11)?))
                .column(Length::Em(RelativeSpacing::from_pixels(13.2, 11)?)),
            RelativeSpacing::from_pixels(7.8, 12)?,
            RelativeSpacing::new(0.2)?,
            Insets::all(Length::short_side(0.04)?),
            Insets::zero(),
        )?;
        let lengths = GradientLengths::new(
            RelativeSpacing::ratio(40, 11)?,
            RelativeSpacing::ratio(160, 11)?,
        )?;
        Self::new(spacing, lengths, None)
    }
    /// Construct complete spacing, continuous lengths and an optional container frame.
    pub fn new(
        spacing: LegendSpacing,
        gradient_lengths: GradientLengths,
        frame: Option<LegendFrameTheme>,
    ) -> Result<Self> {
        let value = Self {
            spacing,
            gradient_lengths,
            frame,
        };
        value.validate_in()?;
        Ok(value)
    }
    pub(crate) fn validate_in(&self) -> Result<()> {
        self.get_spacing().validate()?;
        self.get_gradient_lengths().validate_in()?;
        if let Some(frame) = self.get_frame() {
            frame.validate()?;
        }
        Ok(())
    }
    /// Borrow all complete exact guide relationships.
    pub fn get_spacing(&self) -> &LegendSpacing {
        &self.spacing
    }
    /// Borrow the continuous-guide minimum and preference.
    pub fn get_gradient_lengths(&self) -> &GradientLengths {
        &self.gradient_lengths
    }
    /// Borrow the optional guide-container appearance.
    pub fn get_frame(&self) -> Option<&LegendFrameTheme> {
        self.frame.as_ref()
    }
    /// Borrow the Canvas-owned shared-guide gap relationship.
    pub fn get_shared_gap(&self) -> &RelativeSpacing {
        self.get_spacing().get_shared_gap()
    }
    /// Replace the complete guide-spacing value.
    pub fn spacing(self, spacing: LegendSpacing) -> Result<Self> {
        Self::new(spacing, self.gradient_lengths, self.frame)
    }
    /// Replace the complete continuous-guide length value.
    pub fn gradient_lengths(self, value: GradientLengths) -> Result<Self> {
        Self::new(self.spacing, value, self.frame)
    }
    /// Replace only the optional guide-container appearance.
    pub fn frame(self, frame: Option<LegendFrameTheme>) -> Result<Self> {
        Self::new(self.spacing, self.gradient_lengths, frame)
    }
    /// Replace only the Canvas-owned shared-guide gap relationship.
    pub fn shared_gap(self, value: RelativeSpacing) -> Result<Self> {
        let spacing = self.spacing.shared_gap(value)?;
        Self::new(spacing, self.gradient_lengths, self.frame)
    }

    pub(crate) fn same(&self, other: &Self) -> bool {
        self == other
    }
    pub(crate) fn observe_feedback(&self, round: &mut FeedbackRound) -> Result<()> {
        round.observe_count(usize::from(self.get_frame().is_some()))?;
        self.get_spacing().observe_feedback(round)?;
        self.get_gradient_lengths()
            .get_minimum()
            .observe_feedback(round)?;
        self.get_gradient_lengths()
            .get_preferred()
            .observe_feedback(round)?;
        if let Some(frame) = self.get_frame() {
            for color in [
                Some(frame.get_fill()),
                frame.get_outline().map(OutlineTheme::get_color),
            ]
            .into_iter()
            .flatten()
            {
                for byte in [color.red(), color.green(), color.blue()] {
                    round.observe_count(usize::from(byte))?;
                }
                round.observe_number(color.get_alpha())?;
            }
            round.observe_count(usize::from(frame.get_outline().is_some()))?;
            if let Some(outline) = frame.get_outline() {
                round.observe_number(f64::from(outline.get_width()))?;
            }
            frame.get_radius().observe_feedback(round)?;
        }
        Ok(())
    }
    pub(crate) fn outside_gap_pixels(&self, label_size: f64) -> Result<f64> {
        self.get_spacing()
            .get_outside_gap()
            .product(LocalMetric::css_pixels(label_size)?)
            .pixels_rounded(SpatialRounding::NearestEven)
    }
    pub(crate) fn shared_gap_pixels(&self, label_size: f64) -> Result<f64> {
        self.get_shared_gap()
            .product(LocalMetric::css_pixels(label_size)?)
            .pixels_rounded(SpatialRounding::NearestEven)
    }
}