Add /tellraw and /title

ComponentArgument reads SNBT or JSON text components (text, translate
with fallback, selector, keybind, colours, formatting, extra, lists);
selector components resolve for the command source. /title drives the
Gui title, subtitle, times and action bar, drawn with vanilla's fades
and 4x / 2x scales over the hotbar.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-09 01:04:21 +02:00
parent a5db4eb8e3
commit d5438f61e8
9 changed files with 543 additions and 1 deletions
+11 -1
View File
@@ -111,6 +111,8 @@ pub enum ArgType {
Anchor,
/// SwizzleArgument: a set of `x`, `y` and `z` (kept as text).
Swizzle,
/// ComponentArgument: an SNBT/JSON text component (kept as JSON text).
Component,
/// CompoundTagArgument (kept as SNBT text).
Nbt,
}
@@ -1402,6 +1404,14 @@ impl ArgType {
}
Arg::Str(read_braced(reader, '{', '}')?)
}
ArgType::Component => {
let (value, used) =
crate::component::parse_snbt(reader.remaining()).map_err(|e| {
CommandError::tr_at("argument.component.invalid", &[&e], reader)
})?;
reader.cursor += used;
Arg::Str(value.to_string())
}
ArgType::Swizzle => {
let mut axes = String::new();
while reader.can_read() && reader.peek() != ' ' {
@@ -1493,7 +1503,7 @@ impl ArgType {
}
ArgType::GameMode => builder.suggest_matching(GameMode::ALL.map(GameMode::name)),
ArgType::Anchor => builder.suggest_matching(["eyes", "feet"]),
ArgType::Swizzle => {}
ArgType::Swizzle | ArgType::Component => {}
ArgType::Message => {
// MessageArgument suggests selectors and names for the last word.
let rem = builder.remaining();
@@ -314,6 +314,32 @@ pub fn build() -> Dispatcher {
let uuids = d.literal(list, "uuids");
d.executes(uuids, "list");
// tellraw <targets> <message>
let tellraw = d.literal(root, "tellraw");
d.requires(tellraw, GAMEMASTERS);
let t = d.argument(tellraw, "targets", PLAYERS);
let m = d.argument(t, "message", ArgType::Component);
d.executes(m, "tellraw");
// title <targets> clear|reset|title|subtitle|actionbar <title>|times <in> <stay> <out>
let title = d.literal(root, "title");
d.requires(title, GAMEMASTERS);
let t = d.argument(title, "targets", PLAYERS);
for mode in ["clear", "reset"] {
let l = d.literal(t, mode);
d.executes(l, "title");
}
for mode in ["title", "subtitle", "actionbar"] {
let l = d.literal(t, mode);
let c = d.argument(l, "title", ArgType::Component);
d.executes(c, "title");
}
let times = d.literal(t, "times");
let fade_in = d.argument(times, "fadeIn", ArgType::Time { min: 0 });
let stay = d.argument(fade_in, "stay", ArgType::Time { min: 0 });
let fade_out = d.argument(stay, "fadeOut", ArgType::Time { min: 0 });
d.executes(fade_out, "title");
execute(&mut d, root);
d
}
+245
View File
@@ -0,0 +1,245 @@
//! Text components from commands: `ComponentArgument` reads an SNBT (or JSON)
//! value, `ComponentSerialization` turns it into styled text.
use crate::text::{Style, Text, named_color};
use serde_json::{Map, Value};
/// `SnbtGrammar`, enough for components: compounds, lists, quoted and
/// unquoted strings, numbers (with type suffixes) and booleans. Returns the
/// value and the bytes consumed.
pub fn parse_snbt(input: &str) -> Result<(Value, usize), String> {
let mut p = Parser {
s: input.as_bytes(),
i: 0,
};
let v = p.value()?;
Ok((v, p.i))
}
struct Parser<'a> {
s: &'a [u8],
i: usize,
}
impl Parser<'_> {
fn ws(&mut self) {
while self.i < self.s.len() && self.s[self.i].is_ascii_whitespace() {
self.i += 1;
}
}
fn peek(&self) -> Option<u8> {
self.s.get(self.i).copied()
}
fn expect(&mut self, c: u8) -> Result<(), String> {
self.ws();
if self.peek() == Some(c) {
self.i += 1;
Ok(())
} else {
Err(format!("expected '{}'", c as char))
}
}
fn value(&mut self) -> Result<Value, String> {
self.ws();
match self.peek() {
Some(b'{') => {
self.i += 1;
let mut map = Map::new();
self.ws();
if self.peek() == Some(b'}') {
self.i += 1;
return Ok(Value::Object(map));
}
loop {
self.ws();
let key = self.string()?;
self.expect(b':')?;
map.insert(key, self.value()?);
self.ws();
match self.peek() {
Some(b',') => self.i += 1,
Some(b'}') => {
self.i += 1;
return Ok(Value::Object(map));
}
_ => return Err("expected ',' or '}'".into()),
}
}
}
Some(b'[') => {
self.i += 1;
let mut list = Vec::new();
self.ws();
// Typed arrays [B;...], [I;...], [L;...].
if matches!(
self.s.get(self.i..self.i + 2),
Some([b'B' | b'I' | b'L', b';'])
) {
self.i += 2;
}
self.ws();
if self.peek() == Some(b']') {
self.i += 1;
return Ok(Value::Array(list));
}
loop {
list.push(self.value()?);
self.ws();
match self.peek() {
Some(b',') => self.i += 1,
Some(b']') => {
self.i += 1;
return Ok(Value::Array(list));
}
_ => return Err("expected ',' or ']'".into()),
}
}
}
Some(b'"' | b'\'') => Ok(Value::String(self.string()?)),
Some(_) => {
let word = self.unquoted();
if word.is_empty() {
return Err("expected a value".into());
}
Ok(match word.as_str() {
"true" => Value::Bool(true),
"false" => Value::Bool(false),
_ => {
let digits = word
.trim_end_matches(['b', 'B', 's', 'S', 'l', 'L', 'f', 'F', 'd', 'D']);
match (digits.parse::<i64>(), digits.parse::<f64>()) {
(Ok(n), _) if digits.len() + 1 >= word.len() => Value::from(n),
(_, Ok(f)) if digits.len() + 1 >= word.len() => Value::from(f),
_ => Value::String(word),
}
}
})
}
None => Err("expected a value".into()),
}
}
fn unquoted(&mut self) -> String {
let start = self.i;
while let Some(c) = self.peek() {
if c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.' | b'+') {
self.i += 1;
} else {
break;
}
}
String::from_utf8_lossy(&self.s[start..self.i]).into_owned()
}
fn string(&mut self) -> Result<String, String> {
self.ws();
let Some(q @ (b'"' | b'\'')) = self.peek() else {
return Ok(self.unquoted());
};
self.i += 1;
let mut out = Vec::new();
while let Some(c) = self.peek() {
self.i += 1;
match c {
b'\\' => {
let Some(e) = self.peek() else { break };
self.i += 1;
out.push(match e {
b'n' => b'\n',
b't' => b'\t',
other => other,
});
}
c if c == q => return Ok(String::from_utf8_lossy(&out).into_owned()),
c => out.push(c),
}
}
Err("unterminated string".into())
}
}
/// `ComponentSerialization.CODEC` decoding into text. `selector` components
/// are resolved by `resolve` (ComponentUtils.updateForEntity).
pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text {
match v {
Value::String(s) => Text::literal(s.clone()),
Value::Number(n) => Text::literal(n.to_string()),
Value::Bool(b) => Text::literal(b.to_string()),
// A list is its first element with the rest as siblings.
Value::Array(list) => {
let Some((first, rest)) = list.split_first() else {
return Text::empty();
};
let mut base = to_text(first, resolve);
let style = base
.spans
.first()
.map(|s| s.style.clone())
.unwrap_or_default();
for sibling in rest {
base.push(to_text(sibling, resolve).with_style(&style));
}
base
}
Value::Object(o) => {
let mut style = Style::default();
if let Some(c) = o.get("color").and_then(Value::as_str) {
style.color = named_color(c).or_else(|| {
c.strip_prefix('#')
.and_then(|h| u32::from_str_radix(h, 16).ok())
});
}
let flag = |k: &str| o.get(k).and_then(Value::as_bool);
style.bold = flag("bold");
style.italic = flag("italic");
style.underlined = flag("underlined");
style.strikethrough = flag("strikethrough");
style.obfuscated = flag("obfuscated");
let content = if let Some(t) = o.get("text") {
match t {
Value::String(s) => Text::literal(s.clone()),
other => Text::literal(other.to_string()),
}
} else if let Some(key) = o.get("translate").and_then(Value::as_str) {
let args: Vec<Text> = o
.get("with")
.and_then(Value::as_array)
.map(|a| a.iter().map(|x| to_text(x, resolve)).collect())
.unwrap_or_default();
let translated = Text::translate(key, &args);
match o.get("fallback").and_then(Value::as_str) {
Some(fallback) if translated.plain() == key => Text::translate(fallback, &args),
_ => translated,
}
} else if let Some(sel) = o.get("selector").and_then(Value::as_str) {
resolve(sel)
} else if let Some(key) = o.get("keybind").and_then(Value::as_str) {
crate::keybinds::display_name(key)
} else {
Text::empty()
};
let mut out = content.with_style(&style);
for extra in o
.get("extra")
.and_then(Value::as_array)
.into_iter()
.flatten()
{
out.push(to_text(extra, resolve).with_style(&style));
}
out
}
Value::Null => Text::empty(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn snbt_and_json_components() {
let input = "{text:'Hi ',color:red,extra:[{text:\"there\",bold:1b}]} rest";
let (v, n) = parse_snbt(input).unwrap();
assert_eq!(&input[n..], " rest");
let t = to_text(&v, &mut |_| Text::empty());
assert_eq!(t.plain(), "Hi there");
assert_eq!(t.spans[1].style.color, named_color("red"));
let (v, _) = parse_snbt("[\"a\",{\"text\":\"b\"}]").unwrap();
assert_eq!(to_text(&v, &mut |_| Text::empty()).plain(), "ab");
}
}
+6
View File
@@ -25,6 +25,7 @@ mod shield;
mod sign_edit;
mod station_control;
mod stations;
mod titles;
mod tnt;
mod trading;
use horizon_client::{
@@ -479,6 +480,7 @@ struct Game<'a> {
shield_cooldown: u32,
/// The source of a command run through /execute (the player otherwise).
command_source: Option<commands::execute::Source>,
titles: titles::Titles,
applied_modifiers: Vec<(String, String)>,
experience: Experience,
orbs: Vec<ExperienceOrb>,
@@ -2031,6 +2033,7 @@ impl Game<'_> {
self.tick_effects();
self.tick_burning();
self.tick_using();
self.titles.tick();
self.tick_mining()?;
self.tick_items();
self.spawn_loaded_entities();
@@ -2397,6 +2400,8 @@ impl Game<'_> {
}
}
self.draw_effect_icons(&mut batch);
// Hud: the action bar and titles draw over the hotbar (nextStratum).
self.draw_titles(&mut batch);
let atlas = &self.res.atlas;
if !self.creative
&& let Some(p) = &self.player
@@ -6949,6 +6954,7 @@ pub fn run() -> Result<()> {
offhand: None,
shield_cooldown: 0,
command_source: None,
titles: Default::default(),
applied_modifiers: Vec::new(),
experience: Experience::default(),
orbs: Vec::new(),
@@ -2,6 +2,7 @@
//! entity selectors resolved against the game, vanilla feedback and errors.
mod effects;
pub(super) mod execute;
mod text_commands;
use super::{Dim, Game, Screen, chat::PLAYER_NAME};
use horizon_client::{
@@ -423,6 +424,8 @@ impl Game<'_> {
"effect.give" => self.cmd_effect_give(ctx),
"effect.clear" => self.cmd_effect_clear(ctx),
"enchant" => self.cmd_enchant(ctx),
"tellraw" => self.cmd_tellraw(ctx),
"title" => self.cmd_title(ctx),
"setblock" => self.cmd_setblock(ctx),
"fill" => self.cmd_fill(ctx),
"clone" => self.cmd_clone(ctx),
@@ -0,0 +1,91 @@
//! `/tellraw` (TellRawCommand) and `/title` (TitleCommand).
use super::{Arg, Context, Game, R, Target, err};
use horizon_client::text::Text;
impl Game<'_> {
/// ComponentArgument with selectors resolved for the source
/// (ComponentUtils.updateForEntity: names joined by ", ").
fn component_arg(&mut self, ctx: &Context, name: &str) -> R<Text> {
let Some(Arg::Str(json)) = ctx.get(name) else {
return Ok(Text::empty());
};
let value: serde_json::Value =
serde_json::from_str(json).map_err(|e| err("argument.component.invalid", &[&e]))?;
let mut resolve = |raw: &str| -> Text {
let mut reader = horizon_client::command::Reader::new(raw);
let entities = horizon_client::command::args::ArgType::Entity {
single: false,
players: false,
};
let Ok(Arg::Entity(sel)) = entities.parse(&mut reader, &self.ui.registries) else {
return Text::literal(raw);
};
let found = self.select(&sel);
let mut out = Text::empty();
for (i, t) in found.into_iter().enumerate() {
if i > 0 {
out.push(Text::literal(", "));
}
out.push(self.target_name(t));
}
out
};
Ok(horizon_client::component::to_text(&value, &mut resolve))
}
fn player_targets(&mut self, ctx: &Context) -> R<usize> {
// Only the local player can receive messages and titles.
let targets = self.entities(ctx, "targets", true)?;
Ok(targets.iter().filter(|t| **t == Target::Player).count())
}
pub(super) fn cmd_tellraw(&mut self, ctx: &Context) -> R<i32> {
let n = self.player_targets(ctx)?;
let message = self.component_arg(ctx, "message")?;
if n > 0 {
self.system_message(message);
}
Ok(n as i32)
}
pub(super) fn cmd_title(&mut self, ctx: &Context) -> R<i32> {
let n = self.player_targets(ctx)?;
let name = self.target_name(Target::Player);
let single = n == 1;
let key = if ctx.has("clear") {
self.titles.clear();
"cleared"
} else if ctx.has("reset") {
self.titles.clear();
self.titles.reset_times();
"reset"
} else if ctx.has("times") {
let get = |k: &str| match ctx.get(k) {
Some(Arg::Int(v)) => *v,
_ => -1,
};
self.titles
.set_times(get("fadeIn"), get("stay"), get("fadeOut"));
"times"
} else {
let text = self.component_arg(ctx, "title")?;
if ctx.has("subtitle") {
self.titles.subtitle = Some(text);
"show.subtitle"
} else if ctx.has("actionbar") {
self.titles.set_overlay(text);
"show.actionbar"
} else {
self.titles.set_title(text);
"show.title"
}
};
let message = if single {
Text::translate(&format!("commands.title.{key}.single"), &[name])
} else {
Text::translate(
&format!("commands.title.{key}.multiple"),
&[Text::literal(n.to_string())],
)
};
self.feedback(message);
Ok(n as i32)
}
}
+142
View File
@@ -0,0 +1,142 @@
//! Titles, subtitles and the action bar (`Gui.setTitle`, `setSubtitle`,
//! `setTimes`, `setOverlayMessage`, `extractTitle`, `extractOverlayMessage`).
use super::Game;
use horizon_client::{
hud::{HudBatch, rgba},
text::Text,
};
pub(super) struct Titles {
pub title: Option<Text>,
pub subtitle: Option<Text>,
pub time: i32,
pub fade_in: i32,
pub stay: i32,
pub fade_out: i32,
pub overlay: Option<Text>,
pub overlay_time: i32,
}
impl Default for Titles {
fn default() -> Self {
Self {
title: None,
subtitle: None,
time: 0,
fade_in: 10,
stay: 70,
fade_out: 20,
overlay: None,
overlay_time: 0,
}
}
}
impl Titles {
pub fn set_title(&mut self, title: Text) {
self.title = Some(title);
self.time = self.fade_in + self.stay + self.fade_out;
}
pub fn set_times(&mut self, fade_in: i32, stay: i32, fade_out: i32) {
if fade_in >= 0 {
self.fade_in = fade_in;
}
if stay >= 0 {
self.stay = stay;
}
if fade_out >= 0 {
self.fade_out = fade_out;
}
if self.time > 0 {
self.time = self.fade_in + self.stay + self.fade_out;
}
}
pub fn clear(&mut self) {
self.title = None;
self.subtitle = None;
self.time = 0;
}
pub fn reset_times(&mut self) {
(self.fade_in, self.stay, self.fade_out) = (10, 70, 20);
}
pub fn set_overlay(&mut self, text: Text) {
self.overlay = Some(text);
self.overlay_time = 60;
}
/// Gui.tick.
pub fn tick(&mut self) {
if self.overlay_time > 0 {
self.overlay_time -= 1;
}
if self.time > 0 {
self.time -= 1;
if self.time <= 0 {
self.title = None;
self.subtitle = None;
}
}
}
}
impl Game<'_> {
pub(super) fn draw_titles(&self, batch: &mut HudBatch) {
let t = &self.titles;
let partial = self.clock.fraction() as f32;
let atlas = &self.res.atlas;
let (w, h) = (batch.width, batch.height);
if let Some(text) = &t.overlay
&& t.overlay_time > 0
{
let ticks = t.overlay_time as f32 - partial;
let alpha = ((ticks * 255.0 / 20.0) as i32).min(255);
if alpha > 0 {
let width = atlas.font.width_text(text);
let color = rgba(255, 255, 255, alpha as u8);
batch.text_posed(
atlas,
text,
[-(width / 2.0).trunc(), -4.0],
color,
1.0,
[(w / 2.0).trunc(), (h - 68.0).trunc()],
);
}
}
let Some(title) = &t.title else { return };
if t.time <= 0 {
return;
}
let ticks = t.time as f32 - partial;
let mut alpha = 255;
if t.time > t.fade_out + t.stay {
let time = (t.fade_in + t.stay + t.fade_out) as f32 - ticks;
alpha = (time * 255.0 / t.fade_in.max(1) as f32) as i32;
}
if t.time <= t.fade_out {
alpha = (ticks * 255.0 / t.fade_out.max(1) as f32) as i32;
}
let alpha = alpha.clamp(0, 255);
if alpha == 0 {
return;
}
let color = rgba(255, 255, 255, alpha as u8);
let origin = [(w / 2.0).trunc(), (h / 2.0).trunc()];
let width = atlas.font.width_text(title);
batch.text_posed(
atlas,
title,
[-(width / 2.0).trunc(), -10.0],
color,
4.0,
origin,
);
if let Some(sub) = &t.subtitle {
let width = atlas.font.width_text(sub);
batch.text_posed(
atlas,
sub,
[-(width / 2.0).trunc(), 5.0],
color,
2.0,
origin,
);
}
}
}
+18
View File
@@ -296,6 +296,24 @@ impl HudBatch {
};
self.text_styled(atlas, &t, x, y, color, shadow)
}
/// `text_styled` under a pose: GUI positions scaled by `scale`, then
/// moved to `origin` (Matrix3x2fStack translate + scale).
pub fn text_posed(
&mut self,
atlas: &HudAtlas,
text: &crate::text::Text,
at: [f32; 2],
color: u32,
scale: f32,
origin: [f32; 2],
) -> f32 {
let start = self.vertices.len();
let advance = self.text_styled(atlas, text, at[0], at[1], color, true);
for v in &mut self.vertices[start..] {
v.pos = [origin[0] + v.pos[0] * scale, origin[1] + v.pos[1] * scale];
}
advance
}
/// Font.drawInternal: styled glyphs, shadows first, with bold, italic,
/// underline and strikethrough. `color` is the default colour and alpha.
pub fn text_styled(
+1
View File
@@ -15,6 +15,7 @@ pub mod chunk;
pub mod clock;
pub mod collisions;
pub mod command;
pub mod component;
pub mod containers;
pub mod control;
pub mod crafting;