liveplot 2.0.1

Realtime interactive plotting library using egui/eframe, with optional gRPC and Parquet export support.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//! Scope data: axis settings, display state, and coordinate management.

use crate::data::trace_look::TraceLook;
use crate::data::traces::{TraceData, TraceRef, TracesCollection};
use crate::data::x_formatter::{TimeFormatter, XFormatter};
use std::collections::{HashMap, VecDeque};

/// Formatting options for the x-value (time) shown in point labels.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum XDateFormat {
    /// Local time with date, ISO8601-like: YYYY-MM-DD HH:MM:SS
    Iso8601WithDate,
    /// Local time, time-of-day only: HH:MM:SS
    Iso8601Time,
}

impl Default for XDateFormat {
    fn default() -> Self {
        XDateFormat::Iso8601Time
    }
}

impl XDateFormat {
    /// Format an `x` value (seconds since UNIX epoch as f64) according to the selected format.
    pub fn format_value(&self, x_seconds: f64) -> String {
        let secs = x_seconds as i64;
        let nsecs = ((x_seconds - secs as f64) * 1e9) as u32;
        let dt_utc = chrono::DateTime::from_timestamp(secs, nsecs)
            .unwrap_or_else(|| chrono::DateTime::from_timestamp(0, 0).unwrap());
        match self {
            XDateFormat::Iso8601WithDate => dt_utc
                .with_timezone(&chrono::Local)
                .format("%Y-%m-%d %H:%M:%S")
                .to_string(),
            XDateFormat::Iso8601Time => dt_utc
                .with_timezone(&chrono::Local)
                .format("%H:%M:%S")
                .to_string(),
        }
    }
}

/// Axis type enum: Time or Value (Value holds optional unit).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AxisType {
    Time(XDateFormat),
    Value(Option<String>),
}

/// Settings for a single axis (X or Y).
#[derive(Clone, Debug)]
pub struct AxisSettings {
    pub log_scale: bool,
    pub name: Option<String>,
    pub bounds: (f64, f64),
    pub auto_fit: bool,
    pub axis_type: AxisType,
    /// Controls how X (and incidentally Y) values are formatted for tick labels
    /// and cursor readouts. Defaults to [`XFormatter::Auto`] which picks the
    /// appropriate formatter based on [`axis_type`](Self::axis_type).
    pub x_formatter: XFormatter,
}

impl Default for AxisSettings {
    fn default() -> Self {
        Self {
            log_scale: false,
            name: None,
            bounds: (0.0, 1.0),
            auto_fit: false,
            axis_type: AxisType::Value(None),
            x_formatter: XFormatter::Auto,
        }
    }
}

impl AxisSettings {
    pub fn new_time_axis() -> Self {
        Self {
            name: Some("Time".to_string()),
            axis_type: AxisType::Time(XDateFormat::default()),
            ..Default::default()
        }
    }

    /// Get the unit for this axis. Returns "s" for time axes and the configured unit for value axes.
    pub fn get_unit(&self) -> Option<String> {
        match &self.axis_type {
            AxisType::Time(_) => Some("s".to_string()),
            AxisType::Value(unit) => unit.clone(),
        }
    }

    /// Set the unit for value axes. For time axes this is a no-op.
    pub fn set_unit(&mut self, unit: Option<String>) {
        match &mut self.axis_type {
            AxisType::Time(_) => {}
            AxisType::Value(existing) => *existing = unit,
        }
    }

    /// Format a numeric value with unit, using scientific notation when appropriate.
    fn format_value_numeric(&self, v: f64, dec_pl: usize, step: f64) -> String {
        // Decide scientific formatting based on step magnitude vs precision:
        // - Use scientific if step < 10^-dec_pl (too fine to show with dec_pl)
        // - Or if step >= 10^dec_pl (too large; many digits before decimal)
        let sci = if step.is_finite() && step != 0.0 {
            let exp = step.abs().log10().floor() as i32;
            exp < -(dec_pl as i32) || exp >= dec_pl as i32
        } else {
            false
        };

        let formatted = if sci {
            if v == 0.0 || !v.is_finite() {
                // Just show the value as-is with requested precision if zero/NaN/inf
                format!("{:.*}", dec_pl, v)
            } else {
                // Create a compact scientific representation like 1.23e5 (no +00 padding)
                let sign = if v.is_sign_negative() { -1.0 } else { 1.0 };
                let av = v.abs();
                let exp = av.log10().floor() as i32;
                let pow = 10f64.powi(exp);
                let mant = sign * (av / pow);
                if exp == 0 {
                    format!("{:.*}", dec_pl, mant)
                } else {
                    format!("{:.*}e{}", dec_pl, mant, exp)
                }
            }
        } else {
            format!("{:.*}", dec_pl, v)
        };

        if let Some(unit) = self.get_unit() {
            format!("{} {}", formatted, unit)
        } else {
            formatted
        }
    }

