ghast-inventory 0.5.4

Inventory and container windows for the ghast Minecraft Java Edition client library: vanilla client-side click prediction, the window confirm protocol, hashed 26.1 clicks and lazy NBT / data-component item stacks (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3)
Documentation
//! The legacy (1.8.9 – 1.16.5) special screens: villager trades, the 1.16.5 workstations, anvil
//! names and costs, menu buttons, mounts, tags, experience and the creative flag.

use super::*;

impl Inventory {
    /// 1.8 – 1.16.5 villager screen: the server's offers for window `window_id` (vanilla
    /// keeps them only while that window's trading screen is open). The output is not looked up
    /// again until the next slot change, like vanilla. [`Inventory::apply_v1_8`] /
    /// [`Inventory::apply_v1_12_2`] (`MC|TrList`) and [`Inventory::apply_v1_16_5`]
    /// (`trade_list`) call this.
    pub fn on_trade_offers(&mut self, window_id: i32, offers: Vec<crate::merchant::TradeOffer>) {
        if self.open_id() == window_id
            && let Some(mer) = self.m.merchant.as_deref_mut()
        {
            mer.offers = Some(offers);
        }
    }

    /// 1.16.5 `open_window` by menu type id ([`WindowKind::from_v1_16_5`]); also remembers
    /// which recipes a furnace, blast furnace or smoker smelts (its shift-click reads them).
    /// [`Inventory::apply_v1_16_5`] calls this.
    pub fn on_open_window_v1_16_5(&mut self, id: i32, menu_type: i32, title: ByteString) {
        self.on_open_window(id, WindowKind::from_v1_16_5(menu_type), title);
        if self.open_id() == id {
            self.m.furnace = match menu_type {
                9 => 1,
                21 => 2,
                _ => 0,
            };
        }
    }

    /// A workstation's `window_items`: vanilla's `updateSlotStacks` sets the slots in order
    /// (`Slot.setStack`, which notifies the menu twice for an input), so each input change sees
    /// the slots before it new and the ones after it old.
    pub(super) fn station_window_items(&mut self, before: Vec<Option<Stack>>) {
        let Some(st) = self.m.station.as_deref() else {
            return;
        };
        let inputs: Vec<bool> = (0..before.len()).map(|k| st.is_input(k)).collect();
        let new = std::mem::replace(&mut self.m.container, before);
        let lay = self.layout();
        let mut sim = Sim {
            v: self.version,
            lay,
            m: &mut self.m,
            book: &self.book,
            binding_curse: None,
            tags: self.tags16.as_deref(),
        };
        for (k, s) in new.into_iter().enumerate() {
            if k >= sim.m.container.len() {
                break;
            }
            sim.m.container[k] = s;
            if inputs[k] {
                sim.station_touched(Loc::Container(k));
                sim.station_touched(Loc::Container(k));
            }
        }
        self.m.container_result_known = true;
    }

    /// A server `set_slot` of workstation container slot `k` (`None`: all of them): an input
    /// change runs the menu's update; the result slot keeps what the packet set.
    pub(super) fn station_inbound(&mut self, k: Option<usize>) {
        let Some(st) = self.m.station.as_deref() else {
            return;
        };
        let out = st.output();
        if k.is_some_and(|k| !st.is_input(k)) {
            // the server's result
            self.m.container_result_known = true;
            return;
        }
        let keep = self.m.container.get(out).cloned();
        let lay = self.layout();
        let mut sim = Sim {
            v: self.version,
            lay,
            m: &mut self.m,
            book: &self.book,
            binding_curse: None,
            tags: self.tags16.as_deref(),
        };
        // `Slot.setStack`: twice
        sim.station_touched(Loc::Container(0));
        sim.station_touched(Loc::Container(0));
        if k.is_none()
            && let (Some(slot), Some(keep)) = (self.m.container.get_mut(out), keep)
        {
            *slot = keep;
            self.m.container_result_known = true;
        }
    }

    /// The packets the open screen sent by itself since the last call, to write before
    /// anything else this tick (the 1.16.5 anvil screen's `rename_item` when its first input
    /// changed, also through a server packet). A click's own packet comes after these.
    pub fn take_screen_packets(&mut self) -> Vec<Outgoing> {
        std::mem::take(&mut self.m.screen_out)
    }

    /// The player's experience level (the 1.16.5 anvil's cost check; also the 26.x anvil).
    /// Set from the `experience` packet ([`Inventory::apply_v1_16_5`] does).
    pub fn set_experience_level(&mut self, level: i32) {
        self.m.xp_level = level;
        #[cfg(modern)]
        if self.version.is_modern() {
            self.set_experience_level_modern(level);
        }
    }

    /// The experience level as the client holds it (taking an anvil result lowers it).
    #[must_use]
    pub fn experience_level(&self) -> i32 {
        self.m.xp_level
    }

