lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
//! Placement coordinates in a frozen scene's CSS-pixel frame.

use super::{Insets, LengthUnit, Rect, RectRef};
use crate::coordinates::AxisRef;
use crate::{Error, Result};

/// A point of an object viewport, measured downwards from its top-left.
#[derive(Debug, Default, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum Anchor {
    /// Upper left corner.
    #[default]
    TopLeft,
    /// Center of the upper edge.
    Top,
    /// Upper right corner.
    TopRight,
    /// Center of the left edge.
    Left,
    /// Viewport center.
    Center,
    /// Center of the right edge.
    Right,
    /// Lower left corner.
    BottomLeft,
    /// Center of the lower edge.
    Bottom,
    /// Lower right corner.
    BottomRight,
    /// An actual local CSS-pixel point.
    Local(f64, f64),
}

impl Anchor {
    /// Anchor at a finite point in the object's original local coordinates.
    pub fn local(x: f64, y: f64) -> Result<Self> {
        finite_point((x, y))?;
        Ok(Self::Local(x, y))
    }

    pub(crate) fn point(self, rect: Rect) -> Result<(f64, f64)> {
        let fraction = match self {
            Self::TopLeft => (0., 0.),
            Self::Top => (0.5, 0.),
            Self::TopRight => (1., 0.),
            Self::Left => (0., 0.5),
            Self::Center => (0.5, 0.5),
            Self::Right => (1., 0.5),
            Self::BottomLeft => (0., 1.),
            Self::Bottom => (0.5, 1.),
            Self::BottomRight => (1., 1.),
            Self::Local(x, y) => return finite_point((rect.left() + x, rect.top() + y)),
        };
        finite_point((
            rect.left() + rect.width() * fraction.0,
            rect.top() + rect.height() * fraction.1,
        ))
    }
}

impl std::str::FromStr for Anchor {
    type Err = Error;
    fn from_str(value: &str) -> Result<Self> {
        match value {
            "top_left" => Ok(Self::TopLeft),
            "top" => Ok(Self::Top),
            "top_right" => Ok(Self::TopRight),
            "left" => Ok(Self::Left),
            "center" => Ok(Self::Center),
            "right" => Ok(Self::Right),
            "bottom_left" => Ok(Self::BottomLeft),
            "bottom" => Ok(Self::Bottom),
            "bottom_right" => Ok(Self::BottomRight),
            _ => Err(Error::Data(
                format!("unknown placement anchor {value:?}").into(),
            )),
        }
    }
}

fn finite_point(point: (f64, f64)) -> Result<(f64, f64)> {
    if point.0.is_finite() && point.1.is_finite() {
        Ok(point)
    } else {
        Err(Error::Data("placement coordinates must be finite".into()))
    }
}

/// One fractional coordinate of an actual layout rectangle.
#[derive(Debug, Clone, PartialEq)]
pub struct RectAxisPosition {
    pub(super) reference: RectRef,
    pub(super) axis: AxisRef,
    pub(super) fraction: f64,
}

impl RectAxisPosition {
    pub(super) fn new(reference: RectRef, axis: AxisRef, fraction: f64) -> Result<Self> {
        finite_point((fraction, 0.))?;
        Ok(Self {
            reference,
            axis,
            fraction,
        })
    }

    fn resolve(&self, rect: &impl Fn(&RectRef) -> Result<Rect>) -> Result<f64> {
        let bounds = rect(&self.reference)?;
        Ok(match self.axis {
            AxisRef::X => bounds.left() + bounds.width() * self.fraction,
            AxisRef::Y => bounds.top() + bounds.height() * self.fraction,
        })
    }
}

/// A CSS point or a point resolved from the actual frozen layout.
#[derive(Debug, Clone, PartialEq)]
pub struct PlacePoint {
    pub(super) target: PointTarget,
    pub(super) offset: (f64, f64),
}

#[derive(Debug, Clone, PartialEq)]
pub(super) enum PointTarget {
    Absolute((f64, f64)),
    On(RectRef, Anchor),
    Axes(RectAxisPosition, RectAxisPosition),
}

impl PlacePoint {
    /// Absolute CSS-pixel coordinates in the chain's original frame.
    pub fn xy(x: f64, y: f64) -> Result<Self> {
        Ok(Self {
            target: PointTarget::Absolute(finite_point((x, y))?),
            offset: (0., 0.),
        })
    }

    /// Anchor on an actual layout rectangle.
    pub fn on(reference: RectRef, anchor: Anchor) -> Self {
        Self {
            target: PointTarget::On(reference, anchor),
            offset: (0., 0.),
        }
    }

