cargo-lbin 0.10.1

Cargo-powered application manager for crates.io command-line binaries
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
//! Rendering: a pure function of the [`App`] state.

use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{
    Block, Borders, Cell, Clear, Paragraph, Row as TableRow, Table, TableState, Tabs, Wrap,
};

use super::{App, Filter, InputPurpose, MessageKind, RowStatus};
use crate::report::describe_age;

pub fn draw(frame: &mut Frame, app: &App) {
    // The build gauge gets its own framed, transient panel, laid out
    // only while a build runs: on success the rows return to the list,
    // on failure the sticky report panel takes over — and the footer
    // stays free for messages, which the old arrangement hid behind the
    // gauge for the whole build.
    if let Some(gauge) = app.build_progress() {
        let [header, list, details, build, footer] = Layout::new(
            Direction::Vertical,
            [
                Constraint::Length(3),
                Constraint::Min(5),
                Constraint::Length(8),
                Constraint::Length(3),
                Constraint::Length(3),
            ],
        )
        .areas(frame.area());
        draw_tabs(frame, app, header);
        draw_list(frame, app, list);
        draw_details(frame, app, details);
        draw_gauge(frame, &gauge, build);
        draw_footer(frame, app, footer);
        if app.show_help {
            draw_help(frame, frame.area());
        }
        return;
    }
    let [header, list, details, footer] = Layout::new(
        Direction::Vertical,
        [
            Constraint::Length(3),
            Constraint::Min(5),
            Constraint::Length(8),
            Constraint::Length(3),
        ],
    )
    .areas(frame.area());

    draw_tabs(frame, app, header);
    draw_list(frame, app, list);
    draw_details(frame, app, details);
    draw_footer(frame, app, footer);

    if app.show_help {
        let area = frame.area();
        draw_help(frame, area);
    }
}

/// A framed, labeled box — the tty's verdict over the frameless line
/// that shipped first: on a real terminal one yellow row blended into
/// the footer, and a build deserves to be unmissable while it runs.
/// Deliberately a status line inside, never a progress bar: cargo
/// knows what it has started, not what remains, so a count of started
/// units is the truth and any percentage would be an invention.
fn draw_gauge(frame: &mut Frame, gauge: &str, area: Rect) {
    let block = Block::default().borders(Borders::ALL).title(" Build ");
    let inner = block.inner(area);
    frame.render_widget(block, area);
    frame.render_widget(
        Paragraph::new(Span::styled(
            format!(" {gauge}"),
            Style::default().fg(Color::Yellow),
        )),
        inner,
    );
}

fn draw_tabs(frame: &mut Frame, app: &App, area: Rect) {
    let titles = Filter::ALL.iter().map(|f| match f {
        Filter::All => format!(" Packages ({}) ", app.total()),
        Filter::Updates => format!(" Updates ({}) ", app.updates_available()),
        Filter::Pinned => format!(" Pinned ({}) ", app.pinned_count()),
    });
    let tabs = Tabs::new(titles)
        .select(app.filter.index())
        .highlight_style(
            Style::default()
                .fg(Color::Black)
                .bg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        )
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title(format!(" cargo-lbin — {} ", app.prefix().display())),
        );
    frame.render_widget(tabs, area);
}

fn status_cell(status: &RowStatus) -> Cell<'static> {
    let (text, color) = match status {
        RowStatus::UpToDate => ("✓ up to date".to_owned(), Color::Green),
        RowStatus::Outdated(latest) => (format!("{latest}"), Color::Yellow),
        // Gray, not DarkGray: the selected row paints a DarkGray
        // background, and the one status that must never be missed is
        // the one that would vanish into it.
        RowStatus::Unknown => ("? not checked".to_owned(), Color::Gray),
    };
    Cell::from(Span::styled(text, Style::default().fg(color)))
}

