govmr 2.2.0

A high-performance, asynchronous Go Version Manager with a slick terminal UI.
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
//! Module modals - Centered modal overlays: theme picker, install progress, and delete confirmation.

use super::widgets::{centered_rect, clear_area, download_percent, spinner_span};
use crate::{
    app::{AppState, BusyState, Phase, SystemPrompt},
    theme::ThemePickerView,
    theme::{Theme, ThemeFamily, ThemeName},
    version::GoVersion,
};
use ratatui::{
    Frame,
    layout::{Alignment, Constraint, Direction, Layout, Margin, Rect},
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, BorderType, Borders, Gauge, List, ListItem, ListState, Paragraph},
};

// ------------------------------------- Public (crate) API ------------------------------------- //

/// Renders the color-theme picker as a two-level 📁 browser.
///
/// The top level shows the Dark / Light folders; opening one shows only the
/// themes inside it. The live dashboard behind the overlay previews whichever
/// theme is highlighted, so the effect of a choice is visible before saving.
pub(crate) fn render_theme_picker(
    frame: &mut Frame,
    screen: Rect,
    state: &AppState,
    theme: &Theme,
) {
    match state.theme_picker.view {
        ThemePickerView::Categories => render_picker_categories(frame, screen, state, theme),
        ThemePickerView::Family(family) => {
            render_picker_family(frame, screen, state, family, theme);
        }
    }
}

/// Renders the centered progress modal for installs and self-updates.
pub(crate) fn render_progress_modal(
    frame: &mut Frame,
    screen: Rect,
    busy: &BusyState,
    tick: u64,
    theme: &Theme,
) {
    let (version, phase, downloaded, total, speed, is_update) = match busy {
        BusyState::Installing {
            version,
            phase,
            downloaded,
            total,
            speed,
            ..
        } => (version.clone(), *phase, *downloaded, *total, *speed, false),
        BusyState::Updating {
            version,
            phase,
            downloaded,
            total,
            speed,
            ..
        } => (version.clone(), *phase, *downloaded, *total, *speed, true),
        _ => return,
    };

    let area = centered_rect(62, 38, screen);
    clear_area(frame, area, theme);

    let title_text = if is_update {
        format!(" Updating govmr to {version} ")
    } else {
        format!(" Installing Go {version} ")
    };

    let block = Block::default()
        .title(Span::styled(title_text, theme.title()))
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(theme.border())
        .style(Style::default().bg(theme.bg));
    frame.render_widget(block, area);

    let inner = area.inner(Margin {
        horizontal: 2,
        vertical: 1,
    });
    let rows = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // phase line
            Constraint::Length(3), // gauge
            Constraint::Length(1), // stats
            Constraint::Min(1),
        ])
        .split(inner);

    match phase {
        Phase::Downloading => {
            render_downloading_phase(frame, &rows, tick, downloaded, total, speed, theme);
        }
        Phase::Extracting => {
            render_extracting_phase(frame, &rows, tick, theme);
        }
    }
}

/// Renders the destructive-action confirmation modal.
pub(crate) fn render_delete_modal(
    frame: &mut Frame,
    screen: Rect,
    state: &AppState,
    theme: &Theme,
) {
    let Some(target) = &state.confirming_delete else {
        return;
    };
    let area = centered_rect(58, 30, screen);
    clear_area(frame, area, theme);
    let block = Block::default()
        .title(Span::styled(" ⚠ Confirm Deletion ", theme.warning()))
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(theme.error())
        .style(Style::default().bg(theme.bg));
    frame.render_widget(block, area);

    let inner = area.inner(Margin {
        horizontal: 2,
        vertical: 1,
    });
    let text = vec![
        Line::from(""),
        Line::from(vec![
            Span::styled("  Remove ", theme.modal_body()),
            Span::styled(
                format!("Go {target}"),
                theme.error().add_modifier(Modifier::BOLD),
            ),
            Span::styled(" from your machine?", theme.modal_body()),
        ]),
        Line::from(""),
        Line::from(Span::styled(
            "  This permanently deletes the toolchain directory.",
            theme.muted(),
        )),
        Line::from(""),
        Line::from(vec![
            Span::styled("   [y] ", theme.error().add_modifier(Modifier::BOLD)),
            Span::styled("Yes, delete it     ", theme.muted()),
            Span::styled("[n/esc] ", theme.key_hint()),
            Span::styled("Cancel", theme.muted()),
        ]),
    ];
    frame.render_widget(Paragraph::new(text).alignment(Alignment::Left), inner);
}

