ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
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
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
//! Custom widgets for IronMonitor GUI
//!
//! Cyber-styled widgets for displaying hardware metrics
//! Now with Glances-style threshold colors and quicklook panel

use super::theme::{self, threshold_color, CyberColors};
use egui::epaint::PathShape;
use egui::{Color32, Pos2, Rect, Response, Sense, Stroke, Ui, Vec2, Widget};

/// A cyber-styled progress bar with glow effect, animated pulse, and Glances-style threshold colors
pub struct CyberProgressBar {
    progress: f32,
    color: Color32,
    label: Option<String>,
    show_percentage: bool,
    height: f32,
    animated: bool,
    use_threshold_color: bool,
    trend: Option<&'static str>,
}

impl CyberProgressBar {
    pub fn new(progress: f32) -> Self {
        Self {
            progress: progress.clamp(0.0, 1.0),
            color: CyberColors::CYAN,
            label: None,
            show_percentage: true,
            height: 20.0,
            // Off by default. The animation is a scanline sweep and a glow pulse —
            // decoration that carries no reading — and any visible animated bar keeps
            // the whole window repainting continuously. On a 3440x1440 display that
            // cost more CPU than collecting the hardware data it was decorating. Opt
            // in with `.animated(true)` where it is worth the frames.
            animated: false,
            use_threshold_color: false,
            trend: None,
        }
    }

    pub fn color(mut self, color: Color32) -> Self {
        self.color = color;
        self
    }

    /// Use Glances-style threshold colors based on percentage
    pub fn with_threshold_color(mut self) -> Self {
        self.use_threshold_color = true;
        self
    }

    /// Add a trend indicator (↑, ↓, or →)
    pub fn with_trend(mut self, trend: &'static str) -> Self {
        self.trend = Some(trend);
        self
    }

    pub fn label(mut self, label: impl Into<String>) -> Self {
        self.label = Some(label.into());
        self
    }

    #[allow(dead_code)]
    pub fn show_percentage(mut self, show: bool) -> Self {
        self.show_percentage = show;
        self
    }

    pub fn height(mut self, height: f32) -> Self {
        self.height = height;
        self
    }

    #[allow(dead_code)]
    pub fn animated(mut self, animated: bool) -> Self {
        self.animated = animated;
        self
    }
}

