gpur 0.5.0

btop-style GPU monitor TUI — NVIDIA, AMD, Apple Silicon; Linux, macOS, Windows
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
use crate::app::{App, GraphStyle};
use crate::backend::GpuSnapshot;
use crate::theme::UiTheme;
use ratatui::Frame;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::Style;
use ratatui::text::{Line, Span};
use ratatui::widgets::{
    Block, BorderType, Cell, Paragraph, Row, Scrollbar, ScrollbarOrientation, ScrollbarState, Table,
};

/// Minimum rows for an unfolded GPU card (borders + meters + info + waveform).
const CARD_MIN: u16 = 8;

pub fn draw(frame: &mut Frame, app: &mut App) {
    let area = frame.area();
    frame.render_widget(
        Block::new().style(Style::new().bg(app.theme.bg).fg(app.theme.fg)),
        area,
    );

    if app.splash_active() {
        crate::splash::render(frame, area, app.started, &app.splash_path, &app.theme);
        return;
    }

    let [header, body, footer] = Layout::vertical([
        Constraint::Length(1),
        Constraint::Fill(1),
        Constraint::Length(1),
    ])
    .areas(area);

    {
        let t = &app.theme;
        let mut head = vec![
            Span::styled(format!(" gpur v{} ", env!("CARGO_PKG_VERSION")), t.title),
            Span::styled(format!("[{}] ", app.backend.name()), t.dim),
            Span::styled(format!("{}ms ", app.tick_ms), t.dim),
        ];
        if app.paused {
            head.push(Span::styled("PAUSED ", t.temp_warn));
        }
        if let Some(err) = &app.poll_error {
            head.push(Span::styled(format!("{err} "), t.temp_crit));
        }
        if let Some(msg) = app.status_line() {
            head.push(Span::styled(format!("· {msg} "), t.spark_power));
        }
        frame.render_widget(Paragraph::new(Line::from(head)), header);
    }

    // Process pane takes only what it needs, up to 30% of the body; the GPU
    // cards get the rest. Careful on tiny terminals: the cap can drop below
    // the 4-row minimum.
    let want = app.procs.len() as u16 + 3;
    let cap = ((body.height * 3) / 10).max(4);
    let proc_height = want.min(cap).min(body.height);
    let [gpus_area, proc_area] =
        Layout::vertical([Constraint::Fill(1), Constraint::Length(proc_height)]).areas(body);

    app.gpus_rect = gpus_area;
    app.proc_rect = proc_area;
    draw_gpus(frame, gpus_area, app);
    draw_processes(frame, proc_area, app);

    let footer_line = if app.input_mode == crate::app::InputMode::Filter {
        Line::from(vec![
            Span::styled(" filter> ", app.theme.title),
            Span::styled(app.filter_input.clone(), Style::new().fg(app.theme.fg)),
            Span::styled("", app.theme.title),
            Span::styled("  (Enter apply · empty clears · Esc cancel)", app.theme.dim),
        ])
    } else {
        Line::styled(
            " q quit  ␣ pause  p procs  0-9 gpu  j/k move  s sort  r rev  / filter  x/X kill  +/- rate",
            app.theme.dim,
        )
    };
    frame.render_widget(Paragraph::new(footer_line), footer);

    draw_confirm_popup(frame, area, app);
}

