diff --git a/crates/horizon-client/examples/probe/hud_fixture/kinds.rs b/crates/horizon-client/examples/probe/hud_fixture/kinds.rs index 850db5218..d1450f2e1 100644 --- a/crates/horizon-client/examples/probe/hud_fixture/kinds.rs +++ b/crates/horizon-client/examples/probe/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 868a8d046..41d2276f5 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -678,6 +678,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 0247896f5..96cb52536 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. @@ -949,3 +959,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 fb1e57ad6..c5a3fc456 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 49266a855..b387d5b4f 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -468,8 +468,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 82edac4df..a2b23c8c6 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -87,7 +87,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, } @@ -1422,6 +1422,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, @@ -1431,9 +1433,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); } } @@ -1822,7 +1823,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 32613e42a..d7418975c 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, @@ -694,11 +694,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, @@ -2381,42 +2384,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) => { @@ -2848,11 +2836,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) @@ -2861,30 +2855,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 { @@ -4692,7 +4687,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 97acc91c9..5fc09e35b 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -589,6 +589,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 11abb3328..1254d32f6 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 5ba25e99a..994636066 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -68,6 +68,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) @@ -221,7 +224,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', 'looks', 'leads', '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', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'particles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'hands', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', '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', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'particles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'hands', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] class Game: @@ -1462,8 +1465,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}: ') @@ -2028,6 +2031,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() @@ -4303,7 +4369,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, '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, 'machines': check_machines, 'brewing': check_brewing, + 'chat': check_chat, 'styles': check_styles, 'machines': check_machines, 'brewing': check_brewing, 'loom': check_loom, 'stonecutter': check_stonecutter, 'grindstone': check_grindstone, 'anvil': check_anvil, 'smithing': check_smithing, 'enchanting': check_enchanting, 'beacon': check_beacon, 'crafter': check_crafter, 'lectern': check_lectern,