dear-imgui-rs 0.12.0

High-level Rust bindings to Dear ImGui v1.92.7 with docking, WGPU/GL backends, and extensions (ImPlot/ImPlot3D, ImNodes, ImGuizmo, file browser, reflection-based UI)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
//! Popups and modals
//!
//! Popup windows (context menus, modals) with builders and token helpers to
//! ensure balanced begin/end calls.
//!
#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::as_conversions
)]
use crate::MouseButton;
use crate::sys;
use crate::ui::Ui;
use crate::window::WindowFlags;

/// # Popup Widgets
impl Ui {
    /// Instructs ImGui that a popup is open.
    ///
    /// You should **call this function once** while calling any of the following per-frame:
    ///
    /// - [`begin_popup`](Self::begin_popup)
    /// - [`popup`](Self::popup)
    /// - [`begin_modal_popup`](Self::begin_modal_popup)
    /// - [`modal_popup`](Self::modal_popup)
    ///
    /// The confusing aspect to popups is that ImGui holds control over the popup itself.
    #[doc(alias = "OpenPopup")]
    pub fn open_popup(&self, str_id: impl AsRef<str>) {
        let str_id_ptr = self.scratch_txt(str_id);
        unsafe { sys::igOpenPopup_Str(str_id_ptr, PopupFlags::NONE.bits()) }
    }

    /// Instructs ImGui that a popup is open with flags.
    #[doc(alias = "OpenPopup")]
    pub fn open_popup_with_flags(&self, str_id: impl AsRef<str>, flags: PopupFlags) {
        let str_id_ptr = self.scratch_txt(str_id);
        unsafe { sys::igOpenPopup_Str(str_id_ptr, flags.bits()) }
    }

    /// Opens a popup when the last item is clicked (typically right-click).
    ///
    /// If `str_id` is `None`, the popup is associated with the last item ID.
    #[doc(alias = "OpenPopupOnItemClick")]
    pub fn open_popup_on_item_click(&self, str_id: Option<&str>) {
        self.open_popup_on_item_click_with_flags(str_id, PopupContextOptions::new());
    }

    /// Opens a popup when the last item is clicked, with explicit flags.
    #[doc(alias = "OpenPopupOnItemClick")]
    pub fn open_popup_on_item_click_with_flags(
        &self,
        str_id: Option<&str>,
        flags: impl Into<PopupContextOptions>,
    ) {
        let options = flags.into();
        let str_id_ptr = str_id
            .map(|s| self.scratch_txt(s))
            .unwrap_or(std::ptr::null());
        unsafe { sys::igOpenPopupOnItemClick(str_id_ptr, options.raw()) }
    }