/// Centered y/N dialog for a pending kill.
fn draw_confirm_popup(frame: &mut Frame, area: Rect, app: &App) {
    let Some((pid, force, cmd)) = &app.pending_kill else {
        return;
    };
    let t = &app.theme;
    let sig = if *force { "SIGKILL" } else { "SIGTERM" };
    let text = format!("send {sig} to {pid}?");
    let w = (text.len().max(cmd.len()) as u16 + 6).min(area.width);
    let h = 5u16.min(area.height);
    let popup = Rect::new(
        area.x + (area.width.saturating_sub(w)) / 2,
        area.y + (area.height.saturating_sub(h)) / 2,
        w,
        h,
    );
    frame.render_widget(ratatui::widgets::Clear, popup);
    let block = Block::bordered()
        .border_type(BorderType::Rounded)
        .border_style(t.temp_crit)
        .title(caption("confirm".into(), t.temp_crit, t.temp_crit));
    let inner = block.inner(popup);
    frame.render_widget(block, popup);
    let lines = vec![
        Line::styled(text, Style::new().fg(t.fg)),
        Line::styled(cmd.clone(), t.dim),
        Line::from(vec![
            Span::styled("y", t.temp_crit),
            Span::styled(" confirm · ", t.dim),
            Span::styled("any other key", Style::new().fg(t.fg)),
            Span::styled(" cancels", t.dim),
        ]),
    ];
    frame.render_widget(Paragraph::new(lines), inner);
}

/// GPU card region. When every card fits it behaves like a plain vertical
/// split; when it overflows (many GPUs / small terminal) it becomes a
/// scrolled list of fixed-height cards with a scrollbar, keeping the
/// selected card visible.
fn draw_gpus(frame: &mut Frame, area: Rect, app: &mut App) {
    let t = &app.theme;
    if app.gpus.is_empty() {
        frame.render_widget(
            Paragraph::new("no GPUs reported by backend").style(t.dim),
            area,
        );
        return;
    }

    let height_of =
        |app: &App, i: usize| -> u16 { if app.folded.contains(&i) { 1 } else { CARD_MIN } };
    let n = app.gpus.len();
    let needed: u16 = (0..n).map(|i| height_of(app, i)).sum();

    if needed <= area.height {
        // Everything fits: unfolded cards stretch to share the space.
        app.gpu_scroll = 0;
        let rows = Layout::vertical((0..n).map(|i| {
            if app.folded.contains(&i) {
                Constraint::Length(1)
            } else {
                Constraint::Fill(1)
            }
        }))
        .split(area);
        app.card_rects = rows.iter().copied().zip(0..n).collect();
        for (i, gpu) in app.gpus.iter().enumerate() {
            if app.folded.contains(&i) {
                draw_gpu_folded(frame, rows[i], app, gpu, i);
            } else {
                draw_gpu(frame, rows[i], app, gpu, i);
            }
        }
        return;
    }

    // Overflow: scroll whole cards so the selection stays visible.
    app.gpu_scroll = app.gpu_scroll.min(n - 1).min(app.selected);
    loop {
        let visible_span: u16 = (app.gpu_scroll..=app.selected)
            .map(|i| height_of(app, i))
            .sum();
        if visible_span <= area.height || app.gpu_scroll >= app.selected {
            break;
        }
        app.gpu_scroll += 1;
    }

    // How many whole cards fit at their minimum height...
    let mut shown = 0usize;
    let mut used = 0u16;
    for i in app.gpu_scroll..n {
        let h = height_of(app, i);
        if used + h > area.height {
            break;
        }
        used += h;
        shown += 1;
    }
    let shown = shown.max(1);

    // ...then let that window stretch to fill the area — no dead gap.
    let cards = Rect {
        width: area.width.saturating_sub(1),
        ..area
    };
    let window: Vec<usize> = (app.gpu_scroll..(app.gpu_scroll + shown).min(n)).collect();
    let rows = Layout::vertical(window.iter().map(|i| {
        if app.folded.contains(i) {
            Constraint::Length(1)
        } else {
            Constraint::Fill(1)
        }
    }))
    .split(cards);
    app.card_rects = rows.iter().copied().zip(window.iter().copied()).collect();
    for (slot, &i) in rows.iter().zip(&window) {
        let gpu = &app.gpus[i];
        if app.folded.contains(&i) {
            draw_gpu_folded(frame, *slot, app, gpu, i);
        } else {
            draw_gpu(frame, *slot, app, gpu, i);
        }
    }

    // ratatui quirk: the thumb only reaches the track end when
    // position == content_length - 1, so content_length must be the number
    // of SCROLL POSITIONS (max_scroll + 1), not the item count. With
    // viewport = shown this also keeps thumb size = shown/total of track.
    let max_scroll = n.saturating_sub(shown);
    let mut sb = ScrollbarState::new(max_scroll + 1)
        .position(app.gpu_scroll)
        .viewport_content_length(shown);
    frame.render_stateful_widget(
        Scrollbar::new(ScrollbarOrientation::VerticalRight)
            .begin_symbol(None)
            .end_symbol(None)
            .style(app.theme.dim),
        area,
        &mut sb,
    );
}

