liveplot 2.0.5

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
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
//! TraceRef and TracesCollection: trace identity and data management.

use crate::data::trace_look::TraceLook;
use crate::sink::PlotCommand;
use serde::{Deserialize, Serialize};
use std::collections::{hash_map::Entry, HashMap, VecDeque};

/// Identifier for a trace by name.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct TraceRef(pub String);

impl Default for TraceRef {
    fn default() -> Self {
        TraceRef("".to_string())
    }
}

impl TraceRef {
    pub fn new<S: Into<String>>(name: S) -> Self {
        TraceRef(name.into())
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    pub fn into_string(self) -> String {
        self.0
    }
}

impl std::fmt::Display for TraceRef {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl std::cmp::Ord for TraceRef {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.0.cmp(&other.0)
    }
}

impl std::cmp::PartialOrd for TraceRef {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq<str> for TraceRef {
    fn eq(&self, other: &str) -> bool {
        self.0 == other
    }
}

impl PartialEq<String> for TraceRef {
    fn eq(&self, other: &String) -> bool {
        &self.0 == other
    }
}

impl PartialEq<TraceRef> for String {
    fn eq(&self, other: &TraceRef) -> bool {
        self == &other.0
    }
}

impl PartialEq<&str> for TraceRef {
    fn eq(&self, other: &&str) -> bool {
        self.0.as_str() == *other
    }
}

impl std::cmp::PartialOrd<str> for TraceRef {
    fn partial_cmp(&self, other: &str) -> Option<std::cmp::Ordering> {
        Some(self.0.as_str().cmp(other))
    }
}

impl std::ops::Deref for TraceRef {
    type Target = str;
    fn deref(&self) -> &str {
        &self.0
    }
}

impl AsRef<str> for TraceRef {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl std::borrow::Borrow<str> for TraceRef {
    fn borrow(&self) -> &str {
        &self.0
    }
}

impl From<&str> for TraceRef {
    fn from(s: &str) -> Self {
        TraceRef(s.to_string())
    }
}

impl From<String> for TraceRef {
    fn from(s: String) -> Self {
        TraceRef(s)
    }
}

impl From<TraceRef> for String {
    fn from(value: TraceRef) -> Self {
        value.0
    }
}

/// Collection of all traces with their data.
pub struct TracesCollection {
    traces: HashMap<TraceRef, TraceData>,
    pub max_points: usize,
    pub points_bounds: (usize, usize),
    /// Maximum age in seconds for retained points.  0.0 disables time-based pruning.
    pub max_age_secs: f64,
    /// Slider bounds for `max_age_secs`.
    pub max_age_bounds: (f64, f64),
    pub hover_trace: Option<TraceRef>,
    rx: Option<std::sync::mpsc::Receiver<PlotCommand>>,
    /// Mapping from numeric trace ID to trace name (for PlotCommand API)
    id_to_name: HashMap<u32, String>,
    /// Pending styles for traces that haven't been created yet.
    /// When a trace is loaded from a saved state, the style is stored here
    /// until the trace is created from incoming data.
    pending_styles: HashMap<String, (TraceLook, f64)>,
}

impl Default for TracesCollection {
    fn default() -> Self {
        Self {
            traces: HashMap::new(),
            max_points: 10_000,
            points_bounds: (100, 200000),
            max_age_secs: 0.0,
            max_age_bounds: (0.0, 3600.0),
            hover_trace: None,
            rx: None,
            id_to_name: HashMap::new(),
            pending_styles: HashMap::new(),
        }
    }
}

impl TracesCollection {
    pub fn new(rx: std::sync::mpsc::Receiver<PlotCommand>) -> Self {
        let mut instance = Self::default();
        instance.set_rx(rx);
        instance
    }

    pub fn set_rx(&mut self, rx: std::sync::mpsc::Receiver<PlotCommand>) {
        self.rx = Some(rx);
    }

