diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 6de683c67..f13be4c84 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1139,6 +1139,10 @@ struct Game<'a> { lan_acting_uuid: Option, /// Command feedback to forward to a guest. chat_capture: Option>, + /// `broadcastToAdmins` lines a guest's command queued, sent once it + /// returns: the line, whether operators get it and whether the console + /// logs it. + admin_feedback: Vec<(horizon_client::text::Text, bool, bool)>, /// State of `/spectate`, `/posteffect`, `/debug`, `/waypoint` and friends. cmds: commands::extra::CommandExtras, ui: chat::UiState, @@ -10280,6 +10284,7 @@ impl<'a> Game<'a> { lan_acting_name: None, lan_acting_uuid: None, chat_capture: None, + admin_feedback: Vec::new(), cmds: Default::default(), ui: Default::default(), combat: Default::default(), diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 962075ee7..1995efbf4 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1,5 +1,6 @@ //! Command execution (the `execute` side of each vanilla command class): //! entity selectors resolved against the game, vanilla feedback and errors. +mod admin; pub(super) mod compute; mod data; mod effects; @@ -160,8 +161,38 @@ impl Game<'_> { return; } if self.ui.rules.bool("send_command_feedback") { - self.system_message(message); + self.system_message(message.clone()); } + self.broadcast_to_admins(message); + } + /// CommandSourceStack.broadcastToAdmins, for a guest's command on a + /// dedicated server (`sendSuccess` with `broadcast`): `[name: message]`, + /// gray and italic, for the other operators when `send_command_feedback` + /// and the console when `log_admin_commands`. Queued while the guest acts; + /// `send_admin_feedback` sends it. + fn broadcast_to_admins(&mut self, message: Text) { + if self.lan_acting.is_none() + || self.options.dedicated.is_none() + || message + .translation_key() + .is_some_and(|k| admin::QUIET.contains(&k)) + { + return; + } + let ops = self.ui.rules.bool("send_command_feedback"); + let console = self.ui.rules.bool("log_admin_commands"); + if !ops && !console { + return; + } + // getDisplayName: the entity the command runs as (`execute as`). + let who = self + .command_source + .and_then(|s| s.entity) + .unwrap_or(Target::Player); + let line = Text::translate("chat.type.admin", &[self.target_name(who), message]) + .with_color(text::GRAY) + .italic(); + self.admin_feedback.push((line, ops, console)); } fn source_position(&self) -> [f64; 3] { if let Some(s) = &self.command_source { @@ -321,12 +352,16 @@ impl Game<'_> { .map_or_else(String::new, |o| o.kind.clone()), } } + /// The name of the player the game acts for: a guest's own while their + /// command or action runs (`Player.getName`). + pub(super) fn acting_player_name(&self) -> &str { + self.lan_acting_name.as_deref().unwrap_or(PLAYER_NAME) + } /// Entity.getDisplayName. pub(super) fn target_name(&self, t: Target) -> Text { match t { Target::Player => { - // A guest's commands name the guest. - let name = self.lan_acting_name.as_deref().unwrap_or(PLAYER_NAME); + let name = self.acting_player_name(); match self.score.board.players_team(name) { // PlayerTeam.formatNameForTeam. Some(team) => team.formatted_name(Text::literal(name)), @@ -767,7 +802,7 @@ impl Game<'_> { } self.feedback(Text::translate( "commands.gamemode.success.other", - &[Text::literal(PLAYER_NAME), mode_name], + &[Text::literal(self.acting_player_name()), mode_name], )); } } @@ -922,7 +957,7 @@ impl Game<'_> { &[ Text::literal(count.to_string()), name, - Text::literal(PLAYER_NAME), + Text::literal(self.acting_player_name()), ], ) } else { @@ -1794,7 +1829,7 @@ impl Game<'_> { ), _ => None, }; - let player = Text::literal(PLAYER_NAME); + let player = Text::literal(self.acting_player_name()); let players = targets.len(); if let (Some(i), Some(Arg::Str(criterion))) = (index, ctx.get("criterion")) { let a = &tree.list[i]; @@ -1904,7 +1939,10 @@ impl Game<'_> { }; self.system_message(Text::translate( &format!("commands.experience.query.{unit}"), - &[Text::literal(PLAYER_NAME), Text::literal(value.to_string())], + &[ + Text::literal(self.acting_player_name()), + Text::literal(value.to_string()), + ], )); return Ok(value); } @@ -1941,7 +1979,7 @@ impl Game<'_> { &key, &[ Text::literal(amount.to_string()), - Text::literal(PLAYER_NAME), + Text::literal(self.acting_player_name()), ], )); Ok(targets.len() as i32) @@ -2248,7 +2286,7 @@ impl Game<'_> { return Err(if targets.len() == 1 { CommandError::new(Text::translate( "clear.failed.single", - &[Text::literal(PLAYER_NAME)], + &[Text::literal(self.acting_player_name())], )) } else { err("clear.failed.multiple", &[&targets.len()]) @@ -2259,7 +2297,7 @@ impl Game<'_> { &format!("commands.clear.{kind}.single"), &[ Text::literal(removed.to_string()), - Text::literal(PLAYER_NAME), + Text::literal(self.acting_player_name()), ], )); Ok(removed) @@ -2510,7 +2548,7 @@ impl Game<'_> { let name = match self.command_source.map(|s| s.entity) { Some(Some(t)) => self.target_name(t), Some(None) => Text::literal("Server"), - None => Text::literal(PLAYER_NAME), + None => Text::literal(self.acting_player_name()), }; let line = match id { "say" => Text::translate("chat.type.announcement", &[name, message]), @@ -2520,14 +2558,14 @@ impl Game<'_> { // Whispering to yourself: the incoming and outgoing lines. let out = Text::translate( "commands.message.display.outgoing", - &[Text::literal(PLAYER_NAME), message.clone()], + &[Text::literal(self.acting_player_name()), message.clone()], ) .with_color(text::GRAY) .italic(); self.system_message(out); Text::translate( "commands.message.display.incoming", - &[Text::literal(PLAYER_NAME), message], + &[Text::literal(self.acting_player_name()), message], ) .with_color(text::GRAY) .italic() diff --git a/crates/horizon-client/src/game/commands/admin.rs b/crates/horizon-client/src/game/commands/admin.rs new file mode 100644 index 000000000..1a5115f4d --- /dev/null +++ b/crates/horizon-client/src/game/commands/admin.rs @@ -0,0 +1,92 @@ +//! Which command feedback vanilla tells the other operators and the console +//! about (`CommandSourceStack.sendSuccess`'s `broadcast`). + +/// The replies vanilla sends with `broadcast` false: queries and lists, which +/// only the player who asked sees. Every other success message is broadcast. +pub(super) const QUIET: &[&str] = &[ + "commands.attribute.base_value.get.success", + "commands.attribute.base_value.reset.success", + "commands.attribute.base_value.set.success", + "commands.attribute.modifier.add.success", + "commands.attribute.modifier.remove.success", + "commands.attribute.modifier.value.get.success", + "commands.attribute.value.get.success", + "commands.banlist.entry", + "commands.banlist.list", + "commands.banlist.none", + "commands.bossbar.list.bars.none", + "commands.bossbar.list.bars.some", + "commands.data.block.get", + "commands.data.block.query", + "commands.data.entity.get", + "commands.data.entity.query", + "commands.data.storage.get", + "commands.data.storage.query", + "commands.datapack.list.available.none", + "commands.datapack.list.available.success", + "commands.datapack.list.enabled.none", + "commands.datapack.list.enabled.success", + "commands.difficulty.query", + "commands.execute.conditional.pass", + "commands.execute.conditional.pass_count", + "commands.experience.query.levels", + "commands.experience.query.points", + "commands.fetchprofile.copy_component", + "commands.fetchprofile.copy_text", + "commands.fetchprofile.give_item", + "commands.fetchprofile.summon_mannequin", + "commands.forceload.list.multiple", + "commands.forceload.list.single", + "commands.forceload.query.success", + "commands.gamerule.query", + "commands.jfr.started", + "commands.jfr.stopped", + "commands.list.players", + "commands.locate.biome.success", + "commands.locate.poi.success", + "commands.locate.structure.success", + "commands.perf.started", + "commands.perf.stopped", + "commands.posteffect.list.empty", + "commands.posteffect.list.success", + "commands.random.reset.all.success", + "commands.random.reset.success", + "commands.random.sample.success", + "commands.save.saving", + "commands.scoreboard.objectives.list.empty", + "commands.scoreboard.objectives.list.success", + "commands.scoreboard.players.get.success", + "commands.scoreboard.players.list.empty", + "commands.scoreboard.players.list.entity.empty", + "commands.scoreboard.players.list.entity.entry", + "commands.scoreboard.players.list.entity.success", + "commands.scoreboard.players.list.success", + "commands.seed.success", + "commands.spectate.success.started", + "commands.spectate.success.stopped", + "commands.team.list.members.empty", + "commands.team.list.members.success", + "commands.team.list.teams.empty", + "commands.team.list.teams.success", + "commands.team.option.prefix.success", + "commands.team.option.suffix.success", + "commands.tick.query.percentiles", + "commands.tick.query.rate.running", + "commands.tick.query.rate.sprinting", + "commands.tick.status.frozen", + "commands.tick.status.lagging", + "commands.tick.status.running", + "commands.tick.status.sprinting", + "commands.time.query.absolute", + "commands.time.query.gametime", + "commands.time.query.timeline", + "commands.time.query.timeline.repetitions", + "commands.waypoint.list.empty", + "commands.waypoint.list.success", + "commands.waypoint.modify.color", + "commands.waypoint.modify.color.reset", + "commands.waypoint.modify.style", + "commands.whitelist.list", + "commands.whitelist.none", + "commands.worldborder.get", +]; diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 578153247..2055798f4 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -1,7 +1,6 @@ //! `/recipe`, `/damage`, `/rotate`, `/swing`, `/playsound`, `/stopsound`, //! `/particle`, `/attribute`, `/ride` and `/spreadplayers`. use super::{Arg, Context, Game, R, Target, err}; -use crate::game::chat::PLAYER_NAME; use horizon_client::{ mobs::{Damage, DamageKind, Who}, scoreboard_cmd::{Holder, Tracker}, @@ -313,7 +312,7 @@ impl Game<'_> { (pos, volume) }; self.audio.play_on(source, &sound, Some(at), v, pitch); - tracker.mark(&holder(Text::literal(PLAYER_NAME))); + tracker.mark(&holder(Text::literal(self.acting_player_name()))); } let name = Text::literal(sound.clone()); let (message, total) = tracker.message( diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 7cd4b0474..65da99dae 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -650,6 +650,7 @@ impl Game<'_> { }), ); } + self.send_admin_feedback(host, conn); } } S::Unknown(8, payload) => { @@ -860,6 +861,32 @@ impl Game<'_> { }), ); } + self.send_admin_feedback(host, conn); + } + + /// The `broadcastToAdmins` lines a guest's command queued: every other + /// operator gets them, and the console logs them as the server's own + /// system messages (MinecraftServer.sendSystemMessage). + fn send_admin_feedback(&mut self, host: &mut LanHost, source: u32) { + for (line, ops, console) in std::mem::take(&mut self.admin_feedback) { + if ops { + let content = horizon_client::lan::data::component_nbt(&line.component()); + for g in host + .hub + .guests + .iter() + .filter(|g| g.conn != source && g.permission > 0) + { + g.send(&C::SystemChat(play::SystemChat { + content: content.clone(), + overlay: false, + })); + } + } + if console { + super::dedicated::log("INFO", &format!("System chat: {}", line.plain())); + } + } } /// ServerGamePacketListenerImpl.handleCustomCommandSuggestions: the diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 60894a14e..6ab5a9ff3 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -130,7 +130,7 @@ impl Game<'_> { /// `ScoreHolder.getScoreboardName`: the player's name, an entity's UUID. pub(super) fn holder_name(&mut self, t: Target) -> Option { match t { - Target::Player => Some(PLAYER_NAME.to_owned()), + Target::Player => Some(self.acting_player_name().to_owned()), Target::Mob(id) | Target::Item(id) => Some(uuid_text(self.uuid_for(id))), _ => None, } @@ -146,7 +146,7 @@ impl Game<'_> { } /// The entity with the given scoreboard name. fn target_of_holder(&self, name: &str) -> Option { - if name == PLAYER_NAME { + if name == self.acting_player_name() { return Some(Target::Player); } let uuid = uuid_from_text(name).filter(|_| name.len() == 36)?; @@ -379,8 +379,9 @@ impl Game<'_> { /// `ServerPlayer.die`: the death count. pub(super) fn score_player_died(&mut self) { let display = self.player_display_comp(); + let me = self.acting_player_name().to_owned(); let board = &mut self.score.board; - board.for_all_objectives_with(sb::CRITERIA_DEATH_COUNT, PLAYER_NAME, Some(&display), |v| { + board.for_all_objectives_with(sb::CRITERIA_DEATH_COUNT, &me, Some(&display), |v| { v.wrapping_add(1) }); // A respawned player has everything to record again. @@ -390,25 +391,21 @@ impl Game<'_> { pub(super) fn score_player_killed(&mut self, victim: Target) { let victim_name = self.holder_name(victim); let display = self.player_display_comp(); + let me = self.acting_player_name().to_owned(); let board = &mut self.score.board; let inc = |v: i32| v.wrapping_add(1); - board.for_all_objectives_with(sb::CRITERIA_TOTAL_KILLS, PLAYER_NAME, Some(&display), inc); + board.for_all_objectives_with(sb::CRITERIA_TOTAL_KILLS, &me, Some(&display), inc); if victim == Target::Player { - board.for_all_objectives_with( - sb::CRITERIA_PLAYER_KILLS, - PLAYER_NAME, - Some(&display), - inc, - ); + board.for_all_objectives_with(sb::CRITERIA_PLAYER_KILLS, &me, Some(&display), inc); } let color_of = |board: &Scoreboard, name: &str| board.players_team(name).and_then(|t| t.color.clone()); if let Some(victim_name) = victim_name { if let Some(color) = color_of(board, &victim_name) { let criteria = format!("teamkill.{color}"); - board.for_all_objectives_with(&criteria, PLAYER_NAME, Some(&display), inc); + board.for_all_objectives_with(&criteria, &me, Some(&display), inc); } - if let Some(color) = color_of(board, PLAYER_NAME) { + if let Some(color) = color_of(board, &me) { let criteria = format!("killedByTeam.{color}"); board.for_all_objectives(&criteria, &victim_name, inc); } @@ -430,7 +427,7 @@ impl Game<'_> { self.score.board.players_team(&uuid_text(*uuid)) } pub(super) fn player_team(&self) -> Option<&sb::Team> { - self.score.board.players_team(PLAYER_NAME) + self.score.board.players_team(self.acting_player_name()) } /// The teams of the player and of the mobs on one (empty without teams). pub(super) fn mob_teams(&self) -> horizon_client::mobs::Teams { @@ -464,16 +461,17 @@ impl Game<'_> { } /// `Player.getDisplayName`: the name with the team's prefix, suffix and colour. pub(super) fn player_display_comp(&self) -> Comp { - let name = literal(PLAYER_NAME); + let name = literal(self.acting_player_name()); match self.player_team() { Some(t) => t.formatted_name_comp(&name), None => name, } } pub(super) fn player_display_text(&self) -> Text { + let name = Text::literal(self.acting_player_name()); match self.player_team() { - Some(t) => t.formatted_name(Text::literal(PLAYER_NAME)), - None => Text::literal(PLAYER_NAME), + Some(t) => t.formatted_name(name), + None => name, } } @@ -688,7 +686,7 @@ impl Env for GameEnv<'_, '_> { .collect() } fn named(&mut self, name: &str) -> Holder { - if name.eq_ignore_ascii_case(PLAYER_NAME) && self.g.player.is_some() { + if name.eq_ignore_ascii_case(self.g.acting_player_name()) && self.g.player.is_some() { return self .g .holder_for(Target::Player) @@ -705,7 +703,7 @@ impl Env for GameEnv<'_, '_> { None => Some(Target::Player), }?; let name = match entity { - Target::Player => PLAYER_NAME.to_owned(), + Target::Player => self.g.acting_player_name().to_owned(), Target::Mob(id) | Target::Item(id) => uuid_text(self.g.uuid_for(id)), _ => return None, }; diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client/src/text.rs index e9710e442..e0b144714 100644 --- a/crates/horizon-client/src/text.rs +++ b/crates/horizon-client/src/text.rs @@ -233,6 +233,10 @@ impl Text { } /// The `Component` as vanilla's JSON (ComponentSerialization): the one /// built through the constructors, else the spans as literal siblings. + /// The key of a `Component.translatable` built through [`Text::translate`]. + pub fn translation_key(&self) -> Option<&str> { + self.source.as_deref()?.get("translate")?.as_str() + } pub fn component(&self) -> Value { if let Some(c) = &self.source { return (**c).clone(); diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java index bb438b735..f87e9cf0f 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java @@ -643,6 +643,11 @@ public final class VanillaProtocolClient { + " minecraft:furnace")); send(new ServerboundChatCommandPacket("give @s minecraft:raw_iron")); send(new ServerboundChatCommandPacket("give @s minecraft:coal")); + // A score on @s is the player's own (its feedback reaches the console: broadcast); + // a query's reply doesn't. + send(new ServerboundChatCommandPacket("scoreboard objectives add parity dummy")); + send(new ServerboundChatCommandPacket("scoreboard players set @s parity 3")); + send(new ServerboundChatCommandPacket("scoreboard players get @s parity")); step++; stepAt = now; } else if (step == 7 + REPLIES.length && now - stepAt > 1500) { diff --git a/tools/test_dedicated_server_parity.py b/tools/test_dedicated_server_parity.py index 0f40893c8..6ac9aecbe 100644 --- a/tools/test_dedicated_server_parity.py +++ b/tools/test_dedicated_server_parity.py @@ -13,7 +13,8 @@ the same files), chats, runs /list and commands that fail (`/random value 7..7`, `/random value x`, `/trigger nope`), trades, is made an operator by the console, runs /kill, respawns (as vanilla's LevelLoadTracker waits: until the "level chunks load start" event and the chunk under the player), sets a furnace -beside itself, gives itself raw iron and coal, opens the furnace, shift-clicks +beside itself, gives itself raw iron and coal, sets and asks its own score +(`@s`), opens the furnace, shift-clicks the ore and the coal in and the ingot out, and leaves. The console then runs `list` and `say` and `stop`. Compared, all of them exactly: @@ -33,7 +34,9 @@ exactly: player respawned (guests' death messages aren't Horizon's yet: left out); - the furnace menu: its type and title, its contents, the slots each shift-click changes and its lit and cooking totals; -- the console lines about the player, the chat, `list`, `say` and `stop`; +- the console lines about the player (an operator's command feedback, which + vanilla broadcasts to the console, included), the chat, `list`, `say` and + `stop`; - the files the servers leave: server.properties (but the date line), eula.txt, ops.json, whitelist.json, banned-players.json, banned-ips.json, usercache.json (but the date the player's entry expires). @@ -209,10 +212,9 @@ CONSOLE_LINE = re.compile(r'^\[\d\d:\d\d:\d\d\] \[([^\]]+)\]: (.*)$') KEPT = re.compile(r'Tester|\[Server\]|\[Not Secure\]|There are|Stopping|Saving|ThreadedAnvilChunkStorage|All dimensions|Unknown or incomplete') -# Guests' death messages, the op's command feedback broadcast to the console and guests' -# advancement announcements aren't Horizon's yet (the client's own transcript leaves the -# death message out as well). -NOT_YET = re.compile(r'Tester was killed|Killed Tester|System chat: \[Tester: |Tester has made the advancement') +# Guests' death messages and advancement announcements aren't Horizon's yet (the client's +# own transcript leaves the death message out as well). +NOT_YET = re.compile(r'Tester was killed|Tester has made the advancement') def console_lines(lines):