ghast-client 0.5.5

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3)
Documentation
//! Sign editing: the sign editor the server opens (`open_sign_entity`) and the lines the
//! client sends back (`update_sign`), as the vanilla sign screen does it.
//!
//! The server opens the editor after the player placed a sign (every version) and, on 1.20+,
//! when the player right-clicks a sign it may edit (front or back side). While the editor is
//! open ([`crate::TickContext::sign_editor`]) the screen has the keyboard and the mouse: the
//! movement keys are released and the mouse buttons are up, as for any screen. The behaviour
//! answers with [`crate::TickContext::write_sign`] (the Done button after typing the lines) or
//! [`crate::TickContext::close_sign`] (Done / Escape without typing). Either way vanilla
//! sends exactly one `update_sign` when the screen goes away (`removed()`), written in call
//! order with the tick's other actions, before its movement packet.
//!
//! # Vanilla rules modelled (read from the client jars)
//!
//! - Lines are typed one character at a time; the screen drops the characters a chat line
//!   may not hold (`SharedConstants.isValidChar` / `StringUtil.isAllowedChatCharacter`: `§`,
//!   control characters below U+0020 and U+007F) — [`vanilla_line`].
//! - 1.8.9 sends each line as a chat component in JSON (`Text.Serializer` with Gson's default
//!   HTML-safe escaping); 1.12.2 and later send plain strings. 1.20+ (26.x) also sends the
//!   side (front / back).
//! - The server reads at most 384 characters per line (`readString(384)`); longer lines are
//!   cut there so the packet never kicks the client.
//! - The editor that opens while another is open replaces it: the old one sends its lines
//!   first ([`SignCloseReason::Replaced`]).
//! - 1.16.5: an editor opened where the client has no sign closes on the screen's first tick
//!   (`SignEditScreen.tick`: the block entity the client made up reads the block there),
//!   sending its lines ([`SignCloseReason::BlockGone`]). The 1.16.5 server sends the editor
//!   before the block (the vanilla client has the sign from its own placement prediction,
//!   which ghast does not make for signs), so ghast closes it only when the client knows
//!   another block there, not for air.
//! - 26.x: the client opens the editor only when it has a sign block entity at the position
//!   (otherwise vanilla logs "Ignoring openTextEdit": [`SignEvent::Ignored`]); the screen's tick
//!   closes it (sending its lines) when the sign is gone or the player's eyes are farther than
//!   the block interaction range + 4 from the sign's block box
//!   (`SignBlockEntity.playerIsTooFarAwayToEdit`).
//!
//! # Not modelled
//!
//! - The width limit: the vanilla screen stops a line at 90 font pixels (60 on hanging signs),
//!   which needs the font's glyph widths. ghast does not cut lines by width; servers keep
//!   what they get (vanilla servers do not check widths), so keep lines short (about 15
//!   characters) to look like a vanilla client.
//! - The text the sign already shows: vanilla's screen starts with it and sends it back
//!   unchanged when closed without typing. ghast does not keep sign text, so
//!   [`crate::TickContext::close_sign`] sends four empty lines — what vanilla sends for a sign
//!   just placed. To leave an existing sign's text as it is, pass its lines to
//!   [`crate::TickContext::write_sign`].
//! - Other screens: a window the server opens while the editor is open does not close it.

use ghast_protocol::BlockPos;

/// The longest line the server reads (`readString(384)`), in UTF-16 units.
pub const MAX_LINE_LENGTH: usize = 384;

/// The sign editor the server opened.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct SignEditor {
    /// The sign's block position.
    pub pos: BlockPos,
    /// The front text is edited (1.20+: `false` = the back); always `true` before 1.20.
    pub front: bool,
}

impl SignEditor {
    /// An editor of the sign at `pos`, front or back side.
    #[must_use]
    pub const fn new(pos: BlockPos, front: bool) -> Self {
        SignEditor { pos, front }
    }
}

/// Why the client closed the sign editor by itself (it sent the lines it had, four empty
/// ones: see the module docs).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SignCloseReason {
    /// The server opened another sign editor.
    Replaced,
    /// The sign is gone (26.x) or was not there when the editor opened (1.16.5).
    BlockGone,
    /// 26.x: the player is too far from the sign.
    TooFar,
}

/// What happened to the sign editor since the behaviour's previous tick
/// ([`crate::TickEvents::signs`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SignEvent {
    /// The server opened the editor (now [`crate::TickContext::sign_editor`]).
    Opened(SignEditor),
    /// The client closed the editor by itself and sent its lines.
    Closed(SignEditor, SignCloseReason),
    /// 26.x: the server asked to edit a sign the client does not have (no sign block at the
    /// position, or its column is not loaded); vanilla ignores it.
    Ignored(SignEditor),
}

/// Why [`crate::TickContext::write_sign`] sent nothing.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SignError {
    /// No sign editor is open.
    NotOpen,
    /// More than four lines.
    TooManyLines,
}

impl std::fmt::Display for SignError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            SignError::NotOpen => "no sign editor is open",
            SignError::TooManyLines => "a sign has four lines",
        })
    }
}

impl std::error::Error for SignError {}