impl Widget for CyberProgressBar {
    fn ui(self, ui: &mut Ui) -> Response {
        let widget_color = theme::color(ui.ctx(), self.color);
        let desired_size = Vec2::new(ui.available_width(), self.height);
        let (rect, response) = ui.allocate_exact_size(desired_size, Sense::hover());

        if ui.is_rect_visible(rect) {
            let painter = ui.painter();
            let time = ui.input(|i| i.time) as f32;

            // Use threshold color if enabled, otherwise use provided color
            let bar_color = if self.use_threshold_color {
                theme::color(ui.ctx(), threshold_color(self.progress * 100.0))
            } else {
                widget_color
            };

            // Background with gradient effect
            painter.rect_filled(
                rect,
                4.0,
                theme::color(ui.ctx(), CyberColors::BACKGROUND_DARK),
            );

            // Subtle inner shadow
            let inner_shadow = Rect::from_min_size(
                rect.min + Vec2::new(1.0, 1.0),
                rect.size() - Vec2::new(2.0, 2.0),
            );
            painter.rect_filled(
                inner_shadow,
                3.0,
                Color32::from_rgba_unmultiplied(0, 0, 0, 40),
            );

            // Progress fill
            let fill_width = rect.width() * self.progress;
            if fill_width > 0.0 {
                let fill_rect = Rect::from_min_size(rect.min, Vec2::new(fill_width, rect.height()));

                // Multi-layer gradient fill using bar_color
                let dark_color = bar_color.linear_multiply(0.4);
                let bright_color = bar_color.linear_multiply(1.2);

                // Base fill
                painter.rect_filled(fill_rect.shrink(1.0), 3.0, dark_color);

                // Middle gradient band
                let mid_rect = Rect::from_min_size(
                    fill_rect.min + Vec2::new(1.0, rect.height() * 0.3),
                    Vec2::new(fill_width - 2.0, rect.height() * 0.4),
                );
                painter.rect_filled(mid_rect, 0.0, bar_color.linear_multiply(0.7));

                // Top highlight (glossy effect)
                let highlight_rect = Rect::from_min_size(
                    fill_rect.min + Vec2::new(1.0, 1.0),
                    Vec2::new(fill_width - 2.0, rect.height() * 0.35),
                );
                let highlight_color = Color32::from_rgba_unmultiplied(
                    bright_color.r(),
                    bright_color.g(),
                    bright_color.b(),
                    80,
                );
                painter.rect_filled(highlight_rect, 2.0, highlight_color);

                // Animated scanline effect
                if self.animated && fill_width > 10.0 {
                    let scan_pos = ((time * 2.0).sin() * 0.5 + 0.5) * fill_width;
                    let scan_width = 20.0;
                    if scan_pos > 0.0 && scan_pos < fill_width {
                        let scan_rect = Rect::from_min_size(
                            fill_rect.min + Vec2::new(scan_pos - scan_width / 2.0, 0.0),
                            Vec2::new(
                                scan_width.min(fill_width - scan_pos + scan_width / 2.0),
                                rect.height(),
                            ),
                        );
                        let scan_color = Color32::from_rgba_unmultiplied(255, 255, 255, 25);
                        painter.rect_filled(scan_rect.shrink(1.0), 2.0, scan_color);
                    }
                }

                // Glow effect on the edge (pulsing)
                let glow_x = rect.min.x + fill_width;
                if fill_width > 2.0 {
                    let pulse = if self.animated {
                        (time * 3.0).sin() * 0.3 + 0.7
                    } else {
                        1.0
                    };

                    for i in 0..5 {
                        let alpha = ((80.0 - i as f32 * 15.0) * pulse) as u8;
                        let glow_color = Color32::from_rgba_unmultiplied(
                            bar_color.r(),
                            bar_color.g(),
                            bar_color.b(),
                            alpha,
                        );
                        painter.vline(
                            glow_x - i as f32,
                            rect.y_range(),
                            Stroke::new(1.0_f32, glow_color),
                        );
                    }

                    // Bright dot at the end
                    let dot_y = rect.center().y;
                    painter.circle_filled(
                        Pos2::new(glow_x - 1.0, dot_y),
                        3.0,
                        Color32::from_rgba_unmultiplied(255, 255, 255, (150.0 * pulse) as u8),
                    );
                }
            }

            // Outer border with subtle glow
            painter.rect_stroke(
                rect,
                4.0,
                Stroke::new(1.0_f32, theme::color(ui.ctx(), CyberColors::BORDER)),
                egui::StrokeKind::Middle,
            );

            // Label and percentage with trend indicator
            let text_color = theme::color(ui.ctx(), CyberColors::TEXT_PRIMARY);

            if let Some(label) = &self.label {
                // Add trend indicator to label if present
                let label_with_trend = if let Some(trend) = self.trend {
                    format!("{} {}", trend, label)
                } else {
                    label.clone()
                };

                // Text shadow
                painter.text(
                    Pos2::new(rect.min.x + 9.0, rect.center().y + 1.0),
                    egui::Align2::LEFT_CENTER,
                    &label_with_trend,
                    theme::data_font(ui.ctx(), 12.0),
                    Color32::from_black_alpha(180),
                );
                painter.text(
                    Pos2::new(rect.min.x + 8.0, rect.center().y),
                    egui::Align2::LEFT_CENTER,
                    &label_with_trend,
                    theme::data_font(ui.ctx(), 12.0),
                    theme::legible(ui.ctx(), text_color),
                );
            }

            if self.show_percentage {
                let percent_text = format!("{:.1}%", self.progress * 100.0);
                // Text shadow
                painter.text(
                    Pos2::new(rect.max.x - 7.0, rect.center().y + 1.0),
                    egui::Align2::RIGHT_CENTER,
                    &percent_text,
                    theme::data_font(ui.ctx(), 12.0),
                    Color32::from_black_alpha(180),
                );
                painter.text(
                    Pos2::new(rect.max.x - 8.0, rect.center().y),
                    egui::Align2::RIGHT_CENTER,
                    percent_text,
                    theme::data_font(ui.ctx(), 12.0),
                    theme::legible(ui.ctx(), text_color),
                );
            }
        }

        // Drive the scanline and glow pulse at a bounded rate.
        //
        // This was a bare `request_repaint()`, which means "repaint as soon as
        // possible" — so a single visible progress bar pinned the whole app at the
        // display's refresh rate, permanently, to animate decoration. On a 3440x1440
        // screen that was the single largest consumer in the process, several times
        // the cost of actually collecting the hardware data. Decoration does not need
        // more than ~30 FPS, and egui still repaints instantly on input.
        if self.animated {
            ui.ctx()
                .request_repaint_after(std::time::Duration::from_millis(33));
        }

        response
    }
}

/// A cyber-styled metric card
pub struct MetricCard<'a> {
    title: &'a str,
    value: String,
    unit: Option<&'a str>,
    color: Color32,
    icon: Option<&'a str>,
}

impl<'a> MetricCard<'a> {
    pub fn new(title: &'a str, value: impl std::fmt::Display) -> Self {
        Self {
            title,
            value: value.to_string(),
            unit: None,
            color: CyberColors::CYAN,
            icon: None,
        }
    }

    pub fn unit(mut self, unit: &'a str) -> Self {
        self.unit = Some(unit);
        self
    }

    pub fn color(mut self, color: Color32) -> Self {
        self.color = color;
        self
    }

    #[allow(dead_code)]
    pub fn icon(mut self, icon: &'a str) -> Self {
        self.icon = Some(icon);
        self
    }
}

impl Widget for MetricCard<'_> {
    fn ui(self, ui: &mut Ui) -> Response {
        let widget_color = theme::color(ui.ctx(), self.color);
        let desired_size = Vec2::new(140.0, 70.0);
        let (rect, response) = ui.allocate_exact_size(desired_size, Sense::hover());

        if ui.is_rect_visible(rect) {
            let painter = ui.painter();

            // Card background
            painter.rect_filled(rect, 6.0, theme::color(ui.ctx(), CyberColors::SURFACE));

            // Accent border on left
            let accent_rect = Rect::from_min_size(rect.min, Vec2::new(3.0, rect.height()));
            painter.rect_filled(
                accent_rect,
                egui::CornerRadius {
                    nw: 6,
                    sw: 6,
                    ne: 0,
                    se: 0,
                },
                widget_color,
            );

            // Title
            painter.text(
                Pos2::new(rect.min.x + 12.0, rect.min.y + 12.0),
                egui::Align2::LEFT_TOP,
                self.title,
                theme::data_font(ui.ctx(), 11.0),
                theme::legible(
                    ui.ctx(),
                    theme::color(ui.ctx(), CyberColors::TEXT_SECONDARY),
                ),
            );

            // Value with unit
            let value_text = if let Some(unit) = self.unit {
                format!("{} {}", self.value, unit)
            } else {
                self.value.clone()
            };

            painter.text(
                Pos2::new(rect.min.x + 12.0, rect.max.y - 12.0),
                egui::Align2::LEFT_BOTTOM,
                value_text,
                theme::data_font(ui.ctx(), 18.0),
                theme::legible(ui.ctx(), widget_color),
            );
        }

        response
    }
}

