From 94362f09476399cd4ddb7d49fff71aeb485eb41e Mon Sep 17 00:00:00 2001 From: objz Date: Thu, 3 Sep 2026 20:56:58 +0200 Subject: [PATCH] fix: restore settings panel workflow --- src/tui/app.rs | 3 + src/tui/event.rs | 4 + src/tui/input.rs | 109 ++++ src/tui/render.rs | 1 + src/tui/tests/flows.rs | 36 +- src/tui/tests/harness.rs | 1 + ...nfirmation_renders_the_complete_frame.snap | 6 +- src/tui/tests/widgets/settings.rs | 19 + src/tui/widgets/popups/global_settings.rs | 103 +++- src/tui/widgets/popups/instance_settings.rs | 149 +++-- src/tui/widgets/settings.rs | 540 ++++++++++++++++-- 11 files changed, 856 insertions(+), 115 deletions(-) create mode 100644 src/tui/tests/widgets/settings.rs diff --git a/src/tui/app.rs b/src/tui/app.rs index ae2d527..3c00e89 100644 --- a/src/tui/app.rs +++ b/src/tui/app.rs @@ -41,6 +41,7 @@ pub struct App { pub(super) screenshots_state: widgets::screenshots_grid::ScreenshotsState, pub(super) logs_state: widgets::logs_viewer::LogsState, pub(super) account_state: widgets::account::AccountState, + pub(super) settings_state: widgets::settings::SettingsState, pub(super) instance_settings: Option, pub(super) global_settings: Option, pub(super) picker: ratatui_image::picker::Picker, @@ -126,6 +127,7 @@ impl App { crate::instance::import::refresh::recover_interrupted(&instances_dir); let manager = InstanceManager::new(instances_dir, meta_dir); + let settings_state = widgets::settings::SettingsState::new(manager.meta_dir.clone()); let instances = manager.load_all(); instances::spawn_modpack_update_checks(&instances); let instances_state = instances::State::with_instances(instances); @@ -172,6 +174,7 @@ impl App { world_quick_play_support: None, logs_state: widgets::logs_viewer::LogsState::default(), account_state: widgets::account::AccountState::default(), + settings_state, instance_settings: None, global_settings: None, screenshots_state: { diff --git a/src/tui/event.rs b/src/tui/event.rs index e04ac89..28293f1 100644 --- a/src/tui/event.rs +++ b/src/tui/event.rs @@ -223,6 +223,10 @@ impl App { &self.account_state.add_mode, widgets::account::AddMode::None )) + + usize::from(!matches!( + &self.settings_state.add_mode, + widgets::settings::AddMode::None + )) + [ &self.mods_discovery_state, &self.resource_packs_discovery_state, diff --git a/src/tui/input.rs b/src/tui/input.rs index a8fd94b..10160b6 100644 --- a/src/tui/input.rs +++ b/src/tui/input.rs @@ -223,6 +223,8 @@ impl App { message: e.to_string(), pushed_at: std::time::Instant::now(), }); + } else { + self.settings_state.remove_profile(&profile); } FocusedArea::Settings } @@ -552,6 +554,112 @@ impl App { return Ok(()); } + if self.focused == FocusedArea::Settings { + let editing_profile = matches!( + &self.settings_state.add_mode, + widgets::settings::AddMode::ProfileName(_) + ); + match widgets::settings::handle_key( + &key_event, + &mut self.settings_state, + self.instances_state.selected_instance(), + ) { + widgets::settings::SettingsAction::OpenInstance => { + if let Some(instance) = self.instances_state.selected_instance() { + self.pre_overlay_focused = FocusedArea::Settings; + self.instance_settings = + Some(widgets::popups::instance_settings::State::new( + instance, + &self.instance_manager.meta_dir, + )); + self.focused = FocusedArea::InstanceSettings; + } + return Ok(()); + } + widgets::settings::SettingsAction::OpenGlobal => { + self.pre_overlay_focused = FocusedArea::Settings; + self.global_settings = Some(widgets::popups::global_settings::State::new()); + self.focused = FocusedArea::GlobalSettings; + return Ok(()); + } + widgets::settings::SettingsAction::ToggleDesktop => { + if let Some(instance) = self.instances_state.selected_instance() { + let name = instance.name.clone(); + match crate::instance::desktop::toggle(instance) { + Ok(true) => error_buffer::push_error(error_buffer::ErrorEvent { + id: 0, + level: tracing::Level::INFO, + message: format!("Desktop shortcut created for '{name}'"), + pushed_at: std::time::Instant::now(), + }), + Ok(false) => error_buffer::push_error(error_buffer::ErrorEvent { + id: 0, + level: tracing::Level::INFO, + message: format!("Desktop shortcut removed for '{name}'"), + pushed_at: std::time::Instant::now(), + }), + Err(error) => { + tracing::error!("Failed to toggle desktop shortcut: {error}"); + } + } + } + return Ok(()); + } + widgets::settings::SettingsAction::SelectProfile(profile) => { + if let Some(instance) = self.instances_state.selected_instance().cloned() { + let instance_dir = self.instance_manager.instances_dir.join(&instance.name); + match crate::instance::config_sync::switch_profile( + &instance.name, + instance.config_sync_profile.as_deref(), + profile.as_deref(), + &self.instance_manager.meta_dir, + &instance_dir, + ) { + Ok(selected) => { + let mut updated = instance.clone(); + updated.config_sync_profile = selected; + if let Err(error) = self.instance_manager.save(&updated) { + tracing::error!("Failed to save config profile: {error}"); + } else { + self.instances_state + .replace_instance(&instance.name, updated); + } + } + Err(error) => { + error_buffer::push_error(error_buffer::ErrorEvent { + id: 0, + level: tracing::Level::ERROR, + message: error.to_string(), + pushed_at: std::time::Instant::now(), + }); + } + } + } + return Ok(()); + } + widgets::settings::SettingsAction::ConfirmDeleteProfile(profile) => { + confirm_popup::set_pending(confirm_popup::ConfirmTarget::ConfigProfile { + profile, + }); + self.focused = FocusedArea::ConfirmDelete; + return Ok(()); + } + widgets::settings::SettingsAction::Error(message) => { + error_buffer::push_error(error_buffer::ErrorEvent { + id: 0, + level: tracing::Level::ERROR, + message, + pushed_at: std::time::Instant::now(), + }); + return Ok(()); + } + widgets::settings::SettingsAction::None => {} + } + if editing_profile { + return Ok(()); + } + } + if self.focused == FocusedArea::GlobalSettings { let action = self .global_settings @@ -617,6 +725,7 @@ impl App { widgets::popups::instance_settings::Action::DeleteProfile(profile) => { match self.delete_config_profile(&profile) { Ok(()) => { + self.settings_state.remove_profile(&profile); if let Some(state) = self.instance_settings.as_mut() { state.profile_deleted(&profile); } diff --git a/src/tui/render.rs b/src/tui/render.rs index e0f213e..f087519 100644 --- a/src/tui/render.rs +++ b/src/tui/render.rs @@ -135,6 +135,7 @@ impl App { frame, bottom_chunks[1], self.focused, + &mut self.settings_state, self.instances_state.selected_instance(), ); widgets::status::render( diff --git a/src/tui/tests/flows.rs b/src/tui/tests/flows.rs index 524a7ef..d96632b 100644 --- a/src/tui/tests/flows.rs +++ b/src/tui/tests/flows.rs @@ -571,17 +571,20 @@ fn confirmed_account_delete_updates_the_account_panel() { } #[test] -fn settings_popups_open_from_global_key_events() { +fn settings_panel_routes_legacy_edit_keys_to_tui_popups() { let mut ui = UiHarness::new(); ui.add_instance("settings-test"); ui.app.focused = FocusedArea::Settings; - ui.key(KeyCode::Char('E')); + ui.key(KeyCode::Right); + ui.key(KeyCode::Char('e')); assert_eq!(ui.app.focused, FocusedArea::InstanceSettings); ui.draw(); assert!(ui.screen().contains("Instance settings: settings-test")); assert!(ui.screen().contains("Game version")); assert!(ui.screen().contains("Desktop shortcut")); + assert!(ui.screen().contains('‹')); + assert!(ui.screen().contains('›')); ui.key(KeyCode::Down); ui.key(KeyCode::Enter); ui.draw(); @@ -591,11 +594,13 @@ fn settings_popups_open_from_global_key_events() { ui.key(KeyCode::Esc); assert_eq!(ui.app.focused, FocusedArea::Settings); - ui.key(KeyCode::Char('G')); + ui.key(KeyCode::Char('g')); assert_eq!(ui.app.focused, FocusedArea::GlobalSettings); ui.draw(); assert!(ui.screen().contains("Launcher settings")); assert!(ui.screen().contains("Default memory max")); + assert!(ui.screen().contains('‹')); + assert!(ui.screen().contains('›')); ui.key(KeyCode::Enter); ui.draw(); assert!(ui.screen().contains("Select theme")); @@ -604,6 +609,31 @@ fn settings_popups_open_from_global_key_events() { assert_eq!(ui.app.focused, FocusedArea::Settings); } +#[test] +fn settings_panel_keeps_direct_profile_management() { + let mut ui = UiHarness::new(); + ui.add_instance("profile-test"); + ui.app.focused = FocusedArea::Settings; + + ui.key(KeyCode::Char('a')); + for character in "main".chars() { + ui.key(KeyCode::Char(character)); + } + ui.key(KeyCode::Enter); + + assert_eq!( + ui.app + .instances_state + .selected_instance() + .unwrap() + .config_sync_profile + .as_deref(), + Some("main") + ); + ui.draw(); + assert!(ui.screen().contains("main")); +} + #[test] fn instance_wizards_open_render_and_cancel_through_app_input() { let mut ui = UiHarness::new(); diff --git a/src/tui/tests/harness.rs b/src/tui/tests/harness.rs index 587dfad..695cf5a 100644 --- a/src/tui/tests/harness.rs +++ b/src/tui/tests/harness.rs @@ -82,6 +82,7 @@ impl UiHarness { }, logs_state: widgets::logs_viewer::LogsState::default(), account_state, + settings_state: widgets::settings::SettingsState::new(meta_dir), instance_settings: None, global_settings: None, picker, diff --git a/src/tui/tests/snapshots/rmcl__tui__tests__snapshots__instance_delete_confirmation_renders_the_complete_frame.snap b/src/tui/tests/snapshots/rmcl__tui__tests__snapshots__instance_delete_confirmation_renders_the_complete_frame.snap index 454390f..bf31793 100644 --- a/src/tui/tests/snapshots/rmcl__tui__tests__snapshots__instance_delete_confirmation_renders_the_complete_frame.snap +++ b/src/tui/tests/snapshots/rmcl__tui__tests__snapshots__instance_delete_confirmation_renders_the_complete_frame.snap @@ -28,7 +28,7 @@ expression: ui.screen() "│ ││ │" "│ │╰──────────────────────────────────────────────────────────────────────────────╯" "│ │╭Accounts─────────╮╭Settings───────────────────────────╮╭Overview──────────────╮" -"│ ││No accounts. ││Version 1.21.1 / Fabric ││Ready │" -"│ ││ ││Runtime 512M-2G, auto java ││ │" -"│ ││ ││Profile instance default / desk no││ │" +"│ ││No accounts. ││▸ instance default ││Ready │" +"│ ││ ││ ││ │" +"│ ││ ││ ││ │" "╰──────────────────╯╰─────────────────╯╰───────────────────────────────────╯╰──────────────────────╯" diff --git a/src/tui/tests/widgets/settings.rs b/src/tui/tests/widgets/settings.rs new file mode 100644 index 0000000..4bac7f5 --- /dev/null +++ b/src/tui/tests/widgets/settings.rs @@ -0,0 +1,19 @@ +// SPDX-FileCopyrightText: 2026 Constantin Bauer +// SPDX-License-Identifier: GPL-3.0-only + +use super::*; + +#[test] +fn removing_selected_last_profile_clamps_selection() { + let tmp = tempfile::tempdir().unwrap(); + let mut state = SettingsState::new(tmp.path().to_path_buf()); + state.profiles = vec!["first".to_string(), "second".to_string()]; + state.active_profile = Some("second".to_string()); + state.list_state.selected = Some(2); + + state.remove_profile("second"); + + assert_eq!(state.profiles, vec!["first"]); + assert_eq!(state.active_profile, None); + assert_eq!(state.list_state.selected, Some(1)); +} diff --git a/src/tui/widgets/popups/global_settings.rs b/src/tui/widgets/popups/global_settings.rs index 0566196..a5f49d2 100644 --- a/src/tui/widgets/popups/global_settings.rs +++ b/src/tui/widgets/popups/global_settings.rs @@ -75,10 +75,15 @@ impl State { } fn display_value(&self, field: usize) -> String { - if field == 4 && self.config.paths.java_path.is_none() { - "auto-detect".to_owned() - } else { - self.value(field) + match field { + 1 => match &self.theme.border_style { + BorderStyle::Rounded => "╭─╮ rounded".to_owned(), + BorderStyle::Plain => "┌─┐ plain".to_owned(), + BorderStyle::Double => "╔═╗ double".to_owned(), + BorderStyle::Thick => "┏━┓ thick".to_owned(), + }, + 4 if self.config.paths.java_path.is_none() => "auto-detect".to_owned(), + _ => self.value(field), } } @@ -146,13 +151,26 @@ impl State { } } - fn cycle_border(&mut self) { + fn cycle_theme(&mut self, forward: bool) { + let count = self.themes.len(); + if count == 0 { + return; + } + self.theme_index = if forward { + (self.theme_index + 1) % count + } else { + (self.theme_index + count - 1) % count + }; + self.select_theme(); + } + + fn cycle_border(&mut self, forward: bool) { let previous = self.theme.border_style.clone(); - self.theme.border_style = match self.theme.border_style { - BorderStyle::Rounded => BorderStyle::Plain, - BorderStyle::Plain => BorderStyle::Double, - BorderStyle::Double => BorderStyle::Thick, - BorderStyle::Thick => BorderStyle::Rounded, + self.theme.border_style = match (&self.theme.border_style, forward) { + (BorderStyle::Rounded, true) | (BorderStyle::Double, false) => BorderStyle::Plain, + (BorderStyle::Plain, true) | (BorderStyle::Thick, false) => BorderStyle::Double, + (BorderStyle::Double, true) | (BorderStyle::Rounded, false) => BorderStyle::Thick, + (BorderStyle::Thick, true) | (BorderStyle::Plain, false) => BorderStyle::Rounded, }; self.error = None; if let Err(error) = crate::config::theme::apply_theme( @@ -200,9 +218,19 @@ impl State { match key.code { KeyCode::Char('j') | KeyCode::Down => self.selected = (self.selected + 1).min(4), KeyCode::Char('k') | KeyCode::Up => self.selected = self.selected.saturating_sub(1), + KeyCode::Left => match self.selected { + 0 => self.cycle_theme(false), + 1 => self.cycle_border(false), + _ => {} + }, + KeyCode::Right => match self.selected { + 0 => self.cycle_theme(true), + 1 => self.cycle_border(true), + _ => {} + }, KeyCode::Enter => match self.selected { 0 => self.theme_picker = true, - 1 => self.cycle_border(), + 1 => self.cycle_border(true), field => self.editing = Some(new_text_area(vec![self.value(field)])), }, KeyCode::Char('s') => { @@ -301,6 +329,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &State) { super::keybind_line(&[ ("j/k", " field"), ("Enter", " edit"), + ("←/→", " switch"), ("s", " save"), ("E", " raw"), ("Esc", " back"), @@ -380,7 +409,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &State) { } else { state.display_value(index) }; - lines.push(Line::from(vec![ + let mut spans = vec![ Span::styled( if selected { "▸ " } else { " " }, Style::default().fg(theme.accent()), @@ -389,21 +418,41 @@ pub fn render(frame: &mut Frame, area: Rect, state: &State) { format!("{label:<20}"), Style::default().fg(theme.text_dim()), ), - Span::styled( - displayed, - Style::default() - .fg(if selected { - theme.accent() - } else { - theme.text() - }) - .add_modifier(if selected { - Modifier::BOLD - } else { - Modifier::empty() - }), - ), - ])); + ]; + let value_style = Style::default() + .fg(if selected { + theme.accent() + } else { + theme.text() + }) + .bg(theme.surface()) + .add_modifier(if selected { + Modifier::BOLD + } else { + Modifier::empty() + }); + if index <= 1 && state.editing.is_none() { + spans.push(Span::styled( + "‹ ", + Style::default().fg(if selected { + theme.accent() + } else { + theme.text_dim() + }), + )); + spans.push(Span::styled(format!(" {displayed} "), value_style)); + spans.push(Span::styled( + " ›", + Style::default().fg(if selected { + theme.accent() + } else { + theme.text_dim() + }), + )); + } else { + spans.push(Span::styled(format!(" {displayed} "), value_style)); + } + lines.push(Line::from(spans)); } if let Some(error) = &state.error { lines.push(Line::from(Span::styled( diff --git a/src/tui/widgets/popups/instance_settings.rs b/src/tui/widgets/popups/instance_settings.rs index d1205ee..82bcb0f 100644 --- a/src/tui/widgets/popups/instance_settings.rs +++ b/src/tui/widgets/popups/instance_settings.rs @@ -176,6 +176,8 @@ impl State { } 6 if self.draft.jvm_args.is_empty() => "none".to_owned(), 7 if self.draft.resolution.is_none() => "default".to_owned(), + 9 if self.desktop => "● enabled".to_owned(), + 9 => "○ disabled".to_owned(), _ => self.value(field).replace('\n', " ↵ "), } } @@ -225,38 +227,53 @@ impl State { let count = self.choice_values().len(); match key.code { KeyCode::Esc => self.choice_picker = None, - KeyCode::Char('j') | KeyCode::Down if count > 0 => { + KeyCode::Char('j') | KeyCode::Down | KeyCode::Right if count > 0 => { self.choice_index = (self.choice_index + 1).min(count - 1); } - KeyCode::Char('k') | KeyCode::Up => { + KeyCode::Char('k') | KeyCode::Up | KeyCode::Left => { self.choice_index = self.choice_index.saturating_sub(1); } - KeyCode::Enter => { - match self.choice_picker { - Some(ChoicePicker::Loader) => { - let available = loaders(); - let loader = available[self.choice_index.min(available.len() - 1)]; - if self.draft.loader != loader { - self.draft.loader = loader; - self.draft.loader_version = None; - self.loader_versions = Arc::new(Mutex::new(LoadState::Idle)); - self.game_versions = Arc::new(Mutex::new(LoadState::Idle)); - } - } - Some(ChoicePicker::Profile) => { - self.draft.config_sync_profile = self - .choice_index - .checked_sub(1) - .and_then(|index| self.profiles.get(index).cloned()); - } - None => {} - } - self.choice_picker = None; - } + KeyCode::Enter => self.apply_choice(), _ => {} } } + fn apply_choice(&mut self) { + match self.choice_picker { + Some(ChoicePicker::Loader) => { + let available = loaders(); + let loader = available[self.choice_index.min(available.len() - 1)]; + if self.draft.loader != loader { + self.draft.loader = loader; + self.draft.loader_version = None; + self.loader_versions = Arc::new(Mutex::new(LoadState::Idle)); + self.game_versions = Arc::new(Mutex::new(LoadState::Idle)); + } + } + Some(ChoicePicker::Profile) => { + self.draft.config_sync_profile = self + .choice_index + .checked_sub(1) + .and_then(|index| self.profiles.get(index).cloned()); + } + None => {} + } + self.choice_picker = None; + } + + fn rotate_choice(&mut self, picker: ChoicePicker, forward: bool) { + self.open_choice_picker(picker); + let count = self.choice_values().len(); + if count > 0 { + self.choice_index = if forward { + (self.choice_index + 1) % count + } else { + (self.choice_index + count - 1) % count + }; + self.apply_choice(); + } + } + fn open_game_picker(&mut self) { self.picker = Some(VersionPicker::Game); self.picker_index = 0; @@ -564,6 +581,18 @@ impl State { self.selected = (self.selected + 1).min(FIELD_COUNT - 1) } KeyCode::Char('k') | KeyCode::Up => self.selected = self.selected.saturating_sub(1), + KeyCode::Left => match self.selected { + 1 => self.rotate_choice(ChoicePicker::Loader, false), + 8 => self.rotate_choice(ChoicePicker::Profile, false), + 9 => self.desktop = !self.desktop, + _ => {} + }, + KeyCode::Right => match self.selected { + 1 => self.rotate_choice(ChoicePicker::Loader, true), + 8 => self.rotate_choice(ChoicePicker::Profile, true), + 9 => self.desktop = !self.desktop, + _ => {} + }, KeyCode::Enter => self.begin_edit(), KeyCode::Char('a') if self.selected == 8 => { self.profile_input = Some(new_text_area(vec![String::new()])); @@ -683,6 +712,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &State) { super::keybind_line(&[ ("j/k", " field"), ("Enter", " edit"), + ("←/→", " switch"), ("s", " save"), ("E", " raw"), ("Esc", " back"), @@ -730,27 +760,49 @@ pub fn render(frame: &mut Frame, area: Rect, state: &State) { } else { state.display_value(index) }; - lines.push(Line::from(vec![ + let mut spans = vec![ Span::styled(marker, Style::default().fg(theme.accent())), Span::styled( format!("{label:<18}"), Style::default().fg(theme.text_dim()), ), - Span::styled( - displayed, - Style::default() - .fg(if selected { - theme.accent() - } else { - theme.text() - }) - .add_modifier(if selected { - Modifier::BOLD - } else { - Modifier::empty() - }), - ), - ])); + ]; + let value_style = Style::default() + .fg(if index == 9 && state.desktop { + theme.success() + } else if selected { + theme.accent() + } else { + theme.text() + }) + .bg(theme.surface()) + .add_modifier(if selected { + Modifier::BOLD + } else { + Modifier::empty() + }); + if matches!(index, 1 | 8 | 9) && state.editing.is_none() && state.profile_input.is_none() { + spans.push(Span::styled( + "‹ ", + Style::default().fg(if selected { + theme.accent() + } else { + theme.text_dim() + }), + )); + spans.push(Span::styled(format!(" {displayed} "), value_style)); + spans.push(Span::styled( + " ›", + Style::default().fg(if selected { + theme.accent() + } else { + theme.text_dim() + }), + )); + } else { + spans.push(Span::styled(format!(" {displayed} "), value_style)); + } + lines.push(Line::from(spans)); } if state.confirm_profile_delete { lines.push(Line::from(Span::styled( @@ -1087,4 +1139,21 @@ mod tests { assert_eq!(state.draft.loader_version, None); assert!(!state.validate_before_save()); } + + #[test] + fn arrow_keys_rotate_badged_choices() { + let temp = tempfile::tempdir().unwrap(); + let mut state = State::new(&instance(), temp.path()); + + state.selected = 1; + state.handle_key(&KeyEvent::from(KeyCode::Right)); + assert_eq!(state.draft.loader, ModLoader::Forge); + state.handle_key(&KeyEvent::from(KeyCode::Left)); + assert_eq!(state.draft.loader, ModLoader::Fabric); + + state.selected = 9; + let desktop = state.desktop; + state.handle_key(&KeyEvent::from(KeyCode::Right)); + assert_ne!(state.desktop, desktop); + } } diff --git a/src/tui/widgets/settings.rs b/src/tui/widgets/settings.rs index 26bb397..a401894 100644 --- a/src/tui/widgets/settings.rs +++ b/src/tui/widgets/settings.rs @@ -1,8 +1,20 @@ // SPDX-FileCopyrightText: 2026 Constantin Bauer // SPDX-License-Identifier: GPL-3.0-only -// compact, read-only summary of the selected instance. editing lives in the -// instance and launcher settings popups. +// settings panel: manages config profiles and shows compact instance info. +// detailed instance and launcher configuration opens in the TUI popups. + +use std::{path::PathBuf, process::Command}; + +use crossterm::event::{KeyCode, KeyEvent}; +use ratatui::{ + Frame, + layout::{Constraint, Direction, Layout, Rect}, + style::{Modifier, Style}, + text::{Line, Span}, + widgets::{Block, Borders, Paragraph, Widget}, +}; +use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView}; use crate::config::{ SETTINGS, @@ -10,24 +22,192 @@ use crate::config::{ }; use crate::instance::models::InstanceConfig; use crate::tui::app::FocusedArea; -use ratatui::{ - Frame, - layout::Rect, - style::{Modifier, Style}, - text::{Line, Span}, - widgets::{Block, Borders, Paragraph}, -}; use super::styled_title; const LOCAL_PROFILE_LABEL: &str = "instance default"; +#[derive(Default)] +pub enum AddMode { + #[default] + None, + ProfileName(String), +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum SettingsPane { + #[default] + Profile, + Info, +} + +pub struct SettingsState { + pub list_state: TuiListState, + pub profiles: Vec, + pub add_mode: AddMode, + pub pane: SettingsPane, + meta_dir: PathBuf, + active_profile: Option, + instance_name: Option, + java_key: Option, + java_source: Option, + java_label: String, +} + +impl SettingsState { + pub fn new(meta_dir: PathBuf) -> Self { + let profiles = crate::instance::config_sync::list_profiles(&meta_dir).unwrap_or_else(|e| { + tracing::warn!("Failed to load config sync profiles: {}", e); + Vec::new() + }); + let mut state = Self { + list_state: TuiListState::default(), + profiles, + add_mode: AddMode::None, + pane: SettingsPane::Profile, + meta_dir, + active_profile: None, + instance_name: None, + java_key: None, + java_source: None, + java_label: "unknown".to_string(), + }; + state.select_active(); + state + } + + fn reload_profiles(&mut self) { + match crate::instance::config_sync::list_profiles(&self.meta_dir) { + Ok(mut profiles) => { + add_active_profile(&mut profiles, self.active_profile.as_deref()); + self.profiles = profiles; + } + Err(e) => tracing::warn!("Failed to reload config sync profiles: {}", e), + } + } + + fn select_active(&mut self) { + self.list_state.selected = Some( + self.active_profile + .as_deref() + .and_then(|active| self.profiles.iter().position(|profile| profile == active)) + .map(|idx| idx + 1) + .unwrap_or(0), + ); + } + + fn count(&self) -> usize { + self.profiles.len() + 1 + } + + pub fn remove_profile(&mut self, profile: &str) { + self.profiles.retain(|candidate| candidate != profile); + if self.active_profile.as_deref() == Some(profile) { + self.active_profile = None; + } + let last = self.count().saturating_sub(1); + self.list_state.selected = Some(self.list_state.selected.unwrap_or(0).min(last)); + } + + fn update_for_instance(&mut self, instance: Option<&InstanceConfig>) { + let instance_name = instance.map(|inst| inst.name.clone()); + let active_profile = instance.and_then(|inst| inst.config_sync_profile.clone()); + let active_profile = active_profile + .filter(|profile| self.profiles.iter().any(|candidate| candidate == profile)); + if self.instance_name != instance_name || self.active_profile != active_profile { + self.instance_name = instance_name; + self.active_profile = active_profile; + add_active_profile(&mut self.profiles, self.active_profile.as_deref()); + self.select_active(); + } + + let java_key = instance.map(java_path_key); + if self.java_key != java_key { + let java_source = instance.map(effective_java_path); + self.java_label = java_source + .as_deref() + .map(java_version_label) + .unwrap_or_else(|| "unknown".to_string()); + self.java_key = java_key; + self.java_source = java_source; + } + } +} + +fn add_active_profile(profiles: &mut Vec, active_profile: Option<&str>) { + if let Some(active) = active_profile + && !profiles.iter().any(|profile| profile == active) + { + profiles.push(active.to_string()); + profiles.sort_unstable(); + } +} + +fn java_path_key(instance: &InstanceConfig) -> String { + instance + .java_path + .as_deref() + .filter(|path| !path.is_empty()) + .map(str::to_owned) + .or_else(|| { + SETTINGS + .read() + .paths + .effective_java_path() + .map(str::to_owned) + }) + .unwrap_or_else(|| "".to_owned()) +} + +fn effective_java_path(instance: &InstanceConfig) -> String { + instance + .java_path + .clone() + .or_else(|| { + SETTINGS + .read() + .paths + .effective_java_path() + .map(str::to_owned) + }) + .unwrap_or_else(crate::instance::java::detect_java_path) +} + +fn java_version_label(java_path: &str) -> String { + let output = Command::new(java_path).arg("-version").output(); + let Ok(output) = output else { + return "unknown".to_string(); + }; + let raw = String::from_utf8_lossy(if output.stderr.is_empty() { + &output.stdout + } else { + &output.stderr + }); + let first_line = raw.lines().next().unwrap_or_default(); + let Some(version) = first_line.split('"').nth(1) else { + return "unknown".to_string(); + }; + let major = if let Some(stripped) = version.strip_prefix("1.") { + stripped.split('.').next().unwrap_or(stripped) + } else { + version.split('.').next().unwrap_or(version) + }; + if major.is_empty() { + "unknown".to_string() + } else { + format!("jdk{major}") + } +} + pub fn render( frame: &mut Frame, area: Rect, focused: FocusedArea, + state: &mut SettingsState, instance: Option<&InstanceConfig>, ) { + state.update_for_instance(instance); + let theme = THEME.as_ref(); let color = if focused == FocusedArea::Settings { theme.accent() @@ -42,7 +222,23 @@ pub fn render( .border_style(Style::default().fg(color)); let keybind_line = if focused == FocusedArea::Settings { - let keybinds: &[(&str, &str)] = &[("E", " instance"), ("G", " launcher"), ("Esc", " back")]; + let keybinds: &[(&str, &str)] = match state.pane { + SettingsPane::Profile => &[ + ("⏎", " select"), + ("a", " add"), + ("d", " del"), + ("j/k", " move"), + ("h/l", " tab"), + ("Esc", " back"), + ], + SettingsPane::Info => &[ + ("e", " instance"), + ("g", " launcher"), + ("d", " desk"), + ("h/l", " tab"), + ("Esc", " back"), + ], + }; Some(super::popups::keybind_line_fitted( keybinds, area.width.saturating_sub(2), @@ -57,10 +253,55 @@ pub fn render( let inner = block.inner(area); frame.render_widget(block, area); - render_instance_info(frame, inner, instance); + if instance.is_none() { + frame.render_widget( + Paragraph::new("No instance selected.") + .style(Style::default().fg(THEME.as_ref().text_dim())), + inner, + ); + } else if inner.width >= 42 { + let chunks = Layout::default() + .direction(Direction::Horizontal) + .constraints([ + Constraint::Percentage(50), + Constraint::Length(3), + Constraint::Percentage(50), + ]) + .split(inner); + render_profile_list(frame, chunks[0], focused, state); + render_separator(frame, chunks[1], focused, state.pane); + render_instance_info(frame, chunks[2], focused, state, instance); + } else { + render_profile_list(frame, inner, focused, state); + } + + if let AddMode::ProfileName(name) = &state.add_mode { + render_add_profile_popup(frame, name); + } } -fn render_instance_info(frame: &mut Frame, area: Rect, instance: Option<&InstanceConfig>) { +fn render_separator(frame: &mut Frame, area: Rect, focused: FocusedArea, pane: SettingsPane) { + let theme = THEME.as_ref(); + let color = if focused == FocusedArea::Settings && pane == SettingsPane::Info { + theme.accent() + } else { + theme.border() + }; + let line = if area.width >= 3 { + " │ \n".repeat(area.height as usize) + } else { + "│\n".repeat(area.height as usize) + }; + frame.render_widget(Paragraph::new(line).style(Style::default().fg(color)), area); +} + +fn render_instance_info( + frame: &mut Frame, + area: Rect, + focused: FocusedArea, + state: &SettingsState, + instance: Option<&InstanceConfig>, +) { let theme = THEME.as_ref(); let label_style = Style::default().fg(theme.text_dim()); let value_style = Style::default() @@ -84,50 +325,265 @@ fn render_instance_info(frame: &mut Frame, area: Rect, instance: Option<&Instanc .memory_max .as_deref() .unwrap_or(&settings.defaults.memory_max); - let active_style = value_style; + let active_style = if focused == FocusedArea::Settings && state.pane == SettingsPane::Info { + value_style.fg(theme.accent()) + } else { + value_style + }; let desktop = if crate::instance::desktop::exists(&inst.name) { "yes" } else { "no" }; - let java_source = if inst - .java_path - .as_deref() - .is_some_and(|path| !path.is_empty()) - { - "instance java" - } else if settings.paths.effective_java_path().is_some() { - "global java" - } else { - "auto java" - }; let lines = vec![ Line::from(vec![ - Span::styled("Version ", label_style), - Span::styled( - format!("{} / {}", inst.game_version, inst.loader), - active_style, - ), + Span::styled("Memory ", label_style), + Span::styled(format!("{memory_min} - {memory_max}"), active_style), ]), Line::from(vec![ - Span::styled("Runtime ", label_style), - Span::styled( - format!("{memory_min}-{memory_max}, {java_source}"), - active_style, - ), + Span::styled("Java ", label_style), + Span::styled(state.java_label.as_str(), active_style), ]), Line::from(vec![ - Span::styled("Profile ", label_style), - Span::styled( - inst.config_sync_profile - .as_deref() - .unwrap_or(LOCAL_PROFILE_LABEL), - active_style, - ), - Span::styled(" / desk ", label_style), + Span::styled("Desktop ", label_style), Span::styled(desktop, active_style), ]), ]; frame.render_widget(Paragraph::new(lines), area); } + +fn render_profile_list( + frame: &mut Frame, + area: Rect, + focused: FocusedArea, + state: &mut SettingsState, +) { + let is_focused = focused == FocusedArea::Settings; + let pane = state.pane; + let active_profile = state.active_profile.clone(); + let profiles = state.profiles.clone(); + let count = profiles.len() + 1; + let last = count.saturating_sub(1); + state.list_state.selected = Some(state.list_state.selected.unwrap_or(0).min(last)); + + let builder = ListBuilder::new(move |context| { + let theme = THEME.as_ref(); + let name = if context.index == 0 { + LOCAL_PROFILE_LABEL.to_string() + } else { + profiles.get(context.index - 1).cloned().unwrap_or_default() + }; + let is_active = if context.index == 0 { + active_profile.is_none() + } else { + active_profile.as_deref() == Some(name.as_str()) + }; + let show_selected = is_focused && pane == SettingsPane::Profile && context.is_selected; + let marker = if is_active { "\u{25b8} " } else { " " }; + let background = if show_selected { + theme.stripe() + } else { + theme.background() + }; + let style = if show_selected { + Style::default() + .fg(theme.accent()) + .add_modifier(Modifier::BOLD) + } else if is_active { + Style::default() + .fg(theme.text()) + .add_modifier(Modifier::BOLD) + } else { + Style::default().fg(theme.text()) + }; + let line = Line::from(vec![ + Span::styled(marker, Style::default().fg(theme.success())), + Span::styled(name, style), + ]); + ( + ratatui::text::Text::from(line).style(Style::default().bg(background)), + 1, + ) + }); + + frame.render_stateful_widget(ListView::new(builder, count), area, &mut state.list_state); +} + +fn render_add_profile_popup(frame: &mut Frame, name: &str) { + use super::popups::{base::PopupFrame, keybind_line}; + let theme = THEME.as_ref(); + let area = popup_area(frame, 42, 5); + let name = name.to_string(); + + let border_color = theme.text_dim(); + let bg_color = theme.surface(); + let dim_color = theme.text_dim(); + let text_color = theme.text(); + + PopupFrame { + title: Line::from(Span::styled( + " Config Profile ", + Style::default() + .fg(border_color) + .add_modifier(Modifier::BOLD), + )) + .centered(), + border_color, + bg: Some(bg_color), + keybinds: Some(keybind_line(&[("Enter", " create"), ("Esc", " cancel")])), + search_line: None, + content: Box::new(move |inner, buf| { + let line = if name.is_empty() { + Line::from(vec![ + Span::styled("Profile name...", Style::default().fg(dim_color)), + Span::styled( + "\u{2588}", + Style::default() + .fg(border_color) + .add_modifier(Modifier::SLOW_BLINK), + ), + ]) + } else { + Line::from(vec![ + Span::styled(name.as_str(), Style::default().fg(text_color)), + Span::styled( + "\u{2588}", + Style::default() + .fg(border_color) + .add_modifier(Modifier::SLOW_BLINK), + ), + ]) + }; + Paragraph::new(line).render(inner, buf); + }), + } + .render(area, frame.buffer_mut()); +} + +fn popup_area(frame: &Frame, width: u16, height: u16) -> Rect { + let area = frame.area(); + let x = area.x + (area.width.saturating_sub(width)) / 2; + let y = area.y + (area.height.saturating_sub(height)) / 2; + Rect { + x, + y, + width: width.min(area.width), + height: height.min(area.height), + } +} + +pub enum SettingsAction { + None, + OpenInstance, + OpenGlobal, + ToggleDesktop, + SelectProfile(Option), + ConfirmDeleteProfile(String), + Error(String), +} + +pub fn handle_key( + key_event: &KeyEvent, + state: &mut SettingsState, + instance: Option<&InstanceConfig>, +) -> SettingsAction { + if let AddMode::ProfileName(name) = &state.add_mode { + match key_event.code { + KeyCode::Enter => { + let name = name.trim().to_string(); + state.add_mode = AddMode::None; + if name.is_empty() { + return SettingsAction::None; + } + return match crate::instance::config_sync::create_profile(&state.meta_dir, &name) { + Ok(profile) => { + state.reload_profiles(); + state.active_profile = Some(profile); + state.select_active(); + SettingsAction::SelectProfile(state.active_profile.clone()) + } + Err(e) => SettingsAction::Error(e.to_string()), + }; + } + KeyCode::Esc => { + state.add_mode = AddMode::None; + return SettingsAction::None; + } + KeyCode::Backspace => { + let mut new_name = name.clone(); + super::search::backspace(&mut new_name, key_event.modifiers); + state.add_mode = AddMode::ProfileName(new_name); + return SettingsAction::None; + } + KeyCode::Char(c) => { + let mut new_name = name.clone(); + new_name.push(c); + state.add_mode = AddMode::ProfileName(new_name); + return SettingsAction::None; + } + _ => return SettingsAction::None, + } + } + + match key_event.code { + KeyCode::Char('h') | KeyCode::Left => { + state.pane = SettingsPane::Profile; + SettingsAction::None + } + KeyCode::Char('l') | KeyCode::Right => { + state.pane = SettingsPane::Info; + SettingsAction::None + } + KeyCode::Enter if state.pane == SettingsPane::Profile => { + let selected = state.list_state.selected.unwrap_or(0); + let profile = if selected == 0 { + None + } else { + state.profiles.get(selected - 1).cloned() + }; + SettingsAction::SelectProfile(profile) + } + KeyCode::Char('a') if state.pane == SettingsPane::Profile => { + state.add_mode = AddMode::ProfileName(String::new()); + SettingsAction::None + } + KeyCode::Char('d') if state.pane == SettingsPane::Profile => { + let selected = state.list_state.selected.unwrap_or(0); + if selected == 0 { + SettingsAction::None + } else if let Some(profile) = state.profiles.get(selected - 1) { + SettingsAction::ConfirmDeleteProfile(profile.clone()) + } else { + SettingsAction::None + } + } + KeyCode::Char('j') | KeyCode::Down if state.pane == SettingsPane::Profile => { + let count = state.count(); + if count > 0 { + let cur = state.list_state.selected.unwrap_or(0); + state.list_state.selected = Some((cur + 1).min(count - 1)); + } + SettingsAction::None + } + KeyCode::Char('k') | KeyCode::Up if state.pane == SettingsPane::Profile => { + let cur = state.list_state.selected.unwrap_or(0); + state.list_state.selected = Some(cur.saturating_sub(1)); + SettingsAction::None + } + KeyCode::Char('e') if state.pane == SettingsPane::Info => { + if instance.is_some() { + SettingsAction::OpenInstance + } else { + SettingsAction::None + } + } + KeyCode::Char('g') if state.pane == SettingsPane::Info => SettingsAction::OpenGlobal, + KeyCode::Char('d') if state.pane == SettingsPane::Info => SettingsAction::ToggleDesktop, + _ => SettingsAction::None, + } +} + +#[cfg(test)] +#[path = "../tests/widgets/settings.rs"] +mod tests;