Skip to main content

lichtung_plot/layout/
length.rs

1//! Authored, exact lengths and directional layout relationships.
2
3use crate::{
4    theme::spacing::{ExactLength, LocalMetric},
5    Error, Result,
6};
7
8use super::{kernel::SpatialRounding, PixelRect, RelativeSpacing};
9
10/// Unit of an authored layout length.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum LengthUnit {
13    /// Multiple of the consuming text role's em.
14    Em,
15    /// Absolute CSS pixels.
16    Px,
17    /// Fraction of the local placement rectangle's short side.
18    ShortSide,
19}
20
21/// A finite nonnegative length whose resolution base is part of its identity.
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum Length {
24    /// Font-relative length.
25    Em(RelativeSpacing),
26    /// Absolute CSS pixel length.
27    Px(RelativeSpacing),
28    /// Fraction of the local placement rectangle's short side.
29    ShortSide(RelativeSpacing),
30}
31
32impl Length {
33    /// Retain a font-relative value or exact relative ratio.
34    pub fn em<V: TryInto<RelativeSpacing>>(value: V) -> Result<Self>
35    where
36        V::Error: Into<Error>,
37    {
38        Ok(Self::Em(value.try_into().map_err(Into::into)?))
39    }
40
41    /// Retain an absolute CSS pixel value.
42    pub fn px<V: TryInto<RelativeSpacing>>(value: V) -> Result<Self>
43    where
44        V::Error: Into<Error>,
45    {
46        Ok(Self::Px(value.try_into().map_err(Into::into)?))
47    }
48
49    /// Retain a fraction of the local placement rectangle's short side.
50    pub fn short_side<V: TryInto<RelativeSpacing>>(value: V) -> Result<Self>
51    where
52        V::Error: Into<Error>,
53    {
54        Ok(Self::ShortSide(value.try_into().map_err(Into::into)?))
55    }
56
57    /// Original resolution unit.
58    pub fn unit(&self) -> LengthUnit {
59        match self {
60            Self::Em(_) => LengthUnit::Em,
61            Self::Px(_) => LengthUnit::Px,
62            Self::ShortSide(_) => LengthUnit::ShortSide,
63        }
64    }
65
66    /// Exact original coefficient, independent of its resolution unit.
67    pub fn value(&self) -> &RelativeSpacing {
68        match self {
69            Self::Em(value) | Self::Px(value) | Self::ShortSide(value) => value,
70        }
71    }
72
73    fn zero() -> Self {
74        Self::Em(RelativeSpacing::ratio(0, 1).expect("zero spacing"))
75    }
76
77    pub(crate) fn observe_feedback(&self, round: &mut super::kernel::FeedbackRound) -> Result<()> {
78        round.observe_count(self.unit() as usize)?;
79        self.value().observe_feedback(round)
80    }
81
82    pub(crate) fn validate_em_px(&self) -> Result<()> {
83        if self.unit() == LengthUnit::ShortSide {
84            Err(Error::Data(
85                "short-side lengths require local placement geometry".into(),
86            ))
87        } else {
88            Ok(())
89        }
90    }
91
92    pub(crate) fn resolve(
93        &self,
94        em: LocalMetric,
95        short_side: Option<LocalMetric>,
96    ) -> Result<ExactLength> {
97        let metric = match self {
98            Self::Em(_) => em,
99            Self::Px(_) => LocalMetric::css_pixels(1.0)?,
100            Self::ShortSide(_) => short_side.ok_or_else(|| {
101                Error::Data("short-side lengths require local placement geometry".into())
102            })?,
103        };
104        Ok(self.value().product(metric))
105    }
106}
107
108impl TryFrom<f64> for RelativeSpacing {
109    type Error = Error;
110
111    fn try_from(value: f64) -> Result<Self> {
112        Self::new(value)
113    }
114}
115
116/// The four physical edges of a rectangular content region.
117#[derive(Debug, Clone, PartialEq, Eq)]
118pub struct Insets {
119    left: Length,
120    right: Length,
121    bottom: Length,
122    top: Length,
123}
124
125macro_rules! sides {
126    ($($field:ident => $get:ident),+ $(,)?) => {$(
127        #[doc=concat!("Borrow the original ",stringify!($field)," length.")]
128        pub fn $get(&self) -> &Length { &self.$field }
129        #[doc=concat!("Replace the ",stringify!($field)," length.")]
130        #[must_use]
131        pub fn $field(mut self,value:Length) -> Self { self.$field=value; self }
132    )+};
133}
134
135impl Insets {
136    /// Zero extent on every physical edge.
137    pub fn zero() -> Self {
138        Self::all(Length::zero())
139    }
140
141    /// The same authored length on all four edges.
142    pub fn all(value: Length) -> Self {
143        Self::symmetric(value.clone(), value)
144    }
145
146    /// Equal left/right and equal top/bottom extents, separately.
147    pub fn symmetric(horizontal: Length, vertical: Length) -> Self {
148        Self {
149            left: horizontal.clone(),
150            right: horizontal,
151            bottom: vertical.clone(),
152            top: vertical,
153        }
154    }
155
156    sides!(left=>get_left, right=>get_right, bottom=>get_bottom, top=>get_top);
157
158    pub(crate) fn observe_feedback(&self, round: &mut super::kernel::FeedbackRound) -> Result<()> {
159        for length in [&self.left, &self.right, &self.bottom, &self.top] {
160            length.observe_feedback(round)?;
161        }
162        Ok(())
163    }
164
165    pub(crate) fn validate_em_px(&self) -> Result<()> {
166        for length in [&self.left, &self.right, &self.bottom, &self.top] {
167            length.validate_em_px()?;
168        }
169        Ok(())
170    }
171
172    pub(crate) fn resolve(
173        &self,
174        em: LocalMetric,
175        short_side: Option<LocalMetric>,
176    ) -> Result<ResolvedInsets> {
177        Ok(ResolvedInsets {
178            left: self.left.resolve(em, short_side)?,
179            right: self.right.resolve(em, short_side)?,
180            bottom: self.bottom.resolve(em, short_side)?,
181            top: self.top.resolve(em, short_side)?,
182        })
183    }
184}
185
186/// The independent space between rows and between columns of a grid.
187#[derive(Debug, Clone, PartialEq, Eq)]
188pub struct GridGap {
189    row: Length,
190    column: Length,
191}
192
193impl GridGap {
194    /// No space between successive tracks.
195    pub fn zero() -> Self {
196        Self::all(Length::zero())
197    }
198
199    /// The same length between rows and columns.
200    pub fn all(value: Length) -> Self {
201        Self {
202            row: value.clone(),
203            column: value,
204        }
205    }
206
207    sides!(row=>get_row,column=>get_column);
208
209    pub(crate) fn validate_em_px(&self) -> Result<()> {
210        self.row.validate_em_px()?;
211        self.column.validate_em_px()
212    }
213
214    pub(crate) fn pixels(&self, em: LocalMetric) -> Result<GridGapPixels> {
215        Ok(GridGapPixels {
216            row: self
217                .row
218                .resolve(em, None)?
219                .pixels_rounded(SpatialRounding::NearestEven)?,
220            column: self
221                .column
222                .resolve(em, None)?
223                .pixels_rounded(SpatialRounding::NearestEven)?,
224        })
225    }
226}
227
228#[derive(Debug, Clone, Copy)]
229pub(crate) struct GridGapPixels {
230    pub(crate) row: f64,
231    pub(crate) column: f64,
232}
233
234#[derive(Debug, Clone)]
235pub(crate) struct ResolvedInsets {
236    pub(crate) left: ExactLength,
237    pub(crate) right: ExactLength,
238    pub(crate) bottom: ExactLength,
239    pub(crate) top: ExactLength,
240}
241
242impl ResolvedInsets {
243    pub(crate) fn zero() -> Result<Self> {
244        let zero = || ExactLength::quanta(super::kernel::LayoutScalar::from_quanta(0));
245        Ok(Self {
246            left: zero()?,
247            right: zero()?,
248            bottom: zero()?,
249            top: zero()?,
250        })
251    }
252
253    pub(crate) fn horizontal(&self) -> ExactLength {
254        self.left.add_length(&self.right)
255    }
256
257    pub(crate) fn vertical(&self) -> ExactLength {
258        self.bottom.add_length(&self.top)
259    }
260
261    pub(crate) fn width_with_content(&self, width: f64) -> Result<f64> {
262        self.horizontal()
263            .add_pixels(width)?
264            .pixels_rounded(SpatialRounding::Ceil)
265    }
266
267    pub(crate) fn height_with_content(&self, height: f64) -> Result<f64> {
268        self.vertical()
269            .add_pixels(height)?
270            .pixels_rounded(SpatialRounding::Ceil)
271    }
272
273    pub(crate) fn inset(&self, span: PixelRect) -> Result<PixelRect> {
274        Ok(PixelRect::new(
275            self.left.after_pixels(span.x0)?,
276            self.right.before_pixels(span.x1)?,
277            self.bottom.after_pixels(span.y0)?,
278            self.top.before_pixels(span.y1)?,
279        ))
280    }
281}