diff --git a/crates/horizon-client/examples/probe/chat_screen_fixture.rs b/crates/horizon-client/examples/probe/chat_screen_fixture.rs index 229d8d861..db334797d 100644 --- a/crates/horizon-client/examples/probe/chat_screen_fixture.rs +++ b/crates/horizon-client/examples/probe/chat_screen_fixture.rs @@ -7,7 +7,7 @@ //! usage: chat_screen_fixture RESOURCES REGISTRIES CASES OUTPUT use crate::pack_screen_fixture; use horizon_client::{ - chat::{ChatAction, ChatScreen, Commands}, + chat::{ChatAbilities, ChatAction, ChatScreen, ChatVisibility, Commands}, command::vanilla, hud::HudAtlas, lang, @@ -53,6 +53,7 @@ pub fn main() -> horizon_client::Result<()> { history.len(), w, h, + ChatAbilities::new(ChatVisibility::Full), ); screen.auto_suggestions = case["autoSuggest"] == true; let mut closed = false; diff --git a/crates/horizon-client/src/chat.rs b/crates/horizon-client/src/chat.rs index 273b87153..e14178c8d 100644 --- a/crates/horizon-client/src/chat.rs +++ b/crates/horizon-client/src/chat.rs @@ -19,6 +19,78 @@ mod tests; /// GuiMessageTag.systemSinglePlayer's indicator colour. pub const SYSTEM_INDICATOR: u32 = 0xD0D0D0; +/// `ChatVisiblity`: the Chat option's three values. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ChatVisibility { + Full, + System, + Hidden, +} +impl ChatVisibility { + /// Options.chatVisibility's saved value (0 full, 1 system, 2 hidden). + pub fn from_option(value: u8) -> Self { + match value { + 0 => Self::Full, + 1 => Self::System, + _ => Self::Hidden, + } + } +} + +/// `ChatAbilities`: what the Chat option allows, as `Minecraft.computeChatAbilities` +/// derives it from the visibility alone (`ChatRestriction`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ChatAbilities { + pub send_messages: bool, + pub send_commands: bool, + pub receive_player_messages: bool, + pub receive_system_messages: bool, +} +impl ChatAbilities { + /// `ChatRestriction.CHAT_AND_COMMANDS_DISABLED_BY_OPTIONS` (Hidden) takes + /// chat, commands, player messages and system messages; + /// `CHAT_DISABLED_BY_OPTIONS` (System) takes the chat and player messages. + pub fn new(visibility: ChatVisibility) -> Self { + match visibility { + ChatVisibility::Full => Self { + send_messages: true, + send_commands: true, + receive_player_messages: true, + receive_system_messages: true, + }, + ChatVisibility::System => Self { + send_messages: false, + send_commands: true, + receive_player_messages: false, + receive_system_messages: true, + }, + ChatVisibility::Hidden => Self { + send_messages: false, + send_commands: false, + receive_player_messages: false, + receive_system_messages: false, + }, + } + } + /// Whether the chat screen may send `input` (`hasAllowedInput`). + pub fn allows(&self, input: &str) -> bool { + if input.starts_with('/') { + self.send_commands + } else { + self.send_messages + } + } +} + +/// Where a chat line came from (`GuiMessageSource`): the visibility filters +/// player messages and the server's, while the client's own always show. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ChatSource { + Player, + Server, + Client, +} + /// The chat options (doubles, as vanilla keeps them). #[derive(Clone, Copy, Debug)] pub struct ChatOptions { @@ -437,6 +509,8 @@ pub struct ChatScreen { allow_suggestions: bool, keep_suggestions: bool, pub auto_suggestions: bool, + /// `CommandSuggestions.setRestrictions`: what the Chat option allows. + pub abilities: ChatAbilities, } /// Local completions waiting for the server's reply to request `id`. struct Awaiting { @@ -482,6 +556,7 @@ impl ChatScreen { history_len: usize, width: i32, height: i32, + abilities: ChatAbilities, ) -> Self { let mut input = TextField::new(4, height - 12, width - 4, 12); input.max_length = 256; @@ -505,6 +580,7 @@ impl ChatScreen { allow_suggestions: false, keep_suggestions: false, auto_suggestions: true, + abilities, }; s.update_command_info(m, c); s @@ -522,7 +598,8 @@ impl ChatScreen { if (width, height) != (self.width, self.height) { let value = self.input.value.clone(); let auto = self.auto_suggestions; - *self = Self::new(m, c, &value, self.history_pos, width, height); + let abilities = self.abilities; + *self = Self::new(m, c, &value, self.history_pos, width, height, abilities); self.auto_suggestions = auto; } } @@ -604,6 +681,14 @@ impl ChatScreen { self.pending = Some((range.0, list)); self.usage_width = 0; self.usage_position = 0; + // CommandSuggestions.updateCommandInfo: the Chat option may take + // the messages. + if !self.abilities.send_messages { + let line = + Text::translate("chat_screen.messages_not_allowed", &[]).with_color(text::RED); + self.usage_width = m.width(&line); + self.usage.push(line); + } } else { self.awaiting = None; self.pending = None; @@ -708,6 +793,15 @@ impl ChatScreen { } self.usage.extend(entries); } + // CommandSuggestions.updateUsageInfo: the Chat option may take the + // commands, under the usage. (Vanilla also counts a command with a + // message argument, `/say hi`, as a message; Horizon's parse keeps no + // argument kinds, so only a bare message does.) + if !self.abilities.send_commands { + self.usage.push( + Text::translate("chat_screen.commands_not_allowed", &[]).with_color(text::RED), + ); + } self.usage_width = self.usage.iter().map(|u| m.width(u)).max().unwrap_or(0); self.usage_position = if self.usage.is_empty() { 0 @@ -842,7 +936,14 @@ impl ChatScreen { } match key { K::Escape => return ChatAction::Close, - K::Enter | K::NumpadEnter => return ChatAction::Submit(self.normalized()), + K::Enter | K::NumpadEnter => { + // ChatScreen.keyPressed: without `hasAllowedInput` the input + // stays, unsent, and the screen stays open. + if !self.abilities.allows(&self.input.value) { + return ChatAction::None; + } + return ChatAction::Submit(self.normalized()); + } K::ArrowUp => self.move_in_history(m, c, history, -1), K::ArrowDown => self.move_in_history(m, c, history, 1), _ => { diff --git a/crates/horizon-client/src/chat_tests.rs b/crates/horizon-client/src/chat_tests.rs index d0ce3f458..cd5860bfb 100644 --- a/crates/horizon-client/src/chat_tests.rs +++ b/crates/horizon-client/src/chat_tests.rs @@ -2,6 +2,11 @@ use super::*; use crate::{font::Font, hud::Rect}; use std::{collections::HashMap, path::Path}; +/// The Chat option's default: no restriction. +fn full() -> ChatAbilities { + ChatAbilities::new(ChatVisibility::Full) +} + fn font() -> Font { // The missing-glyph metrics let these tests run without game assets. Font::load( @@ -139,7 +144,7 @@ fn locate_coordinates_fill_chat_with_teleport_without_submitting() { assert_eq!(link.component()["click_event"]["command"], expected); let mut chat = Chat::default(); add(&mut chat, &font, Text::literal("Found at ").append(link)); - let mut screen = ChatScreen::new(&m, &commands, "draft", 0, 640, 360); + let mut screen = ChatScreen::new(&m, &commands, "draft", 0, 640, 360, full()); let x = 4.0 + f64::from(font.width("Found at ")); assert!(!screen.click(&m, &commands, x, 315.0)); let Some(ClickEvent::SuggestCommand(command)) = chat.click_at(&font, 360, x, 315.0) else { @@ -176,7 +181,15 @@ fn history_arrows_recall_messages_and_restore_the_draft() { registries: ®istries, }; let history = vec!["first message".to_owned(), "latest message".to_owned()]; - let mut screen = ChatScreen::new(&m, &commands, "unfinished draft", history.len(), 640, 360); + let mut screen = ChatScreen::new( + &m, + &commands, + "unfinished draft", + history.len(), + 640, + 360, + full(), + ); for (key, expected) in [ (ArrowUp, "latest message"), (ArrowUp, "first message"), @@ -213,7 +226,7 @@ fn mod_commands_are_coloured_and_complete_like_vanilla_ones() { dispatcher, registries: ®istries, }; - let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360); + let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360, full()); screen.type_text(&m, &c, line); screen }; @@ -259,7 +272,7 @@ fn ask_server_nodes_wait_for_the_servers_completions() { let tab = |screen: &mut ChatScreen| { screen.key(&m, &c, &[], winit::keyboard::KeyCode::Tab, false, false); }; - let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360); + let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360, full()); screen.type_text(&m, &c, "/bossbar get pt"); let (request, sent) = screen.take_request().expect("the server is asked"); assert_eq!(sent, "/bossbar get pt"); @@ -281,7 +294,7 @@ fn ask_server_nodes_wait_for_the_servers_completions() { dispatcher: local, registries: ®istries, }; - let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360); + let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360, full()); screen.type_text(&m, &c, "/bossbar get pt"); assert_eq!(screen.take_request(), None); } @@ -327,3 +340,75 @@ fn a_server_component_keeps_its_click_and_hover_events() { let past = 4.0 + f64::from(font.width("CLICK")) + 20.0; assert!(chat.hover_at(&font, 360, past, 315.0).is_none()); } + +/// `ChatVisiblity`: Commands Only keeps the chat out, Hidden takes the +/// commands too (`ChatAbilities`), and Enter sends nothing the option hides. +#[test] +fn the_chat_option_decides_what_may_be_sent() { + let font = font(); + let m = Measure(&font); + let registries = Registries::default(); + let c = Commands { + dispatcher: crate::command::vanilla::game_dispatcher(), + registries: ®istries, + }; + let enter = |screen: &mut ChatScreen| { + screen.key(&m, &c, &[], winit::keyboard::KeyCode::Enter, false, false) + }; + for (visibility, chat, command) in [ + (ChatVisibility::Full, true, true), + (ChatVisibility::System, false, true), + (ChatVisibility::Hidden, false, false), + ] { + let abilities = ChatAbilities::new(visibility); + assert_eq!(abilities.allows("hi"), chat, "{visibility:?}"); + assert_eq!(abilities.allows("/time set day"), command, "{visibility:?}"); + for (line, allowed) in [("hi", chat), ("/time set day", command)] { + let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360, abilities); + screen.type_text(&m, &c, line); + match enter(&mut screen) { + ChatAction::Submit(sent) => { + assert!(allowed, "{visibility:?} sent {sent}"); + assert_eq!(sent, line); + } + ChatAction::None => assert!(!allowed, "{visibility:?} kept {line}"), + ChatAction::Close => panic!("Enter does not close the chat"), + } + } + } +} + +/// The restriction the option sets is a usage line: red, under the input, for +/// a command the Chat option takes and for a message it takes. +#[test] +fn restricted_input_says_why_it_will_not_send() { + let font = font(); + let m = Measure(&font); + let registries = Registries::default(); + let c = Commands { + dispatcher: crate::command::vanilla::game_dispatcher(), + registries: ®istries, + }; + let usage = |visibility, line: &str| { + let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360, ChatAbilities::new(visibility)); + screen.type_text(&m, &c, line); + screen.usage.iter().map(|t| t.plain()).collect::>() + }; + assert_eq!(usage(ChatVisibility::Full, "hi"), Vec::::new()); + // The font has no language files here, so the line is its key. + assert_eq!( + usage(ChatVisibility::System, "hi"), + ["chat_screen.messages_not_allowed"] + ); + // A command the option allows says nothing about the restriction. + assert!( + !usage(ChatVisibility::System, "/time set day") + .iter() + .any(|line| line == "chat_screen.commands_not_allowed") + ); + assert!( + usage(ChatVisibility::Hidden, "/time set day") + .iter() + .any(|line| line == "chat_screen.commands_not_allowed") + ); +} diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 23a0f0965..fafe88f26 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -2,7 +2,10 @@ //! (game rules, the world clock, difficulty), bound to the game. use super::{Game, Screen}; use horizon_client::{ - chat::{Chat, ChatAction, ChatScreen, Commands, SYSTEM_INDICATOR}, + chat::{ + Chat, ChatAbilities, ChatAction, ChatScreen, ChatSource, ChatVisibility, Commands, + SYSTEM_INDICATOR, + }, command::Registries, gamerules::GameRules, hud::HudBatch, @@ -425,6 +428,7 @@ impl Game<'_> { self.ui.chat.recent.len(), b.width as i32, b.height as i32, + self.chat_abilities(), ); screen.auto_suggestions = self.settings.auto_suggestions; self.ui.chat_screen = Some(screen); @@ -443,6 +447,10 @@ impl Game<'_> { self.capture(true); } } + /// `Minecraft.computeChatAbilities` from the Chat option. + pub(super) fn chat_abilities(&self) -> ChatAbilities { + ChatAbilities::new(ChatVisibility::from_option(self.settings.chat_visibility)) + } /// A chat message from the game (ChatComponent.addServerSystemMessage). pub(super) fn system_message(&mut self, text: Text) { if let Some(capture) = self.chat_capture.as_mut() { @@ -452,7 +460,12 @@ 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); + self.chat_line(text, ChatSource::Server); + return; + } + // ChatListener.handleSystemMessage: the Chat option's Hidden level + // takes the server's messages too. + if !self.chat_abilities().receive_system_messages { return; } let focused = self.screen == Screen::Chat; @@ -570,7 +583,12 @@ impl Game<'_> { } } /// ChatScreen.handleChatInput: history, then a command or a chat line. + /// The Chat option's restrictions stop the message here too, so a + /// control-socket `chat` cannot send what the player's setting hides. pub(super) fn handle_chat_input(&mut self, message: &str) { + if !self.chat_abilities().allows(message) { + return; + } self.ui.chat.add_recent(message); // On a server (single player's own included) the server runs it, // unless a client mod owns the command. diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index ba069522c..80adb5ff6 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -123,6 +123,9 @@ pub(super) struct Remote { loaded_sent: bool, /// The view distance last sent in ClientInformation. sent_view: i8, + /// The Chat option's visibility last sent in ClientInformation + /// (`Options.broadcastOptions` sends it again when it changes). + sent_chat_visibility: i32, /// BlockStatePredictionHandler: blocks changed ahead of the server (a predicted break), /// with the sequence of the last action that changed them and the state the server /// last said they have. Until the server acknowledges that sequence its block updates @@ -430,6 +433,7 @@ impl Game<'_> { abilities: None, loaded_sent: false, sent_view: view, + sent_chat_visibility: self.settings.chat_visibility as i32, predictions: HashMap::new(), menu: None, menu_title: None, @@ -794,8 +798,22 @@ impl Game<'_> { Some(stack) } /// 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) { + /// events (ChatComponent.addMessage). `ChatListener` drops the lines the + /// Chat option hides before they reach the chat. + pub(super) fn chat_line( + &mut self, + content: horizon_client::text::Text, + source: horizon_client::chat::ChatSource, + ) { + let abilities = self.chat_abilities(); + let allowed = match source { + horizon_client::chat::ChatSource::Player => abilities.receive_player_messages, + horizon_client::chat::ChatSource::Server => abilities.receive_system_messages, + horizon_client::chat::ChatSource::Client => true, + }; + if !allowed { + return; + } let text = content.plain(); log::info!("[chat] {text}"); self.ui.chat.add( @@ -1776,9 +1794,10 @@ impl Game<'_> { if let Some(r) = self.remote.as_mut() { r.sent_view = view; } - self.send(S::ClientInformation( - horizon_protocol::packets::configuration::ClientInformation::new(view), - )); + let mut info = + horizon_protocol::packets::configuration::ClientInformation::new(view); + info.chat_visibility = self.settings.chat_visibility as i32; + self.send(S::ClientInformation(info)); } C::Respawn(p) => { // A new player, without effects: the server sends them again. @@ -2568,7 +2587,7 @@ impl Game<'_> { if p.overlay { self.titles.set_overlay(text, false); } else { - self.chat_line(text); + self.chat_line(text, horizon_client::chat::ChatSource::Server); } } C::PlayerChat(p) => { @@ -2578,12 +2597,12 @@ impl Game<'_> { .as_ref() .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); + self.chat_line(line, horizon_client::chat::ChatSource::Player); } C::DisguisedChat(p) => { let content = horizon_client::scoreboard::tag_to_json(&p.message); let line = self.format_chat(&p.chat_type, content); - self.chat_line(line); + self.chat_line(line, horizon_client::chat::ChatSource::Player); } C::PlayerInfoUpdate(p) => { if let Some(r) = self.remote.as_mut() { @@ -3216,16 +3235,19 @@ impl Game<'_> { fn tick_remote_level(&mut self) -> Result<()> { self.ticks += 1; self.track_experience_display(); - // Options.broadcastOptions: a changed render distance is sent again. + // Options.broadcastOptions: a changed render distance or Chat option + // is sent again. let view = client_view_distance(self.settings.render_distance); + let visibility = self.settings.chat_visibility as i32; if let Some(r) = self.remote.as_mut() && r.joined - && r.sent_view != view + && (r.sent_view != view || r.sent_chat_visibility != visibility) { r.sent_view = view; - self.send(S::ClientInformation( - horizon_protocol::packets::configuration::ClientInformation::new(view), - )); + r.sent_chat_visibility = visibility; + let mut info = horizon_protocol::packets::configuration::ClientInformation::new(view); + info.chat_visibility = visibility; + self.send(S::ClientInformation(info)); } // Minecraft.tick: TickRateManager.tick; ClientLevel.tickTime advances // the time only while the level runs normally. @@ -4643,10 +4665,12 @@ impl Game<'_> { _ => Ok(false), } } - /// ClientPacketListener.sendChat / sendCommand (unsigned). + /// ClientPacketListener.sendChat / sendCommand (unsigned). The Chat + /// option's Hidden and System levels keep chat out and Hidden keeps the + /// commands out (ChatAbilities). pub(super) fn send_chat(&mut self, message: &str) { let message = message.trim(); - if message.is_empty() { + if message.is_empty() || !self.chat_abilities().allows(message) { return; } if let Some(command) = message.strip_prefix('/') { @@ -5026,9 +5050,12 @@ impl Game<'_> { self.send(S::ContainerClose(play::ContainerClose { container: p.container, })); - self.chat_line(horizon_client::text::Text::literal(format!( - "(Horizon cannot show {menu} screens yet)" - ))); + self.chat_line( + horizon_client::text::Text::literal(format!( + "(Horizon cannot show {menu} screens yet)" + )), + horizon_client::chat::ChatSource::Client, + ); return; } };