dear-imgui-winit 0.4.1

Winit backend for Dear ImGui
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
//! Multi-viewport support for Dear ImGui winit backend
//!
//! This module provides multi-viewport functionality following the official
//! ImGui backend pattern, allowing Dear ImGui to create and manage multiple
//! OS windows for advanced UI layouts.

use std::cell::RefCell;
use std::ffi::{CStr, c_char, c_void};

use dear_imgui_rs::Context;
use dear_imgui_rs::platform_io::Viewport as IoViewport;
use winit::dpi::{LogicalPosition, LogicalSize};
use winit::event::{
    ElementState, Event, Ime, KeyEvent, MouseButton, MouseScrollDelta, WindowEvent,
};
use winit::event_loop::ActiveEventLoop;
use winit::window::{Window, WindowAttributes, WindowLevel};

// Note: We previously experimented with external C++ debug stubs to validate MSVC ABI when
// returning aggregates by value. These are no longer used; we register our Rust implementations
// directly to PlatformIO below.

// Thread-local storage for winit multi-viewport support
thread_local! {
    static EVENT_LOOP: RefCell<Option<*const ActiveEventLoop>> = const { RefCell::new(None) };
}

// Debug logging helper (off by default). Enable by building this crate with
// `--features mv-log`.
#[allow(unused_macros)]
macro_rules! mvlog {
    ($($arg:tt)*) => {
        if cfg!(feature = "mv-log") { eprintln!($($arg)*); }
    }
}

/// Helper structure stored in the void* PlatformUserData field of each ImGuiViewport
/// to easily retrieve our backend data. Following official ImGui backend pattern.
#[repr(C)]
pub struct ViewportData {
    pub window: *mut Window, // Stored in ImGuiViewport::PlatformHandle
    pub window_owned: bool,  // Set to false for main window
    pub ignore_window_pos_event_frame: i32,
    pub ignore_window_size_event_frame: i32,
}

impl Default for ViewportData {
    fn default() -> Self {
        Self::new()
    }
}

impl ViewportData {
    pub fn new() -> Self {
        Self {
            window: std::ptr::null_mut(),
            window_owned: false,
            ignore_window_pos_event_frame: -1,
            ignore_window_size_event_frame: -1,
        }
    }
}

// Convert client-area logical coordinates to screen coordinates (physical), per-window
pub(crate) fn client_to_screen_pos(window: &Window, logical: [f64; 2]) -> Option<[f32; 2]> {
    // Cross-platform: absolute screen = client top-left (physical) + client offset (physical)
    let scale = window.scale_factor();
    let offset_px_x = (logical[0] * scale) as f32;
    let offset_px_y = (logical[1] * scale) as f32;
    let base = window
        .inner_position()
        .ok()
        .map(|p| [p.x as f32, p.y as f32])
        .or_else(|| {
            window
                .outer_position()
                .ok()
                .map(|p| [p.x as f32, p.y as f32])
        });
    if let Some([bx, by]) = base {
        Some([bx + offset_px_x, by + offset_px_y])
    } else {
        Some([logical[0] as f32, logical[1] as f32])
    }
}