pub(crate) fn render_system_prompt(
    frame: &mut Frame,
    screen: Rect,
    prompt: SystemPrompt,
    theme: &Theme,
) {
    // Dynamic height: Target ~10 rows minimum, clamped between 17% and 25% of screen.
    // This ensures it's never too small (thin bar) or too huge.
    let min_rows = 7;
    let height_percent = (min_rows * 100) / screen.height;
    let height_percent = height_percent.clamp(17, 26);

    let area = centered_rect(50, height_percent, screen);
    clear_area(frame, area, theme);

    let (title, msg, color, buttons) = match prompt {
        SystemPrompt::Update => (
            " 🔄 Update ",
            "Download and install the latest govmr version?",
            theme.highlight(),
            vec![
                Span::styled(" [y] ", theme.success().add_modifier(Modifier::BOLD)),
                Span::styled("Yes   ", theme.muted()),
                Span::styled(" [n/c/esc] ", theme.error().add_modifier(Modifier::BOLD)),
                Span::styled("Cancel", theme.muted()),
            ],
        ),
        SystemPrompt::UninstallKeep => (
            " 🗑️ Uninstall ",
            "Remove govmr binary?",
            theme.warning(),
            vec![
                Span::styled(" [y] ", theme.success().add_modifier(Modifier::BOLD)),
                Span::styled("Uninstall   ", theme.muted()),
                Span::styled(" [n/c/esc] ", theme.error().add_modifier(Modifier::BOLD)),
                Span::styled("Cancel", theme.muted()),
            ],
        ),
        SystemPrompt::UninstallPurge => (
            " 🚨 Purge ",
            "Also DELETE ~/.govmr and ALL installed Go versions?",
            theme.error(),
            vec![
                Span::styled(" [y] ", theme.success().add_modifier(Modifier::BOLD)),
                Span::styled("Yes, Delete Everything   ", theme.muted()),
                Span::styled(" [n/c/esc] ", theme.error().add_modifier(Modifier::BOLD)),
                Span::styled("Cancel", theme.muted()),
            ],
        ),
    };

    let block = Block::default()
        .title(Span::styled(title, color))
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(color)
        .style(Style::default().bg(theme.bg));
    frame.render_widget(block, area);

    let inner = area.inner(Margin {
        horizontal: 2,
        vertical: 1,
    });

    // Center the content vertically/horizontally
    let text = vec![
        Line::from(""),
        Line::from(Span::styled(msg, theme.modal_body())),
        Line::from(""),
        Line::from(buttons),
    ];

    frame.render_widget(Paragraph::new(text).alignment(Alignment::Center), inner);
}

// -------------------------------------- Internal Helpers -------------------------------------- //

