dear-imgui-winit 0.18.0

Winit platform backend for dear-imgui-rs
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
use winit::window::Window;

use super::WinitPlatformError;

#[cfg(target_os = "windows")]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) struct NativeMouseState {
    pub(super) position: [i32; 2],
    pub(super) hovered_window: Option<usize>,
    pub(super) focused_window: Option<usize>,
}

#[cfg(target_os = "windows")]
struct WindowsCursorHitTestState {
    input_enabled: std::sync::atomic::AtomicBool,
    no_focus_on_click: std::sync::atomic::AtomicBool,
}

pub(super) struct NativeCursorHitTest {
    #[cfg(target_os = "windows")]
    windows: windows::WindowsCursorHitTest,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum MouseCaptureTransfer {
    NotOwned,
    Transferred,
}

impl NativeCursorHitTest {
    pub(super) fn install(window: &Window) -> Result<Self, WinitPlatformError> {
        #[cfg(target_os = "windows")]
        {
            Ok(Self {
                windows: windows::WindowsCursorHitTest::install(window)?,
            })
        }

        #[cfg(not(target_os = "windows"))]
        {
            let _ = window;
            Ok(Self {})
        }
    }

    pub(super) fn set_enabled(
        &self,
        window: &Window,
        enabled: bool,
    ) -> Result<(), WinitPlatformError> {
        #[cfg(target_os = "windows")]
        {
            let _ = window;
            self.windows.set_enabled(enabled);
            Ok(())
        }

        #[cfg(not(target_os = "windows"))]
        {
            window.set_cursor_hittest(enabled).map_err(|error| {
                WinitPlatformError::WindowOperation {
                    operation: "set_cursor_hittest",
                    message: error.to_string(),
                }
            })
        }
    }

    pub(super) fn set_no_focus_on_click(
        &self,
        window: &Window,
        enabled: bool,
    ) -> Result<(), WinitPlatformError> {
        #[cfg(target_os = "windows")]
        {
            let _ = window;
            self.windows.set_no_focus_on_click(enabled);
            Ok(())
        }

        #[cfg(not(target_os = "windows"))]
        {
            let _ = (window, enabled);
            Ok(())
        }
    }

    #[cfg(target_os = "windows")]
    pub(super) fn native_window_id(&self) -> usize {
        self.windows.native_window_id()
    }
}

#[cfg(target_os = "windows")]
pub(super) fn query_native_mouse_state() -> Option<NativeMouseState> {
    windows::query_native_mouse_state()
}

pub(super) fn transfer_mouse_capture(
    source: &Window,
    target: &Window,
) -> Result<MouseCaptureTransfer, WinitPlatformError> {
    #[cfg(target_os = "windows")]
    {
        windows::transfer_mouse_capture(source, target)
    }

    #[cfg(not(target_os = "windows"))]
    {
        let _ = (source, target);
        Ok(MouseCaptureTransfer::NotOwned)
    }
}

pub(super) fn raise_window_without_activation(window: &Window) -> Result<(), WinitPlatformError> {
    #[cfg(target_os = "windows")]
    {
        windows::raise_window_without_activation(window)
    }

    #[cfg(target_os = "macos")]
    {
        macos::raise_window_without_activation(window)
    }

    #[cfg(not(any(target_os = "windows", target_os = "macos")))]
    {
        let _ = window;
        Ok(())
    }
}

pub(super) fn show_window_without_activation(window: &Window) -> Result<(), WinitPlatformError> {
    #[cfg(target_os = "macos")]
    {
        macos::raise_window_without_activation(window)
    }

    #[cfg(not(target_os = "macos"))]
    {
        window.set_visible(true);
        Ok(())
    }
}

pub(super) fn focus_and_raise_window(window: &Window) -> Result<(), WinitPlatformError> {
    #[cfg(target_os = "windows")]
    {
        windows::focus_and_raise_window(window)
    }

    #[cfg(not(target_os = "windows"))]
    {
        window.focus_window();
        Ok(())
    }
}

#[cfg(target_os = "macos")]
mod macos {
    use objc2_app_kit::NSView;
    use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle};
    use winit::window::Window;

    use super::WinitPlatformError;

