crisol-plot-core 1.8.0

Crisol plot core: the egui-free math behind the plot, axis ticks, analysis, filters, and decimation.
Documentation
//! The egui-free state of one plot: view, tool, selection, legend, and pipeline.

use crisol_core::data::Bounds;

use crate::axis::Scale;
use crate::filter::FilterKind;
use crate::pipeline::Pipeline;
use crate::transforms::TransformKind;

/// What a primary-button drag does.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum PlotTool {
    /// Drag moves the view.
    #[default]
    Pan,
    /// Drag draws a box and zooms to it.
    Zoom,
    /// Drag draws a box and reports it as the selection.
    Select,
    /// Drag measures the distance and slope between two points.
    MeasureDistance,
    /// Drag measures a rectangular region: area, extrema, slopes, and integrals.
    MeasureArea,
}

/// The egui-free half of a plot's state. The UI crate keeps the annotations, the
/// measurements, and the live drag in its adapter.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Debug)]
pub struct ViewState {
    /// The explicit view, or `None` while automatic.
    pub view: Option<Bounds>,
    /// The tool the primary button uses.
    pub tool: PlotTool,
    /// The selected area in data coordinates.
    pub selection: Option<Bounds>,
    /// Names of the hidden series.
    #[cfg_attr(feature = "serde", serde(default))]
    pub hidden: Vec<String>,
    /// Whether the toolbar's export menu is open.
    #[cfg_attr(feature = "serde", serde(default))]
    pub export_menu: bool,
    /// The right axis range in scaled units, once zoomed or panned.
    #[cfg_attr(feature = "serde", serde(default))]
    pub y2_view: Option<[f64; 2]>,
    /// Where the dragged legend sits: 0–1 across the room left in the frame.
    #[cfg_attr(feature = "serde", serde(default))]
    pub legend_pos: Option<[f32; 2]>,
    /// Series extents by fingerprint, so the automatic view does not walk every point
    /// of every series each frame.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub extents: Vec<(u64, Bounds)>,
    /// The series whose legend row the pointer is over.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub legend_hover: Option<usize>,
    /// When that hover began, for the animation clock.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub legend_hover_start: f64,
    /// Filters and transforms applied to the visible series.
    #[cfg_attr(feature = "serde", serde(default))]
    pub pipeline: Pipeline,
    /// Whether the user changed the measurement settings from the panel.
    #[cfg_attr(feature = "serde", serde(default))]
    pub measurement_customized: bool,
    /// Whether the chart-settings dialog is open.
    #[cfg_attr(feature = "serde", serde(default))]
    pub settings_open: bool,
    /// Whether the tool ribbon stays unrolled.
    #[cfg_attr(feature = "serde", serde(default))]
    pub toolbar_pinned: bool,
    /// Ribbon reveal fraction, animated.
    #[cfg_attr(feature = "serde", serde(skip))]
    pub toolbar_reveal: f32,
    /// Dragged ribbon position relative to the plot frame.
    #[cfg_attr(feature = "serde", serde(default))]
    pub toolbar_anchor: Option<[f32; 2]>,
}

impl Default for ViewState {
    fn default() -> Self {
        Self {
            view: None,
            tool: PlotTool::default(),
            selection: None,
            hidden: Vec::new(),
            export_menu: false,
            y2_view: None,
            legend_pos: None,
            extents: Vec::new(),
            legend_hover: None,
            legend_hover_start: 0.0,
            pipeline: Pipeline::default(),
            measurement_customized: false,
            settings_open: false,
            // Keep the tools visible by default; the pin collapses the ribbon and the
            // hover animation reopens it.
            toolbar_pinned: true,
            toolbar_reveal: 1.0,
            toolbar_anchor: None,
        }
    }
}

impl ViewState {
    /// The cached extent of a series with `fingerprint`, if it is current.
    pub fn cached_extent(&self, fingerprint: u64) -> Option<Bounds> {
        self.extents
            .iter()
            .find(|(cached, _)| *cached == fingerprint)
            .map(|(_, bounds)| *bounds)
    }

