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