Merge pull request #25 from objz/feature/image-render-options

Feature/image render options
This commit is contained in:
objz authored and GitHub committed 2026-07-11 16:04:25 +02:00
commit d10be1676e
13 files changed
+517 -57

No files matched your search

+2
View File
@@ -14,6 +14,8 @@ memory_min = "512M"
memory_max = "2G"
[ui]
# image protocol for content icons and screenshots: halfblocks, quadrants, kitty, or iterm2
image_protocol = "kitty"
# error popup timing (in ms)
error_auto_dismiss_ms = 5000
error_slide_start_ms = 3500
+8 -7
View File
@@ -23,13 +23,14 @@ fn ensure_config_exists() -> PathBuf {
let config_path = get_config_path().join("config.toml");
if !config_path.exists() {
if let Some(parent) = config_path.parent()
&& let Err(e) = fs::create_dir_all(parent) {
tracing::warn!(
"Failed to create config directory {}: {}",
parent.display(),
e
);
}
&& let Err(e) = fs::create_dir_all(parent)
{
tracing::warn!(
"Failed to create config directory {}: {}",
parent.display(),
e
);
}
match fs::write(&config_path, include_str!("../../assets/config.toml")) {
Ok(()) => tracing::debug!("Wrote default config to {}", config_path.display()),
Err(e) => tracing::warn!(
+13
View File
@@ -5,6 +5,16 @@ use std::path::PathBuf;
use serde::Deserialize;
#[derive(Debug, Deserialize, Default, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ImageProtocol {
Halfblocks,
Quadrants,
#[default]
Kitty,
Iterm2,
}
#[derive(Debug, Deserialize, Default)]
pub struct General {}
@@ -102,6 +112,8 @@ impl Default for Defaults {
// timing knobs for the error toast animation: show for 5s, start sliding at 3.5s,
// fly off screen over 300ms. tweak these if the toasts feel too fast or slow.
pub struct Ui {
#[serde(default)]
pub image_protocol: ImageProtocol,
#[serde(default = "default_error_auto_dismiss_ms")]
pub error_auto_dismiss_ms: u64,
#[serde(default = "default_error_slide_start_ms")]
@@ -128,6 +140,7 @@ fn default_max_error_events() -> usize {
impl Default for Ui {
fn default() -> Self {
Self {
image_protocol: ImageProtocol::default(),
error_auto_dismiss_ms: default_error_auto_dismiss_ms(),
error_slide_start_ms: default_error_slide_start_ms(),
error_fly_out_ms: default_error_fly_out_ms(),
+128 -1
View File
@@ -13,6 +13,7 @@ use serde::Deserialize;
// where each character cell shows two vertical pixels (fg = top, bg = bottom)
#[derive(Debug, Clone, Copy)]
pub struct IconCell {
pub symbol: char,
pub bg_r: u8,
pub bg_g: u8,
pub bg_b: u8,
@@ -375,6 +376,14 @@ pub(crate) fn make_icon_pixels(
height: u16,
) -> Option<Vec<Vec<IconCell>>> {
let img = image::load_from_memory(bytes).ok()?;
Some(make_icon_pixels_from_image(&img, width, height))
}
pub(crate) fn make_icon_pixels_from_image(
img: &image::DynamicImage,
width: u16,
height: u16,
) -> Vec<Vec<IconCell>> {
let resized = img.resize_exact(
u32::from(width),
u32::from(height) * 2,
@@ -391,6 +400,7 @@ pub(crate) fn make_icon_pixels(
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(IconCell {
symbol: '\u{2584}',
bg_r: br,
bg_g: bg,
bg_b: bb,
@@ -402,12 +412,110 @@ pub(crate) fn make_icon_pixels(
rows.push(cols);
}
Some(rows)
rows
}
pub(crate) fn make_icon_quadrants_from_image(
img: &image::DynamicImage,
width: u16,
height: u16,
) -> Vec<Vec<IconCell>> {
let resized = img
.resize_exact(
u32::from(width) * 2,
u32::from(height) * 2,
image::imageops::FilterType::Lanczos3,
)
.to_rgb8();
(0..height)
.map(|row| {
(0..width)
.map(|col| {
let x = u32::from(col) * 2;
let y = u32::from(row) * 2;
let pixels = [
resized.get_pixel(x, y).0,
resized.get_pixel(x + 1, y).0,
resized.get_pixel(x, y + 1).0,
resized.get_pixel(x + 1, y + 1).0,
];
quadrant_cell(pixels)
})
.collect()
})
.collect()
}
fn quadrant_cell(pixels: [[u8; 3]; 4]) -> IconCell {
let mut pair = (0, 0);
let mut max_distance = 0;
for left in 0..pixels.len() {
for right in (left + 1)..pixels.len() {
let distance = color_distance(pixels[left], pixels[right]);
if distance > max_distance {
max_distance = distance;
pair = (left, right);
}
}
}
let bg = pixels[pair.0];
let fg = pixels[pair.1];
let mask = pixels
.iter()
.enumerate()
.fold(0_u8, |mask, (index, pixel)| {
if color_distance(*pixel, fg) <= color_distance(*pixel, bg) {
mask | (1 << index)
} else {
mask
}
});
let symbol = match mask {
0 => ' ',
1 => '\u{2598}',
2 => '\u{259d}',
3 => '\u{2580}',
4 => '\u{2596}',
5 => '\u{258c}',
6 => '\u{259e}',
7 => '\u{259b}',
8 => '\u{2597}',
9 => '\u{259a}',
10 => '\u{2590}',
11 => '\u{259c}',
12 => '\u{2584}',
13 => '\u{2599}',
14 => '\u{259f}',
_ => '\u{2588}',
};
IconCell {
symbol,
bg_r: bg[0],
bg_g: bg[1],
bg_b: bg[2],
fg_r: fg[0],
fg_g: fg[1],
fg_b: fg[2],
}
}
fn color_distance(left: [u8; 3], right: [u8; 3]) -> u32 {
left.into_iter()
.zip(right)
.map(|(left, right)| {
let delta = i32::from(left) - i32::from(right);
(delta * delta) as u32
})
.sum()
}
// 6x3 fallback icon showing a "?" pattern for mods without icons.
pub(super) fn fallback_icon() -> Vec<Vec<IconCell>> {
let b = IconCell {
symbol: '\u{2584}',
bg_r: 50,
bg_g: 50,
bg_b: 50,
@@ -416,6 +524,7 @@ pub(super) fn fallback_icon() -> Vec<Vec<IconCell>> {
fg_b: 50,
};
let tb = IconCell {
symbol: '\u{2584}',
bg_r: 50,
bg_g: 50,
bg_b: 50,
@@ -424,6 +533,7 @@ pub(super) fn fallback_icon() -> Vec<Vec<IconCell>> {
fg_b: 130,
};
let bt = IconCell {
symbol: '\u{2584}',
bg_r: 130,
bg_g: 130,
bg_b: 130,
@@ -441,6 +551,7 @@ pub(super) fn fallback_icon() -> Vec<Vec<IconCell>> {
// 12x6 fallback icon showing a "?" pattern for worlds without icons.
pub(super) fn fallback_icon_large() -> Vec<Vec<IconCell>> {
let b = IconCell {
symbol: '\u{2584}',
bg_r: 50,
bg_g: 50,
bg_b: 50,
@@ -449,6 +560,7 @@ pub(super) fn fallback_icon_large() -> Vec<Vec<IconCell>> {
fg_b: 50,
};
let tb = IconCell {
symbol: '\u{2584}',
bg_r: 50,
bg_g: 50,
bg_b: 50,
@@ -457,6 +569,7 @@ pub(super) fn fallback_icon_large() -> Vec<Vec<IconCell>> {
fg_b: 130,
};
let bt = IconCell {
symbol: '\u{2584}',
bg_r: 130,
bg_g: 130,
bg_b: 130,
@@ -497,6 +610,20 @@ pub fn toggle_entry(entry: &ContentEntry) -> Result<(), std::io::Error> {
mod tests {
use super::*;
#[test]
fn quadrant_raster_has_requested_dimensions() {
let image = image::DynamicImage::ImageRgb8(image::RgbImage::from_pixel(
2,
2,
image::Rgb([12, 34, 56]),
));
let rows = make_icon_quadrants_from_image(&image, 7, 3);
assert_eq!(rows.len(), 3);
assert!(rows.iter().all(|row| row.len() == 7));
assert!(rows.iter().flatten().all(|cell| cell.symbol == '\u{2588}'));
}
fn setup_mods_dir(tmp: &Path, instance: &str) -> PathBuf {
let dir = tmp.join(instance).join(".minecraft").join("mods");
std::fs::create_dir_all(&dir).unwrap();
+16 -14
View File
@@ -145,13 +145,14 @@ async fn download_mod_files(
let completed = completed.clone();
tasks.spawn(async move {
if let Some(parent) = dest.parent()
&& let Err(e) = tokio::fs::create_dir_all(parent).await {
tracing::warn!(
"Failed to create mod download directory {}: {}",
parent.display(),
e
);
}
&& let Err(e) = tokio::fs::create_dir_all(parent).await
{
tracing::warn!(
"Failed to create mod download directory {}: {}",
parent.display(),
e
);
}
progress::set_sub_action(filename);
tracing::trace!("Downloading .mrpack file to {}", dest.display());
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
@@ -183,13 +184,14 @@ async fn download_mod_files(
let completed = completed.clone();
tasks.spawn(async move {
if let Some(parent) = dest.parent()
&& let Err(e) = tokio::fs::create_dir_all(parent).await {
tracing::warn!(
"Failed to create mod download directory {}: {}",
parent.display(),
e
);
}
&& let Err(e) = tokio::fs::create_dir_all(parent).await
{
tracing::warn!(
"Failed to create mod download directory {}: {}",
parent.display(),
e
);
}
progress::set_sub_action(filename);
tracing::trace!("Downloading .mrpack file to {}", dest.display());
crate::net::download_file(&client, &url, &dest, |_, _| {}).await?;
+7 -7
View File
@@ -28,17 +28,13 @@ pub enum LaunchError {
Json(#[from] serde_json::Error),
#[error("{0} launch is not yet supported")]
NotSupported(String),
#[error(
"This instance requires Java {required}, but rmcl is using Java {detected}: {java}"
)]
#[error("This instance requires Java {required}, but rmcl is using Java {detected}: {java}")]
JavaTooOld {
java: String,
required: u32,
detected: u32,
},
#[error(
"This instance requires Java {required}, but rmcl could not check {java}: {reason}"
)]
#[error("This instance requires Java {required}, but rmcl could not check {java}: {reason}")]
JavaCheckFailed {
java: String,
required: u32,
@@ -414,7 +410,11 @@ pub async fn build_launch_invocation(
// so we check there first.
let has_local_libs = matches!(config.loader, ModLoader::Forge | ModLoader::NeoForge);
let local_lib_dir = minecraft_dir.join("libraries");
let library_directory = if has_local_libs { &local_lib_dir } else { &lib_dir };
let library_directory = if has_local_libs {
&local_lib_dir
} else {
&lib_dir
};
let mut classpath: Vec<PathBuf> = Vec::new();
for lib in &merged_profile.libraries {
+3 -1
View File
@@ -254,7 +254,9 @@ impl InstanceManager {
.await
.map_err(|e| match e {
InstallError::Download(net_error) => InstanceError::Download(net_error),
InstallError::Installer(installer_error) => InstanceError::InstallerError(installer_error),
InstallError::Installer(installer_error) => {
InstanceError::InstallerError(installer_error)
}
})?;
let config = InstanceConfig {
+43 -18
View File
@@ -227,38 +227,58 @@ pub(crate) async fn install_forge_from_profile(
let file = std::fs::File::open(installer_path)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
let mut archive = zip::ZipArchive::new(file)
.map_err(|e| InstallError::Installer(InstallerError::Profile(format!("Failed to open installer as ZIP: {e}"))))?;
let mut archive = zip::ZipArchive::new(file).map_err(|e| {
InstallError::Installer(InstallerError::Profile(format!(
"Failed to open installer as ZIP: {e}"
)))
})?;
let profile_data: serde_json::Value = {
let entry = archive.by_name("install_profile.json").map_err(|e| {
InstallError::Installer(InstallerError::Profile(format!("install_profile.json not found in installer: {e}")))
InstallError::Installer(InstallerError::Profile(format!(
"install_profile.json not found in installer: {e}"
)))
})?;
serde_json::from_reader(entry)
.map_err(|e| InstallError::Installer(InstallerError::Profile(format!("Failed to parse install_profile.json: {e}"))))?
serde_json::from_reader(entry).map_err(|e| {
InstallError::Installer(InstallerError::Profile(format!(
"Failed to parse install_profile.json: {e}"
)))
})?
};
let version_info = profile_data
.get("versionInfo")
.ok_or_else(|| InstallError::Installer(InstallerError::Profile("install_profile.json missing versionInfo".into())))?;
let install_info = profile_data
.get("install")
.ok_or_else(|| InstallError::Installer(InstallerError::Profile("install_profile.json missing install section".into())))?;
let version_info = profile_data.get("versionInfo").ok_or_else(|| {
InstallError::Installer(InstallerError::Profile(
"install_profile.json missing versionInfo".into(),
))
})?;
let install_info = profile_data.get("install").ok_or_else(|| {
InstallError::Installer(InstallerError::Profile(
"install_profile.json missing install section".into(),
))
})?;
let libraries = version_info
.get("libraries")
.and_then(|v| v.as_array())
.ok_or_else(|| InstallError::Installer(InstallerError::Profile("missing versionInfo.libraries".into())))?;
.ok_or_else(|| {
InstallError::Installer(InstallerError::Profile(
"missing versionInfo.libraries".into(),
))
})?;
let file_path = install_info
.get("filePath")
.and_then(|v| v.as_str())
.ok_or_else(|| InstallError::Installer(InstallerError::Profile("missing install.filePath".into())))?;
.ok_or_else(|| {
InstallError::Installer(InstallerError::Profile("missing install.filePath".into()))
})?;
let install_path_coord = install_info
.get("path")
.and_then(|v| v.as_str())
.ok_or_else(|| InstallError::Installer(InstallerError::Profile("missing install.path".into())))?;
.ok_or_else(|| {
InstallError::Installer(InstallerError::Profile("missing install.path".into()))
})?;
// extract the universal jar to the correct maven location
let universal_maven_path =
@@ -300,12 +320,14 @@ pub(crate) async fn install_forge_from_profile(
// in mojang's modern version metadata, so we fetch those too.
let libraries_dir = meta_dir.join("libraries");
for lib in libraries {
let name = lib.get("name").and_then(|v| v.as_str()).unwrap_or_default();
let name = lib.get("name").and_then(|v| v.as_str()).unwrap_or_default();
let maven_path = match crate::net::maven_coord_to_path(name) {
Some(p) => p,
None => {
return Err(InstallError::Installer(InstallerError::Profile(format!("Invalid Maven coordinate: {name}"))));
return Err(InstallError::Installer(InstallerError::Profile(format!(
"Invalid Maven coordinate: {name}"
))));
}
};
@@ -341,8 +363,11 @@ pub(crate) async fn install_forge_from_profile(
// and whitespace may differ from the original installer JSON because
// the source is a serde_json::Value (which doesn't preserve order),
// but no field is silently dropped.
let serialized = serde_json::to_vec(version_info)
.map_err(|e| InstallError::Installer(InstallerError::Profile(format!("Failed to serialize Forge profile: {e}"))))?;
let serialized = serde_json::to_vec(version_info).map_err(|e| {
InstallError::Installer(InstallerError::Profile(format!(
"Failed to serialize Forge profile: {e}"
)))
})?;
crate::instance::loader::save_profile_bytes(meta_dir, profile_filename, &serialized)
.map_err(|e| InstallError::Installer(InstallerError::Io(e)))?;
Ok(())
+8
View File
@@ -32,12 +32,20 @@ impl App {
self.drain_pending_last_played();
self.mods_state.drain_pending();
self.mods_state.drain_watcher();
self.mods_state.request_image_loads(&self.picker);
self.mods_state.drain_image_loads(&self.picker);
self.resource_packs_state.drain_pending();
self.resource_packs_state.drain_watcher();
self.resource_packs_state.request_image_loads(&self.picker);
self.resource_packs_state.drain_image_loads(&self.picker);
self.shaders_state.drain_pending();
self.shaders_state.drain_watcher();
self.shaders_state.request_image_loads(&self.picker);
self.shaders_state.drain_image_loads(&self.picker);
self.worlds_state.drain_pending();
self.worlds_state.drain_watcher();
self.worlds_state.request_image_loads(&self.picker);
self.worlds_state.drain_image_loads(&self.picker);
self.logs_state.drain_pending();
self.logs_state.try_rescan();
self.account_state.drain_auth_result();
+20 -1
View File
@@ -37,8 +37,27 @@ pub async fn show() -> color_eyre::Result<()> {
// figure out the terminal's font cell size for rendering images.
// falls back to halfblock characters if the terminal doesn't respond
let picker = ratatui_image::picker::Picker::from_query_stdio()
let mut picker = ratatui_image::picker::Picker::from_query_stdio()
.unwrap_or_else(|_| ratatui_image::picker::Picker::halfblocks());
let detected_protocol = picker.protocol_type();
let requested_protocol = match crate::config::SETTINGS.ui.image_protocol {
crate::config::settings::ImageProtocol::Halfblocks
| crate::config::settings::ImageProtocol::Quadrants => {
ratatui_image::picker::ProtocolType::Halfblocks
}
crate::config::settings::ImageProtocol::Kitty
if detected_protocol == ratatui_image::picker::ProtocolType::Kitty =>
{
ratatui_image::picker::ProtocolType::Kitty
}
crate::config::settings::ImageProtocol::Iterm2
if detected_protocol == ratatui_image::picker::ProtocolType::Iterm2 =>
{
ratatui_image::picker::ProtocolType::Iterm2
}
_ => ratatui_image::picker::ProtocolType::Halfblocks,
};
picker.set_protocol_type(requested_protocol);
let result = app::App::new(picker).run(&mut terminal).await;
+1
View File
@@ -65,6 +65,7 @@ impl App {
&mut self.screenshots_state,
&mut self.logs_state,
&self.instance_manager.instances_dir,
&self.picker,
);
let bottom_chunks = Layout::default()
+263 -8
View File
@@ -4,7 +4,7 @@
// also handles minecraft's formatting codes for colored mod names/descriptions
// because apparently mojang thought terminal UIs would need that. thanks guys
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::sync::{Arc, Mutex, mpsc};
@@ -16,12 +16,20 @@ use ratatui::{
text::{Line, Span, Text},
widgets::{Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState},
};
use ratatui_image::{CropOptions, Resize, StatefulImage, protocol::StatefulProtocol};
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::config::theme::THEME;
use crate::instance::content::mods::{ContentEntry, IconCell};
type SnapshotRow = (String, String, bool, Option<Vec<Vec<IconCell>>>);
type SnapshotRow = (
String,
String,
bool,
Option<Vec<Vec<IconCell>>>,
bool,
usize,
);
type ScanOneFn = fn(&Path, &str, bool) -> ContentEntry;
struct CachedList {
@@ -29,6 +37,12 @@ struct CachedList {
selected: Option<usize>,
}
struct PendingContentImage {
path: std::path::PathBuf,
icon_lines: Vec<Vec<IconCell>>,
image: Option<image::DynamicImage>,
}
// result from the notify-triggered background diff
struct WatcherDiff {
toggled: Vec<(String, bool, std::path::PathBuf)>,
@@ -42,6 +56,10 @@ pub struct ContentListState {
pub scrollbar_state: ScrollbarState,
pub loaded_for: Option<String>,
pub loading: bool,
image_protocols: HashMap<std::path::PathBuf, StatefulProtocol>,
requested_images: HashSet<std::path::PathBuf>,
pending_images: Arc<Mutex<Vec<PendingContentImage>>>,
images_dirty: bool,
pub search: crate::tui::widgets::search::SearchState,
cache: HashMap<String, CachedList>,
// streaming: individual entries arrive here during initial load
@@ -70,6 +88,10 @@ impl Default for ContentListState {
scrollbar_state: ScrollbarState::default(),
loaded_for: None,
loading: false,
image_protocols: HashMap::new(),
requested_images: HashSet::new(),
pending_images: Arc::new(Mutex::new(Vec::new())),
images_dirty: true,
search: crate::tui::widgets::search::SearchState::default(),
cache: HashMap::new(),
stream_rx: None,
@@ -83,6 +105,96 @@ impl Default for ContentListState {
}
impl ContentListState {
pub fn request_image_loads(&mut self, picker: &ratatui_image::picker::Picker) {
if !self.images_dirty {
return;
}
self.images_dirty = false;
let use_image_protocol =
picker.protocol_type() != ratatui_image::picker::ProtocolType::Halfblocks;
let use_quadrants = crate::config::SETTINGS.ui.image_protocol
== crate::config::settings::ImageProtocol::Quadrants;
if !use_image_protocol {
self.image_protocols.clear();
}
self.image_protocols
.retain(|path, _| self.entries.iter().any(|entry| &entry.path == path));
self.requested_images
.retain(|path| self.entries.iter().any(|entry| &entry.path == path));
let font_size = picker.font_size();
for entry in &self.entries {
if entry.icon_bytes.is_none() || !self.requested_images.insert(entry.path.clone()) {
continue;
}
let path = entry.path.clone();
let bytes = entry.icon_bytes.clone().unwrap_or_default();
let rows = entry.icon_lines.as_ref().map_or(3, Vec::len) as u32;
let columns = square_icon_columns(rows as u16, font_size);
let pending = self.pending_images.clone();
tokio::spawn(async move {
let result = tokio::task::spawn_blocking(move || {
let image = image::load_from_memory(&bytes).ok()?;
let icon_lines = if use_quadrants {
crate::instance::content::mods::make_icon_quadrants_from_image(
&image,
columns,
rows as u16,
)
} else {
crate::instance::content::mods::make_icon_pixels_from_image(
&image,
columns,
rows as u16,
)
};
let side = rows * u32::from(font_size.1.max(1));
let image = use_image_protocol.then(|| {
image.resize_exact(side, side, image::imageops::FilterType::Lanczos3)
});
Some(PendingContentImage {
path,
icon_lines,
image,
})
})
.await
.ok()
.flatten();
if let Some(result) = result
&& let Ok(mut pending) = pending.lock()
{
pending.push(result);
}
});
}
}
pub fn drain_image_loads(&mut self, picker: &ratatui_image::picker::Picker) {
let images = match self.pending_images.lock() {
Ok(mut pending) => std::mem::take(&mut *pending),
Err(_) => return,
};
for result in images {
if let Some(entry) = self
.entries
.iter_mut()
.find(|entry| entry.path == result.path)
{
entry.icon_lines = Some(result.icon_lines);
if let Some(image) = result.image {
self.image_protocols
.insert(result.path, picker.new_resize_protocol(image));
}
}
}
}
// drain streaming entries from the initial load. each entry arrives
// individually and is inserted in sorted position for a smooth fill-in
pub fn drain_pending(&mut self) {
@@ -97,6 +209,7 @@ impl ContentListState {
match rx.try_recv() {
Ok(entry) => {
received = true;
self.images_dirty = true;
received_count += 1;
let pos = self
.entries
@@ -151,6 +264,7 @@ impl ContentListState {
let Some(diff) = diff else {
return;
};
self.images_dirty = true;
// apply toggles (enabled/path changes)
tracing::debug!(
@@ -353,6 +467,7 @@ impl ContentListState {
) {
self.scan_one_fn = Some(scan_one_fn);
self.content_ext = Some(ext);
self.images_dirty = true;
// save current entries to cache
if let Some(prev) = self.loaded_for.take()
@@ -506,6 +621,9 @@ impl ContentListState {
pub fn remove_path(&mut self, path: &Path) {
self.entries.retain(|entry| entry.path != path);
self.image_protocols.remove(path);
self.requested_images.remove(path);
self.images_dirty = true;
if let Some(sel) = self.list_state.selected {
let visible_count = self.filtered_indices().len();
if visible_count == 0 {
@@ -560,6 +678,7 @@ pub fn handle_key_no_toggle(key_event: &KeyEvent, state: &mut ContentListState)
}
let filtered = state.filtered_indices();
let count = filtered.len();
match key_event.code {
KeyCode::Char('j') | KeyCode::Down => {
if count == 0 {
@@ -595,6 +714,7 @@ pub fn handle_key(key_event: &KeyEvent, state: &mut ContentListState) -> bool {
}
let filtered = state.filtered_indices();
let count = filtered.len();
match key_event.code {
KeyCode::Char('j') | KeyCode::Down => {
if count == 0 {
@@ -640,6 +760,7 @@ pub fn render(
is_focused: bool,
loading_text: &str,
empty_text: &str,
picker: &ratatui_image::picker::Picker,
) {
let theme = THEME.as_ref();
if state.loading {
@@ -679,13 +800,18 @@ pub fn render(
entry.description.clone(),
entry.enabled,
entry.icon_lines.clone(),
entry.icon_bytes.is_some(),
protocol_icon_columns(entry, picker) as usize,
)
})
.collect();
let use_image_protocol =
picker.protocol_type() != ratatui_image::picker::ProtocolType::Halfblocks;
let builder = ListBuilder::new(move |context| {
let theme = THEME.as_ref();
let (name, description, enabled, icon_pixels) = &snapshot[context.index];
let (name, description, enabled, icon_pixels, has_image, protocol_columns) =
&snapshot[context.index];
let show_selected = is_focused && context.is_selected;
let use_mc_colors = *enabled;
@@ -761,7 +887,12 @@ pub fn render(
};
let mut line_0 = vec![selector.clone()];
line_0.extend(icon_spans(icon_pixels.as_ref(), 0));
line_0.extend(icon_spans(
icon_pixels.as_ref(),
0,
use_image_protocol && *has_image,
*protocol_columns,
));
line_0.push(Span::raw(" "));
if use_mc_colors {
line_0.extend(parse_mc_text(name, name_style));
@@ -773,7 +904,12 @@ pub fn render(
if has_description {
let mut row = vec![pad.clone()];
row.extend(icon_spans(icon_pixels.as_ref(), 1));
row.extend(icon_spans(
icon_pixels.as_ref(),
1,
use_image_protocol && *has_image,
*protocol_columns,
));
row.push(Span::raw(" "));
row.push(Span::styled(stripped_desc.clone(), description_style));
lines.push(Line::from(row));
@@ -782,7 +918,12 @@ pub fn render(
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));
row.extend(icon_spans(
icon_pixels.as_ref(),
r,
use_image_protocol && *has_image,
*protocol_columns,
));
lines.push(Line::from(row));
}
@@ -820,6 +961,10 @@ pub fn render(
let list = ListView::new(builder, count);
frame.render_stateful_widget(list, area, &mut state.list_state);
if picker.protocol_type() != ratatui_image::picker::ProtocolType::Halfblocks {
render_image_icons(frame, area, state, &filtered, picker);
}
let scrollbar_area = Rect {
x: area.x + area.width.saturating_sub(0),
y: area.y + 1,
@@ -843,6 +988,77 @@ pub fn render(
);
}
fn render_image_icons(
frame: &mut Frame,
area: Rect,
state: &mut ContentListState,
filtered: &[usize],
picker: &ratatui_image::picker::Picker,
) {
let truncation = state.list_state.scroll_truncation();
let mut y = area.y;
let first = state.list_state.scroll_offset_index();
for (visible_index, &entry_index) in filtered.iter().enumerate().skip(first) {
let Some(entry) = state.entries.get(entry_index) else {
continue;
};
let icon_rows = entry.icon_lines.as_ref().map_or(0, Vec::len);
let description = strip_mc_codes(&entry.description);
let has_description = description
.lines()
.next()
.is_some_and(|line| !line.trim().is_empty());
let height = icon_rows.max(if has_description { 2 } else { 1 }) as u16;
if y >= area.y + area.height {
break;
}
let top_crop = if visible_index == first {
truncation.min(icon_rows as u16)
} else {
0
};
let visible_icon_rows = (icon_rows as u16)
.saturating_sub(top_crop)
.min(area.y + area.height - y);
if visible_icon_rows > 0
&& entry.icon_bytes.is_some()
&& let Some(protocol) = state.image_protocols.get_mut(&entry.path)
{
let icon_area = Rect {
x: area.x + 1,
y,
width: protocol_icon_columns(entry, picker).min(area.width.saturating_sub(1)),
height: visible_icon_rows,
};
if icon_area.height > 0 && icon_area.width > 0 {
let clipped = top_crop > 0 || visible_icon_rows < icon_rows as u16;
let resize = if clipped {
Resize::Crop(Some(CropOptions {
clip_top: top_crop > 0,
clip_left: false,
}))
} else {
Resize::Scale(None)
};
let widget: StatefulImage<StatefulProtocol> =
StatefulImage::default().resize(resize);
frame.render_stateful_widget(widget, icon_area, protocol);
}
}
let visible_height = if visible_index == first {
height.saturating_sub(truncation)
} else {
height
};
y = y.saturating_add(visible_height);
if visible_index + 1 >= filtered.len() {
break;
}
}
}
// minecraft's 16-color palette, keyed by the formatting code character.
// these exact RGB values come from the minecraft wiki
fn mc_color(code: char) -> Option<Color> {
@@ -935,13 +1151,21 @@ fn strip_mc_codes(text: &str) -> String {
// renders one row of a mod icon using half-block characters (U+2584).
// each cell packs two vertical pixels via fg/bg colors, giving
// double the vertical resolution out of the terminal
fn icon_spans(icon_pixels: Option<&Vec<Vec<IconCell>>>, row: usize) -> Vec<Span<'static>> {
fn icon_spans(
icon_pixels: Option<&Vec<Vec<IconCell>>>,
row: usize,
use_image_protocol: bool,
protocol_columns: usize,
) -> Vec<Span<'static>> {
if use_image_protocol {
return vec![Span::raw(" ".repeat(protocol_columns))];
}
match icon_pixels.and_then(|rows| rows.get(row)) {
Some(cols) => cols
.iter()
.map(|cell| {
Span::styled(
"\u{2584}",
cell.symbol.to_string(),
Style::default()
.fg(Color::Rgb(cell.fg_r, cell.fg_g, cell.fg_b))
.bg(Color::Rgb(cell.bg_r, cell.bg_g, cell.bg_b)),
@@ -958,6 +1182,20 @@ fn icon_spans(icon_pixels: Option<&Vec<Vec<IconCell>>>, row: usize) -> Vec<Span<
}
}
fn protocol_icon_columns(
entry: &crate::instance::content::mods::ContentEntry,
picker: &ratatui_image::picker::Picker,
) -> u16 {
let rows = entry.icon_lines.as_ref().map_or(3, Vec::len) as u16;
square_icon_columns(rows, picker.font_size())
}
fn square_icon_columns(rows: u16, font_size: (u16, u16)) -> u16 {
let width = u32::from(font_size.0.max(1));
let height = u32::from(font_size.1.max(1));
((u32::from(rows) * height + width / 2) / width).max(1) as u16
}
// reads a content directory and builds a stem -> (path, enabled) map.
// used both by watch_dir to initialize known state and by the watcher
// thread to detect changes. when ext is empty (worlds), only directories
@@ -995,3 +1233,20 @@ fn read_dir_stems(dir: &std::path::Path, ext: &str) -> HashMap<String, (std::pat
map
}
#[cfg(test)]
mod tests {
use super::square_icon_columns;
#[test]
fn square_columns_follow_terminal_cell_ratio() {
assert_eq!(square_icon_columns(3, (8, 16)), 6);
assert_eq!(square_icon_columns(3, (8, 18)), 7);
assert_eq!(square_icon_columns(6, (8, 18)), 14);
}
#[test]
fn square_columns_handle_missing_cell_size() {
assert_eq!(square_icon_columns(3, (0, 0)), 3);
}
}
+5
View File
@@ -80,6 +80,7 @@ pub fn render(
screenshots_state: &mut crate::tui::widgets::screenshots_grid::ScreenshotsState,
logs_state: &mut crate::tui::widgets::logs_viewer::LogsState,
instances_dir: &std::path::Path,
picker: &ratatui_image::picker::Picker,
) {
let theme = THEME.as_ref();
let is_focused = focused == FocusedArea::Content;
@@ -239,6 +240,7 @@ pub fn render(
is_focused,
"Loading mods...",
"No mods installed.",
picker,
);
} else {
frame.render_widget(
@@ -270,6 +272,7 @@ pub fn render(
is_focused,
"Loading resource packs...",
"No resource packs installed.",
picker,
);
} else {
frame.render_widget(
@@ -301,6 +304,7 @@ pub fn render(
is_focused,
"Loading shaders...",
"No shaders installed.",
picker,
);
} else {
frame.render_widget(
@@ -370,6 +374,7 @@ pub fn render(
is_focused,
"Loading worlds...",
"No worlds saved.",
picker,
);
} else {
frame.render_widget(