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
Generated
+164
-969
File diff suppressed because it is too large.
Load diff
+5
-10
@@ -10,14 +10,9 @@ color-eyre = "0.6.3"
|
||||
config = "0.15.6"
|
||||
crossterm = "0.28.1"
|
||||
dirs-next = "2.0.0"
|
||||
ratatui = "0.29.0"
|
||||
serde = { version = "1.0.217", features = ["derive"]}
|
||||
serde_derive = "1.0.217"
|
||||
lazy_static = "1.5.0"
|
||||
colored = "3.0.0"
|
||||
chrono = "0.4.39"
|
||||
image = "0.25.5"
|
||||
fmt = "0.1.0"
|
||||
once_cell = "1.20.3"
|
||||
rascii_art = "0.4.5"
|
||||
|
||||
ratatui = "0.29.0"
|
||||
serde = { version = "1.0.217", features = ["derive"] }
|
||||
tracing = "0.1"
|
||||
tracing-appender = "0.2"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
-1196
File diff suppressed because it is too large.
Load diff
+12
-13
@@ -1,5 +1,5 @@
|
||||
use crate::tui;
|
||||
use clap::{Arg, ArgAction, Command};
|
||||
use crate::{debug, tui};
|
||||
|
||||
pub fn init() {
|
||||
let matches = Command::new("mcl")
|
||||
@@ -65,7 +65,7 @@ pub fn init() {
|
||||
.short('l')
|
||||
.long("list")
|
||||
.help("List all available profiles")
|
||||
.conflicts_with("delete") // Ensures list and delete are mutually exclusive
|
||||
.conflicts_with("delete")
|
||||
.action(ArgAction::SetTrue),
|
||||
)
|
||||
.arg(
|
||||
@@ -77,7 +77,7 @@ pub fn init() {
|
||||
),
|
||||
)
|
||||
.get_matches();
|
||||
|
||||
|
||||
if matches.subcommand().is_none() {
|
||||
tui::show().unwrap()
|
||||
}
|
||||
@@ -104,27 +104,26 @@ pub fn init() {
|
||||
.unwrap_or_else(|| "None".to_string());
|
||||
|
||||
if launch_matches.get_flag("offline") {
|
||||
debug!("Launching profile '{}' in offline mode...", profile);
|
||||
tracing::debug!("Launching profile '{}' in offline mode...", profile);
|
||||
} else {
|
||||
debug!("Launching profile '{}' in online mode...", profile);
|
||||
tracing::debug!("Launching profile '{}' in online mode...", profile);
|
||||
}
|
||||
|
||||
debug!("Memory: {}", memory);
|
||||
debug!("Resolution: {}", resolution);
|
||||
debug!("JVM Args: {}", jvm_args);
|
||||
tracing::debug!("Memory: {}", memory);
|
||||
tracing::debug!("Resolution: {}", resolution);
|
||||
tracing::debug!("JVM Args: {}", jvm_args);
|
||||
|
||||
if launch_matches.get_flag("no-window") {
|
||||
debug!("Running in headless mode...");
|
||||
tracing::debug!("Running in headless mode...");
|
||||
}
|
||||
}
|
||||
Some(("profiles", profiles_matches)) => {
|
||||
if profiles_matches.get_flag("list") {
|
||||
debug!("Listing all profiles...");
|
||||
tracing::debug!("Listing all profiles...");
|
||||
} else if let Some(profile) = profiles_matches.get_one::<String>("delete") {
|
||||
debug!("Deleting profile '{}'...", profile);
|
||||
tracing::debug!("Deleting profile '{}'...", profile);
|
||||
}
|
||||
}
|
||||
_ => {},
|
||||
_ => {}
|
||||
}
|
||||
|
||||
}
|
||||
+4
-3
@@ -5,8 +5,6 @@ use std::fs;
|
||||
use std::path::PathBuf;
|
||||
use types::Config;
|
||||
|
||||
use crate::debug;
|
||||
|
||||
pub mod types;
|
||||
|
||||
pub fn get_config_path() -> PathBuf {
|
||||
@@ -23,7 +21,10 @@ fn ensure_config_exists(default_path: &str) -> PathBuf {
|
||||
}
|
||||
|
||||
fs::copy(default_path, &config_path).expect("Failed to copy default configuration file");
|
||||
debug!("Default configuration copied to '{}'", config_path.display());
|
||||
tracing::debug!(
|
||||
"Default configuration copied to '{}'",
|
||||
config_path.display()
|
||||
);
|
||||
}
|
||||
|
||||
config_path
|
||||
|
||||
+1
-80
@@ -1,90 +1,11 @@
|
||||
use serde::{Deserialize, Deserializer};
|
||||
use ratatui::style::Color;
|
||||
use crate::error;
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct General {
|
||||
pub debug: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct Colors {
|
||||
#[serde(deserialize_with = "deserialize_color")]
|
||||
pub background: Color, // General background color
|
||||
|
||||
#[serde(deserialize_with = "deserialize_color")]
|
||||
pub foreground: Color, // General text color
|
||||
|
||||
#[serde(deserialize_with = "deserialize_color")]
|
||||
pub border_focused: Color, // Border color for focused areas
|
||||
|
||||
#[serde(deserialize_with = "deserialize_color")]
|
||||
pub border_unfocused: Color, // Border color for unfocused areas
|
||||
|
||||
#[serde(deserialize_with = "deserialize_color")]
|
||||
pub row_highlight: Color, // Highlighted row color
|
||||
|
||||
#[serde(deserialize_with = "deserialize_color")]
|
||||
pub row_background: Color, // Row background color
|
||||
|
||||
#[serde(deserialize_with = "deserialize_color")]
|
||||
pub row_alternate_bg: Color, // Alternate row background color
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct Config {
|
||||
pub general: General,
|
||||
pub colors: Colors,
|
||||
}
|
||||
|
||||
|
||||
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(|_| {
|
||||
error!("Invalid hex color format: {}", color);
|
||||
255
|
||||
});
|
||||
let g = u8::from_str_radix(&hex[3..5], 16).unwrap_or_else(|_| {
|
||||
error!("Invalid hex color format: {}", color);
|
||||
255
|
||||
});
|
||||
let b = u8::from_str_radix(&hex[5..7], 16).unwrap_or_else(|_| {
|
||||
error!("Invalid hex color format: {}", color);
|
||||
255
|
||||
});
|
||||
Color::Rgb(r, g, b)
|
||||
}
|
||||
_ => {
|
||||
error!("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))
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
use std::sync::Mutex;
|
||||
use chrono::Local;
|
||||
use color_eyre::owo_colors::OwoColorize;
|
||||
use lazy_static::lazy_static;
|
||||
|
||||
pub struct Logger {
|
||||
debug: bool,
|
||||
}
|
||||
|
||||
impl Logger {
|
||||
pub fn init(debug: bool) {
|
||||
let mut logger = LOGGER.lock().unwrap();
|
||||
logger.debug = debug;
|
||||
}
|
||||
|
||||
fn timestamp() -> String {
|
||||
Local::now().format("%Y-%m-%d %H:%M:%S").to_string()
|
||||
}
|
||||
|
||||
pub fn debug(&self, message: &str) {
|
||||
if self.debug {
|
||||
println!(
|
||||
"{} {} {}",
|
||||
Self::timestamp().dimmed(),
|
||||
"[DEBUG]".cyan(),
|
||||
message
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn info(&self, message: &str) {
|
||||
println!(
|
||||
"{} {} {}",
|
||||
Self::timestamp().dimmed(),
|
||||
"[INFO]".green(),
|
||||
message
|
||||
);
|
||||
}
|
||||
|
||||
pub fn error(&self, message: &str) {
|
||||
eprintln!(
|
||||
"{} {} {}",
|
||||
Self::timestamp().dimmed(),
|
||||
"[ERROR]".red().bold(),
|
||||
message
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
lazy_static! {
|
||||
pub static ref LOGGER: Mutex<Logger> = Mutex::new(Logger { debug: false });
|
||||
}
|
||||
|
||||
pub fn get_logger() -> std::sync::MutexGuard<'static, Logger> {
|
||||
LOGGER.lock().unwrap()
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
#[macro_export]
|
||||
macro_rules! debug {
|
||||
($msg:expr) => {
|
||||
$crate::logger::get_logger().debug($msg);
|
||||
};
|
||||
($fmt:expr, $($arg:tt)*) => {
|
||||
$crate::logger::get_logger().debug(&format!($fmt, $($arg)*));
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! info {
|
||||
($msg:expr) => {
|
||||
$crate::logger::get_logger().info($msg);
|
||||
};
|
||||
($fmt:expr, $($arg:tt)*) => {
|
||||
$crate::logger::get_logger().info(&format!($fmt, $($arg)*));
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! error {
|
||||
($msg:expr) => {
|
||||
$crate::logger::get_logger().error($msg);
|
||||
};
|
||||
($fmt:expr, $($arg:tt)*) => {
|
||||
$crate::logger::get_logger().error(&format!($fmt, $($arg)*));
|
||||
};
|
||||
}
|
||||
+2
-6
@@ -1,13 +1,9 @@
|
||||
use config::SETTINGS;
|
||||
use logger::Logger;
|
||||
|
||||
mod cli;
|
||||
pub mod config;
|
||||
pub mod logger;
|
||||
pub mod macros;
|
||||
pub mod tui;
|
||||
|
||||
fn main() {
|
||||
Logger::init(SETTINGS.general.debug);
|
||||
let _guard = tui::logging::init();
|
||||
color_eyre::install().expect("Failed to install color-eyre");
|
||||
cli::init()
|
||||
}
|
||||
+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