/// Initialize multi-viewport support following official ImGui backend pattern
pub fn init_multi_viewport_support(ctx: &mut Context, main_window: &Window) {
    // Set up platform callbacks using direct C API
    unsafe {
        let pio = ctx.platform_io_mut();
        // Install platform callbacks using raw function pointers
        pio.set_platform_create_window_raw(Some(winit_create_window));
        pio.set_platform_destroy_window_raw(Some(winit_destroy_window));
        pio.set_platform_show_window_raw(Some(winit_show_window));
        pio.set_platform_set_window_pos_raw(Some(winit_set_window_pos));
        // Avoid direct ImVec2 return on MSVC; use cimgui setters with out-params below
        pio.set_platform_get_window_pos_raw(None);
        pio.set_platform_set_window_size_raw(Some(winit_set_window_size));
        pio.set_platform_get_window_size_raw(None);
        pio.set_platform_set_window_focus_raw(Some(winit_set_window_focus));
        pio.set_platform_get_window_focus_raw(Some(winit_get_window_focus));
        pio.set_platform_get_window_minimized_raw(Some(winit_get_window_minimized));
        pio.set_platform_set_window_title_raw(Some(winit_set_window_title));
        pio.set_platform_update_window_raw(Some(winit_update_window));

        // Also register framebuffer/DPI scale and work area insets callbacks
        let pio_sys = dear_imgui_rs::sys::igGetPlatformIO_Nil();
        // Install out-parameter getters via cimgui helpers (avoid struct-return ABI)
        dear_imgui_rs::sys::ImGuiPlatformIO_Set_Platform_GetWindowPos(
            pio_sys,
            Some(winit_get_window_pos_out_v2),
        );
        dear_imgui_rs::sys::ImGuiPlatformIO_Set_Platform_GetWindowSize(
            pio_sys,
            Some(winit_get_window_size_out_v2),
        );
        // Enable framebuffer scale callback for proper HiDPI support
        // Note: We use DpiScale (float) instead of FramebufferScale (ImVec2) to avoid MSVC ABI issues
        // ImGui will use DpiScale for both X and Y if FramebufferScale is not set
        (*pio_sys).Platform_GetWindowFramebufferScale = None; // Keep None, use DpiScale instead
        (*pio_sys).Platform_GetWindowDpiScale = Some(winit_get_window_dpi_scale);
        (*pio_sys).Platform_GetWindowWorkAreaInsets = None;
        (*pio_sys).Platform_OnChangedViewport = Some(winit_on_changed_viewport);
        // Provide no-op implementations to avoid null-calls
        (*pio_sys).Platform_SetWindowAlpha = Some(winit_set_window_alpha);
        (*pio_sys).Platform_RenderWindow = Some(winit_platform_render_window);
        (*pio_sys).Platform_SwapBuffers = Some(winit_platform_swap_buffers);
        (*pio_sys).Platform_CreateVkSurface = Some(winit_platform_create_vk_surface);

        // Audit: print which callbacks are null/non-null to catch missing ones
        macro_rules! chk {
            ($name:expr, $ptr:expr) => {};
        }
        chk!("CreateWindow", (*pio_sys).Platform_CreateWindow);
        chk!("DestroyWindow", (*pio_sys).Platform_DestroyWindow);
        chk!("ShowWindow", (*pio_sys).Platform_ShowWindow);
        chk!("SetWindowPos", (*pio_sys).Platform_SetWindowPos);
        chk!("GetWindowPos", (*pio_sys).Platform_GetWindowPos);
        chk!("SetWindowSize", (*pio_sys).Platform_SetWindowSize);
        chk!("GetWindowSize", (*pio_sys).Platform_GetWindowSize);
        chk!(
            "GetWindowFramebufferScale",
            (*pio_sys).Platform_GetWindowFramebufferScale
        );
        chk!("SetWindowFocus", (*pio_sys).Platform_SetWindowFocus);
        chk!("GetWindowFocus", (*pio_sys).Platform_GetWindowFocus);
        chk!("GetWindowMinimized", (*pio_sys).Platform_GetWindowMinimized);
        chk!("SetWindowTitle", (*pio_sys).Platform_SetWindowTitle);
        chk!("SetWindowAlpha", (*pio_sys).Platform_SetWindowAlpha);
        chk!("UpdateWindow", (*pio_sys).Platform_UpdateWindow);
        chk!("RenderWindow", (*pio_sys).Platform_RenderWindow);
        chk!("SwapBuffers", (*pio_sys).Platform_SwapBuffers);
        chk!("GetWindowDpiScale", (*pio_sys).Platform_GetWindowDpiScale);
        chk!("OnChangedViewport", (*pio_sys).Platform_OnChangedViewport);
        chk!(
            "GetWindowWorkAreaInsets",
            (*pio_sys).Platform_GetWindowWorkAreaInsets
        );
        chk!("CreateVkSurface", (*pio_sys).Platform_CreateVkSurface);
    }

    // Set up the main viewport
    init_main_viewport(main_window);

    // Set up monitors - required for multi-viewport (after main viewport exists)
    unsafe {
        setup_monitors_with_window(main_window, ctx);
    }
}

/// Set up monitors list for multi-viewport support using a reference window
unsafe fn setup_monitors_with_window(window: &Window, _ctx: &mut Context) {
    // Build monitor list from winit and feed into ImGuiPlatformIO.Monitors.
    // We allocate storage using ImGui's allocator to keep ownership consistent.
    let monitors: Vec<dear_imgui_rs::sys::ImGuiPlatformMonitor> = {
        let mut out = Vec::new();
        let mut iter = window.available_monitors();
        while let Some(m) = iter.next() {
            let pos = m.position();
            let size = m.size();
            let scale = m.scale_factor() as f32;

            let mut monitor = dear_imgui_rs::sys::ImGuiPlatformMonitor::default();
            monitor.MainPos = dear_imgui_rs::sys::ImVec2 {
                x: pos.x as f32,
                y: pos.y as f32,
            };
            monitor.MainSize = dear_imgui_rs::sys::ImVec2 {
                x: size.width as f32,
                y: size.height as f32,
            };
            monitor.WorkPos = monitor.MainPos;
            monitor.WorkSize = monitor.MainSize;
            monitor.DpiScale = scale;
            monitor.PlatformHandle = std::ptr::null_mut();
            out.push(monitor);
        }

        if out.is_empty() {
            // Fallback using window bounds
            let size = window.inner_size();
            let scale = window.scale_factor() as f32;
            let mut monitor = dear_imgui_rs::sys::ImGuiPlatformMonitor::default();
            monitor.MainPos = dear_imgui_rs::sys::ImVec2 { x: 0.0, y: 0.0 };
            monitor.MainSize = dear_imgui_rs::sys::ImVec2 {
                x: size.width as f32,
                y: size.height as f32,
            };
            monitor.WorkPos = monitor.MainPos;
            monitor.WorkSize = monitor.MainSize;
            monitor.DpiScale = scale;
            out.push(monitor);
        }
        out
    };

    let pio = dear_imgui_rs::sys::igGetPlatformIO_Nil();
    let vec = unsafe { &mut (*pio).Monitors };

    // Free existing storage if any (owned by ImGui allocator)
    if vec.Capacity > 0 && !vec.Data.is_null() {
        dear_imgui_rs::sys::igMemFree(vec.Data as *mut _);
        vec.Data = std::ptr::null_mut();
        vec.Size = 0;
        vec.Capacity = 0;
    }

    let count = monitors.len();
    let bytes = count * std::mem::size_of::<dear_imgui_rs::sys::ImGuiPlatformMonitor>();
    let data_ptr = if bytes > 0 {
        dear_imgui_rs::sys::igMemAlloc(bytes) as *mut dear_imgui_rs::sys::ImGuiPlatformMonitor
    } else {
        std::ptr::null_mut()
    };

    if !data_ptr.is_null() {
        for (i, m) in monitors.iter().enumerate() {
            *data_ptr.add(i) = *m;
        }
        vec.Data = data_ptr;
        vec.Size = count as i32;
        vec.Capacity = count as i32;
    }
}