    /// Creative mode (the 1.16.5 anvil: no level check, every enchantment fits; also 26.x).
    /// Set from the `abilities` packet ([`Inventory::apply_v1_16_5`] does).
    pub fn set_creative(&mut self, creative: bool) {
        self.m.creative = creative;
        #[cfg(modern)]
        if self.version.is_modern() {
            self.set_creative_modern(creative);
        }
    }

    /// The 1.16.5 anvil's level cost as the client holds it (`None`: no 1.16.5 anvil open).
    #[must_use]
    pub fn anvil_cost(&self) -> Option<i32> {
        match self.m.station.as_deref() {
            Some(crate::station::Station::Anvil(a)) => Some(a.cost),
            _ => None,
        }
    }

    /// Anvil: types `name` into the name field like the screen (1.16.5: `onRenamed`; 26.x: as
    /// [`Inventory::anvil_rename_modern`]). Returns the `rename_item` / `MC|ItemName` to send
    /// (`Ok(None)`: nothing is sent: no first input, or an empty name on 1.16.5). The field
    /// takes at most 35 characters (1.8.9: 30), without `§` and control characters. Typing exactly the item's translated
    /// name is not recognised (ghast has no translations): it renames.
    ///
    /// # Errors
    /// [`ClickError::NoScreen`] when no anvil is open; [`ClickError::InvalidSlot`] for a name
    /// the field does not take; [`ClickError::Unpredictable`] when the result cannot be
    /// computed (an item name ghast cannot read).
    pub fn anvil_rename(&mut self, name: &str) -> Result<Option<Outgoing>, ClickError> {
        #[cfg(modern)]
        if self.version.is_modern() {
            return self.anvil_rename_modern(name);
        }
        if !matches!(
            self.m.station.as_deref(),
            Some(crate::station::Station::Anvil(_))
        ) {
            return Err(ClickError::NoScreen);
        }
        let field = if self.version == Version::V1_8 {
            30
        } else {
            35
        };
        if name.chars().count() > field
            || name
                .chars()
                .any(|c| c == '\u{a7}' || c < ' ' || c == '\u{7f}')
        {
            return Err(ClickError::InvalidSlot);
        }
        // the field is editable while the screen last saw an item in slot 0
        let editable = matches!(
            self.m.station.as_deref(),
            Some(crate::station::Station::Anvil(a)) if a.tracked.is_some()
        );
        // 1.16.5 sends nothing for an empty field; 1.12 sends every change
        if (name.is_empty() && self.version == Version::V1_16_5) || !editable {
            return Ok(None);
        }
        let lay = self.layout();
        let mut m = self.m.clone();
        let mut sim = Sim {
            v: self.version,
            lay,
            m: &mut m,
            book: &self.book,
            binding_curse: None,
            tags: self.tags16.as_deref(),
        };
        // onRenamed: the item's own (custom) name typed again keeps it
        sim.anvil_set_name(name.to_owned());
        if !m.container_result_known {
            return Err(ClickError::Unpredictable);
        }
        let out = std::mem::take(&mut m.screen_out);
        self.m = m;
        self.events.window_changed = true;
        Ok(out.into_iter().last())
    }

    /// 1.16.5 menu buttons the client acts on itself (stonecutter recipe `index`, like its
    /// screen; [`Outgoing::ButtonClick`] is the packet to send). `Ok(None)`: the menu does not
    /// take that button (nothing to send).
    ///
    /// # Errors
    /// [`ClickError::NoScreen`] when no such menu is open.
    pub fn click_button(&mut self, index: i32) -> Result<Option<Outgoing>, ClickError> {
        use crate::station::Station;
        let id = self.open_id();
        let lay = self.layout();
        // the lectern screen only sends its buttons (page back 1, forward 2, take book 3,
        // page 100 + n); the server answers
        if matches!(&self.screen, ScreenState::Window(w) if w.kind == WindowKind::Lectern)
            && self.version == Version::V1_16_5
        {
            return Ok(
                matches!(index, 1..=3 | 100..).then_some(Outgoing::ButtonClick {
                    window_id: id,
                    button: index,
                }),
            );
        }
        if let Some(Station::Loom { .. }) = self.m.station.as_deref() {
            let before = self.m.container.clone();
            let mut sim = Sim {
                v: self.version,
                lay,
                m: &mut self.m,
                book: &self.book,
                binding_curse: None,
                tags: self.tags16.as_deref(),
            };
            let ok = sim.loom_button(index);
            if self.m.container != before {
                self.events.window_changed = true;
            }
            return Ok(ok.then_some(Outgoing::ButtonClick {
                window_id: id,
                button: index,
            }));
        }
        let Some(Station::Stonecutter {
            recipes, selected, ..
        }) = self.m.station.as_deref_mut()
        else {
            return Err(ClickError::NoScreen);
        };
        if usize::try_from(index).map_or(true, |k| k >= recipes.len()) {
            return Ok(None);
        }
        *selected = index;
        let before = self.m.container.clone();
        let mut sim = Sim {
            v: self.version,
            lay,
            m: &mut self.m,
            book: &self.book,
            binding_curse: None,
            tags: self.tags16.as_deref(),
        };
        sim.stonecutter_populate();
        if self.m.container != before {
            self.events.window_changed = true;
        }
        Ok(Some(Outgoing::ButtonClick {
            window_id: id,
            button: index,
        }))
    }

