lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Authored, exact lengths and directional layout relationships.

use crate::{
    theme::spacing::{ExactLength, LocalMetric},
    Error, Result,
};

use super::{kernel::SpatialRounding, PixelRect, RelativeSpacing};

/// Unit of an authored layout length.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LengthUnit {
    /// Multiple of the consuming text role's em.
    Em,
    /// Absolute CSS pixels.
    Px,
    /// Fraction of the local placement rectangle's short side.
    ShortSide,
}

/// A finite nonnegative length whose resolution base is part of its identity.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Length {
    /// Font-relative length.
    Em(RelativeSpacing),
    /// Absolute CSS pixel length.
    Px(RelativeSpacing),
    /// Fraction of the local placement rectangle's short side.
    ShortSide(RelativeSpacing),
}

impl Length {
    /// Retain a font-relative value or exact relative ratio.
    pub fn em<V: TryInto<RelativeSpacing>>(value: V) -> Result<Self>
    where
        V::Error: Into<Error>,
    {
        Ok(Self::Em(value.try_into().map_err(Into::into)?))
    }

    /// Retain an absolute CSS pixel value.
    pub fn px<V: TryInto<RelativeSpacing>>(value: V) -> Result<Self>
    where
        V::Error: Into<Error>,
    {
        Ok(Self::Px(value.try_into().map_err(Into::into)?))
    }

    /// Retain a fraction of the local placement rectangle's short side.
    pub fn short_side<V: TryInto<RelativeSpacing>>(value: V) -> Result<Self>
    where
        V::Error: Into<Error>,
    {
        Ok(Self::ShortSide(value.try_into().map_err(Into::into)?))
    }

    /// Original resolution unit.
    pub fn unit(&self) -> LengthUnit {
        match self {
            Self::Em(_) => LengthUnit::Em,
            Self::Px(_) => LengthUnit::Px,
            Self::ShortSide(_) => LengthUnit::ShortSide,
        }
    }

    /// Exact original coefficient, independent of its resolution unit.
    pub fn value(&self) -> &RelativeSpacing {
        match self {
            Self::Em(value) | Self::Px(value) | Self::ShortSide(value) => value,
        }
    }

    fn zero() -> Self {
        Self::Em(RelativeSpacing::ratio(0, 1).expect("zero spacing"))
    }

    pub(crate) fn observe_feedback(&self, round: &mut super::kernel::FeedbackRound) -> Result<()> {
        round.observe_count(self.unit() as usize)?;
        self.value().observe_feedback(round)
    }

    pub(crate) fn validate_em_px(&self) -> Result<()> {
        if self.unit() == LengthUnit::ShortSide {
            Err(Error::Data(
                "short-side lengths require local placement geometry".into(),
            ))
        } else {
            Ok(())
        }
    }

    pub(crate) fn resolve(
        &self,
        em: LocalMetric,
        short_side: Option<LocalMetric>,
    ) -> Result<ExactLength> {
        let metric = match self {
            Self::Em(_) => em,
            Self::Px(_) => LocalMetric::css_pixels(1.0)?,
            Self::ShortSide(_) => short_side.ok_or_else(|| {
                Error::Data("short-side lengths require local placement geometry".into())
            })?,
        };
        Ok(self.value().product(metric))
    }
}

impl TryFrom<f64> for RelativeSpacing {
    type Error = Error;

    fn try_from(value: f64) -> Result<Self> {
        Self::new(value)
    }
}

/// The four physical edges of a rectangular content region.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Insets {
    left: Length,
    right: Length,
    bottom: Length,
    top: Length,
}

macro_rules! sides {
    ($($field:ident => $get:ident),+ $(,)?) => {$(
        #[doc=concat!("Borrow the original ",stringify!($field)," length.")]
        pub fn $get(&self) -> &Length { &self.$field }
        #[doc=concat!("Replace the ",stringify!($field)," length.")]
        #[must_use]
        pub fn $field(mut self,value:Length) -> Self { self.$field=value; self }
    )+};
}

impl Insets {
    /// Zero extent on every physical edge.
    pub fn zero() -> Self {
        Self::all(Length::zero())
    }