/// Try to route a winit event to the correct ImGui viewport window
/// Returns true if the event was consumed by Dear ImGui
pub fn route_event_to_viewports<T>(imgui_ctx: &mut Context, event: &Event<T>) -> bool {
    match event {
        Event::WindowEvent { window_id, event } => {
            // Iterate ImGui viewports and find the window that matches this event's WindowId
            #[cfg(feature = "multi-viewport")]
            {
                unsafe {
                    let pio = dear_imgui_rs::sys::igGetPlatformIO_Nil();
                    let viewports = &(*pio).Viewports;
                    if viewports.Data.is_null() || viewports.Size <= 0 {
                        return false;
                    }
                    for i in 0..viewports.Size {
                        let vp = *viewports.Data.add(i as usize);
                        if vp.is_null() {
                            continue;
                        }
                        let vd_ptr = (*vp).PlatformUserData as *mut ViewportData;
                        if vd_ptr.is_null() {
                            continue;
                        }
                        if let Some(vd) = vd_ptr.as_ref() {
                            // Skip main viewport: its events are handled by the primary platform path
                            if !vd.window_owned {
                                continue;
                            }
                            if let Some(window) = vd.window.as_ref() {
                                if &window.id() == window_id {
                                    // Handle OS-move/resize/DPI change/close notifications → set flags and scales
                                    match event {
                                        WindowEvent::Moved(_) => {
                                            let cur = dear_imgui_rs::sys::igGetFrameCount();
                                            if vd.ignore_window_pos_event_frame != cur {
                                                (*vp).PlatformRequestMove = true;
                                            }
                                        }
                                        WindowEvent::Resized(_) => {
                                            let cur = dear_imgui_rs::sys::igGetFrameCount();
                                            if vd.ignore_window_size_event_frame != cur {
                                                (*vp).PlatformRequestResize = true;
                                            }
                                        }
                                        WindowEvent::ScaleFactorChanged {
                                            scale_factor, ..
                                        } => {
                                            let s = *scale_factor as f32;
                                            (*vp).DpiScale = s;
                                            (*vp).FramebufferScale.x = s;
                                            (*vp).FramebufferScale.y = s;
                                        }
                                        WindowEvent::CloseRequested => {
                                            (*vp).PlatformRequestClose = true;
                                        }
                                        _ => {}
                                    }
                                    // Route specific events using existing handlers
                                    match event {
                                        WindowEvent::KeyboardInput { event, .. } => {
                                            return crate::events::handle_keyboard_input(
                                                event, imgui_ctx,
                                            );
                                        }
                                        WindowEvent::ModifiersChanged(mods) => {
                                            crate::events::handle_modifiers_changed(
                                                mods, imgui_ctx,
                                            );
                                            return imgui_ctx.io().want_capture_keyboard();
                                        }
                                        WindowEvent::MouseWheel { delta, .. } => {
                                            return crate::events::handle_mouse_wheel(
                                                *delta, imgui_ctx,
                                            );
                                        }
                                        WindowEvent::MouseInput { state, button, .. } => {
                                            return crate::events::handle_mouse_button(
                                                *button, *state, imgui_ctx,
                                            );
                                        }
                                        WindowEvent::CursorMoved { position, .. } => {
                                            // With multi-viewports, feed absolute/screen coordinates
                                            let pos_logical =
                                                position.to_logical(window.scale_factor());
                                            let logical = [pos_logical.x, pos_logical.y];
                                            if let Some(screen) =
                                                client_to_screen_pos(window, logical)
                                            {
                                                return crate::events::handle_cursor_moved(
                                                    [screen[0] as f64, screen[1] as f64],
                                                    imgui_ctx,
                                                );
                                            } else {
                                                let pos =
                                                    position.to_logical(window.scale_factor());
                                                return crate::events::handle_cursor_moved(
                                                    [pos.x, pos.y],
                                                    imgui_ctx,
                                                );
                                            }
                                        }
                                        WindowEvent::CursorLeft { .. } => {
                                            imgui_ctx
                                                .io_mut()
                                                .add_mouse_pos_event([-f32::MAX, -f32::MAX]);
                                            return false;
                                        }
                                        WindowEvent::Focused(focused) => {
                                            return crate::events::handle_focused(
                                                *focused, imgui_ctx,
                                            );
                                        }
                                        WindowEvent::Ime(ime) => {
                                            crate::events::handle_ime_event(ime, imgui_ctx);
                                            return imgui_ctx.io().want_capture_keyboard();
                                        }
                                        _ => {}
                                    }
                                }
                            }
                        }
                    }
                }
            }
            false
        }
        _ => false,
    }
}

