feat(worlds): add metadata cards and quick launch
This commit is contained in:
1 parent
4eed312c3d
commit
ea7478eb27
22 files changed
+585
-88
No files matched your search
+1
-1
@@ -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)))?;
|
||||
|
||||
|
||||
+140
-19
@@ -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;
|
||||
@@ -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,
|
||||
|
||||
@@ -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,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();
|
||||
|
||||
@@ -27,11 +27,9 @@ pub struct OsCondition {
|
||||
pub struct FeatureSet {
|
||||
pub is_demo_user: Option<bool>,
|
||||
pub has_custom_resolution: Option<bool>,
|
||||
// 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<bool>,
|
||||
pub is_quick_play_singleplayer: Option<bool>,
|
||||
pub is_quick_play_multiplayer: Option<bool>,
|
||||
|
||||
@@ -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<String> {
|
||||
Some(match name {
|
||||
"library_directory" => ctx.library_directory.display().to_string(),
|
||||
@@ -92,6 +84,7 @@ fn lookup(name: &str, ctx: &TemplateContext) -> Option<String> {
|
||||
"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,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -46,6 +46,7 @@ impl Fixture {
|
||||
launcher_name: "rmcl",
|
||||
launcher_version: "0.3.0",
|
||||
clientid: "0",
|
||||
quick_play_singleplayer: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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"
|
||||
);
|
||||
}
|
||||
@@ -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()),
|
||||
|
||||
+23
-2
@@ -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<String>,
|
||||
) {
|
||||
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);
|
||||
}
|
||||
|
||||
+16
-9
@@ -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')
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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();
|
||||
|
||||
+10
@@ -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 "
|
||||
@@ -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::<Vec<_>>()
|
||||
})
|
||||
.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::<Vec<_>>();
|
||||
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,
|
||||
|
||||
@@ -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() {
|
||||
|
||||
Reference in new issue
Block a user