Skip to main content

dear_imgui_winit/platform/
window_observation.rs

1use dear_imgui_rs::NativeWindowTarget;
2use winit::window::{Theme, Window};
3
4use super::WinitWindowSnapshot;
5use super::ownership::{WinitPlatform, WinitPlatformControl};
6
7/// Native policy availability, independent of whether a window manager honors every request.
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub enum WinitWindowPolicySupport {
10    Dynamic,
11    CreationOnly,
12    Unsupported,
13}
14
15/// Backend support for editor window policies on the observed native window system.
16#[derive(Clone, Copy, Debug, Eq, PartialEq)]
17pub struct WinitWindowCapabilities {
18    pub secondary_creation: bool,
19    pub icon: WinitWindowPolicySupport,
20    pub client_size_limits: WinitWindowPolicySupport,
21    pub theme: WinitWindowPolicySupport,
22    pub resizable: WinitWindowPolicySupport,
23    pub transparency: WinitWindowPolicySupport,
24    pub parent_owner: WinitWindowPolicySupport,
25    pub desktop_position: WinitWindowPolicySupport,
26}
27
28impl WinitWindowCapabilities {
29    pub(crate) fn capture(window: &Window) -> Self {
30        #[cfg(target_os = "linux")]
31        use WinitWindowPolicySupport::CreationOnly;
32        use WinitWindowPolicySupport::{Dynamic, Unsupported};
33        let desktop = cfg!(any(
34            target_os = "windows",
35            target_os = "macos",
36            target_os = "linux"
37        ));
38        #[cfg(target_os = "linux")]
39        let x11 = {
40            use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle};
41            window.window_handle().is_ok_and(|handle| {
42                matches!(
43                    handle.as_raw(),
44                    RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_)
45                )
46            })
47        };
48        #[cfg(not(target_os = "linux"))]
49        let _ = window;
50        #[cfg(target_os = "linux")]
51        let positioning = x11;
52        #[cfg(not(target_os = "linux"))]
53        let positioning = cfg!(any(target_os = "windows", target_os = "macos"));
54        Self {
55            secondary_creation: cfg!(feature = "multi-viewport") && positioning,
56            icon: if cfg!(target_os = "windows") {
57                Dynamic
58            } else {
59                #[cfg(target_os = "linux")]
60                if x11 {
61                    Dynamic
62                } else {
63                    Unsupported
64                }
65                #[cfg(not(target_os = "linux"))]
66                Unsupported
67            },
68            client_size_limits: if desktop { Dynamic } else { Unsupported },
69            theme: if desktop { Dynamic } else { Unsupported },
70            resizable: if desktop { Dynamic } else { Unsupported },
71            transparency: {
72                #[cfg(target_os = "linux")]
73                {
74                    if x11 { CreationOnly } else { Dynamic }
75                }
76                #[cfg(not(target_os = "linux"))]
77                {
78                    if desktop { Dynamic } else { Unsupported }
79                }
80            },
81            parent_owner: if cfg!(all(feature = "multi-viewport", target_os = "windows")) {
82                Dynamic
83            } else {
84                Unsupported
85            },
86            desktop_position: if positioning { Dynamic } else { Unsupported },
87        }
88    }
89}
90
91/// Native observations. `None` means Winit cannot establish that fact on this platform.
92///
93/// These fields are observations rather than requested creation settings. In particular, native
94/// transparency and icon contents cannot be queried through Winit and are never inferred here.
95#[derive(Clone, Copy, Debug, PartialEq)]
96pub struct WinitWindowNativeState {
97    pub visible: Option<bool>,
98    pub minimized: Option<bool>,
99    pub maximized: Option<bool>,
100    pub focused: Option<bool>,
101    pub resizable: Option<bool>,
102    pub decorations: Option<bool>,
103    pub theme: Option<Theme>,
104    pub transparent: Option<bool>,
105}
106
107impl WinitWindowNativeState {
108    pub(crate) fn capture(window: &Window) -> Self {
109        let desktop = cfg!(any(
110            target_os = "windows",
111            target_os = "macos",
112            target_os = "linux"
113        ));
114        Self {
115            visible: window.is_visible(),
116            minimized: window.is_minimized(),
117            maximized: desktop.then(|| window.is_maximized()),
118            focused: desktop.then(|| window.has_focus()),
119            resizable: cfg!(any(target_os = "windows", target_os = "macos"))
120                .then(|| window.is_resizable()),
121            decorations: desktop.then(|| window.is_decorated()),
122            theme: window.theme(),
123            transparent: None,
124        }
125    }
126}
127
128/// Exactly-once registration observations owned by a platform owner.
129///
130/// `Created` follows successful native publication. `Retired` ends registry access; renderer work
131/// may still retain a native allocation lease. Neither variant retains a window or a Context.
132#[derive(Clone, Copy, Debug, PartialEq)]
133pub enum WinitWindowLifecycleEvent {
134    Created(WinitWindowSnapshot),
135    Retired(NativeWindowTarget),
136}
137
138impl WinitPlatformControl {
139    pub(crate) fn record_window_created(&self, snapshot: WinitWindowSnapshot) {
140        self.ime_enabled_windows
141            .borrow_mut()
142            .remove(&snapshot.target.instance_id);
143        self.binding
144            .clear_ime_preedit_for_viewport(snapshot.target.viewport_id);
145        self.window_lifecycle_events
146            .borrow_mut()
147            .push_back(WinitWindowLifecycleEvent::Created(snapshot));
148    }
149
150    pub(crate) fn record_window_retired(&self, target: NativeWindowTarget) {
151        self.ime_enabled_windows
152            .borrow_mut()
153            .remove(&target.instance_id);
154        self.binding
155            .clear_ime_preedit_for_viewport(target.viewport_id);
156        self.release_pointer_control(
157            super::WinitPointerReleaseReason::Retired,
158            Some(target.instance_id),
159        );
160        #[cfg(feature = "multi-viewport")]
161        if target.is_main
162            && let Some(state) = self.attached_window_render_state.borrow_mut().take()
163        {
164            state.retire();
165        }
166        self.window_lifecycle_events
167            .borrow_mut()
168            .push_back(WinitWindowLifecycleEvent::Retired(target));
169    }
170
171    pub(super) fn retire_main_window_registration(&self) {
172        if let Some(mut target) = self.attached_window_target.take() {
173            if self.binding.lifecycle() == dear_imgui_rs::ContextLifecycle::Alive {
174                let viewport = unsafe { dear_imgui_rs::sys::igGetMainViewport() };
175                if !viewport.is_null() {
176                    target.viewport_id = dear_imgui_rs::Id::from(unsafe { (*viewport).ID });
177                }
178            }
179            self.record_window_retired(target);
180        }
181    }
182}
183
184impl WinitPlatform {
185    /// Drains owned lifecycle observations in order, including after explicit shutdown.
186    ///
187    /// This queue is independent of callback faults. Main-window viewport toggles and logical
188    /// routing remaps do not create new registrations and therefore emit no additional events.
189    pub fn drain_window_lifecycle_events(&self) -> Vec<WinitWindowLifecycleEvent> {
190        self.control
191            .window_lifecycle_events
192            .borrow_mut()
193            .drain(..)
194            .collect()
195    }
196}