    /// Construct a popup that can have any kind of content.
    ///
    /// This should be called *per frame*, whereas [`open_popup`](Self::open_popup) should be called *once*
    /// to signal that this popup is active.
    #[doc(alias = "BeginPopup")]
    pub fn begin_popup(&self, str_id: impl AsRef<str>) -> Option<PopupToken<'_>> {
        self.begin_popup_with_flags(str_id, WindowFlags::empty())
    }

    /// Construct a popup with window flags.
    #[doc(alias = "BeginPopup")]
    pub fn begin_popup_with_flags(
        &self,
        str_id: impl AsRef<str>,
        flags: WindowFlags,
    ) -> Option<PopupToken<'_>> {
        let str_id_ptr = self.scratch_txt(str_id);
        let render = unsafe { sys::igBeginPopup(str_id_ptr, flags.bits()) };

        if render {
            Some(PopupToken::new(self))
        } else {
            None
        }
    }

    /// Construct a popup that can have any kind of content.
    ///
    /// This should be called *per frame*, whereas [`open_popup`](Self::open_popup) should be called *once*
    /// to signal that this popup is active.
    #[doc(alias = "BeginPopup")]
    pub fn popup<F>(&self, str_id: impl AsRef<str>, f: F)
    where
        F: FnOnce(),
    {
        if let Some(_token) = self.begin_popup(str_id) {
            f();
        }
    }

    /// Creates a modal popup.
    ///
    /// Modal popups block interaction with the rest of the application until closed.
    #[doc(alias = "BeginPopupModal")]
    pub fn begin_modal_popup(&self, name: impl AsRef<str>) -> Option<ModalPopupToken<'_>> {
        let name_ptr = self.scratch_txt(name);
        let render = unsafe {
            sys::igBeginPopupModal(name_ptr, std::ptr::null_mut(), WindowFlags::empty().bits())
        };

        if render {
            Some(ModalPopupToken::new(self))
        } else {
            None
        }
    }

    /// Creates a modal popup with an opened-state tracking variable.
    ///
    /// Passing `opened` enables the title-bar close button (X). When clicked, ImGui will set
    /// `*opened = false` and close the popup.
    ///
    /// Notes:
    /// - You still need to call [`open_popup`](Self::open_popup) once to open the modal.
    /// - To pass window flags, use [`begin_modal_popup_config`](Self::begin_modal_popup_config).
    #[doc(alias = "BeginPopupModal")]
    pub fn begin_modal_popup_with_opened(
        &self,
        name: impl AsRef<str>,
        opened: &mut bool,
    ) -> Option<ModalPopupToken<'_>> {
        let name_ptr = self.scratch_txt(name);
        let opened_ptr = opened as *mut bool;
        let render =
            unsafe { sys::igBeginPopupModal(name_ptr, opened_ptr, WindowFlags::empty().bits()) };

        if render {
            Some(ModalPopupToken::new(self))
        } else {
            None
        }
    }

    /// Creates a modal popup builder.
    pub fn begin_modal_popup_config<'a>(&'a self, name: &'a str) -> ModalPopup<'a> {
        ModalPopup {
            name,
            opened: None,
            flags: WindowFlags::empty(),
            ui: self,
        }
    }

    /// Creates a modal popup and runs a closure to construct the contents.
    ///
    /// Returns the result of the closure if the popup is open.
    pub fn modal_popup<F, R>(&self, name: impl AsRef<str>, f: F) -> Option<R>
    where
        F: FnOnce() -> R,
    {
        self.begin_modal_popup(name).map(|_token| f())
    }

    /// Creates a modal popup with an opened-state tracking variable and runs a closure to
    /// construct the contents.
    ///
    /// Returns the result of the closure if the popup is open.
    pub fn modal_popup_with_opened<F, R>(
        &self,
        name: impl AsRef<str>,
        opened: &mut bool,
        f: F,
    ) -> Option<R>
    where
        F: FnOnce() -> R,
    {
        self.begin_modal_popup_with_opened(name, opened)
            .map(|_token| f())
    }

    /// Closes the current popup.
    #[doc(alias = "CloseCurrentPopup")]
    pub fn close_current_popup(&self) {
        unsafe {
            sys::igCloseCurrentPopup();
        }
    }

    /// Returns true if the popup is open.
    #[doc(alias = "IsPopupOpen")]
    pub fn is_popup_open(&self, str_id: impl AsRef<str>) -> bool {
        let str_id_ptr = self.scratch_txt(str_id);
        unsafe { sys::igIsPopupOpen_Str(str_id_ptr, PopupFlags::NONE.bits()) }
    }

    /// Returns true if the popup is open with flags.
    #[doc(alias = "IsPopupOpen")]
    pub fn is_popup_open_with_flags(&self, str_id: impl AsRef<str>, flags: PopupFlags) -> bool {
        let str_id_ptr = self.scratch_txt(str_id);
        unsafe { sys::igIsPopupOpen_Str(str_id_ptr, flags.bits()) }
    }

    /// Begin a popup context menu for the last item.
    #[doc(alias = "BeginPopupContextItem")]
    pub fn begin_popup_context_item(&self) -> Option<PopupToken<'_>> {
        self.begin_popup_context_item_with_flags(None, PopupContextOptions::new())
    }

    /// Begin a popup context menu for the last item with a custom label.
    #[doc(alias = "BeginPopupContextItem")]
    pub fn begin_popup_context_item_with_label(
        &self,
        str_id: Option<&str>,
    ) -> Option<PopupToken<'_>> {
        self.begin_popup_context_item_with_flags(str_id, PopupContextOptions::new())
    }

    /// Begin a popup context menu for the last item with explicit popup flags.
    #[doc(alias = "BeginPopupContextItem")]
    pub fn begin_popup_context_item_with_flags(
        &self,
        str_id: Option<&str>,
        flags: impl Into<PopupContextOptions>,
    ) -> Option<PopupToken<'_>> {
        let options = flags.into();
        let str_id_ptr = str_id
            .map(|s| self.scratch_txt(s))
            .unwrap_or(std::ptr::null());

        let render = unsafe { sys::igBeginPopupContextItem(str_id_ptr, options.raw()) };

        render.then(|| PopupToken::new(self))
    }

    /// Begin a popup context menu for the current window.
    #[doc(alias = "BeginPopupContextWindow")]
    pub fn begin_popup_context_window(&self) -> Option<PopupToken<'_>> {
        self.begin_popup_context_window_with_flags(None, PopupContextOptions::new())
    }

    /// Begin a popup context menu for the current window with a custom label.
    #[doc(alias = "BeginPopupContextWindow")]
    pub fn begin_popup_context_window_with_label(
        &self,
        str_id: Option<&str>,
    ) -> Option<PopupToken<'_>> {
        self.begin_popup_context_window_with_flags(str_id, PopupContextOptions::new())
    }

    /// Begin a popup context menu for the current window with explicit popup flags.
    #[doc(alias = "BeginPopupContextWindow")]
    pub fn begin_popup_context_window_with_flags(
        &self,
        str_id: Option<&str>,
        flags: impl Into<PopupContextOptions>,
    ) -> Option<PopupToken<'_>> {
        let options = flags.into();
        let str_id_ptr = str_id
            .map(|s| self.scratch_txt(s))
            .unwrap_or(std::ptr::null());

        let render = unsafe { sys::igBeginPopupContextWindow(str_id_ptr, options.raw()) };

        render.then(|| PopupToken::new(self))
    }

    /// Begin a popup context menu for empty space (void).
    #[doc(alias = "BeginPopupContextVoid")]
    pub fn begin_popup_context_void(&self) -> Option<PopupToken<'_>> {
        self.begin_popup_context_void_with_flags(None, PopupContextOptions::new())
    }

    /// Begin a popup context menu for empty space with a custom label.
    #[doc(alias = "BeginPopupContextVoid")]
    pub fn begin_popup_context_void_with_label(
        &self,
        str_id: Option<&str>,
    ) -> Option<PopupToken<'_>> {
        self.begin_popup_context_void_with_flags(str_id, PopupContextOptions::new())
    }

    /// Begin a popup context menu for empty space (void) with explicit popup flags.
    #[doc(alias = "BeginPopupContextVoid")]
    pub fn begin_popup_context_void_with_flags(
        &self,
        str_id: Option<&str>,
        flags: impl Into<PopupContextOptions>,
    ) -> Option<PopupToken<'_>> {
        let options = flags.into();
        let str_id_ptr = str_id
            .map(|s| self.scratch_txt(s))
            .unwrap_or(std::ptr::null());

        let render = unsafe { sys::igBeginPopupContextVoid(str_id_ptr, options.raw()) };

        render.then(|| PopupToken::new(self))
    }
}