/// One-line summary for a folded GPU card: `▸ 0·name  GPU 3%  MEM 8G/24G ...`
fn draw_gpu_folded(frame: &mut Frame, area: Rect, app: &App, gpu: &GpuSnapshot, idx: usize) {
    let t = &app.theme;
    let selected = idx == app.selected;
    let marker = if selected { t.border_selected } else { t.dim };
    let mut line = vec![
        Span::styled("", marker),
        Span::styled(format!("{idx}·{}  ", gpu.name), t.title),
        Span::styled(format!("GPU {:>3.0}%  ", gpu.utilization_pct), t.spark_util),
        Span::styled(
            format!(
                "MEM {}/{}  ",
                human_bytes(gpu.vram_used_bytes),
                human_bytes(gpu.vram_total_bytes)
            ),
            Style::new().fg(t.accent),
        ),
    ];
    if let Some(c) = gpu.temperature_c {
        line.push(Span::styled(format!("{c:.0}°C  "), t.temp_style(c)));
    }
    if let Some(w) = gpu.power_w {
        line.push(Span::styled(format!("{w:.0}W  "), t.spark_power));
    }
    if let Some(reason) = &gpu.throttle {
        line.push(Span::styled(format!("{reason}  "), t.temp_crit));
    }
    frame.render_widget(Paragraph::new(Line::from(line)), area);
}

/// btop-style border caption: `┐ text ┌` sitting in the border line.
fn caption<'a>(text: String, text_style: Style, border: Style) -> Line<'a> {
    Line::from(vec![
        Span::styled("", border),
        Span::styled(text, text_style),
        Span::styled("", border),
    ])
}