/// Initialize the main viewport with proper ViewportData
fn init_main_viewport(main_window: &Window) {
    unsafe {
        let main_viewport = dear_imgui_rs::sys::igGetMainViewport();

        if !main_viewport.is_null() {
            let vp = &*main_viewport;
        }

        // Create ViewportData for main window
        let vd = Box::into_raw(Box::new(ViewportData::new()));
        (*vd).window = main_window as *const Window as *mut Window;
        (*vd).window_owned = false; // Main window is owned by the application

        (*main_viewport).PlatformUserData = vd as *mut c_void;
        (*main_viewport).PlatformHandle = main_window as *const Window as *mut c_void;
    }
}

/// Shutdown multi-viewport support
pub fn shutdown_multi_viewport_support() {
    // Clean up any remaining viewports
    unsafe {
        dear_imgui_rs::sys::igDestroyPlatformWindows();
        // Also clean up main viewport's PlatformUserData allocated by us
        let main_viewport = dear_imgui_rs::sys::igGetMainViewport();
        if !main_viewport.is_null() {
            let vp = &mut *main_viewport;
            let vd_ptr = vp.PlatformUserData as *mut ViewportData;
            if !vd_ptr.is_null() {
                // Main window not owned by us: do not free the window itself
                (*vd_ptr).window = std::ptr::null_mut();
                let _ = Box::from_raw(vd_ptr);
                vp.PlatformUserData = std::ptr::null_mut();
            }
            // Clear handle to avoid dangling pointer
            vp.PlatformHandle = std::ptr::null_mut();
        }
    }
}

/// Store event loop reference for viewport creation
pub fn set_event_loop(event_loop: &ActiveEventLoop) {
    EVENT_LOOP.with(|el| {
        *el.borrow_mut() = Some(event_loop as *const ActiveEventLoop);
    });
}

// Platform callback functions following official ImGui backend pattern

/// Create a new viewport window
unsafe extern "C" fn winit_create_window(vp: *mut dear_imgui_rs::sys::ImGuiViewport) {
    if vp.is_null() {
        return;
    }

    // Get event loop reference
    let event_loop = EVENT_LOOP.with(|el| el.borrow().map(|ptr| unsafe { &*ptr }));

    let event_loop = match event_loop {
        Some(el) => el,
        None => return,
    };

    // Create ViewportData
    let vd = Box::into_raw(Box::new(ViewportData::new()));
    let vp_ref = unsafe { &mut *vp };
    vp_ref.PlatformUserData = vd as *mut c_void;

    // Handle viewport flags
    let viewport_flags = vp_ref.Flags;
    let mut window_attrs = WindowAttributes::default()
        .with_title("ImGui Viewport")
        .with_inner_size(LogicalSize::new(vp_ref.Size.x as f64, vp_ref.Size.y as f64))
        .with_position(winit::dpi::Position::Logical(LogicalPosition::new(
            vp_ref.Pos.x as f64,
            vp_ref.Pos.y as f64,
        )))
        .with_visible(false); // Start hidden, will be shown by show_window callback

    // Handle decorations
    if viewport_flags & (dear_imgui_rs::sys::ImGuiViewportFlags_NoDecoration as i32) != 0 {
        window_attrs = window_attrs.with_decorations(false);
    }

    // Handle always on top
    if viewport_flags & (dear_imgui_rs::sys::ImGuiViewportFlags_TopMost as i32) != 0 {
        window_attrs = window_attrs.with_window_level(WindowLevel::AlwaysOnTop);
    }

    // Create the window
    match event_loop.create_window(window_attrs) {
        Ok(window) => {
            mvlog!(
                "[winit-mv] Platform_CreateWindow id={} size=({}, {})",
                vp_ref.ID,
                vp_ref.Size.x,
                vp_ref.Size.y
            );
            let window_ptr = Box::into_raw(Box::new(window));
            unsafe {
                (*vd).window = window_ptr;
                (*vd).window_owned = true;
            }
            vp_ref.PlatformHandle = window_ptr as *mut c_void;

            // Initialize DPI/framebuffer scale immediately
            let window_ref: &Window = unsafe { &*window_ptr };
            let scale = window_ref.scale_factor() as f32;
            vp_ref.DpiScale = scale;
            vp_ref.FramebufferScale.x = scale;
            vp_ref.FramebufferScale.y = scale;

            // TODO: Set up event callbacks for this window
            // This is a critical missing piece - we need to route events from this window
            // back to ImGui. For now, this is a known limitation.
        }
        Err(_) => {
            // Clean up ViewportData on failure
            unsafe {
                let _ = Box::from_raw(vd);
            }
            vp_ref.PlatformUserData = std::ptr::null_mut();
        }
    }
}

