Skip to main content

ghast_ext/
items.rs

1//! Items: matching by name, equipping, window clicks, containers.
2
3use std::sync::Arc;
4
5use ghast_client::inventory::{Click, ClickError, ClickOutcome, Stack, WindowKind};
6#[cfg(any(
7    feature = "v1_8",
8    feature = "v1_12_2",
9    feature = "v1_16_5",
10    feature = "v26_1",
11    feature = "v26_2",
12    feature = "v26_3"
13))]
14use ghast_client::version::DataSet;
15use ghast_client::{BlockPos, ClickRefused, GameVersion, TickContext};
16
17use crate::{Bot, Error};
18
19/// Ticks a click may wait for its turn (still look, previous confirm, same-tick rules).
20const CLICK_WAIT: u64 = 100;
21
22/// What an item helper looks for: a registry name, an item id of the session's version,
23/// or a predicate on the stack.
24#[derive(Clone)]
25#[non_exhaustive]
26pub enum ItemMatch {
27    /// A registry name (`"diamond_pickaxe"`, `"minecraft:bread"`), resolved per version.
28    Name(String),
29    /// An item id of the session's version.
30    Id(i32),
31    /// A predicate.
32    Pred(Arc<dyn Fn(&Stack) -> bool + Send + Sync>),
33}
34
35impl std::fmt::Debug for ItemMatch {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        match self {
38            ItemMatch::Name(n) => f.debug_tuple("Name").field(n).finish(),
39            ItemMatch::Id(i) => f.debug_tuple("Id").field(i).finish(),
40            ItemMatch::Pred(_) => f.write_str("Pred(..)"),
41        }
42    }
43}
44
45impl std::fmt::Display for ItemMatch {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        match self {
48            ItemMatch::Name(n) => f.write_str(n),
49            ItemMatch::Id(i) => write!(f, "item id {i}"),
50            ItemMatch::Pred(_) => f.write_str("matching item"),
51        }
52    }
53}
54
55impl From<&str> for ItemMatch {
56    fn from(n: &str) -> Self {
57        ItemMatch::Name(n.to_owned())
58    }
59}
60
61impl From<String> for ItemMatch {
62    fn from(n: String) -> Self {
63        ItemMatch::Name(n)
64    }
65}
66
67impl From<i32> for ItemMatch {
68    fn from(id: i32) -> Self {
69        ItemMatch::Id(id)
70    }
71}
72
73impl<F: Fn(&Stack) -> bool + Send + Sync + 'static> From<F> for ItemMatch {
74    fn from(f: F) -> Self {
75        ItemMatch::Pred(Arc::new(f))
76    }
77}
78
79/// The item id of a registry name in `version`.
80///
81/// ```
82/// use ghast_client::GameVersion;
83/// assert_eq!(ghast_ext::item_id(GameVersion::V1_8_9, "diamond_pickaxe"), Some(278));
84/// assert!(ghast_ext::item_id(GameVersion::V1_16_5, "minecraft:diamond_pickaxe").is_some());
85/// assert_eq!(ghast_ext::item_id(GameVersion::V1_8_9, "no_such_item"), None);
86/// ```
87#[must_use]
88pub fn item_id(version: GameVersion, name: &str) -> Option<i32> {
89    let n = name.strip_prefix("minecraft:").unwrap_or(name);
90    // By data set: sub-versions (1.12.1, 1.16.2, ...) share their row's tables.
91    match version.caps().data {
92        #[cfg(feature = "v1_8")]
93        DataSet::V1_8 => ghast_data::v1_8::Item::from_name(n).map(|i| i32::from(i.id())),
94        #[cfg(feature = "v1_12_2")]
95        DataSet::V1_12 => ghast_data::v1_12::Item::from_name(n).map(|i| i32::from(i.id())),
96        #[cfg(feature = "v1_16_5")]
97        DataSet::V1_16_5 => ghast_data::v1_16_5::Item::from_name(n).map(|i| i32::from(i.id())),
98        #[cfg(feature = "v26_1")]
99        DataSet::V26_1 => ghast_data::v26_1::Item::from_name(n).map(|i| i32::from(i.id())),
100        #[cfg(feature = "v26_2")]
101        DataSet::V26_2 => ghast_data::v26_2::Item::from_name(n).map(|i| i32::from(i.id())),
102        #[cfg(feature = "v26_3")]
103        DataSet::V26_3 => ghast_data::v26_3::Item::from_name(n).map(|i| i32::from(i.id())),
104        _ => None,
105    }
106}
107
108/// The registry name of an item id in `version` (`""` when unknown).
109///
110/// ```
111/// use ghast_client::GameVersion;
112/// assert_eq!(ghast_ext::item_name(GameVersion::V1_8_9, 278), "diamond_pickaxe");
113/// ```
114#[must_use]
115pub fn item_name(version: GameVersion, id: i32) -> &'static str {
116    let Ok(id) = u16::try_from(id) else {
117        return "";
118    };
119    // By data set: sub-versions (1.12.1, 1.16.2, ...) share their row's tables.
120    match version.caps().data {
121        #[cfg(feature = "v1_8")]
122        DataSet::V1_8 => ghast_data::v1_8::Item::from_id(id).map_or("", |i| i.info().name),
123        #[cfg(feature = "v1_12_2")]
124        DataSet::V1_12 => ghast_data::v1_12::Item::from_id(id).map_or("", |i| i.info().name),
125        #[cfg(feature = "v1_16_5")]
126        DataSet::V1_16_5 => ghast_data::v1_16_5::Item::from_id(id).map_or("", |i| i.info().name),
127        #[cfg(feature = "v26_1")]
128        DataSet::V26_1 => ghast_data::v26_1::Item::from_id(id).map_or("", |i| i.name()),
129        #[cfg(feature = "v26_2")]
130        DataSet::V26_2 => ghast_data::v26_2::Item::from_id(id).map_or("", |i| i.name()),
131        #[cfg(feature = "v26_3")]
132        DataSet::V26_3 => ghast_data::v26_3::Item::from_id(id).map_or("", |i| i.name()),
133        _ => "",
134    }
135}
136
137/// A resolved [`ItemMatch`].
138#[derive(Clone)]
139pub(crate) struct Matcher(ItemMatchInner);
140
141#[derive(Clone)]
142enum ItemMatchInner {
143    Id(i32),
144    Pred(Arc<dyn Fn(&Stack) -> bool + Send + Sync>),
145}
146
147impl Matcher {
148    pub(crate) fn resolve(m: &ItemMatch, version: GameVersion) -> Result<Matcher, Error> {
149        Ok(Matcher(match m {
150            ItemMatch::Name(n) => ItemMatchInner::Id(
151                item_id(version, n).ok_or_else(|| Error::UnknownItem(n.clone()))?,
152            ),
153            ItemMatch::Id(i) => ItemMatchInner::Id(*i),
154            ItemMatch::Pred(p) => ItemMatchInner::Pred(p.clone()),
155        }))
156    }
157
158    pub(crate) fn matches(&self, s: &Stack) -> bool {
159        if s.count() <= 0 && s.id() <= 0 {
160            return false;
161        }
162        match &self.0 {
163            ItemMatchInner::Id(i) => s.id() == *i,
164            ItemMatchInner::Pred(p) => p(s),
165        }
166    }
167}
168
169/// An open container window ([`Bot::open_container`]).
170#[derive(Debug, Clone, PartialEq, Eq)]
171#[non_exhaustive]
172pub struct Container {
173    /// Window id.
174    pub id: i32,
175    /// Window kind.
176    pub kind: WindowKind,
177    /// Number of container slots (before the player's 36).
178    pub slots: usize,
179}
180
181/// The `PlayerInventory` index (0–8 hotbar, 9–35 main) of the first matching stack in the
182/// hotbar or main inventory, hotbar first.
183fn find_player(ctx: &TickContext<'_>, m: &Matcher) -> Option<usize> {
184    (0..36).find(|&k| ctx.inventory().player(k).is_some_and(|s| m.matches(s)))
185}
186
187impl Bot {
188    /// The window-0 slots / counts are read in the tick: total count of matching items in
189    /// the player inventory (hotbar, main, armour, off hand).
190    ///
191    /// ```no_run
192    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
193    /// let n = bot.count("cobblestone").await?;
194    /// # Ok(()) }
195    /// ```
196    pub async fn count(&self, item: impl Into<ItemMatch>) -> Result<i32, Error> {
197        let item = item.into();
198        self.with(move |ctx| {
199            let m = Matcher::resolve(&item, ctx.version())?;
200            Ok(ctx.inventory().count(|s| m.matches(s)))
201        })
202        .await?
203    }
204
205    /// The `PlayerInventory` index (0–8 hotbar, 9–35 main) of the first matching stack,
206    /// hotbar first, and a copy of the stack.
207    ///
208    /// ```no_run
209    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
210    /// if let Some((index, stack)) = bot.find_item("bread").await? {
211    ///     println!("{} bread in slot {index}", stack.count());
212    /// }
213    /// # Ok(()) }
214    /// ```
215    pub async fn find_item(
216        &self,
217        item: impl Into<ItemMatch>,
218    ) -> Result<Option<(usize, Stack)>, Error> {
219        let item = item.into();
220        self.with(move |ctx| {
221            let m = Matcher::resolve(&item, ctx.version())?;
222            Ok(
223                find_player(ctx, &m)
224                    .and_then(|k| ctx.inventory().player(k).map(|s| (k, s.clone()))),
225            )
226        })
227        .await?
228    }
229
230    /// The held stack (a copy).
231    ///
232    /// ```no_run
233    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
234    /// let held = bot.held_item().await?;
235    /// # Ok(()) }
236    /// ```
237    pub async fn held_item(&self) -> Result<Option<Stack>, Error> {
238        self.with(|ctx| ctx.inventory().held().cloned()).await
239    }
240
241    /// Selects hotbar slot `slot` (0 … 8) in this tick.
242    ///
243    /// ```no_run
244    /// # fn f(bot: ghast_ext::Bot) {
245    /// bot.select_slot(2);
246    /// # }
247    /// ```
248    pub fn select_slot(&self, slot: u8) {
249        self.act(move |ctx| ctx.select_slot(slot));
250    }
251
252    /// Holds a matching item: selects it when it is in the hotbar; otherwise swaps it from
253    /// the main inventory into the hotbar (an empty hotbar slot, else the held one) with a
254    /// number-key click in the inventory screen (opened and closed again unless a container
255    /// is open), then selects it. Returns the hotbar slot.
256    ///
257    /// ```no_run
258    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
259    /// bot.equip("diamond_pickaxe").await?;
260    /// bot.equip(|s: &ghast_client::inventory::Stack| s.id() == 278).await?;
261    /// # Ok(()) }
262    /// ```
263    pub async fn equip(&self, item: impl Into<ItemMatch>) -> Result<u8, Error> {
264        let item = item.into();
265        let label = item.to_string();
266        let found = self
267            .with(move |ctx| -> Result<Option<(usize, u8)>, Error> {
268                let m = Matcher::resolve(&item, ctx.version())?;
269                let Some(k) = find_player(ctx, &m) else {
270                    return Ok(None);
271                };
272                if k < 9 {
273                    ctx.select_slot(k as u8);
274                    return Ok(Some((k, k as u8)));
275                }
276                let inv = ctx.inventory();
277                let hotbar = (0..9u8)
278                    .find(|h| inv.hotbar(usize::from(*h)).is_none())
279                    .unwrap_or(ctx.held_slot());
280                Ok(Some((k, hotbar)))
281            })
282            .await??;
283        let Some((index, hotbar)) = found else {
284            return Err(Error::NoSuchItem(label));
285        };
286        if index < 9 {
287            return Ok(hotbar);
288        }
289        self.swap_to_hotbar(index, hotbar).await?;
290        self.select_slot(hotbar);
291        self.next_tick().await;
292        Ok(hotbar)
293    }
294
295    /// Selects the hotbar tool that digs `pos` fastest, first bringing a faster one from the
296    /// main inventory into the hotbar if there is one. Returns the hotbar slot.
297    ///
298    /// ```no_run
299    /// use ghast_client::BlockPos;
300    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
301    /// let p = BlockPos::new(1, 60, 1);
302    /// bot.equip_for_block(p).await?;
303    /// bot.dig(p).await?;
304    /// # Ok(()) }
305    /// ```
306    pub async fn equip_for_block(&self, pos: BlockPos) -> Result<u8, Error> {
307        let plan = self
308            .with(move |ctx| -> Result<(u8, Option<usize>), Error> {
309                if ctx.world().raw_block(pos.x, pos.y, pos.z).is_none() {
310                    return Err(Error::NotLoaded(pos));
311                }
312                let (slot, hot) = crate::actions::best_hotbar_tool(ctx, pos);
313                let main = (9..36)
314                    .filter_map(|k| {
315                        let s = ctx.dig_speed(pos, ctx.inventory().player(k))?;
316                        (s > hot).then_some((k, s))
317                    })
318                    .max_by(|a, b| a.1.total_cmp(&b.1))
319                    .map(|(k, _)| k);
320                if main.is_none() {
321                    ctx.select_slot(slot);
322                }
323                Ok((slot, main))
324            })
325            .await??;
326        match plan {
327            (slot, None) => Ok(slot),
328            (_, Some(k)) => {
329                let hotbar = self.with(|ctx| ctx.held_slot()).await?;
330                self.swap_to_hotbar(k, hotbar).await?;
331                self.select_slot(hotbar);
332                self.next_tick().await;
333                Ok(hotbar)
334            }
335        }
336    }
337
338    /// Swaps `PlayerInventory` index `index` with hotbar slot `hotbar` (number-key click).
339    /// Uses the open container if there is one, else opens the inventory screen for it and
340    /// closes it again.
341    ///
342    /// ```no_run
343    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
344    /// bot.swap_to_hotbar(20, 0).await?; // main slot 20 <-> hotbar 0
345    /// # Ok(()) }
346    /// ```
347    pub async fn swap_to_hotbar(&self, index: usize, hotbar: u8) -> Result<(), Error> {
348        let opened = self.ensure_screen().await?;
349        let r = async {
350            let slot = self
351                .with(move |ctx| ctx.inventory().slot_of_player(index))
352                .await?
353                .ok_or(Error::Click(ClickError::InvalidSlot))?;
354            self.click(Click::Swap { slot, hotbar }).await
355        }
356        .await;
357        if opened {
358            self.close_window().await?;
359        }
360        r
361    }
362
363    /// Drops the stack at `PlayerInventory` index `index` (all of it, or one with
364    /// `all = false`), with a Q click in the inventory screen.
365    ///
366    /// ```no_run
367    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
368    /// bot.drop_slot(9, true).await?;
369    /// # Ok(()) }
370    /// ```
371    pub async fn drop_slot(&self, index: usize, all: bool) -> Result<(), Error> {
372        let opened = self.ensure_screen().await?;
373        let r = async {
374            let slot = self
375                .with(move |ctx| ctx.inventory().slot_of_player(index))
376                .await?
377                .ok_or(Error::Click(ClickError::InvalidSlot))?;
378            self.click(Click::Drop { slot, all }).await
379        }
380        .await;
381        if opened {
382            self.close_window().await?;
383        }
384        r
385    }
386
387    /// Drops every matching stack from the hotbar and main inventory; returns how many items
388    /// were dropped.
389    ///
390    /// ```no_run
391    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
392    /// let n = bot.toss("rotten_flesh").await?;
393    /// # Ok(()) }
394    /// ```
395    pub async fn toss(&self, item: impl Into<ItemMatch>) -> Result<i32, Error> {
396        let item = item.into();
397        let m = {
398            let item = item.clone();
399            self.with(move |ctx| Matcher::resolve(&item, ctx.version()))
400                .await??
401        };
402        let opened = self.ensure_screen().await?;
403        let r = async {
404            let mut dropped = 0;
405            loop {
406                let m2 = m.clone();
407                let next = self
408                    .with(move |ctx| {
409                        let k = find_player(ctx, &m2)?;
410                        let n = ctx.inventory().player(k)?.count();
411                        Some((ctx.inventory().slot_of_player(k)?, n))
412                    })
413                    .await?;
414                let Some((slot, n)) = next else { break };
415                self.click(Click::Drop { slot, all: true }).await?;
416                dropped += n;
417            }
418            Ok(dropped)
419        }
420        .await;
421        if opened {
422            self.close_window().await?;
423        }
424        r
425    }
426
427    /// Opens the player inventory screen unless a GUI is open; `true` if it opened it.
428    async fn ensure_screen(&self) -> Result<bool, Error> {
429        let need = self.with(|ctx| !ctx.inventory().gui_open()).await?;
430        if !need {
431            return Ok(false);
432        }
433        for _ in 0..CLICK_WAIT {
434            match self.with(|ctx| ctx.open_inventory()).await? {
435                Ok(()) => {
436                    // No click in the tick the 1.8 "open inventory" went out.
437                    self.next_tick().await;
438                    return Ok(true);
439                }
440                Err(ClickRefused::Inventory(ClickError::SameTick | ClickError::Pending)) => {}
441                Err(ClickRefused::Inventory(e)) => return Err(Error::Click(e)),
442                Err(_) => {}
443            }
444            self.next_tick().await;
445        }
446        Err(Error::Timeout)
447    }
448
449    /// Sends a window click in the open screen and waits for the server's confirm. Retries
450    /// (one tick at a time) while the click must wait: the look is turning (clicks only
451    /// while still), another click is in flight, or the same-tick packet rules forbid it.
452    /// Fails with [`Error::Click`] for refusals that will not go away (no screen, invalid
453    /// slot, unpredictable result), [`Error::ClickRejected`] or [`Error::ClickTimedOut`].
454    ///
455    /// ```no_run
456    /// use ghast_client::inventory::Click;
457    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
458    /// bot.click(Click::QuickMove { slot: 0, right: false }).await?; // shift-click slot 0
459    /// # Ok(()) }
460    /// ```
461    pub async fn click(&self, click: Click) -> Result<(), Error> {
462        let start = self.tick();
463        let ticket = loop {
464            match self.with(move |ctx| ctx.click(click)).await? {
465                Ok(t) => break t,
466                Err(ClickRefused::Inventory(
467                    e @ (ClickError::NoScreen
468                    | ClickError::InvalidSlot
469                    | ClickError::InvalidButton
470                    | ClickError::Unpredictable
471                    | ClickError::WindowOpen),
472                )) => return Err(Error::Click(e)),
473                Err(ClickRefused::Dead) => return Err(Error::Died),
474                Err(_) => {}
475            }
476            if self.tick().saturating_sub(start) > CLICK_WAIT {
477                return Err(Error::Timeout);
478            }
479            self.next_tick().await;
480        };
481        if ticket.window_id < 0 {
482            // the 26.x creative screen: its packets are applied as sent, no result follows
483            return Ok(());
484        }
485        // The confirm arrives in a later tick's events (the inventory times out after 40).
486        loop {
487            self.next_tick().await;
488            let r = self
489                .with(move |ctx| {
490                    ctx.events()
491                        .inventory
492                        .clicks
493                        .iter()
494                        .find(|r| ticket.matches(r))
495                        .map(|r| r.outcome)
496                })
497                .await?;
498            match r {
499                Some(ClickOutcome::Accepted) => return Ok(()),
500                Some(ClickOutcome::Rejected) => return Err(Error::ClickRejected),
501                Some(_) => return Err(Error::ClickTimedOut),
502                None => {}
503            }
504            if self.tick().saturating_sub(start) > CLICK_WAIT + 60 {
505                return Err(Error::ClickTimedOut);
506            }
507        }
508    }
509
510    /// Closes the open GUI (container or inventory screen).
511    ///
512    /// ```no_run
513    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
514    /// bot.close_window().await?;
515    /// # Ok(()) }
516    /// ```
517    pub async fn close_window(&self) -> Result<(), Error> {
518        for _ in 0..CLICK_WAIT {
519            match self
520                .with(|ctx| {
521                    if !ctx.inventory().gui_open() {
522                        return Ok(());
523                    }
524                    ctx.close_window()
525                })
526                .await?
527            {
528                Ok(()) => return Ok(()),
529                Err(ClickRefused::Inventory(ClickError::SameTick | ClickError::Pending)) => {}
530                Err(ClickRefused::Inventory(e)) => return Err(Error::Click(e)),
531                Err(_) => {}
532            }
533            self.next_tick().await;
534        }
535        Err(Error::Timeout)
536    }
537
538    /// Right-clicks the container at `pos` (chest, furnace, ...) and waits for its window.
539    ///
540    /// ```no_run
541    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
542    /// if let Some(pos) = bot.find_block("chest", 5.0).await? {
543    ///     let chest = bot.open_container(pos).await?;
544    ///     bot.deposit("cobblestone", None).await?;
545    ///     bot.close_window().await?;
546    /// }
547    /// # Ok(()) }
548    /// ```
549    pub async fn open_container(&self, pos: BlockPos) -> Result<Container, Error> {
550        let mark = self.mark();
551        if self.with(|ctx| ctx.inventory().gui_open()).await? {
552            self.close_window().await?;
553        }
554        self.activate_block(pos).await?;
555        for _ in 0..40 {
556            self.next_tick().await;
557            self.check(mark)?;
558            let w = self
559                .with(|ctx| {
560                    let inv = ctx.inventory();
561                    inv.window().map(|w| Container {
562                        id: w.id(),
563                        kind: w.kind(),
564                        slots: inv.container_len(),
565                    })
566                })
567                .await?;
568            if let Some(c) = w {
569                // The contents come right after the open packet.
570                self.next_tick().await;
571                return Ok(c);
572            }
573        }
574        Err(Error::Timeout)
575    }
576
577    /// The open container's slots (index, stack copy), container part only.
578    ///
579    /// ```no_run
580    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
581    /// for (slot, stack) in bot.container_items().await? {
582    ///     println!("{slot}: {} x{}", stack.id(), stack.count());
583    /// }
584    /// # Ok(()) }
585    /// ```
586    pub async fn container_items(&self) -> Result<Vec<(usize, Stack)>, Error> {
587        self.with(|ctx| {
588            let inv = ctx.inventory();
589            if inv.window().is_none() {
590                return Err(Error::NoWindow);
591            }
592            Ok((0..inv.container_len())
593                .filter_map(|i| inv.slot(i).map(|s| (i, s.clone())))
594                .collect())
595        })
596        .await?
597    }
598
599    /// Shift-clicks matching stacks from the player part of the open container into it,
600    /// whole stacks, until at least `max` items moved (`None`: all). Returns how many items
601    /// left the player inventory (it stops when the container is full).
602    ///
603    /// ```no_run
604    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
605    /// let moved = bot.deposit("cobblestone", Some(128)).await?;
606    /// # Ok(()) }
607    /// ```
608    pub async fn deposit(
609        &self,
610        item: impl Into<ItemMatch>,
611        max: Option<i32>,
612    ) -> Result<i32, Error> {
613        self.transfer(item.into(), max, true).await
614    }
615
616    /// Shift-clicks matching stacks from the open container into the player inventory,
617    /// whole stacks, until at least `max` items moved (`None`: all). Returns how many items
618    /// arrived.
619    ///
620    /// ```no_run
621    /// # async fn f(bot: ghast_ext::Bot) -> Result<(), ghast_ext::Error> {
622    /// let got = bot.withdraw("bread", Some(16)).await?;
623    /// # Ok(()) }
624    /// ```
625    pub async fn withdraw(
626        &self,
627        item: impl Into<ItemMatch>,
628        max: Option<i32>,
629    ) -> Result<i32, Error> {
630        self.transfer(item.into(), max, false).await
631    }
632
633    async fn transfer(
634        &self,
635        item: ItemMatch,
636        max: Option<i32>,
637        deposit: bool,
638    ) -> Result<i32, Error> {
639        let m = self
640            .with(move |ctx| -> Result<(Matcher, i32), Error> {
641                let m = Matcher::resolve(&item, ctx.version())?;
642                if ctx.inventory().window().is_none() {
643                    return Err(Error::NoWindow);
644                }
645                let n = ctx.inventory().count(|s| m.matches(s));
646                Ok((m, n))
647            })
648            .await??;
649        let (m, start) = m;
650        let mut moved = 0;
651        let mut tried: Vec<i16> = Vec::new();
652        while max.is_none_or(|x| moved < x) {
653            let m2 = m.clone();
654            let skip = tried.clone();
655            let slot = self
656                .with(move |ctx| -> Result<Option<i16>, Error> {
657                    let inv = ctx.inventory();
658                    if inv.window().is_none() {
659                        return Err(Error::NoWindow);
660                    }
661                    let n = inv.container_len();
662                    let range = if deposit { n..inv.slot_count() } else { 0..n };
663                    Ok(range
664                        .map(|i| i as i16)
665                        .filter(|i| !skip.contains(i))
666                        .find(|&i| inv.slot(i as usize).is_some_and(|s| m2.matches(s))))
667                })
668                .await??;
669            let Some(slot) = slot else { break };
670            self.click(Click::QuickMove { slot, right: false }).await?;
671            tried.push(slot);
672            let m3 = m.clone();
673            let now = self
674                .with(move |ctx| ctx.inventory().count(|s| m3.matches(s)))
675                .await?;
676            let delta = if deposit { start - now } else { now - start };
677            if delta == moved {
678                break; // nothing moved: full
679            }
680            moved = delta;
681        }
682        Ok(moved)
683    }
684}
685
686#[cfg(all(test, feature = "v1_12_2", feature = "v1_16_5"))]
687mod tests {
688    use super::*;
689
690    #[test]
691    fn sub_versions_use_their_rows_tables() {
692        for (sub, row) in [
693            (GameVersion::V1_12_1, GameVersion::V1_12_2),
694            (GameVersion::V1_16_2, GameVersion::V1_16_5),
695            (GameVersion::V1_16_3, GameVersion::V1_16_5),
696        ] {
697            let id = item_id(row, "diamond_pickaxe");
698            assert!(id.is_some());
699            assert_eq!(item_id(sub, "diamond_pickaxe"), id);
700            assert_eq!(item_name(sub, id.unwrap()), "diamond_pickaxe");
701            assert_eq!(
702                crate::Block::new(sub, 1 << 4).name(),
703                crate::Block::new(row, 1 << 4).name()
704            );
705        }
706    }
707}
708
709#[cfg(all(test, feature = "v26_3"))]
710mod tests_26_3 {
711    use super::*;
712
713    /// 26.3 renumbered items and blocks: the helpers read 26.3's own tables.
714    #[test]
715    fn new_items_and_blocks_resolve() {
716        let v = GameVersion::V26_3;
717        for name in ["poplar_planks", "poplar_door", "diamond_pickaxe", "stone"] {
718            let id = item_id(v, name).unwrap_or_else(|| panic!("{name}: no 26.3 item"));
719            assert_eq!(item_name(v, id), name);
720            assert_eq!(
721                id,
722                i32::from(ghast_data::v26_3::Item::from_name(name).unwrap().id())
723            );
724        }
725        for spec in [
726            "poplar_door",
727            "poplar_fence_gate",
728            "shelf_mushroom",
729            "stone",
730        ] {
731            let s = ghast_data::v26_3::BlockState::parse(spec).expect(spec);
732            assert_eq!(crate::Block::new(v, u32::from(s.id())).name(), spec);
733        }
734    }
735
736    #[cfg(feature = "v26_2")]
737    #[test]
738    fn ids_differ_from_26_2() {
739        // Same name, different ids: no table is shared by accident.
740        let a = item_id(GameVersion::V26_2, "diamond_pickaxe");
741        let b = item_id(GameVersion::V26_3, "diamond_pickaxe");
742        assert!(a.is_some() && b.is_some());
743        assert_eq!(item_id(GameVersion::V26_2, "poplar_planks"), None);
744    }
745}