/// `SharedConstants.isValidChar` (1.8 – 1.16.5) / `StringUtil.isAllowedChatCharacter` (26.x):
/// what the vanilla text fields let the player type.
#[inline]
#[must_use]
pub const fn allowed_char(c: char) -> bool {
    c != '§' && c >= ' ' && c != '\u{7f}'
}

/// A line as the vanilla sign screen lets it be typed: the characters [`allowed_char`] rejects
/// are dropped, then the line is cut to [`MAX_LINE_LENGTH`] UTF-16 units (the width limit is
/// not applied, see the module docs).
///
/// ```
/// assert_eq!(ghast_client::sign::vanilla_line("a§1b\tc"), "a1bc");
/// ```
#[must_use]
pub fn vanilla_line(line: &str) -> String {
    let s: String = line.chars().filter(|&c| allowed_char(c)).collect();
    crate::version::truncate_utf16(&s, MAX_LINE_LENGTH).to_owned()
}

/// 1.8.9: a line as `Text.Serializer.serialize(new LiteralText(line))` writes it — a JSON
/// string with Gson's default escaping (HTML-safe: `<`, `>`, `&`, `=`, `'` as `\u00xx`, the
/// line and paragraph separators too), cut so the JSON stays within [`MAX_LINE_LENGTH`].
#[cfg(feature = "v1_8")]
pub(crate) fn legacy_json_line(line: &str) -> String {
    gson_string(line, MAX_LINE_LENGTH)
}

/// `line` as a JSON string the way Gson writes it (see [`legacy_json_line`]), at most `max`
/// UTF-16 units with its quotes.
pub(crate) fn gson_string(line: &str, max: usize) -> String {
    let mut out = String::with_capacity(line.len() + 2);
    out.push('"');
    let mut units = 1usize;
    for c in line.chars() {
        let mut buf = [0u8; 12];
        let esc: &str = match c {
            '"' => "\\\"",
            '\\' => "\\\\",
            '\t' => "\\t",
            '\u{8}' => "\\b",
            '\n' => "\\n",
            '\r' => "\\r",
            '\u{c}' => "\\f",
            '<' | '>' | '&' | '=' | '\'' | '\u{2028}' | '\u{2029}' | '\0'..='\u{1f}' => {
                use std::io::Write;
                let mut w = &mut buf[..];
                let _ = write!(w, "\\u{:04x}", c as u32);
                let n = 12 - w.len();
                std::str::from_utf8(&buf[..n]).unwrap_or("")
            }
            _ => c.encode_utf8(&mut buf),
        };
        let add = esc.encode_utf16().count();
        // room for the closing quote
        if units.saturating_add(add + 1) > max {
            break;
        }
        units += add;
        out.push_str(esc);
    }
    out.push('"');
    out
}

/// The four lines to send: the given ones through [`vanilla_line`], the missing ones empty.
pub(crate) fn lines(given: &[&str]) -> Result<Box<[String; 4]>, SignError> {
    if given.len() > 4 {
        return Err(SignError::TooManyLines);
    }
    let mut out: Box<[String; 4]> = Box::default();
    for (o, l) in out.iter_mut().zip(given) {
        *o = vanilla_line(l);
    }
    Ok(out)
}

/// The open editor as the core keeps it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct OpenSign {
    pub editor: SignEditor,
    /// 1.16.5: no sign at the position when it opened; the screen's first tick checks again.
    pub check_first_tick: bool,
}

/// The sign rules of a version ([`crate::version::Capabilities::sign_editor`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SignRules {
    /// 1.8.9 (JSON lines) and 1.12.2 (plain lines): the editor always opens (the client makes
    /// up a sign block entity where it has none) and only the player closes it.
    Legacy {
        /// The lines are sent as JSON chat components (1.8).
        json: bool,
    },
    /// 1.16.5: as [`SignRules::Legacy`] (plain lines), but an editor opened where the client
    /// has no sign closes on the screen's first tick.
    FirstTickCheck,
    /// 1.20+: the editor opens only on a sign the client has (front or back side) and closes
    /// when the sign is gone or the player is too far.
    Sided,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn filters_like_the_screen() {
        assert_eq!(vanilla_line("a§1b\tc\u{7f}d é"), "a1bcd é");
        let long = "x".repeat(500);
        assert_eq!(vanilla_line(&long).len(), MAX_LINE_LENGTH);
    }

    #[cfg(feature = "v1_8")]
    #[test]
    fn gson_escapes() {
        assert_eq!(legacy_json_line(""), "\"\"");
        assert_eq!(legacy_json_line("Hello"), "\"Hello\"");
        assert_eq!(
            legacy_json_line("a\"b\\c<d>&='"),
            "\"a\\\"b\\\\c\\u003cd\\u003e\\u0026\\u003d\\u0027\""
        );
        assert_eq!(legacy_json_line("\u{2028}é"), "\"\\u2028é\"");
        let j = legacy_json_line(&"<".repeat(200));
        assert!(
            j.len() <= MAX_LINE_LENGTH && j.ends_with('"'),
            "{}",
            j.len()
        );
        assert_eq!(j.len(), 2 + 6 * 63);
    }

    #[test]
    fn four_lines() {
        let l = lines(&["a", "b"]).unwrap();
        assert_eq!(
            *l,
            ["a".to_owned(), "b".into(), String::new(), String::new()]
        );
        assert_eq!(lines(&["", "", "", "", ""]), Err(SignError::TooManyLines));
    }
}