lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Complete annotation geometry, separate from text, content and placement policy.

use super::component::validated_component;
use super::spacing::ExactLength;
use super::{
    LocalMetric, OpaqueColor, OutlineTheme, RelativeSpacing, ResolvedTheme, SolidStrokeTheme,
    TextTheme,
};
use crate::layout::{kernel::SpatialRounding, Insets, Length, ResolvedInsets};
use crate::Result;

/// One selected significance appearance, including exact-override provenance.
pub(crate) struct EffectiveSignificance {
    pub(crate) label: TextTheme,
    pub(crate) exact_override: bool,
    pub(crate) gap: ExactLength,
    geometry: SignificanceGeometry,
}

impl ResolvedTheme {
    pub(crate) fn effective_significance(
        &self,
        exact: Option<crate::elements::SignificanceMarkStyle>,
    ) -> Result<EffectiveSignificance> {
        let mut label = self
            .typography
            .get_annotations()
            .get_significance_label()
            .try_copy()?;
        if let Some(exact) = exact {
            label = label
                .font_size(exact.get_font_size())?
                .weight(exact.get_weight())?;
        }
        let geometry = self.annotations.get_significance();
        let em = LocalMetric::css_pixels(label.get_font_size())?;
        Ok(EffectiveSignificance {
            gap: exact.map_or_else(
                || Ok(geometry.get_label_gap().product(em)),
                |exact| ExactLength::pixels(exact.get_gap()),
            )?,
            geometry: geometry.clone(),
            label,
            exact_override: exact.is_some(),
        })
    }
}

impl EffectiveSignificance {
    fn length(&self, spacing: &RelativeSpacing) -> Result<ExactLength> {
        Ok(spacing.product(LocalMetric::css_pixels(self.label.get_font_size())?))
    }

    pub(crate) fn tick_height(&self) -> Result<ExactLength> {
        self.length(self.geometry.get_tick_height())
    }

    pub(crate) fn data_gap(&self) -> Result<ExactLength> {
        self.length(self.geometry.get_data_gap())
    }

    pub(crate) fn level_step(&self) -> Result<ExactLength> {
        self.length(self.geometry.get_level_step())
    }

    pub(crate) fn panel_padding(&self) -> Result<ExactLength> {
        let selected = self.length(self.geometry.get_panel_padding())?;
        let ink =
            ExactLength::pixels(f64::from(self.geometry.get_bracket_stroke().get_width()) / 2.0)?
                .add_pixels(1.0 / 1024.0)?;
        Ok(if selected.compare(&ink).is_lt() {
            ink
        } else {
            selected
        })
    }

    pub(crate) fn gap_pixels(&self) -> Result<f64> {
        self.gap.pixels_rounded(SpatialRounding::NearestEven)
    }

    pub(crate) fn attached_reserve(&self, extent: f64) -> Result<f64> {
        self.gap
            .add_length(&self.length(self.geometry.get_attached_extra_clearance())?)
            .add_pixels(extent)?
            .pixels_rounded(SpatialRounding::Ceil)
    }

    pub(crate) fn bracket_style(
        &self,
        label: &crate::layout::ResolvedTextPlan,
    ) -> Result<crate::render::backend::BracketStyle> {
        Ok(crate::render::backend::BracketStyle {
            color: self.geometry.get_bracket_stroke().get_color(),
            width: self.geometry.get_bracket_stroke().get_width(),
            label_color: label.style.paint,
            font_family: label
                .copy_stack()
                .map_err(|error| crate::Error::Render(error.to_string().into()))?,
            font_size: label.style.font_size,
            line_height: label.line_height(),
            weight: label.style.weight,
            label_gap: self.gap_pixels()?,
            tick_height: self
                .tick_height()?
                .pixels_rounded(SpatialRounding::NearestEven)?,
        })
    }
}

validated_component!(SignificanceGeometry {
    borrow bracket_stroke: SolidStrokeTheme => get_bracket_stroke,
    borrow label_gap: RelativeSpacing => get_label_gap,
    borrow tick_height: RelativeSpacing => get_tick_height,
    borrow data_gap: RelativeSpacing => get_data_gap,
    borrow level_step: RelativeSpacing => get_level_step,
    borrow panel_padding: RelativeSpacing => get_panel_padding,
    borrow attached_extra_clearance: RelativeSpacing => get_attached_extra_clearance,
} validate |value| { value.get_bracket_stroke().validate()?; });

validated_component!(CellAnnotationGeometry {
    borrow highlight_outline: OutlineTheme => get_highlight_outline,
    borrow value_padding: Insets => get_value_padding,
    borrow null_row_padding: Insets => get_null_row_padding,
} validate |value| {
    value.get_highlight_outline().validate()?;
    value.get_value_padding().validate_em_px()?;
    value.get_null_row_padding().validate_em_px()?;
});

