ghast-client 0.5.4

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
//! Book and quill editing: what the vanilla book screen sends when the player presses Done
//! (the pages) or signs the book (pages and title), and what it changes in the held stack.
//!
//! Vanilla opens the book screen on the client alone when the player uses a book and quill
//! (right click in the air; the item-use packet goes out as for any item). The server keeps no
//! screen state: the edit is the one packet the screen sends when it closes. ghast does not
//! model the screen itself (no keys are released): [`crate::TickContext::edit_book`] types the
//! pages (and title) and presses Done (or Sign and Finalize) in one call, writing the packet
//! in call order with the tick's other actions, before the movement packet.
//!
//! # Vanilla rules modelled (read from the client jars)
//!
//! | version | packet | pages | page length | title |
//! |---|---|---|---|---|
//! | 1.8.9 | `custom_payload` `MC\|BEdit` / `MC\|BSign` with the held stack | 50 | 255 | 16 |
//! | 1.12.2 | as 1.8.9 | 50 | 255 | 16 |
//! | 1.16.5 | `edit_book` (stack, signing flag, slot) | 100 | 1023 | 15 |
//! | 26.x | `edit_book` (slot, pages, optional title) | 100 | 1024 | 15 |
//!
//! - Characters the screens do not let the player type are dropped (as on signs, see
//!   [`crate::sign::allowed_char`]; pages keep line breaks), and a page or title stops at the
//!   screen's length limit (typing past it does nothing). The title is sent trimmed and must
//!   not be blank (the Finalize button is disabled).
//! - Trailing empty pages are dropped: 1.8.9 / 1.12.2 keep at least one page, 1.16.5 and
//!   26.x's Done drop them all; 26.x's Sign sends the pages as they are.
//! - The slot: 1.16.5 and 26.x send the hotbar slot of the main hand or 40 for the off hand;
//!   1.8.9 / 1.12.2 send the stack only (1.8.9 has no off hand; the 1.12.2 server reads the
//!   main hand).
//! - The held stack changes on the client at once (the screen edits the very stack in the
//!   hand): 1.8.9 / 1.12.2 / 1.16.5 put `pages` (and on signing `author` and `title`) into its
//!   NBT; 1.8.9's signing also turns it into a written book with JSON pages; 26.x's Done sets
//!   its `writable_book_content` (signing leaves it to the server). The server's slot update
//!   follows.
//!
//! # Not modelled
//!
//! - The screen's font-based limits (the page's wrapped height, 14 lines on 26.x): keep pages
//!   to what fits a vanilla page.
//! - The screen itself: vanilla sends nothing when nothing was typed (1.8.9 – 1.16.5) and the
//!   player cannot move while it is open; a behaviour that wants to look vanilla uses the book
//!   first and stands still for a moment.
//! - The NBT key order of the stack ghast sends (vanilla's compound is a hash map; the
//!   server does not care).

use ghast_inventory::Stack;

/// The book's edit as written to the server ([`crate::common::Outbound::EditBook`]).
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct BookEdit {
    /// 1.16.5+: the hotbar slot of the main hand (0 – 8) or 40 for the off hand.
    pub slot: i32,
    /// The pages as sent (filtered, cut, trailing empty pages dropped where vanilla does).
    pub pages: Vec<String>,
    /// The title when signing (trimmed).
    pub title: Option<String>,
    /// 1.8.9 – 1.16.5: the stack the packet carries (the held book after the edit).
    pub stack: Option<Stack>,
}

/// Why [`crate::TickContext::edit_book`] sent nothing.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BookError {
    /// The hand does not hold a book and quill.
    NoBook,
    /// More pages than the version's book holds.
    TooManyPages,
    /// The title is blank (vanilla's Finalize button is disabled).
    EmptyTitle,
    /// 1.8.9 has no off hand.
    OffHand,
}

impl std::fmt::Display for BookError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            BookError::NoBook => "the hand holds no book and quill",
            BookError::TooManyPages => "too many pages for this version",
            BookError::EmptyTitle => "the title is blank",
            BookError::OffHand => "this version has no off hand",
        })
    }
}

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

/// The book rules of a version ([`crate::version::Capabilities::book`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum BookRules {
    /// 1.8.9: `MC|BEdit` / `MC|BSign` with the stack; signing turns the held stack into a
    /// written book with JSON pages.
    Legacy18,
    /// 1.12.2: `MC|BEdit` / `MC|BSign` with the stack (plain pages, still a book and quill
    /// on the client).
    Legacy112,
    /// 1.16.5: `edit_book` with the stack, the signing flag and the slot.
    Stack116,
    /// 1.20.5+: `edit_book` with the slot, the pages and the optional title.
    Pages,
}

impl BookRules {
    /// Most pages (`appendNewPage` / `appendPageToBook`).
    #[must_use]
    pub const fn max_pages(self) -> usize {
        match self {
            BookRules::Legacy18 | BookRules::Legacy112 => 50,
            BookRules::Stack116 | BookRules::Pages => 100,
        }
    }

