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/examples/probe/hud_fixture/kinds.rs b/crates/horizon-client/examples/probe/hud_fixture/kinds.rs index d1450f2e1..9ba66abe1 100644 --- a/crates/horizon-client/examples/probe/hud_fixture/kinds.rs +++ b/crates/horizon-client/examples/probe/hud_fixture/kinds.rs @@ -319,6 +319,7 @@ fn chat(c: &Value, h: i32, atlas: &HudAtlas) -> Vec { atlas, comp(&m["text"]), indicator, + horizon_client::chat::ChatSource::Client, m["at"].as_u64().unwrap_or(0), false, ); diff --git a/crates/horizon-client/src/chat.rs b/crates/horizon-client/src/chat.rs index 273b87153..04b9d486c 100644 --- a/crates/horizon-client/src/chat.rs +++ b/crates/horizon-client/src/chat.rs @@ -19,6 +19,92 @@ 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, + }, + } + } + /// `visibleMessagesFilter`: the client's own lines always show. + pub fn shows(&self, source: ChatSource) -> bool { + match source { + ChatSource::Player => self.receive_player_messages, + ChatSource::Server => self.receive_system_messages, + ChatSource::Client => true, + } + } + /// 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 + } + } +} + +impl Default for ChatAbilities { + fn default() -> Self { + Self::new(ChatVisibility::Full) + } +} + +/// 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 { @@ -71,6 +157,7 @@ struct Message { added: u64, content: Text, indicator: Option, + source: ChatSource, } /// A wrapped line (`GuiMessage.Line`). #[derive(Clone, Debug)] @@ -105,6 +192,8 @@ pub struct Chat { pub log: bool, /// Messages added since the start, for the control socket's events. pub received: u64, + /// The Chat option's `visibleMessageFilter` (`set_abilities`). + abilities: ChatAbilities, } impl Chat { pub fn lines_per_page(&self, focused: bool) -> usize { @@ -114,16 +203,32 @@ impl Chat { fn max_width(&self) -> i32 { (f64::from(self.options.width_px()) / self.options.scale).floor() as i32 } - /// ChatComponent.addMessage: wrap, prepend and trim to 100 lines. + /// ChatComponent.addMessage: wrap, prepend and trim to 100 lines. A + /// message the Chat option hides is dropped, unlogged. pub fn add( &mut self, atlas: &HudAtlas, content: Text, indicator: Option, + source: ChatSource, ticks: u64, focused: bool, ) { - // ChatComponent.logChatMessage: every message is in the log. + self.add_message(&atlas.font, content, indicator, source, ticks, focused); + } + fn add_message( + &mut self, + font: &crate::font::Font, + content: Text, + indicator: Option, + source: ChatSource, + ticks: u64, + focused: bool, + ) { + if !self.abilities.shows(source) { + return; + } + // ChatComponent.logChatMessage: every message shown is in the log. crate::logging::write_only(log::Level::Info, &format!("[CHAT] {}", content.plain())); if self.log { println!("[CHAT] {}", content.plain()); @@ -132,16 +237,17 @@ impl Chat { added: ticks, content, indicator, + source, }; - self.add_lines(atlas, &message, focused); + self.add_lines(font, &message, focused); self.messages.insert(0, message); self.messages.truncate(100); self.received += 1; } - fn add_lines(&mut self, atlas: &HudAtlas, message: &Message, focused: bool) { + fn add_lines(&mut self, font: &crate::font::Font, message: &Message, focused: bool) { let width = self.max_width(); let content = self.displayed(&message.content); - for line in atlas.font.wrap_components(&content, width) { + for line in font.wrap_components(&content, width) { if focused && self.scroll > 0 { self.new_since_scroll = true; self.scroll_by(1, focused); @@ -167,16 +273,38 @@ impl Chat { content.strip_legacy() } } - /// Re-wrap after a width or scale change (ChatComponent.rescaleChat). + /// Re-wrap after a width or scale change (ChatComponent.rescaleChat), + /// keeping only the messages the Chat option shows. pub fn rescale(&mut self, atlas: &HudAtlas) { + self.rewrap(&atlas.font); + } + fn rewrap(&mut self, font: &crate::font::Font) { self.scroll = 0; self.new_since_scroll = false; self.lines.clear(); - let messages: Vec = self.messages.iter().rev().cloned().collect(); + let messages: Vec = self + .messages + .iter() + .rev() + .filter(|m| self.abilities.shows(m.source)) + .cloned() + .collect(); for m in &messages { - self.add_lines(atlas, m, false); + self.add_lines(font, m, false); } } + /// `ChatComponent.setVisibleMessageFilter`: the Chat option changed; + /// the messages it now hides leave the chat, those it shows again return. + pub fn set_abilities(&mut self, font: &crate::font::Font, abilities: ChatAbilities) { + if self.abilities != abilities { + self.abilities = abilities; + self.rewrap(font); + } + } + /// Whether a message from `source` would show (`visibleMessagesFilter`). + pub fn shows(&self, source: ChatSource) -> bool { + self.abilities.shows(source) + } pub fn clear(&mut self) { self.messages.clear(); self.lines.clear(); @@ -437,6 +565,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 +612,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 +636,7 @@ impl ChatScreen { allow_suggestions: false, keep_suggestions: false, auto_suggestions: true, + abilities, }; s.update_command_info(m, c); s @@ -522,7 +654,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 +737,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 +849,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 +992,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..6b058c0fb 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,99 @@ 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") + ); +} + +/// `ChatComponent.setVisibleMessageFilter`: a message the Chat option hides +/// on arrival is dropped; one already in the chat leaves it while the option +/// hides its kind and comes back when it shows it again. +#[test] +fn the_chat_option_filters_the_lines_both_ways() { + let font = font(); + let mut chat = Chat::default(); + let says = |chat: &mut Chat, text: &str, source| { + chat.add_message(&font, Text::literal(text), None, source, 0, false); + }; + let shown = + |chat: &Chat| -> Vec { chat.lines.iter().map(|l| l.content.plain()).collect() }; + says(&mut chat, "player", ChatSource::Player); + says(&mut chat, "server", ChatSource::Server); + chat.set_abilities(&font, ChatAbilities::new(ChatVisibility::System)); + assert_eq!(shown(&chat), ["server"]); + says(&mut chat, "dropped", ChatSource::Player); + chat.set_abilities(&font, ChatAbilities::new(ChatVisibility::Hidden)); + says(&mut chat, "client", ChatSource::Client); + assert_eq!(shown(&chat), ["client"]); + chat.set_abilities(&font, ChatAbilities::new(ChatVisibility::Full)); + assert_eq!(shown(&chat), ["client", "server", "player"]); +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index ce49e25fa..aa49f8fd0 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9346,6 +9346,9 @@ impl Game<'_> { ) } fn apply_settings(&mut self) { + // LocalPlayer.refreshChatAbilities: the chat shows what the Chat option allows. + let abilities = self.chat_abilities(); + self.ui.chat.set_abilities(&self.gui.atlas.font, abilities); self.streaming.radius = self.settings.render_distance; // Options.biomeBlendRadius, ambientOcclusion and cutoutLeaves: // LevelExtractor.allChanged when they change. diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 12d6e72f1..5d3919c8b 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,11 @@ 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; + } + // The Chat option's Hidden level takes the server's messages too. + if !self.ui.chat.shows(ChatSource::Server) { return; } let focused = self.screen == Screen::Chat; @@ -461,6 +473,7 @@ impl Game<'_> { &self.gui.atlas, text, Some(SYSTEM_INDICATOR), + ChatSource::Server, self.ticks, focused, ); @@ -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. @@ -592,9 +610,14 @@ impl Game<'_> { ); let focused = self.screen == Screen::Chat; let heard = self.mods.running().then(|| line.plain()); - self.ui - .chat - .add(&self.gui.atlas, line, None, self.ticks, focused); + self.ui.chat.add( + &self.gui.atlas, + line, + None, + ChatSource::Player, + self.ticks, + focused, + ); if let Some(line) = heard { self.mods_chat(&line); } @@ -898,9 +921,14 @@ impl Game<'_> { Err(e) => Text::translate("screenshot.failure", &[Text::literal(e.clone())]), }; let focused = self.screen == Screen::Chat; - self.ui - .chat - .add(&self.gui.atlas, message, None, self.ticks, focused); + self.ui.chat.add( + &self.gui.atlas, + message, + None, + ChatSource::Client, + self.ticks, + focused, + ); } } /// `yyyy-MM-dd_HH.mm.ss[_n].png` (Util.getFilenameFormattedDateTime, local time diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 78585e8be..267f358d5 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -2841,9 +2841,14 @@ impl Game<'_> { capture.push(line.clone()); } let focused = self.screen == Screen::Chat; - self.ui - .chat - .add(&self.gui.atlas, line, None, self.ticks, focused); + self.ui.chat.add( + &self.gui.atlas, + line, + None, + horizon_client::chat::ChatSource::Player, + self.ticks, + focused, + ); Ok(1) } /// MessageArgument: `@p`-style selectors in a message become names. diff --git a/crates/horizon-client/src/game/lan_screen.rs b/crates/horizon-client/src/game/lan_screen.rs index 2d0416d72..260cc76c3 100644 --- a/crates/horizon-client/src/game/lan_screen.rs +++ b/crates/horizon-client/src/game/lan_screen.rs @@ -388,7 +388,10 @@ impl Restrictions { 1 => Some("chat_restriction.chat_disabled_by_options"), _ => None, }; - let (chat, commands) = (chat_visibility == 0, chat_visibility < 2); + let abilities = horizon_client::chat::ChatAbilities::new( + horizon_client::chat::ChatVisibility::from_option(chat_visibility), + ); + let (chat, commands) = (abilities.send_messages, abilities.send_commands); // The body's widgets: text blocks (lines, top) and the action's top. let mut blocks = Vec::new(); let mut action = None; diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index a48ab0841..e9222806a 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -507,10 +507,16 @@ impl Game<'_> { } }; // Not through system_message: a mod must not hear its own lines. + // Written by this client, so the Chat option doesn't hide it. let focused = self.screen == Screen::Chat; - self.ui - .chat - .add(&self.gui.atlas, line, None, self.ticks, focused); + self.ui.chat.add( + &self.gui.atlas, + line, + None, + horizon_client::chat::ChatSource::Client, + self.ticks, + focused, + ); } // A mod may set or clear its settings page in any call, not only // while loading: its row's Settings button follows. diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index d9d082411..a9fb2d4d1 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -129,6 +129,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 @@ -428,6 +431,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, @@ -637,14 +641,23 @@ impl Game<'_> { ) } /// 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). The lines the Chat option hides + /// are dropped there (its `visibleMessageFilter`). + pub(super) fn chat_line( + &mut self, + content: horizon_client::text::Text, + source: horizon_client::chat::ChatSource, + ) { + if !self.ui.chat.shows(source) { + return; + } let text = content.plain(); log::info!("[chat] {text}"); self.ui.chat.add( &self.gui.atlas, content, None, + source, self.ticks, self.screen == Screen::Chat, ); @@ -1644,9 +1657,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. @@ -2416,7 +2430,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) => { @@ -2426,12 +2440,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() { @@ -3076,16 +3090,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. @@ -4511,10 +4528,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('/') { @@ -4888,9 +4907,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; } };