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
//! Module app - Central state container and action dispatcher for interactive TUI execution.
mod action;
mod actions;
mod keys;
mod state;
pub(crate) use action::Action;
pub(crate) use actions::handle_actions;
pub(crate) use keys::{KeyOutcome, handle_key};
pub(crate) use state::{
ActiveTab, AppState, BusyState, MsgKind, Phase, StatusMessage, SystemPrompt, ThemePickerState,
VisualAddition, visible_indices,
};
use crate::{
logging,
manager::{GoManager, InstallProgress},
theme::{Theme, ThemeFamily, ThemeName, ThemePickerView},
version::GoVersion,
};
use ratatui::widgets::ListState;
use std::{
sync::Arc,
time::{Duration, Instant},
};
// ------------------------------------------ Types & Impls ------------------------------------- //
/// One row of the right-docked command reference panel.
///
/// A row is either a [`HelpEntry::Section`] heading or a concrete
/// [`HelpEntry::Binding`] pairing a set of keys with the action they perform.
#[derive(Clone, Copy)]
pub(crate) enum HelpEntry {
/// Section heading text shown as a divider label.
Section(&'static str),
/// A key binding and the action it triggers.
Binding {
keys: &'static str,
action: &'static str,
},
}
/// The full command catalogue rendered by the right-docked keyboard help panel.
///
/// Ordering matters: entries are shown top-to-bottom exactly as listed here,
/// and the panel's scroll offset is expressed in rows of this slice.
pub(crate) const COMMAND_REFERENCE: &[HelpEntry] = &[
HelpEntry::Section("Global"),
HelpEntry::Binding {
keys: "q / ^C",
action: "Quit from any screen",
},
HelpEntry::Binding {
keys: "Esc",
action: "Cancel / close view",
},
HelpEntry::Section("Navigation"),
HelpEntry::Binding {
keys: "k / ↑",
action: "Move up",
},
HelpEntry::Binding {
keys: "j / ↓",
action: "Move down",
},
HelpEntry::Binding {
keys: "Tab",
action: "Switch tabs",
},
HelpEntry::Binding {
keys: "/",
action: "Filter versions",
},
HelpEntry::Section("Version actions"),
HelpEntry::Binding {
keys: "i",
action: "Install selected",
},
HelpEntry::Binding {
keys: "u",
action: "Use (activate) selected",
},
HelpEntry::Binding {
keys: "d",
action: "Delete selected",
},
HelpEntry::Binding {
keys: "r",
action: "Refresh releases",
},
HelpEntry::Section("View & workspace"),
HelpEntry::Binding {
keys: "L",
action: "Toggle operation log",
},
HelpEntry::Binding {
keys: "T",
action: "Open theme picker",
},
HelpEntry::Binding {
keys: "?",
action: "Toggle this help panel",
},
HelpEntry::Binding {
keys: "h",
action: "PATH setup (shim missing only)",
},
HelpEntry::Section("Operation log (focus with `)"),
HelpEntry::Binding {
keys: "`",
action: "Focus / unfocus log",
},
HelpEntry::Binding {
keys: "k / ↑",
action: "Scroll up",
},
HelpEntry::Binding {
keys: "j / ↓",
action: "Scroll down",
},
HelpEntry::Binding {
keys: "g / G",
action: "Newest / oldest",
},
HelpEntry::Binding {
keys: "f",
action: "Toggle auto-follow",
},
HelpEntry::Binding {
keys: "w",
action: "Toggle word wrap",
},
HelpEntry::Binding {
keys: "Ctrl+l",
action: "Clear display (visual only)",
},
HelpEntry::Binding {
keys: "-",
action: "Insert separator line",
},
HelpEntry::Binding {
keys: "Enter",
action: "Insert blank line",
},
HelpEntry::Section("Maintenance"),
HelpEntry::Binding {
keys: "U",
action: "Self-update govmr",
},
HelpEntry::Binding {
keys: "X",
action: "Self-uninstall govmr",
},
HelpEntry::Section("Confirmation dialogs"),
HelpEntry::Binding {
keys: "y",
action: "Confirm action",
},
HelpEntry::Binding {
keys: "n / Esc",
action: "Decline / cancel",
},
];
/// Main application controller holding application state and business logic references.
pub(crate) struct App {
/// Mutable UI state.
pub(crate) state: AppState,
/// Core Go manager handling version operations.
manager: Arc<GoManager>,
}
impl App {
// ------------------------------------- Public (crate) API ------------------------------------- //
/// Instantiates a new application controller, performing initial version manifest loading.
///
/// The initial version fetch is dispatched via the `Action::Refresh`
/// message in the main event loop, allowing the UI to render immediately
/// and show a loading state while the network request proceeds.
pub(crate) fn new(manager: Arc<GoManager>, shim_path: String) -> Self {
let is_in_path = manager.get_shim_manager().is_in_path();
let current_theme = manager.theme_name();
Self {
state: AppState {
versions: Vec::new(),
list_state: ListState::default(),
active_tab: ActiveTab::Available,
busy: None,
status_message: None,
confirming_delete: None,
is_shim_in_path: is_in_path,
shim_path,
filter: String::new(),
filter_mode: false,
show_help: false,
show_command_help: false,
command_help_scroll: 0,
show_theme_picker: false,
theme_picker: ThemePickerState::default(),
theme: Theme::for_name(current_theme),
tick_count: 0,
path_fix_notice: None,
show_logs: false,
log_lines: Vec::new(),
log_scroll: 0,
log_follow: true,
log_refreshed: None,
log_focus: false,
log_wrap: false,
log_visual_skip: 0,
log_visual_additions: Vec::new(),
cancel_install: None,
system_prompt: None,
},
manager,
}
}
/// Asynchronously refreshes the version list from the `GoManager`.
#[deprecated(
since = "1.0.0",
note = "This method is obsolete - version fetching is now handled by background tasks via handle_actions"
)]
#[allow(dead_code)]
pub(crate) async fn refresh_versions(&mut self) {
self.state.busy = Some(BusyState::Refreshing);
match self.manager.fetch_versions().await {
Ok(versions) => {
self.state.versions = versions;
self.state.status_message = None;
self.clamp_selection();
}
Err(e) => {
self.set_status(e.to_string(), MsgKind::Error);
}
}
self.state.busy = None;
}
/// Records a transient status message.
pub(crate) fn set_status(&mut self, text: impl Into<String>, kind: MsgKind) {
self.state.status_message = Some(StatusMessage {
text: text.into(),
kind,
});
}
/// Whether a background task is currently blocking new actions.
#[must_use]
pub(crate) fn is_busy(&self) -> bool {
self.state.busy.is_some()
}
/// Returns indices into [`AppState::versions`] visible under the current tab and filter.
#[must_use]
pub(crate) fn visible_indices(&self) -> Vec<usize> {
visible_indices(&self.state)
}
/// Returns the currently selected [`GoVersion`], honoring tab and filter visibility.
#[must_use]
pub(crate) fn selected_version(&self) -> Option<&GoVersion> {
let visible = self.visible_indices();
let pos = self.state.list_state.selected()?;
visible.get(pos).map(|&i| &self.state.versions[i])
}
/// Switches to the other tab and resets navigation.
pub(crate) fn switch_tab(&mut self) {
self.state.active_tab = self.state.active_tab.toggle();
self.state.list_state.select(Some(0));
}
/// Opens the docked log panel *without* stealing keyboard focus, so the
/// dashboard stays fully usable while logs tail live.
pub(crate) fn open_logs(&mut self) {
self.state.show_logs = true;
self.state.log_focus = false;
self.state.log_follow = true;
self.state.log_scroll = 0;
// Reopening restores the pristine file view: drop watermark + additions.
self.state.log_visual_skip = 0;
self.state.log_visual_additions.clear();
self.refresh_logs();
}
/// Closes the docked log panel and drops focus back to the dashboard.
pub(crate) fn close_logs(&mut self) {
self.state.show_logs = false;
self.state.log_focus = false;
self.state.log_visual_skip = 0;
self.state.log_visual_additions.clear();
}
/// Clears the visible log display without touching the file on disk.
///
/// Terminal semantics: everything currently on screen disappears, but lines
/// written *afterwards* still tail in. The watermark is the physical line
/// count at clear time, so "new" is defined by the file, not by the UI.
pub(crate) fn clear_log_display(&mut self) {
self.state.log_visual_skip = logging::read_lines().len();
self.state.log_visual_additions.clear();
self.refresh_logs();
}
/// Opens the right-docked keyboard help panel, resetting its scroll to the top.
pub(crate) fn open_command_help(&mut self) {
self.state.show_command_help = true;
self.state.command_help_scroll = 0;
}
/// Closes the right-docked keyboard help panel.
pub(crate) fn close_command_help(&mut self) {
self.state.show_command_help = false;
}
/// Opens the help panel if it is closed, or closes it if it is open.
pub(crate) fn toggle_command_help(&mut self) {
if self.state.show_command_help {
self.state.show_command_help = false;
} else {
self.open_command_help();
}
}
/// Scrolls the keyboard help panel by `delta` content lines: positive moves
/// downward through the command list, negative back toward the top.
///
/// The offset is clamped to the panel's row budget so `g`/`G` can jump to
/// either extreme without walking off the end of the catalogue.
pub(crate) fn scroll_command_help(&mut self, delta: i64) {
let max = COMMAND_REFERENCE.len().saturating_sub(1);
// The i64 round-trip safely applies a signed delta; the clamp keeps the
// result non-negative, so the final cast can never go wrong.
#[allow(
clippy::cast_possible_truncation,
clippy::cast_possible_wrap,
clippy::cast_sign_loss
)]
let next = (self.state.command_help_scroll as i64 + delta).clamp(0, max as i64) as usize;
self.state.command_help_scroll = next;
}
/// Toggles word wrapping of long log lines (URLs, stack traces, …).
pub(crate) fn toggle_log_wrap(&mut self) {
self.state.log_wrap = !self.state.log_wrap;
}
/// Re-reads the log file into the viewer cache. When following, stays
/// pinned to the newest entry; otherwise preserves the scroll position.
///
/// Blends the physical file (minus any cleared-away prefix) with transient
/// visual additions (separators, blank lines), inserting each addition exactly
/// at the file-line anchor it was created at.
pub(crate) fn refresh_logs(&mut self) {
let file_lines = logging::read_lines();
// Log rotation replaces the file with a much shorter one; a stale
// watermark would then hide *everything*, so drop it defensively.
if self.state.log_visual_skip > file_lines.len() {
self.state.log_visual_skip = 0;
self.state.log_visual_additions.clear();
}
let mut lines: Vec<String> = Vec::new();
let mut additions_iter = self.state.log_visual_additions.iter().peekable();
for (i, line) in file_lines.into_iter().enumerate() {
if i >= self.state.log_visual_skip {
// Insert any visual additions anchored at or before this file line
while let Some(addition) = additions_iter.peek() {
if addition.anchor <= i {
lines.push(addition.text.clone());
additions_iter.next();
} else {
break;
}
}
lines.push(line);
}
}
// Append any remaining additions anchored at or after the end of the file
for addition in additions_iter {
lines.push(addition.text.clone());
}
self.state.log_lines = lines;
self.state.log_refreshed = Some(Instant::now());
let max = self.state.log_lines.len().saturating_sub(1);
if self.state.log_follow {
self.state.log_scroll = 0;
} else if self.state.log_scroll > max {
self.state.log_scroll = max;
}
}
/// Re-reads the log cache if the viewer is open and the throttle window
/// has elapsed. Cheap no-op otherwise, so it is safe to call every tick.
pub(crate) fn refresh_logs_if_open(&mut self) {
if !self.state.show_logs {
return;
}
let stale = self
.state
.log_refreshed
.is_none_or(|t| t.elapsed() >= Duration::from_millis(500));
if stale {
self.refresh_logs();
}
}
/// Scrolls the log viewer by `delta` lines: positive moves up into older
/// history, negative moves down toward newer entries.
pub(crate) fn scroll_logs(&mut self, delta: i64) {
let max = self.state.log_lines.len().saturating_sub(1);
// The i64 round-trip safely applies a signed delta; the clamp keeps
// the result non-negative, so the final cast can never go wrong.
#[allow(
clippy::cast_possible_truncation,
clippy::cast_possible_wrap,
clippy::cast_sign_loss
)]
let next = (self.state.log_scroll as i64 + delta).clamp(0, max as i64) as usize;
self.state.log_scroll = next;
// Following only makes sense while pinned to the newest entry.
self.state.log_follow = next == 0;
}
/// Toggles auto-follow; re-enabling snaps back to the newest entry.
pub(crate) fn toggle_log_follow(&mut self) {
self.state.log_follow = !self.state.log_follow;
if self.state.log_follow {
self.state.log_scroll = 0;
}
}
/// Opens the picker at the folder level, highlighting the folder that holds
/// the persisted theme and previewing that theme live.
pub(crate) fn open_theme_picker(&mut self) {
self.state.show_theme_picker = true;
let current = self.manager.theme_name();
self.state.theme_picker = ThemePickerState {
view: ThemePickerView::Categories,
family_cursor: current.family().index(),
theme_cursor: current.index_in_family(),
};
self.state.theme = self.manager.theme();
}
/// The theme currently highlighted by the picker. Only meaningful while a
/// family is open; at the folder level it reports the persisted theme.
#[must_use]
pub(crate) fn picker_theme(&self) -> ThemeName {
match self.state.theme_picker.view {
ThemePickerView::Family(family) => ThemeName::in_family(family)
.get(self.state.theme_picker.theme_cursor)
.copied()
.unwrap_or_default(),
ThemePickerView::Categories => self.manager.theme_name(),
}
}
/// Moves the cursor within the current level, live-previewing the highlighted
/// theme while a family is open.
/// Cursors index a tiny fixed set, so the i32 round-trip can neither
/// overflow nor truncate in practice.
#[allow(
clippy::cast_possible_truncation,
clippy::cast_possible_wrap,
clippy::cast_sign_loss
)]
pub(crate) fn picker_move(&mut self, delta: i32) {
match self.state.theme_picker.view {
ThemePickerView::Categories => {
let len = ThemeFamily::ALL.len() as i32;
let mut i = self.state.theme_picker.family_cursor as i32 + delta;
if i < 0 {
i = len - 1;
}
if i >= len {
i = 0;
}
self.state.theme_picker.family_cursor = i as usize;
// Folder level previews the persisted theme, not a candidate.
self.state.theme = self.manager.theme();
}
ThemePickerView::Family(family) => {
let len = ThemeName::in_family(family).len() as i32;
if len == 0 {
return;
}
let mut i = self.state.theme_picker.theme_cursor as i32 + delta;
if i < 0 {
i = len - 1;
}
if i >= len {
i = 0;
}
self.state.theme_picker.theme_cursor = i as usize;
self.state.theme = Theme::for_name(self.picker_theme());
}
}
}
/// Dives into the highlighted folder, or saves the highlighted theme when a
/// folder is already open (Enter does double duty, like a file manager).
pub(crate) fn picker_enter(&mut self) {
match self.state.theme_picker.view {
ThemePickerView::Categories => {
let family = ThemeFamily::at(self.state.theme_picker.family_cursor);
let themes = ThemeName::in_family(family);
let current = self.manager.theme_name();
// Land on the persisted theme when it lives here, else clamp.
self.state.theme_picker.theme_cursor = if current.family() == family {
current.index_in_family()
} else {
self.state
.theme_picker
.theme_cursor
.min(themes.len().saturating_sub(1))
};
self.state.theme_picker.view = ThemePickerView::Family(family);
self.state.theme = Theme::for_name(self.picker_theme());
}
ThemePickerView::Family(_) => self.picker_apply(),
}
}
/// Steps up one level (family → folders) and restores the saved-theme preview.
pub(crate) fn picker_back(&mut self) {
if let ThemePickerView::Family(_) = self.state.theme_picker.view {
self.state.theme_picker.view = ThemePickerView::Categories;
self.state.theme = self.manager.theme();
}
}
/// Persists the highlighted theme and closes the picker. No-op unless a
/// family is open (Enter at the folder level dives in instead).
pub(crate) fn picker_apply(&mut self) {
if !matches!(self.state.theme_picker.view, ThemePickerView::Family(_)) {
return;
}
let chosen = self.picker_theme();
match self.manager.set_theme(chosen) {
Ok(theme) => {
self.state.theme = theme;
self.set_status(
format!("Theme set to {} and saved", chosen.title()),
MsgKind::Success,
);
}
Err(e) => {
self.set_status(format!("Could not save theme: {e}"), MsgKind::Error);
}
}
self.state.show_theme_picker = false;
self.state.theme_picker.view = ThemePickerView::Categories;
}
/// Closes the picker and restores the persisted theme (discards any preview).
pub(crate) fn picker_cancel(&mut self) {
self.state.show_theme_picker = false;
self.state.theme_picker.view = ThemePickerView::Categories;
self.state.theme = self.manager.theme();
}
/// Keeps the selection index within the bounds of the currently visible list.
pub(crate) fn clamp_selection(&mut self) {
self.state.clamp_selection();
}
/// Moves the active selection cursor to the next visible item.
pub(crate) fn next_item(&mut self) {
self.state.next_item();
}
/// Moves the active selection cursor to the previous visible item.
pub(crate) fn previous_item(&mut self) {
self.state.previous_item();
}
/// Applies a [`InstallProgress`] event to the active installation state.
pub(crate) fn update_install_progress(&mut self, progress: InstallProgress) {
if let Some(BusyState::Installing {
version,
phase: _,
downloaded,
total,
speed,
started_at,
}) = self.state.busy.clone()
{
match progress {
InstallProgress::Downloading {
downloaded: d,
total: t,
bytes_per_sec,
} => {
self.state.busy = Some(BusyState::Installing {
version,
phase: Phase::Downloading,
downloaded: d,
total: t,
speed: bytes_per_sec,
started_at,
});
}
InstallProgress::Extracting => {
self.state.busy = Some(BusyState::Installing {
version,
phase: Phase::Extracting,
downloaded,
total,
speed,
started_at,
});
}
}
}
}
/// Applies a [`InstallProgress`] event to the active self-update state.
pub(crate) fn update_update_progress(&mut self, progress: InstallProgress) {
if let Some(BusyState::Updating {
version,
phase: _,
downloaded,
total,
speed,
started_at,
}) = self.state.busy.clone()
{
match progress {
InstallProgress::Downloading {
downloaded: d,
total: t,
bytes_per_sec,
} => {
self.state.busy = Some(BusyState::Updating {
version,
phase: Phase::Downloading,
downloaded: d,
total: t,
speed: bytes_per_sec,
started_at,
});
}
InstallProgress::Extracting => {
self.state.busy = Some(BusyState::Updating {
version,
phase: Phase::Extracting,
downloaded,
total,
speed,
started_at,
});
}
}
}
}
}