dear-imgui-rs 0.13.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
//! Windows and window utilities
//!
//! This module exposes the `Window` builder and related flags for creating
//! top-level Dear ImGui windows. It also houses helpers for child windows,
//! querying content-region size, and controlling window scrolling.
//!
//! Basic usage:
//! ```no_run
//! # use dear_imgui_rs::*;
//! # let mut ctx = Context::create();
//! # let ui = ctx.frame();
//! ui.window("Hello")
//!     .size([320.0, 240.0], Condition::FirstUseEver)
//!     .position([60.0, 60.0], Condition::FirstUseEver)
//!     .build(|| {
//!         ui.text("Window contents go here");
//!     });
//! ```
//!
//! See also:
//! - `child_window` for scoped child areas
//! - `content_region` for available size queries
//! - `scroll` for reading and setting scroll positions
//!
//! Quick example (flags + size/pos conditions):
//! ```no_run
//! # use dear_imgui_rs::*;
//! # let mut ctx = Context::create();
//! # let ui = ctx.frame();
//! use dear_imgui_rs::WindowFlags;
//! ui.window("Tools")
//!     .flags(WindowFlags::NO_RESIZE | WindowFlags::NO_COLLAPSE)
//!     .size([300.0, 200.0], Condition::FirstUseEver)
//!     .position([50.0, 60.0], Condition::FirstUseEver)
//!     .build(|| {
//!         ui.text("Toolbox contents...");
//!     });
//! ```
//!
#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::as_conversions
)]
use bitflags::bitflags;
use std::borrow::Cow;
use std::f32;

use crate::sys;
use crate::{Condition, Ui};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

mod child_window;
pub(crate) mod content_region;
pub(crate) mod scroll;

pub use child_window::{ChildFlags, ChildWindow, ChildWindowToken};

// Window-focused/hovered helpers are available via utils.rs variants.
// Window hovered/focused flag helpers are provided by crate::utils::HoveredFlags.

bitflags! {
    /// Configuration flags for windows
    #[repr(transparent)]
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct WindowFlags: i32 {
        /// Disable title-bar
        const NO_TITLE_BAR = sys::ImGuiWindowFlags_NoTitleBar as i32;
        /// Disable user resizing with the lower-right grip
        const NO_RESIZE = sys::ImGuiWindowFlags_NoResize as i32;
        /// Disable user moving the window
        const NO_MOVE = sys::ImGuiWindowFlags_NoMove as i32;
        /// Disable scrollbars (window can still scroll with mouse or programmatically)
        const NO_SCROLLBAR = sys::ImGuiWindowFlags_NoScrollbar as i32;
        /// Disable user vertically scrolling with mouse wheel
        const NO_SCROLL_WITH_MOUSE = sys::ImGuiWindowFlags_NoScrollWithMouse as i32;
        /// Disable user collapsing window by double-clicking on it
        const NO_COLLAPSE = sys::ImGuiWindowFlags_NoCollapse as i32;
        /// Resize every window to its content every frame
        const ALWAYS_AUTO_RESIZE = sys::ImGuiWindowFlags_AlwaysAutoResize as i32;
        /// Disable drawing background color (WindowBg, etc.) and outside border
        const NO_BACKGROUND = sys::ImGuiWindowFlags_NoBackground as i32;
        /// Never load/save settings in .ini file
        const NO_SAVED_SETTINGS = sys::ImGuiWindowFlags_NoSavedSettings as i32;
        /// Disable catching mouse, hovering test with pass through
        const NO_MOUSE_INPUTS = sys::ImGuiWindowFlags_NoMouseInputs as i32;
        /// Has a menu-bar
        const MENU_BAR = sys::ImGuiWindowFlags_MenuBar as i32;
        /// Allow horizontal scrollbar to appear (off by default)
        const HORIZONTAL_SCROLLBAR = sys::ImGuiWindowFlags_HorizontalScrollbar as i32;
        /// Disable taking focus when transitioning from hidden to visible state
        const NO_FOCUS_ON_APPEARING = sys::ImGuiWindowFlags_NoFocusOnAppearing as i32;
        /// Disable bringing window to front when taking focus (e.g. clicking on it or programmatically giving it focus)
        const NO_BRING_TO_FRONT_ON_FOCUS = sys::ImGuiWindowFlags_NoBringToFrontOnFocus as i32;
        /// Always show vertical scrollbar (even if ContentSize.y < Size.y)
        const ALWAYS_VERTICAL_SCROLLBAR = sys::ImGuiWindowFlags_AlwaysVerticalScrollbar as i32;
        /// Always show horizontal scrollbar (even if ContentSize.x < Size.x)
        const ALWAYS_HORIZONTAL_SCROLLBAR = sys::ImGuiWindowFlags_AlwaysHorizontalScrollbar as i32;
        /// No gamepad/keyboard navigation within the window
        const NO_NAV_INPUTS = sys::ImGuiWindowFlags_NoNavInputs as i32;
        /// No focusing toward this window with gamepad/keyboard navigation (e.g. skipped by CTRL+TAB)
        const NO_NAV_FOCUS = sys::ImGuiWindowFlags_NoNavFocus as i32;
        /// Display a dot next to the title. When used in a tab/docking context, tab is selected when clicking the X + closure is not assumed (will wait for user to stop submitting the tab). Otherwise closure is assumed when pressing the X, so if you keep submitting the tab may reappear at end of tab bar.
        const UNSAVED_DOCUMENT = sys::ImGuiWindowFlags_UnsavedDocument as i32;
        // Docking related flags
        /// Disable docking for this window (the window will not be able to dock into another and others won't be able to dock into it)
        const NO_DOCKING = sys::ImGuiWindowFlags_NoDocking as i32;
        /// Disable gamepad/keyboard navigation and focusing
        const NO_NAV = Self::NO_NAV_INPUTS.bits() | Self::NO_NAV_FOCUS.bits();
        /// Disable all window decorations
        const NO_DECORATION = Self::NO_TITLE_BAR.bits() | Self::NO_RESIZE.bits() | Self::NO_SCROLLBAR.bits() | Self::NO_COLLAPSE.bits();
        /// Disable all user interactions
        const NO_INPUTS = Self::NO_MOUSE_INPUTS.bits() | Self::NO_NAV_INPUTS.bits();
    }
}

