gpur 0.13.2

btop-style GPU monitor TUI — NVIDIA, AMD, Intel, 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
mod app;
mod backend;
mod cli;
mod config;
mod keys;
mod splash;
mod theme;
mod ui;

use anyhow::{Context, Result};
use app::{App, Focus, InputMode};
use clap::Parser;
use cli::Cli;
use config::GpurConfig;
use crossterm::event::{
    self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind, KeyModifiers,
    MouseButton, MouseEventKind,
};
use keys::Action;
use ratatui::layout::Position;
use std::io::{IsTerminal, stdout};
use std::time::{Duration, Instant};

fn main() -> Result<()> {
    let cli = Cli::parse();

    // Packaging helpers (hidden): emit completions / man page and exit.
    if let Some(shell) = cli.completions {
        use clap::CommandFactory;
        shell.generate(&mut Cli::command());
        return Ok(());
    }
    if cli.man {
        use clap::CommandFactory;
        clap_mangen::Man::new(Cli::command()).render(&mut stdout())?;
        return Ok(());
    }

    let cfg: GpurConfig = match &cli.config {
        Some(path) => hjkl_config::load_from(path)?,
        None => hjkl_config::load()?.0,
    };
    // Headless output must not depend on what a human once did in the TUI:
    // sort/fold state is a UI preference, not part of the data.
    let headless = cli.once || cli.json;
    if headless {
        // One-shot output is a measurement, not a stream: the two polls have
        // to bracket the sleep between them.
        backend::sweep_on_poll_thread();
    }
    // Precedence: CLI flag > last-used (persisted state) > config default.
    // Only an *interactively* chosen rate is "last-used" — otherwise the
    // state file shadows config.toml forever after the first run.
    let state = app::load_state().filter(|_| !headless);
    let saved_tick = state.as_ref().and_then(app::UiState::sticky_tick_ms);
    let tick_ms = app::clamp_tick_ms(cli.tick_ms.or(saved_tick).unwrap_or(cfg.tick_ms));
    let theme_path = cli.theme.clone().or(cfg.theme.clone());

    let theme = theme::load(theme_path.as_deref(), theme::detect_color_mode())?;
    // The session carries this along so a re-detect after repeated poll
    // failures re-runs exactly this detection — see `App::poll_inner`.
    let source = backend::BackendSource::from_cli(cli.mock, cli.replay.clone());
    let backend = source.detect()?;
    let graph_style = match cli.graphs {
        Some(s) => s,
        None => app::GraphStyle::from_config(&cfg.graphs).ok_or_else(|| {
            anyhow::anyhow!(
                "unknown graphs value {:?} in config (expected braille, block, or ascii)",
                cfg.graphs
            )
        })?,
    };
    // A pipe, a cron job or a CI runner has no terminal to put into raw
    // mode; ratatui::init() would unwrap the error into a panic backtrace.
    // The check runs before `open_log` and the first `app.poll()`: a session
    // that is about to bail must not create the `--log` file or write a
    // spurious record for a run that never happened.
    if !headless && !stdout().is_terminal() {
        anyhow::bail!("stdout is not a terminal — use --once or --json for non-interactive output");
    }
    let log = match &cli.log {
        Some(path) => Some(std::io::BufWriter::new(open_log(path)?)),
        None => None,
    };

    let mut app = App::new(
        backend,
        theme,
        app::AppOptions {
            tick_ms,
            // Sticky only if it was already an interactive choice; a config,
            // a --tick-ms value, or a pre-flag state file stays non-sticky.
            tick_explicit: cli.tick_ms.is_none()
                && state.as_ref().is_some_and(app::UiState::tick_chosen_by_key),
            history_len: cfg.history_len,
            no_splash: cli.no_splash,
            graph_style,
            source,
            log,
        },
    );
    if headless {
        return snapshot(&mut app, cli.json, tick_ms);
    }
    if let Some(s) = &state {
        app.restore_state(s);
    }
    app.poll();

    // ratatui::init installs a panic hook restoring raw mode + alt screen;
    // it knows nothing about mouse capture or the kitty protocol, so chain
    // our teardown in front of it — a panic must not leave the shell with
    // mouse reporting on.
    let mut terminal = ratatui::try_init().context("initializing the terminal")?;
    // try_init has already put the tty into raw mode + alt screen; on these
    // two paths the panic hook and signal teardown are not installed yet, so
    // restore explicitly before bailing (restore_extras is idempotent).
    if let Err(e) = hjkl_kitty::enable(&mut stdout()) {
        return Err(fail_setup(e, "enabling kitty keyboard protocol"));
    }
    if let Err(e) = crossterm::execute!(stdout(), EnableMouseCapture) {
        return Err(fail_setup(e, "enabling mouse capture"));
    }
    {
        let prev = std::panic::take_hook();
        std::panic::set_hook(Box::new(move |info| {
            restore_extras();
            prev(info);
        }));
    }
    install_signal_teardown();

    let result = run(&mut terminal, &mut app);
    app.save_state();
    restore_extras();
    ratatui::restore();
    result
}