    #[allow(dead_code)]
    fn format_time_with_precision(fmt: XDateFormat, v: f64, step: f64) -> String {
        // Choose base format (date vs time-of-day) using the same threshold as before
        let use_date = step.is_finite() && step >= 86400.0;

        // Compute total nanoseconds rounded to nearest ns to handle fractional seconds correctly
        let total_ns = (v * 1e9).round() as i128;
        let secs = (total_ns / 1_000_000_000) as i64;
        let nsecs = (total_ns % 1_000_000_000) as u32;

        let dt_utc = chrono::DateTime::from_timestamp(secs, nsecs)
            .unwrap_or_else(|| chrono::DateTime::from_timestamp(0, 0).unwrap());
        let local = dt_utc.with_timezone(&chrono::Local);

        // Decide fractional precision based on sampling step (bounds). Show more precision for
        // smaller steps: seconds, ms, us, ns.
        let frac_digits = if !step.is_finite() || step >= 1.0 {
            0
        } else if step >= 1e-3 {
            3
        } else if step >= 1e-6 {
            6
        } else {
            9
        };

        // Base formatting
        let base = if use_date {
            // include date portion
            local.format("%Y-%m-%d %H:%M:%S").to_string()
        } else {
            match fmt {
                XDateFormat::Iso8601WithDate => local.format("%Y-%m-%d %H:%M:%S").to_string(),
                XDateFormat::Iso8601Time => local.format("%H:%M:%S").to_string(),
            }
        };

        if frac_digits == 0 {
            base
        } else {
            // Extract fractional digits from nsecs rounded above
            let frac_value = match frac_digits {
                3 => (nsecs / 1_000_000) as u32,
                6 => (nsecs / 1_000) as u32,
                9 => nsecs,
                _ => 0,
            };
            format!("{}.{:0width$}", base, frac_value, width = frac_digits)
        }
    }

    /// Format a value, with special handling for time axes.
    ///
    /// The `x_formatter` field controls the exact rendering mode. When set to
    /// `XFormatter::Auto` the behaviour matches the legacy logic:
    /// * time axes → [`TimeFormatter`] driven by [`bounds`](Self::bounds) (the visible X range).
    /// * value axes → adaptive decimal / scientific notation.
    pub fn format_value(&self, v: f64, dec_pl: usize, step: f64) -> String {
        match &self.x_formatter {
            XFormatter::Auto => match self.axis_type {
                AxisType::Time(_fmt) => {
                    // Use the stored visible bounds for date-change detection;
                    // fall back to step-based precision for tick granularity.
                    let tf = TimeFormatter::default();
                    // Prefer self.bounds for the visible range, but if bounds
                    // are degenerate (zero-width), fall back to step.
                    let range = if (self.bounds.1 - self.bounds.0).abs() > 1e-15 {
                        self.bounds
                    } else {
                        // Construct a symmetric window around v using step
                        (v - step * 0.5, v + step * 0.5)
                    };
                    tf.format(v, range)
                }
                AxisType::Value(_) => self.format_value_numeric(v, dec_pl, step),
            },
            XFormatter::Decimal(df) => df.format(v, dec_pl),
            XFormatter::Scientific(sf) => sf.format(v, dec_pl),
            XFormatter::Time(tf) => {
                let range = if (self.bounds.1 - self.bounds.0).abs() > 1e-15 {
                    self.bounds
                } else {
                    (v - step * 0.5, v + step * 0.5)
                };
                tf.format(v, range)
            }
        }
    }
}

