Skip to main content

dear_imgui_rs/context/
platform.rs

1use crate::sys;
2
3use super::Context;
4#[cfg(feature = "multi-viewport")]
5use super::attachment::{ContextPlatformWindowTeardown, ContextPlatformWindowTeardownError};
6use super::binding::{CTX_MUTEX, with_bound_context};
7
8#[cfg(feature = "multi-viewport")]
9struct PlatformDrawDataTextureMask {
10    entries: Vec<(
11        std::ptr::NonNull<sys::ImDrawData>,
12        *mut sys::ImVector_ImTextureDataPtr,
13    )>,
14}
15
16#[cfg(feature = "multi-viewport")]
17impl PlatformDrawDataTextureMask {
18    unsafe fn install(platform_io: *mut sys::ImGuiPlatformIO) -> Self {
19        let mut entries = Vec::new();
20        let viewports = unsafe { &(*platform_io).Viewports };
21        if viewports.Size <= 0 {
22            return Self { entries };
23        }
24        assert!(
25            viewports.Capacity >= viewports.Size && !viewports.Data.is_null(),
26            "ImGuiPlatformIO.Viewports has invalid native storage"
27        );
28        for index in 0..viewports.Size as usize {
29            let viewport = unsafe { *viewports.Data.add(index) };
30            let Some(viewport) = std::ptr::NonNull::new(viewport) else {
31                continue;
32            };
33            let Some(draw_data) = std::ptr::NonNull::new(unsafe { viewport.as_ref().DrawData })
34            else {
35                continue;
36            };
37            let textures = unsafe { draw_data.as_ref().Textures };
38            if textures.is_null() {
39                continue;
40            }
41            unsafe { (*draw_data.as_ptr()).Textures = std::ptr::null_mut() };
42            entries.push((draw_data, textures));
43        }
44        Self { entries }
45    }
46}
47
48#[cfg(feature = "multi-viewport")]
49impl Drop for PlatformDrawDataTextureMask {
50    fn drop(&mut self) {
51        for (draw_data, textures) in self.entries.drain(..) {
52            unsafe { (*draw_data.as_ptr()).Textures = textures };
53        }
54    }
55}
56
57impl Context {
58    /// Get shared access to the platform IO.
59    ///
60    /// Note: `ImGuiPlatformIO` exists even when multi-viewport is disabled. We expose it
61    /// unconditionally for platform configuration. Managed renderer texture work is exposed through
62    /// request-bound `PendingFrame` or `FrameSnapshot` APIs, not raw texture pointers.
63    #[doc(alias = "GetPlatformIO")]
64    pub fn platform_io(&self) -> &crate::platform_io::PlatformIo {
65        let _guard = CTX_MUTEX.lock();
66        unsafe {
67            let pio = self.platform_io_ptr("Context::platform_io()");
68            crate::platform_io::PlatformIo::from_raw(pio)
69        }
70    }
71
72    /// Get mutable access to the platform IO.
73    ///
74    /// Platform configuration is available even when multi-viewport is disabled. Callback
75    /// registration always targets this Context, including inside another Context's binding scope.
76    /// Managed renderer texture work uses the request-bound `PendingFrame` or `FrameSnapshot` APIs.
77    pub fn platform_io_mut(&mut self) -> &mut crate::platform_io::PlatformIo {
78        let _guard = CTX_MUTEX.lock();
79        unsafe {
80            let pio = self.platform_io_ptr("Context::platform_io_mut()");
81            crate::platform_io::PlatformIo::from_raw_mut(pio)
82        }
83    }
84
85    /// Returns a reference to the main Dear ImGui viewport.
86    ///
87    /// The returned reference is owned by this ImGui context and
88    /// must not be used after the context is destroyed.
89    #[doc(alias = "GetMainViewport")]
90    pub fn main_viewport(&mut self) -> &mut crate::platform_io::Viewport {
91        let _guard = CTX_MUTEX.lock();
92        unsafe {
93            with_bound_context(self.raw, || {
94                let ptr = sys::igGetMainViewport();
95                if ptr.is_null() {
96                    panic!("Context::main_viewport() requires a valid ImGui context");
97                }
98                crate::platform_io::Viewport::from_raw_mut(ptr)
99            })
100        }
101    }
102
103    /// Enable Dear ImGui's multi-viewport capability.
104    ///
105    /// Docking is an independent capability and must be enabled explicitly by the caller.
106    /// A platform and renderer backend that advertise multi-viewport support must be installed
107    /// before the next frame begins.
108    ///
109    /// Prefer enabling this before the first frame so Dear ImGui can load settings in the correct
110    /// coordinate space. Enabling it between the first and second frames is rejected by Dear
111    /// ImGui. When it is enabled after a later completed frame, [`Context::frame`] automatically
112    /// advances the platform-window lifecycle for the preceding disabled frame.
113    #[cfg(feature = "multi-viewport")]
114    pub fn enable_multi_viewport(&mut self) {
115        let io = self.io_mut();
116        let mut flags = io.config_flags();
117        flags.insert(crate::ConfigFlags::VIEWPORTS_ENABLE);
118        io.set_config_flags(flags);
119    }
120
121    /// Update platform windows
122    ///
123    /// This function should be called every frame when multi-viewport is enabled.
124    /// It updates all platform windows and handles viewport management.
125    ///
126    /// # Panics
127    ///
128    /// Panics if the current frame has not ended, this frame was already updated, or the active
129    /// multi-viewport backend contract is incomplete.
130    #[cfg(feature = "multi-viewport")]
131    #[doc(alias = "UpdatePlatformWindows")]
132    pub fn update_platform_windows(&mut self) {
133        let _guard = CTX_MUTEX.lock();
134        unsafe {
135            with_bound_context(self.raw, || {
136                self.assert_can_update_platform_windows_unlocked(
137                    "Context::update_platform_windows()",
138                );
139                sys::igUpdatePlatformWindows();
140            });
141        }
142    }
143
144    /// Render platform windows with default implementation
145    ///
146    /// This function renders all platform windows using the default implementation.
147    /// It calls the installed render callbacks for visible secondary viewports, then calls their
148    /// swap callbacks. Backends that render the viewports themselves may install only a swap callback.
149    ///
150    /// # Panics
151    ///
152    /// Panics unless [`Self::update_platform_windows`] completed for the current frame after
153    /// [`Self::render`], or if the backends provide no render or swap callback. Managed-texture
154    /// renderers must also reconcile the current frame before using this method.
155    #[cfg(feature = "multi-viewport")]
156    #[doc(alias = "RenderPlatformWindowsDefault")]
157    pub fn render_platform_windows_default(&mut self) {
158        let _guard = CTX_MUTEX.lock();
159        unsafe {
160            with_bound_context(self.raw, || {
161                let raw = &*self.raw;
162                assert!(
163                    raw.FrameCount > 0
164                        && raw.FrameCountRendered == raw.FrameCount
165                        && raw.FrameCountPlatformEnded == raw.FrameCount,
166                    "Context::render_platform_windows_default() requires a rendered frame followed by Context::update_platform_windows()"
167                );
168                let platform_io =
169                    self.platform_io_ptr("Context::render_platform_windows_default()");
170                assert!(
171                    (*platform_io).Platform_RenderWindow.is_some()
172                        || (*platform_io).Renderer_RenderWindow.is_some()
173                        || (*platform_io).Platform_SwapBuffers.is_some()
174                        || (*platform_io).Renderer_SwapBuffers.is_some(),
175                    "Context::render_platform_windows_default() requires a platform or renderer render or swap callback"
176                );
177                let renderer_has_textures =
178                    (*self.io_ptr("Context::render_platform_windows_default()")).BackendFlags
179                        & sys::ImGuiBackendFlags_RendererHasTextures as i32
180                        != 0;
181                if renderer_has_textures {
182                    assert!(
183                        self.snapshot_hub
184                            .is_synchronous_frame_reconciled(raw.FrameCount),
185                        "Context::render_platform_windows_default() requires managed-texture reconciliation for the current rendered frame"
186                    );
187                }
188                let _texture_mask = renderer_has_textures
189                    .then(|| PlatformDrawDataTextureMask::install(platform_io));
190                sys::igRenderPlatformWindowsDefault(std::ptr::null_mut(), std::ptr::null_mut());
191            });
192        }
193    }
194
195    /// Destroy all platform windows
196    ///
197    /// This function should be called during shutdown to properly clean up
198    /// all platform windows and their associated resources.
199    ///
200    /// Any open frame is ended first through the same idempotent lifecycle path used by Context
201    /// destruction. This lets backends revoke UI access before destroying secondary windows. A
202    /// rejected observer preflight still leaves that frame ended.
203    ///
204    /// Platform backends receive a bounded observer scope with this Context current so they can
205    /// validate callback ownership and keep their teardown state coherent. If that preflight
206    /// fails, native teardown does not begin.
207    ///
208    /// This is a platform-backend shutdown primitive. A registered backend may transition its
209    /// own multi-viewport runtime to a released state; prefer its explicit shutdown API when one
210    /// is available.
211    ///
212    /// # Errors
213    ///
214    /// Returns an error when the active platform attachment rejects the transaction, cannot
215    /// complete post-teardown cleanup, or when the operation is re-entered. Post-teardown errors
216    /// report that native platform windows have already been destroyed.
217    #[cfg(feature = "multi-viewport")]
218    #[doc(alias = "DestroyPlatformWindows")]
219    pub fn destroy_platform_windows(&mut self) -> Result<(), ContextPlatformWindowTeardownError> {
220        with_bound_context(self.raw, || {
221            self.end_frame_for_teardown_unlocked();
222            let teardown = ContextPlatformWindowTeardown::new(&self.state);
223            let invocation = self.attachments.begin_platform_window_teardown(&teardown)?;
224            unsafe { sys::igDestroyPlatformWindows() };
225            invocation.finish(&teardown)
226        })
227    }
228
229    #[cfg(feature = "multi-viewport")]
230    pub(super) fn prepare_multi_viewport_new_frame_contract_unlocked(&self, caller: &str) {
231        unsafe {
232            let config_flags = (*self.io_ptr(caller)).ConfigFlags;
233            let viewports_enabled = config_flags & sys::ImGuiConfigFlags_ViewportsEnable != 0;
234            if !viewports_enabled {
235                return;
236            }
237
238            let frame_count = (*self.raw).FrameCount;
239            let frame_count_ended = (*self.raw).FrameCountEnded;
240            let frame_count_platform_ended = (*self.raw).FrameCountPlatformEnded;
241            let config_flags_current_frame = (*self.raw).ConfigFlagsCurrFrame;
242
243            if frame_count == 1
244                && config_flags_current_frame & sys::ImGuiConfigFlags_ViewportsEnable == 0
245            {
246                panic!(
247                    "{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"
248                );
249            }
250            if !self.multi_viewport_backends_advertised_unlocked() {
251                // Dear ImGui intentionally clears ViewportsEnable when either backend declines
252                // support. Preserve that graceful fallback instead of turning it into an error.
253                return;
254            }
255            if frame_count > 0 && frame_count_platform_ended != frame_count {
256                if config_flags_current_frame & sys::ImGuiConfigFlags_ViewportsEnable == 0 {
257                    assert_eq!(
258                        frame_count_ended, frame_count,
259                        "{caller} cannot enable multi-viewport while the previous frame is still open"
260                    );
261                    // The preceding frame had viewports disabled, so native UpdatePlatformWindows
262                    // only advances its frame watermark and cannot invoke backend callbacks.
263                    sys::igUpdatePlatformWindows();
264                } else {
265                    panic!(
266                        "{caller} cannot begin a new multi-viewport frame before Context::update_platform_windows() completes the previous frame"
267                    );
268                }
269            }
270            self.assert_multi_viewport_backend_contract_unlocked(
271                caller,
272                config_flags | config_flags_current_frame,
273            );
274        }
275    }
276
277    #[cfg(feature = "multi-viewport")]
278    fn assert_can_update_platform_windows_unlocked(&self, caller: &str) {
279        unsafe {
280            let frame_count = (*self.raw).FrameCount;
281            let frame_count_ended = (*self.raw).FrameCountEnded;
282            let frame_count_platform_ended = (*self.raw).FrameCountPlatformEnded;
283            let config_flags_current_frame = (*self.raw).ConfigFlagsCurrFrame;
284            assert!(
285                frame_count_ended == frame_count,
286                "{caller} requires Context::render() or an ended frame first"
287            );
288            assert!(
289                frame_count_platform_ended < frame_count,
290                "{caller} was already called for frame {}",
291                frame_count
292            );
293            self.assert_multi_viewport_backend_contract_unlocked(
294                caller,
295                config_flags_current_frame,
296            );
297        }
298    }
299
300    #[cfg(feature = "multi-viewport")]
301    fn assert_multi_viewport_backend_contract_unlocked(&self, caller: &str, config_flags: i32) {
302        if config_flags & sys::ImGuiConfigFlags_ViewportsEnable == 0 {
303            return;
304        }
305
306        unsafe {
307            let io = &*self.io_ptr(caller);
308            assert!(
309                self.multi_viewport_backends_advertised_unlocked(),
310                "{caller} requires platform and renderer backends that advertise multi-viewport support"
311            );
312
313            let platform_io = &*self.platform_io_ptr(caller);
314            for (name, installed) in [
315                (
316                    "Platform_CreateWindow",
317                    platform_io.Platform_CreateWindow.is_some(),
318                ),
319                (
320                    "Platform_DestroyWindow",
321                    platform_io.Platform_DestroyWindow.is_some(),
322                ),
323                (
324                    "Platform_ShowWindow",
325                    platform_io.Platform_ShowWindow.is_some(),
326                ),
327                (
328                    "Platform_GetWindowPos",
329                    platform_io.Platform_GetWindowPos.is_some(),
330                ),
331                (
332                    "Platform_SetWindowPos",
333                    platform_io.Platform_SetWindowPos.is_some(),
334                ),
335                (
336                    "Platform_GetWindowSize",
337                    platform_io.Platform_GetWindowSize.is_some(),
338                ),
339                (
340                    "Platform_SetWindowSize",
341                    platform_io.Platform_SetWindowSize.is_some(),
342                ),
343                (
344                    "Platform_SetWindowTitle",
345                    platform_io.Platform_SetWindowTitle.is_some(),
346                ),
347            ] {
348                assert!(
349                    installed,
350                    "{caller} requires the {name} callback before multi-viewport can run"
351                );
352            }
353
354            let monitor_count = platform_io.Monitors.Size;
355            assert!(
356                monitor_count > 0 && !platform_io.Monitors.Data.is_null(),
357                "{caller} requires at least one valid PlatformIO monitor"
358            );
359            assert!(
360                platform_io.Monitors.Capacity >= monitor_count,
361                "{caller} rejected a corrupt PlatformIO monitor vector"
362            );
363            let monitors = std::slice::from_raw_parts(
364                platform_io.Monitors.Data,
365                usize::try_from(monitor_count)
366                    .expect("positive PlatformIO monitor count must fit usize"),
367            );
368            crate::platform_io::assert_monitor_contract(monitors, caller);
369
370            let main_viewport = sys::igGetMainViewport();
371            assert!(
372                !main_viewport.is_null(),
373                "{caller} requires a valid main viewport"
374            );
375            assert!(
376                !(*main_viewport).PlatformUserData.is_null()
377                    || !(*main_viewport).PlatformHandle.is_null(),
378                "{caller} requires the platform backend to initialize the main viewport"
379            );
380
381            let transparent_docking = io.ConfigDockingTransparentPayload
382                && config_flags & sys::ImGuiConfigFlags_DockingEnable != 0;
383            assert!(
384                !transparent_docking || platform_io.Platform_SetWindowAlpha.is_some(),
385                "{caller} requires Platform_SetWindowAlpha when transparent docking payloads are enabled"
386            );
387        }
388    }
389
390    #[cfg(feature = "multi-viewport")]
391    fn multi_viewport_backends_advertised_unlocked(&self) -> bool {
392        unsafe {
393            let backend_flags = (*self.io_ptr("multi-viewport backend validation")).BackendFlags;
394            backend_flags & sys::ImGuiBackendFlags_PlatformHasViewports != 0
395                && backend_flags & sys::ImGuiBackendFlags_RendererHasViewports != 0
396        }
397    }
398}
399
400#[cfg(all(test, feature = "multi-viewport"))]
401mod tests {
402    use super::*;
403
404    #[test]
405    fn platform_teardown_observers_run_with_the_receiver_bound() {
406        use crate::context::{
407            ContextAttachment, ContextAttachmentRole, ContextAttachmentTeardownError,
408        };
409        use std::{cell::RefCell, rc::Rc};
410
411        thread_local! {
412            static CALLS: RefCell<Vec<(&'static str, *mut sys::ImGuiContext)>> = const { RefCell::new(Vec::new()) };
413        }
414        fn record(phase: &'static str) {
415            CALLS.with_borrow_mut(|calls| {
416                calls.push((phase, unsafe { sys::igGetCurrentContext() }))
417            });
418        }
419        unsafe extern "C" fn destroy(_: *mut crate::Viewport) {
420            record("destroy");
421        }
422        struct Observer;
423
424        impl ContextAttachment for Observer {
425            fn begin_platform_window_teardown(
426                &self,
427                _: &ContextPlatformWindowTeardown<'_>,
428            ) -> Result<(), ContextAttachmentTeardownError> {
429                record("begin");
430                Ok(())
431            }
432
433            fn end_platform_window_teardown(
434                &self,
435                _: &ContextPlatformWindowTeardown<'_>,
436            ) -> Result<(), ContextAttachmentTeardownError> {
437                record("end");
438                Ok(())
439            }
440        }
441
442        let _guard = crate::test_support::imgui_context_guard();
443        let first = Context::create();
444        let binding = first.binding();
445        let first_raw = first.as_raw();
446        let _first = first.suspend_or_panic();
447        let mut target = Context::create();
448        let target_raw = target.as_raw();
449        let _lease = target
450            .register_attachment::<Observer>(ContextAttachmentRole::Platform, Rc::new(Observer))
451            .unwrap();
452        unsafe {
453            target
454                .platform_io_mut()
455                .set_platform_destroy_window(Some(destroy))
456        };
457
458        binding.with_bound_context(|| {
459            target.destroy_platform_windows().unwrap();
460            assert_eq!(unsafe { sys::igGetCurrentContext() }, first_raw);
461        });
462        assert_eq!(
463            CALLS.take(),
464            [
465                ("begin", target_raw),
466                ("destroy", target_raw),
467                ("end", target_raw)
468            ]
469        );
470        assert_eq!(unsafe { sys::igGetCurrentContext() }, target_raw);
471    }
472
473    #[test]
474    fn default_platform_render_dispatches_swap_only_backends() {
475        use crate::context::{
476            ContextAttachment, ContextAttachmentRole, ContextAttachmentTeardownError,
477            ContextTeardown, FramePrepareOptions,
478        };
479        use std::{cell::Cell, ffi::c_void, rc::Rc};
480
481        struct Platform;
482        impl ContextAttachment for Platform {
483            fn release_platform_windows(
484                &self,
485                context: &ContextTeardown<'_>,
486            ) -> Result<(), ContextAttachmentTeardownError> {
487                context.with_bound_context(|| unsafe { sys::igDestroyPlatformWindows() });
488                Ok(())
489            }
490        }
491        thread_local! { static SWAPPED: Cell<Option<crate::Id>> = const { Cell::new(None) }; }
492        unsafe extern "C" fn window(_: *mut sys::ImGuiViewport) {}
493        unsafe extern "C" fn title(_: *mut sys::ImGuiViewport, _: *const std::ffi::c_char) {}
494        unsafe extern "C" fn set_vec(_: *mut sys::ImGuiViewport, _: *const sys::ImVec2) {}
495        unsafe extern "C" fn get_pos(vp: *mut sys::ImGuiViewport, out: *mut sys::ImVec2) {
496            unsafe { out.write((*vp).Pos) };
497        }
498        unsafe extern "C" fn get_size(vp: *mut sys::ImGuiViewport, out: *mut sys::ImVec2) {
499            unsafe { out.write((*vp).Size) };
500        }
501        unsafe extern "C" fn swap(vp: *mut crate::platform_io::Viewport, _: *mut c_void) {
502            SWAPPED.set(Some(unsafe { (*vp).id() }));
503        }
504
505        let _guard = crate::test_support::imgui_context_guard();
506        let mut context = Context::create();
507        context
508            .register_attachment::<Platform>(ContextAttachmentRole::Platform, Rc::new(Platform))
509            .unwrap()
510            .defer_to_context();
511        context.set_ini_filename(None::<&str>).unwrap();
512        context
513            .font_atlas()
514            .try_claim_legacy_renderer()
515            .unwrap()
516            .build();
517        context.prepare_frame(FramePrepareOptions::new([128.0, 128.0], 1.0 / 60.0));
518        let flags = context.io().backend_flags()
519            | crate::BackendFlags::PLATFORM_HAS_VIEWPORTS
520            | crate::BackendFlags::RENDERER_HAS_VIEWPORTS;
521        context.io_mut().set_backend_flags(flags);
522        context.io_mut().set_config_viewports_no_auto_merge(true);
523        context.enable_multi_viewport();
524        let screen = sys::ImVec2::new(1920.0, 1080.0);
525        unsafe {
526            context
527                .main_viewport()
528                .set_platform_handle(std::ptr::dangling_mut::<u8>().cast());
529            let io = context.platform_io_mut();
530            io.set_monitors(&[sys::ImGuiPlatformMonitor {
531                MainSize: screen,
532                WorkSize: screen,
533                DpiScale: 1.0,
534                ..Default::default()
535            }]);
536            io.set_platform_create_window_raw(Some(window));
537            io.set_platform_destroy_window_raw(Some(window));
538            io.set_platform_show_window_raw(Some(window));
539            io.set_platform_set_window_title_raw(Some(title));
540            io.set_platform_set_window_pos_raw(Some(set_vec));
541            io.set_platform_set_window_size_raw(Some(set_vec));
542            io.set_platform_get_window_pos_raw(Some(get_pos));
543            io.set_platform_get_window_size_raw(Some(get_size));
544        }
545        for _ in 0..2 {
546            let ui = context.frame();
547            ui.window("Secondary swap target")
548                .position([200.0, 20.0], crate::Condition::Always)
549                .size([80.0, 80.0], crate::Condition::Always)
550                .build(|| ui.text("secondary"));
551            drop(context.render_legacy());
552            context.update_platform_windows();
553        }
554        let secondary = context
555            .platform_io()
556            .viewports_iter()
557            .find(|v| !v.is_main())
558            .unwrap()
559            .id();
560        unsafe {
561            context
562                .platform_io_mut()
563                .set_platform_swap_buffers(Some(swap))
564        };
565        SWAPPED.set(None);
566        context.render_platform_windows_default();
567        assert_eq!(SWAPPED.get(), Some(secondary));
568
569        unsafe {
570            context.platform_io_mut().set_platform_swap_buffers(None);
571            context
572                .platform_io_mut()
573                .set_renderer_swap_buffers(Some(swap));
574        }
575        SWAPPED.set(None);
576        context.render_platform_windows_default();
577        assert_eq!(SWAPPED.get(), Some(secondary));
578    }
579
580    #[test]
581    fn managed_platform_draw_texture_mask_restores_every_pointer() {
582        let mut textures = sys::ImVector_ImTextureDataPtr::default();
583        let textures_ptr = &mut textures as *mut sys::ImVector_ImTextureDataPtr;
584        let mut draw_data = sys::ImDrawData {
585            Textures: textures_ptr,
586            ..Default::default()
587        };
588        let mut viewport = sys::ImGuiViewport {
589            DrawData: &mut draw_data,
590            ..Default::default()
591        };
592        let viewport = &mut viewport as *mut sys::ImGuiViewport;
593        let mut viewports = [viewport, viewport];
594        let mut platform_io = sys::ImGuiPlatformIO {
595            Viewports: sys::ImVector_ImGuiViewportPtr {
596                Size: viewports.len() as i32,
597                Capacity: viewports.len() as i32,
598                Data: viewports.as_mut_ptr(),
599            },
600            ..Default::default()
601        };
602
603        let mask = unsafe { PlatformDrawDataTextureMask::install(&mut platform_io) };
604        assert!(draw_data.Textures.is_null());
605        drop(mask);
606        assert_eq!(draw_data.Textures, textures_ptr);
607    }
608}