    /// 1.8 – 1.16.5 mount screen (a `Horse` window): what its saddle and armor slots take, read
    /// off the entity like vanilla's screen does (`None`: unknown, the default after the window
    /// opens; clicks that would need them are refused). Vanilla: 1.8 `open_window`
    /// `EntityHorse` names the entity; saddle always, horse armor for horse type 0. 1.12: saddle
    /// for all but llamas, horse armor for horses, carpets for llamas. 1.16.5
    /// (`open_horse_window`): saddle for a tame adult (not a llama), horse armor for horses,
    /// carpets for llamas and trader llamas.
    pub fn set_mount_rules(&mut self, rules: Option<crate::mount::MountRules>) {
        if matches!(&self.screen, ScreenState::Window(w) if matches!(w.kind, WindowKind::Horse { .. }))
        {
            self.m.mount = rules;
        }
    }

    /// The open mount screen's rules ([`Inventory::set_mount_rules`]).
    #[must_use]
    pub fn mount_rules(&self) -> Option<crate::mount::MountRules> {
        self.m.mount
    }

    /// 1.8 / 1.12 `MC|TrList` custom payload data (window id, then the offers).
    #[cfg(any(feature = "v1_8", feature = "v1_12"))]
    pub fn on_trade_list_legacy(&mut self, data: &bytes::Bytes) {
        if let Some((w, offers)) = crate::merchant::parse_legacy(data) {
            self.on_trade_offers(w, offers);
        }
    }

    /// 1.16.5 `tags`: the item tags the beacon, furnace and llama slots read (the client uses
    /// the server's; until they arrive those rules are refused as unpredictable). [`Inventory::apply_v1_16_5`]
    /// calls this.
    #[cfg(feature = "v1_16_5")]
    pub fn on_tags_v1_16_5(&mut self, p: &ghast_protocol::v1_16_5::play::clientbound::Tags) {
        self.tags16 = Some(std::sync::Arc::new(
            crate::tags16::ItemTags16::from_item_tags(
                self.version,
                p.item_tags.iter().map(|t| (&*t.tag_name, &t.entries[..])),
            ),
        ));
    }

    /// 1.16.5 `trade_list`.
    #[cfg(feature = "v1_16_5")]
    pub fn on_trade_list_v1_16_5(
        &mut self,
        p: &ghast_protocol::v1_16_5::play::clientbound::TradeList,
    ) {
        self.on_trade_offers(p.window_id, crate::merchant::from_v1_16_5(p));
    }

    /// The open villager screen's offers as the client holds them (uses counted on the client),
    /// `None` when no villager screen is open or the server has not sent them (1.8 – 1.16.5).
    #[must_use]
    pub fn trade_offers(&self) -> Option<&[crate::merchant::TradeOffer]> {
        self.m.merchant.as_ref()?.offers.as_deref()
    }

    /// Villager screen: picks offer `index` like the screen's arrows / trade buttons and
    /// returns the packet to send (1.8 / 1.12 `MC|TrSel`, 1.16.5 / 26.1 `select_trade`).
    /// 1.8 / 1.12: the output is looked up again for that offer (0 = the first offer that
    /// matches). 1.16.5: also the payments go back into the inventory and the offer's own
    /// items come out of it (`switchTo`), as the screen does. 26.1: as
    /// [`Inventory::select_trade_modern`].
    ///
    /// # Errors
    /// [`ClickError::NoScreen`] when no villager screen is open; [`ClickError::InvalidSlot`]
    /// when the offers are not known or `index` is not one of them.
    pub fn select_trade(&mut self, index: i32) -> Result<Outgoing, ClickError> {
        #[cfg(modern)]
        if self.version.is_modern() {
            return self.select_trade_modern(index);
        }
        let v = self.version;
        let Some(mer) = self.m.merchant.as_deref_mut() else {
            return Err(ClickError::NoScreen);
        };
        let n = mer.offers.as_ref().map_or(0, Vec::len);
        if usize::try_from(index).map_or(true, |k| k >= n) {
            return Err(ClickError::InvalidSlot);
        }
        mer.index = index;
        crate::merchant::update(v, &mut self.m);
        if v == Version::V1_16_5 {
            let lay = self.layout();
            let before = self.m.clone();
            let mut sim = Sim {
                v,
                lay,
                m: &mut self.m,
                book: &self.book,
                binding_curse: None,
                tags: self.tags16.as_deref(),
            };
            sim.switch_trade(index as usize);
            if self.m.container != before.container {
                self.events.window_changed = true;
            }
            if self.m.player != before.player {
                self.events.player_changed = true;
            }
        }
        Ok(Outgoing::SelectTrade(index))
    }
}