/// Sparkline chart for historical data - sexy animated version with improved readability
enum ChartData<'a> {
    Owned(Vec<f32>),
    History(&'a std::collections::VecDeque<f32>),
}

impl ChartData<'_> {
    fn slices(&self) -> (&[f32], &[f32]) {
        match self {
            Self::Owned(values) => (values, &[]),
            Self::History(values) => values.as_slices(),
        }
    }

    fn iter(&self) -> impl Iterator<Item = &f32> {
        let (first, second) = self.slices();
        first.iter().chain(second.iter())
    }

    fn len(&self) -> usize {
        let (first, second) = self.slices();
        first.len() + second.len()
    }

    fn last(&self) -> Option<&f32> {
        let (first, second) = self.slices();
        second.last().or_else(|| first.last())
    }
}

pub struct SparklineChart<'a> {
    data: ChartData<'a>,
    color: Color32,
    height: f32,
    show_grid: bool,
    show_glow: bool,
    show_dots: bool,
    smooth: bool,
    gradient_fill: bool,
    title: Option<String>,
    unit: Option<String>,
    show_scale: bool,
    fixed_max: Option<f32>,
    show_min_max: bool,
    line_thickness: f32,
}

impl<'a> SparklineChart<'a> {
    pub fn new(data: Vec<f32>) -> Self {
        Self {
            data: ChartData::Owned(data),
            color: CyberColors::CYAN,
            height: 70.0,
            show_grid: true,
            show_glow: false, // Disabled - too bright
            show_dots: false, // Disabled - cluttered
            smooth: true,
            gradient_fill: false, // Disabled - cleaner look
            title: None,
            unit: None,
            show_scale: true,
            fixed_max: None,
            show_min_max: false, // Disabled by default - less clutter
            line_thickness: 2.5, // Default thicker lines
        }
    }

    /// Borrow a ring-buffer history without copying samples on every frame.
    pub fn from_history(data: &'a std::collections::VecDeque<f32>) -> Self {
        Self {
            data: ChartData::History(data),
            ..Self::new(Vec::new())
        }
    }

    pub fn color(mut self, color: Color32) -> Self {
        self.color = color;
        self
    }

    pub fn height(mut self, height: f32) -> Self {
        self.height = height;
        self
    }

    #[allow(dead_code)]
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    #[allow(dead_code)]
    pub fn unit(mut self, unit: impl Into<String>) -> Self {
        self.unit = Some(unit.into());
        self
    }

    #[allow(dead_code)]
    pub fn show_grid(mut self, show: bool) -> Self {
        self.show_grid = show;
        self
    }

    #[allow(dead_code)]
    pub fn show_glow(mut self, show: bool) -> Self {
        self.show_glow = show;
        self
    }

    #[allow(dead_code)]
    pub fn smooth(mut self, smooth: bool) -> Self {
        self.smooth = smooth;
        self
    }

    #[allow(dead_code)]
    pub fn show_scale(mut self, show: bool) -> Self {
        self.show_scale = show;
        self
    }

    /// Set a fixed maximum value for consistent scaling
    #[allow(dead_code)]
    pub fn max_value(mut self, max: f32) -> Self {
        self.fixed_max = Some(max);
        self
    }

    #[allow(dead_code)]
    pub fn show_min_max(mut self, show: bool) -> Self {
        self.show_min_max = show;
        self
    }

    /// Set the line thickness for the sparkline
    #[allow(dead_code)]
    pub fn line_thickness(mut self, thickness: f32) -> Self {
        self.line_thickness = thickness;
        self
    }
}