/// Destroy a viewport window
unsafe extern "C" fn winit_destroy_window(vp: *mut dear_imgui_rs::sys::ImGuiViewport) {
    if vp.is_null() {
        return;
    }

    let vp_ref = unsafe { &mut *vp };
    let vd_ptr = vp_ref.PlatformUserData as *mut ViewportData;
    if let Some(vd) = unsafe { vd_ptr.as_mut() } {
        if vd.window_owned && !vd.window.is_null() {
            // Clean up the window
            unsafe {
                let _ = Box::from_raw(vd.window);
            }
        }
        vd.window = std::ptr::null_mut();

        // Clean up ViewportData using the original raw pointer
        unsafe {
            let _ = Box::from_raw(vd_ptr);
        }
    }
    vp_ref.PlatformUserData = std::ptr::null_mut();
    vp_ref.PlatformHandle = std::ptr::null_mut();
}

/// Show a viewport window
unsafe extern "C" fn winit_show_window(vp: *mut dear_imgui_rs::sys::ImGuiViewport) {
    if vp.is_null() {
        return;
    }

    let vp_ref = unsafe { &*vp };
    let vd_ptr = vp_ref.PlatformUserData as *mut ViewportData;
    if let Some(vd) = unsafe { vd_ptr.as_ref() } {
        if let Some(window) = unsafe { vd.window.as_ref() } {
            window.set_visible(true);
        }
    }
}

/// Get window position
unsafe extern "C" fn winit_get_window_pos(
    vp: *mut dear_imgui_rs::sys::ImGuiViewport,
) -> dear_imgui_rs::sys::ImVec2 {
    mvlog!("[winit-mv] ENTER winit_get_window_pos vp={:?}", vp);
    if vp.is_null() {
        mvlog!("[winit-mv] LEAVE winit_get_window_pos (null vp) -> (0,0)");
        return dear_imgui_rs::sys::ImVec2 { x: 0.0, y: 0.0 };
    }

    let vp_ref = &*vp;

    // For main viewport (check by ID or lack of owned window data)
    // The main viewport might not always have ID == 0
    let vd_ptr = vp_ref.PlatformUserData as *mut ViewportData;
    let is_main_viewport = if vd_ptr.is_null() {
        true
    } else if let Some(vd) = vd_ptr.as_ref() {
        !vd.window_owned
    } else {
        true
    };

    if is_main_viewport {
        let result = dear_imgui_rs::sys::ImVec2 {
            x: vp_ref.Pos.x,
            y: vp_ref.Pos.y,
        };
        mvlog!(
            "[winit-mv] LEAVE winit_get_window_pos (main) -> ({:.1}, {:.1})",
            result.x,
            result.y
        );
        return result;
    }

    let vd_ptr = vp_ref.PlatformUserData as *mut ViewportData;
    if let Some(vd) = vd_ptr.as_ref() {
        // Only query window position for windows we own
        if vd.window_owned && !vd.window.is_null() {
            if let Some(window) = vd.window.as_ref() {
                // Prefer client-area top-left in screen space
                if let Some([sx, sy]) = client_to_screen_pos(window, [0.0, 0.0]) {
                    let result = dear_imgui_rs::sys::ImVec2 { x: sx, y: sy };
                    mvlog!(
                        "[winit-mv] LEAVE winit_get_window_pos (client->screen) -> ({:.1}, {:.1})",
                        result.x,
                        result.y
                    );
                    return result;
                }
                // Fallback
                match window.outer_position() {
                    Ok(pos) => {
                        let result = dear_imgui_rs::sys::ImVec2 {
                            x: pos.x as f32,
                            y: pos.y as f32,
                        };
                        mvlog!(
                            "[winit-mv] LEAVE winit_get_window_pos (outer) -> ({:.1}, {:.1})",
                            result.x,
                            result.y
                        );
                        return result;
                    }
                    Err(e) => {
                        mvlog!("[winit-mv] outer_position error: {:?}", e);
                    }
                }
            }
        }
    }

    // Fallback to viewport's stored position
    let result = dear_imgui_rs::sys::ImVec2 {
        x: vp_ref.Pos.x,
        y: vp_ref.Pos.y,
    };
    mvlog!(
        "[winit-mv] LEAVE winit_get_window_pos (fallback) -> ({:.1}, {:.1})",
        result.x,
        result.y
    );
    result
}

