liveplot 2.1.1

Realtime interactive plotting library using egui/eframe, with optional gRPC and Parquet export support.
Documentation
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
//! State persistence: save and load application state to/from JSON files.
//!
//! This module provides serializable mirror types for UI state that cannot directly
//! derive serde traits (e.g., egui types like Color32, LineStyle).

use std::path::Path;

use serde::{Deserialize, Serialize};

#[cfg(feature = "fft")]
use crate::data::fft::FFTWindow;
use crate::data::math::MathTrace;
use crate::data::measurement::Measurement;
use crate::data::scope::{AxisSettings, ScopeData, ScopeType};
use crate::data::thresholds::{ThresholdDef, ThresholdKind};
use crate::data::trace_look::TraceLook;
use crate::data::traces::TraceRef;
use crate::data::triggers::{Trigger, TriggerSlope};
use crate::panels::color_scheme_ui::NamedCustomScheme;

fn default_axis_value_decimals() -> usize {
    4
}

fn default_axis_scientific_min_exp() -> i32 {
    -4
}

fn default_axis_scientific_max_exp() -> i32 {
    6
}

// ---------- Serializable mirror types ----------

/// Serializable version of AxisSettings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AxisSettingsSerde {
    pub unit: Option<String>,
    /// "time" or "value"
    pub axis_type: String,
    /// Time format string (optional). Examples: "%H:%M:%S" or "%Y-%m-%d %H:%M:%S"
    pub time_format: Option<String>,
    pub log_scale: bool,
    pub name: Option<String>,
    pub bounds: [f64; 2],
    pub auto_fit: bool,
    #[serde(default)]
    pub keep_max_fit: bool,
    #[serde(default = "default_axis_value_decimals")]
    pub value_decimals: usize,
    #[serde(default = "default_axis_scientific_min_exp")]
    pub scientific_min_exp: i32,
    #[serde(default = "default_axis_scientific_max_exp")]
    pub scientific_max_exp: i32,
    #[serde(default)]
    pub always_scientific: bool,
    #[serde(default)]
    pub show_label: bool,
}

impl From<&AxisSettings> for AxisSettingsSerde {
    fn from(a: &AxisSettings) -> Self {
        use crate::data::scope::{AxisType, TimeFormat};
        let (
            axis_type,
            time_format,
            unit,
            scientific_min_exp,
            scientific_max_exp,
            always_scientific,
        ) = match &a.axis_type {
            AxisType::Value(vf) => (
                "value".to_string(),
                None,
                vf.unit.clone(),
                vf.scientific_min_exp,
                vf.scientific_max_exp,
                vf.always_scientific,
            ),
            AxisType::Time(fmt) => (
                "time".to_string(),
                Some(match fmt {
                    TimeFormat::Iso8601WithDate => "%Y-%m-%d %H:%M:%S".to_string(),
                    TimeFormat::Iso8601Time => "%H:%M:%S".to_string(),
                    TimeFormat::MinuteSecondMillis => "%M:%S".to_string(),
                    TimeFormat::SecondMillis => "%S".to_string(),
                    TimeFormat::MillisOnly => "%f".to_string(),
                }),
                None,
                default_axis_scientific_min_exp(),
                default_axis_scientific_max_exp(),
                false,
            ),
        };
        Self {
            unit,
            axis_type,
            time_format,
            log_scale: a.log_scale,
            name: a.name.clone(),
            bounds: [a.bounds.0, a.bounds.1],
            auto_fit: a.auto_fit,
            keep_max_fit: a.keep_max_fit,
            value_decimals: a.value_decimals,
            scientific_min_exp,
            scientific_max_exp,
            always_scientific,
            show_label: a.show_label,
        }
    }
}

impl AxisSettingsSerde {
    /// Apply stored settings to an AxisSettings instance.
    pub fn apply_to(self, a: &mut AxisSettings) {
        use crate::data::scope::{AxisType, TimeFormat, ValueFormat};
        a.log_scale = self.log_scale;
        a.name = self.name;
        a.bounds = (self.bounds[0], self.bounds[1]);
        a.auto_fit = self.auto_fit;
        a.keep_max_fit = self.keep_max_fit;
        match self.axis_type.as_str() {
            "time" => {
                let fmt = if let Some(tf) = &self.time_format {
                    if tf == "%M:%S%.3f" {
                        TimeFormat::MinuteSecondMillis
                    } else if tf == "%S%.3f" {
                        TimeFormat::SecondMillis
                    } else if tf == "%f" {
                        TimeFormat::MillisOnly
                    } else if tf.contains("%Y") {
                        TimeFormat::Iso8601WithDate
                    } else {
                        TimeFormat::Iso8601Time
                    }
                } else {
                    TimeFormat::default()
                };
                a.axis_type = AxisType::Time(fmt);
            }
            _ => {
                a.axis_type = AxisType::Value(ValueFormat {
                    scientific_min_exp: self.scientific_min_exp,
                    scientific_max_exp: self.scientific_max_exp,
                    always_scientific: self.always_scientific,
                    unit: self.unit.clone(),
                });
            }
        }
        a.value_decimals = self.value_decimals;
        a.show_label = self.show_label;
    }
}