    pub(super) fn raise_window_without_activation(
        window: &Window,
    ) -> Result<(), WinitPlatformError> {
        let handle =
            window
                .window_handle()
                .map_err(|error| WinitPlatformError::WindowOperation {
                    operation: "access AppKit viewport window handle",
                    message: error.to_string(),
                })?;
        let RawWindowHandle::AppKit(handle) = handle.as_raw() else {
            return Err(WinitPlatformError::WindowOperation {
                operation: "access AppKit viewport window handle",
                message: "Winit returned a non-AppKit window handle on macOS".to_owned(),
            });
        };

        // SAFETY: Winit's borrowed AppKit handle keeps this NSView alive for the duration of the
        // call, and multi-viewport callbacks run inside Winit's main-thread event-loop scope.
        let view = unsafe { &*handle.ns_view.as_ptr().cast::<NSView>() };
        let native_window = view
            .window()
            .ok_or_else(|| WinitPlatformError::WindowOperation {
                operation: "show AppKit viewport without activation",
                message: "Winit's NSView is not attached to an NSWindow".to_owned(),
            })?;
        native_window.orderFront(None);
        Ok(())
    }
}

#[cfg(target_os = "windows")]
mod windows {
    use std::io;
    use std::sync::atomic::{AtomicBool, Ordering};