/// Get window position (out-parameter version to avoid MSVC small-aggregate return)
unsafe extern "C" fn winit_get_window_pos_out(
    vp: *mut dear_imgui_rs::sys::ImGuiViewport,
    out_pos: *mut dear_imgui_rs::sys::ImVec2,
) {
    let mut r = dear_imgui_rs::sys::ImVec2 { x: 0.0, y: 0.0 };
    if !vp.is_null() {
        let vp_ref = &*vp;
        let vd_ptr = vp_ref.PlatformUserData as *mut ViewportData;
        // Heuristic: main viewport or missing data → use cached Pos
        let is_main = vd_ptr.is_null()
            || (|| {
                if let Some(vd) = unsafe { vd_ptr.as_ref() } {
                    !vd.window_owned
                } else {
                    true
                }
            })();
        if is_main {
            r.x = vp_ref.Pos.x;
            r.y = vp_ref.Pos.y;
        } else if let Some(vd) = unsafe { vd_ptr.as_ref() } {
            if !vd.window.is_null() {
                if let Some(window) = unsafe { vd.window.as_ref() } {
                    if let Some([sx, sy]) = client_to_screen_pos(window, [0.0, 0.0]) {
                        r.x = sx;
                        r.y = sy;
                    } else if let Ok(pos) = window.outer_position() {
                        r.x = pos.x as f32;
                        r.y = pos.y as f32;
                    } else {
                        r.x = vp_ref.Pos.x;
                        r.y = vp_ref.Pos.y;
                    }
                }
            }
        }
    }
    if !out_pos.is_null() {
        unsafe {
            *out_pos = r;
        }
    }
}

/// Get window position (v2: always prefer OS window position when available)
unsafe extern "C" fn winit_get_window_pos_out_v2(
    vp: *mut dear_imgui_rs::sys::ImGuiViewport,
    out_pos: *mut dear_imgui_rs::sys::ImVec2,
) {
    let mut r = dear_imgui_rs::sys::ImVec2 { x: 0.0, y: 0.0 };
    if !vp.is_null() {
        let vp_ref = &*vp;
        let vd_ptr = vp_ref.PlatformUserData as *mut ViewportData;
        if let Some(vd) = vd_ptr.as_ref() {
            if let Some(window) = vd.window.as_ref() {
                if let Some([sx, sy]) = client_to_screen_pos(window, [0.0, 0.0]) {
                    r.x = sx;
                    r.y = sy;
                } else if let Ok(pos) = window.outer_position() {
                    r.x = pos.x as f32;
                    r.y = pos.y as f32;
                } else {
                    r.x = vp_ref.Pos.x;
                    r.y = vp_ref.Pos.y;
                }
            } else {
                r.x = vp_ref.Pos.x;
                r.y = vp_ref.Pos.y;
            }
        } else {
            r.x = vp_ref.Pos.x;
            r.y = vp_ref.Pos.y;
        }
    }
    if !out_pos.is_null() {
        *out_pos = r;
    }
}

/// Set window position
unsafe extern "C" fn winit_set_window_pos(
    vp: *mut dear_imgui_rs::sys::ImGuiViewport,
    pos: dear_imgui_rs::sys::ImVec2,
) {
    if vp.is_null() {
        return;
    }

    let vp_ref = unsafe { &*vp };
    let vd_ptr = vp_ref.PlatformUserData as *mut ViewportData;
    if let Some(vd) = unsafe { vd_ptr.as_mut() } {
        if let Some(window) = unsafe { vd.window.as_mut() } {
            // ImGui provides screen-space physical pixels; convert to logical for winit
            let phys = winit::dpi::PhysicalPosition::new(pos.x as f64, pos.y as f64);
            let logical: winit::dpi::LogicalPosition<f64> = phys.to_logical(window.scale_factor());
            window.set_outer_position(winit::dpi::Position::Logical(logical));
            vd.ignore_window_pos_event_frame = unsafe { dear_imgui_rs::sys::igGetFrameCount() };
        }
    }
}

/// Get window size
unsafe extern "C" fn winit_get_window_size(
    vp: *mut dear_imgui_rs::sys::ImGuiViewport,
) -> dear_imgui_rs::sys::ImVec2 {
    if vp.is_null() {
        return dear_imgui_rs::sys::ImVec2 { x: 0.0, y: 0.0 };
    }

    let vp_ref = unsafe { &*vp };

    // For main viewport, always use stored size since we don't own the window handle
    if vp_ref.ID == 0 || vp_ref.PlatformUserData.is_null() {
        let result = dear_imgui_rs::sys::ImVec2 {
            x: vp_ref.Size.x,
            y: vp_ref.Size.y,
        };

        return result;
    }

    let vd_ptr = vp_ref.PlatformUserData as *mut ViewportData;
    if let Some(vd) = unsafe { vd_ptr.as_ref() } {
        // Only query window size for windows we own
        if vd.window_owned && !vd.window.is_null() {
            if let Some(window) = unsafe { vd.window.as_ref() } {
                let size = window.inner_size();
                let result = dear_imgui_rs::sys::ImVec2 {
                    x: size.width as f32,
                    y: size.height as f32,
                };

                return result;
            }
        }
    }

    // Fallback to viewport's stored size
    let result = dear_imgui_rs::sys::ImVec2 {
        x: vp_ref.Size.x,
        y: vp_ref.Size.y,
    };

    result
}