fn draw_gpu(frame: &mut Frame, area: Rect, app: &App, gpu: &GpuSnapshot, idx: usize) {
    let t = &app.theme;
    let selected = idx == app.selected;
    let border = if selected {
        t.border_selected
    } else {
        t.border
    };

    // PCIe caption; a link running below its max (bad riser, wrong slot,
    // power saving stuck) gets a yellow "(max …)" flag.
    let mut right_spans: Vec<Span> = Vec::new();
    if gpu.integrated {
        right_spans.push(Span::styled("integrated", t.dim));
    } else if let (Some(g), Some(w)) = (gpu.pcie_gen, gpu.pcie_width) {
        right_spans.push(Span::styled(format!("PCIe {g}.0@{w}x"), t.dim));
        if let (Some(mg), Some(mw)) = (gpu.pcie_max_gen, gpu.pcie_max_width)
            && (g < mg || w < mw)
        {
            right_spans.push(Span::styled(format!(" (max {mg}.0@{mw}x)"), t.temp_warn));
        }
    }
    let mut block = Block::bordered()
        .border_type(BorderType::Rounded)
        .border_style(border)
        .title(caption(format!("{idx}·{}", gpu.name), t.title, border));
    if !right_spans.is_empty() {
        let mut line = vec![Span::styled("", border)];
        line.extend(right_spans);
        line.push(Span::styled("", border));
        block = block.title_top(Line::from(line).right_aligned());
    }
    let inner = block.inner(area);
    frame.render_widget(block, area);
    if inner.height == 0 {
        return;
    }

    // Session-stats line only when the card has breathing room.
    let show_session = inner.height >= 7 && app.session.get(idx).is_some();
    let [util_row, vram_row, spark_row, session_row, info_row] = Layout::vertical([
        Constraint::Length(1),
        Constraint::Length(1),
        Constraint::Fill(1),
        Constraint::Length(if show_session { 1 } else { 0 }),
        Constraint::Length(1),
    ])
    .areas(inner);

    if show_session && let Some(sess) = app.session.get(idx) {
        let line = Line::from(vec![
            Span::styled(" session ", t.dim),
            Span::styled(
                format!(
                    "peak {:>3.0}%  {:>3.0}°C  {:>3.0}W   ",
                    sess.max_util_pct, sess.max_temp_c, sess.max_power_w
                ),
                Style::new().fg(t.fg),
            ),
            Span::styled(
                format!(
                    "avg {:>3.0}%  {:>3.0}W",
                    sess.avg_util_pct(),
                    sess.avg_power_w()
                ),
                t.dim,
            ),
        ]);
        frame.render_widget(Paragraph::new(line), session_row);
    }

    let hist = app.history.get(idx);
    draw_meter(
        frame,
        util_row,
        "GPU ",
        gpu.utilization_pct / 100.0,
        format!(" {:>3.0}% ", gpu.utilization_pct),
        &t.util_stops(),
        t,
        app.graph_style,
    );
    draw_meter(
        frame,
        vram_row,
        "MEM ",
        gpu.vram_pct() / 100.0,
        format!(
            " {}/{} ",
            human_bytes(gpu.vram_used_bytes),
            human_bytes(gpu.vram_total_bytes)
        ),
        &t.vram_stops(),
        t,
        app.graph_style,
    );

    if spark_row.height >= 2
        && let Some(hist) = hist
    {
        draw_waveform(frame, spark_row, &hist.util, &hist.vram, t, app.graph_style);
    }

    let mut info: Vec<Span> = vec![Span::raw(" ")];
    if let Some(reason) = &gpu.throttle {
        info.push(Span::styled(format!("{reason}  "), t.temp_crit));
    }
    if let Some(c) = gpu.temperature_c {
        if let Some(h) = hist {
            info.push(Span::styled(
                mini_spark(&h.temp, 100, app.graph_style),
                t.dim,
            ));
        }
        info.push(Span::styled(format!(" {c:.0}°C  "), t.temp_style(c)));
    }
    if let Some(w) = gpu.power_w {
        let max_w = gpu.power_limit_w.unwrap_or(0.0).max(w).max(1.0) as u64;
        if let Some(h) = hist {
            info.push(Span::styled(
                mini_spark(&h.power, max_w, app.graph_style),
                t.dim,
            ));
        }
        let limit = gpu
            .power_limit_w
            .map(|l| format!("/{l:.0}"))
            .unwrap_or_default();
        info.push(Span::styled(format!(" {w:.0}{limit}W  "), t.spark_power));
    }
    if let (Some(rx), Some(tx)) = (gpu.pcie_rx_kbs, gpu.pcie_tx_kbs) {
        info.push(Span::styled(format!("{}{}  ", kbs(rx), kbs(tx)), t.dim));
    }
    if let Some(f) = gpu.fan_pct {
        info.push(Span::styled(format!("fan {f:.0}%  "), t.dim));
    }
    if let Some(c) = gpu.clock_mhz {
        info.push(Span::styled(format!("core {c}MHz  "), t.dim));
    }
    if let Some(m) = gpu.mem_clock_mhz {
        info.push(Span::styled(format!("mem {m}MHz  "), t.dim));
    }
    if let Some(mb) = gpu.mem_util_pct {
        info.push(Span::styled(format!("membus {mb:.0}%  "), t.dim));
    }
    if let Some(v) = gpu.video_util_pct {
        info.push(Span::styled(format!("video {v:.0}%  "), t.dim));
    }
    if let Some(e) = gpu.enc_util_pct {
        info.push(Span::styled(format!("enc {e:.0}%  "), t.dim));
    }
    if let Some(d) = gpu.dec_util_pct {
        info.push(Span::styled(format!("dec {d:.0}%  "), t.dim));
    }
    frame.render_widget(Paragraph::new(Line::from(info)), info_row);
}

