Skip to main content

lichtung_plot/layout/
place.rs

1//! Placement coordinates in a frozen scene's CSS-pixel frame.
2
3use super::{Insets, LengthUnit, Rect, RectRef};
4use crate::coordinates::AxisRef;
5use crate::{Error, Result};
6
7/// A point of an object viewport, measured downwards from its top-left.
8#[derive(Debug, Default, Clone, Copy, PartialEq)]
9#[non_exhaustive]
10pub enum Anchor {
11    /// Upper left corner.
12    #[default]
13    TopLeft,
14    /// Center of the upper edge.
15    Top,
16    /// Upper right corner.
17    TopRight,
18    /// Center of the left edge.
19    Left,
20    /// Viewport center.
21    Center,
22    /// Center of the right edge.
23    Right,
24    /// Lower left corner.
25    BottomLeft,
26    /// Center of the lower edge.
27    Bottom,
28    /// Lower right corner.
29    BottomRight,
30    /// An actual local CSS-pixel point.
31    Local(f64, f64),
32}
33
34impl Anchor {
35    /// Anchor at a finite point in the object's original local coordinates.
36    pub fn local(x: f64, y: f64) -> Result<Self> {
37        finite_point((x, y))?;
38        Ok(Self::Local(x, y))
39    }
40
41    pub(crate) fn point(self, rect: Rect) -> Result<(f64, f64)> {
42        let fraction = match self {
43            Self::TopLeft => (0., 0.),
44            Self::Top => (0.5, 0.),
45            Self::TopRight => (1., 0.),
46            Self::Left => (0., 0.5),
47            Self::Center => (0.5, 0.5),
48            Self::Right => (1., 0.5),
49            Self::BottomLeft => (0., 1.),
50            Self::Bottom => (0.5, 1.),
51            Self::BottomRight => (1., 1.),
52            Self::Local(x, y) => return finite_point((rect.left() + x, rect.top() + y)),
53        };
54        finite_point((
55            rect.left() + rect.width() * fraction.0,
56            rect.top() + rect.height() * fraction.1,
57        ))
58    }
59}
60
61impl std::str::FromStr for Anchor {
62    type Err = Error;
63    fn from_str(value: &str) -> Result<Self> {
64        match value {
65            "top_left" => Ok(Self::TopLeft),
66            "top" => Ok(Self::Top),
67            "top_right" => Ok(Self::TopRight),
68            "left" => Ok(Self::Left),
69            "center" => Ok(Self::Center),
70            "right" => Ok(Self::Right),
71            "bottom_left" => Ok(Self::BottomLeft),
72            "bottom" => Ok(Self::Bottom),
73            "bottom_right" => Ok(Self::BottomRight),
74            _ => Err(Error::Data(
75                format!("unknown placement anchor {value:?}").into(),
76            )),
77        }
78    }
79}
80
81fn finite_point(point: (f64, f64)) -> Result<(f64, f64)> {
82    if point.0.is_finite() && point.1.is_finite() {
83        Ok(point)
84    } else {
85        Err(Error::Data("placement coordinates must be finite".into()))
86    }
87}
88
89/// One fractional coordinate of an actual layout rectangle.
90#[derive(Debug, Clone, PartialEq)]
91pub struct RectAxisPosition {
92    pub(super) reference: RectRef,
93    pub(super) axis: AxisRef,
94    pub(super) fraction: f64,
95}
96
97impl RectAxisPosition {
98    pub(super) fn new(reference: RectRef, axis: AxisRef, fraction: f64) -> Result<Self> {
99        finite_point((fraction, 0.))?;
100        Ok(Self {
101            reference,
102            axis,
103            fraction,
104        })
105    }
106
107    fn resolve(&self, rect: &impl Fn(&RectRef) -> Result<Rect>) -> Result<f64> {
108        let bounds = rect(&self.reference)?;
109        Ok(match self.axis {
110            AxisRef::X => bounds.left() + bounds.width() * self.fraction,
111            AxisRef::Y => bounds.top() + bounds.height() * self.fraction,
112        })
113    }
114}
115
116/// A CSS point or a point resolved from the actual frozen layout.
117#[derive(Debug, Clone, PartialEq)]
118pub struct PlacePoint {
119    pub(super) target: PointTarget,
120    pub(super) offset: (f64, f64),
121}
122
123#[derive(Debug, Clone, PartialEq)]
124pub(super) enum PointTarget {
125    Absolute((f64, f64)),
126    On(RectRef, Anchor),
127    Axes(RectAxisPosition, RectAxisPosition),
128}
129
130impl PlacePoint {
131    /// Absolute CSS-pixel coordinates in the chain's original frame.
132    pub fn xy(x: f64, y: f64) -> Result<Self> {
133        Ok(Self {
134            target: PointTarget::Absolute(finite_point((x, y))?),
135            offset: (0., 0.),
136        })
137    }
138
139    /// Anchor on an actual layout rectangle.
140    pub fn on(reference: RectRef, anchor: Anchor) -> Self {
141        Self {
142            target: PointTarget::On(reference, anchor),
143            offset: (0., 0.),
144        }
145    }
146
147    /// Combine a horizontal coordinate and a vertical coordinate, possibly
148    /// from different actual layout rectangles.
149    pub fn axes(x: RectAxisPosition, y: RectAxisPosition) -> Result<Self> {
150        if x.axis != AxisRef::X || y.axis != AxisRef::Y {
151            return Err(Error::Data(
152                "placement axes requires an x and a y coordinate in that order".into(),
153            ));
154        }
155        Ok(Self {
156            target: PointTarget::Axes(x, y),
157            offset: (0., 0.),
158        })
159    }
160
161    /// Add an explicit CSS-pixel displacement.
162    pub fn offset(mut self, dx: f64, dy: f64) -> Result<Self> {
163        self.offset = finite_point((self.offset.0 + dx, self.offset.1 + dy))?;
164        Ok(self)
165    }
166
167    pub(crate) fn resolve(&self, rect: &impl Fn(&RectRef) -> Result<Rect>) -> Result<(f64, f64)> {
168        let point = match &self.target {
169            PointTarget::Absolute(point) => *point,
170            PointTarget::On(reference, anchor) => anchor.point(rect(reference)?)?,
171            PointTarget::Axes(x, y) => (x.resolve(rect)?, y.resolve(rect)?),
172        };
173        finite_point((point.0 + self.offset.0, point.1 + self.offset.1))
174    }
175}
176
177impl TryFrom<(f64, f64)> for PlacePoint {
178    type Error = Error;
179    fn try_from((x, y): (f64, f64)) -> Result<Self> {
180        Self::xy(x, y)
181    }
182}
183
184/// A placement frame specified directly or by real layout geometry.
185#[derive(Debug, Clone, PartialEq)]
186#[must_use]
187pub struct BoxTarget {
188    pub(super) target: RectTarget,
189    pub(super) inset: Insets,
190}
191
192#[derive(Debug, Clone, PartialEq)]
193pub(super) enum RectTarget {
194    Absolute(Rect),
195    Reference(RectRef),
196    Corners(Box<(PlacePoint, PlacePoint)>),
197}
198
199impl BoxTarget {
200    /// The positive rectangle between two actual points.
201    pub fn corners(top_left: PlacePoint, bottom_right: PlacePoint) -> Self {
202        Self {
203            target: RectTarget::Corners(Box::new((top_left, bottom_right))),
204            inset: Insets::zero(),
205        }
206    }
207
208    /// Inset the actual target by four absolute CSS-pixel lengths.
209    pub fn inset(mut self, insets: Insets) -> Self {
210        self.inset = insets;
211        self
212    }
213
214    pub(crate) fn resolve(&self, rect: &impl Fn(&RectRef) -> Result<Rect>) -> Result<Rect> {
215        let bounds = match &self.target {
216            RectTarget::Absolute(rect) => *rect,
217            RectTarget::Reference(reference) => rect(reference)?,
218            RectTarget::Corners(points) => {
219                let (first, second) = points.as_ref();
220                let (left, top) = first.resolve(rect)?;
221                let (right, bottom) = second.resolve(rect)?;
222                Rect::new(left, top, right - left, bottom - top)?
223            }
224        };
225        let px = |length: &super::Length| {
226            let value = length.value().as_f64();
227            if length.unit() == LengthUnit::Px || value == 0. {
228                Ok(value)
229            } else {
230                Err(Error::Data(
231                    "placement box insets require CSS-pixel lengths".into(),
232                ))
233            }
234        };
235        let left = px(self.inset.get_left())?;
236        let top = px(self.inset.get_top())?;
237        let right = px(self.inset.get_right())?;
238        let bottom = px(self.inset.get_bottom())?;
239        let result = Rect::new(
240            bounds.left() + left,
241            bounds.top() + top,
242            bounds.width() - left - right,
243            bounds.height() - top - bottom,
244        )?;
245        if result.width() == 0. || result.height() == 0. {
246            return Err(Error::Data(
247                "placement box must have positive width and height".into(),
248            ));
249        }
250        Ok(result)
251    }
252
253    pub(crate) fn reservation_anchor(&self) -> Option<(usize, usize)> {
254        match &self.target {
255            RectTarget::Reference(reference) => reference.reservation_anchor(),
256            _ => None,
257        }
258    }
259}
260
261impl From<Rect> for BoxTarget {
262    fn from(rect: Rect) -> Self {
263        Self {
264            target: RectTarget::Absolute(rect),
265            inset: Insets::zero(),
266        }
267    }
268}
269impl From<RectRef> for BoxTarget {
270    fn from(reference: RectRef) -> Self {
271        Self {
272            target: RectTarget::Reference(reference),
273            inset: Insets::zero(),
274        }
275    }
276}
277impl TryFrom<(f64, f64, f64, f64)> for BoxTarget {
278    type Error = Error;
279    fn try_from((left, top, width, height): (f64, f64, f64, f64)) -> Result<Self> {
280        Ok(Rect::new(left, top, width, height)?.into())
281    }
282}