refactor: extract cli and config into separate modules
This commit is contained in:
1 parent
03c87a8df0
commit
159b21d39a
17 files changed
+479
-2436
No files matched your search
+8
-20
@@ -1,8 +1,8 @@
|
||||
use super::widgets::popups::new_instance;
|
||||
use super::{
|
||||
widgets::{self, profiles, WidgetKey},
|
||||
Tui,
|
||||
};
|
||||
use super::widgets::popups::new_instance;
|
||||
use color_eyre::eyre::Context;
|
||||
use crossterm::event::{self, Event};
|
||||
use ratatui::{
|
||||
@@ -18,8 +18,9 @@ pub struct App {
|
||||
profiles_state: profiles::State,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq)]
|
||||
pub enum FocusedArea {
|
||||
#[default]
|
||||
Profiles,
|
||||
Content,
|
||||
Account,
|
||||
@@ -28,14 +29,7 @@ pub enum FocusedArea {
|
||||
Popup,
|
||||
}
|
||||
|
||||
impl Default for FocusedArea {
|
||||
fn default() -> Self {
|
||||
FocusedArea::Profiles
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
/// runs the main loop until the user quits
|
||||
pub fn run(&mut self, terminal: &mut Tui) -> color_eyre::Result<()> {
|
||||
while !self.exit {
|
||||
terminal.draw(|frame| self.render_frame(frame))?;
|
||||
@@ -45,7 +39,6 @@ impl App {
|
||||
}
|
||||
|
||||
fn render_frame(&mut self, frame: &mut Frame) {
|
||||
// Divide the screen into horizontal chunks
|
||||
let chunks = Layout::default()
|
||||
.direction(Direction::Horizontal)
|
||||
.constraints([
|
||||
@@ -54,10 +47,8 @@ impl App {
|
||||
])
|
||||
.split(frame.area());
|
||||
|
||||
// Render Instances
|
||||
widgets::profiles::render(frame, chunks[0], self.focused, &mut self.profiles_state);
|
||||
|
||||
// Divide the main content into vertical chunks
|
||||
let main_chunks = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([
|
||||
@@ -84,13 +75,11 @@ impl App {
|
||||
widgets::status::render(frame, bottom_chunks[2], self.focused);
|
||||
}
|
||||
|
||||
/// updates the application's state based on user input
|
||||
fn handle_events(&mut self) -> color_eyre::Result<()> {
|
||||
match event::read()? {
|
||||
Event::Key(key_event) if key_event.kind == KeyEventKind::Press => {
|
||||
self.handle_key_event(key_event)
|
||||
.wrap_err_with(|| format!("handling key event failed:\n{key_event:#?}"))
|
||||
}
|
||||
Event::Key(key_event) if key_event.kind == KeyEventKind::Press => self
|
||||
.handle_key_event(key_event)
|
||||
.wrap_err_with(|| format!("handling key event failed:\n{key_event:#?}")),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
@@ -111,9 +100,8 @@ impl App {
|
||||
_ => {}
|
||||
}
|
||||
|
||||
match self.focused {
|
||||
FocusedArea::Profiles => self.profiles_state.handle_key(&key_event),
|
||||
_ => {}
|
||||
if self.focused == FocusedArea::Profiles {
|
||||
self.profiles_state.handle_key(&key_event)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::fmt;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
use tracing::field::{Field, Visit};
|
||||
use tracing::{Level, Subscriber};
|
||||
use tracing_appender::non_blocking::WorkerGuard;
|
||||
use tracing_subscriber::layer::Context;
|
||||
use tracing_subscriber::prelude::*;
|
||||
use tracing_subscriber::{EnvFilter, Layer};
|
||||
|
||||
use crate::config::get_config_path;
|
||||
|
||||
const MAX_STATUS_EVENTS: usize = 50;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StatusEvent {
|
||||
pub level: Level,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
pub static STATUS_EVENTS: Lazy<Arc<Mutex<VecDeque<StatusEvent>>>> =
|
||||
Lazy::new(|| Arc::new(Mutex::new(VecDeque::new())));
|
||||
|
||||
pub fn init() -> WorkerGuard {
|
||||
let log_dir = get_config_path();
|
||||
std::fs::create_dir_all(&log_dir).expect("Failed to create log directory");
|
||||
|
||||
let file_appender = tracing_appender::rolling::daily(&log_dir, "mcl.log");
|
||||
let (non_blocking, guard) = tracing_appender::non_blocking(file_appender);
|
||||
|
||||
let env_filter = EnvFilter::builder()
|
||||
.with_default_directive(Level::INFO.into())
|
||||
.from_env_lossy();
|
||||
|
||||
tracing_subscriber::registry()
|
||||
.with(
|
||||
tracing_subscriber::fmt::layer()
|
||||
.with_writer(non_blocking)
|
||||
.with_ansi(false)
|
||||
.with_filter(env_filter),
|
||||
)
|
||||
.with(StatusLayer::new(STATUS_EVENTS.clone()))
|
||||
.init();
|
||||
|
||||
guard
|
||||
}
|
||||
|
||||
struct StatusLayer {
|
||||
events: Arc<Mutex<VecDeque<StatusEvent>>>,
|
||||
}
|
||||
|
||||
impl StatusLayer {
|
||||
fn new(events: Arc<Mutex<VecDeque<StatusEvent>>>) -> Self {
|
||||
Self { events }
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: Subscriber> Layer<S> for StatusLayer {
|
||||
fn on_event(&self, event: &tracing::Event<'_>, _ctx: Context<'_, S>) {
|
||||
let level = *event.metadata().level();
|
||||
|
||||
// Only capture errors and warnings for the status bar
|
||||
if level > Level::WARN {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut visitor = MessageVisitor::default();
|
||||
event.record(&mut visitor);
|
||||
|
||||
if let Ok(mut events) = self.events.lock() {
|
||||
events.push_back(StatusEvent {
|
||||
level,
|
||||
message: visitor.message,
|
||||
});
|
||||
while events.len() > MAX_STATUS_EVENTS {
|
||||
events.pop_front();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct MessageVisitor {
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl Visit for MessageVisitor {
|
||||
fn record_str(&mut self, field: &Field, value: &str) {
|
||||
if field.name() == "message" {
|
||||
self.message = value.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
|
||||
if field.name() == "message" {
|
||||
let formatted = format!("{:?}", value);
|
||||
// fmt::Arguments Debug wraps in quotes — strip them
|
||||
self.message = formatted
|
||||
.strip_prefix('"')
|
||||
.and_then(|s| s.strip_suffix('"'))
|
||||
.unwrap_or(&formatted)
|
||||
.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -1,4 +1,6 @@
|
||||
pub mod layout;
|
||||
pub mod logging;
|
||||
pub mod theme;
|
||||
pub mod widgets;
|
||||
|
||||
use std::io::{stdout, Result, Stdout};
|
||||
@@ -10,7 +12,6 @@ use crossterm::{
|
||||
use ratatui::{prelude::CrosstermBackend, Terminal};
|
||||
|
||||
pub fn show() -> color_eyre::Result<()> {
|
||||
color_eyre::install()?;
|
||||
let mut terminal = init_ratatui()?;
|
||||
let result = layout::App::default().run(&mut terminal);
|
||||
if let Err(err) = restore_ratatui() {
|
||||
@@ -22,8 +23,6 @@ pub fn show() -> color_eyre::Result<()> {
|
||||
result
|
||||
}
|
||||
|
||||
/// TUI Impl
|
||||
|
||||
pub type Tui = Terminal<CrosstermBackend<Stdout>>;
|
||||
|
||||
fn init_ratatui() -> Result<Tui> {
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
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(|_| {
|
||||
eprintln!("Invalid hex color format: {}", color);
|
||||
255
|
||||
});
|
||||
let g = u8::from_str_radix(&hex[3..5], 16).unwrap_or_else(|_| {
|
||||
eprintln!("Invalid hex color format: {}", color);
|
||||
255
|
||||
});
|
||||
let b = u8::from_str_radix(&hex[5..7], 16).unwrap_or_else(|_| {
|
||||
eprintln!("Invalid hex color format: {}", color);
|
||||
255
|
||||
});
|
||||
Color::Rgb(r, g, b)
|
||||
}
|
||||
_ => {
|
||||
eprintln!("Invalid color name or hex value: {}", color);
|
||||
panic!("Invalid config");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_color<'de, D>(deserializer: D) -> Result<Color, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let color_str: String = Deserialize::deserialize(deserializer)?;
|
||||
Ok(parse_color(&color_str))
|
||||
}
|
||||
|
||||
pub static THEME: Lazy<ThemeConfig> = Lazy::new(|| {
|
||||
let config_path = get_config_path().join("config.toml");
|
||||
ConfigLoader::builder()
|
||||
.add_source(File::from(config_path))
|
||||
.build()
|
||||
.expect("Failed to load theme config")
|
||||
.try_deserialize()
|
||||
.expect("Failed to parse theme config")
|
||||
});
|
||||
@@ -7,11 +7,11 @@ use ratatui::{
|
||||
pub mod account;
|
||||
pub mod content;
|
||||
pub mod details;
|
||||
pub mod popups;
|
||||
pub mod profiles;
|
||||
pub mod status;
|
||||
pub mod popups;
|
||||
|
||||
pub fn styled_title(title: &str, highlight: bool) -> Line {
|
||||
pub fn styled_title(title: &str, highlight: bool) -> Line<'_> {
|
||||
if !highlight || title.is_empty() {
|
||||
Line::from(Span::raw(title))
|
||||
} else {
|
||||
@@ -26,5 +26,5 @@ pub fn styled_title(title: &str, highlight: bool) -> Line {
|
||||
}
|
||||
|
||||
pub trait WidgetKey {
|
||||
fn handle_key(&mut self, key_event: &KeyEvent);
|
||||
fn handle_key(&mut self, key_event: &KeyEvent);
|
||||
}
|
||||
@@ -2,17 +2,18 @@ use super::base::Popup;
|
||||
use crate::tui::layout::FocusedArea;
|
||||
use crate::tui::widgets::profiles;
|
||||
use crossterm::event::KeyCode;
|
||||
use ratatui::{
|
||||
Frame,
|
||||
style::{Color, Style},
|
||||
layout::{Rect, Layout, Direction, Constraint},
|
||||
text::{Line, Span},
|
||||
widgets::{Block, Borders, Paragraph, Wrap, Widget},
|
||||
};
|
||||
use once_cell::sync::Lazy;
|
||||
use ratatui::{
|
||||
layout::{Constraint, Direction, Layout, Rect},
|
||||
style::{Color, Style},
|
||||
text::{Line, Span},
|
||||
widgets::{Block, Borders, Paragraph, Widget, Wrap},
|
||||
Frame,
|
||||
};
|
||||
use std::sync::Mutex;
|
||||
|
||||
static INSTANCE_POPUP_STATE: Lazy<Mutex<NewInstanceState>> = Lazy::new(|| Mutex::new(NewInstanceState::default()));
|
||||
static INSTANCE_POPUP_STATE: Lazy<Mutex<NewInstanceState>> =
|
||||
Lazy::new(|| Mutex::new(NewInstanceState::default()));
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
enum NewInstanceMode {
|
||||
@@ -32,39 +33,43 @@ pub fn render(frame: &mut Frame, area: Rect, _focused: FocusedArea) {
|
||||
|
||||
let popup = Popup {
|
||||
title: Line::from("New Instance"),
|
||||
content: Box::new(move |area, buf| {
|
||||
match state.mode {
|
||||
NewInstanceMode::Buttons => {
|
||||
let chunks = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([
|
||||
Constraint::Percentage(40),
|
||||
Constraint::Length(3),
|
||||
Constraint::Length(3),
|
||||
Constraint::Percentage(40),
|
||||
])
|
||||
.split(area);
|
||||
content: Box::new(move |area, buf| match state.mode {
|
||||
NewInstanceMode::Buttons => {
|
||||
let chunks = Layout::default()
|
||||
.direction(Direction::Vertical)
|
||||
.constraints([
|
||||
Constraint::Percentage(40),
|
||||
Constraint::Length(3),
|
||||
Constraint::Length(3),
|
||||
Constraint::Percentage(40),
|
||||
])
|
||||
.split(area);
|
||||
|
||||
let create_button = Paragraph::new(Line::from(vec![
|
||||
Span::styled("C", Style::default().fg(Color::Yellow)),
|
||||
Span::raw("reate New Instance"),
|
||||
])).alignment(ratatui::layout::Alignment::Center);
|
||||
let create_button = Paragraph::new(Line::from(vec![
|
||||
Span::styled("C", Style::default().fg(Color::Yellow)),
|
||||
Span::raw("reate New Instance"),
|
||||
]))
|
||||
.alignment(ratatui::layout::Alignment::Center);
|
||||
|
||||
let import_button = Paragraph::new(Line::from(vec![
|
||||
Span::styled("I", Style::default().fg(Color::Yellow)),
|
||||
Span::raw("mport Morinth Modpack"),
|
||||
])).alignment(ratatui::layout::Alignment::Center);
|
||||
let import_button = Paragraph::new(Line::from(vec![
|
||||
Span::styled("I", Style::default().fg(Color::Yellow)),
|
||||
Span::raw("mport Morinth Modpack"),
|
||||
]))
|
||||
.alignment(ratatui::layout::Alignment::Center);
|
||||
|
||||
create_button.render(chunks[1], buf);
|
||||
import_button.render(chunks[2], buf);
|
||||
}
|
||||
NewInstanceMode::Input => {
|
||||
let paragraph = Paragraph::new(state.input_text.clone())
|
||||
.block(Block::default().title("Enter URL or Path").borders(Borders::ALL))
|
||||
.wrap(Wrap { trim: true });
|
||||
create_button.render(chunks[1], buf);
|
||||
import_button.render(chunks[2], buf);
|
||||
}
|
||||
NewInstanceMode::Input => {
|
||||
let paragraph = Paragraph::new(state.input_text.clone())
|
||||
.block(
|
||||
Block::default()
|
||||
.title("Enter URL or Path")
|
||||
.borders(Borders::ALL),
|
||||
)
|
||||
.wrap(Wrap { trim: true });
|
||||
|
||||
paragraph.render(area, buf);
|
||||
}
|
||||
paragraph.render(area, buf);
|
||||
}
|
||||
}),
|
||||
border_style: Default::default(),
|
||||
|
||||
@@ -10,7 +10,7 @@ use ratatui::{
|
||||
Frame,
|
||||
};
|
||||
|
||||
use crate::{config::SETTINGS, tui::layout::FocusedArea};
|
||||
use crate::tui::{layout::FocusedArea, theme::THEME};
|
||||
|
||||
use super::{popups, styled_title, WidgetKey};
|
||||
|
||||
@@ -100,9 +100,9 @@ impl WidgetKey for State {
|
||||
|
||||
pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut State) {
|
||||
let color = if focused == FocusedArea::Profiles {
|
||||
SETTINGS.colors.border_focused
|
||||
THEME.colors.border_focused
|
||||
} else {
|
||||
SETTINGS.colors.border_unfocused
|
||||
THEME.colors.border_unfocused
|
||||
};
|
||||
|
||||
let block = Block::default()
|
||||
@@ -126,9 +126,9 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
|
||||
let status = if data.running { "Running" } else { "Stopped" };
|
||||
|
||||
let background_color = if i % 2 == 0 {
|
||||
SETTINGS.colors.row_background
|
||||
THEME.colors.row_background
|
||||
} else {
|
||||
SETTINGS.colors.row_alternate_bg
|
||||
THEME.colors.row_alternate_bg
|
||||
};
|
||||
|
||||
Row::new(vec![
|
||||
@@ -150,7 +150,7 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
|
||||
.row_highlight_style(
|
||||
Style::default()
|
||||
.add_modifier(Modifier::REVERSED)
|
||||
.fg(SETTINGS.colors.row_highlight),
|
||||
.fg(THEME.colors.row_highlight),
|
||||
)
|
||||
.highlight_spacing(ratatui::widgets::HighlightSpacing::Always);
|
||||
|
||||
@@ -162,7 +162,7 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
|
||||
.begin_symbol(Some("▲"))
|
||||
.style(
|
||||
Style::default()
|
||||
.fg(SETTINGS.colors.border_focused)
|
||||
.fg(THEME.colors.border_focused)
|
||||
.add_modifier(Modifier::BOLD),
|
||||
)
|
||||
.thumb_symbol("┃")
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
use ratatui::{
|
||||
layout::Rect,
|
||||
style::{Color, Style},
|
||||
text::{Line, Span},
|
||||
widgets::{Block, BorderType, Borders, Paragraph},
|
||||
Frame,
|
||||
};
|
||||
use tracing::Level;
|
||||
|
||||
use crate::tui::layout::FocusedArea;
|
||||
use crate::tui::logging::STATUS_EVENTS;
|
||||
|
||||
use super::styled_title;
|
||||
|
||||
pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea) {
|
||||
let color = if focused == FocusedArea::Status {
|
||||
let border_color = if focused == FocusedArea::Status {
|
||||
Color::White
|
||||
} else {
|
||||
Color::DarkGray
|
||||
@@ -20,8 +23,29 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea) {
|
||||
.title(styled_title("Status", true))
|
||||
.borders(Borders::ALL)
|
||||
.border_type(BorderType::Rounded)
|
||||
.border_style(Style::default().fg(color));
|
||||
.border_style(Style::default().fg(border_color));
|
||||
|
||||
let widget = Paragraph::new("TEST CONTENT").block(block);
|
||||
frame.render_widget(widget, area);
|
||||
let latest = STATUS_EVENTS
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|events| events.back().cloned());
|
||||
|
||||
let content = match latest {
|
||||
Some(event) => {
|
||||
let (label, label_color) = match event.level {
|
||||
Level::ERROR => (" ERROR ", Color::Red),
|
||||
Level::WARN => (" WARN ", Color::Yellow),
|
||||
_ => (" INFO ", Color::White),
|
||||
};
|
||||
|
||||
Paragraph::new(Line::from(vec![
|
||||
Span::styled(label, Style::default().fg(Color::White).bg(label_color)),
|
||||
Span::raw(" "),
|
||||
Span::raw(event.message),
|
||||
]))
|
||||
}
|
||||
None => Paragraph::new(Span::styled("Ready", Style::default().fg(Color::DarkGray))),
|
||||
};
|
||||
|
||||
frame.render_widget(content.block(block), area);
|
||||
}
|
||||
Reference in new issue
Block a user