/// Renders the folder level: one row per [`ThemeFamily`] with its theme count.
fn render_picker_categories(frame: &mut Frame, screen: Rect, state: &AppState, theme: &Theme) {
    let area = centered_rect(56, 36, screen);
    clear_area(frame, area, theme);
    let block = Block::default()
        .title(Span::styled(" 🎨 Color Theme ", theme.title()))
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(theme.border())
        .style(Style::default().bg(theme.bg));
    frame.render_widget(block, area);

    let inner = area.inner(Margin {
        horizontal: 2,
        vertical: 1,
    });
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Min(1), Constraint::Length(2)])
        .split(inner);

    let items: Vec<ListItem> = ThemeFamily::ALL
        .iter()
        .enumerate()
        .map(|(i, family)| {
            let selected = i == state.theme_picker.family_cursor;
            let count = ThemeName::in_family(*family).len();
            let marker = if selected { "❯" } else { " " };
            let marker_style = if selected {
                theme.brand_bold()
            } else {
                theme.muted()
            };
            let name_style = if selected {
                Style::default()
                    .fg(theme.brand)
                    .bg(theme.brand_dark)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(theme.fg)
            };
            ListItem::new(Line::from(vec![
                Span::styled(format!(" {marker} "), marker_style),
                Span::styled(format!(" {} ", family.icon()), theme.muted()),
                Span::styled(format!("{:<6}", family.label()), name_style),
                Span::styled(format!("  {count} themes  →"), theme.muted()),
            ]))
        })
        .collect();

    let list = List::new(items)
        .highlight_style(theme.selected_row())
        .highlight_symbol("");
    let mut list_state = ListState::default();
    list_state.select(Some(state.theme_picker.family_cursor));
    frame.render_stateful_widget(list, chunks[0], &mut list_state);

    frame.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled(" ↑↓", theme.key_hint()),
            Span::styled(" pick  ", theme.muted()),
            Span::styled("enter", theme.key_hint()),
            Span::styled(" open  ", theme.muted()),
            Span::styled("esc", theme.key_hint()),
            Span::styled(" cancel ", theme.muted()),
        ]))
        .alignment(Alignment::Center),
        chunks[1],
    );
}

/// Renders the theme level: the themes of one family with live accent swatches.
fn render_picker_family(
    frame: &mut Frame,
    screen: Rect,
    state: &AppState,
    family: ThemeFamily,
    theme: &Theme,
) {
    let area = centered_rect(66, 78, screen);
    clear_area(frame, area, theme);
    let block = Block::default()
        .title(Line::from(vec![
            Span::styled(" 🎨 Color Theme ", theme.title()),
            Span::styled(format!("· {} ", family.label()), theme.muted()),
        ]))
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .border_style(theme.border())
        .style(Style::default().bg(theme.bg));
    frame.render_widget(block, area);

    let inner = area.inner(Margin {
        horizontal: 2,
        vertical: 1,
    });
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Min(1), Constraint::Length(2)])
        .split(inner);

    let items: Vec<ListItem> = ThemeName::in_family(family)
        .iter()
        .enumerate()
        .map(|(i, name)| {
            let selected = i == state.theme_picker.theme_cursor;
            let swatch = Theme::for_name(*name);
            let marker = if selected { "❯" } else { " " };
            let marker_style = if selected {
                theme.brand_bold()
            } else {
                theme.muted()
            };
            let name_style = if selected {
                Style::default()
                    .fg(swatch.brand)
                    .bg(theme.brand_dark)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(theme.fg)
            };
            ListItem::new(Line::from(vec![
                Span::styled(format!(" {marker} "), marker_style),
                Span::styled("███ ", Style::default().fg(swatch.brand)),
                Span::styled(format!("{:<20}", name.title()), name_style),
                Span::styled(format!("  {}", theme_tagline(*name)), theme.muted()),
            ]))
        })
        .collect();

    let list = List::new(items)
        .highlight_style(theme.selected_row())
        .highlight_symbol("");
    let mut list_state = ListState::default();
    list_state.select(Some(state.theme_picker.theme_cursor));
    frame.render_stateful_widget(list, chunks[0], &mut list_state);

    frame.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled(" ↑↓", theme.key_hint()),
            Span::styled(" preview  ", theme.muted()),
            Span::styled("enter", theme.key_hint()),
            Span::styled(" save  ", theme.muted()),
            Span::styled("←/esc", theme.key_hint()),
            Span::styled(" back ", theme.muted()),
        ]))
        .alignment(Alignment::Center),
        chunks[1],
    );
}

