Skip to main content

crisol_plot/plot/
config.rs

1//! Everything about a plot that is not data: text, sizes, colors, axes, grid, legend,
2//! and per-series overrides. Edit a [`PlotConfig`] (for example in a settings dialog)
3//! and pass it to [`super::Plot::config`]; the screen and the SVG/PNG export use it.
4
5use egui::Color32;
6
7use super::LegendPosition;
8use super::animation::LegendHoverConfig;
9use super::axis::Scale;
10use super::chart_config::{DirectionArrowConfig, GaugeConfig, HeatmapConfig, PieConfig, RadarConfig, WaterfallConfig};
11use super::measure::MeasurementConfig;
12use super::series::{LineStyle, Marker, Smoothing, YAxis};
13
14/// Which renderer draws the data layer.
15#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
16#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
18#[non_exhaustive]
19pub enum Renderer {
20    /// The CPU painter: the reference, snapshots, and the fallback.
21    #[default]
22    Cpu,
23    /// GPU lines and scatter through the `gpu` feature; charts, axes, and legend stay CPU.
24    Gpu,
25}
26
27/// Where the chart title sits along the top.
28#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
29#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
30#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
31#[non_exhaustive]
32pub enum TitleAlign {
33    /// Over the left edge of the data area.
34    Left,
35    /// Centered over the data area.
36    #[default]
37    Center,
38    /// Over the right edge of the data area.
39    Right,
40}
41
42pub use super::axis::Minor;
43
44#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
45/// One axis: range, scale, ticks, grid, and labels.
46#[derive(Clone, Debug, PartialEq)]
47pub struct AxisConfig {
48    /// The axis title.
49    pub label: Option<String>,
50    /// Linear or log10.
51    pub scale: Scale,
52    /// Fixed lower limit in data units; automatic when `None`.
53    pub min: Option<f64>,
54    /// Fixed upper limit in data units; automatic when `None`.
55    pub max: Option<f64>,
56    /// Distance between major ticks in data units (decades on log axes); 1-2-5 when
57    /// `None`.
58    pub major_step: Option<f64>,
59    /// Minor ticks between majors.
60    pub minor: Minor,
61    /// Grid lines at major ticks.
62    pub grid_major: bool,
63    /// Grid lines at minor ticks.
64    pub grid_minor: bool,
65    /// Decimals of the tick labels; from the step when `None`.
66    pub decimals: Option<u8>,
67    /// Draw the tick labels.
68    pub tick_labels: bool,
69    /// Axis title size in points; [`PlotConfig::label_size`] when `None`.
70    pub label_size: Option<f32>,
71    /// Axis title color; [`PlotColors::text`] (or the theme) when `None`.
72    pub label_color: Option<Color32>,
73    /// Tick labels and tick marks; the theme when `None`. Coloring the right axis like
74    /// its series tells the two axes apart.
75    pub tick_color: Option<Color32>,
76    /// Labels for [`Scale::Category`], in index order.
77    pub categories: Option<Vec<String>>,
78}
79
80impl Default for AxisConfig {
81    fn default() -> Self {
82        Self {
83            label: None,
84            scale: Scale::Linear,
85            min: None,
86            max: None,
87            major_step: None,
88            minor: Minor::Auto,
89            grid_major: true,
90            grid_minor: true,
91            decimals: None,
92            tick_labels: true,
93            label_size: None,
94            label_color: None,
95            tick_color: None,
96            categories: None,
97        }
98    }
99}
100
101#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
102/// Optional color overrides; `None` follows the theme.
103#[derive(Clone, Copy, Debug, Default, PartialEq)]
104pub struct PlotColors {
105    /// Fill of the data area.
106    pub background: Option<Color32>,
107    /// Fill around the data area (transparent on screen by default).
108    pub canvas: Option<Color32>,
109    /// The frame and tick marks.
110    pub frame: Option<Color32>,
111    /// Grid lines (before the major/minor opacity).
112    pub grid: Option<Color32>,
113    /// Title and axis titles.
114    pub text: Option<Color32>,
115    /// Tick labels.
116    pub tick_text: Option<Color32>,
117    /// Selection fill and outline.
118    pub selection: Option<Color32>,
119}
120
121#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
122/// Overrides for one series, matched by name.
123#[derive(Clone, Debug, Default, PartialEq)]
124pub struct SeriesStyle {
125    /// The series name this applies to.
126    pub name: String,
127    /// Stroke and fill color.
128    pub color: Option<Color32>,
129    /// Line width in points.
130    pub width: Option<f32>,
131    /// Solid, dashed, or dotted.
132    pub line_style: Option<LineStyle>,
133    /// Marker shape (scatter, or markers on line vertices).
134    pub marker: Option<Marker>,
135    /// Marker radius in points.
136    pub marker_size: Option<f32>,
137    /// Opacity of area and bar fills, 0–1.
138    pub fill_opacity: Option<f32>,
139    /// Straight, spline, or monotone segments (lines and areas).
140    pub smoothing: Option<Smoothing>,
141    /// Move the series to the left or the right y axis.
142    pub y_axis: Option<YAxis>,
143    /// Show the direction arrow for this series; [`PlotConfig::direction`] when `None`.
144    pub direction_arrow: Option<bool>,
145}
146
147impl SeriesStyle {
148    /// Whether nothing is overridden (a settings dialog can drop it).
149    pub fn is_empty(&self) -> bool {
150        self.color.is_none()
151            && self.width.is_none()
152            && self.line_style.is_none()
153            && self.marker.is_none()
154            && self.marker_size.is_none()
155            && self.fill_opacity.is_none()
156            && self.smoothing.is_none()
157            && self.y_axis.is_none()
158            && self.direction_arrow.is_none()
159    }
160}
161
162#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
163/// The complete appearance of a plot.
164#[derive(Clone, Debug, PartialEq)]
165pub struct PlotConfig {
166    /// Title above the data area.
167    pub title: Option<String>,
168    /// The horizontal axis.
169    pub x: AxisConfig,
170    /// The vertical axis on the left.
171    pub y: AxisConfig,
172    /// The secondary vertical axis on the right, shown when a series uses
173    /// [`YAxis::Right`]. Its grid is off by default.
174    pub y2: AxisConfig,
175    /// Title size in points.
176    pub title_size: f32,
177    /// Title color; [`PlotColors::text`] (or the theme) when `None`.
178    pub title_color: Option<Color32>,
179    /// Title alignment over the data area.
180    pub title_align: TitleAlign,
181    /// Axis title size in points.
182    pub label_size: f32,
183    /// Tick label size in points.
184    pub tick_size: f32,
185    /// Legend text size in points.
186    pub legend_size: f32,
187    /// Frame line width in points.
188    pub frame_width: f32,
189    /// Grid line width in points.
190    pub grid_width: f32,
191    /// Opacity of major grid lines, 0–1.
192    pub grid_major_opacity: f32,
193    /// Opacity of minor grid lines, 0–1.
194    pub grid_minor_opacity: f32,
195    /// Length of the major tick marks outside the frame (minor marks are half).
196    pub tick_length: f32,
197    /// Multiplies every line width.
198    pub line_scale: f32,
199    /// Multiplies every marker size.
200    pub marker_scale: f32,
201    /// Legend corner or hidden.
202    pub legend: LegendPosition,
203    /// Draw the legend's background box.
204    pub legend_frame: bool,
205    /// Show the tool buttons.
206    pub toolbar: bool,
207    /// Dashed guides from the hovered point to the axes.
208    pub hover_guides: bool,
209    /// The hover popup.
210    pub hover_popup: bool,
211    /// The animation played while a legend row is hovered.
212    pub legend_hover: LegendHoverConfig,
213    /// The arrow beside the newest point of a line (for streaming data).
214    pub direction: DirectionArrowConfig,
215    /// Pie and donut layout.
216    pub pie: PieConfig,
217    /// Radar axes and fill.
218    pub radar: RadarConfig,
219    /// Gauge arc and labels.
220    pub gauge: GaugeConfig,
221    /// Heatmap opacity and color scale.
222    pub heatmap: HeatmapConfig,
223    /// Waterfall width and connectors.
224    pub waterfall: WaterfallConfig,
225    /// Theme overrides.
226    pub colors: PlotColors,
227    /// Per-series overrides.
228    pub series: Vec<SeriesStyle>,
229    /// Measurement mode, snapping, and labels.
230    pub measurement: MeasurementConfig,
231    /// CPU or GPU data layer.
232    pub renderer: Renderer,
233}
234
235impl Default for PlotConfig {
236    fn default() -> Self {
237        Self {
238            title: None,
239            x: AxisConfig::default(),
240            y: AxisConfig::default(),
241            y2: AxisConfig {
242                grid_major: false,
243                grid_minor: false,
244                ..AxisConfig::default()
245            },
246            title_size: 14.0,
247            title_color: None,
248            title_align: TitleAlign::Center,
249            label_size: 12.0,
250            tick_size: 11.0,
251            legend_size: 11.5,
252            frame_width: 1.0,
253            grid_width: 1.0,
254            grid_major_opacity: 0.55,
255            grid_minor_opacity: 0.22,
256            tick_length: 4.0,
257            line_scale: 1.0,
258            marker_scale: 1.0,
259            legend: LegendPosition::TopLeft,
260            legend_frame: true,
261            toolbar: true,
262            hover_guides: true,
263            hover_popup: true,
264            legend_hover: LegendHoverConfig::default(),
265            direction: DirectionArrowConfig::default(),
266            pie: PieConfig::default(),
267            radar: RadarConfig::default(),
268            gauge: GaugeConfig::default(),
269            heatmap: HeatmapConfig::default(),
270            waterfall: WaterfallConfig::default(),
271            colors: PlotColors::default(),
272            series: Vec::new(),
273            measurement: MeasurementConfig::default(),
274            renderer: Renderer::Cpu,
275        }
276    }
277}
278
279impl PlotConfig {
280    /// The overrides for `name`, if any.
281    pub fn series_style(&self, name: &str) -> Option<&SeriesStyle> {
282        self.series.iter().find(|style| style.name == name)
283    }
284
285    /// The overrides for `name`, created empty when missing.
286    pub fn series_style_mut(&mut self, name: &str) -> &mut SeriesStyle {
287        if let Some(index) = self.series.iter().position(|style| style.name == name) {
288            return &mut self.series[index];
289        }
290        self.series.push(SeriesStyle {
291            name: name.to_owned(),
292            ..SeriesStyle::default()
293        });
294        let last = self.series.len() - 1;
295        &mut self.series[last]
296    }
297
298    /// Clamp every size and opacity to a sensible range (after editing in a dialog).
299    pub fn sanitize(&mut self) {
300        self.title_size = self.title_size.clamp(6.0, 48.0);
301        self.label_size = self.label_size.clamp(6.0, 36.0);
302        self.tick_size = self.tick_size.clamp(6.0, 30.0);
303        self.legend_size = self.legend_size.clamp(6.0, 30.0);
304        self.frame_width = self.frame_width.clamp(0.0, 6.0);
305        self.grid_width = self.grid_width.clamp(0.5, 6.0);
306        self.grid_major_opacity = self.grid_major_opacity.clamp(0.0, 1.0);
307        self.grid_minor_opacity = self.grid_minor_opacity.clamp(0.0, 1.0);
308        self.tick_length = self.tick_length.clamp(0.0, 16.0);
309        self.line_scale = self.line_scale.clamp(0.25, 8.0);
310        self.marker_scale = self.marker_scale.clamp(0.25, 8.0);
311        self.legend_hover.period = self.legend_hover.period.clamp(0.2, 10.0);
312        self.direction.points = self.direction.points.clamp(2, 64);
313        self.direction.length = self.direction.length.clamp(4.0, 160.0);
314        self.direction.width = self.direction.width.clamp(0.5, 8.0);
315        self.direction.head = self.direction.head.clamp(2.0, 40.0);
316        self.pie.inner_radius = self.pie.inner_radius.clamp(0.0, 0.9);
317        if !self.pie.start_angle.is_finite() {
318            self.pie.start_angle = -std::f32::consts::FRAC_PI_2;
319        }
320        self.radar.rings = self.radar.rings.clamp(1, 12);
321        self.radar.fill_opacity = self.radar.fill_opacity.clamp(0.0, 1.0);
322        self.radar.max = self.radar.max.filter(|max| max.is_finite() && *max > 0.0);
323        self.gauge.thickness = self.gauge.thickness.clamp(2.0, 40.0);
324        if !(self.gauge.start_angle.is_finite() && self.gauge.end_angle.is_finite())
325            || (self.gauge.end_angle - self.gauge.start_angle).abs() < 0.1
326        {
327            self.gauge.start_angle = 0.75 * std::f32::consts::PI;
328            self.gauge.end_angle = 2.25 * std::f32::consts::PI;
329        }
330        self.heatmap.opacity = self.heatmap.opacity.clamp(0.0, 1.0);
331        self.waterfall.bar_width = self
332            .waterfall
333            .bar_width
334            .filter(|width| width.is_finite() && *width > 0.0);
335        for axis in [&mut self.x, &mut self.y, &mut self.y2] {
336            axis.label_size = axis.label_size.map(|size| size.clamp(6.0, 36.0));
337            if let (Some(min), Some(max)) = (axis.min, axis.max)
338                && min >= max
339            {
340                axis.max = None;
341            }
342            if axis.scale == Scale::Log10 {
343                axis.min = axis.min.filter(|min| *min > 0.0);
344                axis.max = axis.max.filter(|max| *max > 0.0);
345            }
346            axis.major_step = axis.major_step.filter(|step| step.is_finite() && *step > 0.0);
347            if let Minor::Divisions(divisions) = axis.minor {
348                axis.minor = Minor::Divisions(divisions.clamp(2, 20));
349            }
350            axis.decimals = axis.decimals.map(|decimals| decimals.min(10));
351        }
352        for style in &mut self.series {
353            style.width = style.width.map(|width| width.clamp(0.25, 12.0));
354            style.marker_size = style.marker_size.map(|size| size.clamp(0.5, 20.0));
355            style.fill_opacity = style.fill_opacity.map(|opacity| opacity.clamp(0.0, 1.0));
356        }
357    }
358}
359
360#[cfg(test)]
361mod tests {
362    use super::*;
363
364    #[test]
365    fn sanitize_drops_impossible_limits() {
366        let mut config = PlotConfig::default();
367        config.x.min = Some(5.0);
368        config.x.max = Some(1.0);
369        config.y.scale = Scale::Log10;
370        config.y.min = Some(-1.0);
371        config.y.major_step = Some(0.0);
372        config.title_size = 400.0;
373        config.legend_hover.period = 0.0;
374        config.direction.points = 0;
375        config.pie.inner_radius = 4.0;
376        config.radar.rings = 0;
377        config.gauge.thickness = 900.0;
378        config.heatmap.opacity = 4.0;
379        config.waterfall.bar_width = Some(-1.0);
380        config.sanitize();
381        assert_eq!((config.x.min, config.x.max), (Some(5.0), None));
382        assert_eq!(config.y.min, None);
383        assert_eq!(config.y.major_step, None);
384        assert_eq!(config.title_size, 48.0);
385        assert_eq!(config.legend_hover.period, 0.2);
386        assert_eq!(config.direction.points, 2);
387        assert_eq!(config.pie.inner_radius, 0.9);
388        assert_eq!(config.radar.rings, 1);
389        assert_eq!(config.gauge.thickness, 40.0);
390        assert_eq!(config.heatmap.opacity, 1.0);
391        assert_eq!(config.waterfall.bar_width, None);
392    }
393
394    #[test]
395    fn series_styles_are_found_or_created() {
396        let mut config = PlotConfig::default();
397        config.series_style_mut("a").width = Some(3.0);
398        config.series_style_mut("a").color = Some(Color32::RED);
399        assert_eq!(config.series.len(), 1);
400        assert_eq!(config.series_style("a").and_then(|style| style.width), Some(3.0));
401    }
402}