ghast-inventory 0.5.6

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
//! Read access to the inventory: cursor, player slots, hands, the open window and its slots,
//! searches, and whether a click may be sent now.

use super::*;

impl Inventory {
    // ------------------------------------------------------------------ reading

    /// The cursor ("carried") stack.
    #[must_use]
    pub fn cursor(&self) -> Option<&Stack> {
        self.m.cursor.as_ref()
    }

    /// `PlayerInventory` slot by vanilla index: 0..=8 hotbar, 9..=35 main, 36..=39 armor
    /// (feet, legs, chest, head), 40 offhand (1.12 / 1.16.5).
    #[must_use]
    pub fn player(&self, index: usize) -> Option<&Stack> {
        self.m.player.get(index)?.as_ref()
    }

    /// Hotbar slot 0..=8.
    #[must_use]
    pub fn hotbar(&self, k: usize) -> Option<&Stack> {
        if k < 9 { self.player(k) } else { None }
    }

    /// The selected hotbar slot.
    #[must_use]
    pub fn selected(&self) -> u8 {
        self.m.selected
    }

    /// How many times the server wrote the selected hotbar slot (`set_slot`, `window_items`;
    /// 1.8 – 1.16.5), whether the stack changed or not, wrapping. A 1.8 client's item use ends
    /// when the held stack is replaced, even by an equal one.
    #[must_use]
    pub fn held_writes(&self) -> u16 {
        self.hotbar_writes[usize::from(self.m.selected.min(8))]
    }

    /// [`Inventory::held_writes`] for the off-hand slot (1.12 / 1.16.5).
    #[must_use]
    pub fn offhand_writes(&self) -> u16 {
        self.hotbar_writes[9]
    }

    /// Whether the player slots or the selected hotbar slot may have changed since the last
    /// call (and since the inventory was made); clears the flag. Conservative: any write sets
    /// it, changed or not. For a caller that keeps something derived from the hands (or any
    /// player slot) and re-reads only when this is `true`; there must be one such caller.
    #[inline]
    pub fn take_player_touched(&mut self) -> bool {
        self.m.player.take_touched()
    }

    /// The stack in the selected hotbar slot.
    #[must_use]
    pub fn held(&self) -> Option<&Stack> {
        self.player(usize::from(self.m.selected))
    }

    /// Armor piece: 0 head, 1 chest, 2 legs, 3 feet.
    #[must_use]
    pub fn armor(&self, a: usize) -> Option<&Stack> {
        if a < 4 { self.player(39 - a) } else { None }
    }

    /// The offhand stack (1.12 / 1.16.5).
    #[must_use]
    pub fn offhand(&self) -> Option<&Stack> {
        self.player(40)
    }

    /// The open container window, if any.
    #[must_use]
    pub fn window(&self) -> Option<&Window> {
        match &self.screen {
            ScreenState::Window(w) => Some(w),
            _ => None,
        }
    }

    /// Whether a GUI is open (a container window or the player inventory).
    #[must_use]
    pub fn gui_open(&self) -> bool {
        self.screen != ScreenState::None
    }

    /// Whether the player inventory GUI is open (no container window).
    #[must_use]
    pub fn inventory_open(&self) -> bool {
        self.screen == ScreenState::Inventory
    }

    pub(super) fn layout(&self) -> Layout {
        let screen = match &self.screen {
            ScreenState::Window(w) => Screen::Container(w.kind),
            _ => Screen::Player,
        };
        Layout::new(self.version, screen)
    }

    /// Number of slots of the current screen (window 0 when no container is open: 45 on 1.8,
    /// 46 on 1.12 / 1.16.5).
    #[must_use]
    pub fn slot_count(&self) -> usize {
        self.layout().len
    }

    /// Container slots of the open window (before the player's 36), 0 for window 0.
    #[must_use]
    pub fn container_len(&self) -> usize {
        self.layout().n
    }

    /// Slot `i` of the current screen (window 0 layout when no container is open).
    #[must_use]
    pub fn slot(&self, i: usize) -> Option<&Stack> {
        let l = self.layout().loc(i)?;
        self.m.at(l).as_ref()
    }

    /// Slot `i` of window 0 (`PlayerScreenHandler` numbering), whatever is open.
    #[must_use]
    pub fn window0_slot(&self, i: usize) -> Option<&Stack> {
        let l = Layout::new(self.version, Screen::Player).loc(i)?;
        self.m.at(l).as_ref()
    }

