Skip to main content

crisol_plot_core/
state.rs

1//! The egui-free state of one plot: view, tool, selection, legend, and pipeline.
2
3use crisol_core::data::Bounds;
4
5use crate::axis::Scale;
6use crate::filter::FilterKind;
7use crate::pipeline::Pipeline;
8use crate::transforms::TransformKind;
9
10/// What a primary-button drag does.
11#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
12#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
13#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
14#[non_exhaustive]
15pub enum PlotTool {
16    /// Drag moves the view.
17    #[default]
18    Pan,
19    /// Drag draws a box and zooms to it.
20    Zoom,
21    /// Drag draws a box and reports it as the selection.
22    Select,
23    /// Drag measures the distance and slope between two points.
24    MeasureDistance,
25    /// Drag measures a rectangular region: area, extrema, slopes, and integrals.
26    MeasureArea,
27}
28
29/// The egui-free half of a plot's state. The UI crate keeps the annotations, the
30/// measurements, and the live drag in its adapter.
31#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
32#[derive(Clone, Debug)]
33pub struct ViewState {
34    /// The explicit view, or `None` while automatic.
35    pub view: Option<Bounds>,
36    /// The tool the primary button uses.
37    pub tool: PlotTool,
38    /// The selected area in data coordinates.
39    pub selection: Option<Bounds>,
40    /// Names of the hidden series.
41    #[cfg_attr(feature = "serde", serde(default))]
42    pub hidden: Vec<String>,
43    /// Whether the toolbar's export menu is open.
44    #[cfg_attr(feature = "serde", serde(default))]
45    pub export_menu: bool,
46    /// The right axis range in scaled units, once zoomed or panned.
47    #[cfg_attr(feature = "serde", serde(default))]
48    pub y2_view: Option<[f64; 2]>,
49    /// Where the dragged legend sits: 0–1 across the room left in the frame.
50    #[cfg_attr(feature = "serde", serde(default))]
51    pub legend_pos: Option<[f32; 2]>,
52    /// Series extents by fingerprint, so the automatic view does not walk every point
53    /// of every series each frame.
54    #[cfg_attr(feature = "serde", serde(skip))]
55    pub extents: Vec<(u64, Bounds)>,
56    /// The series whose legend row the pointer is over.
57    #[cfg_attr(feature = "serde", serde(skip))]
58    pub legend_hover: Option<usize>,
59    /// When that hover began, for the animation clock.
60    #[cfg_attr(feature = "serde", serde(skip))]
61    pub legend_hover_start: f64,
62    /// Filters and transforms applied to the visible series.
63    #[cfg_attr(feature = "serde", serde(default))]
64    pub pipeline: Pipeline,
65    /// Whether the user changed the measurement settings from the panel.
66    #[cfg_attr(feature = "serde", serde(default))]
67    pub measurement_customized: bool,
68    /// Whether the chart-settings dialog is open.
69    #[cfg_attr(feature = "serde", serde(default))]
70    pub settings_open: bool,
71    /// Whether the tool ribbon stays unrolled.
72    #[cfg_attr(feature = "serde", serde(default))]
73    pub toolbar_pinned: bool,
74    /// Ribbon reveal fraction, animated.
75    #[cfg_attr(feature = "serde", serde(skip))]
76    pub toolbar_reveal: f32,
77    /// Dragged ribbon position relative to the plot frame.
78    #[cfg_attr(feature = "serde", serde(default))]
79    pub toolbar_anchor: Option<[f32; 2]>,
80}
81
82impl Default for ViewState {
83    fn default() -> Self {
84        Self {
85            view: None,
86            tool: PlotTool::default(),
87            selection: None,
88            hidden: Vec::new(),
89            export_menu: false,
90            y2_view: None,
91            legend_pos: None,
92            extents: Vec::new(),
93            legend_hover: None,
94            legend_hover_start: 0.0,
95            pipeline: Pipeline::default(),
96            measurement_customized: false,
97            settings_open: false,
98            // Keep the tools visible by default; the pin collapses the ribbon and the
99            // hover animation reopens it.
100            toolbar_pinned: true,
101            toolbar_reveal: 1.0,
102            toolbar_anchor: None,
103        }
104    }
105}
106
107impl ViewState {
108    /// The cached extent of a series with `fingerprint`, if it is current.
109    pub fn cached_extent(&self, fingerprint: u64) -> Option<Bounds> {
110        self.extents
111            .iter()
112            .find(|(cached, _)| *cached == fingerprint)
113            .map(|(_, bounds)| *bounds)
114    }
115
116    /// The series whose legend row the pointer is over.
117    pub fn legend_hover(&self) -> Option<usize> {
118        self.legend_hover
119    }
120
121    /// When the current legend hover began.
122    pub fn legend_hover_start(&self) -> f64 {
123        self.legend_hover_start
124    }
125
126    /// Set the hovered legend row and restart the animation when it changes.
127    pub fn set_legend_hover(&mut self, series: Option<usize>, now: f64) {
128        if series != self.legend_hover {
129            self.legend_hover = series;
130            self.legend_hover_start = now;
131        }
132    }
133
134    /// The series whose legend row is under the pointer, if any.
135    pub fn hovered_series(&self) -> Option<usize> {
136        self.legend_hover
137    }
138
139    /// Fit the view to the data again.
140    pub fn reset_view(&mut self) {
141        self.view = None;
142        self.y2_view = None;
143    }
144
145    /// Whether the view follows the data (no zoom or pan since the last reset).
146    pub fn is_auto(&self) -> bool {
147        self.view.is_none()
148    }
149
150    /// The explicit view, or `None` while automatic.
151    pub fn view(&self) -> Option<Bounds> {
152        self.view
153    }
154
155    /// Show `bounds` (data coordinates, linear axes) on the x and left y axes.
156    pub fn set_view(&mut self, bounds: Bounds) {
157        self.view = Some(bounds);
158    }
159
160    /// Show `min..=max` (data coordinates, linear axis) on the right y axis.
161    pub fn set_y2_view(&mut self, min: f64, max: f64) {
162        self.y2_view = Some([min.min(max), min.max(max)]);
163    }
164
165    /// The filter/transform pipeline.
166    pub fn pipeline(&self) -> &Pipeline {
167        &self.pipeline
168    }
169
170    /// The filter/transform pipeline, mutably.
171    pub fn pipeline_mut(&mut self) -> &mut Pipeline {
172        &mut self.pipeline
173    }
174
175    /// Enable or disable one filter.
176    pub fn toggle_filter(&mut self, filter: FilterKind) {
177        self.pipeline.toggle_filter(filter);
178    }
179
180    /// Enable or disable one filter explicitly.
181    pub fn set_filter(&mut self, filter: FilterKind, enabled: bool) {
182        self.pipeline.set_filter(filter, enabled);
183    }
184
185    /// Replace the transform.
186    pub fn set_transform(&mut self, transform: Option<TransformKind>) {
187        self.pipeline.set_transform(transform);
188    }
189
190    /// Disable every filter and transform.
191    pub fn clear_analysis(&mut self) {
192        self.pipeline.clear();
193    }
194
195    /// Pin the tool ribbon open or let it unroll on hover.
196    pub fn pin_toolbar(&mut self, pinned: bool) {
197        self.toolbar_pinned = pinned;
198        if pinned {
199            self.toolbar_reveal = 1.0;
200        }
201    }
202
203    /// Collapse the ribbon and unpin it.
204    pub fn collapse_toolbar(&mut self) {
205        self.toolbar_pinned = false;
206        self.toolbar_reveal = 0.0;
207    }
208
209    /// Where the legend was dragged to, as fractions of the room around it.
210    pub fn legend_position(&self) -> Option<[f32; 2]> {
211        self.legend_pos
212    }
213
214    /// Place the legend; `None` returns it to its configured corner.
215    pub fn set_legend_position(&mut self, position: Option<[f32; 2]>) {
216        self.legend_pos = position.map(|[x, y]| [x.clamp(0.0, 1.0), y.clamp(0.0, 1.0)]);
217    }
218
219    /// Whether the legend has hidden the series called `name`.
220    pub fn is_hidden(&self, name: &str) -> bool {
221        self.hidden.iter().any(|hidden| hidden == name)
222    }
223
224    /// Show or hide a series by name.
225    pub fn set_hidden(&mut self, name: &str, hidden: bool) {
226        self.hidden.retain(|entry| entry != name);
227        if hidden {
228            self.hidden.push(name.to_owned());
229        }
230    }
231
232    /// Whether the view or the analysis would be cleared by a reset.
233    pub fn has_overlays(&self) -> bool {
234        self.pipeline.is_active() || self.selection.is_some()
235    }
236}
237
238/// The scaled range of the right axis, when set.
239pub fn scaled_y2(bounds: Option<[f64; 2]>, scale: Scale) -> Option<[f64; 2]> {
240    bounds.map(|[min, max]| [scale.inverse(min), scale.inverse(max)])
241}