/// btop-style meter: `LABEL ■■■■■■■■····  42%` with a position gradient over
/// the filled squares.
#[allow(clippy::too_many_arguments)]
fn draw_meter(
    frame: &mut Frame,
    area: Rect,
    label: &str,
    frac: f64,
    value: String,
    stops: &[(u8, u8, u8)],
    t: &UiTheme,
    style: GraphStyle,
) {
    if area.height == 0 {
        return;
    }
    let (fill, empty) = match style {
        GraphStyle::Ascii => ("=", "."),
        _ => ("", "·"),
    };
    let mut spans = vec![Span::styled(label.to_string(), Style::new().fg(t.fg))];
    let meter_w = (area.width as usize)
        .saturating_sub(label.chars().count() + value.chars().count())
        .max(1);
    let filled = (frac.clamp(0.0, 1.0) * meter_w as f64).round() as usize;
    for i in 0..meter_w {
        let pos = if meter_w > 1 {
            i as f64 / (meter_w - 1) as f64
        } else {
            0.0
        };
        if i < filled {
            spans.push(Span::styled(
                fill,
                Style::new().fg(crate::theme::gradient(stops, pos)),
            ));
        } else {
            spans.push(Span::styled(empty, t.dim));
        }
    }
    spans.push(Span::styled(value, Style::new().fg(t.fg)));
    frame.render_widget(Paragraph::new(Line::from(spans)), area);
}

/// Five-cell inline sparkline of recent samples, scaled to `max` — the
/// `⣀⣀⣀⣠⣤` blips btop puts next to temps and power draws. Follows the
/// configured glyph set.
fn mini_spark(data: &[u64], max: u64, style: GraphStyle) -> String {
    const CELLS: usize = 5;
    let max = max.max(1);
    if style != GraphStyle::Braille {
        const ASCII_RAMP: [char; 5] = ['_', '.', '-', '+', '#'];
        return (0..CELLS)
            .map(|c| {
                let v = if data.len() >= CELLS {
                    data[data.len() - CELLS + c]
                } else {
                    let pad = CELLS - data.len();
                    if c < pad { 0 } else { data[c - pad] }
                }
                .min(max);
                if style == GraphStyle::Block {
                    let lvl = ((v as usize * 8).div_ceil(max as usize)).clamp(1, 8);
                    EIGHTHS[lvl]
                } else {
                    let lvl = ((v as usize * 4).div_ceil(max as usize)).clamp(0, 4);
                    ASCII_RAMP[lvl]
                }
            })
            .collect();
    }
    let n = CELLS * 2;
    let mut out = String::with_capacity(CELLS * 3);
    for c in 0..CELLS {
        let mut bits = 0u8;
        for (s, bit_col) in DOT_BITS.iter().enumerate() {
            let i = c * 2 + s;
            let v = if data.len() >= n {
                data[data.len() - n + i]
            } else {
                let pad = n - data.len();
                if i < pad { 0 } else { data[i - pad] }
            };
            let dots = ((v.min(max) as usize * 4).div_ceil(max as usize)).clamp(1, 4);
            for d in 0..dots {
                bits |= bit_col[3 - d];
            }
        }
        out.push(char::from_u32(BRAILLE_BASE + bits as u32).unwrap_or(''));
    }
    out
}

fn human_bytes(b: u64) -> String {
    let g = b as f64 / (1024.0 * 1024.0 * 1024.0);
    if g >= 10.0 {
        format!("{g:.0}G")
    } else if g >= 1.0 {
        format!("{g:.1}G")
    } else {
        format!("{}M", b / 1024 / 1024)
    }
}

