dear-imgui-rs 0.16.0

High-level Rust bindings to Dear ImGui v1.92.9b 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
use crate::sys;

use super::Context;
#[cfg(feature = "multi-viewport")]
use super::attachment::{ContextPlatformWindowTeardown, ContextPlatformWindowTeardownError};
use super::binding::{CTX_MUTEX, with_bound_context};

#[cfg(feature = "multi-viewport")]
struct PlatformDrawDataTextureMask {
    entries: Vec<(
        std::ptr::NonNull<sys::ImDrawData>,
        *mut sys::ImVector_ImTextureDataPtr,
    )>,
}

#[cfg(feature = "multi-viewport")]
impl PlatformDrawDataTextureMask {
    unsafe fn install(platform_io: *mut sys::ImGuiPlatformIO) -> Self {
        let mut entries = Vec::new();
        let viewports = unsafe { &(*platform_io).Viewports };
        if viewports.Size <= 0 {
            return Self { entries };
        }
        assert!(
            viewports.Capacity >= viewports.Size && !viewports.Data.is_null(),
            "ImGuiPlatformIO.Viewports has invalid native storage"
        );
        for index in 0..viewports.Size as usize {
            let viewport = unsafe { *viewports.Data.add(index) };
            let Some(viewport) = std::ptr::NonNull::new(viewport) else {
                continue;
            };
            let Some(draw_data) = std::ptr::NonNull::new(unsafe { viewport.as_ref().DrawData })
            else {
                continue;
            };
            let textures = unsafe { draw_data.as_ref().Textures };
            if textures.is_null() {
                continue;
            }
            unsafe { (*draw_data.as_ptr()).Textures = std::ptr::null_mut() };
            entries.push((draw_data, textures));
        }
        Self { entries }
    }
}

#[cfg(feature = "multi-viewport")]
impl Drop for PlatformDrawDataTextureMask {
    fn drop(&mut self) {
        for (draw_data, textures) in self.entries.drain(..) {
            unsafe { (*draw_data.as_ptr()).Textures = textures };
        }
    }
}