    /// The same authored length on all four edges.
    pub fn all(value: Length) -> Self {
        Self::symmetric(value.clone(), value)
    }

    /// Equal left/right and equal top/bottom extents, separately.
    pub fn symmetric(horizontal: Length, vertical: Length) -> Self {
        Self {
            left: horizontal.clone(),
            right: horizontal,
            bottom: vertical.clone(),
            top: vertical,
        }
    }

    sides!(left=>get_left, right=>get_right, bottom=>get_bottom, top=>get_top);

    pub(crate) fn observe_feedback(&self, round: &mut super::kernel::FeedbackRound) -> Result<()> {
        for length in [&self.left, &self.right, &self.bottom, &self.top] {
            length.observe_feedback(round)?;
        }
        Ok(())
    }

    pub(crate) fn validate_em_px(&self) -> Result<()> {
        for length in [&self.left, &self.right, &self.bottom, &self.top] {
            length.validate_em_px()?;
        }
        Ok(())
    }

    pub(crate) fn resolve(
        &self,
        em: LocalMetric,
        short_side: Option<LocalMetric>,
    ) -> Result<ResolvedInsets> {
        Ok(ResolvedInsets {
            left: self.left.resolve(em, short_side)?,
            right: self.right.resolve(em, short_side)?,
            bottom: self.bottom.resolve(em, short_side)?,
            top: self.top.resolve(em, short_side)?,
        })
    }
}

/// The independent space between rows and between columns of a grid.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GridGap {
    row: Length,
    column: Length,
}

impl GridGap {
    /// No space between successive tracks.
    pub fn zero() -> Self {
        Self::all(Length::zero())
    }

    /// The same length between rows and columns.
    pub fn all(value: Length) -> Self {
        Self {
            row: value.clone(),
            column: value,
        }
    }

    sides!(row=>get_row,column=>get_column);

    pub(crate) fn validate_em_px(&self) -> Result<()> {
        self.row.validate_em_px()?;
        self.column.validate_em_px()
    }

    pub(crate) fn pixels(&self, em: LocalMetric) -> Result<GridGapPixels> {
        Ok(GridGapPixels {
            row: self
                .row
                .resolve(em, None)?
                .pixels_rounded(SpatialRounding::NearestEven)?,
            column: self
                .column
                .resolve(em, None)?
                .pixels_rounded(SpatialRounding::NearestEven)?,
        })
    }
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct GridGapPixels {
    pub(crate) row: f64,
    pub(crate) column: f64,
}

#[derive(Debug, Clone)]
pub(crate) struct ResolvedInsets {
    pub(crate) left: ExactLength,
    pub(crate) right: ExactLength,
    pub(crate) bottom: ExactLength,
    pub(crate) top: ExactLength,
}

impl ResolvedInsets {
    pub(crate) fn zero() -> Result<Self> {
        let zero = || ExactLength::quanta(super::kernel::LayoutScalar::from_quanta(0));
        Ok(Self {
            left: zero()?,
            right: zero()?,
            bottom: zero()?,
            top: zero()?,
        })
    }

    pub(crate) fn horizontal(&self) -> ExactLength {
        self.left.add_length(&self.right)
    }

    pub(crate) fn vertical(&self) -> ExactLength {
        self.bottom.add_length(&self.top)
    }

    pub(crate) fn width_with_content(&self, width: f64) -> Result<f64> {
        self.horizontal()
            .add_pixels(width)?
            .pixels_rounded(SpatialRounding::Ceil)
    }

    pub(crate) fn height_with_content(&self, height: f64) -> Result<f64> {
        self.vertical()
            .add_pixels(height)?
            .pixels_rounded(SpatialRounding::Ceil)
    }

    pub(crate) fn inset(&self, span: PixelRect) -> Result<PixelRect> {
        Ok(PixelRect::new(
            self.left.after_pixels(span.x0)?,
            self.right.before_pixels(span.x1)?,
            self.bottom.after_pixels(span.y0)?,
            self.top.before_pixels(span.y1)?,
        ))
    }
}