impl Widget for SparklineChart<'_> {
    fn ui(self, ui: &mut Ui) -> Response {
        let widget_color = theme::color(ui.ctx(), self.color);
        // Reserve space for Y-axis labels on left
        let y_axis_width = if self.show_scale { 45.0 } else { 0.0 };
        let title_height = if self.title.is_some() { 20.0 } else { 0.0 };

        let desired_size = Vec2::new(ui.available_width(), self.height + title_height);
        let (rect, response) = ui.allocate_exact_size(desired_size, Sense::hover());

        if ui.is_rect_visible(rect) {
            let painter = ui.painter();
            let time = ui.input(|i| i.time) as f32;

            // Calculate data bounds
            let data_min = self.data.iter().cloned().fold(f32::MAX, f32::min);
            let data_max = self.data.iter().cloned().fold(0.0_f32, f32::max);
            let max_val = self.fixed_max.unwrap_or_else(|| data_max.max(1.0));
            // None for an empty series: nothing was read, so nothing is shown.
            let current_val = self.data.last().cloned();
            let unit_str = self.unit.as_deref().unwrap_or("");

            // Title area
            let graph_rect = if self.title.is_some() {
                let title_rect =
                    Rect::from_min_size(rect.min, Vec2::new(rect.width(), title_height));

                // Draw title
                if let Some(ref title) = self.title {
                    painter.text(
                        title_rect.left_center() + Vec2::new(y_axis_width + 5.0, 0.0),
                        egui::Align2::LEFT_CENTER,
                        title,
                        theme::data_font(ui.ctx(), 13.0),
                        theme::legible(
                            ui.ctx(),
                            theme::color(ui.ctx(), CyberColors::TEXT_SECONDARY),
                        ),
                    );

                    // Min/max info (if enabled and data has variance)
                    if self.show_min_max && self.data.len() > 1 && data_max > data_min {
                        let min_max_text = format!("min:{:.0} max:{:.0}", data_min, data_max);
                        painter.text(
                            title_rect.center() + Vec2::new(20.0, 0.0),
                            egui::Align2::LEFT_CENTER,
                            min_max_text,
                            theme::data_font(ui.ctx(), 10.0),
                            theme::legible(
                                ui.ctx(),
                                theme::color(ui.ctx(), CyberColors::TEXT_SECONDARY),
                            ),
                        );
                    }

                    // Current value on right side of title
                    let value_text = match current_val {
                        Some(v) => format!("{:.1}{}", v, unit_str),
                        None => "-".to_string(),
                    };
                    painter.text(
                        title_rect.right_center() - Vec2::new(10.0, 0.0),
                        egui::Align2::RIGHT_CENTER,
                        value_text,
                        theme::data_font(ui.ctx(), 14.0),
                        theme::legible(ui.ctx(), widget_color),
                    );
                }

                Rect::from_min_max(rect.min + Vec2::new(0.0, title_height), rect.max)
            } else {
                rect
            };

            // Deep backdrop keeps the chart line in focus.
            let muted_bg = theme::color(ui.ctx(), CyberColors::BACKGROUND_DARK);
            painter.rect_filled(graph_rect, 6.0, muted_bg);

            // Very subtle inner shadow for depth
            let inner = graph_rect.shrink(1.0);
            painter.rect_filled(
                Rect::from_min_size(inner.min, Vec2::new(inner.width(), 2.0)),
                0.0,
                Color32::from_rgba_unmultiplied(0, 0, 0, 15),
            );

            // Calculate the actual chart area (with room for Y-axis labels)
            let chart_rect = Rect::from_min_max(
                graph_rect.min + Vec2::new(y_axis_width, 0.0),
                graph_rect.max,
            );

            // Draw Y-axis scale labels
            if self.show_scale {
                let scale_color = theme::text_color(ui.ctx(), CyberColors::TEXT_SECONDARY);
                let font = theme::data_font(ui.ctx(), 10.0);

                // Max value at top
                // Three digits or more reads fine without a decimal; below that the
                // tenth is the only thing distinguishing adjacent samples.
                let max_text = if max_val >= 100.0 {
                    format!("{:.0}{}", max_val, unit_str)
                } else {
                    format!("{:.1}{}", max_val, unit_str)
                };
                painter.text(
                    Pos2::new(
                        graph_rect.min.x + y_axis_width - 5.0,
                        chart_rect.min.y + 8.0,
                    ),
                    egui::Align2::RIGHT_CENTER,
                    max_text,
                    font.clone(),
                    scale_color,
                );

                // Mid value
                let mid_val = max_val / 2.0;
                let mid_text = if mid_val >= 100.0 {
                    format!("{:.0}", mid_val)
                } else {
                    format!("{:.1}", mid_val)
                };
                painter.text(
                    Pos2::new(graph_rect.min.x + y_axis_width - 5.0, chart_rect.center().y),
                    egui::Align2::RIGHT_CENTER,
                    mid_text,
                    font.clone(),
                    scale_color,
                );

                // Zero/min at bottom
                painter.text(
                    Pos2::new(
                        graph_rect.min.x + y_axis_width - 5.0,
                        chart_rect.max.y - 8.0,
                    ),
                    egui::Align2::RIGHT_CENTER,
                    "0",
                    font,
                    scale_color,
                );
            }

            // Simple static grid lines
            if self.show_grid {
                let grid_color =
                    theme::color(ui.ctx(), Color32::from_rgba_unmultiplied(60, 70, 80, 40));

                // Horizontal grid lines (4 lines = 5 zones for 0%, 25%, 50%, 75%, 100%)
                for i in 1..4 {
                    let y = chart_rect.min.y + chart_rect.height() * (i as f32 / 4.0);
                    painter.hline(chart_rect.x_range(), y, Stroke::new(0.5_f32, grid_color));
                }

                // Vertical grid lines (time markers) - very subtle
                let num_vlines = 6;
                for i in 1..num_vlines {
                    let x = chart_rect.min.x + chart_rect.width() * (i as f32 / num_vlines as f32);
                    painter.vline(
                        x,
                        chart_rect.y_range(),
                        Stroke::new(0.5_f32, grid_color.linear_multiply(0.5)),
                    );
                }
            }

            // Draw sparkline
            if self.data.len() >= 2 {
                let padding = 4.0;
                let plot_rect = chart_rect.shrink(padding);

                // Calculate points using the max_val calculated earlier
                let points: Vec<Pos2> = self
                    .data
                    .iter()
                    .enumerate()
                    .map(|(i, &v)| {
                        let x = plot_rect.min.x
                            + (i as f32 / (self.data.len() - 1) as f32) * plot_rect.width();
                        let normalized = (v / max_val).clamp(0.0, 1.0);
                        let y = plot_rect.max.y - normalized * plot_rect.height() * 0.95;
                        Pos2::new(x, y)
                    })
                    .collect();

                // Smooth the curve using Catmull-Rom spline interpolation
                // Higher subdivision = smoother curves (8 for silky smooth)
                let smooth_points = if self.smooth && points.len() >= 4 {
                    catmull_rom_spline(&points, 8)
                } else if self.smooth && points.len() >= 2 {
                    // For fewer points, still apply some smoothing
                    catmull_rom_spline(&points, 4)
                } else {
                    points.clone()
                };

                // Gradient fill under the line (multiple layers for depth)
                if self.gradient_fill {
                    let mut fill_points = smooth_points.clone();
                    fill_points.push(Pos2::new(plot_rect.max.x, plot_rect.max.y));
                    fill_points.push(Pos2::new(plot_rect.min.x, plot_rect.max.y));

                    // Layer 1: Dark base
                    let fill_color_dark = Color32::from_rgba_unmultiplied(
                        widget_color.r(),
                        widget_color.g(),
                        widget_color.b(),
                        8,
                    );
                    painter.add(egui::Shape::convex_polygon(
                        fill_points,
                        fill_color_dark,
                        Stroke::NONE,
                    ));

                    // Layer 2: Gradient bands (simulated)
                    for layer in 0..3 {
                        let _band_height = plot_rect.height() * (0.3 - layer as f32 * 0.1);
                        let alpha = 10 - layer * 3;
                        let band_points: Vec<Pos2> = smooth_points
                            .iter()
                            .map(|p| {
                                let y_offset = (plot_rect.max.y - p.y) * (0.3 - layer as f32 * 0.1);
                                Pos2::new(p.x, (p.y + y_offset).min(plot_rect.max.y))
                            })
                            .collect();

                        let mut band_fill = band_points;
                        band_fill.push(Pos2::new(plot_rect.max.x, plot_rect.max.y));
                        band_fill.push(Pos2::new(plot_rect.min.x, plot_rect.max.y));

                        let band_color = Color32::from_rgba_unmultiplied(
                            widget_color.r(),
                            widget_color.g(),
                            widget_color.b(),
                            alpha as u8,
                        );
                        painter.add(egui::Shape::convex_polygon(
                            band_fill,
                            band_color,
                            Stroke::NONE,
                        ));
                    }
                }

                // Glow effect under the line (if enabled)
                if self.show_glow {
                    for offset in 1..=3 {
                        let glow_alpha = (40 - offset * 12) as u8;
                        let glow_color = Color32::from_rgba_unmultiplied(
                            widget_color.r(),
                            widget_color.g(),
                            widget_color.b(),
                            glow_alpha,
                        );

                        let glow_points: Vec<Pos2> = smooth_points
                            .iter()
                            .map(|p| Pos2::new(p.x, p.y + offset as f32))
                            .collect();

                        let glow_path = PathShape::line(
                            glow_points,
                            Stroke::new(3.0 - offset as f32 * 0.5, glow_color),
                        );
                        painter.add(glow_path);
                    }
                }

                // Full saturation and opacity give a crisp line on the dark fill.
                let line_color = widget_color;
                let main_path =
                    PathShape::line(smooth_points, Stroke::new(self.line_thickness, line_color));
                painter.add(main_path);

                // Data point dots (only on original points, not interpolated)
                if self.show_dots && points.len() <= 30 {
                    for (i, point) in points.iter().enumerate() {
                        let is_last = i == points.len() - 1;
                        let dot_size = if is_last { 5.0 } else { 2.5 };

                        // Outer glow for dots
                        if is_last {
                            let pulse = (time * 4.0).sin() * 0.3 + 0.7;
                            for r in (1..=3).rev() {
                                let alpha = ((60 - r * 15) as f32 * pulse) as u8;
                                painter.circle_filled(
                                    *point,
                                    dot_size + r as f32 * 2.0,
                                    Color32::from_rgba_unmultiplied(
                                        widget_color.r(),
                                        widget_color.g(),
                                        widget_color.b(),
                                        alpha,
                                    ),
                                );
                            }
                        }

                        // Inner dot
                        painter.circle_filled(*point, dot_size, widget_color);

                        // Bright center
                        if is_last {
                            painter.circle_filled(
                                *point,
                                dot_size * 0.5,
                                Color32::from_rgb(255, 255, 255),
                            );
                        }
                    }
                }
            }

            // Simple subtle border
            painter.rect_stroke(
                rect,
                4.0,
                Stroke::new(
                    1.0_f32,
                    theme::color(ui.ctx(), Color32::from_rgba_unmultiplied(60, 70, 80, 80)),
                ),
                egui::StrokeKind::Middle,
            );
        }

        response
    }
}