/// Scope type: time-based or XY mode.
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub enum ScopeType {
    TimeScope,
    XYScope,
}

/// Central state for the scope display.
pub struct ScopeData {
    pub id: usize,
    pub name: String,
    pub y_axis: AxisSettings,
    pub x_axis: AxisSettings,
    pub time_window: f64,
    pub scope_type: ScopeType,
    pub xy_pairs: Vec<(Option<TraceRef>, Option<TraceRef>, TraceLook)>,
    pub paused: bool,
    pub show_legend: bool,
    /// When `true`, the legend is unconditionally hidden regardless of `show_legend`.
    /// Useful for compact/embedded layouts where an overlay legend wastes space.
    pub force_hide_legend: bool,
    pub show_info_in_legend: bool,
    /// When `true`, the plot background grid is visible.
    pub show_grid: bool,

    /// When `true`, Y-axis bounds are automatically fitted to the visible data
    /// each frame. Manual pan/zoom disables this; clicking "Fit to View" or
    /// double-clicking re-enables it. Default: `true`.
    pub auto_fit_to_view: bool,
    /// When `true`, auto-fit only *expands* the view — it never shrinks.
    /// Historical peaks remain visible. Default: `false`.
    pub keep_max_fit: bool,

    pub trace_order: Vec<TraceRef>,
    pub clicked_point: Option<[f64; 2]>,
    /// When `true`, clicking while paused sets `clicked_point` without resuming.
    /// Set by the measurement panel when measurements exist.
    pub measurement_active: bool,
    /// If `true`, clicking the plot toggles pause/resume. Set to `false` to
    /// completely disable this default interaction (useful for embedded or
    /// interactive applications that handle pausing externally).
    pub pause_on_click: bool,
    /// X-coordinate range of active measurement points on this scope.
    /// Set by the measurement panel each frame so that `live_update` can
    /// extend `x_axis.bounds` to keep measurement markers in view after
    /// the scope is resumed.
    pub measurement_x_range: Option<(f64, f64)>,
}

impl Default for ScopeData {
    fn default() -> Self {
        Self {
            id: 0,
            name: "Scope".to_string(),
            y_axis: AxisSettings::default(),
            x_axis: AxisSettings::new_time_axis(),
            time_window: 10.0,
            scope_type: ScopeType::TimeScope,
            xy_pairs: Vec::new(),
            paused: false,
            show_legend: true,
            force_hide_legend: false,
            show_info_in_legend: false,
            show_grid: true,
            auto_fit_to_view: true,
            keep_max_fit: false,
            trace_order: Vec::new(),
            clicked_point: None,
            measurement_active: false,
            pause_on_click: false,
            measurement_x_range: None,
        }
    }
}

impl ScopeData {
    pub fn remove_trace(&mut self, trace: &TraceRef) {
        self.trace_order.retain(|t| t != trace);
        for (x, y, _look) in self.xy_pairs.iter_mut() {
            if x.as_ref() == Some(trace) {
                *x = None;
            }
            if y.as_ref() == Some(trace) {
                *y = None;
            }
        }
        self.xy_pairs.retain(|(x, y, _)| x.is_some() || y.is_some());
    }

    pub fn update(&mut self, traces: &TracesCollection) {
        // Keep trace_order in sync with current traces: drop missing, append new
        self.trace_order.retain(|n| traces.contains_key(n));

        // Keep XY pairs in sync with current traces.
        // Incomplete pairs (None) are allowed, but are not rendered/used until complete.
        self.xy_pairs.retain(|(x, y, _)| {
            let x_ok = x.as_ref().is_none_or(|t| traces.contains_key(t));
            let y_ok = y.as_ref().is_none_or(|t| traces.contains_key(t));
            x_ok && y_ok && !(x.is_none() && y.is_none())
        });

        if self.x_axis.auto_fit {
            self.fit_x_bounds(traces);
        }

        self.live_update(traces);

        if self.y_axis.auto_fit || self.auto_fit_to_view {
            self.fit_y_bounds(traces);
        }
    }