fn draw_list(frame: &mut Frame, app: &App, area: Rect) {
    let rows: Vec<TableRow> = app
        .visible()
        .into_iter()
        .map(|row| {
            let mut name = row.name.clone();
            if row.locked {
                name.push_str(" [locked]");
            }
            if row.pinned {
                name.push_str(" [pinned]");
            }
            if !row.also.is_empty() {
                name.push_str(&row.also);
            }
            TableRow::new(vec![
                Cell::from(name),
                Cell::from(row.version.clone()),
                status_cell(&row.status),
            ])
        })
        .collect();

    let empty_note = match app.filter {
        Filter::All => "nothing installed under this prefix — press i to install",
        Filter::Updates => "no unpinned updates known — press r to check crates.io",
        Filter::Pinned => "no pinned crates — p in Packages pins the selected crate",
    };
    let block = Block::default().borders(Borders::ALL);
    if rows.is_empty() {
        let note = Paragraph::new(Span::styled(
            format!(" {empty_note}"),
            Style::default().fg(Color::DarkGray),
        ))
        .block(block);
        frame.render_widget(note, area);
        return;
    }

    let header = TableRow::new(["NAME", "VERSION", "STATUS"])
        .style(Style::default().add_modifier(Modifier::BOLD));
    let table = Table::new(
        rows,
        [
            Constraint::Min(20),
            Constraint::Length(16),
            Constraint::Length(24),
        ],
    )
    .header(header)
    .block(block)
    // Both colors explicit: with only the background set, a light theme's
    // dark default foreground would sink into DarkGray.
    .row_highlight_style(
        Style::default()
            .fg(Color::White)
            .bg(Color::DarkGray)
            .add_modifier(Modifier::BOLD),
    )
    .highlight_symbol("> ");

    let mut state = TableState::default().with_selected(Some(app.selected));
    frame.render_stateful_widget(table, area, &mut state);
}

/// The sticky report panel: a failure's tail and log path, or a
/// success's warnings. Split from `draw_details` for exactly the reason
/// clippy suggests — it is its own panel with its own rules.
fn draw_report(frame: &mut Frame, report: &crate::tui::BuildReport, area: Rect) {
    let color = if report.failed {
        Color::Red
    } else {
        Color::Yellow
    };
    let mut lines: Vec<Line> = vec![Line::from(Span::styled(
        report.title.clone(),
        Style::default().fg(color).add_modifier(Modifier::BOLD),
    ))];
    lines.extend(
        report
            .lines
            .iter()
            .map(|l| Line::from(Span::raw(l.clone()))),
    );
    let block = Block::default()
        .borders(Borders::ALL)
        .title(" Esc/Enter dismisses ");
    // Wrapped: the log path is one of the two most important lines
    // here, and a panel that truncates it defeats its own purpose.
    frame.render_widget(
        Paragraph::new(lines)
            .block(block)
            .wrap(Wrap { trim: false }),
        area,
    );
}

fn draw_details(frame: &mut Frame, app: &App, area: Rect) {
    // A build's report owns the panel until dismissed: a failure's tail
    // and log path, or a success's warnings — either must survive longer
    // than one keypress.
    if let Some(report) = &app.build_report {
        draw_report(frame, report, area);
        return;
    }
    // A finished search takes over the panel until dismissed; it is the
    // one piece of information here that did not come from the manifest.
    if let Some(search) = &app.search_result {
        let name_w = search.hits.iter().map(|h| h.name.len()).max().unwrap_or(0);
        // `api::search` bounds the hit count locally, so the panel's
        // numbering and the footer's "1-n" describe the same list.
        let lines: Vec<Line> = search
            .hits
            .iter()
            .enumerate()
            .map(|(i, hit)| {
                let mut spans = vec![
                    Span::styled(
                        format!("[{}] ", i + 1),
                        Style::default().add_modifier(Modifier::BOLD),
                    ),
                    Span::raw(format!("{:<name_w$}  {}  ", hit.name, hit.version)),
                ];
                if let Some(have) = search.installed.get(&hit.name) {
                    spans.push(Span::styled(
                        format!("[installed {have}]  "),
                        Style::default().fg(Color::Green),
                    ));
                }
                spans.push(Span::styled(
                    hit.description.clone(),
                    Style::default().fg(Color::Gray),
                ));
                Line::from(spans)
            })
            .collect();
        let panel = Paragraph::new(lines).block(Block::default().borders(Borders::ALL).title(
            format!(" Search: {} (digit installs, Esc dismisses) ", search.query),
        ));
        frame.render_widget(panel, area);
        return;
    }

    let mut lines: Vec<Line> = Vec::new();
    if let Some(row) = app.selected_row() {
        // Plain values inherit the terminal's foreground; only the three
        // status states carry a color of their own, so the panel reads
        // the same on light and dark schemes.
        lines.push(kv("Crate", &row.name, Style::default()));
        lines.push(kv("Installed", &row.version, Style::default()));
        match &row.status {
            RowStatus::UpToDate => {
                lines.push(kv(
                    "Latest",
                    &row.version,
                    Style::default().fg(Color::Green),
                ));
            }
            RowStatus::Outdated(latest) => lines.push(kv(
                "Latest",
                &latest.to_string(),
                Style::default().fg(Color::Yellow),
            )),
            RowStatus::Unknown => lines.push(kv(
                "Latest",
                "not checked (press r)",
                Style::default().fg(Color::Gray),
            )),
        }
        lines.push(kv("Binaries", &row.bins.join(", "), Style::default()));
        if row.locked {
            lines.push(kv("Build", "--locked (reused on update)", Style::default()));
        }
        if row.pinned {
            lines.push(kv(
                "Pinned",
                "held at this version; p to unpin",
                Style::default().fg(Color::Yellow),
            ));
        }
    } else {
        lines.push(Line::from(Span::styled(
            "nothing selected",
            Style::default().fg(Color::DarkGray),
        )));
    }
    let panel =
        Paragraph::new(lines).block(Block::default().borders(Borders::ALL).title(" Selected "));
    frame.render_widget(panel, area);
}

