Skip to main content

ghast_inventory/inventory/
creative_legacy.rs

1//! The creative inventory screen of 1.8.9 (window 0 opened in creative mode), as the real
2//! client drives it: `CreativeInventoryScreen.onMouseClick`, its `CreativeInventoryListener` on
3//! window 0 (every slot that differs from window 0's tracked stacks is sent as a
4//! `creative_inventory_action` when the handler broadcasts), the item tabs' own cursor rules and
5//! the pick block key. Proven against the oracle's `clicks_creative_seed1.jsonl.gz`.
6//!
7//! A child module of `inventory` (it reads the inventory's private state).
8
9use super::{ClickError, CreativePacket, Inventory, Outgoing, ScreenState};
10use crate::rules::Version;
11use crate::sim::{Layout, OUTSIDE, Screen, Sim};
12use crate::stack::Stack;
13
14/// The page the creative inventory screen shows (1.8.9 – 1.16.5).
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16#[non_exhaustive]
17pub enum CreativeTab {
18    /// The survival inventory tab: window 0's slots (5 ..) and the delete slot
19    /// ([`Inventory::creative_delete_slot`]). Clicks use window 0's slot numbers.
20    Inventory,
21    /// Any item tab (building blocks, tools, …): the menu (slots 0..45, clicked with
22    /// [`Inventory::creative_menu_click`]) and the hotbar row (slots 45..54).
23    Items,
24}
25
26/// The legacy creative screen's state; allocated at its first open.
27#[derive(Debug, Clone)]
28pub(crate) struct CreativeLegacy {
29    /// Window 0's tracked stacks (`ScreenHandler.trackedStacks`: what its last broadcast saw).
30    tracked: Vec<Option<Stack>>,
31    /// The screen is open.
32    pub(super) open: bool,
33    /// The selected tab (a static of the screen class: kept between openings).
34    tab: CreativeTab,
35    /// Packets the screen sent outside a click (the broadcast after opening).
36    echo: Vec<CreativePacket>,
37}
38
39impl CreativeLegacy {
40    fn new(len: usize) -> CreativeLegacy {
41        CreativeLegacy {
42            tracked: vec![None; len],
43            open: false,
44            // `selectedTab` starts at the building blocks tab
45            tab: CreativeTab::Items,
46            echo: Vec::new(),
47        }
48    }
49
50    /// A new player entity: a new window 0 (nothing tracked); the tab is a static and stays.
51    pub(crate) fn respawned(mut self: Box<Self>) -> Box<Self> {
52        self.tracked.iter_mut().for_each(|s| *s = None);
53        self.open = false;
54        self.echo.clear();
55        self
56    }
57}
58
59/// A stack the screen drops (`dropCreativeStack`: slot -1), after the arm swing 1.16.5's
60/// `PlayerEntity.dropItem` sends on the client for a non-empty stack.
61fn drop_into(v: Version, out: &mut Vec<CreativePacket>, item: Option<Stack>) {
62    if v == Version::V1_16_5 && item.as_ref().is_some_and(|s| s.count > 0) {
63        out.push(CreativePacket::Swing);
64    }
65    out.push(CreativePacket::SetSlot { slot: -1, item });
66}
67
68/// `ItemStack.equalsAll` (1.8): count, item, damage and NBT.
69fn equals_all(a: Option<&Stack>, b: Option<&Stack>) -> bool {
70    crate::stack::stacks_equal(a, b)
71}
72
73impl Inventory {
74    /// Whether the open screen is the legacy creative inventory screen, and its tab.
75    #[must_use]
76    pub fn creative_screen_legacy(&self) -> Option<CreativeTab> {
77        self.creative16.as_ref().filter(|c| c.open).map(|c| c.tab)
78    }
79
80    /// The slot number of the creative inventory tab's delete slot (window 0's length): a
81    /// click drops the cursor stack, a shift-click asks the server to clear every window 0
82    /// slot.
83    #[must_use]
84    pub fn creative_delete_slot(&self) -> i16 {
85        Layout::new(self.version, Screen::Player).len as i16
86    }
87
88    /// The packets the legacy creative screen sent outside a click since the last call (the
89    /// listener's broadcast when the screen opened); send them right after the packet
90    /// [`Inventory::open_inventory`] returned.
91    pub fn take_creative_echo_legacy(&mut self) -> Vec<CreativePacket> {
92        self.creative16
93            .as_mut()
94            .map(|c| std::mem::take(&mut c.echo))
95            .unwrap_or_default()
96    }
97
98    /// Opening window 0 in creative mode (the inventory key): the survival screen the key
99    /// opens replaces itself with the creative screen, whose listener broadcasts.
100    pub(super) fn open_creative_legacy(&mut self) -> Option<Outgoing> {
101        let len = Layout::new(self.version, Screen::Player).len;
102        // the survival screen's `removed()`: `PlayerScreenHandler.close` (cursor dropped, the
103        // result cleared; 1.8 also drops the crafting grid, later versions only on the server)
104        let mut out = Vec::new();
105        if let Some(c) = self.m.cursor.take() {
106            self.events.cursor_changed = true;
107            // 1.16.5: `PlayerEntity.dropItem` swings on the client
108            if self.version == Version::V1_16_5 && c.count > 0 {
109                out.push(CreativePacket::Swing);
110            }
111        }
112        if self.m.craft_result.take().is_some() {
113            self.events.player_changed = true;
114        }
115        if self.version == Version::V1_8 {
116            if self.m.craft.iter().any(Option::is_some) {
117                self.events.player_changed = true;
118            }
119            self.m.craft = Default::default();
120        }
121        let c = self
122            .creative16
123            .get_or_insert_with(|| Box::new(CreativeLegacy::new(len)));
124        c.open = true;
125        self.screen = ScreenState::Inventory;
126        self.flags.opened = true;
127        self.creative_broadcast_legacy(&mut out);
128        if let Some(c) = &mut self.creative16 {
129            c.echo = out;
130        }
131        (self.version == Version::V1_8).then_some(Outgoing::OpenInventory)
132    }
133
134    /// `PlayerScreenHandler.sendContentUpdates` with the creative listener.
135    fn creative_broadcast_legacy(&mut self, out: &mut Vec<CreativePacket>) {
136        let lay = Layout::new(self.version, Screen::Player);
137        let Some(c) = &mut self.creative16 else {
138            return;
139        };
140        for (i, t) in c.tracked.iter_mut().enumerate().take(lay.len) {
141            let Some(l) = lay.loc(i) else { break };
142            let cur = self.m.at(l);
143            if !equals_all(t.as_ref(), cur.as_ref()) {
144                *t = cur.clone();
145                out.push(CreativePacket::SetSlot {
146                    slot: i as i16,
147                    item: cur.clone(),
148                });
149            }
150        }
151    }
152
153    /// `onScreenHandlerSlotUpdate` with the creative screen open: on an item tab window 0
154    /// slots outside the hotbar are not applied (the open handler is the creative one, whose
155    /// slots are the menu); 1.16.5 also ignores the cursor.
156    pub(super) fn creative_items_ignore_legacy(&self, window_id: i32, slot: i16) -> bool {
157        let Some(tab) = self.creative_screen_legacy() else {
158            return false;
159        };
160        // 1.16.5: the server's cursor is ignored while the creative screen is open
161        (window_id == -1 && self.version == Version::V1_16_5)
162            || (window_id == 0 && !(36..45).contains(&slot) && tab == CreativeTab::Items)
163    }
164
165    /// Selects the creative screen's tab (no packet). The tab is kept while the screen is
166    /// closed (vanilla keeps it in a static), so this also chooses the tab the next opening
167    /// shows; the first opening shows an item tab.
168    pub fn set_creative_tab_legacy(&mut self, tab: CreativeTab) {
169        let len = Layout::new(self.version, Screen::Player).len;
170        self.creative16
171            .get_or_insert_with(|| Box::new(CreativeLegacy::new(len)))
172            .tab = tab;
173    }
174
175    /// 1.16.5: the swings of a window click's drops (`PlayerEntity.dropItem` on the client): a
176    /// throw that took items from its slot, a pickup click outside with a carried stack.
177    pub(super) fn drop_swings_1_16(
178        &self,
179        post: &crate::sim::Model,
180        lay: Layout,
181        slot: i16,
182        button: u8,
183        mode: u8,
184    ) -> u8 {
185        if self.version != Version::V1_16_5 {
186            return 0;
187        }
188        let dropped = match mode {
189            0 | 1 => slot == OUTSIDE && button <= 1 && self.m.cursor.is_some(),
190            4 => {
191                self.m.cursor.is_none()
192                    && usize::try_from(slot).ok().is_some_and(|i| {
193                        let Some(l) = lay.loc(i) else { return false };
194                        let n = |m: &crate::sim::Model| m.at(l).as_ref().map_or(0, |s| s.count);
195                        // a result slot is refilled at once (trade output, stonecutter, ...):
196                        // taken when its inputs were consumed
197                        let refilled = matches!(
198                            lay.kind(i),
199                            crate::SlotKind::CraftResult
200                                | crate::SlotKind::TradeOutput
201                                | crate::SlotKind::MenuResult
202                        ) && n(post) > 0
203                            && (post.container != self.m.container || post.craft != self.m.craft);
204                        n(&self.m) > 0 && (n(post) < n(&self.m) || refilled)
205                    })
206            }
207            _ => false,
208        };
209        u8::from(dropped)
210    }
211
212    /// 1.16.5: a server window replacing the open screen drops the carried stack on the client
213    /// (the old screen's `removed()` closes its handler: `PlayerEntity.dropItem` swings).
214    #[cfg(feature = "v1_16_5")]
215    pub(crate) fn carried_drop_swing(&self) -> bool {
216        self.version == Version::V1_16_5
217            && self.screen != ScreenState::None
218            && self.m.cursor.as_ref().is_some_and(|c| c.count > 0)
219    }
220
221    /// Runs window 0's click on a scratch model (`None`: ghast cannot predict it).
222    fn creative_window0_click(&mut self, slot: i16, button: u8, mode: u8) -> Option<()> {
223        let lay = Layout::new(self.version, Screen::Player);
224        let mut m = self.m.clone();
225        let r = {
226            let mut sim = Sim {
227                v: self.version,
228                lay,
229                m: &mut m,
230                book: &self.book,
231                binding_curse: None,
232                tags: self.tags16.as_deref(),
233            };
234            sim.click(slot, button, mode)
235        };
236        r.ok()?;
237        self.commit(m, lay);
238        Some(())
239    }
240
241    /// A click in the legacy creative screen ([`Inventory::click`] routes here while it is
242    /// open).
243    pub(super) fn creative_click_legacy(
244        &mut self,
245        slot: i16,
246        button: u8,
247        mode: u8,
248    ) -> Result<Outgoing, ClickError> {
249        let tab = self.creative_screen_legacy().ok_or(ClickError::NoScreen)?;
250        let v = self.version;
251        if mode == 5 {
252            // drags are not modelled on the legacy versions
253            return Err(ClickError::Unpredictable);
254        }
255        if mode == 2 && button >= 9 && !(self.version == Version::V1_16_5 && button == 40) {
256            return Err(ClickError::InvalidButton);
257        }
258        let len = Layout::new(self.version, Screen::Player).len as i16;
259        let mut out = Vec::new();
260        let shift = mode == 1;
261        let mode = if slot == OUTSIDE && mode == 0 {
262            4
263        } else {
264            mode
265        };
266        match tab {
267            CreativeTab::Inventory => {
268                let delete = len;
269                // the crafting grid and result (0..5) are not on this tab
270                if slot != OUTSIDE && !(5..=delete).contains(&slot) {
271                    return Err(ClickError::InvalidSlot);
272                }
273                if slot == delete && shift {
274                    // asks the server to clear every slot; nothing changes here
275                    for i in 0..len {
276                        out.push(CreativePacket::SetSlot {
277                            slot: i,
278                            item: None,
279                        });
280                    }
281                } else if slot == delete {
282                    if self.m.cursor.take().is_some() {
283                        self.events.cursor_changed = true;
284                    }
285                } else if mode == 4
286                    && let Some(l) = usize::try_from(slot)
287                        .ok()
288                        .and_then(|i| Layout::new(self.version, Screen::Player).loc(i))
289                    && let Some(st) = self.m.at(l).clone()
290                {
291                    // `slot.takeStack(button == 0 ? 1 : max)`, then dropped
292                    let n = if button == 0 {
293                        1
294                    } else {
295                        self.version.max_count(&st)
296                    };
297                    let s = self.m.at_mut(l);
298                    let dropped = if st.count <= n {
299                        s.take()
300                    } else {
301                        if let Some(x) = s {
302                            x.count -= n;
303                        }
304                        Some(st.with_count(n))
305                    };
306                    self.events.player_changed = true;
307                    drop_into(v, &mut out, dropped);
308                    if self.version != Version::V1_8 {
309                        // 1.12+: the slot's rest goes out at once
310                        out.push(CreativePacket::SetSlot {
311                            slot,
312                            item: self.m.at(l).clone(),
313                        });
314                    }
315                } else if mode == 4
316                    && let Some(c) = self.m.cursor.take()
317                {
318                    self.events.cursor_changed = true;
319                    drop_into(v, &mut out, Some(c));
320                } else {
321                    let lay = Layout::new(v, Screen::Player);
322                    let pre = self.m.clone();
323                    self.creative_window0_click(slot, button, mode)
324                        .ok_or(ClickError::Unpredictable)?;
325                    let post = std::mem::replace(&mut self.m, pre);
326                    let swings = self.drop_swings_1_16(&post, lay, slot, button, mode);
327                    self.m = post;
328                    for _ in 0..swings {
329                        out.push(CreativePacket::Swing);
330                    }
331                    self.creative_broadcast_legacy(&mut out);
332                }
333            }
334            CreativeTab::Items => {
335                if slot == OUTSIDE {
336                    if let Some(c) = &mut self.m.cursor {
337                        if button == 0 {
338                            let c = self.m.cursor.take();
339                            drop_into(v, &mut out, c);
340                        } else if button == 1 {
341                            let one = c.with_count(1);
342                            c.count -= 1;
343                            // 1.8 empties only at exactly 0 (a zero-count stack goes to -1)
344                            if c.count == 0 || (v != Version::V1_8 && c.count < 0) {
345                                self.m.cursor = None;
346                            }
347                            drop_into(v, &mut out, Some(one));
348                        }
349                        self.events.cursor_changed = true;
350                    }
351                } else {
352                    if !(45..54).contains(&slot) {
353                        return Err(ClickError::InvalidSlot);
354                    }
355                    let k = (slot - 45) as usize;
356                    let w0 = 36 + k as i16;
357                    let before = self.m.player[k].clone();
358                    // 1.16.5: the handler's throw drops through `PlayerEntity.dropItem` (a swing)
359                    if v == Version::V1_16_5
360                        && mode == 4
361                        && self.m.cursor.is_none()
362                        && before.is_some()
363                    {
364                        out.push(CreativePacket::Swing);
365                    }
366                    // 1.12+ swap with an over-stacked hotbar stack (above the slot limit): the
367                    // clicked stack is inserted into the inventory instead of moving
368                    let spill = (self.version != Version::V1_8
369                        && mode == 2
370                        && before.is_some()
371                        && self.m.player[usize::from(button)]
372                            .as_ref()
373                            .is_some_and(|h| h.count > 64))
374                    .then(|| self.m.player.clone());
375                    match mode {
376                        // `transferSlot` of the creative handler empties a hotbar slot
377                        1 if button <= 1 => {
378                            if self.m.player[k].take().is_some() {
379                                self.events.player_changed = true;
380                            }
381                        }
382                        1 => {}
383                        6 => self.creative_hotbar_pickup_all(k, button),
384                        _ => {
385                            self.creative_window0_click(w0, button, mode)
386                                .ok_or(ClickError::Unpredictable)?;
387                        }
388                    }
389                    if button & 3 == 2 {
390                        // `unpackButtonId(button) == 2` (the drag header bits): the whole row
391                        for (j, st) in self.m.player[..9].iter().enumerate() {
392                            out.push(CreativePacket::SetSlot {
393                                slot: 36 + j as i16,
394                                item: st.clone(),
395                            });
396                        }
397                    } else {
398                        out.push(CreativePacket::SetSlot {
399                            slot: w0,
400                            item: self.m.player[k].clone(),
401                        });
402                        if self.version != Version::V1_8 {
403                            // 1.12+: the screen kept the clicked slot's stack object from before
404                            // the click: a swap sends it for the other slot (where it moved), a
405                            // throw drops a copy of what is left of it (the throw split it);
406                            // then window 0 broadcasts
407                            if mode == 2 {
408                                let moved = match (&spill, &before) {
409                                    // what of it the inventory did not take (dropped)
410                                    (Some(pre), Some(b)) => {
411                                        let like = |x: &Option<Stack>| {
412                                            x.as_ref()
413                                                .filter(|x| {
414                                                    x.id == b.id
415                                                        && x.damage == b.damage
416                                                        && x.nbt_eq(b)
417                                                })
418                                                .map_or(0, |x| x.count)
419                                        };
420                                        let gained: i32 = (0..36)
421                                            .filter(|&i| i != k)
422                                            .map(|i| like(&self.m.player[i]) - like(&pre[i]))
423                                            .sum();
424                                        // a swap with itself split the stack first
425                                        let held = if usize::from(button) == k {
426                                            b.count - 64
427                                        } else {
428                                            b.count
429                                        };
430                                        let left = held - gained;
431                                        (left > 0).then(|| b.with_count(left))
432                                    }
433                                    _ => before.clone(),
434                                };
435                                out.push(CreativePacket::SetSlot {
436                                    slot: 36 + i16::from(button),
437                                    item: moved,
438                                });
439                            } else if mode == 4
440                                && before.is_some()
441                                && let Some(b) = &self.m.player[k]
442                            {
443                                let n = if button == 0 {
444                                    1
445                                } else {
446                                    self.version.max_count(b)
447                                };
448                                drop_into(v, &mut out, Some(b.with_count(n)));
449                            }
450                            self.creative_broadcast_legacy(&mut out);
451                        }
452                    }
453                }
454            }
455        }
456        self.flags.clicked = true;
457        Ok(Outgoing::Creative(out))
458    }
459
460    /// Double click on a hotbar slot of an item tab: the creative handler gathers only from
461    /// its hotbar row (`canInsertIntoSlot(stack, slot)`: the slot is below y 90).
462    fn creative_hotbar_pickup_all(&mut self, k: usize, button: u8) {
463        let v = self.version;
464        let Some(mut c) = self.m.cursor.clone() else {
465            return;
466        };
467        if self.m.player[k].is_some() {
468            // the clicked slot holds a stack: no gathering
469            return;
470        }
471        let max = v.max_count(&c);
472        for pass in 0..2 {
473            let order: [usize; 9] = if button == 0 {
474                [0, 1, 2, 3, 4, 5, 6, 7, 8]
475            } else {
476                [8, 7, 6, 5, 4, 3, 2, 1, 0]
477            };
478            for x in order {
479                if c.count >= max {
480                    break;
481                }
482                let Some(t) = &self.m.player[x] else { continue };
483                if !(c.id == t.id && c.damage == t.damage && t.nbt_eq(&c) && t.count <= max) {
484                    continue;
485                }
486                if pass == 0 && t.count == v.max_count(t) {
487                    continue;
488                }
489                let u = (max - c.count).min(t.count);
490                let s = &mut self.m.player[x];
491                if let Some(t) = s {
492                    t.count -= u;
493                    if t.count <= 0 {
494                        *s = None;
495                    }
496                }
497                c.count += u;
498                self.events.player_changed = true;
499            }
500        }
501        self.m.cursor = Some(c);
502        self.events.cursor_changed = true;
503    }
504
505    /// A click on the menu of a creative item tab: the menu slot shows `menu` (a stack of the
506    /// tab's item list; the server takes whatever the client sends, so any stack works). Pick
507    /// up / shift / double click set the cursor (no packet), the number keys put a full stack
508    /// into the hotbar (window 0 broadcasts), middle click clones, the drop key drops a copy.
509    ///
510    /// # Errors
511    /// [`ClickError::NoScreen`] when no legacy creative item tab is open;
512    /// [`ClickError::InvalidSlot`] for a drag; [`ClickError::SameTick`] for a second action in
513    /// a tick.
514    pub fn creative_menu_click(
515        &mut self,
516        menu: Option<Stack>,
517        click: super::Click,
518    ) -> Result<Outgoing, ClickError> {
519        self.can_click()?;
520        if self.creative_screen_legacy() != Some(CreativeTab::Items) {
521            return Err(ClickError::NoScreen);
522        }
523        let (_, button, mode) = click.wire();
524        if mode == 5 {
525            return Err(ClickError::InvalidSlot);
526        }
527        let v = self.version;
528        let mut out = Vec::new();
529        let full = mode == 1;
530        // 1.12+: a menu slot holding a locked stack (the saved toolbars' placeholder) cannot
531        // be taken from
532        if v != Version::V1_8
533            && menu
534                .as_ref()
535                .is_some_and(|s| s.has_compound_tag("CustomCreativeLock"))
536        {
537            self.flags.clicked = true;
538            return Ok(Outgoing::Creative(out));
539        }
540        let legacy18 = v == Version::V1_8;
541        match mode {
542            2 => {
543                // 1.16.5 takes any button (40: the offhand)
544                if let Some(s) = &menu
545                    && (button < 9 || v == Version::V1_16_5 && button == 40)
546                {
547                    self.m.player[usize::from(button)] = Some(s.with_count(v.max_count(s)));
548                    self.events.player_changed = true;
549                    self.creative_broadcast_legacy(&mut out);
550                }
551            }
552            3 => {
553                if self.m.cursor.is_none()
554                    && let Some(s) = &menu
555                {
556                    self.m.cursor = Some(s.with_count(v.max_count(s)));
557                    self.events.cursor_changed = true;
558                }
559            }
560            4 => {
561                if let Some(s) = &menu {
562                    let n = if button == 0 { 1 } else { v.max_count(s) };
563                    drop_into(v, &mut out, Some(s.with_count(n)));
564                }
565            }
566            _ => {
567                let cursor = self.m.cursor.take();
568                self.m.cursor = match (cursor, &menu) {
569                    // same item and damage (1.12+: and NBT)
570                    (Some(mut c), Some(s))
571                        if c.id == s.id && c.damage == s.damage && (legacy18 || c.nbt_eq(s)) =>
572                    {
573                        let max = v.max_count(&c);
574                        if button == 0 {
575                            if full {
576                                c.count = max;
577                            } else if c.count < max {
578                                c.count += 1;
579                            }
580                            Some(c)
581                        } else if c.count <= 1 {
582                            None
583                        } else {
584                            c.count -= 1;
585                            Some(c)
586                        }
587                    }
588                    (None, Some(s)) => {
589                        let mut c = s.clone();
590                        if full {
591                            c.count = v.max_count(&c);
592                        }
593                        Some(c)
594                    }
595                    // 1.12+: the right button takes one off the cursor
596                    (Some(mut c), _) if !legacy18 && button != 0 => {
597                        c.count -= 1;
598                        (c.count > 0).then_some(c)
599                    }
600                    _ => None,
601                };
602                self.events.cursor_changed = true;
603            }
604        }
605        self.flags.clicked = true;
606        Ok(Outgoing::Creative(out))
607    }
608
609    /// The pick block key (no screen open) for a target whose pick stack is `pick` (1.8: its
610    /// item and damage; `has_data`: the item has subtypes, so the damage must match too, as
611    /// 1.8 `doPick` passes it; 1.12.2: the whole stack, NBT included, the damage compared for
612    /// items with subtypes). 1.8 `PlayerInventory.addPickBlock` / 1.12 `method_13250` select a
613    /// hotbar slot that holds it or, in creative mode, put it into the selected (or first
614    /// empty) hotbar slot; in creative mode the selected slot is then sent. Returns the packet
615    /// (`None` in survival); the selected hotbar slot may change ([`Inventory::selected`]): the
616    /// client then sends `held_item_change`.
617    ///
618    /// # Errors
619    /// [`ClickError::WindowOpen`] when a screen is open; [`ClickError::Unpredictable`] for a
620    /// 1.12.2 survival pick of a stack outside the hotbar (`MC|PickItem`, not modelled) and on
621    /// other versions.
622    pub fn pick_block_legacy(
623        &mut self,
624        pick: &Stack,
625        has_data: bool,
626    ) -> Result<Option<Outgoing>, ClickError> {
627        if self.screen != ScreenState::None {
628            return Err(ClickError::WindowOpen);
629        }
630        match self.version {
631            Version::V1_8 => self.pick_1_8(pick.id, pick.damage, has_data),
632            Version::V1_12 | Version::V1_16_5 => self.pick_1_12(pick)?,
633            _ => return Err(ClickError::Unpredictable),
634        }
635        if !self.m.creative {
636            return Ok(None);
637        }
638        let sel = usize::from(self.m.selected);
639        Ok(Some(Outgoing::Creative(vec![CreativePacket::SetSlot {
640            slot: 36 + sel as i16,
641            item: self.m.player[sel].clone(),
642        }])))
643    }
644
645    fn pick_1_8(&mut self, item: i32, data: i16, has_data: bool) {
646        let creative = self.m.creative;
647        // the selected slot may move below (while `p` borrows the slots)
648        self.m.player.touch();
649        let p = &self.m.player;
650        let with = |id: i32, d: Option<i16>| {
651            (0..36).find(|&i| {
652                p[i].as_ref()
653                    .is_some_and(|s| s.id == id && d.is_none_or(|d| s.damage == d))
654            })
655        };
656        let sel = usize::from(self.m.selected);
657        let held = p[sel].clone();
658        let found = with(item, has_data.then_some(data));
659        if let Some(i) = found.filter(|&i| i < 9) {
660            self.m.selected = i as u8;
661        } else if creative {
662            if let Some(j) = (0..36).find(|&i| p[i].is_none()).filter(|&j| j < 9) {
663                self.m.selected = j as u8;
664            }
665            let sel = usize::from(self.m.selected);
666            let keep = held.as_ref().is_some_and(|h| {
667                self.enchantable_1_8(h) && with(h.id, Some(h.damage)) == Some(sel)
668            });
669            if !keep {
670                let (n, from) = match with(item, Some(data)) {
671                    Some(k) => (self.m.player[k].as_ref().map_or(1, |s| s.count), Some(k)),
672                    None => (1, None),
673                };
674                if let Some(k) = from {
675                    self.m.player[k] = self.m.player[sel].clone();
676                }
677                self.m.player[sel] = Some(Stack::new(item, n, data));
678                self.events.player_changed = true;
679            }
680        }
681    }
682
683    /// 1.12 `doPick`'s tail: `method_13253` (the first slot holding the stack) and, in
684    /// creative mode, `method_13250`.
685    fn pick_1_12(&mut self, pick: &Stack) -> Result<(), ClickError> {
686        let v = self.version;
687        // 1.16.5 `areItemsEqual`: item and tag (the damage is a tag)
688        let same = |s: &Stack| {
689            s.id == pick.id
690                && (v == Version::V1_16_5 || !v.has_subtypes(pick.id) || s.damage == pick.damage)
691                && s.nbt_eq(pick)
692        };
693        let ench = if v == Version::V1_16_5 {
694            "Enchantments"
695        } else {
696            "ench"
697        };
698        let i = (0..36).find(|&i| self.m.player[i].as_ref().is_some_and(same));
699        if let Some(i) = i.filter(|&i| i < 9) {
700            self.m.selected = i as u8;
701            self.m.player.touch();
702            return Ok(());
703        }
704        if !self.m.creative {
705            // the survival pick of a stack in the main inventory asks the server (`MC|PickItem`)
706            return match i {
707                None => Ok(()),
708                Some(_) => Err(ClickError::Unpredictable),
709            };
710        }
711        // `method_13259`: from the selected slot on, the first empty hotbar slot, else the first
712        // without enchantments, else the selected one
713        let start = usize::from(self.m.selected);
714        let p = &self.m.player;
715        let best = (0..9)
716            .map(|k| (start + k) % 9)
717            .find(|&j| p[j].is_none())
718            .or_else(|| {
719                (0..9)
720                    .map(|k| (start + k) % 9)
721                    .find(|&j| !p[j].as_ref().is_some_and(|s| s.has_nonempty_list_tag(ench)))
722            })
723            .unwrap_or(start);
724        self.m.selected = best as u8;
725        self.m.player.touch();
726        match i {
727            None => {
728                if self.m.player[best].is_some()
729                    && let Some(j) = (0..36).find(|&j| self.m.player[j].is_none())
730                {
731                    self.m.player[j] = self.m.player[best].clone();
732                }
733                self.m.player[best] = Some(pick.clone());
734            }
735            Some(i) => self.m.player.swap(best, i),
736        }
737        self.events.player_changed = true;
738        Ok(())
739    }
740
741    /// 1.12.2 creative mode: a saved toolbar loaded with its key (hotbar key + the load key,
742    /// no screen open; `CreativeInventoryScreen.method_14550`): the hotbar becomes `saved`
743    /// (the toolbar the client stored earlier), each slot is sent, and window 0's broadcast
744    /// runs without a listener (it only records the slots as sent).
745    ///
746    /// # Errors
747    /// [`ClickError::WindowOpen`] when a screen is open; [`ClickError::Unpredictable`] outside
748    /// creative mode or on other versions.
749    pub fn creative_load_hotbar_legacy(
750        &mut self,
751        saved: &[Option<Stack>; 9],
752    ) -> Result<Outgoing, ClickError> {
753        if self.screen != ScreenState::None {
754            return Err(ClickError::WindowOpen);
755        }
756        if !matches!(self.version, Version::V1_12 | Version::V1_16_5) || !self.m.creative {
757            return Err(ClickError::Unpredictable);
758        }
759        let mut out = Vec::with_capacity(9);
760        for (j, s) in saved.iter().enumerate() {
761            self.m.player[j] = s.clone();
762            out.push(CreativePacket::SetSlot {
763                slot: 36 + j as i16,
764                item: s.clone(),
765            });
766        }
767        self.events.player_changed = true;
768        let lay = Layout::new(self.version, Screen::Player);
769        let c = self
770            .creative16
771            .get_or_insert_with(|| Box::new(CreativeLegacy::new(lay.len)));
772        for (i, t) in c.tracked.iter_mut().enumerate() {
773            if let Some(l) = lay.loc(i) {
774                t.clone_from(self.m.at(l));
775            }
776        }
777        Ok(Outgoing::Creative(out))
778    }
779
780    /// 1.8 `ItemStack.isEnchantable`: the item takes enchantments (one per stack and damageable
781    /// without subtypes; a book: a single one) and the stack has no `ench` list yet.
782    fn enchantable_1_8(&self, s: &Stack) -> bool {
783        let v = self.version;
784        let item_ok = match s.item_name(v) {
785            Some("book") => s.count == 1,
786            Some("enchanted_book") => false,
787            _ => v.max_count(s) == 1 && v.max_durability(s.id).is_some() && !v.has_subtypes(s.id),
788        };
789        item_ok && !s.has_list_tag("ench")
790    }
791}
792
793impl Stack {
794    /// The root compound has a compound tag `key` (`getNbtCompound(key) != null`).
795    pub(crate) fn has_compound_tag(&self, key: &str) -> bool {
796        use ghast_protocol::nbt::Tag;
797        let Some(Ok(Some(n))) = self.nbt().map(|n| n.parse()) else {
798            return false;
799        };
800        match &n.tag {
801            Tag::Compound(c) => matches!(crate::stack::last(c, key), Some(Tag::Compound(_))),
802            _ => false,
803        }
804    }
805
806    /// The root compound has a non-empty list tag `key` (1.12 `hasEnchantments` for `ench`).
807    pub(crate) fn has_nonempty_list_tag(&self, key: &str) -> bool {
808        use ghast_protocol::nbt::Tag;
809        let Some(Ok(Some(n))) = self.nbt().map(|n| n.parse()) else {
810            return false;
811        };
812        match &n.tag {
813            Tag::Compound(c) => {
814                matches!(crate::stack::last(c, key), Some(Tag::List(l)) if !l.items.is_empty())
815            }
816            _ => false,
817        }
818    }
819
820    /// The root compound has a list tag `key` (`contains(key, 9)`).
821    pub(crate) fn has_list_tag(&self, key: &str) -> bool {
822        use ghast_protocol::nbt::Tag;
823        let Some(Ok(Some(n))) = self.nbt().map(|n| n.parse()) else {
824            return false;
825        };
826        match &n.tag {
827            Tag::Compound(c) => matches!(crate::stack::last(c, key), Some(Tag::List(_))),
828            _ => false,
829        }
830    }
831}
832
833impl CreativePacket {
834    /// The 1.8 `creative_inventory_action` (`None` for [`CreativePacket::Swing`]).
835    #[cfg(feature = "v1_8")]
836    #[must_use]
837    pub fn to_v1_8(&self) -> Option<ghast_protocol::v1_8::play::serverbound::SetCreativeSlot> {
838        match self {
839            CreativePacket::SetSlot { slot, item } => {
840                Some(ghast_protocol::v1_8::play::serverbound::SetCreativeSlot {
841                    slot: *slot,
842                    item: crate::stack::to_legacy_slot(item.as_ref()),
843                })
844            }
845            CreativePacket::Swing => None,
846        }
847    }
848
849    /// The 1.16.5 `creative_inventory_action` (`None` for [`CreativePacket::Swing`]).
850    #[cfg(feature = "v1_16_5")]
851    #[must_use]
852    pub fn to_v1_16_5(
853        &self,
854    ) -> Option<ghast_protocol::v1_16_5::play::serverbound::SetCreativeSlot> {
855        match self {
856            CreativePacket::SetSlot { slot, item } => Some(
857                ghast_protocol::v1_16_5::play::serverbound::SetCreativeSlot {
858                    slot: *slot,
859                    item: crate::stack::to_modern_slot(item.as_ref()),
860                },
861            ),
862            CreativePacket::Swing => None,
863        }
864    }
865
866    /// The 1.12.2 `creative_inventory_action` (`None` for [`CreativePacket::Swing`]).
867    #[cfg(feature = "v1_12")]
868    #[must_use]
869    pub fn to_v1_12_2(
870        &self,
871    ) -> Option<ghast_protocol::v1_12_2::play::serverbound::SetCreativeSlot> {
872        match self {
873            CreativePacket::SetSlot { slot, item } => Some(
874                ghast_protocol::v1_12_2::play::serverbound::SetCreativeSlot {
875                    slot: *slot,
876                    item: crate::stack::to_legacy_slot(item.as_ref()),
877                },
878            ),
879            CreativePacket::Swing => None,
880        }
881    }
882}