Skip to main content

ghast_client/
sign.rs

1//! Sign editing: the sign editor the server opens (`open_sign_entity`) and the lines the
2//! client sends back (`update_sign`), as the vanilla sign screen does it.
3//!
4//! The server opens the editor after the player placed a sign (every version) and, on 1.20+,
5//! when the player right-clicks a sign it may edit (front or back side). While the editor is
6//! open ([`crate::TickContext::sign_editor`]) the screen has the keyboard and the mouse: the
7//! movement keys are released and the mouse buttons are up, as for any screen. The behaviour
8//! answers with [`crate::TickContext::write_sign`] (the Done button after typing the lines) or
9//! [`crate::TickContext::close_sign`] (Done / Escape without typing). Either way vanilla
10//! sends exactly one `update_sign` when the screen goes away (`removed()`), written in call
11//! order with the tick's other actions, before its movement packet.
12//!
13//! # Vanilla rules modelled (read from the client jars)
14//!
15//! - Lines are typed one character at a time; the screen drops the characters a chat line
16//!   may not hold (`SharedConstants.isValidChar` / `StringUtil.isAllowedChatCharacter`: `§`,
17//!   control characters below U+0020 and U+007F) — [`vanilla_line`].
18//! - 1.8.9 sends each line as a chat component in JSON (`Text.Serializer` with Gson's default
19//!   HTML-safe escaping); 1.12.2 and later send plain strings. 1.20+ (26.x) also sends the
20//!   side (front / back).
21//! - The server reads at most 384 characters per line (`readString(384)`); longer lines are
22//!   cut there so the packet never kicks the client.
23//! - The editor that opens while another is open replaces it: the old one sends its lines
24//!   first ([`SignCloseReason::Replaced`]).
25//! - 1.16.5: an editor opened where the client has no sign closes on the screen's first tick
26//!   (`SignEditScreen.tick`: the block entity the client made up reads the block there),
27//!   sending its lines ([`SignCloseReason::BlockGone`]). The 1.16.5 server sends the editor
28//!   before the block (the vanilla client has the sign from its own placement prediction,
29//!   which ghast does not make for signs), so ghast closes it only when the client knows
30//!   another block there, not for air.
31//! - 26.x: the client opens the editor only when it has a sign block entity at the position
32//!   (otherwise vanilla logs "Ignoring openTextEdit": [`SignEvent::Ignored`]); the screen's tick
33//!   closes it (sending its lines) when the sign is gone or the player's eyes are farther than
34//!   the block interaction range + 4 from the sign's block box
35//!   (`SignBlockEntity.playerIsTooFarAwayToEdit`).
36//!
37//! # Not modelled
38//!
39//! - The width limit: the vanilla screen stops a line at 90 font pixels (60 on hanging signs),
40//!   which needs the font's glyph widths. ghast does not cut lines by width; servers keep
41//!   what they get (vanilla servers do not check widths), so keep lines short (about 15
42//!   characters) to look like a vanilla client.
43//! - The text the sign already shows: vanilla's screen starts with it and sends it back
44//!   unchanged when closed without typing. ghast does not keep sign text, so
45//!   [`crate::TickContext::close_sign`] sends four empty lines — what vanilla sends for a sign
46//!   just placed. To leave an existing sign's text as it is, pass its lines to
47//!   [`crate::TickContext::write_sign`].
48//! - Other screens: a window the server opens while the editor is open does not close it.
49
50use ghast_protocol::BlockPos;
51
52/// The longest line the server reads (`readString(384)`), in UTF-16 units.
53pub const MAX_LINE_LENGTH: usize = 384;
54
55/// The sign editor the server opened.
56#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
57#[non_exhaustive]
58pub struct SignEditor {
59    /// The sign's block position.
60    pub pos: BlockPos,
61    /// The front text is edited (1.20+: `false` = the back); always `true` before 1.20.
62    pub front: bool,
63}
64
65impl SignEditor {
66    /// An editor of the sign at `pos`, front or back side.
67    #[must_use]
68    pub const fn new(pos: BlockPos, front: bool) -> Self {
69        SignEditor { pos, front }
70    }
71}
72
73/// Why the client closed the sign editor by itself (it sent the lines it had, four empty
74/// ones: see the module docs).
75#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
76#[non_exhaustive]
77pub enum SignCloseReason {
78    /// The server opened another sign editor.
79    Replaced,
80    /// The sign is gone (26.x) or was not there when the editor opened (1.16.5).
81    BlockGone,
82    /// 26.x: the player is too far from the sign.
83    TooFar,
84}
85
86/// What happened to the sign editor since the behaviour's previous tick
87/// ([`crate::TickEvents::signs`]).
88#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
89#[non_exhaustive]
90pub enum SignEvent {
91    /// The server opened the editor (now [`crate::TickContext::sign_editor`]).
92    Opened(SignEditor),
93    /// The client closed the editor by itself and sent its lines.
94    Closed(SignEditor, SignCloseReason),
95    /// 26.x: the server asked to edit a sign the client does not have (no sign block at the
96    /// position, or its column is not loaded); vanilla ignores it.
97    Ignored(SignEditor),
98}
99
100/// Why [`crate::TickContext::write_sign`] sent nothing.
101#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
102#[non_exhaustive]
103pub enum SignError {
104    /// No sign editor is open.
105    NotOpen,
106    /// More than four lines.
107    TooManyLines,
108}
109
110impl std::fmt::Display for SignError {
111    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112        f.write_str(match self {
113            SignError::NotOpen => "no sign editor is open",
114            SignError::TooManyLines => "a sign has four lines",
115        })
116    }
117}
118
119impl std::error::Error for SignError {}
120
121/// `SharedConstants.isValidChar` (1.8 – 1.16.5) / `StringUtil.isAllowedChatCharacter` (26.x):
122/// what the vanilla text fields let the player type.
123#[inline]
124#[must_use]
125pub const fn allowed_char(c: char) -> bool {
126    c != '§' && c >= ' ' && c != '\u{7f}'
127}
128
129/// A line as the vanilla sign screen lets it be typed: the characters [`allowed_char`] rejects
130/// are dropped, then the line is cut to [`MAX_LINE_LENGTH`] UTF-16 units (the width limit is
131/// not applied, see the module docs).
132///
133/// ```
134/// assert_eq!(ghast_client::sign::vanilla_line("a§1b\tc"), "a1bc");
135/// ```
136#[must_use]
137pub fn vanilla_line(line: &str) -> String {
138    let s: String = line.chars().filter(|&c| allowed_char(c)).collect();
139    crate::version::truncate_utf16(&s, MAX_LINE_LENGTH).to_owned()
140}
141
142/// 1.8.9: a line as `Text.Serializer.serialize(new LiteralText(line))` writes it — a JSON
143/// string with Gson's default escaping (HTML-safe: `<`, `>`, `&`, `=`, `'` as `\u00xx`, the
144/// line and paragraph separators too), cut so the JSON stays within [`MAX_LINE_LENGTH`].
145#[cfg(feature = "v1_8")]
146pub(crate) fn legacy_json_line(line: &str) -> String {
147    gson_string(line, MAX_LINE_LENGTH)
148}
149
150/// `line` as a JSON string the way Gson writes it (see [`legacy_json_line`]), at most `max`
151/// UTF-16 units with its quotes.
152pub(crate) fn gson_string(line: &str, max: usize) -> String {
153    let mut out = String::with_capacity(line.len() + 2);
154    out.push('"');
155    let mut units = 1usize;
156    for c in line.chars() {
157        let mut buf = [0u8; 12];
158        let esc: &str = match c {
159            '"' => "\\\"",
160            '\\' => "\\\\",
161            '\t' => "\\t",
162            '\u{8}' => "\\b",
163            '\n' => "\\n",
164            '\r' => "\\r",
165            '\u{c}' => "\\f",
166            '<' | '>' | '&' | '=' | '\'' | '\u{2028}' | '\u{2029}' | '\0'..='\u{1f}' => {
167                use std::io::Write;
168                let mut w = &mut buf[..];
169                let _ = write!(w, "\\u{:04x}", c as u32);
170                let n = 12 - w.len();
171                std::str::from_utf8(&buf[..n]).unwrap_or("")
172            }
173            _ => c.encode_utf8(&mut buf),
174        };
175        let add = esc.encode_utf16().count();
176        // room for the closing quote
177        if units.saturating_add(add + 1) > max {
178            break;
179        }
180        units += add;
181        out.push_str(esc);
182    }
183    out.push('"');
184    out
185}
186
187/// The four lines to send: the given ones through [`vanilla_line`], the missing ones empty.
188pub(crate) fn lines(given: &[&str]) -> Result<Box<[String; 4]>, SignError> {
189    if given.len() > 4 {
190        return Err(SignError::TooManyLines);
191    }
192    let mut out: Box<[String; 4]> = Box::default();
193    for (o, l) in out.iter_mut().zip(given) {
194        *o = vanilla_line(l);
195    }
196    Ok(out)
197}
198
199/// The open editor as the core keeps it.
200#[derive(Clone, Copy, Debug, PartialEq, Eq)]
201pub(crate) struct OpenSign {
202    pub editor: SignEditor,
203    /// 1.16.5: no sign at the position when it opened; the screen's first tick checks again.
204    pub check_first_tick: bool,
205}
206
207/// The sign rules of a version ([`crate::version::Capabilities::sign_editor`]).
208#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
209#[non_exhaustive]
210pub enum SignRules {
211    /// 1.8.9 (JSON lines) and 1.12.2 (plain lines): the editor always opens (the client makes
212    /// up a sign block entity where it has none) and only the player closes it.
213    Legacy {
214        /// The lines are sent as JSON chat components (1.8).
215        json: bool,
216    },
217    /// 1.16.5: as [`SignRules::Legacy`] (plain lines), but an editor opened where the client
218    /// has no sign closes on the screen's first tick.
219    FirstTickCheck,
220    /// 1.20+: the editor opens only on a sign the client has (front or back side) and closes
221    /// when the sign is gone or the player is too far.
222    Sided,
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    #[test]
230    fn filters_like_the_screen() {
231        assert_eq!(vanilla_line("a§1b\tc\u{7f}d é"), "a1bcd é");
232        let long = "x".repeat(500);
233        assert_eq!(vanilla_line(&long).len(), MAX_LINE_LENGTH);
234    }
235
236    #[cfg(feature = "v1_8")]
237    #[test]
238    fn gson_escapes() {
239        assert_eq!(legacy_json_line(""), "\"\"");
240        assert_eq!(legacy_json_line("Hello"), "\"Hello\"");
241        assert_eq!(
242            legacy_json_line("a\"b\\c<d>&='"),
243            "\"a\\\"b\\\\c\\u003cd\\u003e\\u0026\\u003d\\u0027\""
244        );
245        assert_eq!(legacy_json_line("\u{2028}é"), "\"\\u2028é\"");
246        let j = legacy_json_line(&"<".repeat(200));
247        assert!(
248            j.len() <= MAX_LINE_LENGTH && j.ends_with('"'),
249            "{}",
250            j.len()
251        );
252        assert_eq!(j.len(), 2 + 6 * 63);
253    }
254
255    #[test]
256    fn four_lines() {
257        let l = lines(&["a", "b"]).unwrap();
258        assert_eq!(
259            *l,
260            ["a".to_owned(), "b".into(), String::new(), String::new()]
261        );
262        assert_eq!(lines(&["", "", "", "", ""]), Err(SignError::TooManyLines));
263    }
264}