Skip to main content

dear_imgui_rs/draw/list/
texture.rs

1use std::marker::PhantomData;
2
3use crate::sys;
4
5use super::DrawListMut;
6
7/// Tracks a texture pushed to a draw-list texture stack.
8///
9/// The texture is popped when the token is dropped or when [`Self::pop`] is
10/// called explicitly.
11#[must_use]
12pub struct DrawListTextureToken<'draw_list, 'tex> {
13    draw_list: *mut sys::ImDrawList,
14    _phantom: PhantomData<(&'draw_list (), &'tex mut crate::texture::TextureData)>,
15}
16
17impl<'draw_list, 'tex> DrawListTextureToken<'draw_list, 'tex> {
18    fn new(draw_list: *mut sys::ImDrawList) -> Self {
19        Self {
20            draw_list,
21            _phantom: PhantomData,
22        }
23    }
24
25    /// Pop the texture immediately instead of waiting for drop.
26    #[doc(alias = "PopTexture")]
27    pub fn pop(self) {}
28
29    /// Pop the texture immediately instead of waiting for drop.
30    #[doc(alias = "PopTexture")]
31    pub fn end(self) {}
32}
33
34impl Drop for DrawListTextureToken<'_, '_> {
35    fn drop(&mut self) {
36        unsafe { sys::ImDrawList_PopTexture(self.draw_list) }
37    }
38}
39
40impl<'ui> DrawListMut<'ui> {
41    // channels_split is provided on DrawListMut
42
43    /// Push a texture on the drawlist texture stack (ImGui 1.92+).
44    ///
45    /// While pushed, image and primitives will use this texture unless otherwise specified.
46    /// The returned token pops the texture when dropped.
47    ///
48    /// Example:
49    /// ```no_run
50    /// # use dear_imgui_rs::*;
51    /// # fn demo(ui: &Ui) {
52    /// let dl = ui.get_window_draw_list();
53    /// let tex = texture::TextureId::new(1);
54    /// let _texture = dl.push_texture(tex);
55    /// dl.add_image(tex, [10.0,10.0], [110.0,110.0], [0.0,0.0], [1.0,1.0], Color::WHITE);
56    /// # }
57    /// ```
58    #[doc(alias = "PushTexture")]
59    pub fn push_texture<'tex>(
60        &self,
61        texture: impl Into<crate::texture::TextureRef<'tex>>,
62    ) -> DrawListTextureToken<'_, 'tex> {
63        let tex_ref = texture.into().raw();
64        unsafe { sys::ImDrawList_PushTexture(self.draw_list, tex_ref) };
65        DrawListTextureToken::new(self.draw_list)
66    }
67
68    /// Push a texture, run `f`, then pop the texture.
69    ///
70    /// The texture is popped during unwinding if `f` panics.
71    #[doc(alias = "PushTexture", alias = "PopTexture")]
72    pub fn with_texture<'tex, R>(
73        &self,
74        texture: impl Into<crate::texture::TextureRef<'tex>>,
75        f: impl FnOnce() -> R,
76    ) -> R {
77        let _texture = self.push_texture(texture);
78        f()
79    }
80}