bitflags::bitflags! {
    /// Independent flags for popup functions.
    ///
    /// Context popup mouse button selection is a single-choice setting
    /// represented by [`PopupContextMouseButton`].
    #[repr(transparent)]
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    pub struct PopupFlags: i32 {
        /// No flags
        const NONE = sys::ImGuiPopupFlags_None as i32;
        /// Do not reopen the same popup if already open.
        const NO_REOPEN = sys::ImGuiPopupFlags_NoReopen as i32;
        /// For OpenPopup*(), BeginPopupContext*(): don't open if there's already a popup at the same level of the popup stack
        const NO_OPEN_OVER_EXISTING_POPUP = sys::ImGuiPopupFlags_NoOpenOverExistingPopup as i32;
        /// For BeginPopupContext*(): don't return true when hovering items, only when hovering empty space
        const NO_OPEN_OVER_ITEMS = sys::ImGuiPopupFlags_NoOpenOverItems as i32;
        /// For IsPopupOpen(): ignore the ImGuiID parameter and test for any popup
        const ANY_POPUP_ID = sys::ImGuiPopupFlags_AnyPopupId as i32;
        /// For IsPopupOpen(): search/test at any level of the popup stack (default test in the current level)
        const ANY_POPUP_LEVEL = sys::ImGuiPopupFlags_AnyPopupLevel as i32;
        /// For IsPopupOpen(): test for any popup
        const ANY_POPUP = Self::ANY_POPUP_ID.bits() | Self::ANY_POPUP_LEVEL.bits();
    }
}

/// Single mouse button used by popup context helpers.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum PopupContextMouseButton {
    /// Open on left mouse release.
    Left,
    /// Open on right mouse release.
    #[default]
    Right,
    /// Open on middle mouse release.
    Middle,
}