impl CellAnnotationGeometry {
    pub(crate) fn value_lengths(&self, em: f64) -> Result<ResolvedInsets> {
        self.get_value_padding()
            .resolve(LocalMetric::css_pixels(em)?, None)
    }
    pub(crate) fn null_row_lengths(&self, em: f64) -> Result<ResolvedInsets> {
        self.get_null_row_padding()
            .resolve(LocalMetric::css_pixels(em)?, None)
    }
}

validated_component!(EstimateAnnotationGeometry {
    borrow panel_inset: Insets => get_panel_inset,
    borrow guide_clearance: RelativeSpacing => get_guide_clearance,
    borrow numeric_label_gap: RelativeSpacing => get_numeric_label_gap,
} validate |value| {
    let inset = value.get_panel_inset();
    inset.validate_em_px()?;
    if !inset.get_top().value().is_zero() || !inset.get_bottom().value().is_zero() {
        return Err(crate::Error::Data("estimate panel inset accepts only left and right lengths".into()));
    }
});

pub(crate) struct EstimateAnnotationLengths {
    pub(crate) panel_inset: ResolvedInsets,
    pub(crate) guide_clearance: ExactLength,
}

impl EstimateAnnotationGeometry {
    pub(crate) fn lengths(&self, em: f64) -> Result<EstimateAnnotationLengths> {
        let em = LocalMetric::css_pixels(em)?;
        Ok(EstimateAnnotationLengths {
            panel_inset: self.get_panel_inset().resolve(em, None)?,
            guide_clearance: self.get_guide_clearance().product(em),
        })
    }
}

validated_component!(ValueShelfSpacing {
    borrow padding: Insets => get_padding,
    borrow gap: RelativeSpacing => get_gap,
    borrow row_gap: RelativeSpacing => get_row_gap,
} validate |value| { value.get_padding().validate_em_px()?; });

pub(crate) struct ValueShelfLengths {
    pub(crate) padding: ResolvedInsets,
    pub(crate) gap: ExactLength,
    pub(crate) row_gap: ExactLength,
}

impl ValueShelfSpacing {
    pub(crate) fn lengths(&self, em: f64) -> Result<ValueShelfLengths> {
        let em = LocalMetric::css_pixels(em)?;
        Ok(ValueShelfLengths {
            padding: self.get_padding().resolve(em, None)?,
            gap: self.get_gap().product(em),
            row_gap: self.get_row_gap().product(em),
        })
    }
}

validated_component!(AnnotationTheme {
    borrow significance: SignificanceGeometry => get_significance,
    borrow cells: CellAnnotationGeometry => get_cells,
    borrow estimates: EstimateAnnotationGeometry => get_estimates,
    borrow point_label_gap: RelativeSpacing => get_point_label_gap,
    borrow panel_text_padding: Insets => get_panel_text_padding,
    borrow waterfall_shelf: ValueShelfSpacing => get_waterfall_shelf,
    copy planning_backdrop: OpaqueColor => get_planning_backdrop,
} validate |value| {
    value.get_significance().validate()?;
    value.get_cells().validate()?;
    value.get_estimates().validate()?;
    value.get_waterfall_shelf().validate()?;
    value.get_panel_text_padding().validate_em_px()?;
});

impl AnnotationTheme {
    pub(crate) fn builtin(foreground: super::Color, bracket_width: f32) -> Result<Self> {
        let ratio = RelativeSpacing::ratio;
        Self::new(
            SignificanceGeometry::new(
                SolidStrokeTheme::new(foreground, bracket_width)?,
                ratio(8, 16)?,
                ratio(7, 16)?,
                ratio(6, 16)?,
                ratio(26, 16)?,
                ratio(2, 16)?,
                ratio(2, 16)?,
            )?,
            CellAnnotationGeometry::new(
                OutlineTheme::new(foreground, 2.5)?,
                Insets::symmetric(Length::Em(ratio(3, 11)?), Length::Em(ratio(5, 22)?)),
                Insets::symmetric(Length::Em(ratio(6, 11)?), Length::Em(ratio(2, 11)?)),
            )?,
            EstimateAnnotationGeometry::new(
                Insets::zero()
                    .left(Length::Em(ratio(6, 14)?))
                    .right(Length::Em(ratio(6, 14)?)),
                ratio(6, 14)?,
                ratio(7, 14)?,
            )?,
            ratio(2, 10)?,
            Insets::all(Length::Em(ratio(8, 14)?)),
            ValueShelfSpacing::new(
                Insets::all(Length::Em(ratio(4, 14)?)),
                ratio(4, 14)?,
                ratio(4, 14)?,
            )?,
            OpaqueColor::rgb(255, 255, 255),
        )
    }

    pub(crate) fn point_label_gap_length(&self, em: f64) -> Result<ExactLength> {
        Ok(self
            .get_point_label_gap()
            .product(LocalMetric::css_pixels(em)?))
    }
}