/// Bail out of a setup step that failed after `ratatui::try_init` put the tty
/// into raw mode and the alternate screen. The panic hook and signal teardown
/// are not installed yet, so restore explicitly before returning — a panic or
/// an external kill at this point must not leave the shell with mouse
/// reporting on (both restores are idempotent).
fn fail_setup(e: impl Into<anyhow::Error>, what: &'static str) -> anyhow::Error {
    restore_extras();
    ratatui::restore();
    e.into().context(what)
}

/// Open the `--log` sink, readable only by its owner where the platform has
/// file modes. Every record carries the full process table — command lines,
/// usernames, container ids (see `App::record`) — and argv routinely holds
/// `--api-key=…`, `--token=…` or a database URL with its password in it.
/// Created under the usual `umask 022` the file lands world-readable, and
/// `--log` is meant to be left running for hours on exactly the kind of
/// shared box where that matters.
///
/// `mode` applies only when the file is created, which is the behaviour we
/// want: appending to a log the user already owns must not silently re-tighten
/// permissions they may have relaxed on purpose. Windows has no equivalent
/// knob here, so it simply opens as before.
///
/// On Windows the sink is documented single-writer: records are serialized
/// with `flock` on unix (see `App::write_log`), and Windows has no equivalent
/// without extra APIs, so two appenders there can interleave a record.
fn open_log(path: &std::path::Path) -> std::io::Result<std::fs::File> {
    let mut opts = std::fs::OpenOptions::new();
    opts.create(true).append(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        opts.mode(0o600);
    }
    opts.open(path)
}

/// Undo what we set up beyond ratatui's own raw-mode/alt-screen handling.
/// Safe to call more than once — both sequences are idempotent pops.
fn restore_extras() {
    let _ = crossterm::execute!(stdout(), DisableMouseCapture);
    let _ = hjkl_kitty::disable(&mut stdout());
}

/// External SIGTERM/SIGHUP/SIGINT would otherwise kill the process with raw
/// mode, the alt screen, and mouse capture still active. (Ctrl-C arrives as
/// a key event under raw mode, so SIGINT here means an outside `kill -INT`.)
#[cfg(unix)]
fn install_signal_teardown() {
    use signal_hook::consts::signal::{SIGHUP, SIGINT, SIGTERM};
    use signal_hook::iterator::Signals;
    let Ok(mut signals) = Signals::new([SIGTERM, SIGHUP, SIGINT]) else {
        return;
    };
    std::thread::spawn(move || {
        if let Some(sig) = signals.forever().next() {
            restore_extras();
            ratatui::restore();
            // Conventional 128+signal exit code.
            std::process::exit(128 + sig);
        }
    });
}

