refactor: upgrade crates and restructure project

This commit is contained in:
objz committed 2026-04-18 16:59:27 +02:00
1 parent ea093c044f
commit 47dad69321
80 files changed
+6094 -6125

No files matched your search

+99
View File
@@ -0,0 +1,99 @@
use std::collections::HashMap;
use std::sync::{Arc, LazyLock, Mutex};
use tachyonfx::Effect;
use super::widgets::{self, instances};
use crate::instance::{InstanceConfig, InstanceManager};
pub(super) static PENDING_INSTANCES: LazyLock<Arc<Mutex<Vec<InstanceConfig>>>> =
LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));
pub struct App {
pub(super) exit: bool,
pub(super) focused: FocusedArea,
pub(super) pre_overlay_focused: FocusedArea,
pub(super) content_tab: widgets::content::ContentTab,
pub(super) instances_state: instances::State,
pub(super) mods_state: widgets::content::list::ContentListState,
pub(super) resource_packs_state: widgets::content::list::ContentListState,
pub(super) shaders_state: widgets::content::list::ContentListState,
pub(super) worlds_state: widgets::content::list::ContentListState,
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) picker: ratatui_image::picker::Picker,
pub(super) instance_manager: InstanceManager,
pub(super) log_overlay_scroll: usize,
pub(super) log_overlay_max_scroll: usize,
pub(super) log_overlay_search: widgets::search::SearchState,
pub(super) log_overlay_scrollbar: ratatui::widgets::ScrollbarState,
pub(super) throbber_state: throbber_widgets_tui::ThrobberState,
pub(super) throbber_tick: u8,
pub(super) error_effects: HashMap<u64, ErrorEffectState>,
pub(super) pending_editor: Option<std::path::PathBuf>,
}
pub(super) enum ErrorEffectState {
SlidingIn(Effect, std::time::Instant),
Idle,
FadingOut(Effect, std::time::Instant),
}
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub enum FocusedArea {
#[default]
Instances,
Content,
Account,
Settings,
Overview,
OverviewExpanded,
Popup,
ImportPopup,
ErrorPopup,
ConfirmDelete,
}
impl App {
pub fn new(picker: ratatui_image::picker::Picker) -> Self {
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir();
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
let _ = std::fs::create_dir_all(&instances_dir);
let _ = std::fs::create_dir_all(&meta_dir);
let manager = InstanceManager::new(instances_dir, meta_dir);
let instances = manager.load_all();
let instances_state = instances::State::with_instances(instances);
App {
exit: false,
focused: FocusedArea::default(),
pre_overlay_focused: FocusedArea::default(),
content_tab: widgets::content::ContentTab::default(),
instances_state,
mods_state: widgets::content::list::ContentListState::default(),
resource_packs_state: widgets::content::list::ContentListState::default(),
shaders_state: widgets::content::list::ContentListState::default(),
worlds_state: widgets::content::list::ContentListState::default(),
logs_state: widgets::logs_viewer::LogsState::default(),
account_state: widgets::account::AccountState::default(),
screenshots_state: {
let mut s = widgets::screenshots_grid::ScreenshotsState::default();
s.font_size = picker.font_size();
s
},
picker,
instance_manager: manager,
log_overlay_scroll: 0,
log_overlay_max_scroll: 0,
log_overlay_search: widgets::search::SearchState::default(),
log_overlay_scrollbar: ratatui::widgets::ScrollbarState::default(),
throbber_state: throbber_widgets_tui::ThrobberState::default(),
throbber_tick: 0,
error_effects: HashMap::new(),
pending_editor: None,
}
}
}
+7 -3
View File
@@ -3,7 +3,7 @@ use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Instant;
use once_cell::sync::Lazy;
use std::sync::LazyLock;
use tracing::Level;
const MAX_ERROR_EVENTS: usize = 50;
@@ -17,8 +17,8 @@ pub struct ErrorEvent {
pub pushed_at: Instant,
}
pub static ERROR_EVENTS: Lazy<Arc<Mutex<VecDeque<ErrorEvent>>>> =
Lazy::new(|| Arc::new(Mutex::new(VecDeque::new())));
pub static ERROR_EVENTS: LazyLock<Arc<Mutex<VecDeque<ErrorEvent>>>> =
LazyLock::new(|| Arc::new(Mutex::new(VecDeque::new())));
pub fn push_error(event: ErrorEvent) {
match ERROR_EVENTS.lock() {
@@ -36,6 +36,7 @@ pub fn push_error(event: ErrorEvent) {
}
}
#[must_use]
pub fn has_errors() -> bool {
match ERROR_EVENTS.lock() {
Ok(events) => !events.is_empty(),
@@ -43,6 +44,7 @@ pub fn has_errors() -> bool {
}
}
#[must_use]
pub fn pop_error() -> Option<ErrorEvent> {
match ERROR_EVENTS.lock() {
Ok(mut events) => events.pop_front(),
@@ -50,6 +52,7 @@ pub fn pop_error() -> Option<ErrorEvent> {
}
}
#[must_use]
pub fn peek_error() -> Option<ErrorEvent> {
match ERROR_EVENTS.lock() {
Ok(events) => events.front().cloned(),
@@ -58,6 +61,7 @@ pub fn peek_error() -> Option<ErrorEvent> {
}
/// Returns all queued error events, newest first (for top-to-bottom stacking).
#[must_use]
pub fn peek_all_errors() -> Vec<ErrorEvent> {
match ERROR_EVENTS.lock() {
Ok(events) => events.iter().rev().cloned().collect(),
+260
View File
@@ -0,0 +1,260 @@
use color_eyre::eyre::Context;
use crossterm::event::{self, Event};
use ratatui::crossterm::event::KeyEventKind;
use std::time::Duration;
use super::app::{App, PENDING_INSTANCES};
use super::widgets::{self, popups::import_modpack, popups::new_instance};
use super::Tui;
use crate::instance::InstanceManager;
use crate::tui::error_buffer;
use crate::tui::progress;
impl App {
pub async fn run(&mut self, terminal: &mut Tui) -> color_eyre::Result<()> {
while !self.exit {
if let Some(params) = new_instance::take_result() {
self.spawn_create(params);
}
if let Some(result) = import_modpack::take_result() {
self.spawn_import(result);
}
self.dismiss_expired_errors();
self.drain_pending_instances();
self.drain_pending_last_played();
self.mods_state.drain_pending();
self.mods_state.try_rescan();
self.resource_packs_state.drain_pending();
self.resource_packs_state.try_rescan();
self.shaders_state.drain_pending();
self.shaders_state.try_rescan();
self.worlds_state.drain_pending();
self.worlds_state.try_rescan();
self.logs_state.drain_pending();
self.logs_state.try_rescan();
self.account_state.drain_auth_result();
widgets::account::drain_device_code(&mut self.account_state);
self.screenshots_state.drain_pending_entries();
self.screenshots_state.request_visible_loads();
self.create_screenshot_protocols();
self.throbber_tick = self.throbber_tick.wrapping_add(1);
if self.throbber_tick.is_multiple_of(8) {
self.throbber_state.calc_next();
}
terminal.draw(|frame| self.render_frame(frame))?;
self.handle_events().wrap_err("handle events failed")?;
if let Some(path) = self.pending_editor.take() {
Self::run_editor(terminal, &path);
}
}
Ok(())
}
fn handle_events(&mut self) -> color_eyre::Result<()> {
match crossterm::event::poll(Duration::from_millis(16)) {
Ok(true) => match event::read() {
Ok(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(_) => Ok(()),
Err(e) => {
tracing::error!("Event read error: {}", e);
Ok(())
}
},
Ok(false) => Ok(()),
Err(e) => {
tracing::error!("Event poll error: {}", e);
Ok(())
}
}
}
fn spawn_create(&self, params: new_instance::WizardParams) {
let instances_dir = self.instance_manager.instances_dir.clone();
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
let pending_instances = PENDING_INSTANCES.clone();
tokio::spawn(async move {
progress::set_action(format!("Creating instance '{}'...", params.name));
progress::set_sub_action(format!("{} {}", params.game_version, params.loader));
let manager = InstanceManager::new(instances_dir, meta_dir);
match manager
.create(
&params.name,
&params.game_version,
params.loader,
params.loader_version.as_deref(),
)
.await
{
Ok(config) => {
if let Ok(mut pending) = pending_instances.lock() {
pending.push(config);
}
}
Err(e) => {
progress::clear();
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
message: format!("Failed to create instance '{}': {e}", params.name),
pushed_at: std::time::Instant::now(),
});
}
}
});
}
fn spawn_import(&self, result: import_modpack::ImportResult) {
let instances_dir = self.instance_manager.instances_dir.clone();
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
let pending_instances = PENDING_INSTANCES.clone();
tokio::spawn(async move {
let manager = InstanceManager::new(instances_dir, meta_dir);
match crate::instance::import::execute_import(&result.summary, &manager).await {
Ok(config) => {
if let Ok(mut pending) = pending_instances.lock() {
pending.push(config);
}
}
Err(e) => {
crate::tui::progress::clear();
error_buffer::push_error(error_buffer::ErrorEvent {
id: 0,
level: tracing::Level::ERROR,
message: format!("Import failed: {e}"),
pushed_at: std::time::Instant::now(),
});
}
}
});
}
fn run_editor(terminal: &mut ratatui::DefaultTerminal, path: &std::path::Path) {
use ratatui::crossterm::{
terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
},
ExecutableCommand,
};
use std::io::stdout;
let default_editor = if cfg!(windows) { "notepad" } else { "vi" };
let editor = std::env::var("EDITOR")
.or_else(|_| std::env::var("VISUAL"))
.unwrap_or_else(|_| default_editor.to_owned());
let editor_name = std::path::Path::new(&editor)
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or(&editor);
let is_tui_editor = matches!(
editor_name,
"vi" | "vim"
| "nvim"
| "neovim"
| "nano"
| "micro"
| "helix"
| "hx"
| "emacs"
| "ne"
| "joe"
| "mcedit"
);
if is_tui_editor {
let _ = stdout().execute(LeaveAlternateScreen);
let _ = disable_raw_mode();
let result = std::process::Command::new(&editor)
.arg(path)
.stdin(std::process::Stdio::inherit())
.stdout(std::process::Stdio::inherit())
.stderr(std::process::Stdio::inherit())
.status();
let _ = stdout().execute(EnterAlternateScreen);
let _ = enable_raw_mode();
let _ = terminal.clear();
if let Err(e) = result {
tracing::error!("Failed to open editor: {}", e);
}
} else if let Err(e) = std::process::Command::new(&editor)
.arg(path)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
{
tracing::error!("Failed to open editor: {}", e);
}
}
pub(super) fn spawn_launch(&self, instance: crate::instance::InstanceConfig) {
use crate::instance::launch;
use crate::running;
running::set_state(&instance.name, running::RunState::Authenticating);
let instances_dir = self.instance_manager.instances_dir.clone();
let meta_dir = self.instance_manager.meta_dir.clone();
tokio::spawn(async move {
if let Err(e) = launch::launch(&instance, &instances_dir, &meta_dir).await {
tracing::error!("Failed to launch '{}': {}", instance.name, e);
running::remove(&instance.name);
}
});
}
fn dismiss_expired_errors(&self) {
use crate::config::SETTINGS;
loop {
match error_buffer::peek_error() {
Some(event)
if event.pushed_at.elapsed().as_millis()
>= SETTINGS.ui.error_auto_dismiss_ms as u128 =>
{
let _ = error_buffer::pop_error();
}
_ => break,
}
}
}
fn drain_pending_instances(&mut self) {
if let Ok(mut pending) = PENDING_INSTANCES.lock() {
for config in pending.drain(..) {
self.instances_state.add_instance(config);
}
}
}
fn drain_pending_last_played(&mut self) {
for (name, time) in crate::running::drain_last_played() {
for inst in &mut self.instances_state.instances {
if inst.name == name {
inst.last_played = Some(time);
break;
}
}
}
}
pub(super) fn create_screenshot_protocols(&mut self) {
let pending = self.screenshots_state.take_pending_images();
for (idx, img) in pending {
let proto = self.picker.new_resize_protocol(img);
self.screenshots_state.set_protocol(idx, proto);
}
}
}
+327
View File
@@ -0,0 +1,327 @@
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use super::app::{App, FocusedArea};
use super::widgets::{self, popups::confirm as confirm_popup, popups::import_modpack, popups::new_instance, WidgetKey};
use crate::tui::error_buffer;
impl App {
pub(super) fn handle_key_event(&mut self, key_event: KeyEvent) -> color_eyre::Result<()> {
if self.focused == FocusedArea::OverviewExpanded {
if self.log_overlay_search.active {
match key_event.code {
KeyCode::Esc => {
self.log_overlay_search.deactivate();
}
KeyCode::Backspace => {
self.log_overlay_search.pop();
}
KeyCode::Char(c) => {
self.log_overlay_search.push(c);
}
_ => {}
}
return Ok(());
}
match key_event.code {
KeyCode::Char('O') | KeyCode::Esc => {
self.focused = self.pre_overlay_focused;
self.log_overlay_search.deactivate();
return Ok(());
}
KeyCode::Char('j') | KeyCode::Down => {
if self.log_overlay_scroll < self.log_overlay_max_scroll {
self.log_overlay_scroll += 1;
}
return Ok(());
}
KeyCode::Char('k') | KeyCode::Up => {
self.log_overlay_scroll = self.log_overlay_scroll.saturating_sub(1);
return Ok(());
}
KeyCode::Char('G') => {
self.log_overlay_scroll = self.log_overlay_max_scroll;
return Ok(());
}
KeyCode::Char('g') => {
self.log_overlay_scroll = 0;
return Ok(());
}
KeyCode::Char('/') => {
self.log_overlay_search.activate();
return Ok(());
}
_ => {
return Ok(());
}
}
}
if self.focused == FocusedArea::ConfirmDelete {
match key_event.code {
KeyCode::Enter | KeyCode::Char('y') | KeyCode::Char('Y') => {
let name = confirm_popup::pending_delete_name();
if !name.is_empty() {
match self.instance_manager.delete(&name) {
Ok(_) => {
self.instances_state.remove_instance(&name);
}
Err(e) => {
tracing::error!("Failed to delete instance '{}': {}", name, e);
}
}
}
confirm_popup::clear_pending();
self.focused = FocusedArea::Instances;
return Ok(());
}
KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('N') => {
confirm_popup::clear_pending();
self.focused = FocusedArea::Instances;
return Ok(());
}
_ => {
return Ok(());
}
}
}
if self.focused == FocusedArea::Content {
if self.content_tab == widgets::content::ContentTab::Logs {
if widgets::logs_viewer::handle_key(&key_event, &mut self.logs_state) {
return Ok(());
}
} else if self.content_tab == widgets::content::ContentTab::Screenshots {
if widgets::screenshots_grid::handle_key(&key_event, &mut self.screenshots_state) {
return Ok(());
}
} else if self.content_tab == widgets::content::ContentTab::Worlds {
if widgets::content::list::handle_key_no_toggle(&key_event, &mut self.worlds_state) {
return Ok(());
}
} else {
let state = match self.content_tab {
widgets::content::ContentTab::Mods => Some(&mut self.mods_state),
widgets::content::ContentTab::ResourcePacks => {
Some(&mut self.resource_packs_state)
}
widgets::content::ContentTab::Shaders => Some(&mut self.shaders_state),
_ => None,
};
if let Some(state) = state {
if widgets::content::list::handle_key(&key_event, state) {
return Ok(());
}
}
}
}
if self.focused == FocusedArea::Account
&& widgets::account::handle_key(&key_event, &mut self.account_state)
{
return Ok(());
}
if self.focused == FocusedArea::Settings {
match widgets::details::handle_key(
&key_event,
self.instances_state.selected_instance(),
&self.instance_manager.instances_dir,
) {
widgets::details::SettingsAction::EditInstance(path)
| widgets::details::SettingsAction::EditGlobal(path) => {
self.pending_editor = Some(path);
return Ok(());
}
widgets::details::SettingsAction::ToggleDesktop => {
if let Some(inst) = self.instances_state.selected_instance() {
let name = inst.name.clone();
match crate::instance::desktop::toggle(inst) {
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(e) => {
tracing::error!("Failed to toggle desktop shortcut: {}", e);
}
}
}
return Ok(());
}
widgets::details::SettingsAction::None => {}
}
}
match self.focused {
FocusedArea::Popup => {
new_instance::handle_key(&key_event, &mut self.instances_state);
}
FocusedArea::ImportPopup => {
import_modpack::handle_key(&key_event, &mut self.instances_state);
}
_ => {
if self.focused == FocusedArea::Instances && self.instances_state.renaming.is_some() {
match key_event.code {
KeyCode::Enter => {
let new_name = self.instances_state.renaming.take().unwrap_or_default();
if let Some(inst) = self.instances_state.selected_instance() {
let old_name = inst.name.clone();
match self.instance_manager.rename(&old_name, &new_name) {
Ok(()) => {
if let Some(inst) = self
.instances_state
.instances
.iter_mut()
.find(|i| i.name == old_name)
{
inst.name = new_name.trim().to_owned();
}
}
Err(e) => {
tracing::error!("Rename failed: {}", e);
}
}
}
}
KeyCode::Esc => {
self.instances_state.renaming = None;
}
KeyCode::Backspace => {
if let Some(ref mut name) = self.instances_state.renaming {
name.pop();
}
}
KeyCode::Char(c) => {
if let Some(ref mut name) = self.instances_state.renaming {
name.push(c);
}
}
_ => {}
}
return Ok(());
}
if self.focused == FocusedArea::Instances && self.instances_state.search.active {
self.instances_state.handle_key(&key_event);
return Ok(());
}
match key_event.code {
KeyCode::Char('q') => self.exit = true,
KeyCode::Char('I') => self.focused = FocusedArea::Instances,
KeyCode::Char('C') => self.focused = FocusedArea::Content,
KeyCode::Char('A') => self.focused = FocusedArea::Account,
KeyCode::Char('S') => self.focused = FocusedArea::Settings,
KeyCode::Char('O') => {
self.pre_overlay_focused = self.focused;
self.focused = FocusedArea::OverviewExpanded;
}
KeyCode::Tab | KeyCode::Char('l') | KeyCode::Right
if self.focused == FocusedArea::Content =>
{
self.content_tab = self.content_tab.next();
}
KeyCode::BackTab | KeyCode::Char('h') | KeyCode::Left
if self.focused == FocusedArea::Content =>
{
self.content_tab = self.content_tab.previous();
}
KeyCode::Char('d')
if self.focused == FocusedArea::Instances
&& !self.instances_state.search.active =>
{
if let Some(instance) = self.instances_state.selected_instance() {
let name = instance.name.clone();
confirm_popup::set_pending_delete(&name);
self.focused = FocusedArea::ConfirmDelete;
}
}
KeyCode::Enter
if self.focused == FocusedArea::Instances
&& !self.instances_state.search.active
&& key_event.modifiers.contains(KeyModifiers::SHIFT) =>
{
if let Some(instance) = self.instances_state.selected_instance() {
let dir = self
.instance_manager
.instances_dir
.join(&instance.name)
.join(".minecraft");
if let Err(e) = open::that(&dir) {
tracing::error!("Failed to open instance directory: {}", e);
}
}
}
KeyCode::Enter
if self.focused == FocusedArea::Instances
&& !self.instances_state.search.active =>
{
self.focused = FocusedArea::Content;
}
KeyCode::Char('l')
if self.focused == FocusedArea::Instances
&& !self.instances_state.search.active =>
{
if let Some(instance) = self.instances_state.selected_instance().cloned() {
let can_launch = matches!(
crate::running::get(&instance.name),
None | Some(crate::running::RunState::Crashed(_))
);
if can_launch {
crate::running::remove(&instance.name);
crate::instance_logs::clear(&instance.name);
self.spawn_launch(instance);
}
}
}
KeyCode::Char('r')
if self.focused == FocusedArea::Instances
&& !self.instances_state.search.active =>
{
if let Some(inst) = self.instances_state.selected_instance() {
self.instances_state.renaming = Some(inst.name.clone());
}
}
KeyCode::Esc
if self.focused == FocusedArea::Instances
&& !self.instances_state.search.active =>
{
if let Some(instance) = self.instances_state.selected_instance() {
crate::running::send_kill(&instance.name);
}
}
_ => {}
}
if self.focused == FocusedArea::Instances {
self.instances_state.handle_key(&key_event)
}
}
}
if self.instances_state.wants_popup() {
self.focused = FocusedArea::Popup;
} else if self.focused == FocusedArea::Popup {
self.focused = FocusedArea::Instances;
}
if self.instances_state.wants_import_popup() {
self.focused = FocusedArea::ImportPopup;
} else if self.focused == FocusedArea::ImportPopup {
self.focused = FocusedArea::Instances;
}
Ok(())
}
}
-967
View File
@@ -1,967 +0,0 @@
use super::widgets::popups::import_modpack;
use super::widgets::popups::new_instance;
use super::{
widgets::{self, profiles, WidgetKey},
Tui,
};
use crate::instance::{InstanceConfig, InstanceManager};
use crate::tui::error_buffer;
use crate::tui::progress;
use crate::tui::widgets::popups::confirm as confirm_popup;
use crate::tui::widgets::popups::confirm::{confirm_popup_area, ConfirmPopup};
use crate::tui::widgets::popups::error::{popup_area, ErrorPopup};
use color_eyre::eyre::Context;
use crossterm::event::{self, Event};
use once_cell::sync::Lazy;
use ratatui::{
crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers},
layout::{Constraint, Direction, Layout},
Frame,
};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tachyonfx::{fx, Effect, EffectRenderer, Interpolation, Motion};
static PENDING_INSTANCES: Lazy<Arc<Mutex<Vec<InstanceConfig>>>> =
Lazy::new(|| Arc::new(Mutex::new(Vec::new())));
pub struct App {
exit: bool,
focused: FocusedArea,
pre_overlay_focused: FocusedArea,
content_tab: widgets::content::ContentTab,
profiles_state: profiles::State,
mods_state: widgets::content_list::ContentListState,
resource_packs_state: widgets::content_list::ContentListState,
shaders_state: widgets::content_list::ContentListState,
worlds_state: widgets::content_list::ContentListState,
screenshots_state: widgets::screenshots_grid::ScreenshotsState,
logs_state: widgets::logs_viewer::LogsState,
account_state: widgets::account::AccountState,
picker: ratatui_image::picker::Picker,
instance_manager: InstanceManager,
log_overlay_scroll: usize,
log_overlay_max_scroll: usize,
log_overlay_search: widgets::search::SearchState,
log_overlay_scrollbar: ratatui::widgets::ScrollbarState,
throbber_state: throbber_widgets_tui::ThrobberState,
throbber_tick: u8,
error_effects: HashMap<u64, ErrorEffectState>,
pending_editor: Option<std::path::PathBuf>,
}
enum ErrorEffectState {
SlidingIn(Effect),
Idle,
FadingOut(Effect),
}
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub enum FocusedArea {
#[default]
Profiles,
Content,
Account,
Settings,
Overview,
OverviewExpanded,
Popup,
ImportPopup,
ErrorPopup,
ConfirmDelete,
}
impl App {
pub fn new(picker: ratatui_image::picker::Picker) -> Self {
let instances_dir = crate::config::SETTINGS.paths.resolve_instances_dir();
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
match std::fs::create_dir_all(&instances_dir) {
Ok(_) => {}
Err(e) => {
tracing::error!("Failed to create instances dir: {}", e);
}
}
match std::fs::create_dir_all(&meta_dir) {
Ok(_) => {}
Err(e) => {
tracing::error!("Failed to create meta dir: {}", e);
}
}
let manager = InstanceManager::new(instances_dir, meta_dir);
let instances = manager.load_all();
let profiles_state = profiles::State::with_instances(instances);
App {
exit: false,
focused: FocusedArea::default(),
pre_overlay_focused: FocusedArea::default(),
content_tab: widgets::content::ContentTab::default(),
profiles_state,
mods_state: widgets::content_list::ContentListState::default(),
resource_packs_state: widgets::content_list::ContentListState::default(),
shaders_state: widgets::content_list::ContentListState::default(),
worlds_state: widgets::content_list::ContentListState::default(),
logs_state: widgets::logs_viewer::LogsState::default(),
account_state: widgets::account::AccountState::default(),
screenshots_state: {
let mut s = widgets::screenshots_grid::ScreenshotsState::default();
s.font_size = picker.font_size();
s
},
picker,
instance_manager: manager,
log_overlay_scroll: 0,
log_overlay_max_scroll: 0,
log_overlay_search: widgets::search::SearchState::default(),
log_overlay_scrollbar: ratatui::widgets::ScrollbarState::default(),
throbber_state: throbber_widgets_tui::ThrobberState::default(),
throbber_tick: 0,
error_effects: HashMap::new(),
pending_editor: None,
}
}
}
impl App {
pub async fn run(&mut self, terminal: &mut Tui) -> color_eyre::Result<()> {
while !self.exit {
if let Some(params) = new_instance::take_result() {
self.spawn_create(params);
}
if let Some(result) = import_modpack::take_result() {
self.spawn_import(result);
}
self.dismiss_expired_errors();
self.drain_pending_instances();
self.drain_pending_last_played();
self.mods_state.drain_pending();
self.resource_packs_state.drain_pending();
self.shaders_state.drain_pending();
self.worlds_state.drain_pending();
self.logs_state.drain_pending();
self.logs_state.try_rescan();
self.account_state.drain_auth_result();
widgets::account::drain_device_code(&mut self.account_state);
self.screenshots_state.drain_pending_entries();
self.screenshots_state.request_visible_loads();
self.create_screenshot_protocols();
self.throbber_tick = self.throbber_tick.wrapping_add(1);
if self.throbber_tick.is_multiple_of(8) {
self.throbber_state.calc_next();
}
terminal.draw(|frame| self.render_frame(frame))?;
self.handle_events().wrap_err("handle events failed")?;
if let Some(path) = self.pending_editor.take() {
Self::run_editor(terminal, &path);
}
}
Ok(())
}
fn render_frame(&mut self, frame: &mut Frame) {
let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(20), // Instances
Constraint::Percentage(80), // Main content
])
.split(frame.area());
widgets::profiles::render(frame, chunks[0], self.focused, &mut self.profiles_state);
let main_chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(3), // Title
Constraint::Min(10), // Main Content
Constraint::Length(5), // Bottom panel
])
.split(chunks[1]);
widgets::content::title(
frame,
main_chunks[0],
self.focused,
self.profiles_state.selected_instance(),
&mut self.throbber_state,
);
widgets::content::render(
frame,
main_chunks[1],
self.focused,
self.content_tab,
self.profiles_state.selected_instance(),
&mut self.mods_state,
&mut self.resource_packs_state,
&mut self.shaders_state,
&mut self.worlds_state,
&mut self.screenshots_state,
&mut self.logs_state,
&self.instance_manager.instances_dir,
);
let bottom_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(30),
Constraint::Percentage(40),
Constraint::Percentage(30),
])
.split(main_chunks[2]);
widgets::account::render(
frame,
bottom_chunks[0],
self.focused,
&mut self.account_state,
);
widgets::details::render(
frame,
bottom_chunks[1],
self.focused,
self.profiles_state.selected_instance(),
&self.instance_manager.instances_dir,
);
widgets::status::render(
frame,
bottom_chunks[2],
self.focused,
&mut self.throbber_state,
);
if self.focused == FocusedArea::OverviewExpanded {
self.render_log_overlay(frame);
}
let all_errors = error_buffer::peek_all_errors();
self.sync_error_effects(&all_errors);
let mut next_y: u16 = 1;
for event in all_errors {
let elapsed_ms = event.pushed_at.elapsed().as_millis();
if let Some(area) = popup_area(frame.area(), &event.message, next_y, elapsed_ms) {
next_y = next_y.saturating_add(area.height + 1);
frame.render_widget(ErrorPopup::new(event.clone()), area);
self.render_error_effect(frame, area, &event, elapsed_ms);
}
}
if self.profiles_state.show_popup {
let area = new_instance::popup_rect(frame.area());
new_instance::render(frame, area, self.focused);
}
if self.profiles_state.show_import_popup {
let area = import_modpack::popup_rect(frame.area());
import_modpack::render(frame, area, self.focused);
}
if self.focused == FocusedArea::ConfirmDelete {
let name = confirm_popup::pending_delete_name();
if !name.is_empty() {
let area = confirm_popup_area(frame.area(), &name);
frame.render_widget(ConfirmPopup::new(&name), area);
}
}
}
fn handle_events(&mut self) -> color_eyre::Result<()> {
match crossterm::event::poll(Duration::from_millis(16)) {
Ok(true) => match event::read() {
Ok(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(_) => Ok(()),
Err(e) => {
tracing::error!("Event read error: {}", e);
Ok(())
}
},
Ok(false) => Ok(()),
Err(e) => {
tracing::error!("Event poll error: {}", e);
Ok(())
}
}
}
fn handle_key_event(&mut self, key_event: KeyEvent) -> color_eyre::Result<()> {
if self.focused == FocusedArea::OverviewExpanded {
if self.log_overlay_search.active {
match key_event.code {
KeyCode::Esc => {
self.log_overlay_search.deactivate();
}
KeyCode::Backspace => {
self.log_overlay_search.pop();
}
KeyCode::Char(c) => {
self.log_overlay_search.push(c);
}
_ => {}
}
return Ok(());
}
match key_event.code {
KeyCode::Char('O') | KeyCode::Esc => {
self.focused = self.pre_overlay_focused;
self.log_overlay_search.deactivate();
return Ok(());
}
KeyCode::Char('j') | KeyCode::Down => {
if self.log_overlay_scroll < self.log_overlay_max_scroll {
self.log_overlay_scroll += 1;
}
return Ok(());
}
KeyCode::Char('k') | KeyCode::Up => {
self.log_overlay_scroll = self.log_overlay_scroll.saturating_sub(1);
return Ok(());
}
KeyCode::Char('G') => {
self.log_overlay_scroll = self.log_overlay_max_scroll;
return Ok(());
}
KeyCode::Char('g') => {
self.log_overlay_scroll = 0;
return Ok(());
}
KeyCode::Char('/') => {
self.log_overlay_search.activate();
return Ok(());
}
_ => {
return Ok(());
}
}
}
if self.focused == FocusedArea::ConfirmDelete {
match key_event.code {
KeyCode::Enter | KeyCode::Char('y') | KeyCode::Char('Y') => {
let name = confirm_popup::pending_delete_name();
if !name.is_empty() {
match self.instance_manager.delete(&name) {
Ok(_) => {
self.profiles_state.remove_instance(&name);
}
Err(e) => {
tracing::error!("Failed to delete instance '{}': {}", name, e);
}
}
}
confirm_popup::clear_pending();
self.focused = FocusedArea::Profiles;
return Ok(());
}
KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('N') => {
confirm_popup::clear_pending();
self.focused = FocusedArea::Profiles;
return Ok(());
}
_ => {
return Ok(());
}
}
}
if self.focused == FocusedArea::Content {
if self.content_tab == widgets::content::ContentTab::Logs {
if widgets::logs_viewer::handle_key(&key_event, &mut self.logs_state) {
return Ok(());
}
} else if self.content_tab == widgets::content::ContentTab::Screenshots {
if widgets::screenshots_grid::handle_key(&key_event, &mut self.screenshots_state) {
return Ok(());
}
} else if self.content_tab == widgets::content::ContentTab::Worlds {
if widgets::content_list::handle_key_no_toggle(&key_event, &mut self.worlds_state) {
return Ok(());
}
} else {
let state = match self.content_tab {
widgets::content::ContentTab::Mods => Some(&mut self.mods_state),
widgets::content::ContentTab::ResourcePacks => {
Some(&mut self.resource_packs_state)
}
widgets::content::ContentTab::Shaders => Some(&mut self.shaders_state),
_ => None,
};
if let Some(state) = state {
if widgets::content_list::handle_key(&key_event, state) {
return Ok(());
}
}
}
}
if self.focused == FocusedArea::Account
&& widgets::account::handle_key(&key_event, &mut self.account_state) {
return Ok(());
}
if self.focused == FocusedArea::Settings {
match widgets::details::handle_key(
&key_event,
self.profiles_state.selected_instance(),
&self.instance_manager.instances_dir,
) {
widgets::details::SettingsAction::EditInstance(path)
| widgets::details::SettingsAction::EditGlobal(path) => {
self.pending_editor = Some(path);
return Ok(());
}
widgets::details::SettingsAction::ToggleDesktop => {
if let Some(inst) = self.profiles_state.selected_instance() {
let name = inst.name.clone();
match crate::instance::desktop::toggle(inst) {
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(e) => {
tracing::error!("Failed to toggle desktop shortcut: {}", e);
}
}
}
return Ok(());
}
widgets::details::SettingsAction::None => {}
}
}
match self.focused {
FocusedArea::Popup => {
new_instance::handle_key(&key_event, &mut self.profiles_state);
}
FocusedArea::ImportPopup => {
import_modpack::handle_key(&key_event, &mut self.profiles_state);
}
_ => {
if self.focused == FocusedArea::Profiles && self.profiles_state.renaming.is_some() {
match key_event.code {
KeyCode::Enter => {
let new_name = self.profiles_state.renaming.take().unwrap_or_default();
if let Some(inst) = self.profiles_state.selected_instance() {
let old_name = inst.name.clone();
match self.instance_manager.rename(&old_name, &new_name) {
Ok(()) => {
if let Some(inst) = self
.profiles_state
.instances
.iter_mut()
.find(|i| i.name == old_name)
{
inst.name = new_name.trim().to_string();
}
}
Err(e) => {
tracing::error!("Rename failed: {}", e);
}
}
}
}
KeyCode::Esc => {
self.profiles_state.renaming = None;
}
KeyCode::Backspace => {
if let Some(ref mut name) = self.profiles_state.renaming {
name.pop();
}
}
KeyCode::Char(c) => {
if let Some(ref mut name) = self.profiles_state.renaming {
name.push(c);
}
}
_ => {}
}
return Ok(());
}
if self.focused == FocusedArea::Profiles && self.profiles_state.search.active {
self.profiles_state.handle_key(&key_event);
return Ok(());
}
match key_event.code {
KeyCode::Char('q') => self.exit = true,
KeyCode::Char('P') => self.focused = FocusedArea::Profiles,
KeyCode::Char('C') => self.focused = FocusedArea::Content,
KeyCode::Char('A') => self.focused = FocusedArea::Account,
KeyCode::Char('S') => self.focused = FocusedArea::Settings,
KeyCode::Char('O') => {
self.pre_overlay_focused = self.focused;
self.focused = FocusedArea::OverviewExpanded;
}
KeyCode::Tab | KeyCode::Char('l') | KeyCode::Right
if self.focused == FocusedArea::Content =>
{
self.content_tab = self.content_tab.next();
}
KeyCode::BackTab | KeyCode::Char('h') | KeyCode::Left
if self.focused == FocusedArea::Content =>
{
self.content_tab = self.content_tab.previous();
}
KeyCode::Char('d')
if self.focused == FocusedArea::Profiles
&& !self.profiles_state.search.active =>
{
if let Some(instance) = self.profiles_state.selected_instance() {
let name = instance.name.clone();
confirm_popup::set_pending_delete(&name);
self.focused = FocusedArea::ConfirmDelete;
}
}
KeyCode::Enter
if self.focused == FocusedArea::Profiles
&& !self.profiles_state.search.active
&& key_event.modifiers.contains(KeyModifiers::SHIFT) =>
{
if let Some(instance) = self.profiles_state.selected_instance() {
let dir = self
.instance_manager
.instances_dir
.join(&instance.name)
.join(".minecraft");
if let Err(e) = std::process::Command::new("xdg-open")
.arg(&dir)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
{
tracing::error!("Failed to open instance directory: {}", e);
}
}
}
KeyCode::Enter
if self.focused == FocusedArea::Profiles
&& !self.profiles_state.search.active =>
{
self.focused = FocusedArea::Content;
}
KeyCode::Char('l')
if self.focused == FocusedArea::Profiles
&& !self.profiles_state.search.active =>
{
if let Some(instance) = self.profiles_state.selected_instance().cloned() {
let can_launch = matches!(
crate::running::get(&instance.name),
None | Some(crate::running::RunState::Crashed(_))
);
if can_launch {
crate::running::remove(&instance.name);
crate::instance_logs::clear(&instance.name);
self.spawn_launch(instance);
}
}
}
KeyCode::Char('r')
if self.focused == FocusedArea::Profiles
&& !self.profiles_state.search.active =>
{
if let Some(inst) = self.profiles_state.selected_instance() {
self.profiles_state.renaming = Some(inst.name.clone());
}
}
KeyCode::Esc
if self.focused == FocusedArea::Profiles
&& !self.profiles_state.search.active =>
{
if let Some(instance) = self.profiles_state.selected_instance() {
crate::running::send_kill(&instance.name);
}
}
_ => {}
}
if self.focused == FocusedArea::Profiles {
self.profiles_state.handle_key(&key_event)
}
}
}
if self.profiles_state.wants_popup() {
self.focused = FocusedArea::Popup;
} else if self.focused == FocusedArea::Popup {
self.focused = FocusedArea::Profiles;
}
if self.profiles_state.wants_import_popup() {
self.focused = FocusedArea::ImportPopup;
} else if self.focused == FocusedArea::ImportPopup {
self.focused = FocusedArea::Profiles;
}
Ok(())
}
fn spawn_create(&self, params: new_instance::WizardParams) {
let instances_dir = self.instance_manager.instances_dir.clone();
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
let pending_instances = PENDING_INSTANCES.clone();
tokio::spawn(async move {
progress::set_action(format!("Creating instance '{}'...", params.name));
progress::set_sub_action(format!("{} {}", params.game_version, params.loader));
let manager = InstanceManager::new(instances_dir, meta_dir);
match manager
.create(
&params.name,
&params.game_version,
params.loader,
params.loader_version.as_deref(),
)
.await
{
Ok(config) => match pending_instances.lock() {
Ok(mut pending) => {
pending.push(config);
}
Err(e) => {
tracing::error!("Pending instance queue lock poisoned: {}", e);
}
},
Err(_e) => {
progress::clear();
}
}
});
}
fn spawn_import(&self, result: import_modpack::ImportResult) {
let instances_dir = self.instance_manager.instances_dir.clone();
let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir();
let pending_instances = PENDING_INSTANCES.clone();
tokio::spawn(async move {
let manager = InstanceManager::new(instances_dir, meta_dir);
match crate::instance::import::execute_import(&result.summary, &manager).await {
Ok(config) => match pending_instances.lock() {
Ok(mut pending) => {
pending.push(config);
}
Err(e) => {
tracing::error!("Pending instance queue lock poisoned: {}", e);
}
},
Err(e) => {
tracing::error!("Import failed: {}", e);
crate::tui::progress::clear();
}
}
});
}
fn run_editor(terminal: &mut ratatui::DefaultTerminal, path: &std::path::Path) {
use ratatui::crossterm::{
terminal::{
disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
},
ExecutableCommand,
};
use std::io::stdout;
let editor = std::env::var("EDITOR")
.or_else(|_| std::env::var("VISUAL"))
.unwrap_or_else(|_| "vi".to_string());
let is_tui_editor = matches!(
editor.rsplit('/').next().unwrap_or(&editor),
"vi" | "vim"
| "nvim"
| "neovim"
| "nano"
| "micro"
| "helix"
| "hx"
| "emacs"
| "ne"
| "joe"
| "mcedit"
);
if is_tui_editor {
let _ = stdout().execute(LeaveAlternateScreen);
let _ = disable_raw_mode();
let result = std::process::Command::new(&editor)
.arg(path)
.stdin(std::process::Stdio::inherit())
.stdout(std::process::Stdio::inherit())
.stderr(std::process::Stdio::inherit())
.status();
let _ = stdout().execute(EnterAlternateScreen);
let _ = enable_raw_mode();
let _ = terminal.clear();
if let Err(e) = result {
tracing::error!("Failed to open editor: {}", e);
}
} else {
if let Err(e) = std::process::Command::new(&editor)
.arg(path)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
{
tracing::error!("Failed to open editor: {}", e);
}
}
}
fn spawn_launch(&self, instance: crate::instance::InstanceConfig) {
use crate::instance::launch;
use crate::running;
running::set_state(&instance.name, running::RunState::Authenticating);
let instances_dir = self.instance_manager.instances_dir.clone();
let meta_dir = self.instance_manager.meta_dir.clone();
tokio::spawn(async move {
match launch::launch(&instance, &instances_dir, &meta_dir).await {
Ok(()) => {}
Err(e) => {
tracing::error!("Failed to launch '{}': {}", instance.name, e);
running::remove(&instance.name);
}
}
});
}
fn dismiss_expired_errors(&self) {
use crate::config::SETTINGS;
loop {
match error_buffer::peek_error() {
Some(event)
if event.pushed_at.elapsed().as_millis()
>= SETTINGS.ui.error_auto_dismiss_ms as u128 =>
{
error_buffer::pop_error();
}
_ => break,
}
}
}
fn drain_pending_instances(&mut self) {
match PENDING_INSTANCES.lock() {
Ok(mut pending) => {
for config in pending.drain(..) {
self.profiles_state.add_instance(config);
}
}
Err(e) => {
tracing::error!("Pending instance queue lock poisoned: {}", e);
}
}
}
fn drain_pending_last_played(&mut self) {
for (name, time) in crate::running::drain_last_played() {
for inst in &mut self.profiles_state.instances {
if inst.name == name {
inst.last_played = Some(time);
break;
}
}
}
}
fn create_screenshot_protocols(&mut self) {
let pending = self.screenshots_state.take_pending_images();
for (idx, img) in pending {
let proto = self.picker.new_resize_protocol(img);
self.screenshots_state.set_protocol(idx, proto);
}
}
fn render_log_overlay(&mut self, frame: &mut Frame) {
use crate::tui::logging::get_app_logs;
use crate::tui::theme::THEME;
use ratatui::{
layout::{Alignment, Margin},
style::{Modifier, Style},
text::Line,
widgets::{Block, Clear, Paragraph, Scrollbar, ScrollbarOrientation},
};
let area = frame.area();
let overlay = area.inner(Margin::new(1, 1));
frame.render_widget(Clear, overlay);
let all_lines = get_app_logs();
let filtered: Vec<&String> = all_lines
.iter()
.filter(|l| self.log_overlay_search.matches(l))
.collect();
let visible_height = overlay.height.saturating_sub(2) as usize;
let was_at_bottom =
self.log_overlay_scroll >= self.log_overlay_max_scroll.saturating_sub(1);
self.log_overlay_max_scroll = filtered.len().saturating_sub(visible_height);
if was_at_bottom || self.log_overlay_scroll > self.log_overlay_max_scroll {
self.log_overlay_scroll = self.log_overlay_max_scroll;
}
self.log_overlay_scrollbar =
ratatui::widgets::ScrollbarState::new(self.log_overlay_max_scroll)
.position(self.log_overlay_scroll);
let mut block = Block::bordered()
.title_top(
Line::from(" Logs ").style(
Style::default()
.fg(THEME.log_overlay.text_fg)
.add_modifier(Modifier::BOLD),
),
)
.title_bottom(
crate::tui::widgets::popups::keybind_line(&[("O", " close"), ("/", " search")])
.alignment(Alignment::Right),
)
.border_type(THEME.general.border_type.to_border_type())
.border_style(Style::default().fg(THEME.log_overlay.border_fg));
if let Some(sl) = self.log_overlay_search.title_line() {
block = block.title_top(sl);
}
let inner = block.inner(overlay);
frame.render_widget(block, overlay);
let search = &self.log_overlay_search;
let styled: Vec<Line> = filtered
.iter()
.skip(self.log_overlay_scroll)
.take(visible_height)
.map(|line| {
let style = if line.contains("ERROR") || line.contains("FATAL") {
Style::default().fg(THEME.log_overlay.error_fg)
} else if line.contains("WARN") {
Style::default().fg(THEME.log_overlay.warn_fg)
} else if line.contains("DEBUG") || line.contains("TRACE") {
Style::default().fg(THEME.log_overlay.debug_fg)
} else {
Style::default().fg(THEME.log_overlay.text_fg)
};
search.highlight_line(line, style)
})
.collect();
frame.render_widget(Paragraph::new(styled), inner);
let scrollbar_area = ratatui::layout::Rect {
x: inner.x + inner.width.saturating_sub(1),
y: inner.y + 1,
width: 1,
height: inner.height.saturating_sub(2),
};
frame.render_stateful_widget(
Scrollbar::default()
.orientation(ScrollbarOrientation::VerticalRight)
.begin_symbol(Some("\u{25b2}"))
.style(
Style::default()
.fg(THEME.log_overlay.border_fg)
.add_modifier(Modifier::BOLD),
)
.thumb_symbol("\u{2503}")
.track_symbol(Some(""))
.end_symbol(Some("\u{25bc}")),
scrollbar_area,
&mut self.log_overlay_scrollbar,
);
}
fn sync_error_effects(&mut self, events: &[error_buffer::ErrorEvent]) {
use crate::tui::theme::THEME;
let active_ids: std::collections::HashSet<u64> =
events.iter().map(|event| event.id).collect();
self.error_effects.retain(|id, _| active_ids.contains(id));
for event in events {
self.error_effects.entry(event.id).or_insert_with(|| {
ErrorEffectState::SlidingIn(fx::slide_in(
Motion::RightToLeft,
8,
0,
THEME.log_overlay.bg,
(300, Interpolation::SineOut),
))
});
}
}
fn render_error_effect(
&mut self,
frame: &mut Frame,
area: ratatui::layout::Rect,
event: &error_buffer::ErrorEvent,
elapsed_ms: u128,
) {
use crate::config::SETTINGS;
use crate::tui::theme::THEME;
let fly_out_ms = SETTINGS.ui.error_fly_out_ms as u128;
let fly_start_ms = SETTINGS.ui.error_auto_dismiss_ms as u128
- fly_out_ms.min(SETTINGS.ui.error_auto_dismiss_ms as u128);
if elapsed_ms >= fly_start_ms {
let entry = self
.error_effects
.entry(event.id)
.or_insert(ErrorEffectState::Idle);
if !matches!(entry, ErrorEffectState::FadingOut(_)) {
*entry = ErrorEffectState::FadingOut(fx::slide_out(
Motion::LeftToRight,
8,
0,
THEME.log_overlay.bg,
(fly_out_ms as u32, Interpolation::SineIn),
));
}
}
if let Some(effect_state) = self.error_effects.get_mut(&event.id) {
match effect_state {
ErrorEffectState::SlidingIn(effect) => {
if effect.running() {
frame.render_effect(effect, area, tachyonfx::Duration::from_millis(16));
} else {
*effect_state = ErrorEffectState::Idle;
}
}
ErrorEffectState::Idle => {}
ErrorEffectState::FadingOut(effect) => {
if effect.running() {
frame.render_effect(effect, area, tachyonfx::Duration::from_millis(16));
}
}
}
}
}
}
+3 -3
View File
@@ -8,12 +8,12 @@ use tracing_subscriber::layer::Context;
use tracing_subscriber::prelude::*;
use tracing_subscriber::{EnvFilter, Layer};
use once_cell::sync::Lazy;
use std::sync::LazyLock;
use crate::tui::error_buffer::{self, ErrorEvent};
static APP_LOG_LINES: Lazy<Arc<Mutex<Vec<String>>>> =
Lazy::new(|| Arc::new(Mutex::new(Vec::new())));
static APP_LOG_LINES: LazyLock<Arc<Mutex<Vec<String>>>> =
LazyLock::new(|| Arc::new(Mutex::new(Vec::new())));
pub fn get_app_logs() -> Vec<String> {
APP_LOG_LINES.lock().map(|l| l.clone()).unwrap_or_default()
+5 -3
View File
@@ -1,8 +1,10 @@
pub mod app;
pub mod error_buffer;
pub mod layout;
mod event;
mod input;
pub mod logging;
pub mod progress;
pub mod theme;
mod render;
pub mod widgets;
pub type Tui = ratatui::DefaultTerminal;
@@ -21,7 +23,7 @@ pub async fn show() -> color_eyre::Result<()> {
let picker = ratatui_image::picker::Picker::from_query_stdio()
.unwrap_or_else(|_| ratatui_image::picker::Picker::halfblocks());
let result = layout::App::new(picker).run(&mut terminal).await;
let result = app::App::new(picker).run(&mut terminal).await;
let _ = crossterm::execute!(
std::io::stdout(),
+3 -3
View File
@@ -1,4 +1,4 @@
use once_cell::sync::Lazy;
use std::sync::LazyLock;
use std::sync::{Arc, Mutex};
#[derive(Debug, Default, Clone)]
@@ -11,8 +11,8 @@ pub struct ProgressState {
pub sub_action: Option<String>,
}
pub static PROGRESS: Lazy<Arc<Mutex<ProgressState>>> =
Lazy::new(|| Arc::new(Mutex::new(ProgressState::default())));
pub static PROGRESS: LazyLock<Arc<Mutex<ProgressState>>> =
LazyLock::new(|| Arc::new(Mutex::new(ProgressState::default())));
pub fn set_action(text: impl Into<String>) {
let text = text.into();
+297
View File
@@ -0,0 +1,297 @@
use ratatui::{
layout::{Constraint, Direction, Layout},
Frame,
};
use tachyonfx::{fx, EffectRenderer, Interpolation, Motion};
use super::app::{App, ErrorEffectState, FocusedArea};
use super::widgets::{self, popups::confirm as confirm_popup, popups::import_modpack, popups::new_instance};
use crate::tui::error_buffer;
use crate::tui::widgets::popups::confirm::{confirm_popup_area, ConfirmPopup};
use crate::tui::widgets::popups::error::{popup_area, ErrorPopup};
impl App {
pub(super) fn render_frame(&mut self, frame: &mut Frame) {
use crate::config::theme::THEME;
use ratatui::widgets::Block;
use ratatui::style::Style;
let theme = THEME.as_ref();
frame.render_widget(
Block::default().style(Style::default().bg(theme.background())),
frame.area(),
);
let chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(20),
Constraint::Percentage(80),
])
.split(frame.area());
widgets::instances::render(frame, chunks[0], self.focused, &mut self.instances_state);
let main_chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(3),
Constraint::Min(10),
Constraint::Length(5),
])
.split(chunks[1]);
widgets::content::title(
frame,
main_chunks[0],
self.focused,
self.instances_state.selected_instance(),
&mut self.throbber_state,
);
widgets::content::render(
frame,
main_chunks[1],
self.focused,
self.content_tab,
self.instances_state.selected_instance(),
&mut self.mods_state,
&mut self.resource_packs_state,
&mut self.shaders_state,
&mut self.worlds_state,
&mut self.screenshots_state,
&mut self.logs_state,
&self.instance_manager.instances_dir,
);
let bottom_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage(30),
Constraint::Percentage(40),
Constraint::Percentage(30),
])
.split(main_chunks[2]);
widgets::account::render(
frame,
bottom_chunks[0],
self.focused,
&mut self.account_state,
);
widgets::details::render(
frame,
bottom_chunks[1],
self.focused,
self.instances_state.selected_instance(),
&self.instance_manager.instances_dir,
);
widgets::status::render(
frame,
bottom_chunks[2],
self.focused,
&mut self.throbber_state,
);
if self.focused == FocusedArea::OverviewExpanded {
self.render_log_overlay(frame);
}
let all_errors = error_buffer::peek_all_errors();
self.sync_error_effects(&all_errors);
let mut next_y: u16 = 1;
for event in all_errors {
let elapsed_ms = event.pushed_at.elapsed().as_millis();
if let Some(area) = popup_area(frame.area(), &event.message, next_y, elapsed_ms) {
next_y = next_y.saturating_add(area.height + 1);
frame.render_widget(ErrorPopup::new(event.clone()), area);
self.render_error_effect(frame, area, &event, elapsed_ms);
}
}
if self.instances_state.show_popup {
let area = new_instance::popup_rect(frame.area());
new_instance::render(frame, area, self.focused);
}
if self.instances_state.show_import_popup {
let area = import_modpack::popup_rect(frame.area());
import_modpack::render(frame, area, self.focused);
}
if self.focused == FocusedArea::ConfirmDelete {
let name = confirm_popup::pending_delete_name();
if !name.is_empty() {
let area = confirm_popup_area(frame.area(), &name);
frame.render_widget(ConfirmPopup::new(&name), area);
}
}
}
fn render_log_overlay(&mut self, frame: &mut Frame) {
use crate::config::theme::{THEME, BORDER_STYLE};
use crate::tui::logging::get_app_logs;
use ratatui::{
layout::{Alignment, Margin},
style::{Modifier, Style},
text::Line,
widgets::{Block, Clear, Paragraph, Scrollbar, ScrollbarOrientation},
};
let theme = THEME.as_ref();
let area = frame.area();
let overlay = area.inner(Margin::new(1, 1));
frame.render_widget(Clear, overlay);
let all_lines = get_app_logs();
let filtered: Vec<&String> = all_lines
.iter()
.filter(|l| self.log_overlay_search.matches(l))
.collect();
let visible_height = overlay.height.saturating_sub(2) as usize;
let was_at_bottom =
self.log_overlay_scroll >= self.log_overlay_max_scroll.saturating_sub(1);
self.log_overlay_max_scroll = filtered.len().saturating_sub(visible_height);
if was_at_bottom || self.log_overlay_scroll > self.log_overlay_max_scroll {
self.log_overlay_scroll = self.log_overlay_max_scroll;
}
self.log_overlay_scrollbar =
ratatui::widgets::ScrollbarState::new(self.log_overlay_max_scroll)
.position(self.log_overlay_scroll);
let mut block = Block::bordered()
.title_top(
Line::from(" Logs ").style(
Style::default()
.fg(theme.text())
.add_modifier(Modifier::BOLD),
),
)
.title_bottom(
crate::tui::widgets::popups::keybind_line(&[("O", " close"), ("/", " search")])
.alignment(Alignment::Right),
)
.border_type(BORDER_STYLE.to_border_type())
.border_style(Style::default().fg(theme.accent()));
if let Some(sl) = self.log_overlay_search.title_line() {
block = block.title_top(sl);
}
let inner = block.inner(overlay);
frame.render_widget(block, overlay);
let search = &self.log_overlay_search;
let styled: Vec<Line> = filtered
.iter()
.skip(self.log_overlay_scroll)
.take(visible_height)
.map(|line| {
let style = if line.contains("ERROR") || line.contains("FATAL") {
Style::default().fg(theme.error())
} else if line.contains("WARN") {
Style::default().fg(theme.warning())
} else if line.contains("DEBUG") || line.contains("TRACE") {
Style::default().fg(theme.text_dim())
} else {
Style::default().fg(theme.text())
};
search.highlight_line(line, style)
})
.collect();
frame.render_widget(Paragraph::new(styled), inner);
let scrollbar_area = ratatui::layout::Rect {
x: overlay.x + overlay.width.saturating_sub(1),
y: overlay.y + 1,
width: 1,
height: overlay.height.saturating_sub(2),
};
frame.render_stateful_widget(
Scrollbar::default()
.orientation(ScrollbarOrientation::VerticalRight)
.begin_symbol(Some("\u{25b2}"))
.style(
Style::default()
.fg(theme.text_dim())
.add_modifier(Modifier::BOLD),
)
.thumb_symbol("\u{2551}")
.track_symbol(Some(""))
.end_symbol(Some("\u{25bc}")),
scrollbar_area,
&mut self.log_overlay_scrollbar,
);
}
fn sync_error_effects(&mut self, events: &[error_buffer::ErrorEvent]) {
use crate::config::theme::THEME;
let theme = THEME.as_ref();
let bg = theme.background();
let active_ids: std::collections::HashSet<u64> =
events.iter().map(|event| event.id).collect();
self.error_effects.retain(|id, _| active_ids.contains(id));
for event in events {
self.error_effects.entry(event.id).or_insert_with(|| {
ErrorEffectState::SlidingIn(
fx::slide_in(Motion::RightToLeft, 4, 0, bg, (250, Interpolation::CubicOut)),
std::time::Instant::now(),
)
});
}
}
fn render_error_effect(
&mut self,
frame: &mut Frame,
area: ratatui::layout::Rect,
event: &error_buffer::ErrorEvent,
elapsed_ms: u128,
) {
use crate::config::SETTINGS;
use crate::config::theme::THEME;
let theme = THEME.as_ref();
let bg = theme.background();
let fly_out_ms = SETTINGS.ui.error_fly_out_ms as u128;
let fly_start_ms = SETTINGS.ui.error_auto_dismiss_ms as u128
- fly_out_ms.min(SETTINGS.ui.error_auto_dismiss_ms as u128);
if elapsed_ms >= fly_start_ms {
let entry = self
.error_effects
.entry(event.id)
.or_insert(ErrorEffectState::Idle);
if !matches!(entry, ErrorEffectState::FadingOut(..)) {
*entry = ErrorEffectState::FadingOut(
fx::slide_out(Motion::LeftToRight, 4, 0, bg, (fly_out_ms as u32, Interpolation::CubicIn)),
std::time::Instant::now(),
);
}
}
if let Some(effect_state) = self.error_effects.get_mut(&event.id) {
match effect_state {
ErrorEffectState::SlidingIn(effect, started) => {
let dt = started.elapsed().as_millis() as u32;
if effect.running() {
frame.render_effect(effect, area, tachyonfx::Duration::from_millis(dt.min(32)));
*started = std::time::Instant::now();
} else {
*effect_state = ErrorEffectState::Idle;
}
}
ErrorEffectState::Idle => {}
ErrorEffectState::FadingOut(effect, started) => {
let dt = started.elapsed().as_millis() as u32;
if effect.running() {
frame.render_effect(effect, area, tachyonfx::Duration::from_millis(dt.min(32)));
*started = std::time::Instant::now();
}
}
}
}
}
}
-1611
View File
File diff suppressed because it is too large. Load diff
+68 -55
View File
@@ -3,7 +3,7 @@ use std::sync::{Arc, Mutex};
use crossterm::event::{KeyCode, KeyEvent};
use ratatui::{
layout::Rect,
style::{Color, Modifier, Style},
style::{Modifier, Style},
text::{Line, Span},
widgets::{Block, Borders, Paragraph, Widget},
Frame,
@@ -11,8 +11,8 @@ use ratatui::{
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::auth::{self, AccountStore, AccountType, AuthResult, DeviceCodeInfo};
use crate::tui::layout::FocusedArea;
use crate::tui::theme::THEME;
use crate::tui::app::FocusedArea;
use crate::config::theme::{THEME, BORDER_STYLE};
use super::styled_title;
@@ -213,16 +213,17 @@ pub fn drain_device_code(state: &mut AccountState) {
}
pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut AccountState) {
let theme = THEME.as_ref();
let color = if focused == FocusedArea::Account {
THEME.account.border_focused_fg
theme.accent()
} else {
THEME.account.border_unfocused_fg
theme.border()
};
let mut block = Block::default()
.title(styled_title("Accounts", true))
.borders(Borders::ALL)
.border_type(THEME.general.border_type.to_border_type())
.border_type(BORDER_STYLE.to_border_type())
.border_style(Style::default().fg(color));
if focused == FocusedArea::Account {
@@ -241,7 +242,7 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut A
if state.store.accounts.is_empty() {
frame.render_widget(
Paragraph::new("No accounts.")
.style(Style::default().fg(THEME.account.text_secondary_fg)),
.style(Style::default().fg(theme.text_dim())),
inner,
);
} else {
@@ -282,47 +283,36 @@ fn render_account_list(
let count = accounts.len();
let builder = ListBuilder::new(move |context| {
let theme = THEME.as_ref();
let (username, acc_type, is_active) = &accounts[context.index];
let show_selected = is_focused && context.is_selected;
let stripe_bg = Color::Reset;
let stripe_bg = theme.background();
let bg = if show_selected {
THEME.account.selected_bg
} else {
stripe_bg
};
let bg = stripe_bg;
let active_marker = if *is_active { "\u{25b8} " } else { " " };
let style = if show_selected {
let mut s = Style::default().fg(THEME.account.selected_fg);
if THEME.account.selected_bold {
s = s.add_modifier(Modifier::BOLD);
}
s
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD)
} else if *is_active {
Style::default()
.fg(THEME.account.text_fg)
.fg(theme.text())
.add_modifier(Modifier::BOLD)
} else {
Style::default().fg(THEME.account.text_fg)
Style::default().fg(theme.text())
};
let mut spans = vec![
Span::styled(active_marker, Style::default().fg(THEME.account.active_fg)),
Span::styled(active_marker, Style::default().fg(theme.success())),
Span::styled(username.clone(), style),
];
if *acc_type == AccountType::Offline {
let offline_style = if show_selected {
let mut s = Style::default().fg(THEME.account.selected_fg);
if THEME.account.selected_bold {
s = s.add_modifier(Modifier::BOLD);
}
s
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD)
} else {
Style::default().fg(THEME.account.text_secondary_fg)
Style::default().fg(theme.text_dim())
};
spans.push(Span::styled(" (Offline)", offline_style));
}
@@ -349,42 +339,48 @@ fn popup_area(frame: &Frame, width: u16, height: u16) -> Rect {
fn render_choose_popup(frame: &mut Frame) {
use super::popups::base::PopupFrame;
let theme = THEME.as_ref();
let area = popup_area(frame, 40, 7);
let border_color = theme.text_dim();
let dim_color = theme.text_dim();
let accent_color = theme.success();
let text_color = theme.text();
PopupFrame {
title: Line::from(" Add Account ").centered(),
border_color: THEME.account.border_focused_fg,
border_color,
bg: None,
keybinds: Some(Line::from(Span::styled(
" Esc: cancel ",
Style::default().fg(THEME.account.text_secondary_fg),
Style::default().fg(dim_color),
))),
search_line: None,
content: Box::new(|inner, buf| {
content: Box::new(move |inner, buf| {
let text = vec![
Line::from(""),
Line::from(vec![
Span::styled(
" [m] ",
Style::default()
.fg(THEME.account.active_fg)
.fg(accent_color)
.add_modifier(Modifier::BOLD),
),
Span::styled(
"Microsoft Account",
Style::default().fg(THEME.account.text_fg),
Style::default().fg(text_color),
),
]),
Line::from(vec![
Span::styled(
" [o] ",
Style::default()
.fg(THEME.account.active_fg)
.fg(accent_color)
.add_modifier(Modifier::BOLD),
),
Span::styled(
"Offline Account",
Style::default().fg(THEME.account.text_fg),
Style::default().fg(text_color),
),
]),
];
@@ -396,19 +392,25 @@ fn render_choose_popup(frame: &mut Frame) {
fn render_offline_popup(frame: &mut Frame, name: &str) {
use super::popups::{base::PopupFrame, keybind_line};
let theme = THEME.as_ref();
let area = popup_area(frame, 40, 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(
" Offline Account ",
Style::default()
.fg(THEME.account.border_focused_fg)
.fg(border_color)
.add_modifier(Modifier::BOLD),
))
.centered(),
border_color: THEME.account.border_focused_fg,
bg: Some(THEME.account.popup_bg),
border_color,
bg: Some(bg_color),
keybinds: Some(keybind_line(&[("Enter", " confirm"), ("Esc", " cancel")])),
search_line: None,
content: Box::new(move |inner, buf| {
@@ -416,22 +418,22 @@ fn render_offline_popup(frame: &mut Frame, name: &str) {
Line::from(vec![
Span::styled(
"Username...",
Style::default().fg(THEME.account.border_unfocused_fg),
Style::default().fg(dim_color),
),
Span::styled(
"\u{2588}",
Style::default()
.fg(THEME.account.border_focused_fg)
.fg(border_color)
.add_modifier(Modifier::SLOW_BLINK),
),
])
} else {
Line::from(vec![
Span::styled(name.as_str(), Style::default().fg(THEME.account.text_fg)),
Span::styled(name.as_str(), Style::default().fg(text_color)),
Span::styled(
"\u{2588}",
Style::default()
.fg(THEME.account.border_focused_fg)
.fg(border_color)
.add_modifier(Modifier::SLOW_BLINK),
),
])
@@ -444,6 +446,7 @@ fn render_offline_popup(frame: &mut Frame, name: &str) {
fn render_confirm_delete(frame: &mut Frame, state: &AccountState, idx: usize) {
use super::popups::{base::PopupFrame, keybind_line};
let theme = THEME.as_ref();
let username = state
.store
.accounts
@@ -451,10 +454,11 @@ fn render_confirm_delete(frame: &mut Frame, state: &AccountState, idx: usize) {
.map(|a| a.username.as_str())
.unwrap_or("?");
let border_color = theme.text_dim();
let title = Line::from(Span::styled(
format!(" Delete '{}' ", username),
Style::default()
.fg(THEME.account.border_focused_fg)
.fg(border_color)
.add_modifier(Modifier::BOLD),
));
@@ -462,15 +466,18 @@ fn render_confirm_delete(frame: &mut Frame, state: &AccountState, idx: usize) {
let popup_w = (username.len() + 14).max(body.len() + 2).min(48) as u16 + 2;
let area = popup_area(frame, popup_w, 3);
let bg_color = theme.surface();
let text_color = theme.text();
PopupFrame {
title,
border_color: THEME.account.border_focused_fg,
bg: Some(THEME.account.popup_bg),
border_color,
bg: Some(bg_color),
keybinds: Some(keybind_line(&[("Enter", " confirm")])),
search_line: None,
content: Box::new(|inner, buf| {
content: Box::new(move |inner, buf| {
Paragraph::new("This will permanently remove this account")
.style(Style::default().fg(THEME.account.text_fg))
.style(Style::default().fg(text_color))
.render(inner, buf);
}),
}
@@ -479,57 +486,63 @@ fn render_confirm_delete(frame: &mut Frame, state: &AccountState, idx: usize) {
fn render_device_code_popup(frame: &mut Frame, info: &DeviceCodeInfo) {
use super::popups::{base::PopupFrame, keybind_line};
let theme = THEME.as_ref();
let area = popup_area(frame, 50, 8);
let uri = info.verification_uri.clone();
let code = info.user_code.clone();
let border_color = theme.text_dim();
let bg_color = theme.surface();
let dim_color = theme.text_dim();
let accent_color = theme.success();
PopupFrame {
title: Line::from(Span::styled(
" Microsoft Login ",
Style::default()
.fg(THEME.account.border_focused_fg)
.fg(border_color)
.add_modifier(Modifier::BOLD),
))
.centered(),
border_color: THEME.account.border_focused_fg,
bg: Some(THEME.account.popup_bg),
border_color,
bg: Some(bg_color),
keybinds: Some(keybind_line(&[("Esc", " cancel")])),
search_line: None,
content: Box::new(move |inner, buf| {
let text = if code.is_empty() {
vec![Line::from(Span::styled(
"Connecting to Microsoft...",
Style::default().fg(THEME.account.text_secondary_fg),
Style::default().fg(dim_color),
))]
} else {
vec![
Line::from(Span::styled(
"Open this URL in your browser:",
Style::default().fg(THEME.account.text_secondary_fg),
Style::default().fg(dim_color),
)),
Line::from(Span::styled(
uri.as_str(),
Style::default()
.fg(THEME.account.active_fg)
.fg(accent_color)
.add_modifier(Modifier::BOLD),
)),
Line::from(""),
Line::from(vec![
Span::styled(
"Enter code: ",
Style::default().fg(THEME.account.text_secondary_fg),
Style::default().fg(dim_color),
),
Span::styled(
code.as_str(),
Style::default()
.fg(THEME.account.active_fg)
.fg(accent_color)
.add_modifier(Modifier::BOLD),
),
]),
Line::from(""),
Line::from(Span::styled(
"Waiting for authentication...",
Style::default().fg(THEME.account.text_secondary_fg),
Style::default().fg(dim_color),
)),
]
};
@@ -12,27 +12,29 @@ use ratatui::{
};
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::instance::mods::ModEntry;
use crate::tui::theme::THEME;
use crate::instance::content::mods::{ContentEntry, IconCell};
use crate::config::theme::THEME;
type IconCell = (u8, u8, u8, u8, u8, u8);
type PendingContent = Arc<Mutex<Option<(String, Vec<ModEntry>)>>>;
type PendingContent = Arc<Mutex<Option<(String, Vec<ContentEntry>)>>>;
type SnapshotRow = (String, String, bool, Option<Vec<Vec<IconCell>>>);
struct CachedList {
entries: Vec<ModEntry>,
entries: Vec<ContentEntry>,
selected: Option<usize>,
}
pub struct ContentListState {
pub entries: Vec<ModEntry>,
pub entries: Vec<ContentEntry>,
pub list_state: TuiListState,
pub scrollbar_state: ScrollbarState,
pub loaded_for: Option<String>,
pub loading: bool,
pub search: super::search::SearchState,
pub search: crate::tui::widgets::search::SearchState,
cache: HashMap<String, CachedList>,
pending: PendingContent,
check_counter: u16,
watched_dir: Option<std::path::PathBuf>,
last_dir_mtime: Option<std::time::SystemTime>,
}
impl Default for ContentListState {
@@ -43,14 +45,50 @@ impl Default for ContentListState {
scrollbar_state: ScrollbarState::default(),
loaded_for: None,
loading: false,
search: super::search::SearchState::default(),
search: crate::tui::widgets::search::SearchState::default(),
cache: HashMap::new(),
pending: Arc::new(Mutex::new(None)),
check_counter: 0,
watched_dir: None,
last_dir_mtime: None,
}
}
}
impl ContentListState {
/// Check if the content directory changed (files added/removed).
/// Only triggers a rescan when the directory's modification time differs.
pub fn try_rescan(&mut self) {
self.check_counter = self.check_counter.wrapping_add(1);
// Check every ~2 seconds (120 ticks at 16ms)
if !self.check_counter.is_multiple_of(120) {
return;
}
let Some(dir) = &self.watched_dir else {
return;
};
let current_mtime = std::fs::metadata(dir)
.ok()
.and_then(|m| m.modified().ok());
if current_mtime != self.last_dir_mtime {
self.last_dir_mtime = current_mtime;
// Directory changed — invalidate so next render triggers start_load
if let Some(name) = &self.loaded_for {
self.cache.remove(name);
self.loaded_for = None;
}
}
}
/// Set the directory to watch for changes. Call after start_load.
pub fn watch_dir(&mut self, dir: std::path::PathBuf) {
self.last_dir_mtime = std::fs::metadata(&dir).ok().and_then(|m| m.modified().ok());
self.watched_dir = Some(dir);
}
pub fn filtered_indices(&self) -> Vec<usize> {
self.entries
.iter()
@@ -64,7 +102,7 @@ impl ContentListState {
impl ContentListState {
pub fn start_load<F>(&mut self, instances_dir: &Path, instance_name: &str, scan_fn: F)
where
F: FnOnce(&Path, &str) -> Vec<ModEntry> + Send + 'static,
F: FnOnce(&Path, &str) -> Vec<ContentEntry> + Send + 'static,
{
if let Some(prev) = self.loaded_for.take() {
if !self.entries.is_empty() {
@@ -243,12 +281,7 @@ pub fn handle_key_no_toggle(key_event: &KeyEvent, state: &mut ContentListState)
KeyCode::Enter if key_event.modifiers.contains(KeyModifiers::SHIFT) => {
if let Some(&real_idx) = state.list_state.selected.and_then(|i| filtered.get(i)) {
if let Some(dir) = state.entries[real_idx].path.parent() {
if let Err(e) = std::process::Command::new("xdg-open")
.arg(dir)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
{
if let Err(e) = open::that(dir) {
tracing::error!("Failed to open directory: {}", e);
}
}
@@ -285,12 +318,7 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut ContentListState) -> bool {
KeyCode::Enter if key_event.modifiers.contains(KeyModifiers::SHIFT) => {
if let Some(&real_idx) = state.list_state.selected.and_then(|i| filtered.get(i)) {
if let Some(dir) = state.entries[real_idx].path.parent() {
if let Err(e) = std::process::Command::new("xdg-open")
.arg(dir)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
{
if let Err(e) = open::that(dir) {
tracing::error!("Failed to open directory: {}", e);
}
}
@@ -318,10 +346,11 @@ pub fn render(
loading_text: &str,
empty_text: &str,
) {
let theme = THEME.as_ref();
if state.loading {
frame.render_widget(
Paragraph::new(loading_text)
.style(Style::default().fg(THEME.content_list.text_secondary_fg)),
.style(Style::default().fg(theme.text_dim())),
area,
);
return;
@@ -332,7 +361,7 @@ pub fn render(
if filtered.is_empty() {
frame.render_widget(
Paragraph::new(empty_text)
.style(Style::default().fg(THEME.content_list.text_secondary_fg)),
.style(Style::default().fg(theme.text_dim())),
area,
);
return;
@@ -354,67 +383,57 @@ pub fn render(
.collect();
let builder = ListBuilder::new(move |context| {
let theme = THEME.as_ref();
let (name, description, enabled, icon_pixels) = &snapshot[context.index];
let show_selected = is_focused && context.is_selected;
let use_mc_colors = *enabled && !show_selected;
let use_mc_colors = *enabled;
let stripe_bg = if context.index % 2 == 0 {
Color::Reset
theme.background()
} else {
THEME.content_list.row_alt_bg
theme.stripe()
};
let (name_style, description_style, background) = match (*enabled, show_selected) {
(true, true) => {
let mut ns = Style::default().fg(THEME.content_list.selected_fg);
if THEME.content_list.selected_bold {
ns = ns.add_modifier(Modifier::BOLD);
}
(
ns,
Style::default().fg(THEME.content_list.selected_fg),
THEME.content_list.selected_bg,
)
}
(true, false) => (
Style::default()
.fg(THEME.content_list.text_fg)
.add_modifier(Modifier::BOLD),
Style::default().fg(THEME.content_list.text_secondary_fg),
(true, true) => (
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD),
Style::default().fg(theme.text_dim()),
stripe_bg,
),
(true, false) => (
Style::default()
.fg(theme.text())
.add_modifier(Modifier::BOLD),
Style::default().fg(theme.text_dim()),
stripe_bg,
),
(false, true) => (
Style::default().fg(theme.accent()).add_modifier(Modifier::CROSSED_OUT),
Style::default().fg(theme.text_dim()),
stripe_bg,
),
(false, false) => (
Style::default().fg(theme.text_dim()).add_modifier(Modifier::CROSSED_OUT),
Style::default().fg(theme.text_dim()),
stripe_bg,
),
(false, true) => {
let mut ns = Style::default().fg(THEME.content_list.selected_fg);
if THEME.content_list.disabled_crossed_out {
ns = ns.add_modifier(Modifier::CROSSED_OUT);
}
(
ns,
Style::default().fg(THEME.content_list.selected_fg),
THEME.content_list.selected_bg,
)
}
(false, false) => {
let mut ns = Style::default().fg(THEME.content_list.text_secondary_fg);
if THEME.content_list.disabled_crossed_out {
ns = ns.add_modifier(Modifier::CROSSED_OUT);
}
(
ns,
Style::default().fg(THEME.content_list.text_secondary_fg),
stripe_bg,
)
}
};
let has_icon = icon_pixels.is_some();
let stripped_desc = strip_mc_codes(description);
let has_description = !stripped_desc.trim().is_empty();
let full_desc = strip_mc_codes(description);
let stripped_desc = full_desc.lines().next().unwrap_or("").trim().to_string();
let has_description = !stripped_desc.is_empty();
let compact = !has_icon && !has_description;
let selector = if show_selected {
Span::styled("\u{258c}", Style::default().fg(theme.accent()))
} else {
Span::raw(" ")
};
if compact {
let mut line = Vec::new();
line.push(Span::raw(" "));
line.push(selector.clone());
if use_mc_colors {
line.extend(parse_mc_text(name, name_style));
} else {
@@ -425,9 +444,17 @@ pub fn render(
(item, 1)
} else if has_icon {
let icon_row_count = icon_pixels.as_ref().map(|r| r.len()).unwrap_or(0);
let height = icon_row_count.max(2) as u16;
let text_rows = if has_description { 2 } else { 1 }; // name + optional description
let height = icon_row_count.max(text_rows) as u16;
let mut line_0 = icon_spans(icon_pixels.as_ref(), 0);
let pad = if show_selected {
Span::styled("\u{258c}", Style::default().fg(theme.accent()))
} else {
Span::raw(" ")
};
let mut line_0 = vec![selector.clone()];
line_0.extend(icon_spans(icon_pixels.as_ref(), 0));
line_0.push(Span::raw(" "));
if use_mc_colors {
line_0.extend(parse_mc_text(name, name_style));
@@ -435,41 +462,51 @@ pub fn render(
line_0.push(Span::styled(strip_mc_codes(name), name_style));
}
let mut line_1 = icon_spans(icon_pixels.as_ref(), 1);
line_1.push(Span::raw(" "));
if use_mc_colors {
line_1.extend(parse_mc_text(description, description_style));
} else {
line_1.push(Span::styled(stripped_desc, description_style));
let mut lines = vec![Line::from(line_0)];
if has_description {
let mut row = vec![pad.clone()];
row.extend(icon_spans(icon_pixels.as_ref(), 1));
row.push(Span::raw(" "));
row.push(Span::styled(stripped_desc.clone(), description_style));
lines.push(Line::from(row));
}
let mut lines = vec![Line::from(line_0), Line::from(line_1)];
for r in 2..icon_row_count {
lines.push(Line::from(icon_spans(icon_pixels.as_ref(), r)));
let desc_rows = if has_description { 1 } else { 0 };
for r in (1 + desc_rows)..icon_row_count {
let mut row = vec![pad.clone()];
row.extend(icon_spans(icon_pixels.as_ref(), r));
lines.push(Line::from(row));
}
let item = Text::from(lines).style(Style::default().bg(background));
(item, height)
} else {
let mut line_0 = Vec::new();
line_0.push(Span::raw(" "));
line_0.push(selector.clone());
if use_mc_colors {
line_0.extend(parse_mc_text(name, name_style));
} else {
line_0.push(Span::styled(strip_mc_codes(name), name_style));
}
let mut line_1 = Vec::new();
line_1.push(Span::raw(" "));
if use_mc_colors {
line_1.extend(parse_mc_text(description, description_style));
} else {
line_1.push(Span::styled(stripped_desc, description_style));
let mut lines = vec![Line::from(line_0)];
if has_description {
let pad = if show_selected {
Span::styled("\u{258c}", Style::default().fg(theme.accent()))
} else {
Span::raw(" ")
};
lines.push(Line::from(vec![
pad,
Span::styled(stripped_desc.clone(), description_style),
]));
}
let item = Text::from(vec![Line::from(line_0), Line::from(line_1)])
.style(Style::default().bg(background));
(item, 2)
let height = lines.len() as u16;
let item = Text::from(lines).style(Style::default().bg(background));
(item, height)
}
});
@@ -488,7 +525,7 @@ pub fn render(
.begin_symbol(Some("\u{25b2}"))
.style(
Style::default()
.fg(THEME.content_list.border_focused_fg)
.fg(theme.text_dim())
.add_modifier(Modifier::BOLD),
)
.thumb_symbol("\u{2551}")
@@ -588,18 +625,21 @@ fn icon_spans(icon_pixels: Option<&Vec<Vec<IconCell>>>, row: usize) -> Vec<Span<
match icon_pixels.and_then(|rows| rows.get(row)) {
Some(cols) => cols
.iter()
.map(|&(fg_r, fg_g, fg_b, bg_r, bg_g, bg_b)| {
.map(|cell| {
Span::styled(
"\u{2584}",
Style::default()
.fg(Color::Rgb(fg_r, fg_g, fg_b))
.bg(Color::Rgb(bg_r, bg_g, bg_b)),
.fg(Color::Rgb(cell.fg_r, cell.fg_g, cell.fg_b))
.bg(Color::Rgb(cell.bg_r, cell.bg_g, cell.bg_b)),
)
})
.collect(),
None => vec![Span::styled(
" ",
Style::default().fg(THEME.content_list.text_secondary_fg),
)],
None => {
let theme = THEME.as_ref();
vec![Span::styled(
" ",
Style::default().fg(theme.text_dim()),
)]
}
}
}
+5
View File
@@ -0,0 +1,5 @@
pub mod list;
pub mod tabs;
pub use tabs::{ContentTab, render, title};
pub use list::{ContentListState, handle_key, handle_key_no_toggle};
@@ -7,10 +7,10 @@ use ratatui::{
};
use throbber_widgets_tui::{Throbber, ThrobberState};
use crate::tui::layout::FocusedArea;
use crate::tui::theme::THEME;
use crate::tui::app::FocusedArea;
use crate::config::theme::{THEME, BORDER_STYLE};
use super::styled_title;
use crate::tui::widgets::styled_title;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum ContentTab {
@@ -69,20 +69,21 @@ pub fn render(
focused: FocusedArea,
tab: ContentTab,
instance: Option<&crate::instance::InstanceConfig>,
mods_state: &mut super::content_list::ContentListState,
resource_packs_state: &mut super::content_list::ContentListState,
shaders_state: &mut super::content_list::ContentListState,
worlds_state: &mut super::content_list::ContentListState,
screenshots_state: &mut super::screenshots_grid::ScreenshotsState,
logs_state: &mut super::logs_viewer::LogsState,
mods_state: &mut super::list::ContentListState,
resource_packs_state: &mut super::list::ContentListState,
shaders_state: &mut super::list::ContentListState,
worlds_state: &mut super::list::ContentListState,
screenshots_state: &mut crate::tui::widgets::screenshots_grid::ScreenshotsState,
logs_state: &mut crate::tui::widgets::logs_viewer::LogsState,
instances_dir: &std::path::Path,
) {
let theme = THEME.as_ref();
let is_focused = focused == FocusedArea::Content;
let border_color = if is_focused {
THEME.content.border_focused_fg
theme.accent()
} else {
THEME.content.border_unfocused_fg
theme.border()
};
let tab_titles: Vec<Span> = ContentTab::ALL
@@ -93,21 +94,18 @@ pub fn render(
if i > 0 {
spans.push(Span::styled(
"\u{2022}",
Style::default().fg(THEME.content.border_unfocused_fg),
Style::default().fg(theme.text_dim()),
));
}
if i == tab.index() {
let mut style = Style::default()
.fg(THEME.content.tab_active_fg)
.bg(THEME.content.selected_bg);
if THEME.content.tab_active_bold {
style = style.add_modifier(Modifier::BOLD);
}
let style = Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD);
spans.push(Span::styled(format!(" {} ", t.label()), style));
} else {
spans.push(Span::styled(
format!(" {} ", t.label()),
Style::default().fg(THEME.content.text_fg),
Style::default().fg(theme.text()),
));
}
spans
@@ -132,7 +130,7 @@ pub fn render(
let mut block = Block::default()
.title_top(Line::from(tab_titles))
.borders(Borders::ALL)
.border_type(THEME.general.border_type.to_border_type())
.border_type(BORDER_STYLE.to_border_type())
.border_style(Style::default().fg(border_color));
if let Some(sl) = search_line {
@@ -179,7 +177,7 @@ pub fn render(
}
}
})
} else if focused == FocusedArea::Profiles {
} else if focused == FocusedArea::Instances {
Some(&[
("l", " launch"),
("⏎", " content"),
@@ -196,7 +194,7 @@ pub fn render(
};
if let Some(kb) = kb {
let lines = super::popups::keybind_lines_wrapped(kb, area.width.saturating_sub(2));
let lines = crate::tui::widgets::popups::keybind_lines_wrapped(kb, area.width.saturating_sub(2));
for line in lines {
block = block.title_bottom(line);
}
@@ -214,8 +212,9 @@ pub fn render(
&instance.name,
crate::instance::scan_mods,
);
mods_state.watch_dir(instances_dir.join(&instance.name).join(".minecraft").join("mods"));
}
super::content_list::render(
super::list::render(
frame,
content_area,
mods_state,
@@ -226,7 +225,7 @@ pub fn render(
} else {
frame.render_widget(
Paragraph::new("No instance selected.")
.style(Style::default().fg(THEME.content.tab_inactive_fg)),
.style(Style::default().fg(theme.text_dim())),
content_area,
);
}
@@ -239,8 +238,9 @@ pub fn render(
&instance.name,
crate::instance::scan_resource_packs,
);
resource_packs_state.watch_dir(instances_dir.join(&instance.name).join(".minecraft").join("resourcepacks"));
}
super::content_list::render(
super::list::render(
frame,
content_area,
resource_packs_state,
@@ -251,7 +251,7 @@ pub fn render(
} else {
frame.render_widget(
Paragraph::new("No instance selected.")
.style(Style::default().fg(THEME.content.tab_inactive_fg)),
.style(Style::default().fg(theme.text_dim())),
content_area,
);
}
@@ -264,8 +264,9 @@ pub fn render(
&instance.name,
crate::instance::scan_shaders,
);
shaders_state.watch_dir(instances_dir.join(&instance.name).join(".minecraft").join("shaderpacks"));
}
super::content_list::render(
super::list::render(
frame,
content_area,
shaders_state,
@@ -276,7 +277,7 @@ pub fn render(
} else {
frame.render_widget(
Paragraph::new("No instance selected.")
.style(Style::default().fg(THEME.content.tab_inactive_fg)),
.style(Style::default().fg(theme.text_dim())),
content_area,
);
}
@@ -286,11 +287,11 @@ pub fn render(
if logs_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
logs_state.start_load(instances_dir, &instance.name);
}
super::logs_viewer::render(frame, content_area, logs_state, is_focused);
crate::tui::widgets::logs_viewer::render(frame, content_area, logs_state, is_focused);
} else {
frame.render_widget(
Paragraph::new("No instance selected.")
.style(Style::default().fg(THEME.content.tab_inactive_fg)),
.style(Style::default().fg(theme.text_dim())),
content_area,
);
}
@@ -300,11 +301,11 @@ pub fn render(
if screenshots_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
screenshots_state.start_load(instances_dir, &instance.name);
}
super::screenshots_grid::render(frame, content_area, screenshots_state, is_focused);
crate::tui::widgets::screenshots_grid::render(frame, content_area, screenshots_state, is_focused);
} else {
frame.render_widget(
Paragraph::new("No instance selected.")
.style(Style::default().fg(THEME.content.tab_inactive_fg)),
.style(Style::default().fg(theme.text_dim())),
content_area,
);
}
@@ -317,8 +318,9 @@ pub fn render(
&instance.name,
crate::instance::scan_worlds,
);
worlds_state.watch_dir(instances_dir.join(&instance.name).join(".minecraft").join("saves"));
}
super::content_list::render(
super::list::render(
frame,
content_area,
worlds_state,
@@ -329,7 +331,7 @@ pub fn render(
} else {
frame.render_widget(
Paragraph::new("No instance selected.")
.style(Style::default().fg(THEME.content.tab_inactive_fg)),
.style(Style::default().fg(theme.text_dim())),
content_area,
);
}
@@ -344,16 +346,17 @@ pub fn title(
instance: Option<&crate::instance::InstanceConfig>,
throbber_state: &mut ThrobberState,
) {
let theme = THEME.as_ref();
let color = if focused == FocusedArea::Content {
THEME.content.border_focused_fg
theme.accent()
} else {
THEME.content.border_unfocused_fg
theme.border()
};
let block = Block::default()
.title(styled_title("Content", true))
.borders(Borders::ALL)
.border_type(THEME.general.border_type.to_border_type())
.border_type(BORDER_STYLE.to_border_type())
.border_style(Style::default().fg(color));
let inner = block.inner(area);
@@ -363,7 +366,7 @@ pub fn title(
None => {
frame.render_widget(
Paragraph::new("No instance selected")
.style(Style::default().fg(THEME.content.tab_inactive_fg)),
.style(Style::default().fg(theme.text_dim())),
inner,
);
}
@@ -382,12 +385,12 @@ pub fn title(
.label(inst.name.as_str())
.style(
Style::default()
.fg(THEME.content.text_fg)
.fg(theme.text())
.add_modifier(Modifier::BOLD),
)
.throbber_style(
Style::default()
.fg(THEME.general.success)
.fg(theme.success())
.add_modifier(Modifier::BOLD),
)
.throbber_set(throbber_widgets_tui::BRAILLE_EIGHT_DOUBLE)
@@ -400,13 +403,13 @@ pub fn title(
Span::styled(
"\u{2717} ",
Style::default()
.fg(THEME.general.error)
.fg(theme.error())
.add_modifier(Modifier::BOLD),
),
Span::styled(
inst.name.as_str(),
Style::default()
.fg(THEME.content.text_fg)
.fg(theme.text())
.add_modifier(Modifier::BOLD),
),
])),
@@ -418,7 +421,7 @@ pub fn title(
Paragraph::new(Span::styled(
inst.name.as_str(),
Style::default()
.fg(THEME.content.text_fg)
.fg(theme.text())
.add_modifier(Modifier::BOLD),
)),
left_area,
@@ -432,7 +435,7 @@ pub fn title(
};
frame.render_widget(
Paragraph::new(loader_str)
.style(Style::default().fg(THEME.content.border_focused_fg))
.style(Style::default().fg(theme.text_dim()))
.alignment(Alignment::Right),
right_area,
);
+10 -9
View File
@@ -7,8 +7,8 @@ use ratatui::{
};
use crate::instance::models::InstanceConfig;
use crate::tui::layout::FocusedArea;
use crate::tui::theme::THEME;
use crate::tui::app::FocusedArea;
use crate::config::theme::{THEME, BORDER_STYLE};
use super::styled_title;
@@ -19,16 +19,17 @@ pub fn render(
instance: Option<&InstanceConfig>,
_instances_dir: &std::path::Path,
) {
let theme = THEME.as_ref();
let color = if focused == FocusedArea::Settings {
THEME.details.border_focused_fg
theme.accent()
} else {
THEME.details.border_unfocused_fg
theme.border()
};
let mut block = Block::default()
.title(styled_title("Settings", true))
.borders(Borders::ALL)
.border_type(THEME.general.border_type.to_border_type())
.border_type(BORDER_STYLE.to_border_type())
.border_style(Style::default().fg(color));
if focused == FocusedArea::Settings {
@@ -51,17 +52,17 @@ pub fn render(
let Some(inst) = instance else {
frame.render_widget(
Paragraph::new("No instance selected.")
.style(Style::default().fg(THEME.details.label_fg)),
.style(Style::default().fg(theme.text_dim())),
inner,
);
return;
};
let label_style = Style::default().fg(THEME.details.label_fg);
let label_style = Style::default().fg(theme.text_dim());
let value_style = Style::default()
.fg(THEME.details.value_fg)
.fg(theme.text())
.add_modifier(Modifier::BOLD);
let dim_style = Style::default().fg(THEME.details.border_unfocused_fg);
let dim_style = Style::default().fg(theme.text_dim());
let memory_min = inst.memory_min.as_deref().unwrap_or("512M");
let memory_max = inst.memory_max.as_deref().unwrap_or("2G");
@@ -1,4 +1,4 @@
use crate::tui::theme::THEME;
use crate::config::theme::{THEME, BORDER_STYLE};
use crossterm::event::KeyCode;
use ratatui::{
layout::Rect,
@@ -11,7 +11,7 @@ use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::instance::models::InstanceConfig;
use crate::running::{get as get_run_state, RunState};
use crate::tui::layout::FocusedArea;
use crate::tui::app::FocusedArea;
use super::{search::SearchState, styled_title, WidgetKey};
@@ -33,17 +33,6 @@ fn format_last_played(last_played: Option<chrono::DateTime<chrono::Utc>>) -> Str
}
}
fn loader_color(loader: crate::instance::models::ModLoader) -> ratatui::style::Color {
use crate::instance::models::ModLoader;
match loader {
ModLoader::Vanilla => THEME.profiles.loader_vanilla,
ModLoader::Fabric => THEME.profiles.loader_fabric,
ModLoader::Forge => THEME.profiles.loader_forge,
ModLoader::NeoForge => THEME.profiles.loader_neoforge,
ModLoader::Quilt => THEME.profiles.loader_quilt,
}
}
#[derive(Debug, Default)]
pub struct State {
pub instances: Vec<InstanceConfig>,
@@ -202,16 +191,17 @@ impl WidgetKey for State {
}
pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut State) {
let color = if focused == FocusedArea::Profiles {
THEME.profiles.border_focused_fg
let theme = THEME.as_ref();
let color = if focused == FocusedArea::Instances {
theme.accent()
} else {
THEME.profiles.border_unfocused_fg
theme.border()
};
let mut block = Block::default()
.title(styled_title("Profiles", true))
.title(styled_title("Instances", true))
.borders(Borders::ALL)
.border_type(THEME.general.border_type.to_border_type())
.border_type(BORDER_STYLE.to_border_type())
.border_style(Style::default().fg(color));
if let Some(search_line) = state.search.title_line() {
@@ -229,56 +219,54 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
let count = filtered.len();
let builder = ListBuilder::new(|context| {
let theme = THEME.as_ref();
let idx = filtered[context.index];
let instance = &state.instances[idx];
let stripe_bg = if context.index % 2 == 0 {
THEME.general.bg
theme.background()
} else {
THEME.profiles.row_alt_bg
theme.stripe()
};
let (name_style, meta_style, bg) = if context.is_selected {
let mut style = Style::default().fg(THEME.profiles.selected_fg);
if THEME.profiles.selected_bold {
style = style.add_modifier(Modifier::BOLD);
}
(
style,
Style::default().fg(THEME.profiles.selected_fg),
THEME.profiles.selected_bg,
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD),
Style::default().fg(theme.text_dim()),
stripe_bg,
)
} else {
(
Style::default()
.fg(THEME.profiles.border_focused_fg)
.fg(theme.text())
.add_modifier(Modifier::BOLD),
Style::default().fg(THEME.profiles.border_unfocused_fg),
Style::default().fg(theme.text_dim()),
stripe_bg,
)
};
let stripe = Span::styled(
"\u{258c} ",
Style::default().fg(loader_color(instance.loader)),
);
let selector = if context.is_selected {
Span::styled("\u{258c} ", Style::default().fg(theme.accent()))
} else {
Span::raw(" ")
};
let is_renaming = context.is_selected && state.renaming.is_some();
let name_line = if is_renaming {
let rename_val = state.renaming.as_deref().unwrap_or("");
Line::from(vec![
stripe.clone(),
Span::styled(rename_val, Style::default().fg(THEME.profiles.text_fg)),
selector.clone(),
Span::styled(rename_val, Style::default().fg(theme.text())),
Span::styled(
"\u{2588}",
Style::default()
.fg(THEME.profiles.border_focused_fg)
.fg(theme.text_dim())
.add_modifier(Modifier::SLOW_BLINK),
),
])
} else {
Line::from(vec![
stripe.clone(),
selector.clone(),
Span::styled(instance.name.as_str(), name_style),
])
};
@@ -286,16 +274,16 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
let (meta_text, meta_text_style) = match get_run_state(&instance.name) {
Some(RunState::Authenticating) => (
"Authenticating".to_string(),
Style::default().fg(THEME.profiles.running_fg),
Style::default().fg(theme.success()),
),
Some(RunState::Running) | Some(RunState::Starting) => (
"Playing".to_string(),
Style::default().fg(THEME.profiles.running_fg),
Style::default().fg(theme.success()),
),
_ => (format_last_played(instance.last_played), meta_style),
};
let meta_line = Line::from(vec![stripe, Span::styled(meta_text, meta_text_style)]);
let meta_line = Line::from(vec![selector.clone(), Span::styled(meta_text, meta_text_style)]);
let item = Text::from(vec![name_line, meta_line]).style(Style::default().bg(bg));
(item, 2)
@@ -311,7 +299,7 @@ pub fn render(frame: &mut Frame, area: Rect, focused: FocusedArea, state: &mut S
.begin_symbol(Some("\u{25b2}"))
.style(
Style::default()
.fg(THEME.profiles.border_focused_fg)
.fg(theme.text_dim())
.add_modifier(Modifier::BOLD),
)
.thumb_symbol("\u{2551}")
+31 -36
View File
@@ -4,7 +4,7 @@ use std::sync::{Arc, Mutex};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::{
layout::{Constraint, Layout, Rect},
style::{Color, Modifier, Style},
style::{Modifier, Style},
text::{Line, Span},
widgets::{Block, Borders, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState},
Frame,
@@ -12,7 +12,7 @@ use ratatui::{
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::instance::log_files::{read_log_file, scan_log_files, LogFileEntry};
use crate::tui::theme::THEME;
use crate::config::theme::{THEME, BORDER_STYLE};
type PendingLogs = Arc<Mutex<Option<(String, Vec<LogFileEntry>)>>>;
@@ -342,9 +342,10 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut LogsState) -> bool {
}
pub fn render(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused: bool) {
let theme = THEME.as_ref();
if state.loading {
frame.render_widget(
Paragraph::new("Loading logs...").style(Style::default().fg(THEME.logs.text_fg)),
Paragraph::new("Loading logs...").style(Style::default().fg(theme.text_dim())),
area,
);
return;
@@ -355,7 +356,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut LogsState, is_focused:
if display_count == 0 {
frame.render_widget(
Paragraph::new("No logs yet.").style(Style::default().fg(THEME.logs.text_fg)),
Paragraph::new("No logs yet.").style(Style::default().fg(theme.text_dim())),
area,
);
return;
@@ -380,16 +381,17 @@ fn render_list(
is_focused: bool,
has_live: bool,
) {
let theme = THEME.as_ref();
let list_focused = is_focused && !state.viewer_focused;
let border_color = if list_focused {
THEME.logs.border_focused_fg
theme.accent()
} else {
THEME.logs.border_unfocused_fg
theme.border()
};
let block = Block::default()
.borders(Borders::RIGHT)
.border_type(THEME.general.border_type.to_border_type())
.border_type(BORDER_STYLE.to_border_type())
.border_style(Style::default().fg(border_color));
let inner = block.inner(area);
@@ -413,34 +415,27 @@ fn render_list(
let show_selected = list_focused && context.is_selected;
let style = if *is_live && show_selected {
let s = Style::default().fg(THEME.logs.running_fg);
if THEME.logs.selected_bold {
s.add_modifier(Modifier::BOLD)
} else {
s
}
Style::default().fg(theme.success()).add_modifier(Modifier::BOLD)
} else if *is_live {
Style::default().fg(THEME.logs.running_fg)
Style::default().fg(theme.success())
} else if show_selected {
let s = Style::default().fg(THEME.logs.selected_fg);
if THEME.logs.selected_bold {
s.add_modifier(Modifier::BOLD)
} else {
s
}
Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD)
} else {
Style::default().fg(THEME.logs.text_fg)
Style::default().fg(theme.text())
};
let bg = if show_selected {
THEME.logs.selected_bg
} else if context.index % 2 == 0 {
Color::Reset
let bg = if context.index % 2 == 0 {
theme.background()
} else {
THEME.logs.row_alt_bg
theme.stripe()
};
let item = ratatui::text::Text::from(Line::from(Span::styled(name.clone(), style)))
let selector = if show_selected {
Span::styled("\u{258c} ", Style::default().fg(theme.accent()))
} else {
Span::raw(" ")
};
let item = ratatui::text::Text::from(Line::from(vec![selector, Span::styled(name.clone(), style)]))
.style(Style::default().bg(bg));
(item, 1)
});
@@ -460,7 +455,7 @@ fn render_list(
.begin_symbol(Some("\u{25b2}"))
.style(
Style::default()
.fg(THEME.logs.border_focused_fg)
.fg(theme.accent())
.add_modifier(Modifier::BOLD),
)
.thumb_symbol("\u{2551}")
@@ -478,6 +473,7 @@ fn render_viewer(
_is_focused: bool,
has_live: bool,
) {
let theme = THEME.as_ref();
let is_live = has_live && state.list_state.selected == Some(0);
let all_lines: Vec<String> = if is_live {
@@ -528,7 +524,7 @@ fn render_viewer(
.begin_symbol(Some("\u{25b2}"))
.style(
Style::default()
.fg(THEME.logs.border_focused_fg)
.fg(theme.accent())
.add_modifier(Modifier::BOLD),
)
.thumb_symbol("\u{2551}")
@@ -540,16 +536,15 @@ fn render_viewer(
}
fn line_level_style(line: &str) -> Style {
let theme = THEME.as_ref();
let upper = line.to_uppercase();
if upper.contains("ERROR") || upper.contains("FATAL") || upper.contains("[STDERR]") {
Style::default().fg(THEME.logs.error_fg)
Style::default().fg(theme.error())
} else if upper.contains("WARN") {
Style::default().fg(THEME.logs.warn_fg)
} else if upper.contains("DEBUG") {
Style::default().fg(THEME.logs.debug_fg)
} else if upper.contains("TRACE") {
Style::default().fg(THEME.logs.trace_fg)
Style::default().fg(theme.warning())
} else if upper.contains("DEBUG") || upper.contains("TRACE") {
Style::default().fg(theme.text_dim())
} else {
Style::default().fg(THEME.logs.text_fg)
Style::default().fg(theme.text())
}
}
+5 -5
View File
@@ -1,4 +1,4 @@
use crate::tui::theme::THEME;
use crate::config::theme::THEME;
use crossterm::event::KeyEvent;
use ratatui::{
style::Style,
@@ -7,16 +7,16 @@ use ratatui::{
pub mod account;
pub mod content;
pub mod content_list;
pub mod details;
pub mod logs_viewer;
pub mod popups;
pub mod profiles;
pub mod instances;
pub mod screenshots_grid;
pub mod search;
pub mod status;
pub fn styled_title(title: &str, highlight: bool) -> Line<'_> {
let theme = THEME.as_ref();
if !highlight || title.is_empty() {
Line::from(Span::raw(title))
} else {
@@ -24,8 +24,8 @@ pub fn styled_title(title: &str, highlight: bool) -> Line<'_> {
let first = chars.next().unwrap_or_default().to_string();
let rest: String = chars.collect();
Line::from(vec![
Span::styled(first, Style::default().fg(THEME.general.accent)),
Span::raw(rest),
Span::styled(first, Style::default().fg(theme.accent())),
Span::styled(rest, Style::default().fg(theme.text())),
])
}
}
+2 -2
View File
@@ -6,7 +6,7 @@ use ratatui::{
widgets::{Block, Clear, Widget},
};
use crate::tui::theme::THEME;
use crate::config::theme::BORDER_STYLE;
type ContentFn<'a> = Box<dyn Fn(Rect, &mut Buffer) + 'a>;
@@ -29,7 +29,7 @@ impl<'a> Widget for PopupFrame<'a> {
let mut block = Block::bordered()
.title_top(self.title)
.border_type(THEME.general.border_type.to_border_type())
.border_type(BORDER_STYLE.to_border_type())
.border_style(Style::default().fg(self.border_color));
if let Some(sl) = self.search_line {
+12 -8
View File
@@ -1,4 +1,4 @@
use once_cell::sync::Lazy;
use std::sync::LazyLock;
use std::sync::Mutex;
use ratatui::{
@@ -9,9 +9,9 @@ use ratatui::{
widgets::{Paragraph, Widget},
};
use crate::tui::theme::THEME;
use crate::config::theme::THEME;
static CONFIRM_STATE: Lazy<Mutex<ConfirmState>> = Lazy::new(|| Mutex::new(ConfirmState::default()));
static CONFIRM_STATE: LazyLock<Mutex<ConfirmState>> = LazyLock::new(|| Mutex::new(ConfirmState::default()));
#[derive(Debug, Default)]
struct ConfirmState {
@@ -63,23 +63,27 @@ impl Widget for ConfirmPopup {
fn render(self, area: Rect, buf: &mut Buffer) {
use super::{base::PopupFrame, keybind_line};
let theme = THEME.as_ref();
let title = Line::from(vec![Span::styled(
format!(" Delete '{}' ", self.instance_name),
Style::default()
.fg(THEME.popup_confirm.border_fg)
.fg(theme.text_dim())
.add_modifier(Modifier::BOLD),
)]);
let kb = keybind_line(&[("Enter", " confirm")]);
let border_color = theme.text_dim();
let bg_color = theme.surface();
let text_color = theme.text();
let popup = PopupFrame {
title,
border_color: THEME.popup_confirm.border_fg,
bg: Some(THEME.popup_confirm.highlight_bg),
border_color,
bg: Some(bg_color),
keybinds: Some(kb),
search_line: None,
content: Box::new(|inner, buf| {
content: Box::new(move |inner, buf| {
Paragraph::new("This will permanently remove the instance")
.style(Style::default().fg(THEME.popup_confirm.text_fg))
.style(Style::default().fg(text_color))
.render(inner, buf);
}),
};
+10 -7
View File
@@ -10,7 +10,7 @@ use tracing::Level;
use super::base::PopupFrame;
use crate::config::SETTINGS;
use crate::tui::error_buffer::ErrorEvent;
use crate::tui::theme::THEME;
use crate::config::theme::THEME;
pub struct ErrorPopup {
pub event: ErrorEvent,
@@ -24,31 +24,34 @@ impl ErrorPopup {
impl Widget for ErrorPopup {
fn render(self, area: Rect, buf: &mut Buffer) {
let theme = THEME.as_ref();
let (border_color, label) = match self.event.level {
Level::ERROR => (THEME.popup_error.error_fg, "ERROR"),
Level::WARN => (THEME.popup_error.warn_fg, "WARN"),
_ => (THEME.popup_error.border_fg, "INFO"),
Level::ERROR => (theme.error(), "ERROR"),
Level::WARN => (theme.warning(), "WARN"),
_ => (theme.text_dim(), "INFO"),
};
let title = Line::from(vec![Span::styled(
format!(" {} ", label),
Style::default()
.fg(THEME.popup_error.badge_text_fg)
.fg(theme.text_bright())
.bg(border_color)
.add_modifier(Modifier::BOLD),
)]);
let message = self.event.message.clone();
let text_color = theme.text();
let bg_color = theme.surface();
let popup = PopupFrame {
title,
border_color,
bg: Some(THEME.popup_error.bg),
bg: Some(bg_color),
keybinds: None,
search_line: None,
content: Box::new(move |inner, buf| {
Paragraph::new(message.as_str())
.wrap(Wrap { trim: true })
.style(Style::default().fg(THEME.popup_error.text_fg))
.style(Style::default().fg(text_color))
.render(inner, buf);
}),
};
@@ -0,0 +1,5 @@
mod render;
mod state;
pub use render::{popup_rect, render};
pub use state::{handle_key, take_result, ImportResult, ImportStep, ImportWizardState};
@@ -0,0 +1,254 @@
use super::super::base::PopupFrame;
use super::super::new_instance::LoadState;
use super::state::{ImportStep, ImportWizardState, IMPORT_STATE};
use crate::tui::app::FocusedArea;
use crate::config::theme::THEME;
use ratatui::{
layout::{Constraint, Direction, Layout, Rect},
style::{Modifier, Style},
text::{Line, Span},
widgets::{List, ListItem, ListState, Paragraph, StatefulWidget, Widget, Wrap},
Frame,
};
pub fn render(frame: &mut Frame, area: Rect, _focused: FocusedArea) {
let snapshot = match IMPORT_STATE.lock() {
Ok(state) => state.clone(),
Err(e) => {
tracing::error!("Import state lock poisoned: {}", e);
ImportWizardState::default()
}
};
let keybinds = step_keybinds(&snapshot);
let search_line = if snapshot.step == ImportStep::Version {
snapshot.version_search.title_line()
} else {
None
};
let theme = THEME.as_ref();
let popup = PopupFrame {
title: wizard_title(&snapshot),
border_color: theme.text_dim(),
bg: Some(theme.surface()),
keybinds: Some(keybinds),
search_line,
content: Box::new(move |popup_area, buf| {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Min(1)])
.split(popup_area);
match snapshot.step {
ImportStep::Input => render_input_step(&snapshot, chunks[0], buf),
ImportStep::Fetching => render_fetching_step(chunks[0], buf),
ImportStep::Version => render_version_step(&snapshot, chunks[0], buf),
ImportStep::Confirm => render_confirm_step(&snapshot, chunks[0], buf),
}
}),
};
frame.render_widget(popup, area);
}
pub fn popup_rect(frame_area: Rect) -> Rect {
let w = Constraint::Percentage(50);
let step = match IMPORT_STATE.lock() {
Ok(s) => s.step.clone(),
Err(_) => ImportStep::Input,
};
match step {
ImportStep::Input => {
let h = 8u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
ImportStep::Fetching => {
let h = 5u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
ImportStep::Version => {
let h = (frame_area.height * 2 / 3)
.max(10)
.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
ImportStep::Confirm => {
let h = 10u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
}
}
fn render_input_step(
state: &ImportWizardState,
area: Rect,
buf: &mut ratatui::buffer::Buffer,
) {
let theme = THEME.as_ref();
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(1),
Constraint::Length(1),
Constraint::Min(0),
])
.split(area);
let input_line = if state.input.is_empty() {
Line::from(vec![
Span::styled(
"URL, slug, or .mrpack path...",
Style::default().fg(theme.text_dim()),
),
Span::styled(
"\u{2588}",
Style::default()
.fg(theme.text_dim())
.add_modifier(Modifier::SLOW_BLINK),
),
])
} else {
Line::from(vec![
Span::styled(
state.input.clone(),
Style::default().fg(theme.text()),
),
Span::styled(
"\u{2588}",
Style::default()
.fg(theme.text_dim())
.add_modifier(Modifier::SLOW_BLINK),
),
])
};
Paragraph::new(input_line).render(chunks[0], buf);
}
fn render_fetching_step(area: Rect, buf: &mut ratatui::buffer::Buffer) {
let theme = THEME.as_ref();
Paragraph::new("Fetching modpack info...")
.style(Style::default().fg(theme.text_dim()))
.render(area, buf);
}
fn render_version_step(
state: &ImportWizardState,
area: Rect,
buf: &mut ratatui::buffer::Buffer,
) {
let theme = THEME.as_ref();
match &state.versions {
LoadState::Idle | LoadState::Loading => {
Paragraph::new("Loading versions...")
.style(Style::default().fg(theme.text_dim()))
.render(area, buf);
}
LoadState::Error(message) => {
Paragraph::new(message.as_str())
.wrap(Wrap { trim: true })
.style(Style::default().fg(theme.error()))
.render(area, buf);
}
LoadState::Loaded(_) => {
let items: Vec<ListItem> = super::state::visible_versions(state)
.into_iter()
.map(|version| {
let game_ver = version.game_versions.first().cloned().unwrap_or_default();
let loader = version.loaders.first().cloned().unwrap_or_default();
ListItem::new(Line::from(Span::styled(
format!("{} {} {}", version.version_number, game_ver, loader),
Style::default().fg(theme.text()),
)))
})
.collect();
let list = List::new(items)
.highlight_style(
Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD),
)
.highlight_symbol("\u{25b6} ");
let mut list_state = ListState::default().with_selected(Some(state.version_idx));
StatefulWidget::render(list, area, buf, &mut list_state);
}
}
}
fn render_confirm_step(
state: &ImportWizardState,
area: Rect,
buf: &mut ratatui::buffer::Buffer,
) {
let theme = THEME.as_ref();
let summary = match &state.summary {
Some(s) => s,
None => {
Paragraph::new("No summary available")
.style(Style::default().fg(theme.text_dim()))
.render(area, buf);
return;
}
};
let label_style = Style::default().fg(theme.text_dim());
let loader_display = if let Some(ref lv) = summary.loader_version {
format!("{} {}", summary.loader, lv)
} else {
summary.loader.to_string()
};
Paragraph::new(vec![
Line::from(vec![
Span::styled("Name: ", label_style),
Span::raw(summary.name.clone()),
]),
Line::from(vec![
Span::styled("Pack Version: ", label_style),
Span::raw(summary.pack_version.clone()),
]),
Line::from(vec![
Span::styled("MC Version: ", label_style),
Span::raw(summary.game_version.clone()),
]),
Line::from(vec![
Span::styled("Loader: ", label_style),
Span::raw(loader_display),
]),
Line::from(vec![
Span::styled("Mods: ", label_style),
Span::raw(format!("{} files", summary.mod_count)),
]),
Line::from(vec![
Span::styled("Overrides: ", label_style),
Span::raw(format!("{} files", summary.override_count)),
]),
])
.style(Style::default().fg(theme.text()))
.wrap(Wrap { trim: true })
.render(area, buf);
}
fn wizard_title(_state: &ImportWizardState) -> Line<'static> {
use crate::tui::widgets::styled_title;
styled_title("Import Modpack", false)
}
fn step_keybinds(state: &ImportWizardState) -> Line<'static> {
use super::super::keybind_line;
match state.step {
ImportStep::Input => keybind_line(&[("Enter", " fetch")]),
ImportStep::Fetching => keybind_line(&[("Esc", " cancel")]),
ImportStep::Version => keybind_line(&[
("/", " search"),
("h", " back"),
("Enter", " select"),
]),
ImportStep::Confirm => keybind_line(&[("h", " back"), ("Enter", " import")]),
}
}
@@ -1,28 +1,18 @@
use super::base::PopupFrame;
use super::new_instance::LoadState;
use super::super::new_instance::LoadState;
use crate::instance::import::ImportSummary;
use crate::net::modrinth::{self, ModrinthInput, VersionInfo};
use crate::tui::layout::FocusedArea;
use crate::tui::theme::THEME;
use crate::tui::widgets::profiles;
use crate::tui::widgets::instances;
use crate::tui::widgets::search::SearchState;
use crossterm::event::{KeyCode, KeyEvent};
use once_cell::sync::Lazy;
use ratatui::{
layout::{Constraint, Direction, Layout, Rect},
style::{Modifier, Style},
text::{Line, Span},
widgets::{List, ListItem, ListState, Paragraph, StatefulWidget, Widget, Wrap},
Frame,
};
use std::sync::LazyLock;
use std::sync::{Arc, Mutex};
use std::time::Instant;
use tracing::Level;
static IMPORT_STATE: Lazy<Arc<Mutex<ImportWizardState>>> =
Lazy::new(|| Arc::new(Mutex::new(ImportWizardState::default())));
static IMPORT_RESULT: Lazy<Arc<Mutex<Option<ImportResult>>>> =
Lazy::new(|| Arc::new(Mutex::new(None)));
pub(super) static IMPORT_STATE: LazyLock<Arc<Mutex<ImportWizardState>>> =
LazyLock::new(|| Arc::new(Mutex::new(ImportWizardState::default())));
pub(super) static IMPORT_RESULT: LazyLock<Arc<Mutex<Option<ImportResult>>>> =
LazyLock::new(|| Arc::new(Mutex::new(None)));
#[derive(Debug, Clone)]
pub struct ImportResult {
@@ -69,91 +59,21 @@ impl ImportWizardState {
}
}
pub fn render(frame: &mut Frame, area: Rect, _focused: FocusedArea) {
let snapshot = match IMPORT_STATE.lock() {
Ok(state) => state.clone(),
Err(e) => {
tracing::error!("Import state lock poisoned: {}", e);
ImportWizardState::default()
}
};
let keybinds = step_keybinds(&snapshot);
let search_line = if snapshot.step == ImportStep::Version {
snapshot.version_search.title_line()
} else {
None
};
let popup = PopupFrame {
title: wizard_title(&snapshot),
border_color: THEME.popup_import.border_fg,
bg: Some(THEME.popup_import.bg),
keybinds: Some(keybinds),
search_line,
content: Box::new(move |popup_area, buf| {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Min(1)])
.split(popup_area);
match snapshot.step {
ImportStep::Input => render_input_step(&snapshot, chunks[0], buf),
ImportStep::Fetching => render_fetching_step(chunks[0], buf),
ImportStep::Version => render_version_step(&snapshot, chunks[0], buf),
ImportStep::Confirm => render_confirm_step(&snapshot, chunks[0], buf),
}
}),
};
frame.render_widget(popup, area);
}
pub fn popup_rect(frame_area: Rect) -> Rect {
let w = Constraint::Percentage(50);
let step = match IMPORT_STATE.lock() {
Ok(s) => s.step.clone(),
Err(_) => ImportStep::Input,
};
match step {
ImportStep::Input => {
let h = 8u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
ImportStep::Fetching => {
let h = 5u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
ImportStep::Version => {
let h = (frame_area.height * 2 / 3)
.max(10)
.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
ImportStep::Confirm => {
let h = 10u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
}
}
pub fn handle_key(key_event: &KeyEvent, profiles_state: &mut profiles::State) {
pub fn handle_key(key_event: &KeyEvent, instances_state: &mut instances::State) {
let mut state = match IMPORT_STATE.lock() {
Ok(state) => state,
Err(e) => {
tracing::error!("Import state lock poisoned: {}", e);
profiles_state.show_import_popup = false;
instances_state.show_import_popup = false;
return;
}
};
match state.step {
ImportStep::Input => handle_input_key(&mut state, key_event, profiles_state),
ImportStep::Fetching => handle_fetching_key(&mut state, key_event, profiles_state),
ImportStep::Version => handle_version_key(&mut state, key_event, profiles_state),
ImportStep::Confirm => handle_confirm_key(&mut state, key_event, profiles_state),
ImportStep::Input => handle_input_key(&mut state, key_event, instances_state),
ImportStep::Fetching => handle_fetching_key(&mut state, key_event, instances_state),
ImportStep::Version => handle_version_key(&mut state, key_event, instances_state),
ImportStep::Confirm => handle_confirm_key(&mut state, key_event, instances_state),
}
}
@@ -167,10 +87,10 @@ pub fn take_result() -> Option<ImportResult> {
fn handle_input_key(
state: &mut ImportWizardState,
key_event: &KeyEvent,
profiles_state: &mut profiles::State,
instances_state: &mut instances::State,
) {
match key_event.code {
KeyCode::Esc => close_popup(state, profiles_state),
KeyCode::Esc => close_popup(state, instances_state),
KeyCode::Backspace => {
state.input.pop();
}
@@ -190,17 +110,17 @@ fn handle_input_key(
fn handle_fetching_key(
state: &mut ImportWizardState,
key_event: &KeyEvent,
profiles_state: &mut profiles::State,
instances_state: &mut instances::State,
) {
if key_event.code == KeyCode::Esc {
close_popup(state, profiles_state);
close_popup(state, instances_state);
}
}
fn handle_version_key(
state: &mut ImportWizardState,
key_event: &KeyEvent,
profiles_state: &mut profiles::State,
instances_state: &mut instances::State,
) {
if state.version_search.active {
match key_event.code {
@@ -232,7 +152,7 @@ fn handle_version_key(
let visible_count = visible_versions(state).len();
match key_event.code {
KeyCode::Esc => close_popup(state, profiles_state),
KeyCode::Esc => close_popup(state, instances_state),
KeyCode::Left | KeyCode::Char('h') if !state.version_search.active => {
state.step = ImportStep::Input;
state.versions = LoadState::Idle;
@@ -265,10 +185,10 @@ fn handle_version_key(
fn handle_confirm_key(
state: &mut ImportWizardState,
key_event: &KeyEvent,
profiles_state: &mut profiles::State,
instances_state: &mut instances::State,
) {
match key_event.code {
KeyCode::Esc => close_popup(state, profiles_state),
KeyCode::Esc => close_popup(state, instances_state),
KeyCode::Left | KeyCode::Char('h') => {
if matches!(state.versions, LoadState::Loaded(_)) {
state.step = ImportStep::Version;
@@ -291,7 +211,7 @@ fn handle_confirm_key(
}
}
close_popup(state, profiles_state);
close_popup(state, instances_state);
}
_ => {}
}
@@ -418,14 +338,7 @@ async fn resolve_version_id(
}
fn resolve_local_file(state_arc: Arc<Mutex<ImportWizardState>>, path: &str) {
let resolved = if let Some(stripped) = path.strip_prefix("~/") {
match dirs_next::home_dir() {
Some(home) => home.join(stripped),
None => std::path::PathBuf::from(path),
}
} else {
std::path::PathBuf::from(path)
};
let resolved = crate::config::settings::resolve_path(path);
match modrinth::parse_mrpack(&resolved) {
Ok(index) => {
@@ -506,157 +419,9 @@ fn start_version_download(state: &mut ImportWizardState) {
});
}
fn render_input_step(
state: &ImportWizardState,
area: Rect,
buf: &mut ratatui::buffer::Buffer,
) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(1),
Constraint::Length(1),
Constraint::Min(0),
])
.split(area);
let input_line = if state.input.is_empty() {
Line::from(vec![
Span::styled(
"URL, slug, or .mrpack path...",
Style::default().fg(THEME.popup_import.field_inactive_border_fg),
),
Span::styled(
"\u{2588}",
Style::default()
.fg(THEME.popup_import.border_fg)
.add_modifier(Modifier::SLOW_BLINK),
),
])
} else {
Line::from(vec![
Span::styled(
state.input.clone(),
Style::default().fg(THEME.popup_import.text_fg),
),
Span::styled(
"\u{2588}",
Style::default()
.fg(THEME.popup_import.border_fg)
.add_modifier(Modifier::SLOW_BLINK),
),
])
};
Paragraph::new(input_line).render(chunks[0], buf);
}
fn render_fetching_step(area: Rect, buf: &mut ratatui::buffer::Buffer) {
Paragraph::new("Fetching modpack info...")
.style(Style::default().fg(THEME.popup_import.field_inactive_border_fg))
.render(area, buf);
}
fn render_version_step(
state: &ImportWizardState,
area: Rect,
buf: &mut ratatui::buffer::Buffer,
) {
match &state.versions {
LoadState::Idle | LoadState::Loading => {
Paragraph::new("Loading versions...")
.style(Style::default().fg(THEME.popup_import.field_inactive_border_fg))
.render(area, buf);
}
LoadState::Error(message) => {
Paragraph::new(message.as_str())
.wrap(Wrap { trim: true })
.style(Style::default().fg(THEME.general.error))
.render(area, buf);
}
LoadState::Loaded(_) => {
let items: Vec<ListItem> = visible_versions(state)
.into_iter()
.map(|version| {
let game_ver = version.game_versions.first().cloned().unwrap_or_default();
let loader = version.loaders.first().cloned().unwrap_or_default();
ListItem::new(Line::from(Span::styled(
format!("{} {} {}", version.version_number, game_ver, loader),
Style::default().fg(THEME.popup_import.text_fg),
)))
})
.collect();
let list = List::new(items)
.highlight_style(
Style::default()
.fg(THEME.popup_import.accent_fg)
.add_modifier(Modifier::BOLD),
)
.highlight_symbol("\u{25b6} ");
let mut list_state = ListState::default().with_selected(Some(state.version_idx));
StatefulWidget::render(list, area, buf, &mut list_state);
}
}
}
fn render_confirm_step(
state: &ImportWizardState,
area: Rect,
buf: &mut ratatui::buffer::Buffer,
) {
let summary = match &state.summary {
Some(s) => s,
None => {
Paragraph::new("No summary available")
.style(Style::default().fg(THEME.popup_import.field_inactive_border_fg))
.render(area, buf);
return;
}
};
let label_style = Style::default().fg(THEME.popup_import.border_fg);
let loader_display = if let Some(ref lv) = summary.loader_version {
format!("{} {}", summary.loader, lv)
} else {
summary.loader.to_string()
};
Paragraph::new(vec![
Line::from(vec![
Span::styled("Name: ", label_style),
Span::raw(summary.name.clone()),
]),
Line::from(vec![
Span::styled("Pack Version: ", label_style),
Span::raw(summary.pack_version.clone()),
]),
Line::from(vec![
Span::styled("MC Version: ", label_style),
Span::raw(summary.game_version.clone()),
]),
Line::from(vec![
Span::styled("Loader: ", label_style),
Span::raw(loader_display),
]),
Line::from(vec![
Span::styled("Mods: ", label_style),
Span::raw(format!("{} files", summary.mod_count)),
]),
Line::from(vec![
Span::styled("Overrides: ", label_style),
Span::raw(format!("{} files", summary.override_count)),
]),
])
.style(Style::default().fg(THEME.popup_import.text_fg))
.wrap(Wrap { trim: true })
.render(area, buf);
}
fn close_popup(state: &mut ImportWizardState, profiles_state: &mut profiles::State) {
fn close_popup(state: &mut ImportWizardState, instances_state: &mut instances::State) {
state.reset();
profiles_state.show_import_popup = false;
instances_state.show_import_popup = false;
}
fn push_import_error(msg: String) {
@@ -668,35 +433,7 @@ fn push_import_error(msg: String) {
});
}
fn wizard_title(_state: &ImportWizardState) -> Line<'static> {
use crate::tui::widgets::styled_title;
styled_title("Import Modpack", false)
}
fn step_keybinds(state: &ImportWizardState) -> Line<'static> {
use super::keybind_line;
match state.step {
ImportStep::Input => keybind_line(&[("Enter", " fetch")]),
ImportStep::Fetching => keybind_line(&[("Esc", " cancel")]),
ImportStep::Version => keybind_line(&[
("/", " search"),
("h", " back"),
("Enter", " select"),
]),
ImportStep::Confirm => keybind_line(&[("h", " back"), ("Enter", " import")]),
}
}
fn selected_version(state: &ImportWizardState) -> Option<&VersionInfo> {
if let LoadState::Loaded(ref versions) = state.versions {
let visible: Vec<_> = visible_versions_ref(versions, &state.version_search);
visible.get(state.version_idx).copied()
} else {
None
}
}
fn visible_versions(state: &ImportWizardState) -> Vec<VersionInfo> {
pub(super) fn visible_versions(state: &ImportWizardState) -> Vec<VersionInfo> {
match &state.versions {
LoadState::Loaded(versions) => {
let q = state.version_search.query.to_lowercase();
@@ -729,6 +466,15 @@ fn visible_versions_ref<'a>(
.collect()
}
fn selected_version(state: &ImportWizardState) -> Option<&VersionInfo> {
if let LoadState::Loaded(ref versions) = state.versions {
let visible: Vec<_> = visible_versions_ref(versions, &state.version_search);
visible.get(state.version_idx).copied()
} else {
None
}
}
fn clamp_version_index(state: &mut ImportWizardState) {
let count = visible_versions(state).len();
if count == 0 {
+12 -18
View File
@@ -56,26 +56,23 @@ pub fn top_right_rect(frame: Rect, inner_w: usize, inner_h: usize) -> Rect {
}
pub fn keybind_line(binds: &[(&str, &str)]) -> ratatui::text::Line<'static> {
use crate::tui::theme::THEME;
use crate::config::theme::THEME;
use ratatui::{
style::{Modifier, Style},
text::{Line, Span},
};
let mut key_style = Style::default().fg(THEME.popup.keybind_active_fg);
if THEME.popup.keybind_active_bold {
key_style = key_style.add_modifier(Modifier::BOLD);
}
let dim_style = Style::default().fg(THEME.popup.keybind_inactive_fg);
let theme = THEME.as_ref();
let key_style = Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD);
let label_style = Style::default().fg(theme.text());
let mut spans: Vec<Span<'static>> = Vec::new();
for (i, (key, label)) in binds.iter().enumerate() {
if i > 0 {
spans.push(Span::styled(" ", dim_style));
spans.push(Span::styled(" ", label_style));
}
spans.push(Span::styled(format!("[{}]", key), key_style));
if !label.is_empty() {
spans.push(Span::styled(label.to_string(), dim_style));
spans.push(Span::styled(label.to_string(), label_style));
}
}
Line::from(spans)
@@ -85,17 +82,14 @@ pub fn keybind_lines_wrapped(
binds: &[(&str, &str)],
max_width: u16,
) -> Vec<ratatui::text::Line<'static>> {
use crate::tui::theme::THEME;
use crate::config::theme::THEME;
use ratatui::{
style::{Modifier, Style},
text::{Line, Span},
};
let mut key_style = Style::default().fg(THEME.popup.keybind_active_fg);
if THEME.popup.keybind_active_bold {
key_style = key_style.add_modifier(Modifier::BOLD);
}
let dim_style = Style::default().fg(THEME.popup.keybind_inactive_fg);
let theme = THEME.as_ref();
let key_style = Style::default().fg(theme.accent()).add_modifier(Modifier::BOLD);
let label_style = Style::default().fg(theme.text());
let mut rows: Vec<Line<'static>> = Vec::new();
let mut current_spans: Vec<Span<'static>> = Vec::new();
@@ -117,13 +111,13 @@ pub fn keybind_lines_wrapped(
}
if !current_spans.is_empty() {
current_spans.push(Span::styled(" ", dim_style));
current_spans.push(Span::styled(" ", label_style));
current_width += 2;
}
current_spans.push(Span::styled(format!("[{}]", key), key_style));
if !label.is_empty() {
current_spans.push(Span::styled(label.to_string(), dim_style));
current_spans.push(Span::styled(label.to_string(), label_style));
}
current_width += item_w;
}
@@ -0,0 +1,5 @@
mod render;
mod state;
pub use render::{popup_rect, render};
pub use state::{handle_key, take_result, LoadState, WizardParams, WizardStep, WizardState};
@@ -0,0 +1,321 @@
use super::state::{
clamp_loader_version_index, clamp_version_index, ensure_loader_versions_loaded,
ensure_versions_loaded, visible_versions, LoadState, WizardState, WizardStep, WIZARD_STATE,
};
use crate::instance::models::ModLoader;
use crate::tui::app::FocusedArea;
use crate::config::theme::THEME;
use crate::tui::widgets::popups::base::PopupFrame;
use tui_prompts::State as PromptState;
use ratatui::{
layout::{Constraint, Direction, Layout, Rect},
style::{Modifier, Style},
text::{Line, Span},
widgets::{List, ListItem, ListState, Paragraph, StatefulWidget, Widget, Wrap},
Frame,
};
pub fn render(frame: &mut Frame, area: Rect, _focused: FocusedArea) {
let snapshot = match WIZARD_STATE.lock() {
Ok(mut state) => {
if state.step == WizardStep::Version {
ensure_versions_loaded(&mut state);
clamp_version_index(&mut state);
}
if state.step == WizardStep::LoaderVersion {
if state.selected_loader() == ModLoader::Vanilla {
state.step = WizardStep::Confirm;
} else {
clamp_loader_version_index(&mut state);
let game_version = state.selected_version().map(|v| v.id.clone());
let loader = state.selected_loader();
if let Some(game_version) = game_version {
ensure_loader_versions_loaded(&mut state, loader, game_version);
}
}
}
state.clone()
}
Err(e) => {
tracing::error!("Wizard state lock poisoned: {}", e);
WizardState::default()
}
};
let keybinds = step_keybinds(&snapshot);
let search_line = snapshot.version_search.title_line();
let theme = THEME.as_ref();
let popup = PopupFrame {
title: wizard_title(&snapshot),
border_color: theme.text_dim(),
bg: Some(theme.surface()),
keybinds: Some(keybinds),
search_line,
content: Box::new(move |popup_area, buf| {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Min(1)])
.split(popup_area);
match snapshot.step {
WizardStep::Name => render_name_step(&snapshot, chunks[0], buf),
WizardStep::Version => render_version_step(&snapshot, chunks[0], buf),
WizardStep::Loader => render_loader_step(&snapshot, chunks[0], buf),
WizardStep::LoaderVersion => render_loader_version_step(&snapshot, chunks[0], buf),
WizardStep::Confirm => render_confirm_step(&snapshot, chunks[0], buf),
}
}),
};
frame.render_widget(popup, area);
}
pub fn popup_rect(frame_area: Rect) -> Rect {
use ratatui::layout::Constraint;
let step = match WIZARD_STATE.lock() {
Ok(s) => s.step.clone(),
Err(_) => WizardStep::Name,
};
let w = Constraint::Percentage(50);
match step {
WizardStep::Name => {
let h = 6u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
WizardStep::Version | WizardStep::LoaderVersion => {
let h = (frame_area.height * 2 / 3)
.max(10)
.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
WizardStep::Loader => {
let h = 9u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
WizardStep::Confirm => {
let h = 8u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
}
}
fn wizard_title(_state: &WizardState) -> Line<'static> {
use crate::tui::widgets::styled_title;
styled_title("New Instance", false)
}
fn step_keybinds(state: &WizardState) -> ratatui::text::Line<'static> {
use crate::tui::widgets::popups::keybind_line;
match state.step {
WizardStep::Name => keybind_line(&[("Enter", " continue")]),
WizardStep::Loader => keybind_line(&[("h", " back"), ("Enter", " select")]),
WizardStep::Version => keybind_line(&[
("/", " search"),
("s", " snap"),
("h", " back"),
("Enter", " select"),
]),
WizardStep::LoaderVersion => keybind_line(&[("h", " back"), ("Enter", " select")]),
WizardStep::Confirm => keybind_line(&[("h", " back"), ("Enter", " create")]),
}
}
fn render_name_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
let theme = THEME.as_ref();
let value = state.name_state.value();
let line = if value.is_empty() {
Line::from(vec![
Span::styled(
"Instance name...",
Style::default().fg(theme.text_dim()),
),
Span::styled(
"\u{2588}",
Style::default()
.fg(theme.text_dim())
.add_modifier(Modifier::SLOW_BLINK),
),
])
} else {
Line::from(vec![
Span::styled(value, Style::default().fg(theme.text())),
Span::styled(
"\u{2588}",
Style::default()
.fg(theme.text_dim())
.add_modifier(Modifier::SLOW_BLINK),
),
])
};
Paragraph::new(line).render(area, buf);
}
fn render_version_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
let theme = THEME.as_ref();
match &state.versions {
LoadState::Idle | LoadState::Loading => {
Paragraph::new("Loading versions...")
.style(Style::default().fg(theme.text_dim()))
.render(area, buf);
}
LoadState::Error(message) => {
Paragraph::new(message.as_str())
.wrap(Wrap { trim: true })
.style(Style::default().fg(theme.error()))
.render(area, buf);
}
LoadState::Loaded(_) => {
let items: Vec<ListItem> = visible_versions(state)
.into_iter()
.map(|version| {
let suffix = if version.stable {
String::new()
} else {
" (snapshot)".to_string()
};
ListItem::new(Line::from(Span::styled(
format!("{}{}", version.id, suffix),
Style::default().fg(theme.text()),
)))
})
.collect();
let list = List::new(items)
.highlight_style(
Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD),
)
.highlight_symbol("▶ ");
let mut list_state = ListState::default().with_selected(Some(state.version_idx));
StatefulWidget::render(list, area, buf, &mut list_state);
}
}
}
fn render_loader_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
let theme = THEME.as_ref();
let loaders = [
ModLoader::Vanilla,
ModLoader::Fabric,
ModLoader::Forge,
ModLoader::NeoForge,
ModLoader::Quilt,
];
let items: Vec<ListItem> = loaders
.into_iter()
.map(|loader| {
ListItem::new(Line::from(Span::styled(
loader.to_string(),
Style::default().fg(theme.text()),
)))
})
.collect();
let list = List::new(items)
.highlight_style(
Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD),
)
.highlight_symbol("▶ ");
let mut list_state = ListState::default().with_selected(Some(state.loader_idx));
StatefulWidget::render(list, area, buf, &mut list_state);
}
fn render_loader_version_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
let theme = THEME.as_ref();
if state.selected_loader() == ModLoader::Vanilla {
Paragraph::new("Vanilla has no loader version.")
.style(Style::default().fg(theme.text_dim()))
.render(area, buf);
return;
}
match &state.loader_versions {
LoadState::Idle | LoadState::Loading => {
Paragraph::new(format!("Loading {} versions...", state.selected_loader()))
.style(Style::default().fg(theme.text_dim()))
.render(area, buf);
}
LoadState::Error(message) => {
Paragraph::new(message.as_str())
.wrap(Wrap { trim: true })
.style(Style::default().fg(theme.error()))
.render(area, buf);
}
LoadState::Loaded(versions) => {
let items: Vec<ListItem> = versions
.iter()
.map(|version| {
ListItem::new(Line::from(Span::styled(
version.clone(),
Style::default().fg(theme.text()),
)))
})
.collect();
let list = List::new(items)
.highlight_style(
Style::default()
.fg(theme.accent())
.add_modifier(Modifier::BOLD),
)
.highlight_symbol("▶ ");
let mut list_state = ListState::default().with_selected(Some(state.loader_version_idx));
StatefulWidget::render(list, area, buf, &mut list_state);
}
}
}
fn render_confirm_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
let theme = THEME.as_ref();
let game_version = state
.selected_version()
.map(|version| version.id.as_str())
.unwrap_or("<not selected>");
let loader = state.selected_loader();
let loader_version = if loader == ModLoader::Vanilla {
"n/a".to_string()
} else {
state
.selected_loader_version()
.unwrap_or_else(|| "<not selected>".to_string())
};
let label_style = Style::default().fg(theme.text_dim());
Paragraph::new(vec![
Line::from(vec![
Span::styled("Name: ", label_style),
Span::raw(state.name_state.value()),
]),
Line::from(vec![
Span::styled("MC: ", label_style),
Span::raw(game_version),
]),
Line::from(vec![
Span::styled("Loader: ", label_style),
Span::raw(loader.to_string()),
]),
Line::from(vec![
Span::styled("Loader version: ", label_style),
Span::raw(loader_version),
]),
])
.style(Style::default().fg(theme.text()))
.wrap(Wrap { trim: true })
.render(area, buf);
}
@@ -1,27 +1,17 @@
use super::base::PopupFrame;
use crate::instance::{
loader::{get_installer, GameVersion},
models::ModLoader,
};
use crate::tui::layout::FocusedArea;
use crate::tui::theme::THEME;
use crate::tui::widgets::profiles;
use crate::tui::widgets::instances;
use crossterm::event::{KeyCode, KeyEvent};
use once_cell::sync::Lazy;
use ratatui::{
layout::{Constraint, Direction, Layout, Rect},
style::{Modifier, Style},
text::{Line, Span},
widgets::{List, ListItem, ListState, Paragraph, StatefulWidget, Widget, Wrap},
Frame,
};
use std::sync::LazyLock;
use std::sync::{Arc, Mutex};
use tui_prompts::{FocusState, State as PromptState, TextState};
static WIZARD_STATE: Lazy<Arc<Mutex<WizardState>>> =
Lazy::new(|| Arc::new(Mutex::new(WizardState::default())));
static WIZARD_RESULT: Lazy<Arc<Mutex<Option<WizardParams>>>> =
Lazy::new(|| Arc::new(Mutex::new(None)));
pub(crate) static WIZARD_STATE: LazyLock<Arc<Mutex<WizardState>>> =
LazyLock::new(|| Arc::new(Mutex::new(WizardState::default())));
pub(crate) static WIZARD_RESULT: LazyLock<Arc<Mutex<Option<WizardParams>>>> =
LazyLock::new(|| Arc::new(Mutex::new(None)));
#[derive(Debug, Clone)]
pub struct WizardParams {
@@ -51,7 +41,6 @@ pub enum LoadState<T> {
Error(String),
}
#[derive(Debug, Clone)]
pub struct WizardState {
pub step: WizardStep,
@@ -118,82 +107,24 @@ impl WizardState {
}
}
pub fn render(frame: &mut Frame, area: Rect, _focused: FocusedArea) {
let snapshot = match WIZARD_STATE.lock() {
Ok(mut state) => {
if state.step == WizardStep::Version {
ensure_versions_loaded(&mut state);
clamp_version_index(&mut state);
}
if state.step == WizardStep::LoaderVersion {
if state.selected_loader() == ModLoader::Vanilla {
state.step = WizardStep::Confirm;
} else {
clamp_loader_version_index(&mut state);
let game_version = state.selected_version().map(|v| v.id.clone());
let loader = state.selected_loader();
if let Some(game_version) = game_version {
ensure_loader_versions_loaded(&mut state, loader, game_version);
}
}
}
state.clone()
}
Err(e) => {
tracing::error!("Wizard state lock poisoned: {}", e);
WizardState::default()
}
};
let keybinds = step_keybinds(&snapshot);
let search_line = snapshot.version_search.title_line();
let popup = PopupFrame {
title: wizard_title(&snapshot),
border_color: THEME.popup_new_instance.border_fg,
bg: Some(THEME.popup_new_instance.bg),
keybinds: Some(keybinds),
search_line,
content: Box::new(move |popup_area, buf| {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Min(1)])
.split(popup_area);
match snapshot.step {
WizardStep::Name => render_name_step(&snapshot, chunks[0], buf),
WizardStep::Version => render_version_step(&snapshot, chunks[0], buf),
WizardStep::Loader => render_loader_step(&snapshot, chunks[0], buf),
WizardStep::LoaderVersion => render_loader_version_step(&snapshot, chunks[0], buf),
WizardStep::Confirm => render_confirm_step(&snapshot, chunks[0], buf),
}
}),
};
frame.render_widget(popup, area);
}
pub fn handle_key(key_event: &KeyEvent, profiles_state: &mut profiles::State) {
pub fn handle_key(key_event: &KeyEvent, instances_state: &mut instances::State) {
let mut state = match WIZARD_STATE.lock() {
Ok(state) => state,
Err(e) => {
tracing::error!("Wizard state lock poisoned: {}", e);
profiles_state.show_popup = false;
instances_state.show_popup = false;
return;
}
};
match state.step {
WizardStep::Name => handle_name_key(&mut state, key_event, profiles_state),
WizardStep::Version => handle_version_key(&mut state, key_event, profiles_state),
WizardStep::Loader => handle_loader_key(&mut state, key_event, profiles_state),
WizardStep::Name => handle_name_key(&mut state, key_event, instances_state),
WizardStep::Version => handle_version_key(&mut state, key_event, instances_state),
WizardStep::Loader => handle_loader_key(&mut state, key_event, instances_state),
WizardStep::LoaderVersion => {
handle_loader_version_key(&mut state, key_event, profiles_state)
handle_loader_version_key(&mut state, key_event, instances_state)
}
WizardStep::Confirm => handle_confirm_key(&mut state, key_event, profiles_state),
WizardStep::Confirm => handle_confirm_key(&mut state, key_event, instances_state),
}
}
@@ -204,46 +135,14 @@ pub fn take_result() -> Option<WizardParams> {
}
}
pub fn popup_rect(frame_area: Rect) -> Rect {
use ratatui::layout::Constraint;
let step = match WIZARD_STATE.lock() {
Ok(s) => s.step.clone(),
Err(_) => WizardStep::Name,
};
let w = Constraint::Percentage(50);
match step {
WizardStep::Name => {
let h = 6u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
WizardStep::Version | WizardStep::LoaderVersion => {
let h = (frame_area.height * 2 / 3)
.max(10)
.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
WizardStep::Loader => {
let h = 9u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
WizardStep::Confirm => {
let h = 8u16.min(frame_area.height.saturating_sub(4));
frame_area.centered(w, Constraint::Length(h))
}
}
}
fn handle_name_key(
state: &mut WizardState,
key_event: &KeyEvent,
profiles_state: &mut profiles::State,
instances_state: &mut instances::State,
) {
match key_event.code {
KeyCode::Esc => {
close_popup(state, profiles_state);
close_popup(state, instances_state);
}
KeyCode::Enter => {
if state.name_state.value().trim().is_empty() {
@@ -260,7 +159,7 @@ fn handle_name_key(
fn handle_version_key(
state: &mut WizardState,
key_event: &KeyEvent,
profiles_state: &mut profiles::State,
instances_state: &mut instances::State,
) {
// Search mode: route char input to search query
if state.version_search.active {
@@ -294,7 +193,7 @@ fn handle_version_key(
match key_event.code {
KeyCode::Esc => {
close_popup(state, profiles_state);
close_popup(state, instances_state);
}
KeyCode::Left | KeyCode::Char('h') if !state.version_search.active => {
state.step = WizardStep::Loader;
@@ -342,10 +241,10 @@ fn handle_version_key(
fn handle_loader_key(
state: &mut WizardState,
key_event: &KeyEvent,
profiles_state: &mut profiles::State,
instances_state: &mut instances::State,
) {
match key_event.code {
KeyCode::Esc => close_popup(state, profiles_state),
KeyCode::Esc => close_popup(state, instances_state),
KeyCode::Left | KeyCode::Char('h') => state.step = WizardStep::Name,
KeyCode::Char('j') | KeyCode::Down => {
state.loader_idx = (state.loader_idx + 1).min(4);
@@ -368,7 +267,7 @@ fn handle_loader_key(
fn handle_loader_version_key(
state: &mut WizardState,
key_event: &KeyEvent,
profiles_state: &mut profiles::State,
instances_state: &mut instances::State,
) {
if state.selected_loader() == ModLoader::Vanilla {
state.step = WizardStep::Confirm;
@@ -381,7 +280,7 @@ fn handle_loader_version_key(
};
match key_event.code {
KeyCode::Esc => close_popup(state, profiles_state),
KeyCode::Esc => close_popup(state, instances_state),
KeyCode::Left | KeyCode::Char('h') => state.step = WizardStep::Version,
KeyCode::Char('j') | KeyCode::Down => {
if version_count > 0 {
@@ -405,10 +304,10 @@ fn handle_loader_version_key(
fn handle_confirm_key(
state: &mut WizardState,
key_event: &KeyEvent,
profiles_state: &mut profiles::State,
instances_state: &mut instances::State,
) {
match key_event.code {
KeyCode::Esc => close_popup(state, profiles_state),
KeyCode::Esc => close_popup(state, instances_state),
KeyCode::Left | KeyCode::Char('h') => {
if state.selected_loader() == ModLoader::Vanilla {
state.step = WizardStep::Version;
@@ -442,230 +341,18 @@ fn handle_confirm_key(
}
}
close_popup(state, profiles_state);
close_popup(state, instances_state);
}
_ => {}
}
}
fn close_popup(state: &mut WizardState, profiles_state: &mut profiles::State) {
fn close_popup(state: &mut WizardState, instances_state: &mut instances::State) {
state.reset();
profiles_state.show_popup = false;
instances_state.show_popup = false;
}
fn wizard_title(_state: &WizardState) -> Line<'static> {
use crate::tui::widgets::styled_title;
styled_title("New Instance", false)
}
fn step_keybinds(state: &WizardState) -> ratatui::text::Line<'static> {
use super::keybind_line;
match state.step {
WizardStep::Name => keybind_line(&[("Enter", " continue")]),
WizardStep::Loader => keybind_line(&[("h", " back"), ("Enter", " select")]),
WizardStep::Version => keybind_line(&[
("/", " search"),
("s", " snap"),
("h", " back"),
("Enter", " select"),
]),
WizardStep::LoaderVersion => keybind_line(&[("h", " back"), ("Enter", " select")]),
WizardStep::Confirm => keybind_line(&[("h", " back"), ("Enter", " create")]),
}
}
fn render_name_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
use ratatui::style::Modifier;
use ratatui::text::{Line, Span};
let value = state.name_state.value();
let line = if value.is_empty() {
Line::from(vec![
Span::styled(
"Instance name...",
Style::default().fg(THEME.popup_new_instance.field_inactive_border_fg),
),
Span::styled(
"\u{2588}",
Style::default()
.fg(THEME.popup_new_instance.border_fg)
.add_modifier(Modifier::SLOW_BLINK),
),
])
} else {
Line::from(vec![
Span::styled(value, Style::default().fg(THEME.popup_new_instance.text_fg)),
Span::styled(
"\u{2588}",
Style::default()
.fg(THEME.popup_new_instance.border_fg)
.add_modifier(Modifier::SLOW_BLINK),
),
])
};
Paragraph::new(line).render(area, buf);
}
fn render_version_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
match &state.versions {
LoadState::Idle | LoadState::Loading => {
Paragraph::new("Loading versions...")
.style(Style::default().fg(THEME.popup_new_instance.field_inactive_border_fg))
.render(area, buf);
}
LoadState::Error(message) => {
Paragraph::new(message.as_str())
.wrap(Wrap { trim: true })
.style(Style::default().fg(THEME.popup_new_instance.error_fg))
.render(area, buf);
}
LoadState::Loaded(_) => {
let items: Vec<ListItem> = visible_versions(state)
.into_iter()
.map(|version| {
let suffix = if version.stable {
String::new()
} else {
" (snapshot)".to_string()
};
ListItem::new(Line::from(Span::styled(
format!("{}{}", version.id, suffix),
Style::default().fg(THEME.popup_new_instance.text_fg),
)))
})
.collect();
let list = List::new(items)
.highlight_style(
Style::default()
.fg(THEME.popup_new_instance.accent_fg)
.add_modifier(Modifier::BOLD),
)
.highlight_symbol("▶ ");
let mut list_state = ListState::default().with_selected(Some(state.version_idx));
StatefulWidget::render(list, area, buf, &mut list_state);
}
}
}
fn render_loader_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
let loaders = [
ModLoader::Vanilla,
ModLoader::Fabric,
ModLoader::Forge,
ModLoader::NeoForge,
ModLoader::Quilt,
];
let items: Vec<ListItem> = loaders
.into_iter()
.map(|loader| {
ListItem::new(Line::from(Span::styled(
loader.to_string(),
Style::default().fg(THEME.popup_new_instance.text_fg),
)))
})
.collect();
let list = List::new(items)
.highlight_style(
Style::default()
.fg(THEME.popup_new_instance.accent_fg)
.add_modifier(Modifier::BOLD),
)
.highlight_symbol("▶ ");
let mut list_state = ListState::default().with_selected(Some(state.loader_idx));
StatefulWidget::render(list, area, buf, &mut list_state);
}
fn render_loader_version_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
if state.selected_loader() == ModLoader::Vanilla {
Paragraph::new("Vanilla has no loader version.")
.style(Style::default().fg(THEME.popup_new_instance.field_inactive_border_fg))
.render(area, buf);
return;
}
match &state.loader_versions {
LoadState::Idle | LoadState::Loading => {
Paragraph::new(format!("Loading {} versions...", state.selected_loader()))
.style(Style::default().fg(THEME.popup_new_instance.field_inactive_border_fg))
.render(area, buf);
}
LoadState::Error(message) => {
Paragraph::new(message.as_str())
.wrap(Wrap { trim: true })
.style(Style::default().fg(THEME.popup_new_instance.error_fg))
.render(area, buf);
}
LoadState::Loaded(versions) => {
let items: Vec<ListItem> = versions
.iter()
.map(|version| {
ListItem::new(Line::from(Span::styled(
version.clone(),
Style::default().fg(THEME.popup_new_instance.text_fg),
)))
})
.collect();
let list = List::new(items)
.highlight_style(
Style::default()
.fg(THEME.popup_new_instance.accent_fg)
.add_modifier(Modifier::BOLD),
)
.highlight_symbol("▶ ");
let mut list_state = ListState::default().with_selected(Some(state.loader_version_idx));
StatefulWidget::render(list, area, buf, &mut list_state);
}
}
}
fn render_confirm_step(state: &WizardState, area: Rect, buf: &mut ratatui::buffer::Buffer) {
let game_version = state
.selected_version()
.map(|version| version.id.as_str())
.unwrap_or("<not selected>");
let loader = state.selected_loader();
let loader_version = if loader == ModLoader::Vanilla {
"n/a".to_string()
} else {
state
.selected_loader_version()
.unwrap_or_else(|| "<not selected>".to_string())
};
let label_style = Style::default().fg(THEME.popup_new_instance.border_fg);
Paragraph::new(vec![
Line::from(vec![
Span::styled("Name: ", label_style),
Span::raw(state.name_state.value()),
]),
Line::from(vec![
Span::styled("MC: ", label_style),
Span::raw(game_version),
]),
Line::from(vec![
Span::styled("Loader: ", label_style),
Span::raw(loader.to_string()),
]),
Line::from(vec![
Span::styled("Loader version: ", label_style),
Span::raw(loader_version),
]),
])
.style(Style::default().fg(THEME.popup_new_instance.text_fg))
.wrap(Wrap { trim: true })
.render(area, buf);
}
fn visible_versions(state: &WizardState) -> Vec<GameVersion> {
pub(crate) fn visible_versions(state: &WizardState) -> Vec<GameVersion> {
let q = state.version_search.query.to_lowercase();
match &state.versions {
LoadState::Loaded(versions) => versions
@@ -678,7 +365,7 @@ fn visible_versions(state: &WizardState) -> Vec<GameVersion> {
}
}
fn clamp_version_index(state: &mut WizardState) {
pub(crate) fn clamp_version_index(state: &mut WizardState) {
let count = visible_versions(state).len();
if count == 0 {
state.version_idx = 0;
@@ -687,7 +374,7 @@ fn clamp_version_index(state: &mut WizardState) {
}
}
fn clamp_loader_version_index(state: &mut WizardState) {
pub(crate) fn clamp_loader_version_index(state: &mut WizardState) {
if let LoadState::Loaded(versions) = &state.loader_versions {
if versions.is_empty() {
state.loader_version_idx = 0;
@@ -699,7 +386,7 @@ fn clamp_loader_version_index(state: &mut WizardState) {
}
}
fn ensure_versions_loaded(state: &mut WizardState) {
pub(crate) fn ensure_versions_loaded(state: &mut WizardState) {
if !matches!(state.versions, LoadState::Idle) {
return;
}
@@ -733,7 +420,7 @@ fn ensure_versions_loaded(state: &mut WizardState) {
});
}
fn ensure_loader_versions_loaded(state: &mut WizardState, loader: ModLoader, game_version: String) {
pub(crate) fn ensure_loader_versions_loaded(state: &mut WizardState, loader: ModLoader, game_version: String) {
if !matches!(state.loader_versions, LoadState::Idle) {
return;
}
+13 -19
View File
@@ -13,7 +13,7 @@ use ratatui::{
use ratatui_image::{protocol::StatefulProtocol, Resize, StatefulImage};
use crate::instance::screenshots::ScreenshotEntry;
use crate::tui::theme::THEME;
use crate::config::theme::THEME;
const TARGET_CELL_WIDTH: u16 = 34;
const MIN_CELL_WIDTH: u16 = 24;
@@ -219,14 +219,18 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut ScreenshotsState) -> bool {
KeyCode::Enter if key_event.modifiers.contains(KeyModifiers::SHIFT) => {
if let Some(entry) = state.entries.get(state.selected) {
if let Some(dir) = entry.path.parent() {
xdg_open(dir);
if let Err(e) = open::that(dir) {
tracing::error!("Failed to open directory: {}", e);
}
}
}
true
}
KeyCode::Enter => {
if let Some(entry) = state.entries.get(state.selected) {
xdg_open(&entry.path);
if let Err(e) = open::that(&entry.path) {
tracing::error!("Failed to open file: {}", e);
}
}
true
}
@@ -261,22 +265,12 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut ScreenshotsState) -> bool {
}
}
fn xdg_open(path: &std::path::Path) {
if let Err(e) = std::process::Command::new("xdg-open")
.arg(path)
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
{
tracing::error!("Failed to open: {}", e);
}
}
pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_focused: bool) {
let theme = THEME.as_ref();
if state.loading {
frame.render_widget(
Paragraph::new("Loading screenshots...")
.style(Style::default().fg(THEME.screenshots.label_fg)),
.style(Style::default().fg(theme.text_dim())),
area,
);
return;
@@ -285,7 +279,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_fo
if state.entries.is_empty() {
frame.render_widget(
Paragraph::new("No screenshots.")
.style(Style::default().fg(THEME.screenshots.label_fg)),
.style(Style::default().fg(theme.text_dim())),
area,
);
return;
@@ -352,10 +346,10 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_fo
let name = &state.entries[idx].name;
let name_style = if is_selected {
Style::default()
.fg(THEME.screenshots.selected_border_fg)
.fg(theme.accent())
.add_modifier(Modifier::BOLD)
} else {
Style::default().fg(THEME.screenshots.label_fg)
Style::default().fg(theme.text_dim())
};
let truncated = if name.len() > cell_width as usize {
@@ -382,7 +376,7 @@ pub fn render(frame: &mut Frame, area: Rect, state: &mut ScreenshotsState, is_fo
.begin_symbol(Some("\u{25b2}"))
.style(
Style::default()
.fg(THEME.screenshots.border_focused_fg)
.fg(theme.text_dim())
.add_modifier(Modifier::BOLD),
)
.thumb_symbol("\u{2551}")
+4 -3
View File
@@ -3,7 +3,7 @@ use ratatui::{
text::{Line, Span},
};
use crate::tui::theme::THEME;
use crate::config::theme::THEME;
#[derive(Debug, Default, Clone)]
pub struct SearchState {
@@ -77,9 +77,10 @@ impl SearchState {
return None;
}
let dim = Style::default().fg(THEME.search.border_unfocused_fg);
let theme = THEME.as_ref();
let dim = Style::default().fg(theme.text_dim());
let accent = Style::default()
.fg(THEME.search.border_focused_fg)
.fg(theme.text_dim())
.add_modifier(Modifier::BOLD);
let mut spans = vec![
+15 -14
View File
@@ -7,9 +7,9 @@ use ratatui::{
};
use throbber_widgets_tui::{Throbber, ThrobberState};
use crate::tui::layout::FocusedArea;
use crate::tui::app::FocusedArea;
use crate::tui::progress::PROGRESS;
use crate::tui::theme::THEME;
use crate::config::theme::{THEME, BORDER_STYLE};
use super::styled_title;
@@ -19,16 +19,17 @@ pub fn render(
focused: FocusedArea,
throbber_state: &mut ThrobberState,
) {
let theme = THEME.as_ref();
let border_color = if focused == FocusedArea::Overview {
THEME.status.border_focused_fg
theme.accent()
} else {
THEME.status.border_unfocused_fg
theme.border()
};
let block = Block::default()
.title(styled_title("Overview", true))
.borders(Borders::ALL)
.border_type(THEME.general.border_type.to_border_type())
.border_type(BORDER_STYLE.to_border_type())
.border_style(Style::default().fg(border_color));
let state = match PROGRESS.lock() {
@@ -37,7 +38,7 @@ pub fn render(
frame.render_widget(
Paragraph::new(Span::styled(
"Ready",
Style::default().fg(THEME.status.label_fg),
Style::default().fg(theme.text_dim()),
))
.block(block),
area,
@@ -50,7 +51,7 @@ pub fn render(
frame.render_widget(
Paragraph::new(Span::styled(
"Ready",
Style::default().fg(THEME.status.label_fg),
Style::default().fg(theme.text_dim()),
))
.block(block),
area,
@@ -77,19 +78,19 @@ pub fn render(
let gauge = Gauge::default()
.gauge_style(
Style::default()
.fg(THEME.status.progress_fill_fg)
.bg(THEME.status.progress_track_fg)
.fg(theme.success())
.bg(theme.surface())
.add_modifier(Modifier::BOLD),
)
.percent((ratio * 100.0) as u16);
frame.render_widget(gauge, chunks[0]);
frame.render_widget(
Paragraph::new(action_text).style(Style::default().fg(THEME.status.text_fg)),
Paragraph::new(action_text).style(Style::default().fg(theme.text())),
chunks[1],
);
if !sub_text.is_empty() {
frame.render_widget(
Paragraph::new(sub_text).style(Style::default().fg(THEME.status.label_fg)),
Paragraph::new(sub_text).style(Style::default().fg(theme.text_dim())),
chunks[2],
);
}
@@ -99,16 +100,16 @@ pub fn render(
Layout::vertical([Constraint::Length(1), Constraint::Length(1)]).split(inner);
let throbber = Throbber::default()
.label(action_text)
.style(Style::default().fg(THEME.status.text_fg))
.style(Style::default().fg(theme.text()))
.throbber_style(
Style::default()
.fg(THEME.status.border_focused_fg)
.fg(theme.text_dim())
.add_modifier(Modifier::BOLD),
);
frame.render_stateful_widget(throbber, chunks[0], throbber_state);
if !sub_text.is_empty() {
frame.render_widget(
Paragraph::new(sub_text).style(Style::default().fg(THEME.status.label_fg)),
Paragraph::new(sub_text).style(Style::default().fg(theme.text_dim())),
chunks[1],
);
}