/// Catmull-Rom spline interpolation for smooth curves
fn catmull_rom_spline(points: &[Pos2], subdivisions: usize) -> Vec<Pos2> {
    if points.len() < 2 {
        return points.to_vec();
    }

    let mut result = Vec::with_capacity((points.len() - 1) * subdivisions + 1);

    for i in 0..points.len() - 1 {
        let p0 = if i == 0 { points[0] } else { points[i - 1] };
        let p1 = points[i];
        let p2 = points[i + 1];
        let p3 = if i + 2 < points.len() {
            points[i + 2]
        } else {
            points[points.len() - 1]
        };

        for j in 0..=subdivisions {
            let t = j as f32 / subdivisions as f32;
            let t2 = t * t;
            let t3 = t2 * t;

            let x = 0.5
                * ((2.0 * p1.x)
                    + (-p0.x + p2.x) * t
                    + (2.0 * p0.x - 5.0 * p1.x + 4.0 * p2.x - p3.x) * t2
                    + (-p0.x + 3.0 * p1.x - 3.0 * p2.x + p3.x) * t3);

            let y = 0.5
                * ((2.0 * p1.y)
                    + (-p0.y + p2.y) * t
                    + (2.0 * p0.y - 5.0 * p1.y + 4.0 * p2.y - p3.y) * t2
                    + (-p0.y + 3.0 * p1.y - 3.0 * p2.y + p3.y) * t3);

            if j == 0 && i > 0 {
                continue; // Skip duplicate points
            }
            result.push(Pos2::new(x, y));
        }
    }

    result
}

