From 6ff8ae64d5e05e306cd94492ba2b56936e5422dc Mon Sep 17 00:00:00 2001 From: objz Date: Sat, 9 Aug 2025 14:52:44 +0200 Subject: [PATCH] refactor: merge theme into config, remove dead code --- src/config/mod.rs | 1 + src/config/types.rs | 112 ++++++++++++++++++++++++- src/instance/loader.rs | 4 +- src/instance/mod.rs | 2 +- src/instance/models.rs | 9 -- src/tui/error_buffer.rs | 3 + src/tui/layout.rs | 50 +---------- src/tui/theme.rs | 141 +------------------------------- src/tui/widgets/popups/error.rs | 8 +- src/tui/widgets/profiles.rs | 6 +- 10 files changed, 128 insertions(+), 208 deletions(-) diff --git a/src/config/mod.rs b/src/config/mod.rs index 7dc18b6..627199d 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -90,6 +90,7 @@ pub static SETTINGS: Lazy = Lazy::new(|| { general: types::General::default(), paths: types::Paths::default(), defaults: types::Defaults::default(), + colors: types::Colors::default(), } } } diff --git a/src/config/types.rs b/src/config/types.rs index 9ed0420..8a168ee 100644 --- a/src/config/types.rs +++ b/src/config/types.rs @@ -1,4 +1,6 @@ -use serde::Deserialize; +use dirs_next; +use ratatui::style::Color; +use serde::{Deserialize, Deserializer}; #[derive(Debug, Deserialize)] pub struct General { @@ -32,6 +34,25 @@ impl Default for Paths { } } +impl Paths { + pub fn resolve_instances_dir(&self) -> std::path::PathBuf { + let raw = &self.instances_dir; + if let Some(stripped) = raw.strip_prefix("~/") { + return match dirs_next::home_dir() { + Some(home) => home.join(stripped), + None => std::path::PathBuf::from(raw), + }; + } + if raw == "~" { + return match dirs_next::home_dir() { + Some(home) => home, + None => std::path::PathBuf::from(raw), + }; + } + std::path::PathBuf::from(raw) + } +} + #[derive(Debug, Deserialize)] pub struct Defaults { #[serde(default = "default_memory_min")] @@ -57,6 +78,93 @@ impl Default for Defaults { } } +#[derive(Debug, Deserialize, Clone)] +pub struct Colors { + #[serde(deserialize_with = "deserialize_color")] + pub background: Color, + #[serde(deserialize_with = "deserialize_color")] + pub foreground: Color, + #[serde(deserialize_with = "deserialize_color")] + pub border_focused: Color, + #[serde(deserialize_with = "deserialize_color")] + pub border_unfocused: Color, + #[serde(deserialize_with = "deserialize_color")] + pub row_highlight: Color, + #[serde(deserialize_with = "deserialize_color")] + pub row_background: Color, + #[serde(deserialize_with = "deserialize_color")] + pub row_alternate_bg: Color, +} + +impl Default for Colors { + fn default() -> Self { + Colors { + background: Color::Reset, + foreground: Color::White, + border_focused: Color::White, + border_unfocused: Color::DarkGray, + row_highlight: Color::White, + row_background: Color::Reset, + row_alternate_bg: Color::Reset, + } + } +} + +pub fn parse_color(color: &str) -> Color { + match color.to_lowercase().as_str() { + "black" => Color::Black, + "red" => Color::Red, + "green" => Color::Green, + "yellow" => Color::Yellow, + "blue" => Color::Blue, + "magenta" => Color::Magenta, + "cyan" => Color::Cyan, + "white" => Color::White, + "gray" | "grey" => Color::Gray, + "darkgray" | "darkgrey" => Color::DarkGray, + "lightred" => Color::LightRed, + "lightgreen" => Color::LightGreen, + "lightyellow" => Color::LightYellow, + "lightblue" => Color::LightBlue, + "lightmagenta" => Color::LightMagenta, + "lightcyan" => Color::LightCyan, + "reset" => Color::Reset, + hex if hex.starts_with('#') && hex.len() == 7 => { + let r = u8::from_str_radix(&hex[1..3], 16).unwrap_or_else(|_| { + tracing::warn!("Invalid hex color: {}", color); + 255 + }); + let g = u8::from_str_radix(&hex[3..5], 16).unwrap_or_else(|_| { + tracing::warn!("Invalid hex color: {}", color); + 255 + }); + let b = u8::from_str_radix(&hex[5..7], 16).unwrap_or_else(|_| { + tracing::warn!("Invalid hex color: {}", color); + 255 + }); + Color::Rgb(r, g, b) + } + _ => { + tracing::warn!("Unknown color '{}', using White as fallback", color); + Color::White + } + } +} + +fn deserialize_color<'de, D>(deserializer: D) -> Result +where + D: Deserializer<'de>, +{ + let color_str: String = match Deserialize::deserialize(deserializer) { + Ok(s) => s, + Err(e) => { + tracing::warn!("Failed to deserialize color field: {}", e); + return Ok(Color::White); + } + }; + Ok(parse_color(&color_str)) +} + #[derive(Debug, Deserialize)] pub struct Config { #[serde(default)] @@ -65,4 +173,6 @@ pub struct Config { pub paths: Paths, #[serde(default)] pub defaults: Defaults, + #[serde(default)] + pub colors: Colors, } diff --git a/src/instance/loader.rs b/src/instance/loader.rs index 830b043..9455f59 100644 --- a/src/instance/loader.rs +++ b/src/instance/loader.rs @@ -151,7 +151,7 @@ impl ModLoaderInstaller for ForgeInstaller { } } - let java_path = forge::detect_java_path(); + let java_path = crate::net::detect_java_path(); match forge::run_forge_installer(&installer_jar, instance_dir, &java_path).await { Ok(()) => {} Err(e) => { @@ -262,7 +262,7 @@ impl ModLoaderInstaller for NeoForgeInstaller { } } - let java_path = neoforge::detect_java_path(); + let java_path = crate::net::detect_java_path(); match neoforge::run_neoforge_installer(&installer_jar, instance_dir, &java_path).await { Ok(()) => {} Err(e) => { diff --git a/src/instance/mod.rs b/src/instance/mod.rs index 2785e23..5d0eb74 100644 --- a/src/instance/mod.rs +++ b/src/instance/mod.rs @@ -4,4 +4,4 @@ pub mod models; pub use manager::{InstanceError, InstanceManager}; pub use loader::{get_installer, ModLoaderInstaller, VanillaInstaller}; -pub use models::{InstanceConfig, InstanceState, ModLoader}; +pub use models::{InstanceConfig, ModLoader}; diff --git a/src/instance/models.rs b/src/instance/models.rs index 339ac32..0f304aa 100644 --- a/src/instance/models.rs +++ b/src/instance/models.rs @@ -39,15 +39,6 @@ pub struct InstanceConfig { pub resolution: Option<(u32, u32)>, } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum InstanceState { - Ready, - Downloading, - Running, - Error(String), -} - #[cfg(test)] mod tests { use super::*; diff --git a/src/tui/error_buffer.rs b/src/tui/error_buffer.rs index 94aabc7..c1f85b7 100644 --- a/src/tui/error_buffer.rs +++ b/src/tui/error_buffer.rs @@ -5,6 +5,9 @@ use std::time::Instant; use once_cell::sync::Lazy; use tracing::Level; +pub const AUTO_DISMISS_MS: u128 = 5000; +pub const SLIDE_START_MS: u128 = 3500; + const MAX_ERROR_EVENTS: usize = 50; #[derive(Debug, Clone)] diff --git a/src/tui/layout.rs b/src/tui/layout.rs index 5ebd29c..2f14b65 100644 --- a/src/tui/layout.rs +++ b/src/tui/layout.rs @@ -17,7 +17,6 @@ use ratatui::{ layout::{Constraint, Direction, Layout}, Frame, }; -use std::path::PathBuf; use std::sync::{Arc, Mutex}; use std::time::Duration; @@ -48,7 +47,7 @@ pub enum FocusedArea { impl Default for App { fn default() -> Self { - let instances_dir = resolve_instances_dir(); + let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir(); match std::fs::create_dir_all(&instances_dir) { Ok(_) => {} @@ -287,11 +286,9 @@ impl App { } fn dismiss_expired_errors(&self) { - const DISMISS_MS: u128 = 5000; - loop { match error_buffer::peek_error() { - Some(event) if event.pushed_at.elapsed().as_millis() >= DISMISS_MS => { + Some(event) if event.pushed_at.elapsed().as_millis() >= error_buffer::AUTO_DISMISS_MS => { error_buffer::pop_error(); } _ => break, @@ -340,29 +337,8 @@ impl App { .add_modifier(Modifier::BOLD), )])) .title_bottom( - Line::from(vec![ - Span::styled( - "[S]", - Style::default() - .fg(THEME.colors.border_focused) - .add_modifier(Modifier::BOLD), - ), - Span::styled( - "/", - Style::default().fg(THEME.colors.border_unfocused), - ), - Span::styled( - "[Esc]", - Style::default() - .fg(THEME.colors.border_focused) - .add_modifier(Modifier::BOLD), - ), - Span::styled( - " close ", - Style::default().fg(THEME.colors.border_unfocused), - ), - ]) - .alignment(Alignment::Right), + crate::tui::widgets::popups::keybind_line(&[("S", " close"), ("Esc", " close")]) + .alignment(Alignment::Right) ) .borders(Borders::ALL) .border_type(BorderType::Rounded) @@ -400,22 +376,4 @@ impl App { } } -fn resolve_instances_dir() -> PathBuf { - let raw_dir = &crate::config::SETTINGS.paths.instances_dir; - if raw_dir == "~" { - return match dirs_next::home_dir() { - Some(home) => home, - None => PathBuf::from(raw_dir), - }; - } - - if let Some(stripped) = raw_dir.strip_prefix("~/") { - return match dirs_next::home_dir() { - Some(home) => home.join(stripped), - None => PathBuf::from(raw_dir), - }; - } - - PathBuf::from(raw_dir) -} diff --git a/src/tui/theme.rs b/src/tui/theme.rs index b47ac5a..98db45e 100644 --- a/src/tui/theme.rs +++ b/src/tui/theme.rs @@ -1,139 +1,2 @@ -use config::{Config as ConfigLoader, File}; -use once_cell::sync::Lazy; -use ratatui::style::Color; -use serde::{Deserialize, Deserializer}; - -use crate::config::get_config_path; - -#[derive(Debug, Deserialize)] -pub struct ThemeConfig { - pub colors: Colors, -} - -#[derive(Debug, Deserialize)] -pub struct Colors { - #[serde(deserialize_with = "deserialize_color")] - pub background: Color, - - #[serde(deserialize_with = "deserialize_color")] - pub foreground: Color, - - #[serde(deserialize_with = "deserialize_color")] - pub border_focused: Color, - - #[serde(deserialize_with = "deserialize_color")] - pub border_unfocused: Color, - - #[serde(deserialize_with = "deserialize_color")] - pub row_highlight: Color, - - #[serde(deserialize_with = "deserialize_color")] - pub row_background: Color, - - #[serde(deserialize_with = "deserialize_color")] - pub row_alternate_bg: Color, -} - -pub fn parse_color(color: &str) -> Color { - match color.to_lowercase().as_str() { - "black" => Color::Black, - "red" => Color::Red, - "green" => Color::Green, - "yellow" => Color::Yellow, - "blue" => Color::Blue, - "magenta" => Color::Magenta, - "cyan" => Color::Cyan, - "white" => Color::White, - "gray" | "grey" => Color::Gray, - "darkgray" | "darkgrey" => Color::DarkGray, - "lightred" => Color::LightRed, - "lightgreen" => Color::LightGreen, - "lightyellow" => Color::LightYellow, - "lightblue" => Color::LightBlue, - "lightmagenta" => Color::LightMagenta, - "lightcyan" => Color::LightCyan, - "reset" => Color::Reset, - hex if hex.starts_with('#') && hex.len() == 7 => { - let r = u8::from_str_radix(&hex[1..3], 16).unwrap_or_else(|_| { - tracing::warn!("Invalid hex color format: {}", color); - 255 - }); - let g = u8::from_str_radix(&hex[3..5], 16).unwrap_or_else(|_| { - tracing::warn!("Invalid hex color format: {}", color); - 255 - }); - let b = u8::from_str_radix(&hex[5..7], 16).unwrap_or_else(|_| { - tracing::warn!("Invalid hex color format: {}", color); - 255 - }); - Color::Rgb(r, g, b) - } - _ => { - tracing::warn!("Unknown color '{}', using White as fallback", color); - Color::White - } - } -} - -fn deserialize_color<'de, D>(deserializer: D) -> Result -where - D: Deserializer<'de>, -{ - let color_str: String = match Deserialize::deserialize(deserializer) { - Ok(s) => s, - Err(e) => { - tracing::warn!("Failed to deserialize color field: {}", e); - return Ok(Color::White); - } - }; - Ok(parse_color(&color_str)) -} - -impl Default for Colors { - fn default() -> Self { - Colors { - background: Color::Reset, - foreground: Color::White, - border_focused: Color::White, - border_unfocused: Color::DarkGray, - row_highlight: Color::White, - row_background: Color::Reset, - row_alternate_bg: Color::Reset, - } - } -} - -impl Default for ThemeConfig { - fn default() -> Self { - ThemeConfig { - colors: Colors::default(), - } - } -} - -pub static THEME: Lazy = Lazy::new(|| { - let config_path = get_config_path().join("config.toml"); - - let built = match ConfigLoader::builder() - .add_source(File::from(config_path.clone()).required(false)) - .build() - { - Ok(c) => c, - Err(e) => { - tracing::warn!( - "Failed to load theme config from '{}': {}. Using default colors.", - config_path.display(), - e - ); - return ThemeConfig::default(); - } - }; - - match built.try_deserialize::() { - Ok(theme) => theme, - Err(e) => { - tracing::warn!("Failed to parse theme config: {}. Using default colors.", e); - ThemeConfig::default() - } - } -}); +pub use crate::config::types::{parse_color, Colors}; +pub use crate::config::SETTINGS as THEME; diff --git a/src/tui/widgets/popups/error.rs b/src/tui/widgets/popups/error.rs index 5cbdac2..52cf452 100644 --- a/src/tui/widgets/popups/error.rs +++ b/src/tui/widgets/popups/error.rs @@ -8,7 +8,7 @@ use ratatui::{ use tracing::Level; use super::base::PopupFrame; -use crate::tui::error_buffer::ErrorEvent; +use crate::tui::error_buffer::{ErrorEvent, AUTO_DISMISS_MS, SLIDE_START_MS}; use crate::tui::theme::THEME; pub struct ErrorPopup { @@ -60,10 +60,8 @@ pub fn popup_area(frame_area: Rect, message: &str, base_y: u16, elapsed_ms: u128 const MAX_W: usize = 58; const MIN_W: usize = 22; - const SLIDE_START_MS: u128 = 3500; - const DISMISS_MS: u128 = 5000; - if elapsed_ms >= DISMISS_MS { + if elapsed_ms >= AUTO_DISMISS_MS { return None; } @@ -85,7 +83,7 @@ pub fn popup_area(frame_area: Rect, message: &str, base_y: u16, elapsed_ms: u128 }); } - let progress = (elapsed_ms - SLIDE_START_MS) as f32 / (DISMISS_MS - SLIDE_START_MS) as f32; + let progress = (elapsed_ms - SLIDE_START_MS) as f32 / (AUTO_DISMISS_MS - SLIDE_START_MS) as f32; let slide = (progress * popup_w as f32) as u16; let new_x = base_x.saturating_add(slide); diff --git a/src/tui/widgets/profiles.rs b/src/tui/widgets/profiles.rs index 8b5fd5e..d2ccccb 100644 --- a/src/tui/widgets/profiles.rs +++ b/src/tui/widgets/profiles.rs @@ -10,7 +10,7 @@ use ratatui::{ Frame, }; -use crate::instance::models::{InstanceConfig, InstanceState}; +use crate::instance::models::InstanceConfig; use crate::tui::{layout::FocusedArea, theme::THEME}; use super::{popups, styled_title, WidgetKey}; @@ -18,7 +18,6 @@ use super::{popups, styled_title, WidgetKey}; #[derive(Debug, Default)] pub struct State { pub instances: Vec, - pub instance_states: Vec, pub list_state: ListState, pub scrollbar_state: ScrollbarState, pub show_popup: bool, @@ -31,7 +30,6 @@ impl State { let count = instances.len(); let mut s = State { instances, - instance_states: vec![InstanceState::Ready; count], list_state: ListState::default(), scrollbar_state: ScrollbarState::default(), show_popup: false, @@ -131,14 +129,12 @@ impl State { self.instances.retain(|i| i.name != name); let after = self.instances.len(); if after < before { - self.instance_states.truncate(after); self.update_scrollbar(); } } pub fn add_instance(&mut self, instance: InstanceConfig) { self.instances.push(instance); - self.instance_states.push(InstanceState::Ready); self.update_scrollbar(); } }