/// Get window size (out-parameter version to avoid MSVC small-aggregate return)
unsafe extern "C" fn winit_get_window_size_out(
    vp: *mut dear_imgui_rs::sys::ImGuiViewport,
    out_size: *mut dear_imgui_rs::sys::ImVec2,
) {
    let mut r = dear_imgui_rs::sys::ImVec2 { x: 0.0, y: 0.0 };
    if !vp.is_null() {
        let vp_ref = &*vp;
        if vp_ref.ID == 0 || vp_ref.PlatformUserData.is_null() {
            r.x = vp_ref.Size.x;
            r.y = vp_ref.Size.y;
        } else {
            let vd_ptr = vp_ref.PlatformUserData as *mut ViewportData;
            if let Some(vd) = unsafe { vd_ptr.as_ref() } {
                if vd.window_owned && !vd.window.is_null() {
                    if let Some(window) = unsafe { vd.window.as_ref() } {
                        let size = window.inner_size();
                        r.x = size.width as f32;
                        r.y = size.height as f32;
                    }
                } else {
                    r.x = vp_ref.Size.x;
                    r.y = vp_ref.Size.y;
                }
            }
        }
    }
    if !out_size.is_null() {
        unsafe {
            *out_size = r;
        }
    }
}

/// Get window size (v2: always prefer OS inner size when available)
unsafe extern "C" fn winit_get_window_size_out_v2(
    vp: *mut dear_imgui_rs::sys::ImGuiViewport,
    out_size: *mut dear_imgui_rs::sys::ImVec2,
) {
    let mut r = dear_imgui_rs::sys::ImVec2 { x: 0.0, y: 0.0 };
    if !vp.is_null() {
        let vp_ref = &*vp;
        let vd_ptr = vp_ref.PlatformUserData as *mut ViewportData;
        if let Some(vd) = vd_ptr.as_ref() {
            if let Some(window) = vd.window.as_ref() {
                let size = window.inner_size();
                r.x = size.width as f32;
                r.y = size.height as f32;
            } else {
                r.x = vp_ref.Size.x;
                r.y = vp_ref.Size.y;
            }
        } else {
            r.x = vp_ref.Size.x;
            r.y = vp_ref.Size.y;
        }
    }
    if !out_size.is_null() {
        *out_size = r;
    }
}

/// Set window size
unsafe extern "C" fn winit_set_window_size(
    vp: *mut dear_imgui_rs::sys::ImGuiViewport,
    size: dear_imgui_rs::sys::ImVec2,
) {
    if vp.is_null() {
        return;
    }

    let vp_ref = unsafe { &*vp };
    let vd_ptr = vp_ref.PlatformUserData as *mut ViewportData;
    if let Some(vd) = unsafe { vd_ptr.as_mut() } {
        if let Some(window) = unsafe { vd.window.as_mut() } {
            // ImGui provides inner size in physical pixels; convert to logical for winit
            let scale = window.scale_factor();
            let logical: winit::dpi::LogicalSize<f64> =
                LogicalSize::new((size.x as f64) / scale, (size.y as f64) / scale);
            let _ = window.request_inner_size(winit::dpi::Size::Logical(logical));
            vd.ignore_window_size_event_frame = unsafe { dear_imgui_rs::sys::igGetFrameCount() };
        }
    }
}

/// Set window focus
unsafe extern "C" fn winit_set_window_focus(vp: *mut dear_imgui_rs::sys::ImGuiViewport) {
    if vp.is_null() {
        return;
    }

    let vp_ref = unsafe { &*vp };
    let vd_ptr = vp_ref.PlatformUserData as *mut ViewportData;
    if let Some(vd) = unsafe { vd_ptr.as_ref() } {
        if let Some(window) = unsafe { vd.window.as_ref() } {
            window.focus_window();
        }
    }
}

/// Get window focus
unsafe extern "C" fn winit_get_window_focus(vp: *mut dear_imgui_rs::sys::ImGuiViewport) -> bool {
    if vp.is_null() {
        return false;
    }

    let vp_ref = unsafe { &*vp };
    // Query from actual OS window if available (main or secondary)
    let vd_ptr = vp_ref.PlatformUserData as *mut ViewportData;
    if let Some(vd) = unsafe { vd_ptr.as_ref() } {
        if let Some(window) = unsafe { vd.window.as_ref() } {
            return window.has_focus();
        }
    }
    false
}

/// Get window minimized state
unsafe extern "C" fn winit_get_window_minimized(
    vp: *mut dear_imgui_rs::sys::ImGuiViewport,
) -> bool {
    if vp.is_null() {
        return false;
    }

    let vp_ref = unsafe { &*vp };
    // Query from actual OS window if available (main or secondary)
    let vd_ptr = vp_ref.PlatformUserData as *mut ViewportData;
    if let Some(vd) = unsafe { vd_ptr.as_ref() } {
        if let Some(window) = unsafe { vd.window.as_ref() } {
            return window.is_minimized().unwrap_or(false);
        }
    }
    false
}

/// Set window title
unsafe extern "C" fn winit_set_window_title(
    vp: *mut dear_imgui_rs::sys::ImGuiViewport,
    title: *const c_char,
) {
    if vp.is_null() || title.is_null() {
        return;
    }

    let vp_ref = unsafe { &*vp };
    let vd_ptr = vp_ref.PlatformUserData as *mut ViewportData;
    if let Some(vd) = unsafe { vd_ptr.as_ref() } {
        if let Some(window) = unsafe { vd.window.as_ref() } {
            if let Ok(title_str) = unsafe { CStr::from_ptr(title) }.to_str() {
                window.set_title(title_str);
            }
        }
    }
}