    /// The series whose legend row the pointer is over.
    pub fn legend_hover(&self) -> Option<usize> {
        self.legend_hover
    }

    /// When the current legend hover began.
    pub fn legend_hover_start(&self) -> f64 {
        self.legend_hover_start
    }

    /// Set the hovered legend row and restart the animation when it changes.
    pub fn set_legend_hover(&mut self, series: Option<usize>, now: f64) {
        if series != self.legend_hover {
            self.legend_hover = series;
            self.legend_hover_start = now;
        }
    }

    /// The series whose legend row is under the pointer, if any.
    pub fn hovered_series(&self) -> Option<usize> {
        self.legend_hover
    }

    /// Fit the view to the data again.
    pub fn reset_view(&mut self) {
        self.view = None;
        self.y2_view = None;
    }

    /// Whether the view follows the data (no zoom or pan since the last reset).
    pub fn is_auto(&self) -> bool {
        self.view.is_none()
    }

    /// The explicit view, or `None` while automatic.
    pub fn view(&self) -> Option<Bounds> {
        self.view
    }

    /// Show `bounds` (data coordinates, linear axes) on the x and left y axes.
    pub fn set_view(&mut self, bounds: Bounds) {
        self.view = Some(bounds);
    }

    /// Show `min..=max` (data coordinates, linear axis) on the right y axis.
    pub fn set_y2_view(&mut self, min: f64, max: f64) {
        self.y2_view = Some([min.min(max), min.max(max)]);
    }

    /// The filter/transform pipeline.
    pub fn pipeline(&self) -> &Pipeline {
        &self.pipeline
    }

    /// The filter/transform pipeline, mutably.
    pub fn pipeline_mut(&mut self) -> &mut Pipeline {
        &mut self.pipeline
    }

    /// Enable or disable one filter.
    pub fn toggle_filter(&mut self, filter: FilterKind) {
        self.pipeline.toggle_filter(filter);
    }

    /// Enable or disable one filter explicitly.
    pub fn set_filter(&mut self, filter: FilterKind, enabled: bool) {
        self.pipeline.set_filter(filter, enabled);
    }

    /// Replace the transform.
    pub fn set_transform(&mut self, transform: Option<TransformKind>) {
        self.pipeline.set_transform(transform);
    }

    /// Disable every filter and transform.
    pub fn clear_analysis(&mut self) {
        self.pipeline.clear();
    }

    /// Pin the tool ribbon open or let it unroll on hover.
    pub fn pin_toolbar(&mut self, pinned: bool) {
        self.toolbar_pinned = pinned;
        if pinned {
            self.toolbar_reveal = 1.0;
        }
    }

    /// Collapse the ribbon and unpin it.
    pub fn collapse_toolbar(&mut self) {
        self.toolbar_pinned = false;
        self.toolbar_reveal = 0.0;
    }

    /// Where the legend was dragged to, as fractions of the room around it.
    pub fn legend_position(&self) -> Option<[f32; 2]> {
        self.legend_pos
    }

    /// Place the legend; `None` returns it to its configured corner.
    pub fn set_legend_position(&mut self, position: Option<[f32; 2]>) {
        self.legend_pos = position.map(|[x, y]| [x.clamp(0.0, 1.0), y.clamp(0.0, 1.0)]);
    }

    /// Whether the legend has hidden the series called `name`.
    pub fn is_hidden(&self, name: &str) -> bool {
        self.hidden.iter().any(|hidden| hidden == name)
    }

    /// Show or hide a series by name.
    pub fn set_hidden(&mut self, name: &str, hidden: bool) {
        self.hidden.retain(|entry| entry != name);
        if hidden {
            self.hidden.push(name.to_owned());
        }
    }

    /// Whether the view or the analysis would be cleared by a reset.
    pub fn has_overlays(&self) -> bool {
        self.pipeline.is_active() || self.selection.is_some()
    }
}

/// The scaled range of the right axis, when set.
pub fn scaled_y2(bounds: Option<[f64; 2]>, scale: Scale) -> Option<[f64; 2]> {
    bounds.map(|[min, max]| [scale.inverse(min), scale.inverse(max)])
}