/// Lower-block glyphs by filled eighths (index 0..=8).
const EIGHTHS: [char; 9] = [' ', '', '', '', '', '', '', '', ''];
const BRAILLE_BASE: u32 = 0x2800;
/// Braille dot bit for (sub-column, dot-row counted from cell top).
const DOT_BITS: [[u8; 4]; 2] = [[0x01, 0x02, 0x04, 0x40], [0x08, 0x10, 0x20, 0x80]];

/// btop-style mirrored waveform: `up_data` (gpu%) grows upward from the
/// vertical midline, `down_data` (vram%) grows downward, with a color
/// gradient from the midline toward the edges. Zero values keep a minimum
/// sliver, so an idle GPU still draws a thin center line. The glyph set is
/// selectable: braille (2 samples/cell, 4 rows/cell), block eighths, or
/// pure ascii.
fn draw_waveform(
    frame: &mut Frame,
    area: Rect,
    up_data: &[u64],
    down_data: &[u64],
    t: &UiTheme,
    style: GraphStyle,
) {
    if area.height < 2 || area.width == 0 {
        return;
    }
    if style != GraphStyle::Braille {
        return draw_waveform_cells(frame, area, up_data, down_data, t, style);
    }
    let top_rows = (area.height / 2) as usize;
    let bot_rows = area.height as usize - top_rows;
    let cols = area.width as usize;
    let n = cols * 2; // braille doubles horizontal resolution

    let up_stops = t.util_stops();
    let down_stops = t.vram_stops();

    // Newest sample at the right edge; missing history reads as 0.
    let sample = |data: &[u64], i: usize| -> u64 {
        if data.len() >= n {
            data[data.len() - n + i]
        } else {
            let pad = n - data.len();
            if i < pad { 0 } else { data[i - pad] }
        }
    };
    // Value -> dot rows in this half; min 1 keeps the midline alive at 0.
    let dots_for =
        |v: u64, rows: usize| -> usize { ((v.min(100) as usize * rows * 4) / 100).max(1) };

    let buf = frame.buffer_mut();
    for half in 0..2 {
        let (rows, data, stops) = if half == 0 {
            (top_rows, up_data, &up_stops[..])
        } else {
            (bot_rows, down_data, &down_stops[..])
        };
        for cy in 0..rows {
            // cy counts away from the midline in both halves.
            let y = if half == 0 {
                area.y + (top_rows - 1 - cy) as u16
            } else {
                area.y + (top_rows + cy) as u16
            };
            let frac = if rows > 1 {
                cy as f64 / (rows - 1) as f64
            } else {
                0.0
            };
            let color = crate::theme::gradient(stops, frac);
            for cx in 0..cols {
                let mut bits = 0u8;
                for (s, bit_col) in DOT_BITS.iter().enumerate() {
                    let dots = dots_for(sample(data, cx * 2 + s), rows);
                    let in_cell = dots.saturating_sub(cy * 4).min(4);
                    for d in 0..in_cell {
                        // Up half fills cells bottom-up, down half top-down.
                        let row_in_cell = if half == 0 { 3 - d } else { d };
                        bits |= bit_col[row_in_cell];
                    }
                }
                if bits != 0
                    && let Some(cell) = buf.cell_mut((area.x + cx as u16, y))
                {
                    cell.set_char(char::from_u32(BRAILLE_BASE + bits as u32).unwrap_or(''));
                    cell.set_fg(color);
                }
            }
        }
    }

    buf.set_string(area.x, area.y, "gpu%", t.dim);
    buf.set_string(area.x, area.y + area.height - 1, "vram%", t.dim);
}

