Skip to main content

lichtung_plot/theme/
guide.rs

1//! Immutable guide chrome and exact local relationships.
2
3use std::cmp::Ordering;
4
5use crate::layout::kernel::{FeedbackRound, SpatialRounding};
6use crate::{Error, Result};
7
8use super::spacing::ExactLength;
9use super::{Color, LocalMetric, OutlineTheme, RelativeSpacing};
10
11fn positive(value: &RelativeSpacing, field: &str) -> Result<()> {
12    if value.is_zero() {
13        Err(Error::Data(format!("guide {field} must be positive")))
14    } else {
15        Ok(())
16    }
17}
18
19macro_rules! legend_spacing {
20    ($($field:ident => $get:ident: $metric:literal),+ $(,)?) => {
21        #[derive(Clone, Debug, PartialEq, Eq)]
22        /// Complete independent exact guide relationships, resolved against selected guide text em.
23        pub struct LegendSpacing { $($field: RelativeSpacing),+ }
24        impl LegendSpacing {
25            #[expect(clippy::too_many_arguments, reason = "the authoritative complete spacing constructor names all nine independent relationships")]
26            /// Construct complete nonnegative relationships with a strictly positive key width.
27            pub fn new($($field: RelativeSpacing),+) -> Result<Self> {
28                let value = Self { $($field),+ }; value.validate()?; Ok(value)
29            }
30            fn validate(&self) -> Result<()> { positive(self.get_key_width(), "key width") }
31            $(
32                #[doc = concat!("Borrow the exact `", stringify!($field), "` relationship.")]
33                pub fn $get(&self) -> &RelativeSpacing { &self.$field }
34                #[doc = concat!("Replace only `", stringify!($field), "`, validating the complete spacing value.")]
35                pub fn $field(mut self, value: RelativeSpacing) -> Result<Self> { self.$field = value; self.validate()?; Ok(self) }
36            )+
37            fn relationships(&self) -> [&RelativeSpacing; 9] { [$(&self.$field),+] }
38        }
39        #[derive(Debug, Clone)]
40        pub(crate) struct LegendLengths { $(pub(crate) $field: ExactLength),+,
41            pub(crate) minimum: ExactLength, pub(crate) preferred: ExactLength,
42            pub(crate) radius: Option<ExactLength>,
43        }
44        impl LegendTheme {
45            pub(crate) fn lengths(&self, label_size: f64, title_size: f64) -> Result<LegendLengths> {
46                let metrics = [LocalMetric::css_pixels(label_size)?, LocalMetric::css_pixels(title_size)?];
47                Ok(LegendLengths {
48                    $($field: self.get_spacing().$get().product(metrics[$metric])),+,
49                    minimum: self.get_gradient_lengths().get_minimum().product(metrics[0]),
50                    preferred: self.get_gradient_lengths().get_preferred().product(metrics[0]),
51                    radius: self.get_frame().map(|frame| frame.get_radius().product(metrics[0])),
52                })
53            }
54        }
55    };
56}
57
58legend_spacing! {
59    padding => get_padding: 0, key_width => get_key_width: 0,
60    key_label_gap => get_key_label_gap: 0, outside_gap => get_outside_gap: 0,
61    shared_gap => get_shared_gap: 0, row_gap => get_row_gap: 0,
62    column_gap => get_column_gap: 0, title_gap => get_title_gap: 1,
63    glyph_edge_padding => get_glyph_edge_padding: 0,
64}
65
66/// Positive minimum and at-least-minimum preferred continuous-guide lengths.
67#[derive(Clone, Debug, PartialEq, Eq)]
68pub struct GradientLengths {
69    minimum: RelativeSpacing,
70    preferred: RelativeSpacing,
71}
72
73impl GradientLengths {
74    /// Construct positive lengths with preferred at least minimum under exact comparison.
75    pub fn new(minimum: RelativeSpacing, preferred: RelativeSpacing) -> Result<Self> {
76        let value = Self { minimum, preferred };
77        value.validate_in()?;
78        Ok(value)
79    }
80    fn validate_in(&self) -> Result<()> {
81        positive(self.get_minimum(), "gradient minimum")?;
82        positive(self.get_preferred(), "gradient preference")?;
83        if self.get_minimum().compare(self.get_preferred()) == Ordering::Greater {
84            return Err(Error::Data(
85                "guide gradient preference must be at least its minimum".into(),
86            ));
87        }
88        Ok(())
89    }
90    /// Borrow the exact minimum relationship.
91    pub fn get_minimum(&self) -> &RelativeSpacing {
92        &self.minimum
93    }
94    /// Borrow the exact preferred relationship.
95    pub fn get_preferred(&self) -> &RelativeSpacing {
96        &self.preferred
97    }
98    /// Replace minimum, preserving the positive ordered length invariant.
99    pub fn minimum(self, minimum: RelativeSpacing) -> Result<Self> {
100        Self::new(minimum, self.preferred)
101    }
102    /// Replace preference, preserving the positive ordered length invariant.
103    pub fn preferred(self, preferred: RelativeSpacing) -> Result<Self> {
104        Self::new(self.minimum, preferred)
105    }
106}
107
108/// Complete guide-container paint, optional independent outline and local corner radius.
109#[derive(Clone, Debug, PartialEq)]
110pub struct LegendFrameTheme {
111    fill: Color,
112    outline: Option<OutlineTheme>,
113    radius: RelativeSpacing,
114}
115
116impl LegendFrameTheme {
117    /// Construct a complete container with a nonnegative local corner radius.
118    pub fn new(
119        fill: Color,
120        outline: Option<OutlineTheme>,
121        radius: RelativeSpacing,
122    ) -> Result<Self> {
123        let value = Self {
124            fill,
125            outline,
126            radius,
127        };
128        value.validate()?;
129        Ok(value)
130    }
131    fn validate(&self) -> Result<()> {
132        if let Some(outline) = self.get_outline() {
133            outline.validate()?;
134        }
135        Ok(())
136    }
137    /// Inspect the complete container fill.
138    pub fn get_fill(&self) -> Color {
139        self.fill
140    }
141    /// Borrow the optional independent outline.
142    pub fn get_outline(&self) -> Option<&OutlineTheme> {
143        self.outline.as_ref()
144    }
145    /// Borrow the nonnegative legend-label-em corner-radius relationship.
146    pub fn get_radius(&self) -> &RelativeSpacing {
147        &self.radius
148    }
149    /// Replace only the container fill.
150    pub fn fill(self, fill: Color) -> Result<Self> {
151        Self::new(fill, self.outline, self.radius)
152    }
153    /// Replace only the optional independent outline.
154    pub fn outline(self, outline: Option<OutlineTheme>) -> Result<Self> {
155        Self::new(self.fill, outline, self.radius)
156    }
157    /// Replace only the nonnegative local corner-radius relationship.
158    pub fn radius(self, radius: RelativeSpacing) -> Result<Self> {
159        Self::new(self.fill, self.outline, radius)
160    }
161}
162
163/// Complete measured guide chrome, independent of guide content or placement policy.
164#[derive(Clone, Debug, PartialEq)]
165pub struct LegendTheme {
166    spacing: LegendSpacing,
167    gradient_lengths: GradientLengths,
168    frame: Option<LegendFrameTheme>,
169}
170
171impl LegendTheme {
172    pub(crate) fn builtin() -> Result<Self> {
173        let spacing = LegendSpacing::new(
174            RelativeSpacing::from_pixels(8.8, 11)?,
175            RelativeSpacing::ratio(1, 1)?,
176            RelativeSpacing::from_pixels(8.8, 11)?,
177            RelativeSpacing::from_pixels(8.8, 11)?,
178            RelativeSpacing::from_pixels(17.6, 11)?,
179            RelativeSpacing::from_pixels(3.3, 11)?,
180            RelativeSpacing::from_pixels(13.2, 11)?,
181            RelativeSpacing::from_pixels(7.8, 12)?,
182            RelativeSpacing::new(0.2)?,
183        )?;
184        let lengths = GradientLengths::new(
185            RelativeSpacing::ratio(40, 11)?,
186            RelativeSpacing::ratio(160, 11)?,
187        )?;
188        let frame = LegendFrameTheme::new(
189            Color::rgba(255, 255, 255, 204),
190            Some(OutlineTheme::new(Color::rgb(200, 200, 200), 1.0)?),
191            RelativeSpacing::ratio(2, 11)?,
192        )?;
193        Self::new(spacing, lengths, Some(frame))
194    }
195    /// Construct complete spacing, continuous lengths and an optional container frame.
196    pub fn new(
197        spacing: LegendSpacing,
198        gradient_lengths: GradientLengths,
199        frame: Option<LegendFrameTheme>,
200    ) -> Result<Self> {
201        let value = Self {
202            spacing,
203            gradient_lengths,
204            frame,
205        };
206        value.validate_in()?;
207        Ok(value)
208    }
209    pub(crate) fn validate_in(&self) -> Result<()> {
210        self.get_spacing().validate()?;
211        self.get_gradient_lengths().validate_in()?;
212        if let Some(frame) = self.get_frame() {
213            frame.validate()?;
214        }
215        Ok(())
216    }
217    /// Borrow all complete exact guide relationships.
218    pub fn get_spacing(&self) -> &LegendSpacing {
219        &self.spacing
220    }
221    /// Borrow the continuous-guide minimum and preference.
222    pub fn get_gradient_lengths(&self) -> &GradientLengths {
223        &self.gradient_lengths
224    }
225    /// Borrow the optional guide-container appearance.
226    pub fn get_frame(&self) -> Option<&LegendFrameTheme> {
227        self.frame.as_ref()
228    }
229    /// Borrow the Canvas-owned shared-guide gap relationship.
230    pub fn get_shared_gap(&self) -> &RelativeSpacing {
231        self.get_spacing().get_shared_gap()
232    }
233    /// Replace the complete guide-spacing value.
234    pub fn spacing(self, spacing: LegendSpacing) -> Result<Self> {
235        Self::new(spacing, self.gradient_lengths, self.frame)
236    }
237    /// Replace the complete continuous-guide length value.
238    pub fn gradient_lengths(self, value: GradientLengths) -> Result<Self> {
239        Self::new(self.spacing, value, self.frame)
240    }
241    /// Replace only the optional guide-container appearance.
242    pub fn frame(self, frame: Option<LegendFrameTheme>) -> Result<Self> {
243        Self::new(self.spacing, self.gradient_lengths, frame)
244    }
245    /// Replace only the Canvas-owned shared-guide gap relationship.
246    pub fn shared_gap(self, value: RelativeSpacing) -> Result<Self> {
247        let spacing = self.spacing.shared_gap(value)?;
248        Self::new(spacing, self.gradient_lengths, self.frame)
249    }
250
251    pub(crate) fn same(&self, other: &Self) -> bool {
252        match (self.get_frame(), other.get_frame()) {
253            (None, None) => {}
254            (Some(left), Some(right))
255                if left.get_fill() == right.get_fill()
256                    && left.get_outline() == right.get_outline() => {}
257            _ => return false,
258        }
259        for (left, right) in self
260            .get_spacing()
261            .relationships()
262            .into_iter()
263            .zip(other.get_spacing().relationships())
264        {
265            if !left.same(right) {
266                return false;
267            }
268        }
269        for (left, right) in [
270            (
271                self.get_gradient_lengths().get_minimum(),
272                other.get_gradient_lengths().get_minimum(),
273            ),
274            (
275                self.get_gradient_lengths().get_preferred(),
276                other.get_gradient_lengths().get_preferred(),
277            ),
278        ] {
279            if !left.same(right) {
280                return false;
281            }
282        }
283        if let (Some(left), Some(right)) = (self.get_frame(), other.get_frame()) {
284            if !left.get_radius().same(right.get_radius()) {
285                return false;
286            }
287        }
288        true
289    }
290    pub(crate) fn observe_feedback(&self, round: &mut FeedbackRound) -> Result<()> {
291        round.observe_count(usize::from(self.get_frame().is_some()))?;
292        for value in self.get_spacing().relationships() {
293            value.observe_feedback(round)?;
294        }
295        self.get_gradient_lengths()
296            .get_minimum()
297            .observe_feedback(round)?;
298        self.get_gradient_lengths()
299            .get_preferred()
300            .observe_feedback(round)?;
301        if let Some(frame) = self.get_frame() {
302            for color in [
303                Some(frame.get_fill()),
304                frame.get_outline().map(OutlineTheme::get_color),
305            ]
306            .into_iter()
307            .flatten()
308            {
309                for byte in [color.red(), color.green(), color.blue(), color.get_alpha()] {
310                    round.observe_count(usize::from(byte))?;
311                }
312            }
313            round.observe_count(usize::from(frame.get_outline().is_some()))?;
314            if let Some(outline) = frame.get_outline() {
315                round.observe_number(f64::from(outline.get_width()))?;
316            }
317            frame.get_radius().observe_feedback(round)?;
318        }
319        Ok(())
320    }
321    pub(crate) fn outside_gap_pixels(&self, label_size: f64) -> Result<f64> {
322        self.get_spacing()
323            .get_outside_gap()
324            .product(LocalMetric::css_pixels(label_size)?)
325            .pixels_rounded(SpatialRounding::NearestEven)
326    }
327    pub(crate) fn shared_gap_pixels(&self, label_size: f64) -> Result<f64> {
328        self.get_shared_gap()
329            .product(LocalMetric::css_pixels(label_size)?)
330            .pixels_rounded(SpatialRounding::NearestEven)
331    }
332}