/// Serializable version of egui_plot::LineStyle.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SerLineStyle {
    Solid,
    Dashed { length: f32 },
    Dotted { spacing: f32 },
}

/// Serializable version of egui_plot::MarkerShape.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SerMarkerShape {
    Circle,
    Square,
    Diamond,
    Cross,
    Plus,
    Asterisk,
    Up,
    Down,
    Left,
    Right,
}

/// Serializable version of TraceLook.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraceLookSerde {
    pub color_rgba: [u8; 4],
    pub visible: bool,
    pub width: f32,
    pub show_points: bool,
    pub highlight_newest_point: bool,
    pub style: SerLineStyle,
    pub point_size: f32,
    pub marker: SerMarkerShape,
}

impl From<&TraceLook> for TraceLookSerde {
    fn from(l: &TraceLook) -> Self {
        use egui_plot::LineStyle;
        use egui_plot::MarkerShape;
        let style = match l.style {
            LineStyle::Solid => SerLineStyle::Solid,
            LineStyle::Dashed { length } => SerLineStyle::Dashed { length },
            LineStyle::Dotted { spacing } => SerLineStyle::Dotted { spacing },
        };
        let marker = match l.marker {
            MarkerShape::Circle => SerMarkerShape::Circle,
            MarkerShape::Square => SerMarkerShape::Square,
            MarkerShape::Diamond => SerMarkerShape::Diamond,
            MarkerShape::Cross => SerMarkerShape::Cross,
            MarkerShape::Plus => SerMarkerShape::Plus,
            MarkerShape::Asterisk => SerMarkerShape::Asterisk,
            MarkerShape::Up => SerMarkerShape::Up,
            MarkerShape::Down => SerMarkerShape::Down,
            MarkerShape::Left => SerMarkerShape::Left,
            MarkerShape::Right => SerMarkerShape::Right,
        };
        Self {
            color_rgba: [l.color.r(), l.color.g(), l.color.b(), l.color.a()],
            visible: l.visible,
            width: l.width,
            show_points: l.show_points,
            highlight_newest_point: l.highlight_newest_point,
            style,
            point_size: l.point_size,
            marker,
        }
    }
}

impl TraceLookSerde {
    /// Convert back to a TraceLook.
    pub fn into_look(self) -> TraceLook {
        use egui::Color32;
        use egui_plot::LineStyle;
        use egui_plot::MarkerShape;
        let style = match self.style {
            SerLineStyle::Solid => LineStyle::Solid,
            SerLineStyle::Dashed { length } => LineStyle::Dashed { length },
            SerLineStyle::Dotted { spacing } => LineStyle::Dotted { spacing },
        };
        let marker = match self.marker {
            SerMarkerShape::Circle => MarkerShape::Circle,
            SerMarkerShape::Square => MarkerShape::Square,
            SerMarkerShape::Diamond => MarkerShape::Diamond,
            SerMarkerShape::Cross => MarkerShape::Cross,
            SerMarkerShape::Plus => MarkerShape::Plus,
            SerMarkerShape::Asterisk => MarkerShape::Asterisk,
            SerMarkerShape::Up => MarkerShape::Up,
            SerMarkerShape::Down => MarkerShape::Down,
            SerMarkerShape::Left => MarkerShape::Left,
            SerMarkerShape::Right => MarkerShape::Right,
        };
        TraceLook {
            color: Color32::from_rgba_unmultiplied(
                self.color_rgba[0],
                self.color_rgba[1],
                self.color_rgba[2],
                self.color_rgba[3],
            ),
            visible: self.visible,
            width: self.width,
            show_points: self.show_points,
            highlight_newest_point: self.highlight_newest_point,
            style,
            point_size: self.point_size,
            marker,
        }
    }
}

