fix: switch default profile to terminal and fixed some comments

This commit is contained in:
objz committed 2026-04-18 19:44:59 +02:00
1 parent 971375bf1f
commit 52787b57c7
71 files changed
+671 -188

No files matched your search

+9
View File
@@ -1,3 +1,7 @@
// account management panel: list, add (microsoft/offline), delete
// microsoft auth uses the device code flow, so it polls a shared mutex
// for the result while showing the user a code to enter in their browser
use std::sync::{Arc, Mutex};
use crossterm::event::{KeyCode, KeyEvent};
@@ -51,6 +55,8 @@ impl Default for AccountState {
}
impl AccountState {
// called every tick to check if the background auth thread finished.
// can't block on it because the TUI needs to keep rendering
pub fn drain_auth_result(&mut self) {
if let AddMode::DeviceCodeWaiting { pending, .. } = &self.add_mode {
let result = match pending.lock() { Ok(mut slot) => {
@@ -199,6 +205,8 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut AccountState) -> bool {
}
}
// the device code arrives asynchronously from the auth thread,
// so it gets pulled out of a global mutex once it's ready
pub fn drain_device_code(state: &mut AccountState) {
if let AddMode::DeviceCodeWaiting { info, .. } = &mut state.add_mode
&& info.user_code.is_empty()
@@ -322,6 +330,7 @@ fn render_account_list(
frame.render_stateful_widget(list, area, &mut state.list_state);
}
// center a popup of given size within the terminal. nothing fancy
fn popup_area(frame: &Frame, width: u16, height: u16) -> Rect {
let area = frame.area();
let x = area.x + (area.width.saturating_sub(width)) / 2;
+107 -87
View File
@@ -1,19 +1,25 @@
// generic scrollable list for content items (mods, resource packs, shaders, worlds).
// supports toggling items on/off by renaming files with .disabled suffix,
// search filtering, per-instance caching, and directory change detection.
// also handles minecraft's formatting codes for colored mod names/descriptions
// because apparently mojang thought terminal UIs would need that. thanks guys
use std::collections::HashMap;
use std::path::Path;
use std::sync::{Arc, Mutex};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::{
Frame,
layout::Rect,
style::{Color, Modifier, Style},
text::{Line, Span, Text},
widgets::{Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState},
Frame,
};
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::instance::content::mods::{ContentEntry, IconCell};
use crate::config::theme::THEME;
use crate::instance::content::mods::{ContentEntry, IconCell};
type PendingContent = Arc<Mutex<Option<(String, Vec<ContentEntry>)>>>;
type SnapshotRow = (String, String, bool, Option<Vec<Vec<IconCell>>>);
@@ -56,11 +62,11 @@ impl Default for ContentListState {
}
impl ContentListState {
/// Check if the content directory changed (files added/removed).
/// Only triggers a rescan when the directory's modification time differs.
// poll the content directory for changes every ~120 ticks.
// if the dir's mtime changed, invalidate the cache to pick up
// mods/packs the user dropped in from outside the launcher
pub fn try_rescan(&mut self) {
self.check_counter = self.check_counter.wrapping_add(1);
// Check every ~2 seconds (120 ticks at 16ms)
if !self.check_counter.is_multiple_of(120) {
return;
}
@@ -69,13 +75,10 @@ impl ContentListState {
return;
};
let current_mtime = std::fs::metadata(dir)
.ok()
.and_then(|m| m.modified().ok());
let current_mtime = std::fs::metadata(dir).ok().and_then(|m| m.modified().ok());
if current_mtime != self.last_dir_mtime {
self.last_dir_mtime = current_mtime;
// Directory changed — invalidate so next render triggers start_load
if let Some(name) = &self.loaded_for {
self.cache.remove(name);
self.loaded_for = None;
@@ -83,7 +86,6 @@ impl ContentListState {
}
}
/// Set the directory to watch for changes. Call after start_load.
pub fn watch_dir(&mut self, dir: std::path::PathBuf) {
self.last_dir_mtime = std::fs::metadata(&dir).ok().and_then(|m| m.modified().ok());
self.watched_dir = Some(dir);
@@ -100,20 +102,23 @@ impl ContentListState {
}
impl ContentListState {
// saves current entries to cache before loading new ones, and restores
// from cache if this instance was seen before (avoids re-scanning)
pub fn start_load<F>(&mut self, instances_dir: &Path, instance_name: &str, scan_fn: F)
where
F: FnOnce(&Path, &str) -> Vec<ContentEntry> + Send + 'static,
{
if let Some(prev) = self.loaded_for.take()
&& !self.entries.is_empty() {
self.cache.insert(
prev,
CachedList {
entries: std::mem::take(&mut self.entries),
selected: self.list_state.selected,
},
);
}
&& !self.entries.is_empty()
{
self.cache.insert(
prev,
CachedList {
entries: std::mem::take(&mut self.entries),
selected: self.list_state.selected,
},
);
}
if let Some(cached) = self.cache.remove(instance_name) {
self.entries = cached.entries;
@@ -146,35 +151,35 @@ impl ContentListState {
}
pub fn drain_pending(&mut self) {
let taken = match self.pending.lock() { Ok(mut slot) => {
slot.take()
} _ => {
None
}};
let taken = match self.pending.lock() {
Ok(mut slot) => slot.take(),
_ => None,
};
if let Some((instance_name, entries)) = taken
&& (self.loaded_for.as_deref() == Some(&instance_name) || instance_name.is_empty()) {
let selected_name = self
.list_state
.selected
.and_then(|i| self.entries.get(i))
.map(|e| e.name.clone());
&& (self.loaded_for.as_deref() == Some(&instance_name) || instance_name.is_empty())
{
let selected_name = self
.list_state
.selected
.and_then(|i| self.entries.get(i))
.map(|e| e.name.clone());
self.entries = entries;
self.loading = false;
self.entries = entries;
self.loading = false;
if !self.entries.is_empty() {
let new_index = selected_name
.and_then(|name| self.entries.iter().position(|e| e.name == name))
.or(self.list_state.selected)
.map(|i| i.min(self.entries.len().saturating_sub(1)))
.unwrap_or(0);
self.list_state.selected = Some(new_index);
} else {
self.list_state.selected = None;
}
self.update_scrollbar();
if !self.entries.is_empty() {
let new_index = selected_name
.and_then(|name| self.entries.iter().position(|e| e.name == name))
.or(self.list_state.selected)
.map(|i| i.min(self.entries.len().saturating_sub(1)))
.unwrap_or(0);
self.list_state.selected = Some(new_index);
} else {
self.list_state.selected = None;
}
self.update_scrollbar();
}
}
fn update_scrollbar(&mut self) {
@@ -184,6 +189,8 @@ impl ContentListState {
self.scrollbar_state = ScrollbarState::new(max).position(pos);
}
// enable/disable by renaming the file with/without .disabled extension.
// this is how most minecraft launchers handle it
pub fn toggle_selected(&mut self) {
let Some(index) = self.list_state.selected else {
return;
@@ -279,16 +286,16 @@ pub fn handle_key_no_toggle(key_event: &KeyEvent, state: &mut ContentListState)
KeyCode::Enter if key_event.modifiers.contains(KeyModifiers::SHIFT) => {
if let Some(&real_idx) = state.list_state.selected.and_then(|i| filtered.get(i))
&& let Some(dir) = state.entries[real_idx].path.parent()
&& let Err(e) = open::that(dir) {
tracing::error!("Failed to open directory: {}", e);
}
&& let Err(e) = open::that(dir)
{
tracing::error!("Failed to open directory: {}", e);
}
true
}
_ => false,
}
}
/// Returns `true` if the key was consumed.
pub fn handle_key(key_event: &KeyEvent, state: &mut ContentListState) -> bool {
if handle_search_keys(key_event, state) {
return true;
@@ -314,9 +321,10 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut ContentListState) -> bool {
KeyCode::Enter if key_event.modifiers.contains(KeyModifiers::SHIFT) => {
if let Some(&real_idx) = state.list_state.selected.and_then(|i| filtered.get(i))
&& let Some(dir) = state.entries[real_idx].path.parent()
&& let Err(e) = open::that(dir) {
tracing::error!("Failed to open directory: {}", e);
}
&& let Err(e) = open::that(dir)
{
tracing::error!("Failed to open directory: {}", e);
}
true
}
KeyCode::Enter => {
@@ -343,8 +351,7 @@ pub fn render(
let theme = THEME.as_ref();
if state.loading {
frame.render_widget(
Paragraph::new(loading_text)
.style(Style::default().fg(theme.text_dim())),
Paragraph::new(loading_text).style(Style::default().fg(theme.text_dim())),
area,
);
return;
@@ -354,8 +361,7 @@ pub fn render(
if filtered.is_empty() {
frame.render_widget(
Paragraph::new(empty_text)
.style(Style::default().fg(theme.text_dim())),
Paragraph::new(empty_text).style(Style::default().fg(theme.text_dim())),
area,
);
return;
@@ -390,7 +396,9 @@ pub fn render(
let (name_style, description_style, background) = match (*enabled, show_selected) {
(true, true) => (
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD),
Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD),
Style::default().fg(theme.text_dim()),
stripe_bg,
),
@@ -402,12 +410,16 @@ pub fn render(
stripe_bg,
),
(false, true) => (
Style::default().fg(theme.accent()).add_modifier(Modifier::CROSSED_OUT),
Style::default()
.fg(theme.accent())
.add_modifier(Modifier::CROSSED_OUT),
Style::default().fg(theme.text_dim()),
stripe_bg,
),
(false, false) => (
Style::default().fg(theme.text_dim()).add_modifier(Modifier::CROSSED_OUT),
Style::default()
.fg(theme.text_dim())
.add_modifier(Modifier::CROSSED_OUT),
Style::default().fg(theme.text_dim()),
stripe_bg,
),
@@ -530,6 +542,8 @@ pub fn render(
);
}
// minecraft's 16-color palette, keyed by the formatting code character.
// these exact RGB values come from the minecraft wiki
fn mc_color(code: char) -> Option<Color> {
match code {
'0' => Some(Color::Rgb(0x00, 0x00, 0x00)),
@@ -552,6 +566,8 @@ fn mc_color(code: char) -> Option<Color> {
}
}
// parses minecraft's section-sign (U+00A7) formatting codes into styled spans.
// handles colors (0-f), bold (l), strikethrough (m), underline (n), italic (o), reset (r)
fn parse_mc_text(text: &str, base_style: Style) -> Vec<Span<'static>> {
let mut spans = Vec::new();
let mut current_style = base_style;
@@ -560,37 +576,38 @@ fn parse_mc_text(text: &str, base_style: Style) -> Vec<Span<'static>> {
while let Some(ch) = chars.next() {
if ch == '\u{00A7}'
&& let Some(&code) = chars.peek() {
if !current_text.is_empty() {
spans.push(Span::styled(current_text.clone(), current_style));
current_text.clear();
}
chars.next();
if let Some(color) = mc_color(code) {
current_style = base_style.fg(color);
} else {
match code {
'l' | 'L' => {
current_style = current_style.add_modifier(Modifier::BOLD);
}
'm' | 'M' => {
current_style = current_style.add_modifier(Modifier::CROSSED_OUT);
}
'n' | 'N' => {
current_style = current_style.add_modifier(Modifier::UNDERLINED);
}
'o' | 'O' => {
current_style = current_style.add_modifier(Modifier::ITALIC);
}
'r' | 'R' => {
current_style = base_style;
}
_ => {}
}
}
continue;
&& let Some(&code) = chars.peek()
{
if !current_text.is_empty() {
spans.push(Span::styled(current_text.clone(), current_style));
current_text.clear();
}
chars.next();
if let Some(color) = mc_color(code) {
current_style = base_style.fg(color);
} else {
match code {
'l' | 'L' => {
current_style = current_style.add_modifier(Modifier::BOLD);
}
'm' | 'M' => {
current_style = current_style.add_modifier(Modifier::CROSSED_OUT);
}
'n' | 'N' => {
current_style = current_style.add_modifier(Modifier::UNDERLINED);
}
'o' | 'O' => {
current_style = current_style.add_modifier(Modifier::ITALIC);
}
'r' | 'R' => {
current_style = base_style;
}
_ => {}
}
}
continue;
}
current_text.push(ch);
}
@@ -614,6 +631,9 @@ fn strip_mc_codes(text: &str) -> String {
result
}
// renders one row of a mod icon using half-block characters (U+2584).
// each cell packs two vertical pixels via fg/bg colors, giving
// double the vertical resolution out of the terminal
fn icon_spans(icon_pixels: Option<&Vec<Vec<IconCell>>>, row: usize) -> Vec<Span<'static>> {
match icon_pixels.and_then(|rows| rows.get(row)) {
Some(cols) => cols
+2
View File
@@ -1,3 +1,5 @@
// the tabbed content area: mods, resource packs, shaders, screenshots, worlds, logs
pub mod list;
pub mod tabs;
+9
View File
@@ -1,3 +1,7 @@
// the outer frame for the content area: tab bar, keybind footer,
// and dispatching render calls to the active tab's widget.
// also renders the instance name/version header with run state indicators.
use ratatui::{
layout::{Alignment, Constraint, Layout, Rect},
style::{Modifier, Style},
@@ -137,6 +141,8 @@ pub fn render(
block = block.title_top(sl);
}
// keybinds change depending on which tab is active and whether
// the content panel or instances panel has focus
let kb: Option<&[(&str, &str)]> = if is_focused {
Some(match tab {
ContentTab::Mods | ContentTab::ResourcePacks | ContentTab::Shaders => &[
@@ -203,6 +209,7 @@ pub fn render(
let content_area = block.inner(area);
frame.render_widget(block, area);
// lazy-load: only scan when switching to an instance that hasn't been loaded yet
match tab {
ContentTab::Mods => {
if let Some(instance) = instance {
@@ -339,6 +346,8 @@ pub fn render(
}
}
// the header bar above the content tabs, showing instance name, loader info,
// and a spinner/error indicator when the instance is running or crashed
pub fn title(
frame: &mut Frame,
area: Rect,
+3
View File
@@ -1,3 +1,6 @@
// settings panel: shows instance config (memory, java, jvm args, resolution)
// and provides keybinds to open config files in $EDITOR
use ratatui::{
layout::Rect,
style::{Modifier, Style},
+6
View File
@@ -1,3 +1,7 @@
// the instance list on the left side of the UI.
// handles search/filter, scrollbar sync, and inline renaming.
// each row shows instance name + "last played" or current run state.
use crate::config::theme::{THEME, BORDER_STYLE};
use crossterm::event::KeyCode;
use ratatui::{
@@ -15,6 +19,8 @@ use crate::tui::app::FocusedArea;
use super::{search::SearchState, styled_title, WidgetKey};
// rough human-friendly time delta. not trying to be precise here,
// "2 months ago" is close enough when months are ~30 days
fn format_last_played(last_played: Option<chrono::DateTime<chrono::Utc>>) -> String {
let Some(dt) = last_played else {
return "Never played".to_string();
+12
View File
@@ -1,3 +1,8 @@
// split-pane log viewer: file list on the left, log content on the right.
// supports live log tailing when the instance is running, plus search
// filtering in both the file list and the viewer pane.
// log scanning runs on a background thread to avoid blocking the UI.
use std::path::Path;
use std::sync::{Arc, Mutex};
@@ -114,6 +119,8 @@ impl LogsState {
}
}
// periodically re-scan log files in case new ones appeared while playing.
// only triggers every 120 ticks to avoid hammering the filesystem
pub fn try_rescan(&mut self) {
self.rescan_counter = self.rescan_counter.wrapping_add(1);
if !self.rescan_counter.is_multiple_of(120) {
@@ -142,6 +149,7 @@ impl LogsState {
});
}
// when an instance is running, a synthetic "Live" entry is injected at index 0
fn has_live(&self) -> bool {
let name = self.loaded_for.as_deref().unwrap_or("");
matches!(
@@ -487,6 +495,8 @@ fn render_viewer(
.collect();
let visible_height = area.height as usize;
// auto-scroll: if the user was already at the bottom, keep following
// new lines as they come in (like `tail -f` behavior)
let was_at_bottom = state.viewer_scroll >= state.viewer_max_scroll.saturating_sub(1);
state.update_viewer_scrollbar(visible_height, lines.len());
@@ -533,6 +543,8 @@ fn render_viewer(
);
}
// color-code log lines by severity so errors actually stand out
// instead of drowning in a wall of white text
fn line_level_style(line: &str) -> Style {
let theme = THEME.as_ref();
let upper = line.to_uppercase();
+4
View File
@@ -1,3 +1,5 @@
// shared widget utilities and the trait all key-handling widgets implement
use crate::config::theme::THEME;
use crossterm::event::KeyEvent;
use ratatui::{
@@ -15,6 +17,8 @@ pub mod screenshots_grid;
pub mod search;
pub mod status;
// highlight the first character of a title with the accent color,
// gives the UI that "keyboard shortcut hint" look
pub fn styled_title(title: &str, highlight: bool) -> Line<'_> {
let theme = THEME.as_ref();
if !highlight || title.is_empty() {
+5
View File
@@ -1,3 +1,7 @@
// base frame that all popups render inside. handles the border, title bar,
// keybind footer, and optional search indicator. content is injected via closure
// so each popup type only worries about its inner area.
use ratatui::{
buffer::Buffer,
layout::{Alignment, Rect},
@@ -21,6 +25,7 @@ pub struct PopupFrame<'a> {
impl<'a> Widget for PopupFrame<'a> {
fn render(self, area: Rect, buf: &mut Buffer) {
// clear first so the popup doesn't layer on top of whatever was underneath
Clear.render(area, buf);
if let Some(bg) = self.bg {
+3
View File
@@ -1,3 +1,6 @@
// "are you sure?" popup for instance deletion. uses global state so the
// confirmation target persists across render frames.
use std::sync::LazyLock;
use std::sync::Mutex;
+5
View File
@@ -1,3 +1,6 @@
// toast-style error/warning popup that auto-dismisses after a timeout.
// stacks in the top-right corner; border color changes based on severity.
use ratatui::{
buffer::Buffer,
layout::Rect,
@@ -60,6 +63,8 @@ impl Widget for ErrorPopup {
}
}
// returns None when the toast has lived past its expiry, which is
// what triggers removal from the render loop
pub fn popup_area(frame_area: Rect, message: &str, base_y: u16, elapsed_ms: u128) -> Option<Rect> {
use super::word_wrap_size;
@@ -1,3 +1,6 @@
// rendering for the modpack import wizard. same pattern as new_instance:
// snapshot the state, pick the right step renderer, done.
use super::super::base::PopupFrame;
use super::super::new_instance::LoadState;
use super::state::{ImportStep, ImportWizardState, IMPORT_STATE};
@@ -1,3 +1,8 @@
// state machine for the modpack import wizard.
// accepts modrinth URLs, project slugs, version IDs, or local .mrpack paths.
// for remote packs, it fetches project info then lets the user pick a version.
// local files skip straight to the confirm step.
use super::super::new_instance::LoadState;
use crate::instance::import::ImportSummary;
use crate::net::modrinth::{self, ModrinthInput, VersionInfo};
@@ -189,6 +194,7 @@ fn handle_confirm_key(
) {
match key_event.code {
KeyCode::Esc => close_popup(state, instances_state),
// if it came from a local file, there's no version list to go back to
KeyCode::Left | KeyCode::Char('h') => {
if matches!(state.versions, LoadState::Loaded(_)) {
state.step = ImportStep::Version;
@@ -217,6 +223,7 @@ fn handle_confirm_key(
}
}
// pushes an error toast and rewinds the wizard to a previous step
fn set_error_and_back(state_arc: &Arc<Mutex<ImportWizardState>>, msg: String, step: ImportStep) {
push_import_error(msg);
if let Ok(mut s) = state_arc.lock() {
@@ -224,6 +231,8 @@ fn set_error_and_back(state_arc: &Arc<Mutex<ImportWizardState>>, msg: String, st
}
}
// parses user input to figure out what they gave us, then dispatches
// to the appropriate resolve path (slug lookup, direct version, or local file)
fn start_resolve(state: &mut ImportWizardState) {
let input_text = state.input.clone();
state.step = ImportStep::Fetching;
@@ -364,6 +373,8 @@ fn resolve_local_file(state_arc: Arc<Mutex<ImportWizardState>>, path: &str) {
}
}
// user picked a version from the list. download the .mrpack, parse it,
// build a summary, and move to confirm.
fn start_version_download(state: &mut ImportWizardState) {
let version = match selected_version(state) {
Some(v) => v.clone(),
+13 -10
View File
@@ -1,3 +1,6 @@
// shared utilities for popup widgets: layout helpers, word wrapping, keybind rendering.
// individual popup types live in their own submodules.
pub mod base;
pub mod confirm;
pub mod error;
@@ -6,14 +9,8 @@ pub mod new_instance;
use ratatui::layout::Rect;
/// Calculates the minimum inner dimensions needed to display `text` with word-boundary wrapping
/// inside a box of `max_inner_width` columns.
///
/// Returns `(actual_inner_width, line_count)` where:
/// - `actual_inner_width` is the width of the widest wrapped line (never exceeds `max_inner_width`)
/// - `line_count` is how many lines are needed
///
/// Add 2 to each dimension for borders: popup_w = actual_inner_width + 2, popup_h = line_count + 2.
// figures out the (width, height) a text block will need after word wrapping.
// used to size popups before rendering so they fit their content snugly.
pub fn word_wrap_size(text: &str, max_inner_width: usize) -> (usize, usize) {
if text.is_empty() || max_inner_width == 0 {
return (0, 1);
@@ -62,7 +59,9 @@ pub fn keybind_line(binds: &[(&str, &str)]) -> ratatui::text::Line<'static> {
text::{Line, Span},
};
let theme = THEME.as_ref();
let key_style = Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD);
let key_style = Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD);
let label_style = Style::default().fg(theme.text());
let mut spans: Vec<Span<'static>> = Vec::new();
@@ -78,6 +77,8 @@ pub fn keybind_line(binds: &[(&str, &str)]) -> ratatui::text::Line<'static> {
Line::from(spans)
}
// same as keybind_line but wraps to multiple rows when the popup is too narrow
// to fit everything on one line
pub fn keybind_lines_wrapped(
binds: &[(&str, &str)],
max_width: u16,
@@ -88,7 +89,9 @@ pub fn keybind_lines_wrapped(
text::{Line, Span},
};
let theme = THEME.as_ref();
let key_style = Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD);
let key_style = Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD);
let label_style = Style::default().fg(theme.text());
let mut rows: Vec<Line<'static>> = Vec::new();
@@ -1,3 +1,6 @@
// rendering for the new instance wizard. each step gets its own render fn
// and the popup resizes itself based on which step is active.
use super::state::{
clamp_loader_version_index, clamp_version_index, ensure_loader_versions_loaded,
ensure_versions_loaded, visible_versions, LoadState, WizardState, WizardStep, WIZARD_STATE,
@@ -16,6 +19,9 @@ use ratatui::{
};
pub fn render(frame: &mut Frame, area: Rect, _focused: FocusedArea) {
// grab the lock, kick off any lazy-loading, then clone and release.
// data fetching happens here (in render) because the wizard is purely
// reactive: version lists only load when you navigate to that step.
let snapshot = match WIZARD_STATE.lock() {
Ok(mut state) => {
if state.step == WizardStep::Version {
@@ -23,6 +29,7 @@ pub fn render(frame: &mut Frame, area: Rect, _focused: FocusedArea) {
clamp_version_index(&mut state);
}
// vanilla has no loader version, so skip straight to confirm
if state.step == WizardStep::LoaderVersion {
if state.selected_loader() == ModLoader::Vanilla {
state.step = WizardStep::Confirm;
@@ -130,6 +137,7 @@ fn step_keybinds(state: &WizardState) -> ratatui::text::Line<'static> {
fn render_name_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
let theme = THEME.as_ref();
let value = state.name_state.value();
// \u{2588} is the full block char used as a fake blinking cursor
let line = if value.is_empty() {
Line::from(vec![
Span::styled(
+16 -5
View File
@@ -1,5 +1,9 @@
// state machine and input handling for the new instance wizard.
// flow: Name -> Loader -> Version -> LoaderVersion -> Confirm
// version lists are fetched lazily from the network when you reach that step.
use crate::instance::{
loader::{get_installer, GameVersion},
loader::{GameVersion, get_installer},
models::ModLoader,
};
use crate::tui::widgets::instances;
@@ -10,6 +14,7 @@ use tui_prompts::{FocusState, State as PromptState, TextState};
pub(crate) static WIZARD_STATE: LazyLock<Arc<Mutex<WizardState>>> =
LazyLock::new(|| Arc::new(Mutex::new(WizardState::default())));
// populated on confirm, consumed by the main event loop to actually create the instance
pub(crate) static WIZARD_RESULT: LazyLock<Arc<Mutex<Option<WizardParams>>>> =
LazyLock::new(|| Arc::new(Mutex::new(None)));
@@ -31,8 +36,7 @@ pub enum WizardStep {
Confirm,
}
#[derive(Debug, Clone)]
#[derive(Default)]
#[derive(Debug, Clone, Default)]
pub enum LoadState<T> {
#[default]
Idle,
@@ -386,6 +390,8 @@ pub(crate) fn clamp_loader_version_index(state: &mut WizardState) {
}
}
// only fires on the Idle -> Loading transition to avoid spamming requests.
// the spawned task writes results back into WIZARD_STATE when done.
pub(crate) fn ensure_versions_loaded(state: &mut WizardState) {
if !matches!(state.versions, LoadState::Idle) {
return;
@@ -420,7 +426,11 @@ pub(crate) fn ensure_versions_loaded(state: &mut WizardState) {
});
}
pub(crate) fn ensure_loader_versions_loaded(state: &mut WizardState, loader: ModLoader, game_version: String) {
pub(crate) fn ensure_loader_versions_loaded(
state: &mut WizardState,
loader: ModLoader,
game_version: String,
) {
if !matches!(state.loader_versions, LoadState::Idle) {
return;
}
@@ -452,6 +462,8 @@ pub(crate) fn ensure_loader_versions_loaded(state: &mut WizardState, loader: Mod
});
}
// quick and dirty semver compare. doesn't handle pre-release tags or anything
// fancy, just splits on dots and compares numerically. good enough for mc versions.
fn compare_semver(a: &str, b: &str) -> std::cmp::Ordering {
let parse_parts = |s: &str| -> Vec<u64> {
s.split('.')
@@ -470,6 +482,5 @@ fn compare_semver(a: &str, b: &str) -> std::cmp::Ordering {
}
fn sort_versions_semver(versions: &mut [GameVersion]) {
// Sort newest first (descending), so compare b vs a
versions.sort_by(|a, b| compare_semver(&b.id, &a.id));
}
+11
View File
@@ -1,3 +1,7 @@
// responsive grid of screenshot thumbnails rendered directly in the terminal.
// images load lazily on background threads as they scroll into view,
// and get converted to terminal graphics via ratatui-image protocols.
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::{Arc, Mutex};
@@ -15,6 +19,8 @@ use ratatui_image::{protocol::StatefulProtocol, Resize, StatefulImage};
use crate::instance::screenshots::ScreenshotEntry;
use crate::config::theme::THEME;
// grid cell sizing constraints in terminal columns.
// the grid auto-fits columns within these bounds depending on terminal width
const TARGET_CELL_WIDTH: u16 = 34;
const MIN_CELL_WIDTH: u16 = 24;
const MAX_CELL_WIDTH: u16 = 52;
@@ -118,6 +124,8 @@ impl ScreenshotsState {
self.protocols.insert(idx, proto);
}
// only load images that are currently visible (or about to be).
// no point decoding a 4K screenshot the user can't even see yet
pub fn request_visible_loads(&mut self) {
if self.entries.is_empty() {
return;
@@ -286,6 +294,9 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_fo
let cols = target_cols.clamp(min_cols, max_cols);
let cell_width = area.width / cols as u16;
// figure out how tall each thumbnail should be in terminal rows.
// need the font's pixel aspect ratio to keep screenshots from
// looking stretched since terminal cells aren't square
let (img_w, img_h) = state
.entries
.first()
+6
View File
@@ -1,3 +1,6 @@
// reusable incremental search state used across multiple widgets.
// handles case-insensitive filtering and inline match highlighting.
use ratatui::{
style::{Modifier, Style},
text::{Line, Span},
@@ -40,6 +43,8 @@ impl SearchState {
text.to_lowercase().contains(&self.query.to_lowercase())
}
// splits a line into spans, bolding+underlining the parts that match
// the query so they pop out visually
pub fn highlight_line<'a>(&self, text: &'a str, base_style: Style) -> Line<'a> {
if self.query.is_empty() {
return Line::from(Span::styled(text, base_style));
@@ -72,6 +77,7 @@ impl SearchState {
}
}
// renders the "/ query█" indicator in the block title bar
pub fn title_line(&self) -> Option<Line<'static>> {
if !self.active && self.query.is_empty() {
return None;
+3
View File
@@ -1,3 +1,6 @@
// the "overview" panel showing download/install progress.
// shows a gauge when the total is known, or a spinner when it's not.
use ratatui::{
layout::{Constraint, Layout, Rect},
style::{Modifier, Style},