/// Block/ascii waveform: one sample per column. Block mode uses eighth
/// glyphs (down-growing partials via fg/bg swap since Unicode has no lower
/// upper-partials); ascii uses a `.-+#` coverage ramp.
fn draw_waveform_cells(
    frame: &mut Frame,
    area: Rect,
    up_data: &[u64],
    down_data: &[u64],
    t: &UiTheme,
    style: GraphStyle,
) {
    let top_rows = (area.height / 2) as usize;
    let bot_rows = area.height as usize - top_rows;
    let cols = area.width as usize;
    let up_stops = t.util_stops();
    let down_stops = t.vram_stops();
    // Sub-units per cell: 8 block eighths or 4 ascii coverage steps.
    let unit = if style == GraphStyle::Block { 8 } else { 4 };
    const ASCII_RAMP: [char; 5] = [' ', '.', '-', '+', '#'];

    let sample = |data: &[u64], i: usize| -> u64 {
        if data.len() >= cols {
            data[data.len() - cols + i]
        } else {
            let pad = cols - data.len();
            if i < pad { 0 } else { data[i - pad] }
        }
    };

    let bg = crate::theme::rgb_of(Some(t.bg), (0x1e, 0x1e, 0x2e));
    let buf = frame.buffer_mut();
    for half in 0..2 {
        let (rows, data, stops) = if half == 0 {
            (top_rows, up_data, &up_stops[..])
        } else {
            (bot_rows, down_data, &down_stops[..])
        };
        for cy in 0..rows {
            let y = if half == 0 {
                area.y + (top_rows - 1 - cy) as u16
            } else {
                area.y + (top_rows + cy) as u16
            };
            let frac = if rows > 1 {
                cy as f64 / (rows - 1) as f64
            } else {
                0.0
            };
            let color = crate::theme::gradient(stops, frac);
            for cx in 0..cols {
                let v = sample(data, cx).min(100) as usize;
                let units = ((v * rows * unit) / 100).max(1);
                let in_cell = units.saturating_sub(cy * unit).min(unit);
                if in_cell == 0 {
                    continue;
                }
                let (ch, cell_style) = match style {
                    GraphStyle::Block if half == 0 => (EIGHTHS[in_cell], Style::new().fg(color)),
                    GraphStyle::Block => {
                        if in_cell == 8 {
                            ('', Style::new().fg(color))
                        } else {
                            // Complement trick: paint the empty lower part in
                            // the background color over a bar-colored cell.
                            (
                                EIGHTHS[8 - in_cell],
                                Style::new()
                                    .fg(ratatui::style::Color::Rgb(bg.0, bg.1, bg.2))
                                    .bg(color),
                            )
                        }
                    }
                    _ => (ASCII_RAMP[in_cell], Style::new().fg(color)),
                };
                if let Some(cell) = buf.cell_mut((area.x + cx as u16, y)) {
                    cell.set_char(ch);
                    cell.set_style(cell_style);
                }
            }
        }
    }
    buf.set_string(area.x, area.y, "gpu%", t.dim);
    buf.set_string(area.x, area.y + area.height - 1, "vram%", t.dim);
}