/// Serializable trace style entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraceStyleSerde {
    pub name: String,
    pub look: TraceLookSerde,
    pub offset: f64,
}

/// Serializable trigger slope.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SerTriggerSlope {
    Rising,
    Falling,
    Any,
}

impl From<TriggerSlope> for SerTriggerSlope {
    fn from(s: TriggerSlope) -> Self {
        match s {
            TriggerSlope::Rising => SerTriggerSlope::Rising,
            TriggerSlope::Falling => SerTriggerSlope::Falling,
            TriggerSlope::Any => SerTriggerSlope::Any,
        }
    }
}

impl From<SerTriggerSlope> for TriggerSlope {
    fn from(s: SerTriggerSlope) -> Self {
        match s {
            SerTriggerSlope::Rising => TriggerSlope::Rising,
            SerTriggerSlope::Falling => TriggerSlope::Falling,
            SerTriggerSlope::Any => TriggerSlope::Any,
        }
    }
}

/// Serializable trigger definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TriggerSerde {
    pub name: String,
    pub target: String,
    pub enabled: bool,
    pub level: f64,
    pub slope: SerTriggerSlope,
    pub single_shot: bool,
    pub trigger_position: f64,
    pub look: TraceLookSerde,
    /// Holdoff time in seconds.
    #[serde(default)]
    pub holdoff_secs: f64,
}

impl TriggerSerde {
    /// Create from a Trigger.
    pub fn from_trigger(t: &Trigger) -> Self {
        Self {
            name: t.name.clone(),
            target: t.target.0.clone(),
            enabled: t.enabled,
            level: t.level,
            slope: SerTriggerSlope::from(t.slope),
            single_shot: t.single_shot,
            trigger_position: t.trigger_position,
            look: TraceLookSerde::from(&t.look),
            holdoff_secs: t.holdoff_secs,
        }
    }

    /// Convert back to a Trigger.
    pub fn into_trigger(self) -> Trigger {
        let mut t = Trigger::default();
        t.name = self.name;
        t.target = TraceRef(self.target);
        t.enabled = self.enabled;
        t.level = self.level;
        t.slope = TriggerSlope::from(self.slope);
        t.single_shot = self.single_shot;
        t.trigger_position = self.trigger_position;
        t.look = self.look.into_look();
        t.holdoff_secs = self.holdoff_secs;
        t
    }
}

/// Serializable threshold definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThresholdSerde {
    pub name: String,
    pub target: String,
    pub kind: ThresholdKind,
    pub min_duration_s: f64,
    pub max_events: usize,
    pub look: TraceLookSerde,
    pub start_look: TraceLookSerde,
    pub stop_look: TraceLookSerde,
}

impl ThresholdSerde {
    /// Create from a ThresholdDef.
    pub fn from_threshold(d: &ThresholdDef) -> Self {
        Self {
            name: d.name.clone(),
            target: d.target.0.clone(),
            kind: d.kind.clone(),
            min_duration_s: d.min_duration_s,
            max_events: d.max_events,
            look: TraceLookSerde::from(&d.look),
            start_look: TraceLookSerde::from(&d.start_look),
            stop_look: TraceLookSerde::from(&d.stop_look),
        }
    }

    /// Convert back to a ThresholdDef.
    pub fn into_threshold(self) -> ThresholdDef {
        let mut d = ThresholdDef::default();
        d.name = self.name;
        d.target = TraceRef(self.target);
        d.kind = self.kind;
        d.min_duration_s = self.min_duration_s;
        d.max_events = self.max_events;
        d.look = self.look.into_look();
        d.start_look = self.start_look.into_look();
        d.stop_look = self.stop_look.into_look();
        d
    }
}