pub(crate) fn validate_window_flags(caller: &str, flags: WindowFlags) {
    let unsupported = flags.bits() & !WindowFlags::all().bits();
    assert!(
        unsupported == 0,
        "{caller} received unsupported ImGuiWindowFlags bits: 0x{unsupported:X}"
    );
}

fn assert_finite_vec2(caller: &str, name: &str, value: [f32; 2]) {
    assert!(
        value[0].is_finite() && value[1].is_finite(),
        "{caller} {name} must contain finite values"
    );
}

#[cfg(feature = "serde")]
impl Serialize for WindowFlags {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_i32(self.bits())
    }
}

#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for WindowFlags {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let bits = i32::deserialize(deserializer)?;
        Ok(WindowFlags::from_bits_truncate(bits))
    }
}

/// Represents a window that can be built
pub struct Window<'ui> {
    ui: &'ui Ui,
    name: Cow<'ui, str>,
    opened: Option<&'ui mut bool>,
    flags: WindowFlags,
    size: Option<[f32; 2]>,
    size_condition: Condition,
    size_constraints: Option<([f32; 2], [f32; 2])>,
    pos: Option<[f32; 2]>,
    pos_condition: Condition,
    content_size: Option<[f32; 2]>,
    collapsed: Option<bool>,
    collapsed_condition: Condition,
    focused: Option<bool>,
    bg_alpha: Option<f32>,
    scroll: Option<[f32; 2]>,
}

impl<'ui> Window<'ui> {
    /// Creates a new window builder
    pub fn new(ui: &'ui Ui, name: impl Into<Cow<'ui, str>>) -> Self {
        Self {
            ui,
            name: name.into(),
            opened: None,
            flags: WindowFlags::empty(),
            size: None,
            size_condition: Condition::Always,
            size_constraints: None,
            pos: None,
            pos_condition: Condition::Always,
            content_size: None,
            collapsed: None,
            collapsed_condition: Condition::Always,
            focused: None,
            bg_alpha: None,
            scroll: None,
        }
    }

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

    /// Controls whether the window is open (adds a title-bar close button).
    ///
    /// In Dear ImGui, a window is "closed" by the user by toggling the `p_open` boolean.
    /// When the close button (X) is pressed, `opened` will be set to `false`.
    ///
    /// Note: as an immediate-mode UI, you should stop submitting this window when
    /// `*opened == false` (typically by guarding the `window(...).build(...)` call).
    #[doc(alias = "Begin")]
    pub fn opened(mut self, opened: &'ui mut bool) -> Self {
        self.opened = Some(opened);
        self
    }

    /// Sets window size
    pub fn size(mut self, size: [f32; 2], condition: Condition) -> Self {
        self.size = Some(size);
        self.size_condition = condition;
        self
    }

    /// Sets window size constraints for the next Begin call.
    ///
    /// This is a convenience wrapper over `ImGui::SetNextWindowSizeConstraints`
    /// without a custom size callback.
    #[doc(alias = "SetNextWindowSizeConstraints")]
    pub fn size_constraints(mut self, min: [f32; 2], max: [f32; 2]) -> Self {
        self.size_constraints = Some((min, max));
        self
    }

    /// Sets window position
    pub fn position(mut self, pos: [f32; 2], condition: Condition) -> Self {
        self.pos = Some(pos);
        self.pos_condition = condition;
        self
    }