impl PopupContextMouseButton {
    #[inline]
    const fn raw(self) -> i32 {
        match self {
            Self::Left => sys::ImGuiPopupFlags_MouseButtonLeft as i32,
            Self::Right => sys::ImGuiPopupFlags_MouseButtonRight as i32,
            Self::Middle => sys::ImGuiPopupFlags_MouseButtonMiddle as i32,
        }
    }
}

impl From<MouseButton> for PopupContextMouseButton {
    fn from(button: MouseButton) -> Self {
        match button {
            MouseButton::Left => Self::Left,
            MouseButton::Right => Self::Right,
            MouseButton::Middle => Self::Middle,
            MouseButton::Extra1 | MouseButton::Extra2 => {
                panic!(
                    "Dear ImGui popup context helpers only support left, right, and middle buttons"
                )
            }
        }
    }
}

/// Complete popup options assembled from independent flags and optional
/// single mouse button.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PopupContextOptions {
    pub flags: PopupFlags,
    pub mouse_button: PopupContextMouseButton,
}

impl PopupContextOptions {
    pub const fn new() -> Self {
        Self {
            flags: PopupFlags::NONE,
            mouse_button: PopupContextMouseButton::Right,
        }
    }

    pub fn flags(mut self, flags: PopupFlags) -> Self {
        self.flags = flags;
        self
    }

    pub fn mouse_button(mut self, button: impl Into<PopupContextMouseButton>) -> Self {
        self.mouse_button = button.into();
        self
    }

    pub fn bits(self) -> i32 {
        self.raw()
    }

    #[inline]
    pub(crate) fn raw(self) -> i32 {
        self.flags.bits() | self.mouse_button.raw()
    }
}

impl Default for PopupContextOptions {
    fn default() -> Self {
        Self::new()
    }
}

impl From<PopupFlags> for PopupContextOptions {
    fn from(flags: PopupFlags) -> Self {
        Self::new().flags(flags)
    }
}

impl From<PopupContextMouseButton> for PopupContextOptions {
    fn from(button: PopupContextMouseButton) -> Self {
        Self::new().mouse_button(button)
    }
}

impl From<MouseButton> for PopupContextOptions {
    fn from(button: MouseButton) -> Self {
        Self::new().mouse_button(button)
    }
}

/// Builder for a modal popup
#[derive(Debug)]
#[must_use]
pub struct ModalPopup<'ui> {
    name: &'ui str,
    opened: Option<&'ui mut bool>,
    flags: WindowFlags,
    ui: &'ui Ui,
}

impl<'ui> ModalPopup<'ui> {
    /// Sets the opened state tracking variable
    pub fn opened(mut self, opened: &'ui mut bool) -> Self {
        self.opened = Some(opened);
        self
    }

    /// Sets the window flags
    pub fn flags(mut self, flags: WindowFlags) -> Self {
        self.flags = flags;
        self
    }

    /// Begins the modal popup
    pub fn begin(self) -> Option<ModalPopupToken<'ui>> {
        let name_ptr = self.ui.scratch_txt(self.name);
        let opened_ptr = self
            .opened
            .map(|o| o as *mut bool)
            .unwrap_or(std::ptr::null_mut());

        let render = unsafe { sys::igBeginPopupModal(name_ptr, opened_ptr, self.flags.bits()) };

        if render {
            Some(ModalPopupToken::new(self.ui))
        } else {
            None
        }
    }
}

/// Tracks a popup that can be ended by calling `.end()` or by dropping
#[must_use]
pub struct PopupToken<'ui> {
    _ui: &'ui Ui,
}

impl<'ui> PopupToken<'ui> {
    /// Creates a new popup token
    fn new(ui: &'ui Ui) -> Self {
        PopupToken { _ui: ui }
    }

    /// Ends the popup
    pub fn end(self) {
        // The drop implementation will handle the actual ending
    }
}

impl<'ui> Drop for PopupToken<'ui> {
    fn drop(&mut self) {
        unsafe {
            sys::igEndPopup();
        }
    }
}

/// Tracks a modal popup that can be ended by calling `.end()` or by dropping
#[must_use]
pub struct ModalPopupToken<'ui> {
    _ui: &'ui Ui,
}

impl<'ui> ModalPopupToken<'ui> {
    /// Creates a new modal popup token
    fn new(ui: &'ui Ui) -> Self {
        ModalPopupToken { _ui: ui }
    }

    /// Ends the modal popup
    pub fn end(self) {
        // The drop implementation will handle the actual ending
    }
}

impl<'ui> Drop for ModalPopupToken<'ui> {
    fn drop(&mut self) {
        unsafe {
            sys::igEndPopup();
        }
    }
}