#[cfg(test)]
mod chart_history_tests {
    use super::*;

    #[test]
    fn borrowed_history_preserves_wrapped_ring_order_and_last_sample() {
        let mut history = std::collections::VecDeque::with_capacity(4);
        history.extend([1.0, 2.0, 3.0, 4.0]);
        history.pop_front();
        history.pop_front();
        history.extend([5.0, 6.0]);
        assert!(!history.as_slices().1.is_empty());
        let chart = SparklineChart::from_history(&history);
        assert_eq!(
            chart.data.iter().copied().collect::<Vec<_>>(),
            vec![3.0, 4.0, 5.0, 6.0]
        );
        assert_eq!(chart.data.len(), 4);
        assert_eq!(chart.data.last(), Some(&6.0));
        assert_eq!(
            SparklineChart::from_history(&std::collections::VecDeque::new())
                .data
                .last(),
            None
        );
    }
}

/// Section header with cyber styling
pub struct SectionHeader<'a> {
    title: &'a str,
    icon: Option<&'a str>,
}

impl<'a> SectionHeader<'a> {
    pub fn new(title: &'a str) -> Self {
        Self { title, icon: None }
    }

    pub fn icon(mut self, icon: &'a str) -> Self {
        self.icon = Some(icon);
        self
    }
}

impl Widget for SectionHeader<'_> {
    fn ui(self, ui: &mut Ui) -> Response {
        let desired_size = Vec2::new(ui.available_width(), 28.0);
        let (rect, response) = ui.allocate_exact_size(desired_size, Sense::hover());

        if ui.is_rect_visible(rect) {
            let painter = ui.painter();

            // Title with icon
            let title_text = if let Some(icon) = self.icon {
                format!("{} {}", icon, self.title)
            } else {
                self.title.to_string()
            };

            painter.text(
                Pos2::new(rect.min.x, rect.center().y),
                egui::Align2::LEFT_CENTER,
                title_text,
                egui::FontId::proportional(14.0),
                theme::color(ui.ctx(), CyberColors::CYAN),
            );

            // Decorative line
            let line_start = rect.min.x
                + painter
                    .layout_no_wrap(
                        self.title.to_string(),
                        egui::FontId::proportional(14.0),
                        theme::color(ui.ctx(), CyberColors::CYAN),
                    )
                    .rect
                    .width()
                + 20.0;

            painter.hline(
                line_start..=rect.max.x,
                rect.center().y,
                Stroke::new(1.0_f32, theme::color(ui.ctx(), CyberColors::BORDER)),
            );
        }

        response
    }
}

/// Glances-style QuickLook summary panel
/// Shows CPU, MEM, SWAP, LOAD in a compact horizontal bar format
pub struct QuickLookPanel {
    /// CPU usage, or `None` before the first CPU sample.
    cpu_percent: Option<f32>,
    /// Memory usage, or `None` where RAM was not read.
    mem_percent: Option<f32>,
    /// Swap usage, or `None` where the pagefile was not read.
    ///
    /// A summary panel showing `SWAP 0%` for a machine whose swap could not be
    /// read is the most reassuring possible rendering of an unknown.
    swap_percent: Option<f32>,
    /// One-minute load, or `None` where the OS has none (Windows).
    load_1m: Option<f32>,
    cpu_trend: Option<&'static str>,
    mem_trend: Option<&'static str>,
}

impl QuickLookPanel {
    pub fn new(cpu: Option<f32>, mem: Option<f32>, swap: Option<f32>, load: Option<f32>) -> Self {
        Self {
            cpu_percent: cpu.map(|c| c.clamp(0.0, 100.0)),
            mem_percent: mem.map(|m| m.clamp(0.0, 100.0)),
            swap_percent: swap.map(|s| s.clamp(0.0, 100.0)),
            load_1m: load,
            cpu_trend: None,
            mem_trend: None,
        }
    }

    pub fn with_trends(mut self, cpu_trend: &'static str, mem_trend: &'static str) -> Self {
        self.cpu_trend = Some(cpu_trend);
        self.mem_trend = Some(mem_trend);
        self
    }
}

