govmr 2.2.0

A high-performance, asynchronous Go Version Manager with a slick terminal UI.
//! Module state - Mutable UI state containers and transient status types for the TUI.

use crate::{
    theme::{Theme, ThemeName, ThemePickerView},
    version::GoVersion,
};
use ratatui::{text::Line, widgets::ListState};
use std::time::Instant;

// ------------------------------------------ Types & Impls ------------------------------------- //

/// Identifies the currently active tab view in the TUI.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum ActiveTab {
    /// Browsing all official remote versions.
    Available,
    /// Browsing locally installed toolchains.
    Installed,
}
impl ActiveTab {
    /// Flips to the other tab.
    #[must_use]
    pub(crate) fn toggle(self) -> Self {
        match self {
            ActiveTab::Available => ActiveTab::Installed,
            ActiveTab::Installed => ActiveTab::Available,
        }
    }
}

/// Severity of a transient status message.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum MsgKind {
    /// Positive confirmation.
    Success,
    /// Failure or destructive warning.
    Error,
    /// Neutral informational note.
    Info,
}

/// A transient status-bar message.
#[derive(Clone)]
pub(crate) struct StatusMessage {
    /// Human-readable text.
    pub(crate) text: String,
    /// Visual severity.
    pub(crate) kind: MsgKind,
}

/// Lifecycle phase of a running installation.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Phase {
    /// The archive is being downloaded.
    Downloading,
    /// The archive is being extracted to disk.
    Extracting,
}

/// Background task state surfaced to the UI.
#[derive(Clone)]
pub(crate) enum BusyState {
    /// Refreshing the version manifest from `go.dev`.
    Refreshing,
    /// Switching the active toolchain.
    Switching(String),
    /// Removing an installed toolchain.
    Deleting(String),
    /// Installing a toolchain, with live progress.
    Installing {
        /// Version being installed.
        version: String,
        /// Current lifecycle phase.
        phase: Phase,
        /// Bytes fetched so far.
        downloaded: u64,
        /// Total archive size in bytes.
        total: u64,
        /// Download speed in bytes per second.
        speed: f64,
        /// When the download started (for ETA calculations).
        started_at: Instant,
    },
    /// Self-updating the govmr binary, with live progress.
    Updating {
        version: String,
        phase: Phase,
        downloaded: u64,
        total: u64,
        speed: f64,
        started_at: Instant,
    },
}
impl BusyState {
    /// Returns the version targeted by the busy operation, if any.
    #[must_use]
    pub(crate) fn target(&self) -> Option<&str> {
        match self {
            BusyState::Refreshing => None,
            BusyState::Switching(v)
            | BusyState::Deleting(v)
            | BusyState::Installing { version: v, .. }
            | BusyState::Updating { version: v, .. } => Some(v),
        }
    }
}

/// Navigation state of the two-level theme picker (📁 folders → themes).
///
/// `view` says which level is on screen; `family_cursor` is only meaningful
/// at the folder level and `theme_cursor` only inside an open family, so a
/// stale cursor can never leak across levels.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct ThemePickerState {
    /// Which level of the picker is currently rendered.
    pub(crate) view: ThemePickerView,
    /// Highlighted folder at the folder level (0 = Dark, 1 = Light).
    pub(crate) family_cursor: usize,
    /// Highlighted theme inside the open family.
    pub(crate) theme_cursor: usize,
}

/// Tracks pending destructive/system actions requiring confirmation.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum SystemPrompt {
    /// Prompt the user to confirm downloading and applying the latest govmr update.
    Update,
    /// Prompt the user to confirm uninstalling the govmr binary while keeping `~/.govmr`.
    UninstallKeep,
    /// Prompt the user to confirm uninstalling the govmr binary AND purging `~/.govmr`.
    UninstallPurge,
}

/// A visual addition (separator, blank line) inserted into the log display.
///
/// Anchored to the physical file line count at the time it was created, so
/// new log entries tail in *below* the separator rather than pushing it down.
#[derive(Clone)]
pub(crate) struct VisualAddition {
    /// The text to render (e.g. a line of hyphens, or an empty string).
    pub(crate) text: String,
    /// The physical file line count when this addition was created.
    pub(crate) anchor: usize,
}