/// Serializable XY pair entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct XYPairSerde {
    pub x: Option<String>,
    pub y: Option<String>,
    pub look: TraceLookSerde,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ScopeLayoutDirectionSerde {
    Horizontal,
    Vertical,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ScopeLayoutNodeSerde {
    Pane {
        scope_id: usize,
    },
    Tabs {
        #[serde(default)]
        active_scope_id: Option<usize>,
        children: Vec<ScopeLayoutNodeSerde>,
    },
    Linear {
        direction: ScopeLayoutDirectionSerde,
        children: Vec<ScopeLayoutNodeSerde>,
    },
}

/// Serializable scope state.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScopeStateSerde {
    pub x_axis: AxisSettingsSerde,
    pub y_axis: AxisSettingsSerde,
    pub time_window: f64,
    pub scope_is_xy: bool,
    pub show_legend: bool,
    pub show_info_in_legend: bool,
    /// Position of the legend within the plot area.
    #[serde(default)]
    pub legend_position: crate::data::scope::LegendPosition,
    /// Scope id (for multi-scope layouts).
    #[serde(default)]
    pub id: Option<usize>,
    /// Scope display name.
    #[serde(default)]
    pub name: Option<String>,
    /// Ordered list of trace names assigned to this scope (time-scope mode).
    #[serde(default)]
    pub trace_order: Vec<String>,
    /// XY pair assignments (xy-scope mode).
    #[serde(default)]
    pub xy_pairs: Vec<XYPairSerde>,
    /// Whether clicks should pause/resume the scope. Defaults to `false` when
    /// absent so the behaviour is opt-in on new installs.
    #[serde(default)]
    pub pause_on_click: bool,
    /// Whether this scope shows its controls in the toolbar.
    #[serde(default)]
    pub controls_in_toolbar: bool,
    /// Scroll-wheel zoom mode for this scope.
    #[serde(default)]
    pub zoom_mode: crate::panels::scope_ui::ZoomMode,
}

impl From<&ScopeData> for ScopeStateSerde {
    fn from(s: &ScopeData) -> Self {
        Self {
            x_axis: AxisSettingsSerde::from(&s.x_axis),
            y_axis: AxisSettingsSerde::from(&s.y_axis),
            time_window: s.time_window,
            scope_is_xy: matches!(s.scope_type, ScopeType::XYScope),
            show_legend: s.show_legend,
            show_info_in_legend: s.show_info_in_legend,
            legend_position: s.legend_position,
            id: Some(s.id),
            name: Some(s.name.clone()),
            trace_order: s.trace_order.iter().map(|t| t.0.clone()).collect(),
            xy_pairs: s
                .xy_pairs
                .iter()
                .map(|(x, y, look)| XYPairSerde {
                    x: x.as_ref().map(|t| t.0.clone()),
                    y: y.as_ref().map(|t| t.0.clone()),
                    look: TraceLookSerde::from(look),
                })
                .collect(),
            pause_on_click: s.pause_on_click,
            controls_in_toolbar: false,
            zoom_mode: crate::panels::scope_ui::ZoomMode::default(),
        }
    }
}

impl From<&crate::panels::scope_ui::ScopePanel> for ScopeStateSerde {
    fn from(panel: &crate::panels::scope_ui::ScopePanel) -> Self {
        let mut state = Self::from(panel.get_data());
        state.controls_in_toolbar = panel.controls_in_toolbar();
        state.zoom_mode = panel.zoom_mode();
        state
    }
}

impl ScopeStateSerde {
    /// Apply stored settings to a ScopeData instance.
    pub fn apply_to(self, scope: &mut ScopeData) {
        self.x_axis.apply_to(&mut scope.x_axis);
        self.y_axis.apply_to(&mut scope.y_axis);
        scope.time_window = self.time_window;
        scope.scope_type = if self.scope_is_xy {
            ScopeType::XYScope
        } else {
            ScopeType::TimeScope
        };
        scope.show_legend = self.show_legend;
        scope.show_info_in_legend = self.show_info_in_legend;
        scope.legend_position = self.legend_position;
        if let Some(name) = self.name {
            scope.name = name;
        }
        if !self.trace_order.is_empty() {
            scope.trace_order = self.trace_order.into_iter().map(TraceRef).collect();
        }
        if !self.xy_pairs.is_empty() {
            scope.xy_pairs = self
                .xy_pairs
                .into_iter()
                .map(|p| (p.x.map(TraceRef), p.y.map(TraceRef), p.look.into_look()))
                .collect();
        }
        scope.pause_on_click = self.pause_on_click;
    }

    /// Apply stored settings to a full scope panel, including UI-only state.
    pub fn apply_to_panel(self, panel: &mut crate::panels::scope_ui::ScopePanel) {
        let controls_in_toolbar = self.controls_in_toolbar;
        let zoom_mode = self.zoom_mode;
        self.apply_to(panel.get_data_mut());
        panel.set_controls_in_toolbar(controls_in_toolbar);
        panel.set_zoom_mode(zoom_mode);
    }
}

#[cfg(feature = "fft")]
fn default_zero_pad_factor() -> usize {
    1
}

#[cfg(feature = "fft")]
fn default_recompute_interval_ms() -> u64 {
    100
}