    /// Sets window content size
    pub fn content_size(mut self, size: [f32; 2]) -> Self {
        self.content_size = Some(size);
        self
    }

    /// Sets window collapsed state
    pub fn collapsed(mut self, collapsed: bool, condition: Condition) -> Self {
        self.collapsed = Some(collapsed);
        self.collapsed_condition = condition;
        self
    }

    /// Sets window focused state
    pub fn focused(mut self, focused: bool) -> Self {
        self.focused = Some(focused);
        self
    }

    /// Sets window background alpha
    pub fn bg_alpha(mut self, alpha: f32) -> Self {
        self.bg_alpha = Some(alpha);
        self
    }

    /// Sets the initial scroll position for the next Begin call.
    #[doc(alias = "SetNextWindowScroll")]
    pub fn scroll(mut self, scroll: [f32; 2]) -> Self {
        self.scroll = Some(scroll);
        self
    }

    /// Builds the window and calls the provided closure
    pub fn build<F, R>(self, f: F) -> Option<R>
    where
        F: FnOnce() -> R,
    {
        let _token = self.begin()?;
        Some(f())
    }

    /// Begins the window and returns a token
    fn begin(self) -> Option<WindowToken<'ui>> {
        let name = self.name;
        let name_ptr = self.ui.scratch_txt(name);
        validate_window_flags("Window::begin()", self.flags);

        // Set window properties before beginning
        if let Some(size) = self.size {
            assert_finite_vec2("Window::begin()", "size", size);
            unsafe {
                let size_vec = crate::sys::ImVec2 {
                    x: size[0],
                    y: size[1],
                };
                crate::sys::igSetNextWindowSize(size_vec, self.size_condition as i32);
            }
        }

        if let Some((min, max)) = self.size_constraints {
            assert_finite_vec2("Window::begin()", "minimum size constraint", min);
            assert_finite_vec2("Window::begin()", "maximum size constraint", max);
            unsafe {
                let min_vec = sys::ImVec2_c {
                    x: min[0],
                    y: min[1],
                };
                let max_vec = sys::ImVec2_c {
                    x: max[0],
                    y: max[1],
                };
                sys::igSetNextWindowSizeConstraints(min_vec, max_vec, None, std::ptr::null_mut());
            }
        }

        if let Some(pos) = self.pos {
            assert_finite_vec2("Window::begin()", "position", pos);
            unsafe {
                let pos_vec = crate::sys::ImVec2 {
                    x: pos[0],
                    y: pos[1],
                };
                let pivot_vec = crate::sys::ImVec2 { x: 0.0, y: 0.0 };
                crate::sys::igSetNextWindowPos(pos_vec, self.pos_condition as i32, pivot_vec);
            }
        }

        if let Some(content_size) = self.content_size {
            assert_finite_vec2("Window::begin()", "content size", content_size);
            unsafe {
                let content_size_vec = crate::sys::ImVec2 {
                    x: content_size[0],
                    y: content_size[1],
                };
                crate::sys::igSetNextWindowContentSize(content_size_vec);
            }
        }

        if let Some(collapsed) = self.collapsed {
            unsafe {
                crate::sys::igSetNextWindowCollapsed(collapsed, self.collapsed_condition as i32);
            }
        }

        if let Some(focused) = self.focused
            && focused
        {
            unsafe {
                crate::sys::igSetNextWindowFocus();
            }
        }

        if let Some(alpha) = self.bg_alpha {
            assert!(
                alpha.is_finite(),
                "Window::begin() background alpha must be finite"
            );
            unsafe {
                crate::sys::igSetNextWindowBgAlpha(alpha);
            }
        }

        if let Some(scroll) = self.scroll {
            assert_finite_vec2("Window::begin()", "scroll", scroll);
            unsafe {
                let scroll_vec = sys::ImVec2_c {
                    x: scroll[0],
                    y: scroll[1],
                };
                sys::igSetNextWindowScroll(scroll_vec);
            }
        }

        // Begin the window
        let mut opened = self.opened;
        let opened_ptr: *mut bool = match opened.as_deref_mut() {
            Some(opened) => opened as *mut bool,
            None => std::ptr::null_mut(),
        };
        let result = unsafe { crate::sys::igBegin(name_ptr, opened_ptr, self.flags.bits()) };
        let is_open = opened.is_none_or(|opened| *opened);

        // IMPORTANT: According to ImGui documentation, Begin/End calls must be balanced.
        // If Begin returns false, we need to call End immediately and return None.
        if result && is_open {
            Some(WindowToken {
                _phantom: std::marker::PhantomData,
            })
        } else {
            // If Begin returns false, call End immediately and return None
            unsafe {
                crate::sys::igEnd();
            }
            None
        }
    }
}

/// Token representing an active window
pub struct WindowToken<'ui> {
    _phantom: std::marker::PhantomData<&'ui ()>,
}

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