-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathui.rs
More file actions
2550 lines (2364 loc) · 83.7 KB
/
Copy pathui.rs
File metadata and controls
2550 lines (2364 loc) · 83.7 KB
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
use ratatui::{
layout::{Constraint, Direction, Layout, Margin, Rect},
style::{Color, Modifier, Style},
text::{Line, Span},
widgets::{Block, Borders, Cell, Clear, Paragraph, Row, ScrollbarState, Table, TableState},
Frame,
};
use super::app::{
all_columns, App, CounterRate, DeviceClass, PortThroughput, TableColumn, EXTRA_COUNTERS,
};
use super::theme::ThemeColors;
use crate::gpu::GpuMetrics;
const HELP_KEYS: &[(&str, &str)] = &[
("↑ / k", "Move up"),
("↓ / j", "Move down"),
("← / →", "Scroll columns"),
("Enter", "Toggle detail panel"),
("Esc", "Close detail / quit"),
("t", "Cycle theme"),
("Tab / S-Tab", "Switch device class (RDMA/XGMI/NVLink)"),
("a", "Toggle rolling average"),
("+ / =", "Increase avg window (+1s)"),
("-", "Decrease avg window (-1s)"),
("w", "Set avg window (custom)"),
("< / >", "Refresh faster / slower (±0.5s)"),
("c", "Configure columns"),
("r", "Record Perfetto trace (start/stop)"),
("h", "Toggle this help"),
("q", "Quit"),
];
const RDMA_LINK_GBPS: f64 = 100.0;
pub fn draw(frame: &mut Frame, app: &mut App) {
let tc = app.theme.colors();
if tc.bg != ratatui::style::Color::Reset {
frame.render_widget(
Block::default().style(Style::default().bg(tc.bg)),
frame.area(),
);
}
if app.seen_tabs.len() >= 2 {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(5),
Constraint::Length(1),
Constraint::Min(5),
Constraint::Length(1),
])
.split(frame.area());
draw_header(frame, app, chunks[0], &tc);
draw_tab_bar(frame, app, chunks[1], &tc);
draw_body(frame, app, chunks[2], &tc);
draw_status_bar(frame, app, chunks[3], &tc);
} else {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(5),
Constraint::Min(5),
Constraint::Length(1),
])
.split(frame.area());
draw_header(frame, app, chunks[0], &tc);
draw_body(frame, app, chunks[1], &tc);
draw_status_bar(frame, app, chunks[2], &tc);
}
if app.show_help {
draw_help_popup(frame, &tc);
}
if app.show_window_input {
draw_window_input_popup(frame, app, &tc);
}
if app.show_column_picker {
draw_column_picker(frame, app, &tc);
}
}
fn draw_body(frame: &mut Frame, app: &mut App, area: Rect, tc: &ThemeColors) {
if app.show_detail {
let split = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
.split(area);
draw_table(frame, app, split[0], tc);
draw_detail(frame, app, split[1], tc);
} else {
draw_table(frame, app, area, tc);
}
}
fn header_line1(app: &App, tc: &ThemeColors) -> Line<'static> {
Line::from(vec![
styled(" rdmatop ", tc.accent, true),
styled(
&format!(
"- {} │ {} │ load average: {}",
app.sysinfo.hostname, app.sysinfo.uptime, app.sysinfo.load_avg
),
tc.muted,
false,
),
])
}
fn header_line2(app: &App, tc: &ThemeColors) -> Line<'static> {
let display = app.display_throughputs();
let n = display.len();
let total_tx: f64 = display.iter().map(|t| t.tx_gbps).sum();
let total_rx: f64 = display.iter().map(|t| t.rx_gbps).sum();
let total_drops: f64 = display.iter().map(|t| t.rx_drops_per_sec).sum();
let drop_color = if total_drops > 0.0 {
tc.error
} else {
tc.muted
};
let avg_label = if app.show_rolling_avg {
format!(
" │ avg:{}s({}/{})",
app.rolling_avg.window_secs,
app.rolling_avg.sample_count(),
app.rolling_avg.window_secs,
)
} else {
String::new()
};
let status = format!(
" │ refresh: {:.1}s │ theme: {}",
app.refresh_interval.as_secs_f64(),
app.theme.label()
);
let label = app.active_tab.label();
Line::from(vec![
styled(
&format!(" {}: {} device{}", label, n, if n == 1 { "" } else { "s" }),
tc.fg,
false,
),
styled(" │ TX: ", tc.muted, false),
styled(&format!("{:.2} Gbps", total_tx), tc.good, false),
styled(" │ RX: ", tc.muted, false),
styled(&format!("{:.2} Gbps", total_rx), tc.good, false),
styled(" │ Drops: ", tc.muted, false),
styled(&format!("{:.0}/s", total_drops), drop_color, false),
styled(&status, tc.muted, false),
styled(&avg_label, tc.accent, false),
])
}
fn cpu_bar(pct: f32, width: usize, tc: &ThemeColors) -> Vec<Span<'static>> {
let filled = ((pct / 100.0) * width as f32).round() as usize;
let empty = width.saturating_sub(filled);
let color = if pct > 80.0 {
tc.error
} else if pct > 50.0 {
tc.warning
} else {
tc.good
};
vec![
styled("[", tc.muted, false),
styled(&"|".repeat(filled), color, false),
styled(&" ".repeat(empty), tc.muted, false),
styled(&format!("{:>5.1}%]", pct), color, false),
]
}
fn mem_bar(used: u64, total: u64, pct: f32, width: usize, tc: &ThemeColors) -> Vec<Span<'static>> {
let filled = ((pct / 100.0) * width as f32).round() as usize;
let empty = width.saturating_sub(filled);
let color = if pct > 80.0 {
tc.error
} else if pct > 50.0 {
tc.warning
} else {
tc.good
};
let label = if total >= 1024 {
format!("{:.1}/{:.1}G]", used as f64 / 1024.0, total as f64 / 1024.0)
} else {
format!("{}/{}M]", used, total)
};
vec![
styled("[", tc.muted, false),
styled(&"|".repeat(filled), color, false),
styled(&" ".repeat(empty), tc.muted, false),
styled(&label, color, false),
]
}
fn header_line3(app: &App, tc: &ThemeColors) -> Line<'static> {
let s = &app.sysinfo;
let mut spans = vec![styled(" CPU ", tc.muted, false)];
spans.extend(cpu_bar(s.cpu_pct, 20, tc));
spans.push(styled(" Mem ", tc.muted, false));
spans.extend(mem_bar(s.mem_used_mb, s.mem_total_mb, s.mem_pct, 20, tc));
spans.push(styled(" Net ", tc.muted, false));
spans.push(styled(
&format!(
"↓{}/s ↑{}/s",
fmt_bytes_short(s.net.rx_bytes_per_sec),
fmt_bytes_short(s.net.tx_bytes_per_sec),
),
tc.fg,
false,
));
Line::from(spans)
}
fn draw_header(frame: &mut Frame, app: &App, area: Rect, tc: &ThemeColors) {
let block = Block::default()
.borders(Borders::ALL)
.border_set(super::glyphs::border())
.border_style(Style::default().fg(tc.border));
let lines = vec![
header_line1(app, tc),
header_line2(app, tc),
header_line3(app, tc),
];
frame.render_widget(Paragraph::new(lines).block(block), area);
}
/// One-line tab bar: ` RDMA │ XGMI │ NVLink `, active tab highlighted.
fn tab_bar_line(app: &App, tc: &ThemeColors) -> Line<'static> {
let mut spans: Vec<Span<'static>> = vec![styled(" ", tc.muted, false)];
for (i, tab) in app.seen_tabs.iter().enumerate() {
if i > 0 {
spans.push(styled(" │ ", tc.muted, false));
}
let label = tab.label();
if *tab == app.active_tab {
spans.push(Span::styled(
format!(" {} ", label),
Style::default()
.fg(Color::Black)
.bg(tc.accent)
.add_modifier(Modifier::BOLD),
));
} else {
spans.push(styled(&format!(" {} ", label), tc.muted, false));
}
}
Line::from(spans)
}
fn draw_tab_bar(frame: &mut Frame, app: &App, area: Rect, tc: &ThemeColors) {
frame.render_widget(Paragraph::new(tab_bar_line(app, tc)), area);
}
fn gbps_bar(gbps: f64, link_gbps: Option<f64>, width: usize) -> String {
// Scale to the port's line rate; fall back to a default when unknown.
let max = link_gbps.filter(|&r| r > 0.0).unwrap_or(RDMA_LINK_GBPS);
let ratio = (gbps / max).clamp(0.0, 1.0);
ratio_bar(ratio, width)
}
/// Meter string for a 0..=1 ratio, `width` chars, glyph-mode aware.
fn ratio_bar(ratio: f64, width: usize) -> String {
let filled = (ratio.clamp(0.0, 1.0) * width as f64).round() as usize;
let (fill, empty) = super::glyphs::meter();
let mut bar = String::with_capacity(width * fill.len_utf8());
bar.extend(std::iter::repeat_n(fill, filled));
bar.extend(std::iter::repeat_n(empty, width - filled));
bar
}
/// "██████░░░░ 87%" gauge text for a 0-100 percent, or "-" when None.
/// `bar_w` sizes the meter; the trailing " {:>3}%" text is fixed.
fn pct_gauge_text(pct: Option<u32>, bar_w: usize) -> String {
match pct {
Some(p) => format!("{} {:>3}%", ratio_bar(p as f64 / 100.0, bar_w), p),
None => "-".to_string(),
}
}
/// Scale column widths by a common fraction of their naturals to fit
/// `avail` (incl. one-cell gaps), flooring each at `mins`. Fits whenever
/// `avail >= sum(mins) + gaps`; below that all columns sit at their min
/// and ratatui clips. See the shave pass for how floor overshoot is paid.
fn scaled_col_widths(natural: &[u16], mins: &[u16], avail: u16) -> Vec<u16> {
debug_assert_eq!(natural.len(), mins.len());
if natural.is_empty() {
return Vec::new();
}
let gaps = natural.len().saturating_sub(1) as u16;
let total: u16 = natural.iter().sum::<u16>() + gaps;
if avail >= total {
return natural.to_vec();
}
// Rounded division avoids a systematic downward bias; overshoot from
// rounding or min-flooring is paid back by the shave pass below.
let mut out: Vec<u16> = natural
.iter()
.zip(mins)
.map(|(&nat, &min)| {
let scaled = (nat as u32 * avail as u32 + total as u32 / 2) / total as u32;
(scaled as u16).max(min)
})
.collect();
// Reclaim overshoot from columns still above their floor, largest
// excess first, so the result fits whenever sum(mins) does.
let mut sum: u16 = out.iter().sum();
while sum + gaps > avail {
let Some(i) = (0..out.len())
.filter(|&i| out[i] > mins[i])
.max_by_key(|&i| out[i] - mins[i])
else {
break; // all at min: avail < sum(mins)+gaps, clipping unavoidable
};
out[i] -= 1;
sum -= 1;
}
out
}
/// Natural per-column widths for the GPU table, scaled to fit `avail`
/// (inner table width) by a common fraction, each floored at a minimum
/// so labels stay legible before ratatui clips whole columns.
fn gpu_col_widths(avail: u16) -> [u16; 12] {
const BAR: u16 = super::app::BAR_WIDTH as u16;
const NATURAL: [u16; 12] = [9, 16, 16, 16, 5, 6, BAR, 7, BAR, 7, 6, 5];
const MIN: [u16; 12] = [7, 8, 9, 9, 4, 4, 6, 6, 6, 6, 5, 4];
scaled_col_widths(&NATURAL, &MIN, avail)
.try_into()
.expect("12 naturals in, 12 widths out")
}
/// Minimum width a scaled RDMA column may shrink to: bars stay 6 cells
/// wide so the meter reads; everything else keeps 3/5 of its natural
/// width (at least 4) so values stay legible.
fn rdma_col_min(col: &TableColumn) -> u16 {
match col {
TableColumn::TxBar | TableColumn::RxBar => 6,
_ => {
// 3/5 of natural, floored at 4 cells; capped at natural so a
// future column narrower than 4 can't get a min wider than itself.
let n = col.width();
(n * 3 / 5).max(4).min(n)
}
}
}
fn column_cell(
col: &TableColumn,
t: &PortThroughput,
tc: &ThemeColors,
col_w: u16,
) -> Cell<'static> {
match col {
TableColumn::Device => Cell::from(t.dev_name.clone()).style(Style::default().fg(tc.fg)),
TableColumn::Port => {
let port_text = t.port_label.clone().unwrap_or_else(|| t.port.to_string());
Cell::from(port_text).style(Style::default().fg(tc.muted))
}
TableColumn::TxBar => Cell::from(gbps_bar(t.tx_gbps, t.link_gbps, col_w as usize))
.style(Style::default().fg(throughput_color(t.tx_gbps, t.link_gbps, tc))),
TableColumn::TxGbps => Cell::from(format!("{:.2}", t.tx_gbps))
.style(Style::default().fg(throughput_color(t.tx_gbps, t.link_gbps, tc))),
TableColumn::RxBar => Cell::from(gbps_bar(t.rx_gbps, t.link_gbps, col_w as usize))
.style(Style::default().fg(throughput_color(t.rx_gbps, t.link_gbps, tc))),
TableColumn::RxGbps => Cell::from(format!("{:.2}", t.rx_gbps))
.style(Style::default().fg(throughput_color(t.rx_gbps, t.link_gbps, tc))),
TableColumn::TxPps => {
Cell::from(format_pps(t.tx_pkts_per_sec)).style(Style::default().fg(tc.fg))
}
TableColumn::RxPps => {
Cell::from(format_pps(t.rx_pkts_per_sec)).style(Style::default().fg(tc.fg))
}
TableColumn::Drops => {
let c = if t.rx_drops_per_sec > 0.0 {
tc.error
} else {
tc.muted
};
Cell::from(format!("{:.0}", t.rx_drops_per_sec)).style(Style::default().fg(c))
}
TableColumn::Counter(name) => {
let rate = t
.counter_rates
.iter()
.find(|r| &r.name == name)
.map(|r| r.rate)
.unwrap_or(0.0);
let is_bytes = t
.counter_rates
.iter()
.find(|r| &r.name == name)
.map(|r| r.is_bytes)
.unwrap_or(false);
let text = if is_bytes {
format_bytes(rate)
} else {
format_rate(rate)
};
let color = if rate > 0.0 { tc.fg } else { tc.muted };
Cell::from(text).style(Style::default().fg(color))
}
}
}
/// Marketing name from whichever GPU meta the row carries.
fn gpu_meta_name(t: &PortThroughput) -> String {
if let Some(ref m) = t.xgmi {
return m.gpu_name.clone();
}
if let Some(ref m) = t.nvlink {
return m.gpu_name.clone();
}
String::new()
}
/// XGMI: "ce/ue". NVLink: single summed nvlink_* error total.
fn gpu_errs(t: &PortThroughput) -> String {
let counter = |name: &str| {
t.counter_rates
.iter()
.find(|c| c.name == name)
.map(|c| c.value)
.unwrap_or(0)
};
if t.xgmi.is_some() {
return format!("{}/{}", counter("xgmi_wafl_ce"), counter("xgmi_wafl_ue"));
}
let sum: u64 = t
.counter_rates
.iter()
.filter(|c| c.name.starts_with("nvlink_"))
.map(|c| c.value)
.sum();
sum.to_string()
}
/// Health metrics from whichever GPU meta the row carries.
fn gpu_metrics(t: &PortThroughput) -> Option<&GpuMetrics> {
let nv = t.nvlink.as_ref().and_then(|m| m.metrics.as_ref());
nv.or_else(|| t.xgmi.as_ref().and_then(|m| m.metrics.as_ref()))
}
fn gpu_row_cells(t: &PortThroughput, tc: &ThemeColors, widths: &[u16; 12]) -> Vec<Cell<'static>> {
let m = gpu_metrics(t);
let util = m.and_then(|m| m.util_pct);
let mem = m.and_then(|m| match (m.vram_used_mb, m.vram_total_mb) {
(Some(used), Some(total)) if total > 0 => {
Some((used as f64 / total as f64 * 100.0).round() as u32)
}
_ => None,
});
// Gauge bar fills its column minus the fixed " 100%" suffix (5 chars).
let pct_cell = |p: Option<u32>, col_w: u16| {
let color = match p {
Some(v) => capacity_color(v as f64 / 100.0, tc),
None => tc.muted,
};
let bar_w = (col_w as usize).saturating_sub(5).max(3);
Cell::from(pct_gauge_text(p, bar_w)).style(Style::default().fg(color))
};
let temp_cell = match m.and_then(|m| m.temp_c) {
Some(t) => Cell::from(format!("{}C", t)).style(Style::default().fg(temp_color(t, tc))),
None => Cell::from("-").style(Style::default().fg(tc.muted)),
};
let pwr_cell = match m.and_then(|m| m.power_w) {
Some(p) => Cell::from(format!("{:.0}W", p)).style(Style::default().fg(tc.fg)),
None => Cell::from("-").style(Style::default().fg(tc.muted)),
};
// Bar and Gbps live in separate cells styled with gbps_color, exactly
// like the RDMA table, so the two tabs stay visually aligned.
vec![
Cell::from(t.dev_name.clone()).style(Style::default().fg(tc.fg)),
Cell::from(gpu_meta_name(t)).style(Style::default().fg(tc.muted)),
pct_cell(util, widths[2]),
pct_cell(mem, widths[3]),
temp_cell,
pwr_cell,
Cell::from(gbps_bar(t.tx_gbps, t.link_gbps, widths[6] as usize))
.style(Style::default().fg(throughput_color(t.tx_gbps, t.link_gbps, tc))),
Cell::from(format!("{:.2}", t.tx_gbps)).style(Style::default().fg(throughput_color(
t.tx_gbps,
t.link_gbps,
tc,
))),
Cell::from(gbps_bar(t.rx_gbps, t.link_gbps, widths[8] as usize))
.style(Style::default().fg(throughput_color(t.rx_gbps, t.link_gbps, tc))),
Cell::from(format!("{:.2}", t.rx_gbps)).style(Style::default().fg(throughput_color(
t.rx_gbps,
t.link_gbps,
tc,
))),
Cell::from(t.port_label.clone().unwrap_or_default()).style(Style::default().fg(tc.fg)),
Cell::from(gpu_errs(t)).style(Style::default().fg(tc.warning)),
]
}
/// Bordered placeholder shown in a table area before the first snapshot:
/// "initializing" while the sampler is warming up, "failed" once it died.
fn draw_startup_placeholder(
frame: &mut Frame,
app: &App,
area: Rect,
tc: &ThemeColors,
title: String,
) {
let text = if app.sampler_error.is_some() {
"sampling failed - see status bar"
} else {
"initializing devices..."
};
let block = Block::default()
.borders(Borders::ALL)
.border_set(super::glyphs::border())
.border_style(Style::default().fg(tc.border))
.title(title)
.title_style(Style::default().fg(tc.accent));
let msg = Paragraph::new(text)
.style(Style::default().fg(tc.muted))
.block(block);
frame.render_widget(msg, area);
}
/// GPU-tab table: fixed columns for XGMI / NVLink rows.
/// h-scroll and the column picker are RDMA-only; this function ignores both.
fn draw_gpu_table(frame: &mut Frame, app: &mut App, area: Rect, tc: &ThemeColors) {
let display = app.display_throughputs().to_vec();
let label = app.active_tab.label();
let title = if app.show_rolling_avg {
format!(
" {} Throughput (avg {}s) ",
label, app.rolling_avg.window_secs
)
} else {
format!(" {} Throughput ", label)
};
// Before the first background-sampler snapshot arrives, show a placeholder.
if display.is_empty() && !app.has_data {
draw_startup_placeholder(frame, app, area, tc, title);
return;
}
let header = Row::new(vec![
"Device", "Name", "Util", "Mem", "Temp", "Pwr", "TX", "Gbps", "RX", "Gbps", "Links", "Errs",
])
.style(
Style::default()
.fg(tc.header_fg)
.add_modifier(Modifier::BOLD),
)
.height(1);
// Block borders (2) and the "▶ " highlight column (2) shrink what the
// Table layout actually distributes among columns; scale to fit that.
let avail = area.width.saturating_sub(2 + 2);
let widths = gpu_col_widths(avail);
let rows: Vec<Row> = display
.iter()
.map(|t| Row::new(gpu_row_cells(t, tc, &widths)))
.collect();
let table = Table::new(rows, widths.map(Constraint::Length))
.header(header)
.block(
Block::default()
.borders(Borders::ALL)
.border_set(super::glyphs::border())
.border_style(Style::default().fg(tc.border))
.title(title)
.title_style(Style::default().fg(tc.accent)),
)
.row_highlight_style(
Style::default()
.bg(tc.highlight_bg)
.add_modifier(Modifier::BOLD),
)
.highlight_symbol(super::glyphs::cursor());
let mut state = TableState::default();
if !display.is_empty() {
let viewport = area.height.saturating_sub(4) as usize;
if viewport > 0 {
if app.selected_row >= app.table_offset + viewport {
app.table_offset = app.selected_row + 1 - viewport;
} else if app.selected_row < app.table_offset {
app.table_offset = app.selected_row;
}
}
state.select(Some(app.selected_row));
*state.offset_mut() = app.table_offset;
}
frame.render_stateful_widget(table, area, &mut state);
if display.len() > area.height.saturating_sub(4) as usize {
let mut v_scroll = ScrollbarState::new(display.len()).position(app.selected_row);
frame.render_stateful_widget(
super::glyphs::v_scrollbar()
.thumb_style(Style::default().fg(tc.accent))
.track_style(Style::default().fg(tc.border)),
area.inner(Margin {
vertical: 1,
horizontal: 0,
}),
&mut v_scroll,
);
}
}
fn draw_table(frame: &mut Frame, app: &mut App, area: Rect, tc: &ThemeColors) {
if app.active_tab != DeviceClass::Rdma {
draw_gpu_table(frame, app, area, tc);
return;
}
let display = app.display_throughputs().to_vec();
let title = if app.show_rolling_avg {
format!(" RDMA Throughput (avg {}s) ", app.rolling_avg.window_secs)
} else {
" RDMA Throughput ".to_string()
};
// Before the first background-sampler snapshot arrives, show a placeholder.
if display.is_empty() && !app.has_data {
draw_startup_placeholder(frame, app, area, tc, title);
return;
}
// In detail mode, use default columns with no scrolling (original behavior).
// In normal mode, use configured columns with horizontal scroll.
let default_cols = super::app::default_columns();
let (cols_to_render, show_scrollbars) = if app.show_detail {
(default_cols.iter().collect::<Vec<_>>(), false)
} else {
let all_cols = &app.columns;
let avail = area.width.saturating_sub(4) as usize;
let visible: Vec<&super::app::TableColumn> = all_cols
.iter()
.skip(app.h_scroll)
.scan(0usize, |used, col| {
let sep = if *used > 0 { 1 } else { 0 };
let w = col.width() as usize + sep;
if *used + w <= avail {
*used += w;
Some(col)
} else {
None
}
})
.collect();
// Compute max horizontal scroll
let mut max_offset = 0;
for start in 0..all_cols.len() {
let total_w: usize = all_cols[start..]
.iter()
.map(|c| c.width() as usize + 1)
.sum();
if total_w > avail {
max_offset = start + 1;
} else {
break;
}
}
app.h_scroll_max = max_offset;
if app.h_scroll > app.h_scroll_max {
app.h_scroll = app.h_scroll_max;
}
(visible, true)
};
let header = Row::new(
cols_to_render
.iter()
.map(|c| c.header_label())
.collect::<Vec<_>>(),
)
.style(
Style::default()
.fg(tc.header_fg)
.add_modifier(Modifier::BOLD),
)
.height(1);
// Scale the rendered set to fit, like the GPU table. Normal-mode
// windowing already fits naturals, so scaling only bites when it
// doesn't (detail mode's fixed default set, or a too-narrow pane).
let natural: Vec<u16> = cols_to_render.iter().map(|c| c.width()).collect();
let mins: Vec<u16> = cols_to_render.iter().map(|c| rdma_col_min(c)).collect();
// Block borders (2) and the highlight column (2), as in draw_gpu_table.
let col_widths = scaled_col_widths(&natural, &mins, area.width.saturating_sub(2 + 2));
let rows: Vec<Row> = display
.iter()
.map(|t| {
Row::new(
cols_to_render
.iter()
.zip(&col_widths)
.map(|(c, &w)| column_cell(c, t, tc, w))
.collect::<Vec<_>>(),
)
})
.collect();
let widths: Vec<Constraint> = col_widths.iter().map(|&w| Constraint::Length(w)).collect();
let table = Table::new(rows, widths)
.header(header)
.block(
Block::default()
.borders(Borders::ALL)
.border_set(super::glyphs::border())
.border_style(Style::default().fg(tc.border))
.title(title)
.title_style(Style::default().fg(tc.accent)),
)
.row_highlight_style(
Style::default()
.bg(tc.highlight_bg)
.add_modifier(Modifier::BOLD),
)
.highlight_symbol(super::glyphs::cursor());
let mut state = TableState::default();
if !display.is_empty() {
let viewport = area.height.saturating_sub(4) as usize; // borders + header
if viewport > 0 {
if app.selected_row >= app.table_offset + viewport {
app.table_offset = app.selected_row + 1 - viewport;
} else if app.selected_row < app.table_offset {
app.table_offset = app.selected_row;
}
}
state.select(Some(app.selected_row));
*state.offset_mut() = app.table_offset;
}
frame.render_stateful_widget(table, area, &mut state);
if !show_scrollbars {
return;
}
// Vertical scrollbar (right side, inside border)
if display.len() > area.height.saturating_sub(4) as usize {
let mut v_scroll = ScrollbarState::new(display.len()).position(app.selected_row);
frame.render_stateful_widget(
super::glyphs::v_scrollbar()
.thumb_style(Style::default().fg(tc.accent))
.track_style(Style::default().fg(tc.border)),
area.inner(Margin {
vertical: 1,
horizontal: 0,
}),
&mut v_scroll,
);
}
// Horizontal scrollbar (bottom, inside border)
let all_cols = &app.columns;
if all_cols.len() > cols_to_render.len() || app.h_scroll > 0 {
let mut h_scroll = ScrollbarState::new(all_cols.len()).position(app.h_scroll);
frame.render_stateful_widget(
super::glyphs::h_scrollbar()
.thumb_style(Style::default().fg(tc.accent))
.track_style(Style::default().fg(tc.border)),
area.inner(Margin {
vertical: 0,
horizontal: 1,
}),
&mut h_scroll,
);
}
}
fn sparkline_str(data: &[f64], width: usize) -> String {
let max = data.iter().copied().fold(0.0f64, f64::max);
sparkline_scaled(data, width, max)
}
/// Render a sparkline with a fixed `max` scale (e.g. 100.0 for percentages).
fn sparkline_scaled(data: &[f64], width: usize, max: f64) -> String {
// Height ramps by index 0..8; ASCII keeps the graph shape without a
// mushy underline (idle reads as '.', not '_') in non-UTF-8 locales.
const U: &[char] = &[' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
const A: &[char] = &[' ', '.', '.', ':', ':', '=', '=', '#', '#'];
let bars = if super::glyphs::unicode() { U } else { A };
let max = max.max(0.01);
let start = data.len().saturating_sub(width);
let mut s = String::with_capacity(width);
for &v in &data[start..] {
let idx = ((v / max) * 8.0).round() as usize;
s.push(bars[idx.min(8)]);
}
// Pad if not enough data
while s.chars().count() < width {
s.insert(0, ' ');
}
s
}
/// Append GPU health lines: util sparkline (fixed 0-100 scale) plus a
/// temp/power/clock summary with '-' fallbacks for missing values.
fn append_gpu_health(
lines: &mut Vec<Line<'static>>,
metrics: Option<&crate::gpu::GpuMetrics>,
history: Option<&super::app::DeviceHistory>,
spark_w: usize,
tc: &ThemeColors,
) {
let Some(m) = metrics else { return };
if let Some(h) = history {
if !h.util.is_empty() {
let pct_span = match m.util_pct {
Some(u) => styled(
&format!(" {}%", u),
capacity_color(u as f64 / 100.0, tc),
false,
),
None => styled(" -%", tc.muted, false),
};
lines.push(Line::from(vec![
styled(" Util ", tc.muted, false),
styled(&sparkline_scaled(&h.util, spark_w, 100.0), tc.accent, false),
pct_span,
]));
}
}
let mem = match (m.vram_used_mb, m.vram_total_mb) {
(Some(u), Some(t)) if t > 0 => {
format!("{:.1}/{:.1}G", u as f64 / 1024.0, t as f64 / 1024.0)
}
_ => "-".to_string(),
};
let temp = m.temp_c.map_or("-".to_string(), |t| format!("{}C", t));
let pwr = m.power_w.map_or("-".to_string(), |p| format!("{:.0}W", p));
let clk = m.clock_mhz.map_or("-".to_string(), |c| format!("{}MHz", c));
lines.push(Line::from(styled(
&format!(" Mem {} Temp {} Pwr {} Clk {}", mem, temp, pwr, clk),
tc.fg,
false,
)));
}
fn build_detail_lines(
t: &PortThroughput,
procs: &[&crate::stat::ProcessRdmaInfo],
history: Option<&super::app::DeviceHistory>,
tc: &ThemeColors,
show_avg: bool,
avg_window: usize,
) -> Vec<Line<'static>> {
let mut lines = build_device_header(t, history, tc, show_avg, avg_window);
append_active_counters(&mut lines, t, tc);
append_process_table(&mut lines, procs, tc);
lines
}
/// Build the per-lane detail panel for a NVLink GPU row.
///
/// Layout: header, TX/RX sparklines, lane table (Lane, State, Ver,
/// TX MB/s, RX MB/s, Remote), summed error counters.
fn build_nvlink_detail_lines(
t: &PortThroughput,
meta: &super::app::NvLinkThroughputMeta,
history: Option<&super::app::DeviceHistory>,
tc: &ThemeColors,
show_avg: bool,
avg_window: usize,
) -> Vec<Line<'static>> {
let spark_w = 30;
let (tx_spark, rx_spark) = match history {
Some(h) => (sparkline_str(&h.tx, spark_w), sparkline_str(&h.rx, spark_w)),
None => (" ".repeat(spark_w), " ".repeat(spark_w)),
};
let avg_label = if show_avg {
format!(" [avg {}s]", avg_window)
} else {
String::new()
};
let mut lines: Vec<Line<'static>> = Vec::new();
// Header: Device: nvidiaN [NVLink] active/total active
lines.push(Line::from(vec![
styled(" Device: ", tc.muted, false),
styled(&t.dev_name, tc.accent, true),
styled(" [NVLink] ", tc.accent, false),
styled(
&format!("{}/{} active", meta.active_links, meta.links.len()),
tc.fg,
false,
),
styled(&avg_label, tc.accent, false),
]));
// Aggregate TX line with sparkline.
lines.push(Line::from(vec![
styled(" TX: ", tc.muted, false),
styled(&format!("{:.2} Gbps ", t.tx_gbps), tc.good, false),
styled(&tx_spark, tc.good, false),
]));
// Aggregate RX line with sparkline.
lines.push(Line::from(vec![
styled(" RX: ", tc.muted, false),
styled(&format!("{:.2} Gbps ", t.rx_gbps), tc.accent, false),
styled(&rx_spark, tc.accent, false),
]));
append_gpu_health(&mut lines, meta.metrics.as_ref(), history, spark_w, tc);
lines.push(Line::from(""));
// Muted note explaining that the per-lane TX/RX columns below show the
// GPU-wide aggregate, since NVML does not expose per-lane throughput.
lines.push(Line::from(styled(
" Per-lane throughput is not available from NVML on some drivers; values below show either per-lane rate or the GPU aggregate.",
tc.muted,
false,
)));
// Lane table header.
lines.push(Line::from(vec![styled(
" Lane State Ver TX MB/s RX MB/s Remote",
tc.header_fg,
true,
)]));
// One row per link (active + inactive). Render per-lane throughput if available,
// otherwise fallback to the GPU aggregate rate (converted from Gbps to MB/s).
for link in &meta.links {
let link_tx_mb_s = match link.tx_bytes {
Some(bytes) => bytes as f64 / 1_000_000.0,
None => t.tx_gbps * 1000.0 / 8.0,
};
let link_rx_mb_s = match link.rx_bytes {
Some(bytes) => bytes as f64 / 1_000_000.0,
None => t.rx_gbps * 1000.0 / 8.0,
};
let state_label = if link.is_active {
"enabled"
} else {
"disabled"
};
let state_color = if link.is_active { tc.good } else { tc.muted };
let ver_label = link
.version
.map(|v| v.to_string())
.unwrap_or_else(|| "-".to_string());
let remote_label = match (&link.remote_pci_bdf, &link.remote_device_type) {
(Some(bdf), ty) => format!("{} {}", ty.label(), bdf),
(None, ty) => match ty {
crate::nvlink::RemoteDeviceType::Unknown => "-".to_string(),
_ => ty.label().to_string(),
},
};
lines.push(Line::from(vec![
styled(&format!(" {:>4}", link.link_id), tc.accent, false),
styled(&format!(" {:<8}", state_label), state_color, false),
styled(&format!(" {:>3}", ver_label), tc.fg, false),
styled(&format!(" {:>6.1}", link_tx_mb_s), tc.fg, false),
styled(&format!(" {:>6.1}", link_rx_mb_s), tc.fg, false),
styled(&format!(" {}", remote_label), tc.muted, false),
]));
}
lines.push(Line::from(""));
// Errors line: sum per-link counters across all lanes. None -> 0.
let mut crc: u64 = 0;
let mut replay: u64 = 0;
let mut recovery: u64 = 0;
for link in &meta.links {
crc = crc.saturating_add(link.crc_error_count.unwrap_or(0));
replay = replay.saturating_add(link.replay_error_count.unwrap_or(0));
recovery = recovery.saturating_add(link.recovery_error_count.unwrap_or(0));
}
lines.push(Line::from(vec![
styled(" Errors: ", tc.muted, false),
styled(&format!("replay={}", replay), tc.warning, false),
styled(" ", tc.muted, false),
styled(&format!("recovery={}", recovery), tc.warning, false),
styled(" ", tc.muted, false),
styled(&format!("crc={}", crc), tc.warning, false),
]));
lines
}
/// Build the per-link detail panel for an XGMI GPU row.
/// Layout mirrors the NVLink pane: header, TX/RX sparklines, a link table