fn draw_footer(frame: &mut Frame, app: &App, area: Rect) {
    use std::fmt::Write as _;
    let [keys_area, status_area, line_area] = Layout::new(
        Direction::Vertical,
        [
            Constraint::Length(1),
            Constraint::Length(1),
            Constraint::Length(1),
        ],
    )
    .areas(area);

    let keys = if app.confirm.is_some() {
        " y confirm · any other key cancel"
    } else if app.input.is_some() {
        " Enter run · Esc cancel"
    } else if app.build_running() {
        // Deliberately uncategorical: past the placement door `c`
        // answers TooLate and Ctrl-C only arms quit-after — the hint
        // describes the controls, and the truthful per-press outcome is
        // the runtime message's job (which is typed and never lies).
        " ↑/↓ select · c cancel/escalate · Ctrl-C cancel/quit"
    } else {
        " ↑/↓ select · Tab filter · Enter/u update · U update all · i install · x remove · \
         m migrate · M migrate all · B other prefix · p pin · D downgrade · r check · s search · ? help · q quit"
    };
    frame.render_widget(
        Paragraph::new(Span::styled(keys, Style::default().fg(Color::DarkGray))),
        keys_area,
    );

    let checked = match app.report_age {
        Some(age) => format!("checked {}", describe_age(age)),
        None => "never checked".to_owned(),
    };
    // "0 updates" alone would read as "all current"; the unknown count
    // keeps the footer as honest as the status column.
    let mut status = format!(
        " {} packages · {} updates",
        app.total(),
        app.updates_available()
    );
    // The pinned backlog is deliberately absent from the updates count
    // (it is not something `U` will do), so it must be voiced here: a
    // held-back update stays loud, it just moved homes.
    match (app.pinned_count(), app.pinned_outdated()) {
        (0, _) => {}
        (p, 0) => {
            let _ = write!(status, " · {p} pinned");
        }
        (p, held) => {
            let _ = write!(status, " · {p} pinned ({held} behind)");
        }
    }
    if app.not_checked() > 0 {
        let _ = write!(status, " · {} not checked", app.not_checked());
    }
    let _ = write!(status, " · {checked}");
    frame.render_widget(
        Paragraph::new(Span::styled(status, Style::default().fg(Color::DarkGray))),
        status_area,
    );

    // Bottom line, by priority: a pending confirmation, an open input, a
    // background job, the last message.
    if let Some(confirm) = &app.confirm {
        let line = Span::styled(
            format!(" {}", confirm.prompt),
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        );
        frame.render_widget(Paragraph::new(line), line_area);
    } else if let Some(input) = &app.input {
        let label = match input.purpose {
            InputPurpose::Install => "install: ",
            InputPurpose::Search => "search: ",
        };
        let text = format!(" {label}{}", input.buffer);
        // Cursor after the typed text; widths are clamped to u16 because
        // that is what the terminal addresses, and a line longer than the
        // terminal is already unreadable.
        let cursor_x = line_area
            .x
            .saturating_add(u16::try_from(text.chars().count()).unwrap_or(u16::MAX));
        frame.render_widget(Paragraph::new(text), line_area);
        frame.set_cursor_position((
            cursor_x.min(line_area.right().saturating_sub(1)),
            line_area.y,
        ));
    } else if app.build_progress().is_none()
        && let Some(label) = app.busy()
    {
        // The Build panel owns build status; a footer that also said
        // "building foo…" would say the same thing twice. Skipping the
        // generic label here is also what lets the message branch below
        // fire during a build — "a build is running; c cancels it"
        // must show exactly while the gauge is up, and before this skip
        // the busy label sat in front of it for the whole build.
        let line = Span::styled(format!(" {label}"), Style::default().fg(Color::Cyan));
        frame.render_widget(Paragraph::new(line), line_area);
    } else if let Some(message) = &app.message {
        let color = match message.kind {
            MessageKind::Info => Color::Green,
            MessageKind::Warning => Color::Yellow,
            MessageKind::Error => Color::Red,
        };
        let line = Span::styled(format!(" {}", message.text), Style::default().fg(color));
        frame.render_widget(Paragraph::new(line), line_area);
    }
}

