diff --git a/Cargo.lock b/Cargo.lock index b40106b..e4cb7a9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -354,6 +354,12 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "byteorder-lite" version = "0.1.0" @@ -396,6 +402,12 @@ dependencies = [ "shlex", ] +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + [[package]] name = "cfg-if" version = "1.0.4" @@ -1138,6 +1150,18 @@ dependencies = [ "vt-push-parser", ] +[[package]] +name = "fastnbt" +version = "2.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c075c8f2b92819bec6af26321830809f47574c72fd5b53ce81436bbac54bcea" +dependencies = [ + "byteorder", + "cesu8", + "serde", + "serde_bytes", +] + [[package]] name = "fastrand" version = "2.4.1" @@ -3630,6 +3654,8 @@ dependencies = [ "dirs", "dirs-next", "fast-strip-ansi", + "fastnbt", + "flate2", "fs2", "html-to-markdown-rs", "image", @@ -3942,6 +3968,16 @@ dependencies = [ "typeid", ] +[[package]] +name = "serde_bytes" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8" +dependencies = [ + "serde", + "serde_core", +] + [[package]] name = "serde_core" version = "1.0.228" diff --git a/Cargo.toml b/Cargo.toml index 67f8766..b1457b1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -70,6 +70,8 @@ regex = "1" fast-strip-ansi = "0.13" libcasr = "2.13" fs2 = "0.4" +fastnbt = "2.6.2" +flate2 = "1.1.9" [profile.release] diff --git a/src/cli/instance.rs b/src/cli/instance.rs index c54ab75..62c181d 100644 --- a/src/cli/instance.rs +++ b/src/cli/instance.rs @@ -136,7 +136,7 @@ async fn launch_instance(matches: &ArgMatches) -> CliResult { let meta_dir = crate::config::SETTINGS.paths.resolve_meta_dir(); let config = manager.load_one(name)?; - crate::instance::launch::launch(&config, &instances_dir, &meta_dir) + crate::instance::launch::launch(&config, &instances_dir, &meta_dir, None) .await .map_err(|error| io::Error::other(format!("Launch failed: {}", error)))?; diff --git a/src/instance/content/worlds.rs b/src/instance/content/worlds.rs index cbc1eab..97c1b0a 100644 --- a/src/instance/content/worlds.rs +++ b/src/instance/content/worlds.rs @@ -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 String { +#[derive(Debug, Deserialize)] +struct LevelDat { + #[serde(rename = "Data")] + data: WorldMetadata, +} + +#[derive(Debug, Deserialize)] +struct WorldMetadata { + #[serde(rename = "LevelName")] + level_name: Option, + #[serde(rename = "GameType")] + game_type: Option, + #[serde(rename = "hardcore")] + hardcore: Option, + #[serde(rename = "Difficulty")] + difficulty: Option, + #[serde(rename = "allowCommands")] + allow_commands: Option, + #[serde(rename = "LastPlayed")] + last_played: Option, + #[serde(rename = "Version")] + version: Option, + #[serde(rename = "DataVersion")] + data_version: Option, +} + +#[derive(Debug, Deserialize)] +struct WorldVersion { + #[serde(rename = "Name")] + name: Option, +} + +impl WorldMetadata { + fn game_mode(&self) -> Option { + 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 { + 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; diff --git a/src/instance/launch/mod.rs b/src/instance/launch/mod.rs index e7085d8..7ddf9ca 100644 --- a/src/instance/launch/mod.rs +++ b/src/instance/launch/mod.rs @@ -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::(&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 { 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, diff --git a/src/instance/tests/content/worlds.rs b/src/instance/tests/content/worlds.rs new file mode 100644 index 0000000..edfc7a6 --- /dev/null +++ b/src/instance/tests/content/worlds.rs @@ -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:")); +} diff --git a/src/instance/tests/launch/pipeline.rs b/src/instance/tests/launch/pipeline.rs index 631f0d9..6ab7281 100644 --- a/src/instance/tests/launch/pipeline.rs +++ b/src/instance/tests/launch/pipeline.rs @@ -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(); diff --git a/src/launch_profile/rules.rs b/src/launch_profile/rules.rs index 1a384e1..3fe77c7 100644 --- a/src/launch_profile/rules.rs +++ b/src/launch_profile/rules.rs @@ -27,11 +27,9 @@ pub struct OsCondition { pub struct FeatureSet { pub is_demo_user: Option, pub has_custom_resolution: Option, - // quick-play feature flags (1.20+). rmcl never sets these, so any rule - // gated on them is filtered out by features_match. listing them - // explicitly is what makes that filter work: without the fields, - // serde would silently drop them during deserialization, leaving a - // FeatureSet::default that matches everything. + // quick-play feature flags (1.20+). normal launches leave these unset; + // world quick launch enables only the singleplayer flag. listing every + // flag explicitly keeps unrelated conditional arguments filtered out. pub has_quick_plays_support: Option, pub is_quick_play_singleplayer: Option, pub is_quick_play_multiplayer: Option, diff --git a/src/launch_profile/templates.rs b/src/launch_profile/templates.rs index 0bd563b..6b43aff 100644 --- a/src/launch_profile/templates.rs +++ b/src/launch_profile/templates.rs @@ -29,6 +29,7 @@ pub struct TemplateContext<'a> { pub launcher_name: &'a str, pub launcher_version: &'a str, pub clientid: &'a str, + pub quick_play_singleplayer: Option<&'a str>, } pub fn substitute(input: &str, ctx: &TemplateContext) -> String { @@ -63,15 +64,6 @@ pub fn substitute(input: &str, ctx: &TemplateContext) -> String { out } -// quick-play templates (`${quickPlayPath}`, `${quickPlaySingleplayer}`, -// `${quickPlayMultiplayer}`, `${quickPlayRealms}`) are intentionally not -// listed here. they only appear in `arguments.game` entries gated on -// `is_quick_play_*` feature flags; since rmcl never sets those flags -// (FeatureSet defaults to None across the board), the surrounding -// conditional argument is filtered out by the rule evaluator before -// template substitution even runs. if we ever expose quick-play to users, -// add the variables here AND set the corresponding feature flags in -// RuleContext at launch. fn lookup(name: &str, ctx: &TemplateContext) -> Option { Some(match name { "library_directory" => ctx.library_directory.display().to_string(), @@ -92,6 +84,7 @@ fn lookup(name: &str, ctx: &TemplateContext) -> Option { "launcher_name" => ctx.launcher_name.to_string(), "launcher_version" => ctx.launcher_version.to_string(), "clientid" => ctx.clientid.to_string(), + "quickPlaySingleplayer" => ctx.quick_play_singleplayer?.to_owned(), _ => return None, }) } diff --git a/src/launch_profile/tests/render.rs b/src/launch_profile/tests/render.rs index 07f60f2..0533774 100644 --- a/src/launch_profile/tests/render.rs +++ b/src/launch_profile/tests/render.rs @@ -46,6 +46,7 @@ impl Fixture { launcher_name: "rmcl", launcher_version: "0.3.0", clientid: "0", + quick_play_singleplayer: None, } } diff --git a/src/launch_profile/tests/templates.rs b/src/launch_profile/tests/templates.rs index bfa7659..447196a 100644 --- a/src/launch_profile/tests/templates.rs +++ b/src/launch_profile/tests/templates.rs @@ -54,6 +54,7 @@ impl Fixture { launcher_name: "rmcl", launcher_version: "0.3.0", clientid: "0", + quick_play_singleplayer: None, } } } @@ -100,3 +101,14 @@ fn windows_style_backslashes_in_value_pass_through() { "expected backslashes preserved, got: {result}" ); } + +#[test] +fn quick_play_world_is_substituted_when_present() { + let fx = Fixture::unix(); + let mut context = fx.ctx(); + context.quick_play_singleplayer = Some("New World"); + assert_eq!( + substitute("${quickPlaySingleplayer}", &context), + "New World" + ); +} diff --git a/src/tui/app.rs b/src/tui/app.rs index 1b16565..ed7612f 100644 --- a/src/tui/app.rs +++ b/src/tui/app.rs @@ -31,6 +31,7 @@ pub struct App { pub(super) shaders_state: widgets::content::list::ContentListState, pub(super) shaders_discovery_state: widgets::content::DiscoveryState, pub(super) worlds_state: widgets::content::list::ContentListState, + pub(super) world_quick_play_support: Option<(String, String, bool)>, pub(super) screenshots_state: widgets::screenshots_grid::ScreenshotsState, pub(super) logs_state: widgets::logs_viewer::LogsState, pub(super) account_state: widgets::account::AccountState, @@ -80,6 +81,28 @@ pub enum FocusedArea { } impl App { + pub(super) fn selected_instance_supports_quick_play(&mut self) -> bool { + let Some((name, game_version)) = self + .instances_state + .selected_instance() + .map(|instance| (instance.name.clone(), instance.game_version.clone())) + else { + return false; + }; + if let Some((cached_name, cached_version, supported)) = &self.world_quick_play_support + && cached_name == &name + && cached_version == &game_version + { + return *supported; + } + let supported = crate::instance::launch::supports_quick_play( + &self.instance_manager.meta_dir, + &game_version, + ); + self.world_quick_play_support = Some((name, game_version, supported)); + supported + } + 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(); @@ -123,6 +146,7 @@ impl App { crate::instance::ContentKind::Shader, ), worlds_state: widgets::content::list::ContentListState::default(), + world_quick_play_support: None, logs_state: widgets::logs_viewer::LogsState::default(), account_state: widgets::account::AccountState::default(), settings_state: widgets::settings::SettingsState::new(manager.meta_dir.clone()), diff --git a/src/tui/event.rs b/src/tui/event.rs index a20edc8..5bc3b36 100644 --- a/src/tui/event.rs +++ b/src/tui/event.rs @@ -552,7 +552,11 @@ impl App { } } - pub(super) fn spawn_launch(&self, instance: crate::instance::InstanceConfig) { + pub(super) fn spawn_launch( + &self, + instance: crate::instance::InstanceConfig, + quick_play_world: Option, + ) { use crate::instance::launch; use crate::instance::runtime; @@ -569,13 +573,30 @@ impl App { } }; + let can_launch = matches!( + runtime::get(&instance.name), + None | Some(runtime::RunState::Crashed(_)) + ); + if !can_launch { + return; + } + runtime::remove(&instance.name); + crate::instance::logs::live::clear(&instance.name); + runtime::set_state(&instance.name, runtime::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 { + if let Err(e) = launch::launch( + &instance, + &instances_dir, + &meta_dir, + quick_play_world.as_deref(), + ) + .await + { tracing::error!("Failed to launch '{}': {}", instance.name, e); runtime::remove(&instance.name); } diff --git a/src/tui/input.rs b/src/tui/input.rs index 3d56d52..232dc3e 100644 --- a/src/tui/input.rs +++ b/src/tui/input.rs @@ -366,6 +366,21 @@ impl App { return Ok(()); } } else if self.content_tab == widgets::content::ContentTab::Worlds { + if key_event.code == KeyCode::Char('q') && !self.worlds_state.search.active { + if self.selected_instance_supports_quick_play() { + let instance = self.instances_state.selected_instance().cloned(); + let world = self + .worlds_state + .selected_entry() + .and_then(|entry| entry.path.file_name()) + .and_then(|name| name.to_str()) + .map(str::to_owned); + if let (Some(instance), Some(world)) = (instance, world) { + self.spawn_launch(instance, Some(world)); + } + } + return Ok(()); + } if key_event.code == KeyCode::Char('d') && !self.worlds_state.search.active { if let Some(pending) = self.worlds_state.pending_delete() { self.confirm_content_delete(pending); @@ -631,15 +646,7 @@ impl App { && !self.instances_state.search.active => { if let Some(instance) = self.instances_state.selected_instance().cloned() { - let can_launch = matches!( - crate::instance::runtime::get(&instance.name), - None | Some(crate::instance::runtime::RunState::Crashed(_)) - ); - if can_launch { - crate::instance::runtime::remove(&instance.name); - crate::instance::logs::live::clear(&instance.name); - self.spawn_launch(instance); - } + self.spawn_launch(instance, None); } } KeyCode::Char('r') diff --git a/src/tui/render.rs b/src/tui/render.rs index 6b3e6d3..471c98e 100644 --- a/src/tui/render.rs +++ b/src/tui/render.rs @@ -60,6 +60,7 @@ impl App { self.instances_state.selected_instance(), &mut self.throbber_state, ); + let world_quick_play_supported = self.selected_instance_supports_quick_play(); if load_content { widgets::content::render( frame, @@ -79,6 +80,7 @@ impl App { &mut self.logs_state, &self.instance_manager.instances_dir, &self.picker, + world_quick_play_supported, ); } else { frame.render_widget( diff --git a/src/tui/tests/flows.rs b/src/tui/tests/flows.rs index 76038ae..6fc28e8 100644 --- a/src/tui/tests/flows.rs +++ b/src/tui/tests/flows.rs @@ -32,6 +32,41 @@ fn global_navigation_returns_from_log_overlay() { assert!(ui.app.exit); } +#[test] +fn worlds_reserves_q_for_available_quick_launch() { + let mut ui = UiHarness::new(); + ui.add_instance("Test Instance"); + ui.app.focused = FocusedArea::Content; + ui.app.content_tab = ContentTab::Worlds; + + ui.key(KeyCode::Char('q')); + assert!(!ui.app.exit, "unsupported Quick Play must not quit rmcl"); + + let meta = serde_json::json!({ + "id": "1.21.1", + "mainClass": "net.minecraft.client.main.Main", + "arguments": { + "game": [{ + "rules": [{ + "action": "allow", + "features": { "is_quick_play_singleplayer": true } + }], + "value": ["--quickPlaySingleplayer", "${quickPlaySingleplayer}"] + }], + "jvm": [] + } + }); + let meta_path = crate::storage::MetadataPaths::new(&ui.app.instance_manager.meta_dir) + .versions() + .join("1.21.1/meta.json"); + std::fs::create_dir_all(meta_path.parent().unwrap()).unwrap(); + std::fs::write(meta_path, serde_json::to_vec(&meta).unwrap()).unwrap(); + ui.app.world_quick_play_support = None; + ui.draw(); + + assert!(ui.screen().contains("quick launch")); +} + #[test] fn mouse_wheel_uses_the_focused_views_scroll_navigation() { let mut ui = UiHarness::new(); diff --git a/src/tui/tests/harness.rs b/src/tui/tests/harness.rs index 9a3057c..035ffd3 100644 --- a/src/tui/tests/harness.rs +++ b/src/tui/tests/harness.rs @@ -66,6 +66,7 @@ impl UiHarness { crate::instance::ContentKind::Shader, ), worlds_state: widgets::content::ContentListState::default(), + world_quick_play_support: None, screenshots_state: { let mut state = widgets::screenshots_grid::ScreenshotsState::default(); state.font_size = (font_size.width, font_size.height); diff --git a/src/tui/tests/widgets/content/list.rs b/src/tui/tests/widgets/content/list.rs index 616968c..488443f 100644 --- a/src/tui/tests/widgets/content/list.rs +++ b/src/tui/tests/widgets/content/list.rs @@ -417,6 +417,7 @@ fn rendering_visible_entries_restores_the_first_selection() { "Empty", &picker, false, + false, ); }) .unwrap(); @@ -424,6 +425,37 @@ fn rendering_visible_entries_restores_the_first_selection() { assert_eq!(state.list_state.selected, Some(0)); } +#[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.icon_lines = Some(crate::instance::content::fallback_icon_large()); + let mut state = ContentListState::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(); + + terminal + .draw(|frame| { + super::render( + frame, + frame.area(), + &mut state, + true, + "Loading...", + "Empty", + &picker, + false, + true, + ); + }) + .unwrap(); + + insta::assert_snapshot!(terminal.backend().to_string()); +} + #[test] fn pager_tracks_viewport_pages_and_jumps_to_their_first_item() { assert_eq!( @@ -470,6 +502,7 @@ fn pager_tracks_viewport_pages_and_jumps_to_their_first_item() { "Empty", &picker, true, + false, ); }) .unwrap(); diff --git a/src/tui/tests/widgets/content/snapshots/rmcl__tui__widgets__content__list__tests__multiline_rendering_uses_the_space_beside_large_icons.snap b/src/tui/tests/widgets/content/snapshots/rmcl__tui__widgets__content__list__tests__multiline_rendering_uses_the_space_beside_large_icons.snap new file mode 100644 index 0000000..9932271 --- /dev/null +++ b/src/tui/tests/widgets/content/snapshots/rmcl__tui__widgets__content__list__tests__multiline_rendering_uses_the_space_beside_large_icons.snap @@ -0,0 +1,10 @@ +--- +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 " diff --git a/src/tui/widgets/content/list.rs b/src/tui/widgets/content/list.rs index 13a0a25..5d5330f 100644 --- a/src/tui/widgets/content/list.rs +++ b/src/tui/widgets/content/list.rs @@ -1006,6 +1006,15 @@ impl ContentListState { .map(|entry| entry.file_stem.clone()) } + pub fn selected_entry(&self) -> Option<&ContentEntry> { + let filtered = self.filtered_indices(); + let index = self + .list_state + .selected + .and_then(|index| filtered.get(index))?; + self.entries.get(*index) + } + fn restore_selected_file_stem(&mut self, file_stem: Option<&str>) { let filtered = self.filtered_indices(); self.list_state.selected = file_stem @@ -1421,6 +1430,7 @@ pub fn render( empty_text: &str, picker: &ratatui_image::picker::Picker, paginate: bool, + multiline_descriptions: bool, ) { let theme = THEME.as_ref(); state.pagination = None; @@ -1534,8 +1544,20 @@ pub fn render( let footer_label_style = Style::default().fg(theme.text()); let has_icon = icon_pixels.is_some(); - let stripped_desc = metadata.map_or("", |metadata| metadata.description.as_str()); - let has_description = metadata.is_some_and(|metadata| metadata.has_description); + let mut descriptions = metadata + .map(|metadata| { + metadata + .description + .lines() + .map(str::trim) + .filter(|line| !line.is_empty()) + .collect::>() + }) + .unwrap_or_default(); + if !multiline_descriptions { + descriptions.truncate(1); + } + let has_description = !descriptions.is_empty(); let rendered_icon_columns = if use_image_protocol && has_image { protocol_columns } else { @@ -1549,10 +1571,21 @@ pub fn render( rendered_icon_columns, has_icon, ); - let visible_description = ellipsize( - stripped_desc, - description_text_width(description_width, footer_label, has_description), - ); + let visible_descriptions = descriptions + .iter() + .enumerate() + .map(|(index, description)| { + ellipsize( + description, + if index == 0 { + description_text_width(description_width, footer_label, has_description) + } else { + description_width + }, + ) + }) + .collect::>(); + let visible_description = visible_descriptions.first().map_or("", String::as_str); let compact = !has_icon && !has_description && footer_label.is_none(); let selector = if show_selected { @@ -1575,11 +1608,9 @@ 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 text_rows = if has_description || footer_label.is_some() { - 2 - } else { - 1 - }; + let text_rows = 1 + visible_descriptions + .len() + .max(usize::from(footer_label.is_some())); let height = icon_row_count.max(text_rows) as u16; let pad = if show_selected { @@ -1605,22 +1636,24 @@ pub fn render( let mut lines = vec![Line::from(line_0)]; - if has_description || footer_label.is_some() { + for r in 1..text_rows { let mut row = vec![pad.clone()]; row.extend(icon_spans( icon_pixels.as_ref(), - 1, + r, use_image_protocol && has_image, protocol_columns, )); row.push(Span::raw(" ")); - if has_description { - row.extend(search.highlight_spans(&visible_description, description_style)); + if let Some(description) = visible_descriptions.get(r - 1) { + row.extend(search.highlight_spans(description, description_style)); } - if let Some(footer_label) = footer_label { + if r == 1 + && let Some(footer_label) = footer_label + { row.extend(right_aligned_footer_spans( description_width, - &visible_description, + visible_description, has_description, footer_label, footer_label_style, @@ -1663,12 +1696,12 @@ pub fn render( let mut description = vec![pad]; if has_description { description - .extend(search.highlight_spans(&visible_description, description_style)); + .extend(search.highlight_spans(visible_description, description_style)); } if let Some(footer_label) = footer_label { description.extend(right_aligned_footer_spans( description_width, - &visible_description, + visible_description, has_description, footer_label, footer_label_style, @@ -1994,7 +2027,7 @@ fn strip_mc_codes(text: &str) -> String { fn display_metadata(entry: &ContentEntry) -> DisplayMetadata { let description = strip_mc_codes(&entry.description); - let description = description.lines().next().unwrap_or("").trim().to_string(); + let description = description.trim().to_string(); DisplayMetadata { has_description: !description.is_empty(), description, diff --git a/src/tui/widgets/content/tabs.rs b/src/tui/widgets/content/tabs.rs index a144658..3086b5c 100644 --- a/src/tui/widgets/content/tabs.rs +++ b/src/tui/widgets/content/tabs.rs @@ -165,6 +165,7 @@ pub fn render( logs_state: &mut crate::tui::widgets::logs_viewer::LogsState, instances_dir: &std::path::Path, picker: &ratatui_image::picker::Picker, + world_quick_play_supported: bool, ) { let theme = THEME.as_ref(); let is_focused = focused == FocusedArea::Content; @@ -319,6 +320,15 @@ pub fn render( ("/", " search"), ("Tab", " discover"), ], + (ContentMode::Installed, ContentTab::Worlds) if world_quick_play_supported => &[ + ("j/k", " navigate"), + ("q", " quick launch"), + ("d", " delete"), + ("Shift+⏎", " open dir"), + ("h/l", " tabs"), + ("/", " search"), + ("Tab", " discover"), + ], (ContentMode::Installed, ContentTab::Worlds) => &[ ("j/k", " navigate"), ("d", " delete"), @@ -473,6 +483,7 @@ pub fn render( "No worlds saved.", picker, false, + true, ); } else { frame.render_widget( @@ -534,6 +545,7 @@ fn render_downloadable( tab.empty_text, picker, false, + false, ); } } @@ -611,6 +623,7 @@ fn render_discovery_body( &empty_text, picker, paginate, + false, ); } if state.version_popup.is_some() { diff --git a/tests/launch_pipeline.rs b/tests/launch_pipeline.rs index e93b532..d770758 100644 --- a/tests/launch_pipeline.rs +++ b/tests/launch_pipeline.rs @@ -10,7 +10,9 @@ use chrono::Utc; use serde_json::json; use tempfile::TempDir; -use rmcl::instance::launch::{LaunchAuth, LaunchError, build_launch_invocation}; +use rmcl::instance::launch::{ + LaunchAuth, LaunchError, build_launch_invocation, supports_quick_play, +}; use rmcl::instance::models::{InstanceConfig, ModLoader}; // ---------- helpers ---------- @@ -201,7 +203,7 @@ async fn vanilla_modern_builds_complete_invocation() { let fx = Fixture::new("v1", "1.20.1", modern_vanilla_meta("1.20.1")); let config = make_config("v1", "1.20.1", ModLoader::Vanilla); - let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth(), None) .await .unwrap(); @@ -249,6 +251,43 @@ async fn vanilla_modern_builds_complete_invocation() { assert!(inv.classpath.contains(&client_jar)); } +#[tokio::test] +async fn quick_play_passes_the_selected_save_folder() { + let mut meta = modern_vanilla_meta("1.20.1"); + meta["arguments"]["game"] + .as_array_mut() + .unwrap() + .push(json!({ + "rules": [{ + "action": "allow", + "features": { "is_quick_play_singleplayer": true } + }], + "value": ["--quickPlaySingleplayer", "${quickPlaySingleplayer}"] + })); + let fx = Fixture::new("quick", "1.20.1", meta); + let world_dir = fx.instances_dir.join("quick/minecraft/saves/Display World"); + std::fs::create_dir_all(&world_dir).unwrap(); + let config = make_config("quick", "1.20.1", ModLoader::Vanilla); + + assert!(supports_quick_play(&fx.meta_dir, "1.20.1")); + let invocation = build_launch_invocation( + &config, + &fx.instances_dir, + &fx.meta_dir, + &test_auth(), + Some("Display World"), + ) + .await + .unwrap(); + + assert!( + invocation + .game_args + .windows(2) + .any(|args| args == ["--quickPlaySingleplayer", "Display World"]) + ); +} + #[cfg(unix)] #[tokio::test] async fn launch_fails_when_selected_java_is_older_than_profile_requires() { @@ -260,7 +299,7 @@ async fn launch_fails_when_selected_java_is_older_than_profile_requires() { let mut config = make_config("java-old", "26.1.2", ModLoader::Vanilla); config.java_path = Some(fake_java(&fx._tmp, 21)); - let err = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + let err = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth(), None) .await .expect_err("java 21 should fail for a Java 25 profile"); @@ -282,7 +321,7 @@ async fn vanilla_legacy_args_format_substitutes_tokens() { let fx = Fixture::new("vlegacy", "1.7.10", legacy_vanilla_meta("1.7.10")); let config = make_config("vlegacy", "1.7.10", ModLoader::Vanilla); - let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth(), None) .await .unwrap(); @@ -328,7 +367,7 @@ async fn forge_modern_includes_add_opens() { ); let config = make_config_with("f1", "1.20.1", ModLoader::Forge, Some("47.2.0")); - let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth(), None) .await .unwrap(); @@ -384,7 +423,7 @@ async fn forge_local_lib_dir_preferred_over_meta_dir() { std::fs::write(&local_jar, b"jar").unwrap(); let config = make_config_with("f2", "1.20.1", ModLoader::Forge, Some("47.2.0")); - let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth(), None) .await .unwrap(); @@ -423,7 +462,7 @@ async fn fabric_implicit_inheritsfrom_resolves() { ); let config = make_config_with("fab", "1.20.1", ModLoader::Fabric, Some("0.15.0")); - let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth(), None) .await .unwrap(); @@ -473,7 +512,7 @@ async fn neoforge_inheritsfrom_resolves() { ); let config = make_config_with("ne", "1.20.6", ModLoader::NeoForge, Some("20.4.190")); - let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth(), None) .await .unwrap(); @@ -497,7 +536,7 @@ async fn auth_credentials_substituted_in_game_args() { let fx = Fixture::new("auth", "1.20.1", modern_vanilla_meta("1.20.1")); let config = make_config("auth", "1.20.1", ModLoader::Vanilla); - let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth(), None) .await .unwrap(); @@ -531,7 +570,7 @@ async fn version_type_substituted() { let fx = Fixture::new("vt", "1.20.1", meta); let config = make_config("vt", "1.20.1", ModLoader::Vanilla); - let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth(), None) .await .unwrap(); @@ -549,7 +588,7 @@ async fn classpath_uses_platform_separator() { let fx = Fixture::new("cp", "1.20.1", modern_vanilla_meta("1.20.1")); let config = make_config("cp", "1.20.1", ModLoader::Vanilla); - let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth(), None) .await .unwrap(); @@ -591,7 +630,7 @@ async fn rule_disallow_excludes_library() { let fx = Fixture::new("rule", "1.20.1", meta); let config = make_config("rule", "1.20.1", ModLoader::Vanilla); - let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth(), None) .await .unwrap(); @@ -612,7 +651,7 @@ async fn xms_xmx_use_config_memory() { config.memory_min = Some("1G".into()); config.memory_max = Some("4G".into()); - let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth(), None) .await .unwrap(); @@ -626,7 +665,7 @@ async fn default_memory_used_when_unset() { let config = make_config("memdef", "1.20.1", ModLoader::Vanilla); // memory_min and memory_max default to None in make_config - let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + let inv = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth(), None) .await .unwrap(); @@ -645,7 +684,7 @@ async fn meta_not_found_returns_error() { std::fs::create_dir_all(meta_dir.join("cache/minecraft/versions")).unwrap(); let config = make_config("ghost", "1.20.1", ModLoader::Vanilla); - let err = build_launch_invocation(&config, &instances_dir, &meta_dir, &test_auth()) + let err = build_launch_invocation(&config, &instances_dir, &meta_dir, &test_auth(), None) .await .unwrap_err(); assert!( @@ -659,7 +698,7 @@ async fn loader_profile_missing_returns_error() { let fx = Fixture::new("lpmiss", "1.20.1", modern_vanilla_meta("1.20.1")); let config = make_config_with("lpmiss", "1.20.1", ModLoader::Fabric, Some("0.15.0")); - let err = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + let err = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth(), None) .await .unwrap_err(); assert!( @@ -678,7 +717,7 @@ async fn merged_profile_missing_main_class_fails() { let fx = Fixture::new("nomc", "1.20.1", meta); let config = make_config("nomc", "1.20.1", ModLoader::Vanilla); - let err = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + let err = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth(), None) .await .unwrap_err(); let msg = format!("{err:?}"); @@ -708,7 +747,7 @@ async fn legacy_loader_profile_missing_loader_version_errors() { let mut config = make_config("nolv", "1.20.1", ModLoader::Forge); config.loader_version = None; - let err = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + let err = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth(), None) .await .unwrap_err(); let msg = format!("{err:?}"); @@ -735,7 +774,7 @@ async fn legacy_loader_profile_missing_installer_json_errors() { let config = make_config_with("noinst", "1.20.1", ModLoader::Forge, Some("47.2.0")); - let err = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth()) + let err = build_launch_invocation(&config, &fx.instances_dir, &fx.meta_dir, &test_auth(), None) .await .unwrap_err(); let msg = format!("{err:?}");