impl Widget for QuickLookPanel {
    fn ui(self, ui: &mut Ui) -> Response {
        let desired_size = Vec2::new(ui.available_width(), 48.0);
        let (rect, response) = ui.allocate_exact_size(desired_size, Sense::hover());

        if ui.is_rect_visible(rect) {
            let painter = ui.painter();

            // Background
            painter.rect_filled(rect, 4.0, theme::color(ui.ctx(), CyberColors::SURFACE));

            // Calculate bar widths (4 equal sections)
            let section_width = rect.width() / 4.0 - 8.0;
            let bar_height = 16.0;
            let y_center = rect.center().y;

            // Draw each metric
            let metrics = [
                ("CPU", self.cpu_percent, self.cpu_trend),
                ("MEM", self.mem_percent, self.mem_trend),
                ("SWAP", self.swap_percent, None),
                // LOAD has no percentage. The load average is not a share of
                // anything, and the x10 scale this used to draw against was a
                // constant guess, so LOAD shows its value and no bar.
                ("LOAD", None, None),
            ];

            for (i, (label, percent, trend)) in metrics.iter().enumerate() {
                // A metric with no reading draws its label and a dash, and no
                // bar at all -- an empty bar is indistinguishable from a bar at
                // zero, and only one of those is something that was measured.
                let percent = *percent;
                let has_bar = *label != "LOAD";
                let x_start = rect.min.x + 4.0 + i as f32 * (section_width + 8.0);

                // Label with trend
                let label_text = if let Some(t) = trend {
                    format!("{} {}", t, label)
                } else {
                    label.to_string()
                };

                painter.text(
                    Pos2::new(x_start, y_center - 10.0),
                    egui::Align2::LEFT_CENTER,
                    &label_text,
                    theme::data_font(ui.ctx(), 10.0),
                    theme::legible(
                        ui.ctx(),
                        theme::color(ui.ctx(), CyberColors::TEXT_SECONDARY),
                    ),
                );

                // Mini bar. Drawn only for a reading that has a percentage; the
                // track of an unread metric or of LOAD is left out, not emptied.
                if let (true, Some(pct)) = (has_bar, percent) {
                    let bar_rect = Rect::from_min_size(
                        Pos2::new(x_start, y_center),
                        Vec2::new(section_width * 0.6, bar_height),
                    );
                    painter.rect_filled(
                        bar_rect,
                        2.0,
                        theme::color(ui.ctx(), CyberColors::BACKGROUND_DARK),
                    );
                    let fill_width = bar_rect.width() * (pct / 100.0);
                    if fill_width > 0.0 {
                        let fill_rect = Rect::from_min_size(
                            bar_rect.min,
                            Vec2::new(fill_width, bar_rect.height()),
                        );
                        painter.rect_filled(
                            fill_rect,
                            2.0,
                            theme::color(ui.ctx(), threshold_color(pct)),
                        );
                    }
                }

                // Percentage text
                let percent_text = match (percent, *label == "LOAD") {
                    (_, true) => self
                        .load_1m
                        .map_or_else(|| "-".to_string(), |l| format!("{l:.2}")),
                    (Some(pct), false) => format!("{pct:.0}%"),
                    (None, false) => "-".to_string(),
                };

                painter.text(
                    Pos2::new(x_start + section_width * 0.65, y_center + bar_height * 0.5),
                    egui::Align2::LEFT_CENTER,
                    percent_text,
                    theme::data_font(ui.ctx(), 13.0),
                    // An unread value takes the neutral text colour. Coloring
                    // the dash by threshold_color(0.0) gave it the "healthy"
                    // green, which reads as a measured low reading.
                    theme::legible(
                        ui.ctx(),
                        match percent {
                            Some(pct) if has_bar => theme::color(ui.ctx(), threshold_color(pct)),
                            _ => theme::color(ui.ctx(), CyberColors::TEXT_SECONDARY),
                        },
                    ),
                );
            }

            // Border
            painter.rect_stroke(
                rect,
                4.0,
                Stroke::new(1.0_f32, theme::color(ui.ctx(), CyberColors::BORDER)),
                egui::StrokeKind::Middle,
            );
        }

        response
    }
}

/// Glances-style threshold legend
pub struct ThresholdLegend;

