Merge pull request #1857 from Joansitoh/fix/item-lore-tooltips

🤖 Agent: merged after contribution gate 14 (integration run of main + this PR, harnesses for the touched areas) and verify on the resolved head. Thank you!
This commit is contained in:
Ludovic Marie
2026-10-25 23:01:30 +01:00
committed by GitHub
9 changed files with 322 additions and 60 deletions
@@ -0,0 +1,53 @@
//! Lore tooltip companion for tools/test_lore_tooltip_parity.py: the spans
//! `item_tooltip::lore_texts` gives each stack (SNBT, one per line).
use horizon_client::{
item_data::parse_stack,
item_tooltip::{TooltipDisplay, lore_texts},
};
use std::{error::Error, fmt::Write};
pub fn main() -> Result<(), Box<dyn Error>> {
let args: Vec<String> = crate::args().collect();
let input = std::fs::read_to_string(&args[1])?;
let mut output = String::new();
for line in input
.lines()
.filter(|l| !l.is_empty() && !l.starts_with('#'))
{
let stack = parse_stack(line)?.ok_or("empty stack")?;
let display = TooltipDisplay::for_stack(&stack);
if !display.shows("minecraft:lore") {
writeln!(output, "-")?;
continue;
}
let lines = lore_texts(&stack);
if lines.is_empty() {
writeln!(output, "-")?;
continue;
}
let mut rendered = Vec::new();
for text in lines {
let mut spans = Vec::new();
for span in &text.spans {
if span.text.is_empty() {
continue;
}
let style = &span.style;
spans.push(format!(
"{}\t{}\t{}\t{}\t{}\t{}\t{}",
span.text,
style.color.map(|c| c as i32).unwrap_or(-1),
style.bold == Some(true),
style.italic == Some(true),
style.underlined == Some(true),
style.strikethrough == Some(true),
style.obfuscated == Some(true),
));
}
rendered.push(spans.join(" | "));
}
writeln!(output, "{}", rendered.join(" || "))?;
}
std::fs::write(&args[2], output)?;
Ok(())
}
@@ -49,6 +49,7 @@ mod input_probe;
mod interaction_input_fixture;
mod lan_probe;
mod light_parity;
mod lore_tooltip_fixture;
mod marker_particles_probe;
mod menu_fixture;
mod mipmap_probe;
@@ -133,6 +134,7 @@ probes! {
interaction_input_fixture,
lan_probe,
light_parity,
lore_tooltip_fixture,
marker_particles_probe,
menu_fixture,
mipmap_probe,
+6 -1
View File
@@ -519,7 +519,12 @@ impl Game<'_> {
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
} else if let Some(key) = tooltip {
let text = self.translate(&key, &key);
self.draw_tooltip_lines(batch, &[(text, u32::MAX)], self.cursor.0, self.cursor.1);
self.draw_tooltip_lines(
batch,
&[(horizon_client::text::Text::literal(text), u32::MAX)],
self.cursor.0,
self.cursor.1,
);
}
}
/// `BeaconRenderer`: each section's rotating solid beam and its glow.
+6 -3
View File
@@ -218,7 +218,7 @@ impl Game<'_> {
oy: f32,
draws: &[ScreenDraw],
background: bool,
) -> Option<Vec<(String, u32)>> {
) -> Option<Vec<(horizon_client::text::Text, u32)>> {
let atlas = &self.gui.atlas;
let mut tooltip = None;
let mut sheet: Option<String> = None;
@@ -261,7 +261,10 @@ impl Game<'_> {
..
} => self.draw_banner_result(batch, ox + *x0 as f32, oy + *y0 as f32, base, layers),
ScreenDraw::Tooltip { key } => {
tooltip = Some(vec![(self.translate(key, key), u32::MAX)]);
tooltip = Some(vec![(
horizon_client::text::Text::literal(self.translate(key, key)),
u32::MAX,
)]);
}
ScreenDraw::SpriteOf { id } => sheet = Some(id.clone()),
ScreenDraw::Fill {
@@ -314,7 +317,7 @@ impl Game<'_> {
ox: f32,
oy: f32,
local: (f32, f32),
) -> Option<Vec<(String, u32)>> {
) -> Option<Vec<(horizon_client::text::Text, u32)>> {
let s = self.station.as_ref()?;
let l = &s.loom;
let dye = s.inputs[1]
+16 -5
View File
@@ -1163,8 +1163,12 @@ impl Game<'_> {
}
/// Paints recipe book calls; returns the first tooltip set (vanilla keeps
/// the first one a frame asks for).
fn paint_book(&mut self, batch: &mut HudBatch, calls: &[Drawn]) -> Option<Vec<(String, u32)>> {
let mut tooltip: Option<Vec<(String, u32)>> = None;
fn paint_book(
&mut self,
batch: &mut HudBatch,
calls: &[Drawn],
) -> Option<Vec<(horizon_client::text::Text, u32)>> {
let mut tooltip: Option<Vec<(horizon_client::text::Text, u32)>> = None;
for d in calls {
let start = batch.vertices.len();
let atlas = &self.gui.atlas;
@@ -1259,7 +1263,14 @@ impl Game<'_> {
tooltip = Some(
lines
.iter()
.map(|l| (l.iter().map(|r| r.text.as_str()).collect(), u32::MAX))
.map(|l| {
(
horizon_client::text::Text::literal(
l.iter().map(|r| r.text.as_str()).collect::<String>(),
),
u32::MAX,
)
})
.collect(),
);
}
@@ -1269,10 +1280,10 @@ impl Game<'_> {
let mut lines = self.stack_tooltip(stack);
if *more {
lines.push((
self.translate(
horizon_client::text::Text::literal(self.translate(
"gui.recipebook.moreRecipes",
"Right Click for More",
),
)),
u32::MAX,
));
}
+90 -45
View File
@@ -1092,7 +1092,7 @@ impl Game<'_> {
}
let (ox, oy) = self.inventory_origin(batch);
let local = (self.cursor.0 - ox, self.cursor.1 - oy);
let mut tooltip: Option<Vec<(String, u32)>> = None;
let mut tooltip: Option<Vec<(horizon_client::text::Text, u32)>> = None;
{
let atlas = &self.gui.atlas;
batch.fill(
@@ -1341,16 +1341,19 @@ impl Game<'_> {
let clue = self
.translate("container.enchant.clue", "%s . . . ?")
.replace("%s", &name);
let mut lines = vec![(clue, u32::MAX)];
let mut lines =
vec![(horizon_client::text::Text::literal(clue), u32::MAX)];
if !self.creative {
lines.push((String::new(), u32::MAX));
lines.push((horizon_client::text::Text::literal(""), u32::MAX));
if level < cost {
lines.push((
self.translate(
"container.enchant.level.requirement",
"Level Requirement: %s",
)
.replace("%s", &cost.to_string()),
horizon_client::text::Text::literal(
self.translate(
"container.enchant.level.requirement",
"Level Requirement: %s",
)
.replace("%s", &cost.to_string()),
),
rgba(255, 85, 85, 255),
));
} else {
@@ -1368,7 +1371,7 @@ impl Game<'_> {
.replace("%s", &n.to_string())
};
lines.push((
lapis,
horizon_client::text::Text::literal(lapis),
if gold >= n as i32 {
rgba(170, 170, 170, 255)
} else {
@@ -1387,7 +1390,10 @@ impl Game<'_> {
)
.replace("%s", &n.to_string())
};
lines.push((levels, rgba(170, 170, 170, 255)));
lines.push((
horizon_client::text::Text::literal(levels),
rgba(170, 170, 170, 255),
));
}
}
tooltip = Some(lines);
@@ -1496,10 +1502,10 @@ impl Game<'_> {
);
if inside(local, 65.0, 46.0, 28.0, 21.0) {
tooltip = Some(vec![(
self.translate(
horizon_client::text::Text::literal(self.translate(
"container.upgrade.error_tooltip",
"Item can't be upgraded this way",
),
)),
u32::MAX,
)]);
}
@@ -1626,9 +1632,12 @@ impl Game<'_> {
// ---------------------------------------------------------------- tooltips
/// `ItemStack.getTooltipLines` subset: name in rarity colour, potion
/// effects, enchantments (gray, curses red), stored enchantments, trims.
pub(super) fn stack_tooltip(&self, stack: &ItemStack) -> Vec<(String, u32)> {
/// `ItemStack.getTooltipLines` subset: name in rarity colour, lore,
/// potion effects, enchantments (gray, curses red), stored enchantments, trims.
pub(super) fn stack_tooltip(
&self,
stack: &ItemStack,
) -> Vec<(horizon_client::text::Text, u32)> {
let e: &Enchantments = &self.res.stations().enchantments;
let props = e.props(&stack.item);
let rarity = horizon_client::item_tooltip::rarity(
@@ -1660,24 +1669,27 @@ impl Game<'_> {
let display = horizon_client::item_tooltip::TooltipDisplay::for_stack(stack);
let mut lines = Vec::new();
if display.name_visible(self.screen == Screen::Creative) {
lines.push((name, color));
lines.push((horizon_client::text::Text::legacy(&name), color));
}
let translate = |k: &str| self.pack.names.display_get(k);
let push = |lines: &mut Vec<(horizon_client::text::Text, u32)>, s: String, c: u32| {
lines.push((horizon_client::text::Text::legacy(&s), c));
};
// ItemContainerContents.addToTooltip.
let hover_name = |s: &ItemStack| {
s.custom_name()
.map_or_else(|| self.pack.names.display_item(&s.item), str::to_owned)
};
if display.shows("minecraft:container") {
for line in
for text in
horizon_client::item_tooltip::container_lines(stack, &hover_name, &translate)
{
lines.push((line, u32::MAX));
push(&mut lines, text, u32::MAX);
}
}
// Fireworks / FireworkExplosion.addToTooltip.
for line in horizon_client::item_tooltip::firework_lines(stack, &translate) {
lines.push((line, rgba(170, 170, 170, 255)));
for text in horizon_client::item_tooltip::firework_lines(stack, &translate) {
push(&mut lines, text, rgba(170, 170, 170, 255));
}
if display.shows("minecraft:potion_contents")
&& (stack.item.ends_with("potion") || &*stack.item == "minecraft:tipped_arrow")
@@ -1687,7 +1699,7 @@ impl Game<'_> {
"minecraft:tipped_arrow" => 0.125,
_ => 1.0,
};
for (line, cat) in brewing::tooltip(stack.potion(), scale, &|k| {
for (text, cat) in brewing::tooltip(stack.potion(), scale, &|k| {
e.translate(k).map(str::to_owned)
}) {
let c = match cat {
@@ -1695,18 +1707,19 @@ impl Game<'_> {
brewing::Category::Harmful => rgba(255, 85, 85, 255),
brewing::Category::Neutral => rgba(170, 170, 170, 255),
};
lines.push((line, c));
push(&mut lines, text, c);
}
}
if display.shows("minecraft:trim")
&& let Some((material, pattern)) = stack.data().and_then(|d| d.trim.clone())
{
lines.push((
push(
&mut lines,
e.translate("item.minecraft.smithing_template.upgrade")
.unwrap_or("Upgrade:")
.to_owned(),
rgba(170, 170, 170, 255),
));
);
let short = |s: &str| s.trim_start_matches("minecraft:").to_owned();
let p = e
.translate(&format!("trim_pattern.minecraft.{}", short(&pattern)))
@@ -1714,38 +1727,51 @@ impl Game<'_> {
let m = e
.translate(&format!("trim_material.minecraft.{}", short(&material)))
.map_or_else(|| short(&material), str::to_owned);
lines.push((format!(" {p}"), rgba(170, 170, 170, 255)));
lines.push((format!(" {m}"), rgba(170, 170, 170, 255)));
push(&mut lines, format!(" {p}"), rgba(170, 170, 170, 255));
push(&mut lines, format!(" {m}"), rgba(170, 170, 170, 255));
}
if display.shows("minecraft:stored_enchantments") {
for (text, curse) in e.tooltip(stack.stored_enchantments()) {
lines.push((
push(
&mut lines,
text,
if curse {
rgba(255, 85, 85, 255)
} else {
rgba(170, 170, 170, 255)
},
));
);
}
}
if display.shows("minecraft:enchantments") {
for (text, curse) in e.tooltip(stack.enchantments()) {
lines.push((
push(
&mut lines,
text,
if curse {
rgba(255, 85, 85, 255)
} else {
rgba(170, 170, 170, 255)
},
));
);
}
}
// BannerPatternLayers.addToTooltip: up to six layer names.
if display.shows("minecraft:banner_patterns") {
for layer in horizon_client::banner::tooltip_layers(stack).iter().take(6) {
let key = self.res.stations().banners.layer_key(layer);
lines.push((self.translate(&key, &key), rgba(170, 170, 170, 255)));
push(
&mut lines,
self.translate(&key, &key),
rgba(170, 170, 170, 255),
);
}
}
// ItemLore.addToTooltip: after the enchantments, before the attributes
// (ItemStack.addDetailsToTooltip).
if display.shows("minecraft:lore") {
for text in horizon_client::item_tooltip::lore_texts(stack) {
lines.push((text, u32::MAX));
}
}
// Spawner.appendHoverText: what a spawner or trial spawner item spawns.
@@ -1759,15 +1785,15 @@ impl Game<'_> {
match block_entity_item::spawner_entity(stack) {
Some(id) => {
let key = format!("entity.{}", id.replacen(':', ".", 1));
lines.push((self.translate(&key, &id), gray));
push(&mut lines, self.translate(&key, &id), gray);
}
None => {
lines.push((String::new(), u32::MAX));
push(&mut lines, String::new(), u32::MAX);
let desc1 =
self.translate("block.minecraft.spawner.desc1", "Interact with Spawn Egg:");
lines.push((desc1, gray));
push(&mut lines, desc1, gray);
let desc2 = self.translate("block.minecraft.spawner.desc2", "Sets Mob Type");
lines.push((format!(" {desc2}"), rgba(85, 85, 255, 255)));
push(&mut lines, format!(" {desc2}"), rgba(85, 85, 255, 255));
}
}
}
@@ -1795,11 +1821,13 @@ impl Game<'_> {
horizon_client::attack_strength::BASE_ATTACK_SPEED,
),
];
lines.extend(horizon_client::item_tooltip::attribute_lines(
for (text, c) in horizon_client::item_tooltip::attribute_lines(
&info.modifiers,
Some(player_base),
&translate,
));
) {
push(&mut lines, text, c);
}
}
if display.shows("minecraft:damage")
&& let Some(info) = self.res.items().get(&stack.item)
@@ -1807,14 +1835,15 @@ impl Game<'_> {
&& stack.damage > 0
&& self.options_advanced_tooltips()
{
lines.push((
push(
&mut lines,
format!(
"Durability: {} / {}",
info.max_damage - stack.damage,
info.max_damage
),
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) {
@@ -1829,7 +1858,11 @@ impl Game<'_> {
"Do not use unless you know the exact contents!",
),
] {
lines.push((self.translate(key, fallback), rgba(255, 85, 85, 255)));
push(
&mut lines,
self.translate(key, fallback),
rgba(255, 85, 85, 255),
);
}
}
lines
@@ -1860,20 +1893,27 @@ impl Game<'_> {
self.settings.file.bool("advancedItemTooltips")
}
/// `TooltipRenderUtil`: dark box with the purple border, first line spaced.
pub(super) fn draw_tooltip_lines(
pub(super) fn draw_tooltip_lines<T: Clone + Into<horizon_client::text::Text>>(
&self,
batch: &mut HudBatch,
lines: &[(String, u32)],
lines: &[(T, u32)],
x: f32,
y: f32,
) {
if lines.is_empty() {
return;
}
let lines: Vec<_> = lines
.iter()
.map(|(text, color)| {
let text: horizon_client::text::Text = text.clone().into();
(text.resolve_legacy(), *color)
})
.collect();
let atlas = &self.gui.atlas;
let w = lines
.iter()
.map(|(t, _)| HudBatch::text_width(atlas, t))
.map(|(t, _)| atlas.font.width_text(t))
.fold(0.0, f32::max);
let h = if lines.len() == 1 {
8.0
@@ -1926,7 +1966,7 @@ impl Game<'_> {
);
let mut ty = y;
for (i, (text, color)) in lines.iter().enumerate() {
batch.text(atlas, text, x, ty, *color, true);
batch.text_styled(atlas, text, x, ty, *color, true);
ty += if i == 0 { 12.0 } else { 10.0 };
}
}
@@ -1943,7 +1983,12 @@ impl Game<'_> {
let lines = self.stack_tooltip(&stack);
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
} else if let Some(text) = self.crafter_tooltip(slot) {
self.draw_tooltip_lines(batch, &[(text, u32::MAX)], self.cursor.0, self.cursor.1);
self.draw_tooltip_lines(
batch,
&[(horizon_client::text::Text::literal(text), u32::MAX)],
self.cursor.0,
self.cursor.1,
);
}
}
+50 -6
View File
@@ -487,23 +487,31 @@ pub fn lines(
) -> Vec<String> {
let mut lines = vec![name_line(stack, translate)];
if TooltipDisplay::for_stack(stack).shows("minecraft:lore") {
lines.extend(lore_lines(stack));
lines.extend(lore_texts(stack).into_iter().map(|t| t.plain()));
}
lines.extend(detail_lines(stack, info, translate));
lines
}
/// `LoreComponent.addToTooltip`: the saved component lines, as plain text.
fn lore_lines(stack: &ItemStack) -> Vec<String> {
/// `ItemLore.addToTooltip`: each lore component under dark purple italic, with
/// the component's own styles (including explicit `false`) winning on children.
pub fn lore_texts(stack: &ItemStack) -> Vec<crate::text::Text> {
let Some(Tag::List(entries)) = stack.data().and_then(|d| d.other("minecraft:lore")) else {
return Vec::new();
};
let base = crate::text::Style {
color: Some(crate::text::DARK_PURPLE),
italic: Some(true),
..Default::default()
};
entries
.iter()
.map(|entry| {
let json = crate::scoreboard::tag_to_json(entry);
let text = crate::component::to_text(&json, &mut |s| crate::text::Text::literal(s));
text.plain()
let mut text = crate::entity_nbt::name_text(entry).resolve_legacy();
for span in &mut text.spans {
span.style.inherit(&base);
}
text
})
.collect()
}
@@ -512,6 +520,42 @@ fn lore_lines(stack: &ItemStack) -> Vec<String> {
mod tests {
use super::*;
#[test]
fn lore_keeps_component_colours_under_dark_purple_italic() {
let mut stack = ItemStack::new("minecraft:stick", 1);
stack.data_mut().set_other(
"minecraft:lore",
Some(Tag::List(vec![
Tag::compound([
("text", Tag::String("Gold line".into())),
("color", Tag::String("gold".into())),
("italic", Tag::Byte(0)),
]),
Tag::String("Plain lore".into()),
])),
);
let lines = lore_texts(&stack);
assert_eq!(lines.len(), 2);
assert_eq!(lines[0].plain(), "Gold line");
assert_eq!(lines[0].spans[0].style.color, Some(crate::text::GOLD));
assert!(!lines[0].spans[0].style.is_italic());
assert_eq!(lines[1].plain(), "Plain lore");
assert_eq!(
lines[1].spans[0].style.color,
Some(crate::text::DARK_PURPLE)
);
assert!(lines[1].spans[0].style.is_italic());
assert!(TooltipDisplay::for_stack(&stack).shows("minecraft:lore"));
stack.data_mut().set_other(
"minecraft:tooltip_display",
Some(Tag::compound([(
"hidden_components",
Tag::List(vec![Tag::String("minecraft:lore".into())]),
)])),
);
assert!(!TooltipDisplay::for_stack(&stack).shows("minecraft:lore"));
}
#[test]
fn tooltip_display_controls_name_and_component_visibility() {
let mut stack = ItemStack::new("minecraft:diamond_sword", 1);
@@ -0,0 +1,58 @@
package dev.horizonlab.parity;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Optional;
import net.minecraft.core.component.DataComponents;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.Style;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.item.component.ItemLore;
import net.minecraft.world.item.component.TooltipDisplay;
/**
* The styled lines {@code ItemLore.addToTooltip} adds, one stack (SNBT) per input
* line. Each line is its visited spans ({@code text, colour, bold, italic,
* underlined, strikethrough, obfuscated}); lines are separated by {@code ||}.
*/
public final class VanillaLoreTooltipOracle {
public static void main(String[] args) throws Exception {
ParityData.init();
var context = Item.TooltipContext.of(ParityData.lookup);
var output = new ArrayList<String>();
for (String line : Files.readAllLines(Path.of(args[0]))) {
if (line.isBlank() || line.startsWith("#")) continue;
var stack = ParityData.stack(line);
var display = stack.getOrDefault(DataComponents.TOOLTIP_DISPLAY, TooltipDisplay.DEFAULT);
ItemLore lore = stack.get(DataComponents.LORE);
if (lore == null || !display.shows(DataComponents.LORE)) {
output.add("-");
continue;
}
var lines = new ArrayList<String>();
lore.addToTooltip(context, component -> lines.add(spans(component)), TooltipFlag.NORMAL, stack);
output.add(lines.isEmpty() ? "-" : String.join(" || ", lines));
}
Files.write(Path.of(args[1]), output);
}
/** {@code Component.visit} from {@code Style.EMPTY}: the style a tooltip draws. */
static String spans(Component component) {
var out = new StringBuilder();
component.visit((style, text) -> {
if (text.isEmpty()) return Optional.empty();
if (out.length() > 0) out.append(" | ");
int color = style.getColor() == null ? -1 : style.getColor().getValue();
out.append(text).append('\t').append(color).append('\t')
.append(style.isBold()).append('\t')
.append(style.isItalic()).append('\t')
.append(style.isUnderlined()).append('\t')
.append(style.isStrikethrough()).append('\t')
.append(style.isObfuscated());
return Optional.empty();
}, Style.EMPTY);
return out.toString();
}
}
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env python3
"""Compare item lore tooltip styles with the pinned vanilla client.
Vanilla prints what ``ItemLore.addToTooltip`` adds after ``ComponentUtils.mergeStyles``
with dark purple italic (VanillaLoreTooltipOracle). Horizon prints what
``item_tooltip::lore_texts`` gives (examples/probe/lore_tooltip_fixture).
"""
try:
from . import lab, oracle_harness as harness
except ImportError:
import lab, oracle_harness as harness
# SNBT stacks. A lore line is a text component; italic:0b is an explicit false.
CASES = [
'{id:"minecraft:stick",count:1}',
'{id:"minecraft:stick",count:1,components:{"minecraft:lore":[\'"Plain"\']}}',
'{id:"minecraft:stick",count:1,components:{"minecraft:lore":[\'{"text":"Gold","color":"gold","italic":0b}\']}}',
'{id:"minecraft:stick",count:1,components:{"minecraft:lore":[\'{"text":"A","extra":[{"text":"B","color":"aqua","italic":0b}]}\']}}',
'{id:"minecraft:stick",count:1,components:{"minecraft:lore":[\'"One"\',\'{"text":"Two","bold":1b}\']}}',
'{id:"minecraft:stick",count:1,components:{"minecraft:lore":[\'"Hidden"\'],"minecraft:tooltip_display":{hidden_components:["minecraft:lore"]}}}',
'{id:"minecraft:stick",count:1,components:{"minecraft:lore":[\'{"text":"Line","underlined":1b,"strikethrough":1b}\']}}',
]
def cases(build):
path = build / 'cases.txt'
path.write_text(''.join(line + '\n' for line in CASES))
return path, len(CASES)
if __name__ == '__main__':
harness.differential(
'lore-tooltip-parity', 'VanillaLoreTooltipOracle', 'lore_tooltip_fixture', cases,
'Item lore tooltip lines: dark purple italic, child colours, explicit non-italic, and tooltip_display',
sources=[
lab.ROOT / 'crates/horizon-client/src/item_tooltip.rs',
lab.ROOT / 'crates/horizon-client/src/item_data.rs',
lab.ROOT / 'crates/horizon-client/src/text.rs',
lab.ROOT / 'crates/horizon-client/src/component.rs',
],
expected_lines=len(CASES))