Skip to main content

azalea/
container.rs

1use std::{fmt, fmt::Debug};
2
3use azalea_chat::FormattedText;
4use azalea_client::{
5    client_inventory::{CloseContainerEvent, ContainerClickEvent},
6    packet::game::ReceiveGamePacketEvent,
7};
8use azalea_core::position::BlockPos;
9use azalea_entity::inventory::Inventory;
10use azalea_inventory::{
11    Menu,
12    operations::{ClickOperation, PickupClick, QuickMoveClick},
13};
14use azalea_physics::collision::BlockWithShape;
15use azalea_protocol::packets::game::ClientboundGamePacket;
16use azalea_registry::item::ItemStack;
17use bevy_app::{App, Plugin, Update};
18use bevy_ecs::{component::Component, prelude::MessageReader, system::Commands};
19use derive_more::Deref;
20
21use crate::{Client, client_impl::error::AzaleaResult};
22
23pub struct ContainerPlugin;
24impl Plugin for ContainerPlugin {
25    fn build(&self, app: &mut App) {
26        app.add_systems(Update, handle_menu_opened_event);
27    }
28}
29
30impl Client {
31    /// Open a container in the world, like a chest.
32    ///
33    /// Use [`Client::open_inventory`] to open your own inventory.
34    ///
35    /// This function times out after 5 seconds (100 ticks). Use
36    /// [`Self::open_container_at_with_timeout_ticks`] if you would like to
37    /// configure this.
38    ///
39    /// ```
40    /// # use azalea::{prelude::*, registry::builtin::BlockKind};
41    /// # async fn example(mut bot: azalea::Client) -> azalea::error::AzaleaResult<()> {
42    /// let target_pos = bot
43    ///     .world()?
44    ///     .read()
45    ///     .find_block(bot.position()?, &BlockKind::Chest.into());
46    /// let Some(target_pos) = target_pos else {
47    ///     bot.chat("no chest found");
48    ///     return Ok(());
49    /// };
50    /// let container = bot.open_container_at(target_pos).await?;
51    /// # Ok(())
52    /// # }
53    /// ```
54    pub async fn open_container_at(&self, pos: BlockPos) -> AzaleaResult<Option<ContainerHandle>> {
55        self.open_container_at_with_timeout_ticks(pos, Some(20 * 5))
56            .await
57    }
58
59    /// Open a container in the world, or time out after a specified amount of
60    /// ticks.
61    ///
62    /// See [`Self::open_container_at`] for more information. That function
63    /// defaults to a timeout of 5 seconds (100 ticks), which is usually good
64    /// enough. However to detect failures faster or to account for server
65    /// lag, you may find it useful to adjust the timeout to a different
66    /// value.
67    ///
68    /// The timeout is measured in game ticks (on the client, not the server),
69    /// i.e. 1/20th of a second.
70    pub async fn open_container_at_with_timeout_ticks(
71        &self,
72        pos: BlockPos,
73        timeout_ticks: Option<usize>,
74    ) -> AzaleaResult<Option<ContainerHandle>> {
75        let mut ticks = self.get_tick_broadcaster();
76        // wait until it's not air (up to 10 ticks)
77        for _ in 0..10 {
78            let block = self
79                .world()?
80                .read()
81                .get_block_state(pos)
82                .unwrap_or_default();
83            if !block.is_collision_shape_empty() {
84                break;
85            }
86            let _ = ticks.recv().await;
87        }
88
89        self.ecs
90            .write()
91            .entity_mut(self.entity)
92            .insert(WaitingForInventoryOpen);
93        self.block_interact(pos);
94
95        self.wait_for_container_open(timeout_ticks).await
96    }
97
98    /// Wait until a container is open, up to the specified number of ticks.
99    ///
100    /// Returns `None` if the container was immediately opened and closed, or if
101    /// the timeout expired.
102    ///
103    /// If `timeout_ticks` is None, there will be no timeout.
104    pub async fn wait_for_container_open(
105        &self,
106        timeout_ticks: Option<usize>,
107    ) -> AzaleaResult<Option<ContainerHandle>> {
108        let mut ticks = self.get_tick_broadcaster();
109        let mut elapsed_ticks = 0;
110        while ticks.recv().await.is_ok() {
111            let ecs = self.ecs.read();
112            if ecs.get::<WaitingForInventoryOpen>(self.entity).is_none() {
113                break;
114            }
115
116            elapsed_ticks += 1;
117            if let Some(timeout_ticks) = timeout_ticks
118                && elapsed_ticks >= timeout_ticks
119            {
120                return Ok(None);
121            }
122        }
123
124        let inventory_id = self.component::<Inventory>()?.id;
125        if inventory_id == 0 {
126            Ok(None)
127        } else {
128            Ok(Some(ContainerHandle::new(inventory_id, self.clone())))
129        }
130    }
131
132    /// Open the player's inventory.
133    ///
134    /// This will return None if another container is open.
135    ///
136    /// Note that this will send a packet to the server once it's dropped. Also,
137    /// due to how it's implemented, you could call this function multiple times
138    /// while another inventory handle already exists (but you shouldn't).
139    ///
140    /// If you just want to get the items in the player's inventory without
141    /// sending any packets, use [`Client::menu`], [`Menu::player_slots_range`],
142    /// and [`Menu::slots`].
143    pub fn open_inventory(&self) -> AzaleaResult<Option<ContainerHandle>> {
144        let inventory = self.component::<Inventory>()?;
145        Ok(if inventory.id == 0 {
146            Some(ContainerHandle::new(0, self.clone()))
147        } else {
148            None
149        })
150    }
151
152    /// Returns a [`ContainerHandleRef`] to the client's currently open
153    /// container, or their inventory.
154    ///
155    /// This will not send a packet to close the container when it's dropped,
156    /// which may cause anticheat compatibility issues if you modify your
157    /// inventory without closing it afterwards.
158    ///
159    /// To simulate opening your own inventory (like pressing 'e') in a way that
160    /// won't trigger anticheats, use [`Client::open_inventory`].
161    ///
162    /// To open a container in the world, use [`Client::open_container_at`].
163    pub fn get_inventory(&self) -> AzaleaResult<ContainerHandleRef> {
164        Ok(ContainerHandleRef::new(
165            self.component::<Inventory>()?.id,
166            self.clone(),
167        ))
168    }
169
170    /// Get the item in the bot's hotbar that is currently being held in its
171    /// main hand.
172    pub fn get_held_item(&self) -> AzaleaResult<ItemStack> {
173        Ok(self.component::<Inventory>()?.held_item().clone())
174    }
175}
176
177/// A handle to a container that may be open.
178///
179/// This does not close the container when it's dropped. See [`ContainerHandle`]
180/// if that behavior is desired.
181pub struct ContainerHandleRef {
182    id: i32,
183    client: Client,
184}
185impl Debug for ContainerHandleRef {
186    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187        f.debug_struct("ContainerHandle")
188            .field("id", &self.id())
189            .finish()
190    }
191}
192impl ContainerHandleRef {
193    pub fn new(id: i32, client: Client) -> Self {
194        Self { id, client }
195    }
196
197    pub fn close(&self) {
198        self.client.ecs.write().trigger(CloseContainerEvent {
199            entity: self.client.entity,
200            id: self.id,
201        });
202    }
203
204    /// Get the ID of the container.
205    ///
206    /// If this is 0, that means it's the player's inventory. Otherwise, the
207    /// number isn't really meaningful since only one container can be open
208    /// at a time.
209    pub fn id(&self) -> i32 {
210        self.id
211    }
212
213    /// Returns the menu of the container.
214    ///
215    /// If the container is closed, this will return `None`.
216    ///
217    /// Note that any modifications you make to the `Menu` you're given will not
218    /// actually cause any packets to be sent. If you're trying to modify your
219    /// inventory, use [`Self::click`] instead
220    pub fn menu(&self) -> AzaleaResult<Option<Box<Menu>>> {
221        self.map_inventory(|inv| {
222            if self.id == 0 {
223                inv.inventory_menu.clone()
224            } else {
225                inv.container_menu.clone().unwrap()
226            }
227        })
228    }
229
230    fn map_inventory<R>(&self, f: impl FnOnce(&Inventory) -> R) -> AzaleaResult<Option<R>> {
231        self.client.query_self::<&Inventory, _>(|inv| {
232            if inv.id == self.id {
233                Some(f(inv))
234            } else {
235                // a different inventory is open
236                None
237            }
238        })
239    }
240
241    /// Returns the item slots in the container, not including the player's
242    /// inventory.
243    ///
244    /// If the container is closed, this will return `None`.
245    pub fn contents(&self) -> Option<Vec<ItemStack>> {
246        Some(self.menu().ok()??.contents())
247    }
248
249    /// Return the contents of the menu, including the player's inventory.
250    ///
251    /// If the container is closed, this will return `None`.
252    pub fn slots(&self) -> Option<Vec<ItemStack>> {
253        Some(self.menu().ok()??.slots())
254    }
255
256    /// Returns the title of the container, or `None` if no container is open.
257    ///
258    /// ```no_run
259    /// # use azalea::prelude::*;
260    /// # fn example(bot: &Client) -> azalea::error::AzaleaResult<()> {
261    /// let inventory = bot.get_inventory()?;
262    /// let inventory_title = inventory.title().unwrap_or_default().to_string();
263    /// // would be true if an unnamed chest is open
264    /// assert_eq!(inventory_title, "Chest");
265    /// # Ok(())
266    /// # }
267    /// ```
268    pub fn title(&self) -> Option<FormattedText> {
269        self.map_inventory(|inv| inv.container_menu_title.clone())
270            .ok()??
271            .map(|t| *t)
272    }
273
274    /// A shortcut for [`Self::click`] with `PickupClick::Left`.
275    pub fn left_click(&self, slot: impl Into<usize>) {
276        self.click(PickupClick::Left {
277            slot: Some(slot.into() as u16),
278        });
279    }
280    /// A shortcut for [`Self::click`] with `QuickMoveClick::Left`.
281    pub fn shift_click(&self, slot: impl Into<usize>) {
282        self.click(QuickMoveClick::Left {
283            slot: slot.into() as u16,
284        });
285    }
286    /// A shortcut for [`Self::click`] with `PickupClick::Right`.
287    pub fn right_click(&self, slot: impl Into<usize>) {
288        self.click(PickupClick::Right {
289            slot: Some(slot.into() as u16),
290        });
291    }
292
293    /// Simulate a click in the container and send the packet to perform the
294    /// action.
295    pub fn click(&self, operation: impl Into<ClickOperation>) {
296        let operation = operation.into();
297        self.client.ecs.write().trigger(ContainerClickEvent {
298            entity: self.client.entity,
299            window_id: self.id,
300            operation,
301        });
302    }
303}
304
305/// A handle to the open container.
306///
307/// The container will be closed once this is dropped.
308#[derive(Deref)]
309pub struct ContainerHandle(ContainerHandleRef);
310
311impl Drop for ContainerHandle {
312    fn drop(&mut self) {
313        self.0.close();
314    }
315}
316impl Debug for ContainerHandle {
317    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
318        f.debug_struct("ContainerHandle")
319            .field("id", &self.id())
320            .finish()
321    }
322}
323impl ContainerHandle {
324    fn new(id: i32, client: Client) -> Self {
325        Self(ContainerHandleRef { id, client })
326    }
327
328    /// Closes the inventory by dropping the handle.
329    pub fn close(self) {
330        // implicitly calls drop
331    }
332}
333
334#[derive(Component, Debug)]
335pub struct WaitingForInventoryOpen;
336
337pub fn handle_menu_opened_event(
338    mut commands: Commands,
339    mut events: MessageReader<ReceiveGamePacketEvent>,
340) {
341    for event in events.read() {
342        if let ClientboundGamePacket::ContainerSetContent { .. } = event.packet.as_ref() {
343            commands
344                .entity(event.entity)
345                .remove::<WaitingForInventoryOpen>();
346        }
347    }
348}