fn draw_help(frame: &mut Frame, area: Rect) {
    let lines = [
        "↑/↓ j/k     select        Tab       Packages / Updates / Pinned",
        "g/G Home/End first / last ?         this help",
        "",
        "Enter, u    update selected crate (confirmed in the terminal)",
        "U           run update --all: fresh plan from crates.io, not the cache",
        "i           install: NAME[@VERSION]... [--locked]  (@VERSION pins);",
        "            a single crate builds in place inside the Build panel,",
        "            a batch hands the terminal over as before",
        "x           remove selected crate (asks first; in place unless",
        "            removal needs sudo — then the terminal, as before)",
        "m           migrate selected crate to the other prefix (asks",
        "            first; exact version rebuilt there, retired here;",
        "            /usr/local <-> ~/.local only, custom via CLI --to)",
        "M           migrate every crate (asks first; a queue of single",
        "            migrations, one summary; c cancels the batch)",
        "c           cancel the running build (again, or automatically",
        "            after ~2s of no effect: SIGKILL); past the placement",
        "            door a cancel is too late: an install finishes placing,",
        "            a migration proceeds through its retirement attempt",
        "B           jump to the other prefix (/usr/local <-> ~/.local);",
        "            the selection follows the crate when it is visible there",
        "p           pin / unpin selected crate (held back by update --all;",
        "            in place unless pinning needs sudo)",
        "D           downgrade: pick an older version in the terminal, pinned",
        "r           check crates.io for updates (writes the report)",
        "s           search crates.io by keyword; a digit then picks a hit",
        "            and opens the install line with its name",
        "",
        "Nothing runs on its own: no refresh or network access on start.",
        "Single-crate installs build inside the TUI: sudo credentials are",
        "checked up front and prompts happen on the real terminal (again",
        "only if the timestamp expires); a failed build",
        "keeps its last lines and the log path in the details panel.",
        "update, downgrade and batch installs hand the terminal to cargo",
        "and sudo as before, and return when you press Enter.",
        "",
        "q / Esc     quit (from the list); during a build, Ctrl-C",
        "            cancels it and quits once the worker stops",
        "",
        "any key closes this help",
    ];
    let width = lines.iter().map(|l| l.chars().count()).max().unwrap_or(0);
    let popup = centered(
        area,
        u16::try_from(width + 4).unwrap_or(u16::MAX),
        u16::try_from(lines.len() + 2).unwrap_or(u16::MAX),
    );
    frame.render_widget(Clear, popup);
    let text: Vec<Line> = lines.iter().map(|l| Line::from(format!(" {l}"))).collect();
    let help = Paragraph::new(text).block(Block::default().borders(Borders::ALL).title(" Keys "));
    frame.render_widget(help, popup);
}

/// A `width`×`height` rectangle in the middle of `area`, shrunk to fit.
fn centered(area: Rect, width: u16, height: u16) -> Rect {
    let width = width.min(area.width);
    let height = height.min(area.height);
    Rect {
        x: area.x + (area.width - width) / 2,
        y: area.y + (area.height - height) / 2,
        width,
        height,
    }
}

fn kv(key: &str, value: &str, value_style: Style) -> Line<'static> {
    Line::from(vec![
        Span::styled(
            format!("{key:<10}"),
            Style::default().add_modifier(Modifier::BOLD),
        ),
        Span::styled(value.to_owned(), value_style),
    ])
}