feat(worlds): add metadata cards and quick launch

This commit is contained in:
objz committed 2026-08-01 16:47:33 +02:00
1 parent 4eed312c3d
commit ea7478eb27
22 files changed
+585 -88

No files matched your search

+140 -19
View File
@@ -2,7 +2,10 @@
// their icon as icon.png. also computes an approximate size from top-level
// files + region data so the user gets some sense of how chonky their world is.
use std::path::Path;
use std::{fs::File, path::Path};
use flate2::read::GzDecoder;
use serde::Deserialize;
use super::entry::ContentEntry;
use super::{fallback_icon_large, make_icon_pixels};
@@ -14,15 +17,21 @@ pub fn scan_one_world(path: &Path, file_stem: &str, enabled: bool) -> ContentEnt
.and_then(|bytes| make_icon_pixels(bytes, 12, 6))
.or_else(|| Some(fallback_icon_large()));
let description = world_description(path);
let metadata = read_world_metadata(path);
let description = world_description(path, metadata.as_ref());
ContentEntry {
name: file_stem.to_owned(),
name: metadata
.as_ref()
.and_then(|metadata| metadata.level_name.as_deref())
.filter(|name| !name.trim().is_empty())
.unwrap_or(file_stem)
.to_owned(),
file_stem: file_stem.to_owned(),
source_slug: None,
installed_path: None,
provider_project: None,
title_suffix: None,
title_suffix: metadata.as_ref().and_then(WorldMetadata::game_mode),
footer_label: None,
description,
enabled,
@@ -66,7 +75,82 @@ pub fn scan_worlds(instances_dir: &Path, instance_name: &str) -> Vec<ContentEntr
entries
}
fn world_description(world_dir: &Path) -> String {
#[derive(Debug, Deserialize)]
struct LevelDat {
#[serde(rename = "Data")]
data: WorldMetadata,
}
#[derive(Debug, Deserialize)]
struct WorldMetadata {
#[serde(rename = "LevelName")]
level_name: Option<String>,
#[serde(rename = "GameType")]
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)]
struct WorldVersion {
#[serde(rename = "Name")]
name: Option<String>,
}
impl WorldMetadata {
fn game_mode(&self) -> Option<String> {
if self.hardcore.is_some_and(|hardcore| hardcore != 0) {
return Some("Hardcore".to_owned());
}
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",
_ => return None,
})
}
}
fn read_world_metadata(world_dir: &Path) -> Option<WorldMetadata> {
let path = world_dir.join("level.dat");
let file = File::open(&path).ok()?;
match fastnbt::from_reader::<_, LevelDat>(GzDecoder::new(file)) {
Ok(level) => Some(level.data),
Err(error) => {
tracing::debug!(
"Could not read world metadata from {}: {error}",
path.display()
);
None
}
}
}
fn world_description(world_dir: &Path, metadata: Option<&WorldMetadata>) -> String {
let level_dat = world_dir.join("level.dat");
let created = world_dir
@@ -76,31 +160,64 @@ fn world_description(world_dir: &Path) -> String {
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs());
let modified = level_dat
.metadata()
.ok()
.and_then(|m| m.modified().ok())
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs());
let modified = metadata
.and_then(|metadata| metadata.last_played)
.filter(|millis| *millis > 0)
.map(|millis| millis / 1000)
.or_else(|| {
level_dat
.metadata()
.ok()
.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 let Some(secs) = modified
&& let Some(dt) = chrono::DateTime::from_timestamp(secs as i64, 0)
{
lines.push(format!("Played: {}", dt.format("%Y-%m-%d %H:%M")));
lines.push(format!("Created: {}", dt.format("%Y-%m-%d %H:%M")));
}
if dir_size > 0 {
lines.push(format!("Size: {}", format_size(dir_size)));
lines.push(format!("Approx. size: {}", format_size(dir_size)));
}
lines.join("\n")
@@ -142,3 +259,7 @@ fn format_size(bytes: u64) -> String {
format!("{:.2} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
}
}
#[cfg(test)]
#[path = "../tests/content/worlds.rs"]
mod tests;
+59 -4
View File
@@ -11,8 +11,8 @@ use thiserror::Error;
use crate::auth::AccountType;
use crate::instance::models::{InstanceConfig, ModLoader};
use crate::launch_profile::model::LaunchProfile;
use crate::launch_profile::rules::{self, FeatureSet, RuleContext};
use crate::launch_profile::model::{Argument, LaunchProfile};
use crate::launch_profile::rules::{self, FeatureSet, RuleAction, RuleContext};
use crate::launch_profile::templates::TemplateContext;
use crate::launch_profile::{render, resolve, system};
@@ -306,6 +306,46 @@ pub struct LaunchInvocation {
pub working_dir: PathBuf,
}
pub fn supports_quick_play(meta_dir: &Path, game_version: &str) -> bool {
let path = crate::storage::MetadataPaths::new(meta_dir)
.versions()
.join(game_version)
.join("meta.json");
std::fs::read(path)
.ok()
.and_then(|bytes| serde_json::from_slice::<LaunchProfile>(&bytes).ok())
.is_some_and(|profile| profile_supports_quick_play(&profile))
}
fn profile_supports_quick_play(profile: &LaunchProfile) -> bool {
profile.arguments.as_ref().is_some_and(|arguments| {
arguments.game.iter().any(|argument| {
let Argument::Conditional { rules, .. } = argument else {
return false;
};
rules.iter().any(|rule| {
rule.action == RuleAction::Allow
&& rule
.features
.as_ref()
.is_some_and(|features| features.is_quick_play_singleplayer == Some(true))
})
})
})
}
fn validate_quick_play_world(minecraft_dir: &Path, world: &str) -> Result<(), LaunchError> {
let mut components = Path::new(world).components();
let is_single_name = matches!(components.next(), Some(std::path::Component::Normal(_)))
&& components.next().is_none();
if !is_single_name || !minecraft_dir.join("saves").join(world).is_dir() {
return Err(LaunchError::Parse(
"Selected Quick Play world is not a valid save".to_owned(),
));
}
Ok(())
}
// builds a fully-resolved java invocation for the given instance. reads
// meta.json and the loader profile from disk, migrates legacy formats if
// needed (may hit Mojang to refetch), resolves inheritsFrom, applies
@@ -316,6 +356,7 @@ pub async fn build_launch_invocation(
instances_dir: &Path,
meta_dir: &Path,
auth: &LaunchAuth<'_>,
quick_play_world: Option<&str>,
) -> Result<LaunchInvocation, LaunchError> {
let instance_dir = instances_dir.join(&config.name);
let minecraft_dir = instance_dir.join(crate::storage::MINECRAFT_DIR_NAME);
@@ -334,7 +375,14 @@ pub async fn build_launch_invocation(
None => meta,
};
let current_features = FeatureSet::default();
if let Some(world) = quick_play_world {
validate_quick_play_world(&minecraft_dir, world)?;
}
let current_features = FeatureSet {
is_quick_play_singleplayer: quick_play_world.map(|_| true),
..Default::default()
};
let host_os_version = system::mojang_os_version();
let rule_ctx = RuleContext {
os_name: system::mojang_os_name(),
@@ -404,6 +452,10 @@ pub async fn build_launch_invocation(
.clone()
.ok_or_else(|| LaunchError::Parse("merged profile missing mainClass".into()))?;
if quick_play_world.is_some() && !profile_supports_quick_play(&merged_profile) {
return Err(LaunchError::NotSupported("Quick Play".to_owned()));
}
// rebuild the classpath from the merged profile. vanilla-style libraries
// have `downloads.artifact.path` set and live in meta_dir/libraries/.
// loader-style libraries only have a maven coordinate; for forge/neoforge,
@@ -524,6 +576,7 @@ pub async fn build_launch_invocation(
launcher_name: "rmcl",
launcher_version: env!("CARGO_PKG_VERSION"),
clientid: "0",
quick_play_singleplayer: quick_play_world,
};
let (upstream_jvm_args, game_args) =
@@ -557,6 +610,7 @@ pub async fn launch(
config: &InstanceConfig,
instances_dir: &Path,
meta_dir: &Path,
quick_play_world: Option<&str>,
) -> Result<(), LaunchError> {
let name = config.name.clone();
@@ -614,7 +668,8 @@ pub async fn launch(
user_type,
};
let invocation = build_launch_invocation(config, instances_dir, meta_dir, &auth).await?;
let invocation =
build_launch_invocation(config, instances_dir, meta_dir, &auth, quick_play_world).await?;
tracing::debug!(
"[{}] Prepared launch invocation: working_dir={} classpath_entries={} jvm_args={} extra_args={} game_args={} main_class={}",
name,
+49
View File
@@ -0,0 +1,49 @@
use std::io::Write;
use flate2::{Compression, write::GzEncoder};
use super::*;
#[test]
fn world_scan_uses_level_dat_metadata_and_falls_back_cleanly() {
let temp = tempfile::tempdir().unwrap();
let world = temp.path().join("world-folder");
std::fs::create_dir_all(world.join("region")).unwrap();
std::fs::write(world.join("region/r.0.0.mca"), vec![0; 2048]).unwrap();
let nbt = fastnbt::nbt!({
"Data": {
"LevelName": "Display World",
"GameType": 0,
"hardcore": 1_i8,
"Difficulty": 3_i8,
"allowCommands": 0_i8,
"LastPlayed": 1_700_000_000_000_i64,
"Version": { "Name": "1.21.1" },
"DataVersion": 3955,
}
});
let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
encoder
.write_all(&fastnbt::to_bytes(&nbt).unwrap())
.unwrap();
std::fs::write(world.join("level.dat"), encoder.finish().unwrap()).unwrap();
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")
);
assert!(entry.description.contains("Minecraft: 1.21.1"));
assert!(entry.description.contains("Approx. size:"));
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:"));
}
+12
View File
@@ -12,6 +12,17 @@ fn parse_java_major_version_handles_common_outputs(
assert_eq!(parse_java_major_version(output), expected);
}
#[test]
fn quick_play_world_must_be_a_direct_save_directory() {
let temp = tempfile::tempdir().unwrap();
let minecraft = temp.path().join("minecraft");
std::fs::create_dir_all(minecraft.join("saves/World")).unwrap();
assert!(validate_quick_play_world(&minecraft, "World").is_ok());
assert!(validate_quick_play_world(&minecraft, "../World").is_err());
assert!(validate_quick_play_world(&minecraft, "Missing").is_err());
}
#[test]
fn build_game_args_renders_upstream_arguments() {
use crate::launch_profile::model::{Argument, Arguments, LaunchProfile};
@@ -42,6 +53,7 @@ fn build_game_args_renders_upstream_arguments() {
launcher_name: "rmcl",
launcher_version: "test",
clientid: "0",
quick_play_singleplayer: None,
version_type: "release",
};
let features = FeatureSet::default();