/// Get window framebuffer scale
unsafe extern "C" fn winit_get_window_framebuffer_scale(
    vp: *mut dear_imgui_rs::sys::ImGuiViewport,
) -> dear_imgui_rs::sys::ImVec2 {
    mvlog!(
        "[winit-mv] ENTER winit_get_window_framebuffer_scale vp={:?}",
        vp
    );
    if vp.is_null() {
        mvlog!("[winit-mv] LEAVE winit_get_window_framebuffer_scale (null) -> (1,1)");
        return dear_imgui_rs::sys::ImVec2 { x: 1.0, y: 1.0 };
    }

    let vp_ref = unsafe { &*vp };
    let vd_ptr = vp_ref.PlatformUserData as *mut ViewportData;
    if vd_ptr.is_null() {
        mvlog!(
            "[winit-mv] LEAVE winit_get_window_framebuffer_scale (no PlatformUserData) -> (1,1)"
        );
        return dear_imgui_rs::sys::ImVec2 { x: 1.0, y: 1.0 };
    }
    if let Some(vd) = unsafe { vd_ptr.as_ref() } {
        if vd.window.is_null() {
            mvlog!("[winit-mv] LEAVE winit_get_window_framebuffer_scale (no window) -> (1,1)");
            return dear_imgui_rs::sys::ImVec2 { x: 1.0, y: 1.0 };
        }
        if let Some(window) = unsafe { vd.window.as_ref() } {
            let scale = window.scale_factor() as f32;
            mvlog!(
                "[winit-mv] LEAVE winit_get_window_framebuffer_scale -> ({:.2}, {:.2})",
                scale,
                scale
            );
            return dear_imgui_rs::sys::ImVec2 { x: scale, y: scale };
        }
    }
    mvlog!("[winit-mv] LEAVE winit_get_window_framebuffer_scale (fallback) -> (1,1)");
    dear_imgui_rs::sys::ImVec2 { x: 1.0, y: 1.0 }
}

/// Get window DPI scale (float)
unsafe extern "C" fn winit_get_window_dpi_scale(vp: *mut dear_imgui_rs::sys::ImGuiViewport) -> f32 {
    if vp.is_null() {
        return 1.0;
    }
    let vp_ref = &*vp;
    let vd_ptr = vp_ref.PlatformUserData as *mut ViewportData;
    if let Some(vd) = vd_ptr.as_ref() {
        if let Some(window) = vd.window.as_ref() {
            return window.scale_factor() as f32;
        }
    }
    1.0
}

/// Get window work area insets (ImVec4: left, top, right, bottom)
unsafe extern "C" fn winit_get_window_work_area_insets(
    _vp: *mut dear_imgui_rs::sys::ImGuiViewport,
) -> dear_imgui_rs::sys::ImVec4 {
    dear_imgui_rs::sys::ImVec4 {
        x: 0.0,
        y: 0.0,
        z: 0.0,
        w: 0.0,
    }
}

/// Notify viewport changed (no-op)
unsafe extern "C" fn winit_on_changed_viewport(_vp: *mut dear_imgui_rs::sys::ImGuiViewport) {}

/// Set window alpha (no-op for winit)
unsafe extern "C" fn winit_set_window_alpha(
    vp: *mut dear_imgui_rs::sys::ImGuiViewport,
    alpha: f32,
) {
    if vp.is_null() {
        return;
    }
}

/// Platform render window (no-op; renderer handles rendering)
unsafe extern "C" fn winit_platform_render_window(
    vp: *mut dear_imgui_rs::sys::ImGuiViewport,
    _render_arg: *mut c_void,
) {
    if vp.is_null() {
        return;
    }
}

/// Platform swap buffers (no-op; renderer handles present)
unsafe extern "C" fn winit_platform_swap_buffers(
    vp: *mut dear_imgui_rs::sys::ImGuiViewport,
    _render_arg: *mut c_void,
) {
    if vp.is_null() {
        return;
    }
}

/// Platform create Vulkan surface (not used; return failure)
unsafe extern "C" fn winit_platform_create_vk_surface(
    _vp: *mut dear_imgui_rs::sys::ImGuiViewport,
    _vk_inst: u64,
    _vk_allocators: *const c_void,
    out_vk_surface: *mut u64,
) -> ::std::os::raw::c_int {
    if !out_vk_surface.is_null() {
        *out_vk_surface = 0;
    }
    -1 // Not supported
}

/// Update window - called by ImGui for platform-specific updates
unsafe extern "C" fn winit_update_window(vp: *mut dear_imgui_rs::sys::ImGuiViewport) {
    if vp.is_null() {
        return;
    }

    // For now, this is a no-op. In GLFW implementation, this is used for
    // platform-specific window updates. Winit handles most of this automatically.
    // We might need to add specific logic here later for things like:
    // - Window state synchronization
    // - Platform-specific optimizations
    // - Event processing
}