feat(tui): add mods tab with icons and toggle, fix version sorting

This commit is contained in:
objz committed 2025-11-01 16:45:37 +01:00
1 parent 2adac8306b
commit f65341c0a2
9 files changed
+885 -19

No files matched your search

+3 -1
View File
@@ -2,8 +2,10 @@ pub mod launch;
pub mod manager;
pub mod loader;
pub mod models;
pub mod mods;
pub use launch::LaunchError;
pub use manager::{InstanceError, InstanceManager};
pub use loader::{get_installer, GameVersion, ModLoaderInstaller, VanillaInstaller};
pub use manager::{InstanceError, InstanceManager};
pub use models::{InstanceConfig, ModLoader};
pub use mods::{scan_mods, toggle_mod, ModEntry};
+159
View File
@@ -0,0 +1,159 @@
use std::io::Read;
use std::path::{Path, PathBuf};
use serde::Deserialize;
type IconCell = (u8, u8, u8, u8, u8, u8);
#[derive(Debug, Clone)]
pub struct ModEntry {
pub file_stem: String,
pub name: String,
pub description: String,
pub enabled: bool,
pub icon_bytes: Option<Vec<u8>>,
pub path: PathBuf,
pub icon_lines: Option<Vec<Vec<IconCell>>>,
}
#[derive(Deserialize, Default)]
struct FabricModJson {
#[serde(default)]
pub name: String,
#[serde(default)]
pub description: String,
#[serde(default)]
pub icon: String,
}
pub fn scan_mods(instances_dir: &Path, instance_name: &str) -> Vec<ModEntry> {
let mods_dir = instances_dir
.join(instance_name)
.join(".minecraft")
.join("mods");
let read_dir = match std::fs::read_dir(&mods_dir) {
Ok(read_dir) => read_dir,
Err(_) => return Vec::new(),
};
let mut entries = Vec::new();
for entry in read_dir.flatten() {
let path = entry.path();
let file_name = match path.file_name().and_then(|name| name.to_str()) {
Some(name) => name.to_string(),
None => continue,
};
let (enabled, file_stem) = if file_name.ends_with(".jar") {
(true, file_name.trim_end_matches(".jar").to_string())
} else if file_name.ends_with(".jar.disabled") {
(
false,
file_name.trim_end_matches(".jar.disabled").to_string(),
)
} else {
continue;
};
let (name, description, icon_bytes) = read_mod_metadata(&path);
let icon_lines = icon_bytes
.as_ref()
.and_then(|bytes| make_icon_pixels(bytes, 4, 2));
entries.push(ModEntry {
file_stem: file_stem.clone(),
name: if name.is_empty() { file_stem } else { name },
description,
enabled,
icon_bytes,
path,
icon_lines,
});
}
entries.sort_by(|left, right| left.name.to_lowercase().cmp(&right.name.to_lowercase()));
entries
}
fn read_mod_metadata(jar_path: &Path) -> (String, String, Option<Vec<u8>>) {
let file = match std::fs::File::open(jar_path) {
Ok(file) => file,
Err(_) => return (String::new(), String::new(), None),
};
let mut archive = match zip::ZipArchive::new(file) {
Ok(archive) => archive,
Err(_) => return (String::new(), String::new(), None),
};
if let Some((name, description, icon_path)) = read_fabric_meta(&mut archive) {
let icon_bytes = if icon_path.is_empty() {
None
} else {
read_zip_bytes(&mut archive, &icon_path)
};
return (name, description, icon_bytes);
}
let icon_bytes = read_zip_bytes(&mut archive, "pack.png");
(String::new(), String::new(), icon_bytes)
}
fn read_fabric_meta(
archive: &mut zip::ZipArchive<std::fs::File>,
) -> Option<(String, String, String)> {
let entry = archive.by_name("fabric.mod.json").ok()?;
let data: FabricModJson = serde_json::from_reader(entry).ok()?;
Some((data.name, data.description, data.icon))
}
fn read_zip_bytes(archive: &mut zip::ZipArchive<std::fs::File>, path: &str) -> Option<Vec<u8>> {
let mut entry = archive.by_name(path).ok()?;
let mut bytes = Vec::new();
entry.read_to_end(&mut bytes).ok()?;
Some(bytes)
}
fn make_icon_pixels(bytes: &[u8], width: u16, height: u16) -> Option<Vec<Vec<IconCell>>> {
let img = image::load_from_memory(bytes).ok()?;
let resized = img.resize_exact(
u32::from(width),
u32::from(height) * 2,
image::imageops::FilterType::Nearest,
);
let rgb = resized.to_rgb8();
let mut rows = Vec::new();
for row in 0..height {
let mut cols = Vec::new();
for col in 0..width {
let top_y = u32::from(row) * 2;
let bottom_y = (u32::from(row) * 2 + 1).min(rgb.height().saturating_sub(1));
let [tr, tg, tb] = rgb.get_pixel(u32::from(col), top_y).0;
let [br, bg, bb] = rgb.get_pixel(u32::from(col), bottom_y).0;
cols.push((br, bg, bb, tr, tg, tb));
}
rows.push(cols);
}
Some(rows)
}
pub fn toggle_mod(entry: &ModEntry) -> Result<(), std::io::Error> {
let file_name = match entry.path.file_name().and_then(|name| name.to_str()) {
Some(name) => name,
None => return Ok(()),
};
let new_name = if entry.enabled {
format!("{file_name}.disabled")
} else {
file_name.trim_end_matches(".disabled").to_string()
};
let mut new_path = entry.path.clone();
new_path.set_file_name(new_name);
std::fs::rename(&entry.path, new_path)
}
+16
View File
@@ -31,6 +31,7 @@ pub struct App {
pre_overlay_focused: FocusedArea,
content_tab: widgets::content::ContentTab,
profiles_state: profiles::State,
mods_state: widgets::mods_list::ModsState,
instance_manager: InstanceManager,
log_list_state: tui_logger::TuiWidgetState,
throbber_state: throbber_widgets_tui::ThrobberState,
@@ -87,6 +88,7 @@ impl Default for App {
pre_overlay_focused: FocusedArea::default(),
content_tab: widgets::content::ContentTab::default(),
profiles_state,
mods_state: widgets::mods_list::ModsState::default(),
instance_manager: manager,
log_list_state: tui_logger::TuiWidgetState::new()
.set_default_display_level(log::LevelFilter::Debug),
@@ -152,6 +154,8 @@ impl App {
self.focused,
self.content_tab,
self.profiles_state.selected_instance(),
&mut self.mods_state,
&self.instance_manager.instances_dir,
);
let bottom_chunks = Layout::default()
@@ -275,6 +279,18 @@ impl App {
}
}
if self.focused == FocusedArea::Content
&& self.content_tab == widgets::content::ContentTab::Mods
{
if widgets::mods_list::handle_key(
&key_event,
&mut self.mods_state,
&self.instance_manager.instances_dir,
) {
return Ok(());
}
}
match self.focused {
FocusedArea::Popup => {
new_instance::handle_key(&key_event, &mut self.profiles_state);
+18 -2
View File
@@ -68,6 +68,8 @@ pub fn render(
focused: FocusedArea,
tab: ContentTab,
instance: Option<&crate::instance::InstanceConfig>,
mods_state: &mut super::mods_list::ModsState,
instances_dir: &std::path::Path,
) {
let border_color = if focused == FocusedArea::Content {
THEME.colors.border_focused
@@ -102,6 +104,20 @@ pub fn render(
frame.render_widget(tabs, tabs_area);
match tab {
ContentTab::Mods => {
if let Some(instance) = instance {
if mods_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
mods_state.load_mods(instances_dir, &instance.name);
}
super::mods_list::render(frame, content_area, mods_state);
} else {
frame.render_widget(
Paragraph::new("No instance selected.")
.style(Style::default().fg(THEME.colors.text_idle)),
content_area,
);
}
}
ContentTab::Logs => {
let lines = instance
.map(|i| crate::instance_logs::get_all(&i.name))
@@ -123,7 +139,7 @@ pub fn render(
}
_ => {
let body = match tab {
ContentTab::Mods => "No mods installed.",
ContentTab::Mods => unreachable!(),
ContentTab::ResourcePacks => "No resource packs installed.",
ContentTab::Shaders => "No shaders installed.",
ContentTab::Screenshots => "No screenshots.",
@@ -190,7 +206,7 @@ pub fn title(
.fg(THEME.colors.success)
.add_modifier(Modifier::BOLD),
)
.throbber_set(throbber_widgets_tui::PARENTHESIS)
.throbber_set(throbber_widgets_tui::BRAILLE_EIGHT_DOUBLE)
.use_type(throbber_widgets_tui::WhichUse::Spin);
frame.render_stateful_widget(throbber, left_area, throbber_state);
}
+1
View File
@@ -8,6 +8,7 @@ use crate::tui::theme::THEME;
pub mod account;
pub mod content;
pub mod details;
pub mod mods_list;
pub mod popups;
pub mod profiles;
pub mod search;
+186
View File
@@ -0,0 +1,186 @@
use std::path::Path;
use crossterm::event::{KeyCode, KeyEvent};
use ratatui::{
layout::Rect,
style::{Color, Modifier, Style},
text::{Line, Span, Text},
widgets::Paragraph,
Frame,
};
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::instance::mods::{scan_mods, toggle_mod, ModEntry};
use crate::tui::theme::THEME;
type IconCell = (u8, u8, u8, u8, u8, u8);
pub struct ModsState {
pub mods: Vec<ModEntry>,
pub list_state: TuiListState,
pub loaded_for: Option<String>,
}
impl Default for ModsState {
fn default() -> Self {
Self {
mods: Vec::new(),
list_state: TuiListState::default(),
loaded_for: None,
}
}
}
impl ModsState {
pub fn load_mods(&mut self, instances_dir: &Path, instance_name: &str) {
self.mods = scan_mods(instances_dir, instance_name);
self.loaded_for = Some(instance_name.to_string());
self.list_state = TuiListState::default();
if !self.mods.is_empty() {
self.list_state.selected = Some(0);
}
}
pub fn toggle_selected(&mut self, instances_dir: &Path) {
let Some(index) = self.list_state.selected else {
return;
};
let Some(entry) = self.mods.get(index).cloned() else {
return;
};
match toggle_mod(&entry) {
Ok(()) => {
let loaded_for = self.loaded_for.clone();
if let Some(instance_name) = loaded_for.as_deref() {
self.load_mods(instances_dir, instance_name);
if !self.mods.is_empty() {
self.list_state.selected = Some(index.min(self.mods.len() - 1));
}
}
}
Err(error) => {
tracing::error!("Failed to toggle mod '{}': {}", entry.file_stem, error);
}
}
}
}
/// Returns `true` if the key was consumed by the mods list.
pub fn handle_key(key_event: &KeyEvent, state: &mut ModsState, instances_dir: &Path) -> bool {
match key_event.code {
KeyCode::Char('j') | KeyCode::Down => {
let count = state.mods.len();
if count == 0 {
return true;
}
let current = state.list_state.selected.unwrap_or(0);
state.list_state.selected = Some((current + 1).min(count - 1));
true
}
KeyCode::Char('k') | KeyCode::Up => {
let current = state.list_state.selected.unwrap_or(0);
state.list_state.selected = Some(current.saturating_sub(1));
true
}
KeyCode::Enter => {
state.toggle_selected(instances_dir);
true
}
_ => false,
}
}
pub fn render(frame: &mut Frame, area: Rect, state: &mut ModsState) {
if state.mods.is_empty() {
frame.render_widget(
Paragraph::new("No mods installed.").style(Style::default().fg(THEME.colors.text_idle)),
area,
);
return;
}
let count = state.mods.len();
const ITEM_HEIGHT: u16 = 2;
let mods_snapshot: Vec<(String, String, bool, Option<Vec<Vec<IconCell>>>)> = state
.mods
.iter()
.map(|mod_entry| {
(
mod_entry.name.clone(),
mod_entry.description.clone(),
mod_entry.enabled,
mod_entry.icon_lines.clone(),
)
})
.collect();
let builder = ListBuilder::new(move |context| {
let (name, description, enabled, icon_pixels) = &mods_snapshot[context.index];
let (name_style, description_style, background) = if context.is_selected {
(
Style::default()
.fg(THEME.colors.row_highlight)
.add_modifier(Modifier::BOLD),
Style::default().fg(THEME.colors.row_highlight),
THEME.colors.row_background,
)
} else {
(
Style::default()
.fg(THEME.colors.foreground)
.add_modifier(Modifier::BOLD),
Style::default().fg(THEME.colors.text_idle),
THEME.colors.row_alternate_bg,
)
};
let (status_text, status_style) = if *enabled {
("✓", Style::default().fg(THEME.colors.success))
} else {
("✗", Style::default().fg(THEME.colors.error))
};
let icon_row_0 = icon_spans(icon_pixels.as_ref(), 0);
let icon_row_1 = icon_spans(icon_pixels.as_ref(), 1);
let mut line_0 = icon_row_0;
line_0.push(Span::raw(" "));
line_0.push(Span::styled(name.clone(), name_style));
line_0.push(Span::raw(" "));
line_0.push(Span::styled(status_text, status_style));
let mut line_1 = icon_row_1;
line_1.push(Span::raw(" "));
line_1.push(Span::styled(description.clone(), description_style));
let item = Text::from(vec![Line::from(line_0), Line::from(line_1)])
.style(Style::default().bg(background));
(item, ITEM_HEIGHT)
});
let list = ListView::new(builder, count);
frame.render_stateful_widget(list, area, &mut state.list_state);
}
fn icon_spans(icon_pixels: Option<&Vec<Vec<IconCell>>>, row: usize) -> Vec<Span<'static>> {
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)| {
Span::styled(
"▄",
Style::default()
.fg(Color::Rgb(fg_r, fg_g, fg_b))
.bg(Color::Rgb(bg_r, bg_g, bg_b)),
)
})
.collect(),
None => vec![Span::styled(
" ",
Style::default().fg(THEME.colors.text_idle),
)],
}
}
+24 -1
View File
@@ -705,8 +705,9 @@ fn ensure_versions_loaded(state: &mut WizardState) {
let client = crate::net::HttpClient::new();
let installer = get_installer(loader);
match installer.get_game_versions(&client).await {
Ok(versions) => match versions_arc.lock() {
Ok(mut versions) => match versions_arc.lock() {
Ok(mut s) => {
sort_versions_semver(&mut versions);
s.versions = LoadState::Loaded(versions);
clamp_version_index(&mut s);
}
@@ -761,3 +762,25 @@ fn ensure_loader_versions_loaded(state: &mut WizardState, loader: ModLoader, gam
}
});
}
fn compare_semver(a: &str, b: &str) -> std::cmp::Ordering {
let parse_parts = |s: &str| -> Vec<u64> {
s.split('.')
.map(|p| p.parse::<u64>().unwrap_or(0))
.collect()
};
let a_parts = parse_parts(a);
let b_parts = parse_parts(b);
for (ap, bp) in a_parts.iter().zip(b_parts.iter()) {
match ap.cmp(bp) {
std::cmp::Ordering::Equal => continue,
other => return other,
}
}
a_parts.len().cmp(&b_parts.len())
}
fn sort_versions_semver(versions: &mut Vec<GameVersion>) {
// Sort newest first (descending), so compare b vs a
versions.sort_by(|a, b| compare_semver(&b.id, &a.id));
}