#[cfg(feature = "fft")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FftPanelStateSerde {
    pub fft_size: usize,
    pub fft_window: String,
    pub fft_db: bool,
    #[serde(default = "default_zero_pad_factor")]
    pub zero_pad_factor: usize,
    #[serde(default = "default_recompute_interval_ms")]
    pub recompute_interval_ms: u64,
    pub scope: ScopeStateSerde,
}

#[cfg(feature = "fft")]
impl FftPanelStateSerde {
    pub fn from_panel(panel: &crate::panels::fft_ui::FftPanel) -> Self {
        Self {
            fft_size: panel.fft_data.fft_size,
            fft_window: panel.fft_data.fft_window.label().to_string(),
            fft_db: panel.fft_db,
            zero_pad_factor: panel.fft_data.zero_pad_factor,
            recompute_interval_ms: panel.fft_data.recompute_interval_ms,
            scope: ScopeStateSerde::from(&panel.scope_ui),
        }
    }

    pub fn apply_to_panel(&self, panel: &mut crate::panels::fft_ui::FftPanel) {
        panel.fft_data.fft_size = self.fft_size;
        panel.fft_data.fft_window = match self.fft_window.as_str() {
            "Rect" => FFTWindow::Rect,
            "Hamming" => FFTWindow::Hamming,
            "Blackman" => FFTWindow::Blackman,
            _ => FFTWindow::Hann,
        };
        panel.fft_db = self.fft_db;
        panel.fft_data.zero_pad_factor = self.zero_pad_factor;
        panel.fft_data.recompute_interval_ms = self.recompute_interval_ms;
        self.scope.clone().apply_to_panel(&mut panel.scope_ui);
        // FFT panel always uses RightTop legend position
        panel.scope_ui.get_data_mut().legend_position =
            crate::data::scope::LegendPosition::RightTop;
        panel.scope_ui.get_data_mut().show_legend = true;
    }
}

/// Panel visibility state.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PanelVisSerde {
    pub title: String,
    pub visible: bool,
    pub detached: bool,
    pub window_pos: Option<[f32; 2]>,
    pub window_size: Option<[f32; 2]>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MeasurementPanelStateSerde {
    #[serde(default)]
    pub measurements: Vec<Measurement>,
    #[serde(default)]
    pub selected_measurement: Option<usize>,
}

impl MeasurementPanelStateSerde {
    pub fn from_panel(panel: &crate::panels::measurment_ui::MeasurementPanel) -> Self {
        Self {
            measurements: panel.measurements().to_vec(),
            selected_measurement: panel.selected_measurement_index(),
        }
    }

    pub fn apply_to_panel(&self, panel: &mut crate::panels::measurment_ui::MeasurementPanel) {
        panel.restore_measurements(self.measurements.clone(), self.selected_measurement);
    }
}

/// Full application state (for save/load).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppStateSerde {
    pub window_size: Option<[f32; 2]>,
    pub window_pos: Option<[f32; 2]>,
    /// Legacy single-scope field for backward compatibility.
    #[serde(default, skip_serializing)]
    pub scope: Option<ScopeStateSerde>,
    /// All scope states (replaces `scope` for new saves).
    #[serde(default)]
    pub scopes: Vec<ScopeStateSerde>,
    /// Optional scope layout tree (tabs/splits) for restoring arrangement.
    #[serde(default)]
    pub scope_layout: Option<ScopeLayoutNodeSerde>,
    pub panels: Vec<PanelVisSerde>,
    pub traces_style: Vec<TraceStyleSerde>,
    pub thresholds: Vec<ThresholdSerde>,
    pub triggers: Vec<TriggerSerde>,
    /// Math trace definitions.
    #[serde(default)]
    pub math_traces: Vec<MathTrace>,
    #[serde(default)]
    pub measurements: Option<MeasurementPanelStateSerde>,
    /// Next scope index counter for consistent naming.
    #[serde(default)]
    pub next_scope_idx: Option<usize>,
    /// User-defined custom color schemes.
    #[serde(default)]
    pub custom_color_schemes: Vec<NamedCustomScheme>,
    /// The currently active palette (colors being used/edited), even if not saved as a custom scheme.
    #[serde(default)]
    pub active_palette: Option<Vec<[u8; 3]>>,
    #[cfg(feature = "fft")]
    #[serde(default)]
    pub fft_panel: Option<FftPanelStateSerde>,
    /// Maximum number of data points per trace.
    #[serde(default = "default_max_points")]
    pub max_points: usize,
    /// Maximum age of data points in seconds (0 = disabled).
    #[serde(default = "default_max_age_secs")]
    pub max_age_secs: f64,
}

