From c7abc8c718d6fd78bc5ed8f7766a3ab8491cb846 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 08:39:46 +0200 Subject: [PATCH] Chat: styled server components, click and hover events, legacy codes, message order MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A connection's chat keeps the server's component: SystemChat goes through the same translation and styles as the action bar, and player and disguised chat are decorated from their chat type's translation, parameters and style (ChatType.Bound.decorate), so colours, bold, hex colours, and the client's language are kept (#1372, #1389). - Components parse `click_event` (suggest_command, copy_to_clipboard; never open_file from a server) and `hover_event` show_text (#1377), and the chat screen draws the hovered part's tooltip (#1381). - `§` codes in chat colour the text with Chat Colors on and are stripped with it off (ComponentRenderUtils.wrapComponents) (#1379). - A command's operator broadcast skips the player whose command it was on the integrated server too (#1373), and /give fires InventoryChangeTrigger before its message, whose announcement is sent first (#1375). - The control socket's `messages` gives the chat lines as components; lan_e2e `styles` checks a styled tellraw, the advancement order and the missing echo for the host and the guest. Co-Authored-By: Claude Opus 5.5 --- .../examples/hud_fixture/kinds.rs | 1 + crates/horizon-client/src/chat.rs | 42 +++++++- crates/horizon-client/src/chat_tests.rs | 42 ++++++++ crates/horizon-client/src/component.rs | 19 ++++ crates/horizon-client/src/game/agent.rs | 2 + crates/horizon-client/src/game/chat.rs | 35 ++++++- crates/horizon-client/src/game/commands.rs | 5 + crates/horizon-client/src/game/integrated.rs | 4 +- crates/horizon-client/src/game/lan_actions.rs | 11 ++- crates/horizon-client/src/game/remote.rs | 95 +++++++++---------- crates/horizon-client/src/settings.rs | 1 + crates/horizon-client/src/text.rs | 28 ++++++ tools/lan_e2e.py | 74 ++++++++++++++- 13 files changed, 297 insertions(+), 62 deletions(-) diff --git a/crates/horizon-client/examples/hud_fixture/kinds.rs b/crates/horizon-client/examples/hud_fixture/kinds.rs index 850db5218..d1450f2e1 100644 --- a/crates/horizon-client/examples/hud_fixture/kinds.rs +++ b/crates/horizon-client/examples/hud_fixture/kinds.rs @@ -306,6 +306,7 @@ fn chat(c: &Value, h: i32, atlas: &HudAtlas) -> Vec { height_focused: option("chatHeightFocused"), height_unfocused: option("chatHeightUnfocused"), line_spacing: option("chatLineSpacing"), + colors: c["chatColors"].as_bool().unwrap_or(true), }; for m in c["messages"].as_array().into_iter().flatten() { // GuiMessageTag indicator colours: systemSinglePlayer and chatError. diff --git a/crates/horizon-client/src/chat.rs b/crates/horizon-client/src/chat.rs index 7c51a40f1..273b87153 100644 --- a/crates/horizon-client/src/chat.rs +++ b/crates/horizon-client/src/chat.rs @@ -29,10 +29,14 @@ pub struct ChatOptions { pub height_focused: f64, pub height_unfocused: f64, pub line_spacing: f64, + /// Chat Colors (`chatColors`): legacy `§` codes format the text, or are + /// left out. + pub colors: bool, } impl Default for ChatOptions { fn default() -> Self { Self { + colors: true, opacity: 1.0, background_opacity: 0.5, scale: 1.0, @@ -136,7 +140,8 @@ impl Chat { } fn add_lines(&mut self, atlas: &HudAtlas, message: &Message, focused: bool) { let width = self.max_width(); - for line in atlas.font.wrap_components(&message.content, width) { + let content = self.displayed(&message.content); + for line in atlas.font.wrap_components(&content, width) { if focused && self.scroll > 0 { self.new_since_scroll = true; self.scroll_by(1, focused); @@ -152,6 +157,16 @@ impl Chat { } self.lines.truncate(100); } + /// What a message's lines wrap (ComponentRenderUtils.wrapComponents): + /// without Chat Colors its `§` codes are stripped (stripColor); with + /// them the font draws them as formatting. + fn displayed(&self, content: &Text) -> Text { + if self.options.colors { + content.resolve_legacy() + } else { + content.strip_legacy() + } + } /// Re-wrap after a width or scale change (ChatComponent.rescaleChat). pub fn rescale(&mut self, atlas: &HudAtlas) { self.scroll = 0; @@ -308,6 +323,21 @@ impl Chat { x: f64, y: f64, ) -> Option { + self.style_at(font, height, x, y)?.click + } + /// The hover text under a GUI-space cursor while chat is focused + /// (ChatScreen.render's `renderComponentHoverEffect`). + pub fn hover_at(&self, font: &crate::font::Font, height: i32, x: f64, y: f64) -> Option { + self.style_at(font, height, x, y)?.hover.map(|h| *h) + } + /// ChatComponent.getClickedComponentStyleAt. + fn style_at( + &self, + font: &crate::font::Font, + height: i32, + x: f64, + y: f64, + ) -> Option { let scale = self.options.scale as f32; let mut x = x / f64::from(scale) - 4.0; let bottom = hud_layout::floor((height - 40) as f32 / scale); @@ -324,7 +354,7 @@ impl Chat { for (c, style) in content.chars() { x -= f64::from(font.advance(c, style)); if x < 0.0 { - return style.click.clone(); + return Some(style.clone()); } } None @@ -337,6 +367,14 @@ impl Chat { .map(|m| m.content.plain()) .collect() } + /// The newest messages as components, styles included (control socket). + pub fn recent_components(&self, n: usize) -> Vec { + self.messages + .iter() + .take(n) + .map(|m| m.content.component()) + .collect() + } } /// `CommandSuggestions.SuggestionsList`. diff --git a/crates/horizon-client/src/chat_tests.rs b/crates/horizon-client/src/chat_tests.rs index e1bf2feda..d0ce3f458 100644 --- a/crates/horizon-client/src/chat_tests.rs +++ b/crates/horizon-client/src/chat_tests.rs @@ -285,3 +285,45 @@ fn ask_server_nodes_wait_for_the_servers_completions() { screen.type_text(&m, &c, "/bossbar get pt"); assert_eq!(screen.take_request(), None); } + +#[test] +fn legacy_codes_colour_the_line_or_vanish_without_chat_colours() { + let mut chat = Chat::default(); + let red = Text::literal("\u{a7}cRED"); + let shown = chat.displayed(&red); + assert_eq!(shown.plain(), "RED"); + assert!(shown.chars().all(|(_, s)| s.color == Some(0xFF5555))); + chat.options.colors = false; + let shown = chat.displayed(&red); + assert_eq!(shown.plain(), "RED"); + assert!(shown.chars().all(|(_, s)| s.color.is_none())); + // A lone section sign or an unknown code stays as written. + assert_eq!( + chat.displayed(&Text::literal("a\u{a7}zb")).plain(), + "a\u{a7}zb" + ); +} + +#[test] +fn a_server_component_keeps_its_click_and_hover_events() { + let font = font(); + let json = serde_json::json!({ + "text": "CLICK", "color": "green", "bold": true, + "click_event": {"action": "suggest_command", "command": "/say clicked"}, + "hover_event": {"action": "show_text", "value": {"text": "Tip", "color": "aqua"}}, + }); + let line = crate::component::to_text(&json, &mut |s| Text::literal(s)); + let mut chat = Chat::default(); + add(&mut chat, &font, line); + let x = 4.0 + f64::from(font.width("CL")); + let Some(ClickEvent::SuggestCommand(command)) = chat.click_at(&font, 360, x, 315.0) else { + panic!("the line must suggest its command"); + }; + assert_eq!(command, "/say clicked"); + let hover = chat.hover_at(&font, 360, x, 315.0).expect("a hover text"); + assert_eq!(hover.plain(), "Tip"); + assert_eq!(hover.spans[0].style.color, Some(text::AQUA)); + // Past the (bold, so wider) text, nothing. + let past = 4.0 + f64::from(font.width("CLICK")) + 20.0; + assert!(chat.hover_at(&font, 360, past, 315.0).is_none()); +} diff --git a/crates/horizon-client/src/component.rs b/crates/horizon-client/src/component.rs index 68460054b..fced49898 100644 --- a/crates/horizon-client/src/component.rs +++ b/crates/horizon-client/src/component.rs @@ -168,6 +168,25 @@ fn object_style(o: &serde_json::Map) -> Style { style.strikethrough = flag("strikethrough"); style.obfuscated = flag("obfuscated"); style.font = o.get("font").and_then(crate::text::font_id); + // ClickEvent.CODEC: the actions a chat line acts on here. A component + // from a server never opens a file. + if let Some(e) = o.get("click_event").and_then(Value::as_object) { + let text = |k: &str| e.get(k).and_then(Value::as_str).map(str::to_owned); + style.click = match e.get("action").and_then(Value::as_str) { + Some("suggest_command") => text("command").map(crate::text::ClickEvent::SuggestCommand), + Some("copy_to_clipboard") => { + text("value").map(crate::text::ClickEvent::CopyToClipboard) + } + _ => None, + }; + } + // HoverEvent.ShowText. + if let Some(e) = o.get("hover_event").and_then(Value::as_object) + && e.get("action").and_then(Value::as_str) == Some("show_text") + && let Some(value) = e.get("value") + { + style.hover = Some(Box::new(to_text(value, &mut |s| Text::literal(s)))); + } style } /// `ComponentSerialization.CODEC` decoding into text. `selector` components diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 3d957efe0..3ee069778 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -673,6 +673,8 @@ impl Game<'_> { json!({ "chat": self.remote_chat(n).unwrap_or_else(|| self.ui.chat.recent_lines(n)), "order": "newest first", + // The chat lines as drawn: colours, click and hover events. + "styled": self.ui.chat.recent_components(n), "title": (titles.time > 0).then(|| titles.title.as_ref().map(|t| t.plain())).flatten(), "subtitle": (titles.time > 0).then(|| titles.subtitle.as_ref().map(|t| t.plain())).flatten(), "actionbar": (titles.overlay_time > 0).then(|| titles.overlay.as_ref().map(|t| t.plain())).flatten(), diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 20aeeb7fd..be73607ae 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -450,7 +450,7 @@ impl Game<'_> { // Connected to a server (single player's own included), the chat on // screen is the connection's: the game's own messages join it. if self.remote.is_some() { - self.chat_line(text.plain()); + self.chat_line(text); return; } let focused = self.screen == Screen::Chat; @@ -681,6 +681,16 @@ impl Game<'_> { let draws = screen.draw(&m, mouse, blink, background); horizon_client::screen_draw::paint(batch, &self.gui.atlas, &draws); self.ui.chat_screen = Some(screen); + // The hovered message part's tooltip, one row per line of its text. + if let Some(hover) = self.ui.chat.hover_at( + &self.gui.atlas.font, + batch.height as i32, + f64::from(self.cursor.0), + f64::from(self.cursor.1), + ) { + let lines = hover_rows(&hover); + self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1); + } } /// Advance the overworld clock (ServerClockManager.tick) when /// `advance_time` allows it. @@ -953,3 +963,26 @@ fn write_difficulty(world: &std::path::Path, difficulty: u8) -> horizon_client:: fn owner_permission(allow_commands: bool) -> u8 { if allow_commands { 4 } else { 0 } } + +/// A hover text's rows for the tooltip: split at line breaks, each in the +/// colour of its first styled character (white without one). +fn hover_rows(hover: &horizon_client::text::Text) -> Vec<(String, u32)> { + let mut rows = vec![(String::new(), None)]; + for (c, style) in hover.resolve_legacy().chars() { + if c == '\n' { + rows.push((String::new(), None)); + continue; + } + let row = rows.last_mut().expect("one row"); + if row.0.is_empty() { + row.1 = style.color; + } + row.0.push(c); + } + rows.into_iter() + .map(|(text, color)| { + let [_, r, g, b] = color.unwrap_or(0xFF_FFFF).to_be_bytes(); + (text, horizon_client::hud::rgba(r, g, b, 255)) + }) + .collect() +} diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index c6877a839..0a51f6119 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1039,6 +1039,11 @@ impl Game<'_> { .play("minecraft:entity.item.pickup", Some(p), 0.2, pitch); } } + // containerMenu.broadcastChanges: InventoryChangeTrigger + // (and its announcement) comes before the command's message. + if g.player.is_some() { + g.check_inventory_trigger(); + } }); } // The prototype stack: one item. diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index ef5775174..bdb6fe892 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -465,8 +465,10 @@ impl Game<'_> { host = self.lan.take().expect("a command puts the hub back"); self.leave_guest(&mut host, swap); host.hub.sync_all_effects(); - // A teleport into another level happens before its feedback is sent. + // A teleport into another level happens before its feedback is + // sent, and what the command earned is announced before it too. self.run_level_teleports(&mut host); + self.announce_guest_advancements(&mut host); for line in lines { out.push(line.plain()); host.hub.send_to( diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 67764c090..a34eb417c 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -85,7 +85,7 @@ pub(super) struct GuestCommand { conn: u32, command: String, permission: u8, - /// An integrated server's: no admin feedback or level teleports (yet). + /// An integrated server's: no level teleports (yet). integrated: bool, } @@ -1382,6 +1382,8 @@ impl Game<'_> { // A teleport into another level happens before its feedback is sent. self.run_level_teleports(&mut host); } + // What the command earned is announced before its feedback. + self.announce_guest_advancements(&mut host); for line in lines { host.hub.send_to( c.conn, @@ -1391,9 +1393,8 @@ impl Game<'_> { }), ); } - if !c.integrated { - self.send_admin_feedback(&mut host, Some(c.conn)); - } + // The other operators hear of it; never the player whose command it was. + self.send_admin_feedback(&mut host, Some(c.conn)); self.lan = Some(host); } } @@ -1745,7 +1746,7 @@ impl Game<'_> { /// `PlayerList.broadcastSystemMessage` of the advancements guests made /// (their own actions, commands and ticks). - fn announce_guest_advancements(&mut self, host: &mut LanHost) { + pub(super) fn announce_guest_advancements(&mut self, host: &mut LanHost) { for text in std::mem::take(&mut self.adv.announced) { host.hub .system_message(horizon_client::lan::data::component_nbt(&text.component())); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index f969cbeb9..8dff41c6f 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -38,7 +38,7 @@ use horizon_protocol::{ play::{self, Clientbound as C, Serverbound as S}, }, registry::{Builtin, DimensionType, Dynamic, ceil_log2}, - text::{Language, format_java, plain}, + text::{Language, plain}, }; use horizon_world::{nbt::Tag, registry::BlockStateId}; use std::{ @@ -675,11 +675,14 @@ impl Game<'_> { } Some(stack) } - pub(super) fn chat_line(&mut self, text: String) { + /// A line in the connection's chat, with its styles, click and hover + /// events (ChatComponent.addMessage). + pub(super) fn chat_line(&mut self, content: horizon_client::text::Text) { + let text = content.plain(); log::info!("[chat] {text}"); self.ui.chat.add( &self.gui.atlas, - horizon_client::text::Text::literal(text.clone()), + content, None, self.ticks, self.screen == Screen::Chat, @@ -2256,42 +2259,27 @@ impl Game<'_> { } } C::SystemChat(p) => { - let text = plain( - &p.content, - &self - .remote - .as_ref() - .map(|r| r.lang.clone()) - .unwrap_or_default(), - ); - // ChatListener.handleOverlay. + // The component as sent, translated in the client's own + // language. ChatListener.handleOverlay for the action bar. + let text = remote_text(&p.content); if p.overlay { - self.titles.set_overlay(remote_text(&p.content), false); + self.titles.set_overlay(text, false); } else { self.chat_line(text); } } C::PlayerChat(p) => { - let lang = self - .remote - .as_ref() - .map(|r| r.lang.clone()) - .unwrap_or_default(); + use horizon_client::scoreboard::tag_to_json; let content = p .unsigned_content .as_ref() - .map_or_else(|| p.content.clone(), |t| plain(t, &lang)); - let line = self.format_chat(&p.chat_type, &content); + .map_or_else(|| serde_json::Value::from(p.content.as_str()), tag_to_json); + let line = self.format_chat(&p.chat_type, content); self.chat_line(line); } C::DisguisedChat(p) => { - let lang = self - .remote - .as_ref() - .map(|r| r.lang.clone()) - .unwrap_or_default(); - let content = plain(&p.message, &lang); - let line = self.format_chat(&p.chat_type, &content); + let content = horizon_client::scoreboard::tag_to_json(&p.message); + let line = self.format_chat(&p.chat_type, content); self.chat_line(line); } C::PlayerInfoUpdate(p) => { @@ -2723,11 +2711,17 @@ impl Game<'_> { true } /// ChatType decoration: `chat.translation_key` with sender/content parameters. - fn format_chat(&self, bound: &play::ChatTypeBound, content: &str) -> String { + /// ChatType.Bound.decorate: the chat type's translation, with the + /// sender, the target and the message as its parameters, in its style. + fn format_chat( + &self, + bound: &play::ChatTypeBound, + content: serde_json::Value, + ) -> horizon_client::text::Text { + use horizon_client::scoreboard::{comp_text, tag_to_json}; let Some(r) = self.remote.as_ref() else { - return content.to_owned(); + return comp_text(&content); }; - let sender = plain(&bound.name, &r.lang); let decoration = r .registries .data("minecraft:chat_type", bound.chat_type) @@ -2736,30 +2730,31 @@ impl Game<'_> { Some(Tag::String(s)) => s.to_string_lossy(), _ => "chat.type.text".into(), }; - let params: Vec = match decoration.and_then(|d| d.get("parameters")) { + let parameter = |name: &str| match name { + "sender" => tag_to_json(&bound.name), + "target" => bound + .target + .as_ref() + .map_or_else(|| serde_json::Value::from(""), tag_to_json), + _ => content.clone(), + }; + let with: Vec = match decoration.and_then(|d| d.get("parameters")) { Some(Tag::List(list)) => list .iter() .map(|p| match p { - Tag::String(s) => match s.to_string_lossy().as_str() { - "sender" => sender.clone(), - "target" => bound - .target - .as_ref() - .map(|t| plain(t, &r.lang)) - .unwrap_or_default(), - _ => content.to_owned(), - }, - _ => String::new(), + Tag::String(s) => parameter(&s.to_string_lossy()), + _ => serde_json::Value::from(""), }) .collect(), - _ => vec![sender, content.to_owned()], + _ => vec![parameter("sender"), parameter("content")], }; - let pattern = r - .lang - .get(&key) - .cloned() - .unwrap_or_else(|| "<%s> %s".into()); - format_java(&pattern, ¶ms) + let mut component = match decoration.and_then(|d| d.get("style")) { + Some(style @ Tag::Compound(_)) => tag_to_json(style), + _ => serde_json::json!({}), + }; + component["translate"] = key.into(); + component["with"] = with.into(); + comp_text(&component) } fn remote_item_data(&mut self, id: i32, stack: &Option) { let Some(stack) = self.to_stack(stack) else { @@ -4530,7 +4525,9 @@ impl Game<'_> { self.send(S::ContainerClose(play::ContainerClose { container: p.container, })); - self.chat_line(format!("(Horizon cannot show {menu} screens yet)")); + self.chat_line(horizon_client::text::Text::literal(format!( + "(Horizon cannot show {menu} screens yet)" + ))); return; } }; diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 1fadacf57..20f3ade23 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -593,6 +593,7 @@ impl Settings { height_focused: f64::from(self.chat_height_focused), height_unfocused: f64::from(self.chat_height_unfocused), line_spacing: f64::from(self.chat_line_spacing), + colors: self.chat_colors, } } } diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client/src/text.rs index 9f39155d1..41a21d285 100644 --- a/crates/horizon-client/src/text.rs +++ b/crates/horizon-client/src/text.rs @@ -428,6 +428,34 @@ impl Text { } out } + /// The text without its legacy `§` codes (ChatFormatting.stripFormatting: + /// a `§` and a code character, `0`-`9`, `a`-`f`, `k`-`o` or `r`). + pub fn strip_legacy(&self) -> Text { + if !self.spans.iter().any(|s| s.text.contains('§')) { + return self.clone(); + } + let code = + |c: char| matches!(c.to_ascii_lowercase(), '0'..='9' | 'a'..='f' | 'k'..='o' | 'r'); + let mut out = Text::default(); + for span in &self.spans { + let mut text = String::with_capacity(span.text.len()); + let mut chars = span.text.chars().peekable(); + while let Some(c) = chars.next() { + if c == '§' && chars.peek().is_some_and(|&n| code(n)) { + chars.next(); + } else { + text.push(c); + } + } + if !text.is_empty() { + out.spans.push(Span { + text, + style: span.style.clone(), + }); + } + } + out + } /// Characters with their effective styles. pub fn chars(&self) -> impl Iterator { self.spans diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 79250678e..00727d61d 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -61,6 +61,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - feedback: the guest's command feedback names the guest and shows the numbers; - chat: a line the host sends reaches the guest's event log (`wait-for chat`), and on the server thread the host window's too; +- styles: a styled tellraw reaches the host and the guest (each its own) with its colour, bold, click and hover + events; each player's /give tells them of the Diamonds! advancement before the give's + own message, and never echoes their command back to them as `[Name: ...]`; - effects: a beacon's power reaches every player in range, the host and the guest; - distance: (--server-thread) the server follows the host's render distance, past vanilla's 32 too (IntegratedServer.tickServer), and the guest's chunks follow the server's (#804) @@ -179,7 +182,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'levels'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'styles', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'levels'] class Game: @@ -1310,8 +1313,8 @@ def check_loom(host, guest, out): def own_reply(event): """A chat event that answers the guest's own command. On the server thread the guest also gets - its own command's `[Guest: ...]` operator broadcast, a moment later, which an answer to the next - command must not be taken for.""" + its own command's `[Guest: ...]` operator broadcast before #1373, a moment later, which an answer + to the next command must not be taken for.""" return event.get('event') == 'chat' and not event.get('text', '').startswith(f'[{GUEST_NAME}: ') @@ -1876,6 +1879,69 @@ def check_chat(host, guest, out): return seen +def styled_parts(component): + """Every component in a chat line's tree (the line, its `extra` and `with` parts).""" + if isinstance(component, dict): + yield component + for key in ('extra', 'with'): + for part in component.get(key) or []: + yield from styled_parts(part) + elif isinstance(component, list): + for part in component: + yield from styled_parts(part) + + +def check_styles(host, guest, out): + # ChatComponent keeps what the server sent: the style, the click and the hover event. + stamp = f'STYLE {int(time.time())}' + line = {'text': stamp, 'color': 'green', 'bold': True, + 'click_event': {'action': 'suggest_command', 'command': '/say clicked'}, + 'hover_event': {'action': 'show_text', 'value': 'Tip'}} + seen = {} + for g in (host, guest): + # Each to itself: tellraw reaches only the player whose command it is here. + since = g.raw('events')['last'] + g('command', command='tellraw @s ' + json.dumps(line)) + g.raw('wait-for', 'chat', stamp, '--timeout', 10, '--since', since) + part = next((p for c in g.raw('messages', 10)['styled'] for p in styled_parts(c) + if stamp in str(p.get('text', ''))), None) or {} + seen[g.name] = {k: part.get(k) for k in ('color', 'bold', 'click_event', 'hover_event')} + hover = seen[g.name]['hover_event'] or {} + seen[g.name]['hover_event'] = [hover.get('action'), 'Tip' in str(hover.get('value'))] + # InventoryChangeTrigger fires inside /give, before its message; the operator echo + # (broadcastToAdmins) skips the player whose command it was. + order = {} + for g in (host, guest): + for command in ('advancement revoke @s everything', 'clear @s'): + g('command', command=command) + g.wait(5) + since = g.raw('events')['last'] + g('command', command='give @s minecraft:diamond') + g.raw('wait-for', 'chat', 'Diamonds!', '--timeout', 10, '--since', since) + g.wait(20) + chat = g.raw('messages', 8)['chat'] + name = GUEST_NAME if g is guest else host.player + gave = next((i for i, l in enumerate(chat) if l.startswith('Gave 1 [Diamond]')), None) + made = next((i for i, l in enumerate(chat) if '[Diamonds!]' in l), None) + echo = [l for l in chat if l.startswith(f'[{name}: ')] + # Newest first: the give's message is newer than the advancement's. + order[g.name] = {'gave': gave, 'advancement': made, 'echo': echo} + guest.raw('key', 't', 'tap') + guest.wait(5) + guest.shot(out, 'styles') + guest.raw('key', 'esc', 'tap') + want = {'color': 'green', 'bold': True, + 'click_event': {'action': 'suggest_command', 'command': '/say clicked'}, + 'hover_event': ['show_text', True]} + for name, got in seen.items(): + assert got == want, f'{name} styled line: {got}' + for name, o in order.items(): + assert o['gave'] is not None and o['advancement'] is not None, f'{name} chat: {o}' + assert o['gave'] < o['advancement'], f'{name}: the give came before the advancement: {o}' + assert not o['echo'], f'{name} heard its own command: {o}' + return {'styles': seen, 'order': order} + + def png_rows(path): """The rows of an 8-bit RGB or RGBA PNG, unfiltered, as bytes of 4 (or 3) per pixel.""" data = Path(path).read_bytes() @@ -3348,7 +3414,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, 'respawn': check_respawn, - 'containers': check_containers, 'feedback': check_feedback, 'titles': check_titles, 'chat': check_chat, + 'containers': check_containers, 'feedback': check_feedback, 'titles': check_titles, 'chat': check_chat, 'styles': check_styles, 'machines': check_machines, 'brewing': check_brewing, 'loom': check_loom,