Skip to main content

dear_imgui_rs/
state_storage.rs

1//! State storage utilities
2//!
3//! Dear ImGui provides a per-window key/value storage (`ImGuiStorage`) that is
4//! used by many widgets and can also be used by custom widgets to persist state.
5//!
6use crate::context::binding::CTX_MUTEX;
7use crate::{ContextThreadLease, Id, ImGuiResult, sys};
8use std::marker::PhantomData;
9use std::ptr::NonNull;
10
11/// A non-owning reference to an `ImGuiStorage` belonging to the current context.
12#[derive(Copy, Clone, Debug)]
13pub struct StateStorage<'ui> {
14    raw: NonNull<sys::ImGuiStorage>,
15    _phantom: PhantomData<&'ui mut sys::ImGuiStorage>,
16}
17
18impl<'ui> StateStorage<'ui> {
19    /// # Safety
20    /// `raw` must point to an initialized `ImGuiStorage` that remains live and accessible
21    /// on this thread for `'ui`, including through any copies of the returned view. Its
22    /// allocation must remain exclusively owned by the storage and its keys must stay sorted.
23    /// A Context or [`ContextThreadLease`] must cover any mutation that can allocate or free
24    /// entries through Dear ImGui.
25    pub unsafe fn from_raw(raw: *mut sys::ImGuiStorage) -> Self {
26        let raw = NonNull::new(raw).expect("StateStorage::from_raw() requires non-null pointer");
27        Self {
28            raw,
29            _phantom: PhantomData,
30        }
31    }
32
33    /// Returns the raw `ImGuiStorage*`.
34    pub fn as_raw(self) -> *mut sys::ImGuiStorage {
35        self.raw.as_ptr()
36    }
37
38    /// Clears all storage entries.
39    pub fn clear(&mut self) {
40        let _guard = CTX_MUTEX.lock();
41        unsafe { sys::ImGuiStorage_Clear(self.raw.as_ptr()) }
42    }
43
44    pub fn get_int(&self, key: Id, default: i32) -> i32 {
45        unsafe { sys::ImGuiStorage_GetInt(self.raw.as_ptr(), key.raw(), default) }
46    }
47
48    pub fn set_int(&mut self, key: Id, value: i32) {
49        let _guard = CTX_MUTEX.lock();
50        unsafe { sys::ImGuiStorage_SetInt(self.raw.as_ptr(), key.raw(), value) }
51    }
52
53    pub fn get_bool(&self, key: Id, default: bool) -> bool {
54        unsafe { sys::ImGuiStorage_GetBool(self.raw.as_ptr(), key.raw(), default) }
55    }
56
57    pub fn set_bool(&mut self, key: Id, value: bool) {
58        self.set_int(key, i32::from(value));
59    }
60
61    pub fn get_float(&self, key: Id, default: f32) -> f32 {
62        unsafe { sys::ImGuiStorage_GetFloat(self.raw.as_ptr(), key.raw(), default) }
63    }
64
65    pub fn set_float(&mut self, key: Id, value: f32) {
66        let _guard = CTX_MUTEX.lock();
67        unsafe { sys::ImGuiStorage_SetFloat(self.raw.as_ptr(), key.raw(), value) }
68    }
69}
70
71/// Owns an `ImGuiStorage` and clears it on drop.
72///
73/// This is useful when you want to keep widget state outside of the current
74/// window storage (e.g. sharing state across windows or providing custom storage
75/// for a widget subtree via [`crate::Ui::with_state_storage`]).
76#[derive(Debug)]
77pub struct OwnedStateStorage {
78    raw: sys::ImGuiStorage,
79    _thread_lease: ContextThreadLease,
80}
81
82impl OwnedStateStorage {
83    /// Creates storage on the Dear ImGui owner thread.
84    ///
85    /// # Panics
86    ///
87    /// Panics if the thread lease cannot be acquired. Use [`Self::try_new`] to handle this error.
88    pub fn new() -> Self {
89        Self::try_new().expect("failed to acquire Dear ImGui thread ownership for state storage")
90    }
91
92    /// Reserves the current thread for this storage's native entries and creates empty storage.
93    pub fn try_new() -> ImGuiResult<Self> {
94        let thread_lease = ContextThreadLease::acquire()?;
95        Ok(Self {
96            raw: sys::ImGuiStorage::default(),
97            _thread_lease: thread_lease,
98        })
99    }
100
101    /// Borrows the native storage for direct mutation.
102    ///
103    /// # Safety
104    ///
105    /// Preserve the native vector's allocation, length, capacity, and sorted-key invariants.
106    /// This storage must remain the sole owner of any allocation it will clear on drop.
107    ///
108    /// ```compile_fail,E0133
109    /// let mut storage = dear_imgui_rs::OwnedStateStorage::new();
110    /// let _ = storage.as_mut();
111    /// ```
112    pub unsafe fn as_mut(&mut self) -> &mut sys::ImGuiStorage {
113        &mut self.raw
114    }
115
116    pub fn as_ref(&self) -> &sys::ImGuiStorage {
117        &self.raw
118    }
119
120    pub fn as_raw_mut(&mut self) -> *mut sys::ImGuiStorage {
121        &mut self.raw as *mut sys::ImGuiStorage
122    }
123
124    pub fn as_raw(&self) -> *const sys::ImGuiStorage {
125        &self.raw as *const sys::ImGuiStorage
126    }
127}
128
129impl Default for OwnedStateStorage {
130    fn default() -> Self {
131        Self::new()
132    }
133}
134
135impl Drop for OwnedStateStorage {
136    fn drop(&mut self) {
137        unsafe { StateStorage::from_raw(self.as_raw_mut()) }.clear();
138    }
139}
140
141struct StateStorageOverride {
142    window: NonNull<sys::ImGuiWindow>,
143    previous: *mut sys::ImGuiStorage,
144}
145
146impl Drop for StateStorageOverride {
147    fn drop(&mut self) {
148        // The frame borrow keeps the window alive even if the closure changed the current window.
149        unsafe { (*self.window.as_ptr()).DC.StateStorage = self.previous };
150    }
151}
152
153impl crate::ui::Ui {
154    /// Accesses the current window's state storage inside a non-escaping closure.
155    ///
156    /// The storage view cannot outlive this call. The owning context remains current for the
157    /// duration of `f`, including nested calls into other contexts.
158    #[doc(alias = "GetStateStorage")]
159    pub fn with_current_state_storage<R>(
160        &self,
161        f: impl for<'storage> FnOnce(StateStorage<'storage>) -> R,
162    ) -> R {
163        self.run_with_bound_context(|| unsafe {
164            f(StateStorage::from_raw(sys::igGetStateStorage()))
165        })
166    }
167
168    /// Overrides the current state storage while `f` runs.
169    ///
170    /// The owning context remains current throughout the call. Nested overrides restore in LIFO
171    /// order, including if `f` panics or leaves a different window current. The replacement
172    /// storage and its scoped view cannot escape the closure.
173    ///
174    /// ```compile_fail
175    /// use dear_imgui_rs::{Context, OwnedStateStorage, StateStorage};
176    ///
177    /// let mut context = Context::create();
178    /// let ui = context.frame();
179    /// let mut replacement = OwnedStateStorage::new();
180    /// let escaped: StateStorage<'_> =
181    ///     ui.with_state_storage(&mut replacement, |storage| storage);
182    /// # let _ = escaped;
183    /// ```
184    #[doc(alias = "SetStateStorage")]
185    pub fn with_state_storage<R>(
186        &self,
187        storage: &mut OwnedStateStorage,
188        f: impl for<'storage> FnOnce(StateStorage<'storage>) -> R,
189    ) -> R {
190        self.run_with_bound_context(|| {
191            let replacement = storage.as_raw_mut();
192            let scoped_storage = unsafe { StateStorage::from_raw(replacement) };
193            let window = NonNull::new(unsafe { sys::igGetCurrentWindowRead() })
194                .expect("with_state_storage requires a current window");
195            let previous = unsafe {
196                std::ptr::replace(&raw mut (*window.as_ptr()).DC.StateStorage, replacement)
197            };
198            let storage_override = StateStorageOverride { window, previous };
199            let result = f(scoped_storage);
200            drop(storage_override);
201            result
202        })
203    }
204
205    /// Set the storage ID for the next item.
206    #[doc(alias = "SetNextItemStorageID")]
207    pub fn set_next_item_storage_id(&self, storage_id: Id) {
208        self.run_with_bound_context(|| unsafe { sys::igSetNextItemStorageID(storage_id.raw()) });
209    }
210}