diff --git a/crates/horizon-client/src/block_entity_item.rs b/crates/horizon-client/src/block_entity_item.rs index 762de7c22..2361dcbfb 100644 --- a/crates/horizon-client/src/block_entity_item.rs +++ b/crates/horizon-client/src/block_entity_item.rs @@ -23,6 +23,29 @@ pub const OP_ONLY: [&str; 6] = [ "minecraft:trial_spawner", ]; +/// The `minecraft:block_entity_data` of `stack`: its type id and its data. +pub fn data(stack: &crate::items::ItemStack) -> Option<(String, &Tag)> { + let data = stack.data()?.other(BLOCK_ENTITY_DATA)?; + Some((block_entity_nbt::id(data)?, data)) +} + +/// `BlockItem.shouldPrintOpWarning` for a player with game master permission: +/// the item carries data of an op-only type. +pub fn op_warning(stack: &crate::items::ItemStack) -> bool { + data(stack).is_some_and(|(id, _)| OP_ONLY.contains(&id.as_str())) +} + +/// `Spawner.getSpawnEntityDisplayName` (`SpawnData.entity.id` of the item's +/// data, which `ItemStack.addDetailsToTooltip` reads for spawners and trial +/// spawners alike): the entity type a spawner item spawns. +pub fn spawner_entity(stack: &crate::items::ItemStack) -> Option { + let (_, data) = data(stack)?; + match data.get("SpawnData")?.get("entity")?.get("id")? { + Tag::String(id) => Some(id.to_string_lossy()), + _ => None, + } +} + /// A part of a block entity's NBT that its item holds as a component. #[derive(Clone, Copy)] enum Part { @@ -424,6 +447,29 @@ mod tests { assert_eq!(place(&chest, &patch, true), chest); } + #[test] + fn item_data_names_its_spawn_and_op_only_types() { + let item = |text: &str| { + let components = snbt(&format!("{{\"minecraft:block_entity_data\":{text}}}")); + let (damage, extra) = crate::item_data::decode_components(Some(&components)); + crate::items::ItemStack { + damage, + extra, + ..crate::items::ItemStack::new("minecraft:spawner", 1) + } + }; + let spawner = + item("{id:\"minecraft:mob_spawner\",SpawnData:{entity:{id:\"minecraft:zombie\"}}}"); + assert_eq!( + spawner_entity(&spawner).as_deref(), + Some("minecraft:zombie") + ); + assert!(op_warning(&spawner)); + let chest = item("{id:\"minecraft:chest\",LootTable:\"x\"}"); + assert_eq!(spawner_entity(&chest), None); + assert!(!op_warning(&chest)); + } + #[test] fn a_written_sign_gives_its_text_and_wax() { let sign = saved( diff --git a/crates/horizon-client/src/command/item.rs b/crates/horizon-client/src/command/item.rs index e0ed4a516..7c8abe84a 100644 --- a/crates/horizon-client/src/command/item.rs +++ b/crates/horizon-client/src/command/item.rs @@ -61,6 +61,33 @@ pub fn decode_component(id: &str, t: &Tag) -> Result<(), String> { _ => Err(not_map(t)), }, "minecraft:custom_name" | "minecraft:item_name" => super::component::decode(t), + // TypedEntityData.codec: the type is the compound's id. + "minecraft:block_entity_data" => match t { + Tag::Compound(c) => match c.get(&"id".into()) { + None => Err(format!("Expected 'id' field in {}", snbt(t))), + Some(Tag::String(id)) => { + let id = id.to_string_lossy(); + let id = if id.contains(':') { + id + } else { + format!("minecraft:{id}") + }; + let known = crate::block_entity_nbt::TYPES + .iter() + .chain(&crate::block_entity_nbt::NEWEST) + .any(|k| *k == id); + if known { + Ok(()) + } else { + Err(format!( + "Unknown registry key in ResourceKey[minecraft:root / minecraft:block_entity_type]: {id}" + )) + } + } + Some(_) => Ok(()), + }, + _ => Ok(()), + }, _ => Ok(()), } } @@ -609,3 +636,26 @@ pub fn suggest_predicate(builder: &mut SuggestionsBuilder, reg: &Registries) { fn _unused(t: &Tag) -> String { snbt(t) } + +#[cfg(test)] +mod tests { + use super::decode_component; + + fn check(snbt: &str) -> Result<(), String> { + let tag = horizon_world::nbt::parse_snbt(snbt).expect("snbt").0; + decode_component("minecraft:block_entity_data", &tag) + } + + #[test] + fn block_entity_data_needs_a_known_type() { + assert_eq!(check("{id:\"chest\",Lock:1}"), Ok(())); + assert_eq!( + check("{Command:\"say\"}"), + Err("Expected 'id' field in {Command:\"say\"}".into()) + ); + assert_eq!( + check("{id:\"minecraft:stone\"}"), + Err("Unknown registry key in ResourceKey[minecraft:root / minecraft:block_entity_type]: minecraft:stone".into()) + ); + } +} diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 4a2e00349..d8a5d1416 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -5,7 +5,7 @@ //! `BrewingStandScreen`); item rules live in `horizon_client::stations`. use super::{Game, Screen}; use horizon_client::{ - brewing, + block_entity_item, brewing, containers::BlockEntity, enchant::Enchantments, hud::{HudBatch, rgba}, @@ -1894,6 +1894,15 @@ impl Game<'_> { self.res.names.item(&stack.item) }; let mut lines = vec![(name, color)]; + let translate = |k: &str| e.translate(k).map(str::to_owned); + // ItemContainerContents.addToTooltip. + let hover_name = |s: &ItemStack| { + s.custom_name() + .map_or_else(|| self.res.names.item(&s.item), str::to_owned) + }; + for line in horizon_client::item_tooltip::container_lines(stack, &hover_name, &translate) { + lines.push((line, u32::MAX)); + } if stack.item.ends_with("potion") || &*stack.item == "minecraft:tipped_arrow" { let scale = match &*stack.item { "minecraft:lingering_potion" => 0.25, @@ -1947,6 +1956,27 @@ impl Game<'_> { let key = self.res.stations.banners.layer_key(layer); lines.push((self.translate(&key, &key), rgba(170, 170, 170, 255))); } + // Spawner.appendHoverText: what a spawner or trial spawner item spawns. + if matches!( + &*stack.item, + "minecraft:spawner" | "minecraft:trial_spawner" + ) { + let gray = rgba(170, 170, 170, 255); + match block_entity_item::spawner_entity(stack) { + Some(id) => { + let key = format!("entity.{}", id.replacen(':', ".", 1)); + lines.push((self.translate(&key, &id), gray)); + } + None => { + lines.push((String::new(), u32::MAX)); + let desc1 = + self.translate("block.minecraft.spawner.desc1", "Interact with Spawn Egg:"); + lines.push((desc1, gray)); + let desc2 = self.translate("block.minecraft.spawner.desc2", "Sets Mob Type"); + lines.push((format!(" {desc2}"), rgba(85, 85, 255, 255))); + } + } + } if let Some(info) = self.res.items.get(&stack.item) && info.max_damage > 0 && stack.damage > 0 @@ -1961,6 +1991,22 @@ impl Game<'_> { u32::MAX, )); } + // ItemStack.OP_NBT_WARNING, for a player with game master permission. + if self.ui.registries.permission >= 2 && block_entity_item::op_warning(stack) { + for (key, fallback) in [ + ("item.op_warning.line1", "Warning:"), + ( + "item.op_warning.line2", + "Use of this item might lead to command execution.", + ), + ( + "item.op_warning.line3", + "Do not use unless you know the exact contents!", + ), + ] { + lines.push((self.translate(key, fallback), rgba(255, 85, 85, 255))); + } + } lines } /// Menu state for the control socket. diff --git a/crates/horizon-client/src/item_tooltip.rs b/crates/horizon-client/src/item_tooltip.rs index 764470149..cd827d411 100644 --- a/crates/horizon-client/src/item_tooltip.rs +++ b/crates/horizon-client/src/item_tooltip.rs @@ -247,6 +247,36 @@ pub fn detail_lines( lines } +/// `ItemContainerContents.addToTooltip`: "count x name" for the first five +/// stacks, by slot, then how many more there are (an italic line). +pub fn container_lines( + stack: &ItemStack, + name: &dyn Fn(&ItemStack) -> String, + translate: &dyn Fn(&str) -> Option, +) -> Vec { + let Some(data) = stack.data() else { + return Vec::new(); + }; + let mut slots: Vec<&(u8, ItemStack)> = data.container.iter().collect(); + slots.sort_by_key(|(slot, _)| *slot); + let count = translate("item.container.item_count").unwrap_or_else(|| "%s x %s".into()); + let mut lines: Vec = slots + .iter() + .take(5) + .map(|(_, s)| { + count + .replacen("%s", &s.count.to_string(), 1) + .replacen("%s", &name(s), 1) + }) + .collect(); + if slots.len() > 5 { + let more = + translate("item.container.more_items").unwrap_or_else(|| "and %s more...".into()); + lines.push(more.replacen("%s", &(slots.len() - 5).to_string(), 1)); + } + lines +} + /// Every line of `stack`'s tooltip, name first. pub fn lines( stack: &ItemStack, @@ -262,6 +292,40 @@ pub fn lines( mod tests { use super::*; + #[test] + fn container_lines_list_five_stacks_then_how_many_more() { + let mut chest = ItemStack::new("minecraft:chest", 1); + for slot in [9u8, 1, 2, 3, 4, 5, 6] { + chest + .data_mut() + .container + .push((slot, ItemStack::new("minecraft:stone", u32::from(slot)))); + } + let lang = |k: &str| { + Some( + match k { + "item.container.item_count" => "%s x %s", + "item.container.more_items" => "and %s more...", + _ => return None, + } + .to_owned(), + ) + }; + let name = |s: &ItemStack| s.item.trim_start_matches("minecraft:").to_owned(); + assert_eq!( + container_lines(&chest, &name, &lang), + [ + "1 x stone", + "2 x stone", + "3 x stone", + "4 x stone", + "5 x stone", + "and 2 more..." + ] + ); + assert!(container_lines(&ItemStack::new("minecraft:chest", 1), &name, &lang).is_empty()); + } + #[test] fn amounts_use_two_decimals_at_most() { assert_eq!(format_amount(8.0), "8");