/// Windows: console close / logoff / shutdown deliver CTRL_*_EVENTs on a
/// system thread — the only interception point for a vanishing console.
/// (Ctrl-C itself arrives as a key event under raw mode.)
#[cfg(windows)]
fn install_signal_teardown() {
    use windows::Win32::System::Console::SetConsoleCtrlHandler;

    unsafe extern "system" fn handler(_ctrl_type: u32) -> windows::core::BOOL {
        restore_extras();
        ratatui::restore();
        std::process::exit(130);
    }
    unsafe {
        let _ = SetConsoleCtrlHandler(Some(handler), true);
    }
}

#[cfg(not(any(unix, windows)))]
fn install_signal_teardown() {}

/// A string out of a `--replay` recording is untrusted, and `--once` prints
/// it raw — the TUI strips control characters (ratatui's `set_stringn`
/// filters `char::is_control`), so the headless printer mirrors that
/// guarantee instead of handing a crafted recording a terminal to write
/// escape sequences to.
fn strip_controls(s: &str) -> String {
    s.chars().filter(|c| !c.is_control()).collect()
}

/// Headless one-shot: a second poll after a short gap makes the delta-based
/// utilizations (Intel, per-process) real instead of zero. The priming poll
/// is not logged — `--once --log` must write exactly one record.
fn snapshot(app: &mut App, json: bool, tick_ms: u64) -> Result<()> {
    app.poll_priming();
    std::thread::sleep(Duration::from_millis(tick_ms.clamp(100, 1000)));
    app.poll();

    // Any failed poll invalidates the snapshot. `--once`'s promise is two
    // polls so the deltas are real; when the final poll fails, what would
    // print is the priming poll's data (or nothing) with exit 0 — a script
    // cannot tell a stale snapshot from a fresh one, and `--once --log`
    // would have written zero records beside a full snapshot. The empty
    // record shape stays reserved for a successful poll that found no
    // devices, which leaves `poll_error` None.
    if let Some(e) = &app.poll_error {
        anyhow::bail!("{e}");
    }

    if json {
        println!("{}", serde_json::to_string_pretty(&app.record())?);
        return Ok(());
    }

    // `n/a` rather than a fabricated 0: a metric the backend cannot read must
    // not print as a confident "idle"/"empty" in a scriptable output either.
    let mib = |b: Option<u64>| b.map(ui::mib).unwrap_or_else(|| "n/a".to_string());
    for (i, g) in app.gpus.iter().enumerate() {
        // The pool the card actually spends, marked when those bytes are
        // system RAM — an iGPU printing `vram n/a/n/a` reported nothing at
        // all about the memory it was in fact using.
        let mem = g.mem_primary();
        let mut line = format!(
            "{i}  {}  util {}  mem {}/{}{}",
            strip_controls(&g.name),
            g.utilization_pct
                .map(|u| format!("{u:>3.0}%"))
                .unwrap_or_else(|| "n/a".to_string()),
            mib(mem.used),
            mib(mem.total),
            if mem.shared { " shared" } else { "" },
        );
        if let Some(second) = g.mem_secondary() {
            let label = if second.shared { "shared" } else { "gtt" };
            line.push_str(&format!(
                "  {label} {}/{}",
                mib(second.used),
                mib(second.total)
            ));
        }
        if let Some(t) = g.temperature_c {
            line.push_str(&format!("  {t:.0}°C"));
        }
        if let Some(w) = g.power_w {
            line.push_str(&format!("  {w:.0}W"));
        }
        println!("{line}");
    }
    // Same rows the JSON record carries: unfiltered, deterministic order.
    //
    // The process rows spell an unreadable figure `-`, not the `n/a` the GPU
    // lines above use and not the TUI table's `N/A`. That divergence is not
    // new: the per-process utilization has printed `-` for as long as this
    // output has existed, and these lines are column-split by scripts, so
    // one column of a row disagreeing with its neighbours is worse than the
    // two blocks of this output disagreeing with each other. The memory
    // column follows the utilization column beside it.
    let proc_mib = |b: Option<u64>| b.map(ui::mib).unwrap_or_else(|| "-".to_string());
    for p in &app.all_procs {
        println!(
            "  pid {:>7}  gpu {}  {:>4}  {:>8}  {}",
            p.pid,
            p.gpu_index,
            p.gpu_util_pct
                .map(|u| format!("{u:.0}%"))
                .unwrap_or_else(|| "-".into()),
            proc_mib(p.gpu_mem_bytes),
            strip_controls(&p.command),
        );
    }
    Ok(())
}