    fn live_update(&mut self, traces: &TracesCollection) {
        if self.scope_type == ScopeType::TimeScope {
            if !self.paused {
                // Use only traces assigned to this scope to determine the current time
                let now = self
                    .trace_order
                    .iter()
                    .filter_map(|name| traces.get_trace(name))
                    .filter_map(|trace| trace.live.back().map(|last| last[0]))
                    .fold(None, |acc: Option<f64>, val| {
                        Some(acc.map_or(val, |a: f64| a.max(val)))
                    })
                    .unwrap_or(self.time_window);
                let time_lower = now - self.time_window;
                // Extend the lower bound to keep any active measurement markers
                // visible. Without this, markers scroll off-screen after resuming
                // because set_plot_bounds_x forces the view to the current window.
                let x_lower = if let Some((m_min, _)) = self.measurement_x_range {
                    m_min.min(time_lower)
                } else {
                    time_lower
                };
                self.x_axis.bounds = (x_lower, now);
            } else {
                let diff = ((self.x_axis.bounds.1 - self.x_axis.bounds.0) - self.time_window) / 2.0;
                self.x_axis.bounds = (self.x_axis.bounds.0 + diff, self.x_axis.bounds.1 - diff);
            }
        }
    }

    pub fn fit_x_bounds(&mut self, traces: &TracesCollection) {
        if self.scope_type == ScopeType::XYScope && !self.xy_pairs.is_empty() {
            let mut min_x = f64::MAX;
            let mut max_x = f64::MIN;
            let tol = 1e-9_f64;

            for (x_name, y_name, _pair_look) in self.xy_pairs.iter() {
                let (Some(x_name), Some(y_name)) = (x_name.as_ref(), y_name.as_ref()) else {
                    continue;
                };

                let (Some(x_tr), Some(y_tr)) = (traces.get_trace(x_name), traces.get_trace(y_name))
                else {
                    continue;
                };
                if !x_tr.look.visible || !y_tr.look.visible {
                    continue;
                }

                let x_pts = traces.get_points(x_name, self.paused);
                let y_pts = traces.get_points(y_name, self.paused);
                let (Some(x_pts), Some(y_pts)) = (x_pts, y_pts) else {
                    continue;
                };

                let mut i = 0usize;
                let mut j = 0usize;
                while i < x_pts.len() && j < y_pts.len() {
                    let tx = x_pts[i][0];
                    let ty = y_pts[j][0];
                    let dt = tx - ty;
                    if dt.abs() <= tol {
                        let x = x_pts[i][1] + x_tr.offset;
                        if x < min_x {
                            min_x = x;
                        }
                        if x > max_x {
                            max_x = x;
                        }
                        i += 1;
                        j += 1;
                    } else if dt < 0.0 {
                        i += 1;
                    } else {
                        j += 1;
                    }
                }
            }

            if min_x < max_x {
                self.x_axis.bounds = (min_x, max_x);
                self.time_window = max_x - min_x;
            }
            return;
        }

        let mut min_x = f64::MAX;
        let mut max_x = f64::MIN;
        for name in self.trace_order.iter() {
            let Some(trace) = traces.get_trace(name) else {
                continue;
            };
            if !trace.look.visible {
                continue;
            }
            let points = if self.paused {
                if let Some(snap) = &trace.snap {
                    snap
                } else {
                    &trace.live
                }
            } else {
                &trace.live
            };
            for p in points.iter() {
                if p[0] < min_x {
                    min_x = p[0];
                }
                if p[0] > max_x {
                    max_x = p[0];
                }
            }
        }
        if min_x < max_x {
            self.x_axis.bounds = (min_x, max_x);
            self.time_window = max_x - min_x;
        } else if min_x == min_x {
            if min_x < 0.0 {
                self.y_axis.bounds = (min_x, 0.0);
                self.time_window = -min_x;
            } else if min_x > 0.0 {
                self.y_axis.bounds = (0.0, min_x);
                self.time_window = min_x;
            } else {
                // Both min and max are zero; set to -1.0 to 1.0
                self.y_axis.bounds = (-1.0, 1.0);
                self.time_window = 2.0;
            }
        }
    }