    /// Longest page in UTF-16 units (1.8 / 1.12 `length() < 256`, 1.16.5 `length() < 1024`,
    /// 26.x `setCharacterLimit(1024)`).
    #[must_use]
    pub const fn max_page_len(self) -> usize {
        match self {
            BookRules::Legacy18 | BookRules::Legacy112 => 255,
            BookRules::Stack116 => 1023,
            BookRules::Pages => 1024,
        }
    }

    /// Longest title (1.8 / 1.12 `length() < 16` before a character is added, 1.16.5
    /// `length() < 16` after, 26.x `setMaxLength(15)`).
    #[must_use]
    pub const fn max_title_len(self) -> usize {
        match self {
            BookRules::Legacy18 | BookRules::Legacy112 => 16,
            BookRules::Stack116 | BookRules::Pages => 15,
        }
    }
}

/// A page as the screen lets it be typed (line breaks kept), cut at `max` UTF-16 units.
#[must_use]
pub(crate) fn page(s: &str, max: usize) -> String {
    let p: String = s
        .chars()
        .filter(|&c| c == '\n' || crate::sign::allowed_char(c))
        .collect();
    crate::version::truncate_utf16(&p, max).to_owned()
}

/// The pages and title to send under `rules` (`signing`: the Sign path).
pub(crate) fn prepare(
    rules: BookRules,
    pages: &[&str],
    title: Option<&str>,
) -> Result<(Vec<String>, Option<String>), BookError> {
    if pages.len() > rules.max_pages() {
        return Err(BookError::TooManyPages);
    }
    let mut p: Vec<String> = pages
        .iter()
        .map(|s| page(s, rules.max_page_len()))
        .collect();
    let title = match title {
        Some(t) => {
            let t: String = t
                .chars()
                .filter(|&c| crate::sign::allowed_char(c))
                .collect();
            let t = crate::version::truncate_utf16(&t, rules.max_title_len()).trim();
            if t.is_empty() {
                return Err(BookError::EmptyTitle);
            }
            Some(t.to_owned())
        }
        None => None,
    };
    match rules {
        BookRules::Legacy18 | BookRules::Legacy112 => {
            // the screen starts with one empty page and keeps one
            if p.is_empty() {
                p.push(String::new());
            }
            while p.len() > 1 && p.last().is_some_and(String::is_empty) {
                p.pop();
            }
        }
        // 26.x's Sign sends the edit screen's pages as they are
        BookRules::Pages if title.is_some() => {}
        BookRules::Stack116 | BookRules::Pages => {
            while p.last().is_some_and(String::is_empty) {
                p.pop();
            }
        }
    }
    Ok((p, title))
}

/// The NBT stack the legacy screens send (and leave in the hand): `pages` (1.16.5: only when
/// there are pages), and when signing `author` and `title`; 1.8.9's signing writes the pages
/// as JSON and the item becomes `written_book`.
pub(crate) fn nbt_stack(
    rules: BookRules,
    held: &Stack,
    pages: &[String],
    title: Option<&str>,
    author: &str,
    written_book: i32,
) -> Stack {
    use ghast_protocol::nbt::{Compound, List, NamedTag, RawNbt, Tag, tag};
    let mut root = held
        .nbt()
        .and_then(|n| n.parse().ok().flatten())
        .and_then(|t| match t.tag {
            Tag::Compound(c) => Some(c),
            _ => None,
        })
        .unwrap_or_default();
    let put = |c: &mut Compound, k: &str, v: Tag| {
        if let Some(e) = c.0.iter_mut().find(|(n, _)| n == k) {
            e.1 = v;
        } else {
            c.0.push((k.to_owned(), v));
        }
    };
    let json = rules == BookRules::Legacy18 && title.is_some();
    if rules != BookRules::Stack116 || !pages.is_empty() {
        let items = pages
            .iter()
            .map(|p| {
                Tag::String(if json {
                    crate::sign::gson_string(p, usize::MAX)
                } else {
                    p.clone()
                })
            })
            .collect();
        put(
            &mut root,
            "pages",
            Tag::List(List {
                elem_type: tag::STRING,
                items,
            }),
        );
    }
    if let Some(t) = title {
        put(&mut root, "author", Tag::String(author.to_owned()));
        put(&mut root, "title", Tag::String(t.to_owned()));
    }
    let nbt = RawNbt::from_named(&NamedTag {
        name: String::new(),
        tag: Tag::Compound(root),
    })
    .ok();
    Stack::new(
        if json { written_book } else { held.id() },
        held.count(),
        held.damage(),
    )
    .with_nbt(nbt)
}