/// Holds all state variables required for rendering and interacting with the TUI.
/// A flat bag of independent UI toggles: they combine freely, so neither a
/// state machine nor grouped bool enums would model them more accurately.
#[allow(clippy::struct_excessive_bools)]
pub(crate) struct AppState {
    /// Full list of available and installed versions.
    pub(crate) versions: Vec<GoVersion>,
    /// State container for the interactive version list widget.
    pub(crate) list_state: ListState,
    /// The currently selected tab view.
    pub(crate) active_tab: ActiveTab,
    /// Current background task, if any.
    pub(crate) busy: Option<BusyState>,
    /// Transient status-bar message.
    pub(crate) status_message: Option<StatusMessage>,
    /// Targeted version pending user deletion confirmation.
    pub(crate) confirming_delete: Option<String>,
    /// Indicates whether the `GoVMR` shim path is configured in system `PATH`.
    pub(crate) is_shim_in_path: bool,
    /// Filesystem path to the shim directory (shown in the help overlay).
    pub(crate) shim_path: String,
    /// Live filter query applied to the current view.
    pub(crate) filter: String,
    /// Whether the user is actively typing a filter query.
    pub(crate) filter_mode: bool,
    /// Whether the PATH-setup help overlay is displayed.
    pub(crate) show_help: bool,
    /// Whether the right-docked keyboard help panel is currently displayed.
    pub(crate) show_command_help: bool,
    /// Vertical scroll offset (in content lines) of the keyboard help panel.
    pub(crate) command_help_scroll: usize,
    /// Whether the color-theme picker overlay is displayed.
    pub(crate) show_theme_picker: bool,
    /// Two-level theme-picker navigation (folder → theme) state.
    pub(crate) theme_picker: ThemePickerState,
    /// The active color palette (reloaded instantly when switching themes).
    pub(crate) theme: Theme,
    /// Monotonic render counter used to drive spinner animations.
    pub(crate) tick_count: u64,
    /// Result feedback of the permanent PATH fix (`f` in the setup/help overlay),
    /// rendered *inside* the overlay so the user sees exactly what govmr did.
    pub(crate) path_fix_notice: Option<Vec<Line<'static>>>,
    /// Whether the operation-log viewer overlay is displayed.
    pub(crate) show_logs: bool,
    /// Cached log lines shown by the viewer (refreshed periodically while open).
    pub(crate) log_lines: Vec<String>,
    /// How far the viewer is scrolled up from the newest entry (0 = pinned to bottom).
    pub(crate) log_scroll: usize,
    /// Whether the viewer auto-follows the newest log entries.
    pub(crate) log_follow: bool,
    /// When the log cache was last refreshed (used to throttle re-reads).
    pub(crate) log_refreshed: Option<Instant>,
    /// Whether keyboard focus is currently on the docked log panel.
    pub(crate) log_focus: bool,
    /// Whether long log lines wrap instead of clipping at the panel edge.
    pub(crate) log_wrap: bool,
    /// How many leading *physical* log lines a visual clear (`Ctrl+l`) hides.
    ///
    /// Behaves like clearing a terminal: lines written *after* the clear still
    /// tail into the panel, and closing/reopening resets the watermark so the
    /// full file is visible again. Replaces the boolean flag that hid the
    /// entire file until the panel was reopened.
    pub(crate) log_visual_skip: usize,
    /// Visual additions (separators, blank lines) inserted into the log display.
    /// Each addition is anchored to the physical file line count at the time it
    /// was created, so new log entries tail in *below* the separator rather than
    /// pushing it down.
    pub(crate) log_visual_additions: Vec<VisualAddition>,
    /// Sender used to signal cancellation of an ongoing installation.
    pub(crate) cancel_install: Option<tokio::sync::watch::Sender<bool>>,
    /// Tracks which system-level confirmation modal (Update/Uninstall) is currently active.
    pub(crate) system_prompt: Option<SystemPrompt>,
}
impl AppState {
    /// Constructs a fresh state for the supplied version list (used by tests/setup).
    #[allow(dead_code)]
    pub(crate) fn from_versions(versions: Vec<GoVersion>, is_shim_in_path: bool) -> Self {
        let mut list_state = ListState::default();
        if !versions.is_empty() {
            list_state.select(Some(0));
        }
        let theme = Theme::for_name(ThemeName::default());
        Self {
            versions,
            list_state,
            active_tab: ActiveTab::Available,
            busy: None,
            status_message: None,
            confirming_delete: None,
            is_shim_in_path,
            shim_path: String::from("~/.govmr/shim"),
            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,
            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,
            cancel_install: None,
            system_prompt: None,
            log_visual_skip: 0,
            log_visual_additions: Vec::new(),
        }
    }

    /// Returns indices into `versions` visible under the current tab and filter.
    #[must_use]
    pub(crate) fn visible_indices(&self) -> Vec<usize> {
        visible_indices(self)
    }

    /// Keeps the selection index within the bounds of the currently visible list.
    pub(crate) fn clamp_selection(&mut self) {
        let len = self.visible_indices().len();
        match self.list_state.selected() {
            Some(i) if len > 0 && i >= len => self.list_state.select(Some(len - 1)),
            None if len > 0 => self.list_state.select(Some(0)),
            Some(_) | None => {}
        }
    }

    /// Moves the active selection cursor to the next visible item (wraps around).
    pub(crate) fn next_item(&mut self) {
        let len = self.visible_indices().len();
        if len == 0 {
            return;
        }
        let i = match self.list_state.selected() {
            Some(i) => (i + 1) % len,
            None => 0,
        };
        self.list_state.select(Some(i));
    }

    /// Moves the active selection cursor to the previous visible item (wraps around).
    pub(crate) fn previous_item(&mut self) {
        let len = self.visible_indices().len();
        if len == 0 {
            return;
        }
        let i = match self.list_state.selected() {
            Some(0) => len - 1,
            Some(i) => i - 1,
            None => 0,
        };
        self.list_state.select(Some(i));
    }
}

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

/// Returns indices into [`AppState::versions`] visible under the given state's tab and filter.
#[must_use]
pub(crate) fn visible_indices(state: &AppState) -> Vec<usize> {
    let query = state.filter.to_lowercase();
    state
        .versions
        .iter()
        .enumerate()
        .filter(|(_, v)| match state.active_tab {
            ActiveTab::Available => true,
            ActiveTab::Installed => v.installed,
        })
        .filter(|(_, v)| {
            query.is_empty()
                || v.raw_version.to_lowercase().contains(&query)
                || v.display_name.to_lowercase().contains(&query)
        })
        .map(|(i, _)| i)
        .collect()
}