/// Splash animation frame budget (~16 fps).
const SPLASH_FRAME_MS: u64 = 60;

/// How long to wait for input before the next frame is due. Frames and
/// polls run on separate clocks: the splash animates at ~16 fps while polls
/// stay at `tick_ms`, and pacing frames off the poll clock spun the loop at
/// full speed for the rest of every tick.
fn event_timeout(
    splash: bool,
    tick_ms: u64,
    since_draw: Duration,
    since_poll: Duration,
) -> Duration {
    let frame_interval = if splash {
        Duration::from_millis(SPLASH_FRAME_MS)
    } else {
        Duration::from_millis(tick_ms)
    };
    let tick = Duration::from_millis(tick_ms);
    frame_interval
        .saturating_sub(since_draw)
        .min(tick.saturating_sub(since_poll))
}

fn run(terminal: &mut ratatui::DefaultTerminal, app: &mut App) -> Result<()> {
    let mut keymap = keys::default_keymap();
    let mut last_poll = Instant::now();

    loop {
        terminal.draw(|frame| ui::draw(frame, app))?;
        let last_draw = Instant::now();

        let timeout = event_timeout(
            app.splash_active(),
            app.tick_ms,
            last_draw.elapsed(),
            last_poll.elapsed(),
        );

        if event::poll(timeout)? {
            match event::read()? {
                Event::Key(key) if key.kind != KeyEventKind::Release => {
                    if app.splash_active() {
                        app.splash_skipped = true;
                        continue;
                    }
                    match app.input_mode {
                        // Filter editing: raw input, bypasses the keymap.
                        // Control chords must never reach the buffer — raw
                        // mode gives no SIGINT, so a literal 'c' from Ctrl-C
                        // left the app with no way out but Esc.
                        InputMode::Filter => {
                            let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);
                            match key.code {
                                KeyCode::Char('c') if ctrl => return Ok(()),
                                KeyCode::Char('u') if ctrl => app.filter_input.clear(),
                                KeyCode::Char('w') if ctrl => app.filter_delete_word(),
                                // Any other control chord is ignored, not typed.
                                KeyCode::Char(_) if ctrl => {}
                                KeyCode::Enter => app.commit_filter(),
                                KeyCode::Esc => app.input_mode = InputMode::Normal,
                                KeyCode::Backspace => {
                                    app.filter_input.pop();
                                }
                                KeyCode::Char(c) => app.filter_input.push(c),
                                _ => {}
                            }
                        }
                        // Kill confirmation: y confirms, anything else cancels.
                        InputMode::Confirm => {
                            if matches!(key.code, KeyCode::Char('y') | KeyCode::Char('Y')) {
                                app.confirm_kill();
                            } else {
                                app.pending_kill = None;
                                app.input_mode = InputMode::Normal;
                            }
                        }
                        InputMode::Normal => {
                            // Any key dismisses the help overlay.
                            if app.show_help {
                                app.show_help = false;
                                continue;
                            }
                            if let Some(action) = keys::resolve(&mut keymap, key)
                                && app.apply(action)
                            {
                                return Ok(());
                            }
                        }
                    }
                }
                Event::Mouse(m) => {
                    if app.splash_active() {
                        app.splash_skipped = true;
                        continue;
                    }
                    // Modals own the screen: a wheel or click must not move
                    // the selection underneath the kill dialog, the filter
                    // input, or the help overlay.
                    if app.show_help || app.input_mode != InputMode::Normal {
                        continue;
                    }
                    let pos = Position::new(m.column, m.row);
                    let in_procs = app.proc_rect.contains(pos);
                    let in_gpus = app.gpus_rect.contains(pos);
                    let action = match m.kind {
                        // Wheel and click both focus the pane under the cursor.
                        MouseEventKind::ScrollDown if in_procs => {
                            app.focus = Focus::Procs;
                            Some(Action::ProcScrollDown)
                        }
                        MouseEventKind::ScrollUp if in_procs => {
                            app.focus = Focus::Procs;
                            Some(Action::ProcScrollUp)
                        }
                        MouseEventKind::ScrollDown if in_gpus => {
                            app.focus = Focus::Gpus;
                            Some(Action::NextGpu)
                        }
                        MouseEventKind::ScrollUp if in_gpus => {
                            app.focus = Focus::Gpus;
                            Some(Action::PrevGpu)
                        }
                        MouseEventKind::Down(MouseButton::Left) if in_procs => {
                            app.focus = Focus::Procs;
                            // Rows start after the top border + header line
                            // and stop before the bottom border — which
                            // proc_rect.contains() counts as inside.
                            let first_row_y = app.proc_rect.y + 2;
                            let border_y = app.proc_rect.bottom().saturating_sub(1);
                            if m.row >= first_row_y && m.row < border_y {
                                let clicked = app.proc_scroll + (m.row - first_row_y) as usize;
                                // Only rows actually on screen: a click must
                                // select what was clicked, never scroll.
                                if clicked < app.proc_scroll + app.proc_visible {
                                    app.proc_sel = clicked;
                                }
                            }
                            None
                        }
                        MouseEventKind::Down(MouseButton::Left) if in_gpus => {
                            app.focus = Focus::Gpus;
                            if let Some(&(_, i)) =
                                app.card_rects.iter().find(|(rect, _)| rect.contains(pos))
                            {
                                app.selected = i;
                            }
                            None
                        }
                        _ => None,
                    };
                    if let Some(action) = action {
                        app.apply(action);
                    }
                }
                _ => {}
            }
        }

        if last_poll.elapsed() >= Duration::from_millis(app.tick_ms) {
            app.poll();
            last_poll = Instant::now();
        }
    }
}

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

    /// The splash busy-loop: with frames paced off the *poll* clock, the
    /// timeout collapsed to zero for the rest of every tick and the loop
    /// spun at ~1000 fps. Frames get their own clock now.
    #[test]
    fn splash_frames_wait_a_frame_not_zero() {
        // 100 ms into a 1000 ms tick, 40 ms into a 60 ms frame.
        let t = event_timeout(
            true,
            1000,
            Duration::from_millis(40),
            Duration::from_millis(100),
        );
        assert_eq!(t, Duration::from_millis(SPLASH_FRAME_MS - 40));
    }

    #[test]
    fn a_due_poll_wins_over_a_later_frame() {
        // 990 ms into the tick: the poll is 10 ms away, the frame 60 ms.
        let t = event_timeout(true, 1000, Duration::ZERO, Duration::from_millis(990));
        assert_eq!(t, Duration::from_millis(10));
    }

    /// Outside the splash both clocks are the tick, so a fresh draw waits a
    /// whole tick and an overdue poll returns immediately.
    #[test]
    fn steady_state_paces_on_the_tick() {
        assert_eq!(
            event_timeout(false, 500, Duration::ZERO, Duration::ZERO),
            Duration::from_millis(500)
        );
        assert_eq!(
            event_timeout(false, 500, Duration::ZERO, Duration::from_millis(700)),
            Duration::ZERO
        );
    }
}