/// 26.x Done: the held stack with its `writable_book_content` set to `pages`
/// (`updateLocalCopy`; each page a `Filterable.passThrough`).
#[cfg(ghast_modern)]
pub(crate) fn modern_stack(held: &Stack, pages: &[String], protocol: i32) -> Option<Stack> {
    use bytes::BufMut;
    use ghast_protocol::types::slot::v775::ComponentPatch;
    // the component type's id per protocol (26.3 inserted two types before it)
    let ty = if protocol >= 777 { 56 } else { 54 };
    let mut v = bytes::BytesMut::new();
    let varint = |v: &mut bytes::BytesMut, mut n: u32| loop {
        if n < 0x80 {
            v.put_u8(n as u8);
            break;
        }
        v.put_u8((n as u8 & 0x7f) | 0x80);
        n >>= 7;
    };
    varint(&mut v, u32::try_from(pages.len()).ok()?);
    for p in pages {
        varint(&mut v, u32::try_from(p.len()).ok()?);
        v.put_slice(p.as_bytes());
        v.put_u8(0); // no filtered text
    }
    let old = held.components();
    let mut added: Vec<(i32, bytes::Bytes)> = old
        .map(|c| c.iter().filter(|(t, _)| *t != ty).collect())
        .unwrap_or_default();
    added.push((ty, v.freeze()));
    let removed: Vec<i32> = old
        .map(|c| c.removed().filter(|t| *t != ty).collect())
        .unwrap_or_default();
    let parts: Vec<(i32, &[u8])> = added.iter().map(|(t, b)| (*t, &b[..])).collect();
    let patch = match protocol {
        775 => ComponentPatch::from_parts(&parts, &removed),
        776 => ComponentPatch::from_parts_776(&parts, &removed),
        _ => ComponentPatch::from_parts_777(&parts, &removed),
    };
    Some(
        held.clone()
            .with_data(ghast_inventory::ItemData::Components(Box::new(patch))),
    )
}

/// `(book and quill, written book)` item ids of a data set.
pub(crate) fn book_items(data: crate::version::DataSet) -> Option<(i32, i32)> {
    #[allow(unused_imports)]
    use crate::version::DataSet;
    #[allow(unused_macros)]
    macro_rules! by_name {
        ($m:path) => {{
            use $m as d;
            Some((
                i32::from(d::Item::from_name("writable_book")?.id()),
                i32::from(d::Item::from_name("written_book")?.id()),
            ))
        }};
    }
    match data {
        #[cfg(feature = "v1_8")]
        DataSet::V1_8 => Some((386, 387)),
        #[cfg(feature = "v1_12_2")]
        DataSet::V1_12 => Some((386, 387)),
        #[cfg(feature = "v1_16_5")]
        DataSet::V1_16_5 => by_name!(ghast_data::v1_16_5),
        #[cfg(feature = "v26_1")]
        DataSet::V26_1 => by_name!(ghast_data::v26_1),
        #[cfg(feature = "v26_2")]
        DataSet::V26_2 => by_name!(ghast_data::v26_2),
        #[cfg(feature = "v26_3")]
        DataSet::V26_3 => by_name!(ghast_data::v26_3),
        #[allow(unreachable_patterns)]
        _ => None,
    }
}

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

    #[test]
    fn pages_and_titles() {
        let (p, t) = prepare(BookRules::Legacy18, &["a§b\nc", "", ""], Some("  Ti§tle  ")).unwrap();
        assert_eq!(p, ["ab\nc"]);
        assert_eq!(t.as_deref(), Some("Title"));
        let (p, _) = prepare(BookRules::Legacy112, &[], None).unwrap();
        assert_eq!(p, [""]);
        let (p, _) = prepare(BookRules::Stack116, &["", ""], None).unwrap();
        assert!(p.is_empty());
        // 26.x's Sign keeps trailing empty pages, its Done drops them
        let (p, _) = prepare(BookRules::Pages, &["x", ""], Some("t")).unwrap();
        assert_eq!(p, ["x", ""]);
        let (p, _) = prepare(BookRules::Pages, &["x", ""], None).unwrap();
        assert_eq!(p, ["x"]);
        assert_eq!(
            prepare(BookRules::Pages, &["x"], Some("  ")),
            Err(BookError::EmptyTitle)
        );
        let many = vec!["p"; 51];
        assert_eq!(
            prepare(BookRules::Legacy18, &many, None),
            Err(BookError::TooManyPages)
        );
        assert!(prepare(BookRules::Stack116, &many, None).is_ok());
        let long = "y".repeat(2000);
        let (p, t) = prepare(BookRules::Stack116, &[&long], Some(&long)).unwrap();
        assert_eq!((p[0].len(), t.unwrap().len()), (1023, 15));
        let (p, t) = prepare(BookRules::Legacy112, &[&long], Some(&long)).unwrap();
        assert_eq!((p[0].len(), t.unwrap().len()), (255, 16));
        let (p, _) = prepare(BookRules::Pages, &[&long], None).unwrap();
        assert_eq!(p[0].len(), 1024);
    }
}