impl Context {
    /// Get shared access to the platform IO.
    ///
    /// Note: `ImGuiPlatformIO` exists even when multi-viewport is disabled. We expose it
    /// unconditionally so callers can use ImGui 1.92+ texture management via `PlatformIO.Textures[]`.
    #[doc(alias = "GetPlatformIO")]
    pub fn platform_io(&self) -> &crate::platform_io::PlatformIo {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            let pio = self.platform_io_ptr("Context::platform_io()");
            crate::platform_io::PlatformIo::from_raw(pio)
        }
    }

    /// Get mutable access to the platform IO.
    ///
    /// Note: `ImGuiPlatformIO` exists even when multi-viewport is disabled. We expose it
    /// unconditionally so callers can use ImGui 1.92+ texture management via `PlatformIO.Textures[]`.
    pub fn platform_io_mut(&mut self) -> &mut crate::platform_io::PlatformIo {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            let pio = self.platform_io_ptr("Context::platform_io_mut()");
            crate::platform_io::PlatformIo::from_raw_mut(pio)
        }
    }

    /// Returns a reference to the main Dear ImGui viewport.
    ///
    /// The returned reference is owned by this ImGui context and
    /// must not be used after the context is destroyed.
    #[doc(alias = "GetMainViewport")]
    pub fn main_viewport(&mut self) -> &mut crate::platform_io::Viewport {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            with_bound_context(self.raw, || {
                let ptr = sys::igGetMainViewport();
                if ptr.is_null() {
                    panic!("Context::main_viewport() requires a valid ImGui context");
                }
                crate::platform_io::Viewport::from_raw_mut(ptr)
            })
        }
    }

    /// Enable Dear ImGui's multi-viewport capability.
    ///
    /// Docking is an independent capability and must be enabled explicitly by the caller.
    /// A platform and renderer backend that advertise multi-viewport support must be installed
    /// before the next frame begins.
    ///
    /// Prefer enabling this before the first frame so Dear ImGui can load settings in the correct
    /// coordinate space. Enabling it between the first and second frames is rejected by Dear
    /// ImGui. When it is enabled after a later completed frame, [`Context::frame`] automatically
    /// advances the platform-window lifecycle for the preceding disabled frame.
    #[cfg(feature = "multi-viewport")]
    pub fn enable_multi_viewport(&mut self) {
        let io = self.io_mut();
        let mut flags = io.config_flags();
        flags.insert(crate::ConfigFlags::VIEWPORTS_ENABLE);
        io.set_config_flags(flags);
    }

    /// Update platform windows
    ///
    /// This function should be called every frame when multi-viewport is enabled.
    /// It updates all platform windows and handles viewport management.
    ///
    /// # Panics
    ///
    /// Panics if the current frame has not ended, this frame was already updated, or the active
    /// multi-viewport backend contract is incomplete.
    #[cfg(feature = "multi-viewport")]
    #[doc(alias = "UpdatePlatformWindows")]
    pub fn update_platform_windows(&mut self) {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            with_bound_context(self.raw, || {
                self.assert_can_update_platform_windows_unlocked(
                    "Context::update_platform_windows()",
                );
                sys::igUpdatePlatformWindows();
            });
        }
    }

    /// Render platform windows with default implementation
    ///
    /// This function renders all platform windows using the default implementation.
    /// It calls the platform and renderer backends to render each viewport.
    ///
    /// # Panics
    ///
    /// Panics unless [`Self::update_platform_windows`] completed for the current frame after
    /// [`Self::render`], or unless the installed backends provide `Platform_RenderWindow` or
    /// `Renderer_RenderWindow`. Snapshot-driven renderers should render their detached viewport
    /// data directly instead of calling this default callback pump.
    #[cfg(feature = "multi-viewport")]
    #[doc(alias = "RenderPlatformWindowsDefault")]
    pub fn render_platform_windows_default(&mut self) {
        let _guard = CTX_MUTEX.lock();
        unsafe {
            with_bound_context(self.raw, || {
                let raw = &*self.raw;
                assert!(
                    raw.FrameCount > 0
                        && raw.FrameCountRendered == raw.FrameCount
                        && raw.FrameCountPlatformEnded == raw.FrameCount,
                    "Context::render_platform_windows_default() requires a rendered frame followed by Context::update_platform_windows()"
                );
                let platform_io = sys::igGetPlatformIO_Nil();
                assert!(
                    !platform_io.is_null()
                        && ((*platform_io).Platform_RenderWindow.is_some()
                            || (*platform_io).Renderer_RenderWindow.is_some()),
                    "Context::render_platform_windows_default() requires Platform_RenderWindow or Renderer_RenderWindow; render snapshots directly when the renderer does not use default callbacks"
                );
                let renderer_has_textures =
                    (*self.io_ptr("Context::render_platform_windows_default()")).BackendFlags
                        & sys::ImGuiBackendFlags_RendererHasTextures as i32
                        != 0;
                if renderer_has_textures {
                    assert!(
                        self.snapshot_hub
                            .is_synchronous_frame_reconciled(raw.FrameCount),
                        "Context::render_platform_windows_default() requires managed-texture reconciliation for the current rendered frame"
                    );
                }
                let _texture_mask = renderer_has_textures
                    .then(|| PlatformDrawDataTextureMask::install(platform_io));
                sys::igRenderPlatformWindowsDefault(std::ptr::null_mut(), std::ptr::null_mut());
            });
        }
    }

    /// Destroy all platform windows
    ///
    /// This function should be called during shutdown to properly clean up
    /// all platform windows and their associated resources.
    ///
    /// Any open frame is ended first through the same idempotent lifecycle path used by Context
    /// destruction. This lets backends revoke UI access before destroying secondary windows. A
    /// rejected observer preflight still leaves that frame ended.
    ///
    /// Platform backends receive a bounded observer scope around the native call so they can
    /// validate callback ownership and keep their teardown state coherent. If that preflight
    /// fails, native teardown does not begin.
    ///
    /// This is a platform-backend shutdown primitive. A registered backend may transition its
    /// own multi-viewport runtime to a released state; prefer its explicit shutdown API when one
    /// is available.
    ///
    /// # Errors
    ///
    /// Returns an error when the active platform attachment rejects the transaction, cannot
    /// complete post-teardown cleanup, or when the operation is re-entered. Post-teardown errors
    /// report that native platform windows have already been destroyed.
    #[cfg(feature = "multi-viewport")]
    #[doc(alias = "DestroyPlatformWindows")]
    pub fn destroy_platform_windows(&mut self) -> Result<(), ContextPlatformWindowTeardownError> {
        let _guard = CTX_MUTEX.lock();
        self.end_frame_for_teardown_unlocked();
        let teardown = ContextPlatformWindowTeardown::new(&self.state);
        let invocation = self.attachments.begin_platform_window_teardown(&teardown)?;
        unsafe {
            with_bound_context(self.raw, || {
                sys::igDestroyPlatformWindows();
            });
        }
        invocation.finish(&teardown)
    }

    #[cfg(feature = "multi-viewport")]
    pub(super) fn prepare_multi_viewport_new_frame_contract_unlocked(&self, caller: &str) {
        unsafe {
            let config_flags = (*self.io_ptr(caller)).ConfigFlags;
            let viewports_enabled = config_flags & sys::ImGuiConfigFlags_ViewportsEnable != 0;
            if !viewports_enabled {
                return;
            }

            let frame_count = (*self.raw).FrameCount;
            let frame_count_ended = (*self.raw).FrameCountEnded;
            let frame_count_platform_ended = (*self.raw).FrameCountPlatformEnded;
            let config_flags_current_frame = (*self.raw).ConfigFlagsCurrFrame;

            if frame_count == 1
                && config_flags_current_frame & sys::ImGuiConfigFlags_ViewportsEnable == 0
            {
                panic!(
                    "{caller} cannot enable multi-viewport on the second frame; enable it before the first frame or after the second frame so Dear ImGui preserves its settings contract"
                );
            }
            if !self.multi_viewport_backends_advertised_unlocked() {
                // Dear ImGui intentionally clears ViewportsEnable when either backend declines
                // support. Preserve that graceful fallback instead of turning it into an error.
                return;
            }
            if frame_count > 0 && frame_count_platform_ended != frame_count {
                if config_flags_current_frame & sys::ImGuiConfigFlags_ViewportsEnable == 0 {
                    assert_eq!(
                        frame_count_ended, frame_count,
                        "{caller} cannot enable multi-viewport while the previous frame is still open"
                    );
                    // The preceding frame had viewports disabled, so native UpdatePlatformWindows
                    // only advances its frame watermark and cannot invoke backend callbacks.
                    sys::igUpdatePlatformWindows();
                } else {
                    panic!(
                        "{caller} cannot begin a new multi-viewport frame before Context::update_platform_windows() completes the previous frame"
                    );
                }
            }
            self.assert_multi_viewport_backend_contract_unlocked(
                caller,
                config_flags | config_flags_current_frame,
            );
        }
    }

    #[cfg(feature = "multi-viewport")]
    fn assert_can_update_platform_windows_unlocked(&self, caller: &str) {
        unsafe {
            let frame_count = (*self.raw).FrameCount;
            let frame_count_ended = (*self.raw).FrameCountEnded;
            let frame_count_platform_ended = (*self.raw).FrameCountPlatformEnded;
            let config_flags_current_frame = (*self.raw).ConfigFlagsCurrFrame;
            assert!(
                frame_count_ended == frame_count,
                "{caller} requires Context::render() or an ended frame first"
            );
            assert!(
                frame_count_platform_ended < frame_count,
                "{caller} was already called for frame {}",
                frame_count
            );
            self.assert_multi_viewport_backend_contract_unlocked(
                caller,
                config_flags_current_frame,
            );
        }
    }

    #[cfg(feature = "multi-viewport")]
    fn assert_multi_viewport_backend_contract_unlocked(&self, caller: &str, config_flags: i32) {
        if config_flags & sys::ImGuiConfigFlags_ViewportsEnable == 0 {
            return;
        }

        unsafe {
            let io = &*self.io_ptr(caller);
            assert!(
                self.multi_viewport_backends_advertised_unlocked(),
                "{caller} requires platform and renderer backends that advertise multi-viewport support"
            );

            let platform_io = &*self.platform_io_ptr(caller);
            for (name, installed) in [
                (
                    "Platform_CreateWindow",
                    platform_io.Platform_CreateWindow.is_some(),
                ),
                (
                    "Platform_DestroyWindow",
                    platform_io.Platform_DestroyWindow.is_some(),
                ),
                (
                    "Platform_ShowWindow",
                    platform_io.Platform_ShowWindow.is_some(),
                ),
                (
                    "Platform_GetWindowPos",
                    platform_io.Platform_GetWindowPos.is_some(),
                ),
                (
                    "Platform_SetWindowPos",
                    platform_io.Platform_SetWindowPos.is_some(),
                ),
                (
                    "Platform_GetWindowSize",
                    platform_io.Platform_GetWindowSize.is_some(),
                ),
                (
                    "Platform_SetWindowSize",
                    platform_io.Platform_SetWindowSize.is_some(),
                ),
                (
                    "Platform_SetWindowTitle",
                    platform_io.Platform_SetWindowTitle.is_some(),
                ),
            ] {
                assert!(
                    installed,
                    "{caller} requires the {name} callback before multi-viewport can run"
                );
            }

            let monitor_count = platform_io.Monitors.Size;
            assert!(
                monitor_count > 0 && !platform_io.Monitors.Data.is_null(),
                "{caller} requires at least one valid PlatformIO monitor"
            );
            assert!(
                platform_io.Monitors.Capacity >= monitor_count,
                "{caller} rejected a corrupt PlatformIO monitor vector"
            );
            let monitors = std::slice::from_raw_parts(
                platform_io.Monitors.Data,
                usize::try_from(monitor_count)
                    .expect("positive PlatformIO monitor count must fit usize"),
            );
            crate::platform_io::assert_monitor_contract(monitors, caller);

            let main_viewport = sys::igGetMainViewport();
            assert!(
                !main_viewport.is_null(),
                "{caller} requires a valid main viewport"
            );
            assert!(
                !(*main_viewport).PlatformUserData.is_null()
                    || !(*main_viewport).PlatformHandle.is_null(),
                "{caller} requires the platform backend to initialize the main viewport"
            );

            let transparent_docking = io.ConfigDockingTransparentPayload
                && config_flags & sys::ImGuiConfigFlags_DockingEnable != 0;
            assert!(
                !transparent_docking || platform_io.Platform_SetWindowAlpha.is_some(),
                "{caller} requires Platform_SetWindowAlpha when transparent docking payloads are enabled"
            );
        }
    }

    #[cfg(feature = "multi-viewport")]
    fn multi_viewport_backends_advertised_unlocked(&self) -> bool {
        unsafe {
            let backend_flags = (*self.io_ptr("multi-viewport backend validation")).BackendFlags;
            backend_flags & sys::ImGuiBackendFlags_PlatformHasViewports != 0
                && backend_flags & sys::ImGuiBackendFlags_RendererHasViewports != 0
        }
    }
}

#[cfg(all(test, feature = "multi-viewport"))]
mod tests {
    use super::*;

    #[test]
    fn managed_platform_draw_texture_mask_restores_every_pointer() {
        let mut textures = sys::ImVector_ImTextureDataPtr::default();
        let textures_ptr = &mut textures as *mut sys::ImVector_ImTextureDataPtr;
        let mut draw_data = sys::ImDrawData {
            Textures: textures_ptr,
            ..Default::default()
        };
        let mut viewport = sys::ImGuiViewport {
            DrawData: &mut draw_data,
            ..Default::default()
        };
        let viewport = &mut viewport as *mut sys::ImGuiViewport;
        let mut viewports = [viewport, viewport];
        let mut platform_io = sys::ImGuiPlatformIO {
            Viewports: sys::ImVector_ImGuiViewportPtr {
                Size: viewports.len() as i32,
                Capacity: viewports.len() as i32,
                Data: viewports.as_mut_ptr(),
            },
            ..Default::default()
        };

        let mask = unsafe { PlatformDrawDataTextureMask::install(&mut platform_io) };
        assert!(draw_data.Textures.is_null());
        drop(mask);
        assert_eq!(draw_data.Textures, textures_ptr);
    }
}