fn draw_processes(frame: &mut Frame, area: Rect, app: &mut App) {
    if area.height < 3 {
        return;
    }
    let total = app.procs.len();
    let visible = (area.height.saturating_sub(3) as usize).min(total);
    let max_scroll = total - visible;
    // Viewport follows the cursor row.
    app.proc_sel = app.proc_sel.min(total.saturating_sub(1));
    if app.proc_sel < app.proc_scroll {
        app.proc_scroll = app.proc_sel;
    } else if visible > 0 && app.proc_sel >= app.proc_scroll + visible {
        app.proc_scroll = app.proc_sel + 1 - visible;
    }
    app.proc_scroll = app.proc_scroll.min(max_scroll);
    let arrow = if app.sort_desc { "" } else { "" };
    let mut counter = format!("{}{arrow}", app.sort_by.label());
    if !app.filter.is_empty() {
        counter = format!("filter:{} · {counter}", app.filter);
    }
    if max_scroll > 0 {
        counter.push_str(&format!(
            " · {}-{}/{total}",
            app.proc_scroll + 1,
            app.proc_scroll + visible
        ));
    } else {
        counter.push_str(&format!(" · {total}"));
    }
    let t = &app.theme;
    let border = if app.focus == crate::app::Focus::Procs {
        t.border_selected
    } else {
        t.border
    };
    let block = Block::bordered()
        .border_type(BorderType::Rounded)
        .title(caption("processes".into(), t.title, border))
        .title_top(caption(counter, t.dim, border).right_aligned())
        .border_style(border);

    if app.procs.is_empty() {
        let inner = block.inner(area);
        frame.render_widget(block, area);
        frame.render_widget(
            Paragraph::new("no GPU processes visible (need same-user or root for fdinfo)")
                .style(t.dim),
            inner,
        );
        return;
    }

    let arrow = if app.sort_desc { "" } else { "" };
    let mark = |label: &str, is: bool| -> String {
        if is {
            format!("{label}{arrow}")
        } else {
            label.to_string()
        }
    };
    use crate::app::SortBy;
    let header = Row::new(
        [
            mark("PID", app.sort_by == SortBy::Pid),
            "USER".into(),
            "DEV".into(),
            "TYPE".into(),
            mark("GPU%", app.sort_by == SortBy::GpuUtil),
            mark("GPU MEM", app.sort_by == SortBy::GpuMem),
            mark("CPU%", app.sort_by == SortBy::Cpu),
            mark("HOST MEM", app.sort_by == SortBy::HostMem),
            "COMMAND".into(),
        ]
        .into_iter()
        .map(Cell::from),
    )
    .style(t.title);

    let proc_sel = app.proc_sel;
    let selection = t.selection;
    let rows = app.procs[app.proc_scroll..app.proc_scroll + visible]
        .iter()
        .enumerate()
        .map(|(vi, p)| {
            let row_style = if app.proc_scroll + vi == proc_sel {
                selection
            } else {
                Style::default()
            };
            Row::new(vec![
                Cell::from(p.pid.to_string()),
                Cell::from(p.user.clone()),
                Cell::from(p.gpu_index.to_string()),
                Cell::from(p.kind.label()),
                Cell::from(
                    p.gpu_util_pct
                        .map(|u| format!("{u:>3.0}%"))
                        .unwrap_or_else(|| "N/A".into()),
                ),
                Cell::from(format!("{}MiB", p.gpu_mem_bytes / 1024 / 1024)),
                Cell::from(format!("{:>3.0}%", p.cpu_pct)),
                Cell::from(format!("{}MiB", p.host_mem_bytes / 1024 / 1024)),
                Cell::from(p.command.clone()),
            ])
            .style(row_style)
        });

    let table = Table::new(
        rows,
        [
            Constraint::Length(8),
            Constraint::Length(10),
            Constraint::Length(3),
            Constraint::Length(8),
            Constraint::Length(5),
            Constraint::Length(9),
            Constraint::Length(5),
            Constraint::Length(9),
            Constraint::Fill(1),
        ],
    )
    .header(header)
    .block(block);
    frame.render_widget(table, area);

    if max_scroll > 0 {
        // Track spans the data rows only (skip borders + header line).
        let track = Rect::new(
            area.x,
            area.y + 2,
            area.width,
            area.height.saturating_sub(3),
        );
        // Same scroll-positions semantics as the GPU list scrollbar.
        let mut sb = ScrollbarState::new(max_scroll + 1)
            .position(app.proc_scroll)
            .viewport_content_length(visible);
        frame.render_stateful_widget(
            Scrollbar::new(ScrollbarOrientation::VerticalRight)
                .begin_symbol(None)
                .end_symbol(None)
                .style(app.theme.dim),
            track,
            &mut sb,
        );
    }
}

/// KiB/s -> human rate, matching nvtop's per-direction PCIe readout.
fn kbs(v: u64) -> String {
    if v >= 1024 * 1024 {
        format!("{:.1}GiB/s", v as f64 / (1024.0 * 1024.0))
    } else if v >= 1024 {
        format!("{:.1}MiB/s", v as f64 / 1024.0)
    } else {
        format!("{v}KiB/s")
    }
}