    /// Store a pending style for a trace that may not exist yet.
    /// When the trace is created from incoming data, this style will be applied
    /// instead of the default palette color.
    pub fn set_pending_style(&mut self, name: &str, look: TraceLook, offset: f64) {
        // If the trace already exists, apply immediately
        let tref = TraceRef(name.to_string());
        if let Some(tr) = self.traces.get_mut(&tref) {
            tr.look = look;
            tr.offset = offset;
        } else {
            self.pending_styles.insert(name.to_string(), (look, offset));
        }
    }

    fn update_rx(&mut self) -> Vec<TraceRef> {
        let mut new_traces: Vec<TraceRef> = Vec::new();
        if let Some(rx) = &self.rx {
            while let Ok(cmd) = rx.try_recv() {
                match cmd {
                    PlotCommand::RegisterTrace { id, name, info } => {
                        self.id_to_name.insert(id, name.clone());
                        let tref = TraceRef(name.clone());
                        let new_index = self.next_color_index();
                        let pending = self.pending_styles.remove(name.as_str());
                        let entry = match self.traces.entry(tref.clone()) {
                            Entry::Occupied(entry) => entry.into_mut(),
                            Entry::Vacant(entry) => {
                                new_traces.push(tref.clone());
                                let (look, offset) =
                                    pending.unwrap_or((TraceLook::new(new_index), 0.0));
                                entry.insert(TraceData {
                                    look,
                                    offset,
                                    live: VecDeque::new(),
                                    snap: None,
                                    info: String::new(),
                                    creation_index: new_index,
                                    #[cfg(feature = "fft")]
                                    last_fft: None,
                                })
                            }
                        };
                        if let Some(inf) = info {
                            entry.info = inf;
                        }
                    }
                    PlotCommand::SetTraceInfo { trace_id, info } => {
                        if let Some(name) = self.id_to_name.get(&trace_id) {
                            let tref = TraceRef(name.clone());
                            if let Some(entry) = self.traces.get_mut(&tref) {
                                entry.info = info;
                            }
                        }
                    }
                    PlotCommand::Point { trace_id, point } => {
                        if let Some(name) = self.id_to_name.get(&trace_id).cloned() {
                            let tref = TraceRef(name.clone());
                            let new_index = self.next_color_index();
                            let pending = self.pending_styles.remove(name.as_str());
                            let entry = match self.traces.entry(tref.clone()) {
                                Entry::Occupied(entry) => entry.into_mut(),
                                Entry::Vacant(entry) => {
                                    new_traces.push(tref.clone());
                                    let (look, offset) =
                                        pending.unwrap_or((TraceLook::new(new_index), 0.0));
                                    entry.insert(TraceData {
                                        look,
                                        offset,
                                        live: VecDeque::new(),
                                        snap: None,
                                        info: String::new(),
                                        creation_index: new_index,
                                        #[cfg(feature = "fft")]
                                        last_fft: None,
                                    })
                                }
                            };
                            entry.live.push_back([point.x, point.y]);
                            if entry.live.len() > self.max_points {
                                entry.live.pop_front();
                            }
                        } else {
                            // Auto-register trace
                            let name = format!("trace-{}", trace_id);
                            self.id_to_name.insert(trace_id, name.clone());
                            let tref = TraceRef(name.clone());
                            let new_index = self.next_color_index();
                            let pending = self.pending_styles.remove(name.as_str());
                            let entry = self.traces.entry(tref.clone()).or_insert_with(|| {
                                new_traces.push(tref.clone());
                                let (look, offset) =
                                    pending.unwrap_or((TraceLook::new(new_index), 0.0));
                                TraceData {
                                    look,
                                    offset,
                                    live: VecDeque::new(),
                                    snap: None,
                                    info: String::new(),
                                    creation_index: new_index,
                                    #[cfg(feature = "fft")]
                                    last_fft: None,
                                }
                            });
                            entry.live.push_back([point.x, point.y]);
                        }
                    }
                    PlotCommand::Points { trace_id, points } => {
                        if let Some(name) = self.id_to_name.get(&trace_id).cloned() {
                            let tref = TraceRef(name.clone());
                            let new_index = self.next_color_index();
                            let pending = self.pending_styles.remove(name.as_str());
                            let entry = match self.traces.entry(tref.clone()) {
                                Entry::Occupied(entry) => entry.into_mut(),
                                Entry::Vacant(entry) => {
                                    new_traces.push(tref.clone());
                                    let (look, offset) =
                                        pending.unwrap_or((TraceLook::new(new_index), 0.0));
                                    entry.insert(TraceData {
                                        look,
                                        offset,
                                        live: VecDeque::new(),
                                        snap: None,
                                        info: String::new(),
                                        creation_index: new_index,
                                        #[cfg(feature = "fft")]
                                        last_fft: None,
                                    })
                                }
                            };
                            for p in points {
                                entry.live.push_back([p.x, p.y]);
                            }
                            while entry.live.len() > self.max_points {
                                entry.live.pop_front();
                            }
                        }
                    }
                    PlotCommand::SetData { trace_id, points } => {
                        if let Some(name) = self.id_to_name.get(&trace_id).cloned() {
                            let tref = TraceRef(name.clone());
                            let new_index = self.next_color_index();
                            let pending = self.pending_styles.remove(name.as_str());
                            let entry = match self.traces.entry(tref.clone()) {
                                Entry::Occupied(entry) => entry.into_mut(),
                                Entry::Vacant(entry) => {
                                    new_traces.push(tref.clone());
                                    let (look, offset) =
                                        pending.unwrap_or((TraceLook::new(new_index), 0.0));
                                    entry.insert(TraceData {
                                        look,
                                        offset,
                                        live: VecDeque::new(),
                                        snap: None,
                                        info: String::new(),
                                        creation_index: new_index,
                                        #[cfg(feature = "fft")]
                                        last_fft: None,
                                    })
                                }
                            };
                            entry.live.clear();
                            for p in points {
                                entry.live.push_back([p.x, p.y]);
                            }
                        }
                    }
                    PlotCommand::ClearData { trace_id } => {
                        if let Some(name) = self.id_to_name.get(&trace_id).cloned() {
                            let tref = TraceRef(name);
                            if let Some(tr) = self.traces.get_mut(&tref) {
                                tr.live.clear();
                            }
                        }
                    }
                    PlotCommand::SetPointsY { trace_id, xs, y } => {
                        if let Some(name) = self.id_to_name.get(&trace_id).cloned() {
                            let tref = TraceRef(name);
                            if let Some(tr) = self.traces.get_mut(&tref) {
                                for pt in tr.live.iter_mut() {
                                    if xs.iter().any(|&x| (x - pt[0]).abs() < 1e-12) {
                                        pt[1] = y;
                                    }
                                }
                            }
                        }
                    }
                    PlotCommand::DeletePointsX { trace_id, xs } => {
                        if let Some(name) = self.id_to_name.get(&trace_id).cloned() {
                            let tref = TraceRef(name);
                            if let Some(tr) = self.traces.get_mut(&tref) {
                                tr.live
                                    .retain(|pt| !xs.iter().any(|&x| (x - pt[0]).abs() < 1e-12));
                            }
                        }
                    }
                    PlotCommand::DeleteXRange {
                        trace_id,
                        x_min,
                        x_max,
                    } => {
                        if let Some(name) = self.id_to_name.get(&trace_id).cloned() {
                            let tref = TraceRef(name);
                            if let Some(tr) = self.traces.get_mut(&tref) {
                                tr.live.retain(|pt| pt[0] < x_min || pt[0] > x_max);
                            }
                        }
                    }
                    PlotCommand::ApplyYFnAtX { trace_id, xs, f } => {
                        if let Some(name) = self.id_to_name.get(&trace_id).cloned() {
                            let tref = TraceRef(name);
                            if let Some(tr) = self.traces.get_mut(&tref) {
                                for pt in tr.live.iter_mut() {
                                    if xs.iter().any(|&x| (x - pt[0]).abs() < 1e-12) {
                                        pt[1] = f(pt[1]);
                                    }
                                }
                            }
                        }
                    }
                    PlotCommand::ApplyYFnInXRange {
                        trace_id,
                        x_min,
                        x_max,
                        f,
                    } => {
                        if let Some(name) = self.id_to_name.get(&trace_id).cloned() {
                            let tref = TraceRef(name);
                            if let Some(tr) = self.traces.get_mut(&tref) {
                                for pt in tr.live.iter_mut() {
                                    if pt[0] >= x_min && pt[0] <= x_max {
                                        pt[1] = f(pt[1]);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        new_traces
    }

    fn drain(&mut self) {
        for (_name, trace) in self.traces.iter_mut() {
            trace.prune_by_points(self.max_points);
            trace.prune_by_age(self.max_age_secs);
        }
    }

    pub fn update(&mut self) -> Vec<TraceRef> {
        let new_traces = self.update_rx();
        self.drain();
        new_traces
    }

    pub fn take_snapshot(&mut self) {
        for (_name, trace) in self.traces.iter_mut() {
            trace.take_snapshot();
        }
    }

    pub fn clear_snapshot(&mut self) {
        for (_name, trace) in self.traces.iter_mut() {
            trace.clear_snapshot();
        }
    }

    pub fn has_snapshot(&self) -> bool {
        self.traces.values().any(|tr| tr.snap.is_some())
    }

    pub fn clear_trace(&mut self, name: &TraceRef) {
        if let Some(trace) = self.traces.get_mut(name) {
            trace.clear_all();
        }
    }

    pub fn clear_all(&mut self) {
        for trace in self.traces.values_mut() {
            trace.clear_all();
        }
    }

    pub fn remove_trace(&mut self, name: &TraceRef) {
        self.traces.remove(name);
    }

    pub fn get_trace_or_new(&mut self, name: &TraceRef) -> &mut TraceData {
        if !self.traces.contains_key(name) {
            let new_index = self.next_color_index();
            let pending = self.pending_styles.remove(name.as_ref());
            let (look, offset) = pending.unwrap_or((TraceLook::new(new_index), 0.0));
            // note: later when the TraceData is created the `creation_index` is set
            // appropriately (see above insertion sites)
            self.traces.insert(
                name.clone(),
                TraceData {
                    look,
                    offset,
                    live: VecDeque::new(),
                    snap: None,
                    info: String::new(),
                    creation_index: new_index,
                    #[cfg(feature = "fft")]
                    last_fft: None,
                },
            );
        }
        self.traces.get_mut(name).unwrap()
    }

    pub fn get_points(&self, name: &TraceRef, snapshot: bool) -> Option<VecDeque<[f64; 2]>> {
        if let Some(trace) = self.traces.get(name) {
            if snapshot {
                if let Some(snap) = &trace.snap {
                    Some(snap.clone())
                } else {
                    Some(trace.live.clone())
                }
            } else {
                Some(trace.live.clone())
            }
        } else {
            None
        }
    }

    /// Return a reference to the point buffer without cloning.
    /// When `snapshot` is true, returns the snapshot buffer if available,
    /// otherwise falls back to the live buffer.
    pub fn get_points_ref(&self, name: &TraceRef, snapshot: bool) -> Option<&VecDeque<[f64; 2]>> {
        let trace = self.traces.get(name)?;
        if snapshot {
            Some(trace.snap.as_ref().unwrap_or(&trace.live))
        } else {
            Some(&trace.live)
        }
    }

    /// Return decimated points for a trace, filtering by x-bounds and
    /// reducing to at most `max_pts` points.  This avoids cloning the
    /// full VecDeque — it iterates in-place and collects only the kept
    /// points into a Vec.
    pub fn get_drawn_points_decimated(
        &self,
        name: &TraceRef,
        snapshot: bool,
        bounds: (f64, f64),
        max_pts: usize,
    ) -> Option<Vec<[f64; 2]>> {
        let trace = self.traces.get(name)?;
        let source: &VecDeque<[f64; 2]> = if snapshot {
            trace.snap.as_ref().unwrap_or(&trace.live)
        } else {
            &trace.live
        };
        let len = source.len();
        if len == 0 {
            return Some(Vec::new());
        }
        if len <= max_pts {
            // No decimation needed — just filter by bounds
            return Some(
                source
                    .iter()
                    .filter(|p| p[0] >= bounds.0 && p[0] <= bounds.1)
                    .copied()
                    .collect(),
            );
        }
        // Stride decimation: pick every Nth point within bounds
        let stride = (len + max_pts - 1) / max_pts;
        let mut out = Vec::with_capacity(max_pts.min(len));
        let mut i = 0usize;
        while i < len {
            let p = source[i];
            if p[0] >= bounds.0 && p[0] <= bounds.1 {
                out.push(p);
            }
            i += stride;
        }
        // Always include the last point so the line doesn't appear truncated
        if let Some(&last) = source.back() {
            if last[0] >= bounds.0 && last[0] <= bounds.1 {
                if out.last() != Some(&last) {
                    out.push(last);
                }
            }
        }
        Some(out)
    }

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

    pub fn traces_iter(&self) -> impl Iterator<Item = (&TraceRef, &TraceData)> {
        self.traces.iter()
    }

    pub fn traces_iter_mut(&mut self) -> impl Iterator<Item = (&TraceRef, &mut TraceData)> {
        self.traces.iter_mut()
    }

    pub fn get_trace(&self, name: &TraceRef) -> Option<&TraceData> {
        self.traces.get(name)
    }

    pub fn get_trace_mut(&mut self, name: &TraceRef) -> Option<&mut TraceData> {
        self.traces.get_mut(name)
    }

    pub fn contains_key(&self, name: &TraceRef) -> bool {
        self.traces.contains_key(name)
    }

    pub fn keys(&self) -> impl Iterator<Item = &TraceRef> {
        self.traces.keys()
    }

    pub fn all_trace_names(&self) -> Vec<TraceRef> {
        self.traces.keys().cloned().collect()
    }

    /// Update every trace's colour to match the current global palette.
    ///
    /// This is called when the colour scheme changes so that existing traces
    /// (created before the scheme was applied) are recoloured appropriately.
    pub fn recolor_using_palette(&mut self) {
        let palette = crate::color_scheme::global_palette();
        if palette.is_empty() {
            return;
        }
        for (_name, tr) in self.traces.iter_mut() {
            let idx = tr.creation_index;
            tr.look.color = palette[idx % palette.len()];
        }
    }

    /// Find the first palette slot not currently used by any existing trace.
    ///
    /// Returns the index to use for `TraceLook::new(index)` so that a newly
    /// created trace gets a colour that doesn't collide with any existing
    /// trace.  If all palette slots are in use, wraps around to 0.
    pub fn next_color_index(&self) -> usize {
        let palette = crate::color_scheme::global_palette();
        if palette.is_empty() {
            return 0;
        }
        let pal_len = palette.len();
        let used: std::collections::HashSet<usize> = self
            .traces
            .values()
            .map(|tr| tr.creation_index % pal_len)
            .collect();
        for slot in 0..pal_len {
            if !used.contains(&slot) {
                return slot;
            }
        }
        0
    }

    /// Recolour traces to match their position in `order`.
    ///
    /// The Nth trace in `order` gets `palette[N % palette.len()]`.  Traces
    /// not present in `order` are left unchanged.
    pub fn recolor_by_order(&mut self, order: &[TraceRef]) {
        let palette = crate::color_scheme::global_palette();
        if palette.is_empty() {
            return;
        }
        for (i, name) in order.iter().enumerate() {
            if let Some(tr) = self.traces.get_mut(name) {
                tr.look.color = palette[i % palette.len()];
                tr.creation_index = i;
            }
        }
    }

    pub fn len(&self) -> usize {
        self.traces.len()
    }

    pub fn is_empty(&self) -> bool {
        self.traces.is_empty()
    }
}

/// Per-trace data: live buffer, optional snapshot, and styling.
#[derive(Default)]
pub struct TraceData {
    pub look: TraceLook,
    pub offset: f64,
    pub live: VecDeque<[f64; 2]>,
    pub snap: Option<VecDeque<[f64; 2]>>,
    pub info: String,
    /// Index assigned when the trace was created.  Used for deterministic
    /// colour allocation so that recolouring after a scheme change keeps the
    /// same order.
    pub creation_index: usize,
    /// Cached spectrum for the trace when the `fft` feature is enabled.
    ///
    /// The various constructors in this module previously filled this field
    /// during `cfg(feature = "fft")` builds, which led to compilation
    /// failures when the field was missing.  The value is not used anywhere
    /// outside of FFT-related code, so it is only included behind the same
    /// feature flag.
    #[cfg(feature = "fft")]
    pub last_fft: Option<VecDeque<[f64; 2]>>,
}

impl TraceData {
    pub fn prune_by_points(&mut self, max_points: usize) {
        while self.live.len() > max_points {
            self.live.pop_front();
        }
    }

    /// Remove points whose X value is older than `max_age_secs` behind the
    /// newest point.  A value of `0.0` or negative disables this pruning.
    pub fn prune_by_age(&mut self, max_age_secs: f64) {
        if max_age_secs <= 0.0 {
            return;
        }
        let Some(newest_x) = self.live.back().map(|p| p[0]) else {
            return;
        };
        let cutoff = newest_x - max_age_secs;
        while let Some(&front) = self.live.front() {
            if front[0] < cutoff {
                self.live.pop_front();
            } else {
                break;
            }
        }
    }

    pub fn clear_all(&mut self) {
        self.live.clear();
        self.snap = None;
    }

    pub fn take_snapshot(&mut self) {
        self.snap = Some(self.live.clone());
    }

    pub fn clear_snapshot(&mut self) {
        self.snap = None;
    }

    pub fn get_last_live_timestamp(&self) -> Option<f64> {
        self.live.back().map(|p| p[0])
    }

    pub fn get_last_snapshot_timestamp(&self) -> Option<f64> {
        self.snap.as_ref().and_then(|s| s.back().map(|p| p[0]))
    }

    pub fn cap_by_x_bounds(pts: &VecDeque<[f64; 2]>, bounds: (f64, f64)) -> VecDeque<[f64; 2]> {
        pts.iter()
            .filter(|p| p[0] >= bounds.0 && p[0] <= bounds.1)
            .cloned()
            .collect()
    }

    /// Filter by x-bounds and decimate to at most `max_pts` points.
    /// Returns a Vec suitable for passing directly to egui_plot.
    /// When the input has fewer points than `max_pts`, all points within
    /// bounds are returned.  When more, every Nth point is kept (stride
    /// = ceil(len / max_pts)) so the overall shape is preserved.
    pub fn cap_and_decimate(
        pts: &[[f64; 2]],
        bounds: (f64, f64),
        max_pts: usize,
    ) -> Vec<[f64; 2]> {
        let len = pts.len();
        if len <= max_pts {
            return pts
                .iter()
                .filter(|p| p[0] >= bounds.0 && p[0] <= bounds.1)
                .copied()
                .collect();
        }
        let stride = (len + max_pts - 1) / max_pts;
        let mut out = Vec::with_capacity(max_pts.min(len));
        let mut i = 0;
        while i < len {
            let p = pts[i];
            if p[0] >= bounds.0 && p[0] <= bounds.1 {
                out.push(p);
            }
            i += stride;
        }
        // Always include the last point so the line doesn't appear truncated
        if let Some(last) = pts.last() {
            if last[0] >= bounds.0 && last[0] <= bounds.1 {
                if out.last() != Some(last) {
                    out.push(*last);
                }
            }
        }
        out
    }
}

// --- tests -----------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::color_scheme;
    use crate::sink::PlotCommand;
    use egui::Color32;

    #[test]
    fn cap_and_decimate_reduces_points() {
        let pts: Vec<[f64; 2]> = (0..10_000).map(|i| [i as f64, i as f64]).collect();
        let result = TraceData::cap_and_decimate(&pts, (0.0, 9999.0), 2000);
        assert!(result.len() <= 2001, "result should have at most 2001 points (2000 + last), got {}", result.len());
        assert!(result.len() > 1000, "result should have significant decimation, got {}", result.len());
        // First and last points should be preserved
        assert_eq!(result[0], [0.0, 0.0]);
        assert_eq!(*result.last().unwrap(), [9999.0, 9999.0]);
    }

    #[test]
    fn cap_and_decimate_respects_bounds() {
        let pts: Vec<[f64; 2]> = (0..100).map(|i| [i as f64, i as f64]).collect();
        let result = TraceData::cap_and_decimate(&pts, (10.0, 20.0), 2000);
        assert!(result.iter().all(|p| p[0] >= 10.0 && p[0] <= 20.0));
        assert_eq!(result.len(), 11); // 10..=20 inclusive
    }

    #[test]
    fn cap_and_decimate_no_decimation_when_under_limit() {
        let pts: Vec<[f64; 2]> = (0..100).map(|i| [i as f64, i as f64]).collect();
        let result = TraceData::cap_and_decimate(&pts, (0.0, 99.0), 2000);
        assert_eq!(result.len(), 100);
    }

    #[test]
    fn recolor_changes_existing_traces() {
        // create collection with two traces
        let (tx, rx) = std::sync::mpsc::channel();
        let mut col = TracesCollection::new(rx);
        // register two traces via commands
        let _ = tx.send(PlotCommand::RegisterTrace {
            id: 1,
            name: "a".to_string(),
            info: None,
        });
        let _ = tx.send(PlotCommand::RegisterTrace {
            id: 2,
            name: "b".to_string(),
            info: None,
        });
        let new = col.update();
        assert_eq!(new.len(), 2);
        // initial palette must be default dark
        let first_color = col.traces.get(&TraceRef("a".into())).unwrap().look.color;
        assert_ne!(first_color, Color32::GRAY); // sanity
                                                // set a simple custom palette
        color_scheme::set_global_palette(vec![
            Color32::from_rgb(9, 9, 9),
            Color32::from_rgb(8, 8, 8),
        ]);
        col.recolor_using_palette();
        assert_eq!(
            col.traces.get(&TraceRef("a".into())).unwrap().look.color,
            Color32::from_rgb(9, 9, 9)
        );
        assert_eq!(
            col.traces.get(&TraceRef("b".into())).unwrap().look.color,
            Color32::from_rgb(8, 8, 8)
        );
    }

    #[test]
    fn next_color_index_avoids_collision_after_removal() {
        color_scheme::set_global_palette(vec![
            Color32::from_rgb(1, 1, 1),
            Color32::from_rgb(2, 2, 2),
            Color32::from_rgb(3, 3, 3),
        ]);
        let (tx, rx) = std::sync::mpsc::channel();
        let mut col = TracesCollection::new(rx);
        // Register 3 traces → indices 0, 1, 2
        let _ = tx.send(PlotCommand::RegisterTrace { id: 1, name: "a".into(), info: None });
        let _ = tx.send(PlotCommand::RegisterTrace { id: 2, name: "b".into(), info: None });
        let _ = tx.send(PlotCommand::RegisterTrace { id: 3, name: "c".into(), info: None });
        let _ = col.update();
        // Remove "b" (index 1) → used slots are {0, 2}
        col.remove_trace(&TraceRef("b".into()));
        // Next index should be 1 (first unused slot)
        assert_eq!(col.next_color_index(), 1);
    }

    #[test]
    fn recolor_by_order_assigns_palette_in_order() {
        let palette = vec![
            Color32::from_rgb(10, 10, 10),
            Color32::from_rgb(20, 20, 20),
            Color32::from_rgb(30, 30, 30),
        ];
        color_scheme::set_global_palette(palette.clone());
        let (tx, rx) = std::sync::mpsc::channel();
        let mut col = TracesCollection::new(rx);
        let _ = tx.send(PlotCommand::RegisterTrace { id: 1, name: "a".into(), info: None });
        let _ = tx.send(PlotCommand::RegisterTrace { id: 2, name: "b".into(), info: None });
        let _ = tx.send(PlotCommand::RegisterTrace { id: 3, name: "c".into(), info: None });
        let _ = col.update();

        // Recolor in reverse order: c, b, a
        let order = vec![
            TraceRef("c".into()),
            TraceRef("b".into()),
            TraceRef("a".into()),
        ];
        col.recolor_by_order(&order);
        assert_eq!(col.get_trace(&TraceRef("c".into())).unwrap().look.color, palette[0]);
        assert_eq!(col.get_trace(&TraceRef("b".into())).unwrap().look.color, palette[1]);
        assert_eq!(col.get_trace(&TraceRef("a".into())).unwrap().look.color, palette[2]);
    }
}