Item tooltips for container contents, spawner data and op-only data
ItemContainerContents.addToTooltip: an item with a container (a shulker box, or a chest Ctrl + Pick Block copied) lists its first five stacks as "count x name" and how many more there are. Spawner.appendHoverText: a spawner or trial spawner item names the entity its block_entity_data spawns, else how to set one. ItemStack.OP_NBT_WARNING: for a player with game master permission, an item carrying data of an op-only block entity type (command blocks, lecterns, signs, spawners) warns that it might run commands. The item argument now refuses block_entity_data without an id or with an unknown block entity type, with vanilla's TypedEntityData messages. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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<String> {
|
||||
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(
|
||||
|
||||
@@ -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())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<String>,
|
||||
) -> Vec<String> {
|
||||
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<String> = 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");
|
||||
|
||||
Reference in New Issue
Block a user