    /// Combine a horizontal coordinate and a vertical coordinate, possibly
    /// from different actual layout rectangles.
    pub fn axes(x: RectAxisPosition, y: RectAxisPosition) -> Result<Self> {
        if x.axis != AxisRef::X || y.axis != AxisRef::Y {
            return Err(Error::Data(
                "placement axes requires an x and a y coordinate in that order".into(),
            ));
        }
        Ok(Self {
            target: PointTarget::Axes(x, y),
            offset: (0., 0.),
        })
    }

    /// Add an explicit CSS-pixel displacement.
    pub fn offset(mut self, dx: f64, dy: f64) -> Result<Self> {
        self.offset = finite_point((self.offset.0 + dx, self.offset.1 + dy))?;
        Ok(self)
    }

    pub(crate) fn resolve(&self, rect: &impl Fn(&RectRef) -> Result<Rect>) -> Result<(f64, f64)> {
        let point = match &self.target {
            PointTarget::Absolute(point) => *point,
            PointTarget::On(reference, anchor) => anchor.point(rect(reference)?)?,
            PointTarget::Axes(x, y) => (x.resolve(rect)?, y.resolve(rect)?),
        };
        finite_point((point.0 + self.offset.0, point.1 + self.offset.1))
    }
}

impl TryFrom<(f64, f64)> for PlacePoint {
    type Error = Error;
    fn try_from((x, y): (f64, f64)) -> Result<Self> {
        Self::xy(x, y)
    }
}

/// A placement frame specified directly or by real layout geometry.
#[derive(Debug, Clone, PartialEq)]
#[must_use]
pub struct BoxTarget {
    pub(super) target: RectTarget,
    pub(super) inset: Insets,
}

#[derive(Debug, Clone, PartialEq)]
pub(super) enum RectTarget {
    Absolute(Rect),
    Reference(RectRef),
    Corners(Box<(PlacePoint, PlacePoint)>),
}

impl BoxTarget {
    /// The positive rectangle between two actual points.
    pub fn corners(top_left: PlacePoint, bottom_right: PlacePoint) -> Self {
        Self {
            target: RectTarget::Corners(Box::new((top_left, bottom_right))),
            inset: Insets::zero(),
        }
    }

    /// Inset the actual target by four absolute CSS-pixel lengths.
    pub fn inset(mut self, insets: Insets) -> Self {
        self.inset = insets;
        self
    }

    pub(crate) fn resolve(&self, rect: &impl Fn(&RectRef) -> Result<Rect>) -> Result<Rect> {
        let bounds = match &self.target {
            RectTarget::Absolute(rect) => *rect,
            RectTarget::Reference(reference) => rect(reference)?,
            RectTarget::Corners(points) => {
                let (first, second) = points.as_ref();
                let (left, top) = first.resolve(rect)?;
                let (right, bottom) = second.resolve(rect)?;
                Rect::new(left, top, right - left, bottom - top)?
            }
        };
        let px = |length: &super::Length| {
            let value = length.value().as_f64();
            if length.unit() == LengthUnit::Px || value == 0. {
                Ok(value)
            } else {
                Err(Error::Data(
                    "placement box insets require CSS-pixel lengths".into(),
                ))
            }
        };
        let left = px(self.inset.get_left())?;
        let top = px(self.inset.get_top())?;
        let right = px(self.inset.get_right())?;
        let bottom = px(self.inset.get_bottom())?;
        let result = Rect::new(
            bounds.left() + left,
            bounds.top() + top,
            bounds.width() - left - right,
            bounds.height() - top - bottom,
        )?;
        if result.width() == 0. || result.height() == 0. {
            return Err(Error::Data(
                "placement box must have positive width and height".into(),
            ));
        }
        Ok(result)
    }

    pub(crate) fn reservation_anchor(&self) -> Option<(usize, usize)> {
        match &self.target {
            RectTarget::Reference(reference) => reference.reservation_anchor(),
            _ => None,
        }
    }
}

impl From<Rect> for BoxTarget {
    fn from(rect: Rect) -> Self {
        Self {
            target: RectTarget::Absolute(rect),
            inset: Insets::zero(),
        }
    }
}
impl From<RectRef> for BoxTarget {
    fn from(reference: RectRef) -> Self {
        Self {
            target: RectTarget::Reference(reference),
            inset: Insets::zero(),
        }
    }
}
impl TryFrom<(f64, f64, f64, f64)> for BoxTarget {
    type Error = Error;
    fn try_from((left, top, width, height): (f64, f64, f64, f64)) -> Result<Self> {
        Ok(Rect::new(left, top, width, height)?.into())
    }
}