feat(worlds): refine metadata cards

This commit is contained in:
objz committed 2026-08-01 17:08:43 +02:00
1 parent 3bee6d8338
commit 3192851556
13 files changed
+251 -127

No files matched your search

+1
View File
@@ -9,6 +9,7 @@ fn entry(file_stem: &str) -> ContentEntry {
source_slug: None,
installed_path: None,
provider_project: None,
world_details: None,
title_suffix: None,
footer_label: None,
description: String::new(),
+30
View File
@@ -2,6 +2,35 @@ use std::path::PathBuf;
use super::icons::IconCell;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WorldGameMode {
Survival,
Creative,
Adventure,
Spectator,
Hardcore,
}
impl WorldGameMode {
pub fn label(self) -> &'static str {
match self {
Self::Survival => "Survival",
Self::Creative => "Creative",
Self::Adventure => "Adventure",
Self::Spectator => "Spectator",
Self::Hardcore => "Hardcore",
}
}
}
#[derive(Debug, Clone)]
pub struct WorldDetails {
pub game_mode: Option<WorldGameMode>,
pub last_played: Option<chrono::DateTime<chrono::Utc>>,
pub minecraft_version: Option<String>,
pub size: Option<String>,
}
#[derive(Debug, Clone)]
pub struct ContentEntry {
pub file_stem: String,
@@ -9,6 +38,7 @@ pub struct ContentEntry {
pub source_slug: Option<String>,
pub installed_path: Option<PathBuf>,
pub provider_project: Option<super::manifest::ProviderProject>,
pub world_details: Option<WorldDetails>,
pub title_suffix: Option<String>,
pub footer_label: Option<String>,
pub description: String,
+1
View File
@@ -90,6 +90,7 @@ pub fn scan_one_mod(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry
source_slug: None,
installed_path: None,
provider_project: None,
world_details: None,
title_suffix: None,
footer_label: None,
description,
+1
View File
@@ -59,6 +59,7 @@ pub(crate) fn scan_one_pack(path: &Path, file_stem: &str, enabled: bool) -> Cont
source_slug: None,
installed_path: None,
provider_project: None,
world_details: None,
title_suffix: None,
footer_label: None,
description,
+31 -90
View File
@@ -7,7 +7,7 @@ use std::{fs::File, path::Path};
use flate2::read::GzDecoder;
use serde::Deserialize;
use super::entry::ContentEntry;
use super::entry::{ContentEntry, WorldDetails, WorldGameMode};
use super::{fallback_icon_large, make_icon_pixels};
pub fn scan_one_world(path: &Path, file_stem: &str, enabled: bool) -> ContentEntry {
@@ -18,7 +18,19 @@ pub fn scan_one_world(path: &Path, file_stem: &str, enabled: bool) -> ContentEnt
.or_else(|| Some(fallback_icon_large()));
let metadata = read_world_metadata(path);
let description = world_description(path, metadata.as_ref());
let last_played = world_last_played(path, metadata.as_ref());
let size = dir_size_approx(path);
let world_details = WorldDetails {
game_mode: metadata.as_ref().and_then(WorldMetadata::game_mode),
last_played,
minecraft_version: metadata
.as_ref()
.and_then(|metadata| metadata.version.as_ref())
.and_then(|version| version.name.as_deref())
.filter(|version| !version.trim().is_empty())
.map(str::to_owned),
size: (size > 0).then(|| format_size(size)),
};
ContentEntry {
name: metadata
@@ -31,9 +43,10 @@ pub fn scan_one_world(path: &Path, file_stem: &str, enabled: bool) -> ContentEnt
source_slug: None,
installed_path: None,
provider_project: None,
title_suffix: metadata.as_ref().and_then(WorldMetadata::game_mode),
world_details: Some(world_details),
title_suffix: None,
footer_label: None,
description,
description: String::new(),
enabled,
icon_bytes,
provider_icon: false,
@@ -89,16 +102,10 @@ struct WorldMetadata {
game_type: Option<i32>,
#[serde(rename = "hardcore")]
hardcore: Option<i8>,
#[serde(rename = "Difficulty")]
difficulty: Option<i8>,
#[serde(rename = "allowCommands")]
allow_commands: Option<i8>,
#[serde(rename = "LastPlayed")]
last_played: Option<i64>,
#[serde(rename = "Version")]
version: Option<WorldVersion>,
#[serde(rename = "DataVersion")]
data_version: Option<i32>,
}
#[derive(Debug, Deserialize)]
@@ -108,28 +115,15 @@ struct WorldVersion {
}
impl WorldMetadata {
fn game_mode(&self) -> Option<String> {
fn game_mode(&self) -> Option<WorldGameMode> {
if self.hardcore.is_some_and(|hardcore| hardcore != 0) {
return Some("Hardcore".to_owned());
return Some(WorldGameMode::Hardcore);
}
Some(
match self.game_type? {
0 => "Survival",
1 => "Creative",
2 => "Adventure",
3 => "Spectator",
_ => return None,
}
.to_owned(),
)
}
fn difficulty(&self) -> Option<&'static str> {
Some(match self.difficulty? {
0 => "Peaceful",
1 => "Easy",
2 => "Normal",
3 => "Hard",
Some(match self.game_type? {
0 => WorldGameMode::Survival,
1 => WorldGameMode::Creative,
2 => WorldGameMode::Adventure,
3 => WorldGameMode::Spectator,
_ => return None,
})
}
@@ -150,17 +144,12 @@ fn read_world_metadata(world_dir: &Path) -> Option<WorldMetadata> {
}
}
fn world_description(world_dir: &Path, metadata: Option<&WorldMetadata>) -> String {
fn world_last_played(
world_dir: &Path,
metadata: Option<&WorldMetadata>,
) -> Option<chrono::DateTime<chrono::Utc>> {
let level_dat = world_dir.join("level.dat");
let created = world_dir
.metadata()
.ok()
.and_then(|m| m.created().ok().or_else(|| m.modified().ok()))
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs());
let modified = metadata
metadata
.and_then(|metadata| metadata.last_played)
.filter(|millis| *millis > 0)
.map(|millis| millis / 1000)
@@ -171,56 +160,8 @@ fn world_description(world_dir: &Path, metadata: Option<&WorldMetadata>) -> Stri
.and_then(|m| m.modified().ok())
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs() as i64)
});
let dir_size = dir_size_approx(world_dir);
let mut lines = Vec::new();
if let Some(secs) = modified
&& let Some(dt) = chrono::DateTime::from_timestamp(secs, 0)
{
lines.push(format!("Last played: {}", dt.format("%Y-%m-%d %H:%M")));
}
if let Some(metadata) = metadata {
let mut settings = Vec::new();
if let Some(difficulty) = metadata.difficulty() {
settings.push(format!("Difficulty: {difficulty}"));
}
if let Some(allow_commands) = metadata.allow_commands {
settings.push(format!(
"Cheats: {}",
if allow_commands == 0 { "Off" } else { "On" }
));
}
if !settings.is_empty() {
lines.push(settings.join(" • "));
}
if let Some(version) = metadata
.version
.as_ref()
.and_then(|version| version.name.as_deref())
.filter(|version| !version.trim().is_empty())
{
lines.push(format!("Minecraft: {version}"));
} else if let Some(data_version) = metadata.data_version {
lines.push(format!("Data version: {data_version}"));
}
}
if let Some(secs) = created
&& let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0)
{
lines.push(format!("Created: {}", dt.format("%Y-%m-%d %H:%M")));
}
if dir_size > 0 {
lines.push(format!("Approx. size: {}", format_size(dir_size)));
}
lines.join("\n")
})
.and_then(|seconds| chrono::DateTime::from_timestamp(seconds, 0))
}
// only counts top-level files + region/ contents, not a full recursive walk.
+2
View File
@@ -75,6 +75,7 @@ fn toggle_entry_enable() {
source_slug: None,
installed_path: None,
provider_project: None,
world_details: None,
title_suffix: None,
footer_label: None,
description: String::new(),
@@ -351,6 +352,7 @@ fn toggle_entry_disable() {
source_slug: None,
installed_path: None,
provider_project: None,
world_details: None,
title_suffix: None,
footer_label: None,
description: String::new(),
+15 -9
View File
@@ -31,19 +31,25 @@ fn world_scan_uses_level_dat_metadata_and_falls_back_cleanly() {
let entry = scan_one_world(&world, "world-folder", true);
assert_eq!(entry.name, "Display World");
assert_eq!(entry.title_suffix.as_deref(), Some("Hardcore"));
assert!(entry.description.contains("Last played: 2023-11-14 22:13"));
assert!(
entry
.description
.contains("Difficulty: Hard • Cheats: Off")
let details = entry.world_details.as_ref().unwrap();
assert_eq!(details.game_mode, Some(WorldGameMode::Hardcore));
assert_eq!(
details.last_played,
chrono::DateTime::from_timestamp(1_700_000_000, 0)
);
assert!(entry.description.contains("Minecraft: 1.21.1"));
assert!(entry.description.contains("Approx. size:"));
assert_eq!(details.minecraft_version.as_deref(), Some("1.21.1"));
assert_eq!(details.size.as_deref(), Some("2.2 KB"));
assert!(entry.description.is_empty());
std::fs::write(world.join("level.dat"), b"not nbt").unwrap();
let fallback = scan_one_world(&world, "world-folder", true);
assert_eq!(fallback.name, "world-folder");
assert_eq!(fallback.title_suffix, None);
assert!(fallback.description.contains("Approx. size:"));
assert_eq!(
fallback
.world_details
.as_ref()
.and_then(|details| details.size.as_deref()),
Some("2.0 KB")
);
}
+1
View File
@@ -235,6 +235,7 @@ fn content_entry(name: &str, path: PathBuf) -> ContentEntry {
source_slug: None,
installed_path: Some(path.clone()),
provider_project: None,
world_details: None,
title_suffix: None,
footer_label: None,
description: String::new(),
+50 -5
View File
@@ -4,7 +4,7 @@ use std::{
sync::{Arc, Mutex},
};
use crate::instance::content::entry::ContentEntry;
use crate::instance::content::entry::{ContentEntry, WorldDetails, WorldGameMode};
use ratatui::{
buffer::Buffer,
layout::Rect,
@@ -17,6 +17,7 @@ use super::{
ContentListState, WatcherEventHandling, available_description_width, description_text_width,
diff_directory, diff_event_paths, ellipsize, load_provider_metadata, read_dir_stems,
right_aligned_footer_spans, square_icon_columns, title_suffix_spans, watcher_event_handling,
world_game_mode_color, world_summary_spans,
};
fn entry(name: &str) -> ContentEntry {
@@ -26,6 +27,7 @@ fn entry(name: &str) -> ContentEntry {
source_slug: None,
installed_path: None,
provider_project: None,
world_details: None,
title_suffix: None,
footer_label: None,
description: String::new(),
@@ -189,6 +191,42 @@ fn title_suffix_keeps_label_style_after_the_row_background_is_applied() {
assert!(label_cell.modifier.contains(Modifier::BOLD));
}
#[test]
fn world_modes_use_distinct_theme_roles() {
let theme = crate::config::theme::THEME.as_ref();
assert_eq!(
world_game_mode_color(WorldGameMode::Survival),
theme.success()
);
assert_eq!(world_game_mode_color(WorldGameMode::Creative), theme.info());
assert_eq!(
world_game_mode_color(WorldGameMode::Adventure),
theme.warning()
);
assert_eq!(
world_game_mode_color(WorldGameMode::Spectator),
theme.text_dim()
);
assert_eq!(
world_game_mode_color(WorldGameMode::Hardcore),
theme.error()
);
}
#[test]
fn mismatched_world_version_uses_the_error_color() {
let details = WorldDetails {
game_mode: None,
last_played: None,
minecraft_version: Some("1.20.1".to_owned()),
size: None,
};
let summary = "Minecraft 1.20.1";
let spans = world_summary_spans(&details, Some("1.21.1"), summary, summary, Style::default());
assert_eq!(spans[1].style.fg, Some(crate::config::theme::THEME.error()));
}
#[test]
fn descriptions_are_ellipsized_to_the_available_cell_width() {
assert_eq!(ellipsize("short", 5), "short");
@@ -428,14 +466,21 @@ fn rendering_visible_entries_restores_the_first_selection() {
#[test]
fn multiline_rendering_uses_the_space_beside_large_icons() {
let mut world = entry("World");
world.description =
"Last played\nDifficulty: Normal\nMinecraft: 1.21.1\nCreated\nApprox. size".to_owned();
world.world_details = Some(WorldDetails {
game_mode: Some(WorldGameMode::Survival),
last_played: None,
minecraft_version: Some("1.21.1".to_owned()),
size: Some("2.0 MB".to_owned()),
});
world.icon_lines = Some(crate::instance::content::fallback_icon_large());
let mut state = ContentListState::default();
let mut state = ContentListState {
expected_game_version: Some("1.21.1".to_owned()),
..Default::default()
};
state.entries.push(world);
state.rebuild_display_metadata();
let picker = ratatui_image::picker::Picker::halfblocks();
let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(50, 6)).unwrap();
let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(70, 6)).unwrap();
terminal
.draw(|frame| {
@@ -2,9 +2,9 @@
source: src/tui/tests/widgets/content/list.rs
expression: terminal.backend().to_string()
---
"▌▄▄▄▄▄▄▄▄▄▄▄▄ World "
"▌▄▄▄▄▄▄▄▄▄▄▄▄ Last played "
"▌▄▄▄▄▄▄▄▄▄▄▄▄ Difficulty: Normal "
"▌▄▄▄▄▄▄▄▄▄▄▄▄ Minecraft: 1.21.1 "
"▌▄▄▄▄▄▄▄▄▄▄▄▄ Created "
"▌▄▄▄▄▄▄▄▄▄▄▄▄ Approx. size "
"▌▄▄▄▄▄▄▄▄▄▄▄▄ World Survival "
"▌▄▄▄▄▄▄▄▄▄▄▄▄ Minecraft 1.21.1 • 2.0 MB Never played "
"▌▄▄▄▄▄▄▄▄▄▄▄▄ "
"▌▄▄▄▄▄▄▄▄▄▄▄▄ "
"▌▄▄▄▄▄▄▄▄▄▄▄▄ "
"▌▄▄▄▄▄▄▄▄▄▄▄▄ "
+1
View File
@@ -1182,6 +1182,7 @@ pub(crate) fn provider_project_entry(
project_id: project.id.clone(),
version_id: String::new(),
}),
world_details: None,
title_suffix: installed_path.is_some().then(|| "Installed".to_owned()),
footer_label: Some(format!("{} downloads", format_downloads(project.downloads))),
description: project.description,
+111 -17
View File
@@ -20,8 +20,9 @@ use ratatui_image::{CropOptions, Resize, StatefulImage, protocol::StatefulProtoc
use tui_widget_list::{ListBuilder, ListState as TuiListState, ListView};
use crate::config::theme::THEME;
use crate::instance::content::entry::ContentEntry;
use crate::instance::content::entry::{ContentEntry, WorldDetails, WorldGameMode};
use crate::instance::content::icons::IconCell;
use crate::time::format_relative_time;
type ScanOneFn = fn(&Path, &str, bool) -> ContentEntry;
static PROVIDER_ICON_SLOTS: LazyLock<Arc<tokio::sync::Semaphore>> =
@@ -197,6 +198,7 @@ pub struct ContentListState {
scan_one_fn: Option<ScanOneFn>,
content_ext: Option<&'static str>,
pagination: Option<PaginationState>,
pub(crate) expected_game_version: Option<String>,
}
#[derive(Clone, Debug)]
@@ -234,6 +236,7 @@ impl Default for ContentListState {
scan_one_fn: None,
content_ext: None,
pagination: None,
expected_game_version: None,
}
}
}
@@ -447,7 +450,8 @@ impl ContentListState {
let icon_rows = entry.icon_lines.as_ref().map_or(0, Vec::len);
let metadata = self.display_metadata.get(&entry.file_stem);
let has_second_line = metadata.is_some_and(|metadata| metadata.has_description)
|| entry.footer_label.is_some();
|| entry.footer_label.is_some()
|| entry.world_details.is_some();
icon_rows.max(if has_second_line { 2 } else { 1 }) as u16
}
@@ -1482,6 +1486,7 @@ pub fn render(
let display_metadata = &state.display_metadata;
let filtered_rows = &filtered;
let search = &state.search;
let expected_game_version = state.expected_game_version.as_deref();
let ready_image_stems: HashSet<String> = state.image_protocols.keys().cloned().collect();
let builder = ListBuilder::new(move |context| {
@@ -1491,8 +1496,13 @@ pub fn render(
let metadata = display_metadata.get(&entry.file_stem);
let enabled = entry.enabled;
let icon_pixels = &entry.icon_lines;
let title_suffix = entry.title_suffix.as_deref();
let footer_label = entry.footer_label.as_deref();
let world_details = entry.world_details.as_ref();
let title_suffix = world_details
.and_then(|details| details.game_mode)
.map(WorldGameMode::label)
.or(entry.title_suffix.as_deref());
let world_footer = world_details.map(|details| format_relative_time(details.last_played));
let footer_label = world_footer.as_deref().or(entry.footer_label.as_deref());
// Keep rendering the terminal fallback until the asynchronous image
// decoder has produced a protocol. Invalid and unsupported images
// therefore remain visible as a question mark instead of blank space.
@@ -1537,23 +1547,38 @@ pub fn render(
stripe_bg,
),
};
let title_suffix_color = world_details
.and_then(|details| details.game_mode)
.map(world_game_mode_color)
.unwrap_or_else(|| theme.success());
let title_suffix_style = Style::default()
.fg(theme.background())
.bg(theme.success())
.bg(title_suffix_color)
.add_modifier(Modifier::BOLD);
let footer_label_style = Style::default().fg(theme.text());
let footer_label_style = Style::default().fg(if world_details.is_some() {
theme.text_dim()
} else {
theme.text()
});
let world_summary = world_details
.map(world_summary)
.filter(|line| !line.is_empty());
let has_icon = icon_pixels.is_some();
let mut descriptions = metadata
.map(|metadata| {
metadata
.description
.lines()
.map(str::trim)
.filter(|line| !line.is_empty())
.collect::<Vec<_>>()
})
.unwrap_or_default();
let mut descriptions = if let Some(summary) = world_summary.as_deref() {
vec![summary]
} else {
metadata
.map(|metadata| {
metadata
.description
.lines()
.map(str::trim)
.filter(|line| !line.is_empty())
.collect::<Vec<_>>()
})
.unwrap_or_default()
};
if !multiline_descriptions {
descriptions.truncate(1);
}
@@ -1646,7 +1671,19 @@ pub fn render(
));
row.push(Span::raw(" "));
if let Some(description) = visible_descriptions.get(r - 1) {
row.extend(search.highlight_spans(description, description_style));
if r == 1
&& let Some(details) = world_details
{
row.extend(world_summary_spans(
details,
expected_game_version,
world_summary.as_deref().unwrap_or_default(),
description,
description_style,
));
} else {
row.extend(search.highlight_spans(description, description_style));
}
}
if r == 1
&& let Some(footer_label) = footer_label
@@ -2068,6 +2105,63 @@ fn icon_spans(
}
}
fn world_game_mode_color(mode: WorldGameMode) -> Color {
let theme = THEME.as_ref();
match mode {
WorldGameMode::Survival => theme.success(),
WorldGameMode::Creative => theme.info(),
WorldGameMode::Adventure => theme.warning(),
WorldGameMode::Spectator => theme.text_dim(),
WorldGameMode::Hardcore => theme.error(),
}
}
fn world_summary(details: &WorldDetails) -> String {
match (&details.minecraft_version, &details.size) {
(Some(version), Some(size)) => format!("Minecraft {version} • {size}"),
(Some(version), None) => format!("Minecraft {version}"),
(None, Some(size)) => size.clone(),
(None, None) => String::new(),
}
}
fn world_summary_spans(
details: &WorldDetails,
expected_game_version: Option<&str>,
summary: &str,
visible_summary: &str,
fallback_style: Style,
) -> Vec<Span<'static>> {
if summary != visible_summary {
return vec![Span::styled(visible_summary.to_owned(), fallback_style)];
}
let theme = THEME.as_ref();
let mut spans = Vec::new();
if let Some(version) = &details.minecraft_version {
let color = if expected_game_version.is_some_and(|expected| expected != version) {
theme.error()
} else {
theme.info()
};
spans.push(Span::styled("Minecraft ", fallback_style));
spans.push(Span::styled(
version.clone(),
Style::default().fg(color).add_modifier(Modifier::BOLD),
));
}
if let Some(size) = &details.size {
if !spans.is_empty() {
spans.push(Span::styled(" • ", fallback_style));
}
spans.push(Span::styled(
size.clone(),
Style::default().fg(theme.text_bright()).bg(theme.surface()),
));
}
spans
}
fn title_suffix_spans(
suffix: Option<&str>,
spacing_style: Style,
+1
View File
@@ -461,6 +461,7 @@ pub fn render(
}
ContentTab::Worlds => {
if let Some(instance) = instance {
worlds_state.expected_game_version = Some(instance.game_version.clone());
if worlds_state.loaded_for.as_deref() != Some(instance.name.as_str()) {
let content_dir = instances_dir
.join(&instance.name)