    use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, POINT, WPARAM};
    use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
        GetCapture, ReleaseCapture, SetCapture, SetFocus,
    };
    use windows_sys::Win32::UI::Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass};
    use windows_sys::Win32::UI::WindowsAndMessaging::{
        BringWindowToTop, GetCursorPos, GetForegroundWindow, HTTRANSPARENT, HWND_TOP,
        MA_NOACTIVATE, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE, SetForegroundWindow, SetWindowPos,
        WM_MOUSEACTIVATE, WM_NCDESTROY, WM_NCHITTEST, WindowFromPoint,
    };
    use winit::raw_window_handle::{HasWindowHandle, RawWindowHandle};
    use winit::window::Window;

    use super::{MouseCaptureTransfer, NativeMouseState, WinitPlatformError};

    pub(super) struct WindowsCursorHitTest {
        hwnd: HWND,
        state: Box<super::WindowsCursorHitTestState>,
        subclass_id: usize,
    }

    impl WindowsCursorHitTest {
        pub(super) fn install(window: &Window) -> Result<Self, WinitPlatformError> {
            let hwnd = window_handle(window)?;
            let state = Box::new(super::WindowsCursorHitTestState {
                input_enabled: AtomicBool::new(true),
                no_focus_on_click: AtomicBool::new(false),
            });
            let subclass_id = state.as_ref() as *const super::WindowsCursorHitTestState as usize;
            let installed = unsafe {
                SetWindowSubclass(
                    hwnd,
                    Some(cursor_hittest_subclass),
                    subclass_id,
                    subclass_id,
                )
            };
            if installed == 0 {
                return Err(WinitPlatformError::WindowOperation {
                    operation: "install Win32 viewport hit-test hook",
                    message: format!(
                        "SetWindowSubclass returned FALSE ({})",
                        io::Error::last_os_error()
                    ),
                });
            }

            Ok(Self {
                hwnd,
                state,
                subclass_id,
            })
        }

        pub(super) fn native_window_id(&self) -> usize {
            self.hwnd as usize
        }

        pub(super) fn set_enabled(&self, enabled: bool) {
            self.state.input_enabled.store(enabled, Ordering::Release);
        }

        pub(super) fn set_no_focus_on_click(&self, enabled: bool) {
            self.state
                .no_focus_on_click
                .store(enabled, Ordering::Release);
        }
    }

    impl Drop for WindowsCursorHitTest {
        fn drop(&mut self) {
            unsafe {
                RemoveWindowSubclass(self.hwnd, Some(cursor_hittest_subclass), self.subclass_id);
            }
        }
    }

    unsafe extern "system" fn cursor_hittest_subclass(
        hwnd: HWND,
        message: u32,
        wparam: WPARAM,
        lparam: LPARAM,
        subclass_id: usize,
        reference_data: usize,
    ) -> LRESULT {
        let state = unsafe { (reference_data as *const super::WindowsCursorHitTestState).as_ref() };
        let input_enabled = state.is_none_or(|state| state.input_enabled.load(Ordering::Acquire));
        if message == WM_NCHITTEST && !input_enabled {
            return HTTRANSPARENT as LRESULT;
        }
        if message == WM_MOUSEACTIVATE
            && state.is_some_and(|state| state.no_focus_on_click.load(Ordering::Acquire))
        {
            return MA_NOACTIVATE as LRESULT;
        }
        if message == WM_NCDESTROY {
            unsafe {
                RemoveWindowSubclass(hwnd, Some(cursor_hittest_subclass), subclass_id);
            }
        }
        unsafe { DefSubclassProc(hwnd, message, wparam, lparam) }
    }

    fn window_handle(window: &Window) -> Result<HWND, WinitPlatformError> {
        let handle = window
            .window_handle()
            .map_err(|error| WinitPlatformError::WindowOperation {
                operation: "query Win32 window handle",
                message: error.to_string(),
            })?
            .as_raw();
        let RawWindowHandle::Win32(handle) = handle else {
            return Err(WinitPlatformError::WindowOperation {
                operation: "query Win32 window handle",
                message: "Winit returned a non-Win32 window handle on Windows".to_owned(),
            });
        };
        Ok(handle.hwnd.get() as HWND)
    }

    pub(super) fn query_native_mouse_state() -> Option<NativeMouseState> {
        let mut position = POINT { x: 0, y: 0 };
        if unsafe { GetCursorPos(&mut position) } == 0 {
            return None;
        }

        let hovered_window = unsafe { WindowFromPoint(position) };
        let focused_window = unsafe { GetForegroundWindow() };
        Some(NativeMouseState {
            position: [position.x, position.y],
            hovered_window: (!hovered_window.is_null()).then_some(hovered_window as usize),
            focused_window: (!focused_window.is_null()).then_some(focused_window as usize),
        })
    }

    pub(super) fn transfer_mouse_capture(
        source: &Window,
        target: &Window,
    ) -> Result<MouseCaptureTransfer, WinitPlatformError> {
        let source = window_handle(source)?;
        let target = window_handle(target)?;
        if unsafe { GetCapture() } != source {
            return Ok(MouseCaptureTransfer::NotOwned);
        }

        if unsafe { ReleaseCapture() } == 0 {
            return Err(WinitPlatformError::WindowOperation {
                operation: "release Win32 viewport mouse capture",
                message: io::Error::last_os_error().to_string(),
            });
        }
        unsafe {
            SetCapture(target);
        }
        if unsafe { GetCapture() } != target {
            return Err(WinitPlatformError::WindowOperation {
                operation: "transfer Win32 viewport mouse capture",
                message: io::Error::last_os_error().to_string(),
            });
        }
        Ok(MouseCaptureTransfer::Transferred)
    }

    pub(super) fn raise_window_without_activation(
        window: &Window,
    ) -> Result<(), WinitPlatformError> {
        let hwnd = window_handle(window)?;
        let raised = unsafe {
            SetWindowPos(
                hwnd,
                HWND_TOP,
                0,
                0,
                0,
                0,
                SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE,
            )
        };
        if raised == 0 {
            return Err(WinitPlatformError::WindowOperation {
                operation: "raise Win32 viewport without activation",
                message: io::Error::last_os_error().to_string(),
            });
        }
        Ok(())
    }

    pub(super) fn focus_and_raise_window(window: &Window) -> Result<(), WinitPlatformError> {
        let hwnd = window_handle(window)?;
        unsafe {
            // Match the official Win32 backend. SetForegroundWindow may be denied by the OS
            // foreground-lock policy, so these focus requests are intentionally best effort.
            BringWindowToTop(hwnd);
            SetForegroundWindow(hwnd);
            SetFocus(hwnd);
        }
        Ok(())
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        #[test]
        fn no_inputs_maps_only_hit_testing_to_transparent() {
            let state = super::super::WindowsCursorHitTestState {
                input_enabled: AtomicBool::new(false),
                no_focus_on_click: AtomicBool::new(false),
            };
            let reference_data = &state as *const super::super::WindowsCursorHitTestState as usize;

            assert_eq!(
                unsafe {
                    cursor_hittest_subclass(
                        std::ptr::null_mut(),
                        WM_NCHITTEST,
                        0,
                        0,
                        1,
                        reference_data,
                    )
                },
                HTTRANSPARENT as LRESULT
            );
        }

        #[test]
        fn no_focus_on_click_returns_no_activate() {
            let state = super::super::WindowsCursorHitTestState {
                input_enabled: AtomicBool::new(true),
                no_focus_on_click: AtomicBool::new(true),
            };
            let reference_data = &state as *const super::super::WindowsCursorHitTestState as usize;

            assert_eq!(
                unsafe {
                    cursor_hittest_subclass(
                        std::ptr::null_mut(),
                        WM_MOUSEACTIVATE,
                        0,
                        0,
                        1,
                        reference_data,
                    )
                },
                MA_NOACTIVATE as LRESULT
            );
        }
    }
}