    /// Kind of slot `i` of the current screen.
    #[must_use]
    pub fn slot_kind(&self, i: usize) -> Option<SlotKind> {
        let lay = self.layout();
        (i < lay.len).then(|| lay.kind(i))
    }

    /// The current screen's slot that shows `PlayerInventory` index `k` (e.g. hotbar 0 is
    /// window 0 slot 36 and slot 54 of a 3-row chest).
    #[must_use]
    pub fn slot_of_player(&self, k: usize) -> Option<i16> {
        self.layout().slot_of_player(k).map(|i| i as i16)
    }

    /// First slot of the current screen whose stack matches.
    pub fn find(&self, mut pred: impl FnMut(&Stack) -> bool) -> Option<i16> {
        let lay = self.layout();
        (0..lay.len)
            .find(|&i| {
                lay.loc(i)
                    .and_then(|l| self.m.at(l).as_ref())
                    .is_some_and(&mut pred)
            })
            .map(|i| i as i16)
    }

    /// Total count of matching stacks in the player inventory (hotbar, main, armor, offhand).
    pub fn count(&self, mut pred: impl FnMut(&Stack) -> bool) -> i32 {
        self.m
            .player
            .iter()
            .flatten()
            .filter(|s| pred(s))
            .map(|s| s.count)
            .sum()
    }

    /// Whether the current screen's crafting result (window 0 slot 0, crafting table slot 0)
    /// is what the vanilla client shows. The 1.8 client computes results from its recipe book
    /// (ghast does not) and the server never sends them except in `window_items`; on 1.16.5 the
    /// server sends each new result as `set_slot`. The 1.12 client never computes results: the
    /// slot always holds what the server last sent (taking a result whose grid changed since is
    /// refused, its remainders depend on the recipes). While unknown, result clicks are
    /// [`ClickError::Unpredictable`]. 1.8 – 1.16.5 anvil and grindstone: whether ghast could
    /// compute the output like the client (false for inputs it cannot read, until the server's
    /// `set_slot`).
    #[must_use]
    pub fn result_known(&self) -> bool {
        match &self.screen {
            ScreenState::Window(w) if w.kind == WindowKind::Crafting => {
                self.m.container_result_known
            }
            // 1.8 – 1.16.5 anvil: the output the client computed after an input change
            ScreenState::Window(w)
                if matches!(w.kind, WindowKind::Anvil | WindowKind::Grindstone)
                    && !self.version.is_modern() =>
            {
                self.m.container_result_known
            }
            ScreenState::Window(_) => true,
            _ => self.m.craft_result_known,
        }
    }

    /// Whether the current screen's crafting result belongs to the grid as it is now. 1.12: the
    /// server sent it and the grid has not changed since (a click that changes the grid leaves
    /// the old result in the slot until the server's `set_slot`; taking such a stale result is
    /// [`ClickError::Unpredictable`]). 1.8 / 1.16.5: the same as
    /// [`result_known`](Inventory::result_known).
    #[must_use]
    pub fn result_current(&self) -> bool {
        if self.version != Version::V1_12 {
            return self.result_known();
        }
        match &self.screen {
            ScreenState::Window(w) if w.kind == WindowKind::Crafting => self.m.container_fresh,
            ScreenState::Window(_) => true,
            _ => self.m.craft_fresh,
        }
    }

    /// Whether a click waits for its confirm.
    #[must_use]
    pub fn pending(&self) -> bool {
        self.pending.is_some()
    }

    /// Whether the inventory waits for the server's resync after a rejected click.
    #[must_use]
    pub fn resyncing(&self) -> bool {
        self.resync.is_some()
    }

    /// Whether [`click`](Inventory::click) would currently refuse for a reason other than the
    /// click itself.
    pub fn can_click(&self) -> Result<(), ClickError> {
        if self.pending.is_some() {
            return Err(ClickError::Pending);
        }
        if self.resync.is_some() {
            return Err(ClickError::Resyncing);
        }
        if self.flags.clicked || self.flags.opened {
            return Err(ClickError::SameTick);
        }
        if self.screen == ScreenState::None {
            return Err(ClickError::NoScreen);
        }
        Ok(())
    }
}