/// Renders the downloading phase: phase line, progress gauge, and stats row.
fn render_downloading_phase(
    frame: &mut Frame,
    rows: &[Rect],
    tick: u64,
    downloaded: u64,
    total: u64,
    speed: f64,
    theme: &Theme,
) {
    let pct = download_percent(downloaded, total);
    frame.render_widget(
        Paragraph::new(Line::from(vec![
            spinner_span(tick, theme),
            Span::styled(" Downloading archive…", theme.highlight()),
        ])),
        rows[0],
    );
    // pct is clamped to 0..=100, so the cast always fits the gauge's u16.
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let percent = pct as u16;
    let gauge = Gauge::default()
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(theme.muted()),
        )
        .gauge_style(
            Style::default()
                .fg(theme.brand)
                .bg(theme.brand_dark)
                .add_modifier(Modifier::BOLD),
        )
        .percent(percent)
        .label(Span::styled(
            format!(" {pct:.1}% "),
            Style::default().fg(theme.fg).add_modifier(Modifier::BOLD),
        ));
    frame.render_widget(gauge, rows[1]);

    let eta = if speed > 1.0 && total > downloaded {
        // Remaining bytes fit f64 exactly for any realistic archive size.
        #[allow(clippy::cast_precision_loss)]
        let remaining_secs = (total - downloaded) as f64 / speed;
        format!("{remaining_secs:.0}s")
    } else {
        "—".to_string()
    };
    // Download speed is always non-negative; truncation drops at most a byte.
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let speed_bps = speed as u64;
    frame.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled(
                format!(
                    "  {} / {}   ",
                    GoVersion::format_size(downloaded),
                    GoVersion::format_size(total)
                ),
                theme.muted(),
            ),
            Span::styled(
                format!("{}/s   ", GoVersion::format_size(speed_bps)),
                theme.highlight(),
            ),
            Span::styled(format!("eta {eta}"), theme.muted()),
        ]))
        .alignment(Alignment::Center),
        rows[2],
    );
}

/// Renders the extracting phase: phase line and the pulsing unpacking gauge.
fn render_extracting_phase(frame: &mut Frame, rows: &[Rect], tick: u64, theme: &Theme) {
    frame.render_widget(
        Paragraph::new(Line::from(vec![
            spinner_span(tick, theme),
            Span::styled(" Download complete — extracting archive…", theme.success()),
        ])),
        rows[0],
    );
    // THE PULSE: Smoothly oscillates between 20% and 80%.
    // Tick counts stay far below 2^53, so the f64 cast cannot lose precision.
    #[allow(clippy::cast_precision_loss)]
    let wave = (tick as f64 * 0.15).sin(); // Generates a smooth wave from -1.0 to 1.0
    // Maps the wave to a 20% - 80% range that always fits the gauge's u16.
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let pct = (wave * 30.0 + 50.0) as u16;
    let gauge = Gauge::default()
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_type(BorderType::Rounded)
                .border_style(theme.muted()),
        )
        .gauge_style(Style::default().fg(theme.success).bg(theme.brand_dark))
        .percent(pct)
        .label(Span::styled(
            " unpacking ",
            Style::default().fg(theme.fg).add_modifier(Modifier::BOLD),
        ));
    frame.render_widget(gauge, rows[1]);
    frame.render_widget(
        Paragraph::new(Span::styled(
            "  This can take a few seconds for large toolchains.",
            theme.muted(),
        ))
        .alignment(Alignment::Center),
        rows[2],
    );
}

/// Short descriptive tagline for each theme.
fn theme_tagline(name: ThemeName) -> &'static str {
    match name {
        ThemeName::GoCyan => "brand cyan default",
        ThemeName::JetBrainsNewIsland => "island slate + orange",
        ThemeName::CursorDark => "cursor neutral dark",
        ThemeName::Midnight => "deep indigo, low glare",
        ThemeName::TokyoNight => "neon tokyo skyline",
        ThemeName::CatppuccinMocha => "cozy pastel espresso",
        ThemeName::Nord => "snowstorm blue",
        ThemeName::Dracula => "dark purple",
        ThemeName::GruvboxDark => "warm retro earth",
        ThemeName::RosePine => "muted dusky rose",
        ThemeName::Matrix => "retro phosphor green",
        ThemeName::Amber => "warm solarized glow",
        ThemeName::Mono => "minimal greyscale",
        ThemeName::CursorLight => "clean cursor indigo",
        ThemeName::CatppuccinLatte => "soft pastel milk",
        ThemeName::GitHubLight => "github paper white",
        ThemeName::SolarizedLight => "solarized parchment",
        ThemeName::RosePineDawn => "gentle morning rose",
        ThemeName::Light => "bright high contrast",
    }
}