    pub fn fit_y_bounds(&mut self, traces: &TracesCollection) {
        if self.scope_type == ScopeType::XYScope && !self.xy_pairs.is_empty() {
            let mut min_y = f64::MAX;
            let mut max_y = f64::MIN;
            let tol = 1e-9_f64;

            for (x_name, y_name, _pair_look) in self.xy_pairs.iter() {
                let (Some(x_name), Some(y_name)) = (x_name.as_ref(), y_name.as_ref()) else {
                    continue;
                };

                let (Some(x_tr), Some(y_tr)) = (traces.get_trace(x_name), traces.get_trace(y_name))
                else {
                    continue;
                };
                if !x_tr.look.visible || !y_tr.look.visible {
                    continue;
                }

                let x_pts = traces.get_points(x_name, self.paused);
                let y_pts = traces.get_points(y_name, self.paused);
                let (Some(x_pts), Some(y_pts)) = (x_pts, y_pts) else {
                    continue;
                };

                let mut i = 0usize;
                let mut j = 0usize;
                while i < x_pts.len() && j < y_pts.len() {
                    let tx = x_pts[i][0];
                    let ty = y_pts[j][0];
                    let dt = tx - ty;
                    if dt.abs() <= tol {
                        let y = y_pts[j][1] + y_tr.offset;
                        if y < min_y {
                            min_y = y;
                        }
                        if y > max_y {
                            max_y = y;
                        }
                        i += 1;
                        j += 1;
                    } else if dt < 0.0 {
                        i += 1;
                    } else {
                        j += 1;
                    }
                }
            }

            if min_y < max_y {
                if self.keep_max_fit {
                    let cur = self.y_axis.bounds;
                    self.y_axis.bounds = (min_y.min(cur.0), max_y.max(cur.1));
                } else {
                    self.y_axis.bounds = (min_y, max_y);
                }
            }
            return;
        }

        let mut min_y = f64::MAX;
        let mut max_y = f64::MIN;
        let x_bounds = self.x_axis.bounds;
        for name in self.trace_order.iter() {
            let Some(trace) = traces.get_trace(name) else {
                continue;
            };
            if !trace.look.visible {
                continue;
            }
            let points = if self.paused {
                if let Some(snap) = &trace.snap {
                    snap
                } else {
                    &trace.live
                }
            } else {
                &trace.live
            };
            for p in points.iter() {
                if p[0] < x_bounds.0 {
                    continue;
                }
                if p[0] > x_bounds.1 {
                    break;
                }
                if p[1] + trace.offset < min_y {
                    min_y = p[1] + trace.offset;
                }
                if p[1] + trace.offset > max_y {
                    max_y = p[1] + trace.offset;
                }
            }
        }
        if min_y < max_y {
            if self.keep_max_fit {
                let cur = self.y_axis.bounds;
                self.y_axis.bounds = (min_y.min(cur.0), max_y.max(cur.1));
            } else {
                self.y_axis.bounds = (min_y, max_y);
            }
        } else if min_y == max_y {
            if min_y < 0.0 {
                self.y_axis.bounds = (min_y, 0.0);
            } else if min_y > 0.0 {
                self.y_axis.bounds = (0.0, max_y);
            } else {
                // Both min and max are zero; set to -1.0 to 1.0
                self.y_axis.bounds = (-1.0, 1.0);
            }
        }
    }

    pub fn fit_bounds(&mut self, traces: &TracesCollection) {
        self.fit_x_bounds(traces);
        self.fit_y_bounds(traces);
    }

    pub fn get_drawn_points(
        &self,
        name: &TraceRef,
        traces: &TracesCollection,
    ) -> Option<VecDeque<[f64; 2]>> {
        if let Some(trace) = traces.get_points(name, self.paused) {
            if self.scope_type == ScopeType::XYScope {
                Some(trace)
            } else {
                Some(TraceData::cap_by_x_bounds(&trace, self.x_axis.bounds))
            }
        } else {
            None
        }
    }

    pub fn get_all_drawn_points(
        &self,
        traces: &TracesCollection,
    ) -> HashMap<TraceRef, VecDeque<[f64; 2]>> {
        let mut result = HashMap::new();
        for name in self.trace_order.iter() {
            if let Some(pts) = self.get_drawn_points(name, traces) {
                result.insert(name.clone(), pts);
            }
        }
        result
    }
}