impl Widget for ThresholdLegend {
    fn ui(self, ui: &mut Ui) -> Response {
        let desired_size = Vec2::new(ui.available_width(), 20.0);
        let (rect, response) = ui.allocate_exact_size(desired_size, Sense::hover());

        if ui.is_rect_visible(rect) {
            let painter = ui.painter();
            let y = rect.center().y;

            let items = [
                (
                    "OK",
                    theme::color(ui.ctx(), CyberColors::THRESHOLD_OK),
                    "0-50%",
                ),
                (
                    "CAREFUL",
                    theme::color(ui.ctx(), CyberColors::THRESHOLD_CAREFUL),
                    "50-70%",
                ),
                (
                    "WARNING",
                    theme::color(ui.ctx(), CyberColors::THRESHOLD_WARNING),
                    "70-90%",
                ),
                (
                    "CRITICAL",
                    theme::color(ui.ctx(), CyberColors::THRESHOLD_CRITICAL),
                    "90%+",
                ),
            ];

            let mut x = rect.min.x;
            for (label, color, range) in items {
                // Color dot
                painter.circle_filled(Pos2::new(x + 6.0, y), 4.0, color);

                // Label
                painter.text(
                    Pos2::new(x + 14.0, y),
                    egui::Align2::LEFT_CENTER,
                    label,
                    theme::data_font(ui.ctx(), 10.0),
                    theme::legible(ui.ctx(), color),
                );

                // Range
                let label_width = painter
                    .layout_no_wrap(label.to_string(), theme::data_font(ui.ctx(), 10.0), color)
                    .rect
                    .width();

                let range_rect = painter.text(
                    Pos2::new(x + 16.0 + label_width, y),
                    egui::Align2::LEFT_CENTER,
                    range,
                    theme::data_font(ui.ctx(), 9.0),
                    theme::legible(
                        ui.ctx(),
                        theme::color(ui.ctx(), CyberColors::TEXT_SECONDARY),
                    ),
                );

                // Advance past what was drawn. A fixed 90 points overlapped as
                // soon as the bold data face made "CAREFUL 50-70%" wider.
                x = range_rect.max.x + 16.0;
            }
        }

        response
    }
}

/// Section heading whose domain word comes from the ontology rather than a literal.
///
/// The three surfaces used to spell the same domain three ways — the CLI said
/// `cpu`, the GUI said `CPU`, the JSON said `Cpu` — which is what stops an agent
/// correlating a heading a user is looking at with an id it can query. Routing the
/// domain word through [`crate::ontology::labels::domain_label`] makes the ontology
/// the single naming authority, so a heading cannot drift from the id space.
///
/// `domain` must be a domain the ontology knows; unknown domains are returned
/// title-cased rather than silently dropped, because a blank heading is worse than
/// an imperfect one.
pub fn domain_section_title(domain: &str, suffix: &str) -> String {
    let label = crate::ontology::labels::domain_label(domain);
    if suffix.is_empty() {
        label
    } else {
        format!("{label} {suffix}")
    }
}

#[cfg(test)]
mod section_title_tests {
    use super::*;

    #[test]
    fn domain_titles_use_the_ontology_spelling() {
        assert_eq!(
            domain_section_title("gpu", "Utilization"),
            "GPU Utilization"
        );
        assert_eq!(domain_section_title("cpu", "Overview"), "CPU Overview");
        assert_eq!(domain_section_title("network", "I/O"), "Network I/O");
        assert_eq!(domain_section_title("memory", ""), "Memory");
    }

    /// Whatever the surfaces render, the domain word has to be one the ontology
    /// recognises — otherwise the heading names something unqueryable.
    #[test]
    fn every_title_domain_is_queryable() {
        for domain in ["cpu", "gpu", "memory", "network", "disk", "thermal"] {
            assert!(
                crate::ontology::labels::is_known_domain(domain),
                "{domain} is used in a section title but is not an ontology domain"
            );
        }
    }
}

#[cfg(test)]
mod section_header_source_tests {
    use crate::ontology::labels;

    /// The GUI's own source, scanned for hardcoded section headings.
    ///
    /// Scanning the source is unusual in a test, but the alternative is worse: the
    /// headings are string literals scattered across five thousand lines, and there
    /// is no runtime registry to enumerate. Converting each by hand and trusting
    /// future edits to follow suit is exactly how the three surfaces drifted apart
    /// in the first place — the CLI saying `cpu`, the GUI `CPU`, the JSON `Cpu`.
    const GUI_SOURCE: &str = include_str!("app.rs");

    fn literal_headings() -> Vec<String> {
        let mut out = Vec::new();
        let needle = "SectionHeader::new(\"";
        let mut rest = GUI_SOURCE;
        while let Some(start) = rest.find(needle) {
            rest = &rest[start + needle.len()..];
            if let Some(end) = rest.find('"') {
                out.push(rest[..end].to_string());
            }
        }
        out
    }

    /// Any heading beginning with a word the ontology owns must spell it the
    /// ontology's way.
    ///
    /// Headings that are not entity namespaces — "Physical Memory", "Installed
    /// Drivers", "Nmap-Style Scan Results" — are deliberately untouched. Forcing
    /// those through the ontology would assert a correspondence that does not
    /// exist, which is its own kind of dishonesty.
    #[test]
    fn hardcoded_headings_do_not_contradict_the_ontology() {
        for heading in literal_headings() {
            // Strip a leading emoji or symbol so the first *word* is examined.
            let first_word = heading
                .split_whitespace()
                .find(|w| w.chars().any(|c| c.is_ascii_alphabetic()))
                .unwrap_or("");
            let lowered = first_word.to_ascii_lowercase();

            if labels::is_known_domain(&lowered) {
                assert_eq!(
                    first_word,
                    labels::domain_label(&lowered),
                    "the heading {heading:?} starts with the ontology domain \
                     {lowered:?} but spells it {first_word:?}; route it through \
                     `domain_section_title` so the surfaces cannot drift"
                );
            }
        }
    }

    /// The scan must actually find headings, or the assertion above is vacuous —
    /// a refactor that renamed the constructor would silently disable this test.
    #[test]
    fn the_source_scan_finds_headings() {
        let found = literal_headings();
        assert!(
            found.len() > 10,
            "expected the GUI to contain many section headings; the scan found \
             {} — has `SectionHeader::new` been renamed?",
            found.len()
        );
    }
}