fn default_max_points() -> usize {
    10000
}

fn default_max_age_secs() -> f64 {
    0.0
}

impl AppStateSerde {
    /// Get all scope states, migrating legacy single-scope format if needed.
    pub fn all_scopes(&self) -> Vec<ScopeStateSerde> {
        if !self.scopes.is_empty() {
            self.scopes.clone()
        } else if let Some(s) = &self.scope {
            vec![s.clone()]
        } else {
            Vec::new()
        }
    }
}

impl Default for AppStateSerde {
    fn default() -> Self {
        Self {
            window_size: None,
            window_pos: None,
            scope: None,
            scopes: vec![ScopeStateSerde {
                x_axis: AxisSettingsSerde {
                    unit: None,
                    axis_type: "time".to_string(),
                    time_format: Some("%H:%M:%S".to_string()),
                    log_scale: false,
                    name: None,
                    bounds: [0.0, 1.0],
                    auto_fit: true,
                    keep_max_fit: false,
                    value_decimals: default_axis_value_decimals(),
                    scientific_min_exp: default_axis_scientific_min_exp(),
                    scientific_max_exp: default_axis_scientific_max_exp(),
                    always_scientific: false,
                    show_label: false,
                },
                y_axis: AxisSettingsSerde {
                    unit: None,
                    axis_type: "value".to_string(),
                    time_format: None,
                    log_scale: false,
                    name: None,
                    bounds: [0.0, 1.0],
                    auto_fit: true,
                    keep_max_fit: false,
                    value_decimals: default_axis_value_decimals(),
                    scientific_min_exp: default_axis_scientific_min_exp(),
                    scientific_max_exp: default_axis_scientific_max_exp(),
                    always_scientific: false,
                    show_label: false,
                },
                time_window: 10.0,
                scope_is_xy: false,
                show_legend: true,
                show_info_in_legend: false,
                legend_position: crate::data::scope::LegendPosition::default(),
                pause_on_click: false,
                controls_in_toolbar: true,
                zoom_mode: crate::panels::scope_ui::ZoomMode::default(),
                id: Some(0),
                name: Some("Scope".to_string()),
                trace_order: Vec::new(),
                xy_pairs: Vec::new(),
            }],
            scope_layout: None,
            panels: Vec::new(),
            traces_style: Vec::new(),
            thresholds: Vec::new(),
            triggers: Vec::new(),
            math_traces: Vec::new(),
            measurements: None,
            next_scope_idx: None,
            custom_color_schemes: Vec::new(),
            active_palette: None,
            #[cfg(feature = "fft")]
            fft_panel: None,
            max_points: default_max_points(),
            max_age_secs: default_max_age_secs(),
        }
    }
}

// ---------- Public API ----------

/// Serialize the application state as pretty JSON.
pub fn state_to_json(state: &AppStateSerde) -> Result<String, String> {
    serde_json::to_string_pretty(state).map_err(|e| e.to_string())
}

/// Deserialize application state from JSON.
pub fn state_from_json(json: &str) -> Result<AppStateSerde, String> {
    serde_json::from_str(json).map_err(|e| e.to_string())
}

/// Save the application state to a JSON file at the given path.
pub fn save_state_to_path(state: &AppStateSerde, path: &Path) -> Result<(), String> {
    let txt = state_to_json(state)?;
    std::fs::write(path, txt).map_err(|e| e.to_string())
}

/// Load the application state from a JSON file at the given path.
pub fn load_state_from_path(path: &Path) -> Result<AppStateSerde, String> {
    let txt = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
    state_from_json(&txt)
}

/// Helper to capture trace styles from a traces collection.
pub fn capture_trace_styles<'a>(
    trace_order: impl Iterator<Item = &'a TraceRef>,
    get_trace: impl Fn(&TraceRef) -> Option<(&TraceLook, f64)>,
) -> Vec<TraceStyleSerde> {
    trace_order
        .filter_map(|name| {
            get_trace(name).map(|(look, offset)| TraceStyleSerde {
                name: name.0.clone(),
                look: TraceLookSerde::from(look),
                offset,
            })
        })
        .collect()
}

/// Helper to apply trace styles to a traces collection.
pub fn apply_trace_styles(styles: &[TraceStyleSerde], mut apply: impl FnMut(&str, TraceLook, f64)) {
    for s in styles {
        apply(&s.name, s.look.clone().into_look(), s.offset);
    }
}