dear-imgui-winit 0.13.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
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
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
//! 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.

#![allow(unsafe_op_in_unsafe_fn)]

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

use dear_imgui_rs::Context;
use winit::dpi::{LogicalPosition, LogicalSize};
use winit::event::{Event, WindowEvent};
use winit::event_loop::ActiveEventLoop;
use winit::window::{Window, WindowAttributes, WindowLevel};

// Thread-local storage for winit multi-viewport support
thread_local! {
    static EVENT_LOOP: RefCell<Option<*const ActiveEventLoop>> = const { RefCell::new(None) };
    static VIEWPORT_DATA: RefCell<Vec<(*mut dear_imgui_rs::sys::ImGuiContext, *mut ViewportData)>> = const { RefCell::new(Vec::new()) };
}

// 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)*); }
    }
}

fn abort_on_panic<R>(name: &str, f: impl FnOnce() -> R) -> R {
    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
        Ok(v) => v,
        Err(_) => {
            eprintln!("dear-imgui-winit: panic in {}", name);
            std::process::abort();
        }
    }
}

/// Helper structure stored in the void* PlatformUserData field of each ImGuiViewport
/// to easily retrieve our backend data. Following official ImGui backend pattern.
#[repr(C)]
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,
    // Last framebuffer scale we logged for this viewport (debug only).
    pub last_log_fb_scale: f32,
}

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,
            last_log_fb_scale: 0.0,
        }
    }
}

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

/// Compute the decoration offset in logical pixels: inner_position - outer_position.
///
/// This lets us translate between ImGui's platform coordinate space (client origin)
/// and winit's outer-position APIs. Returns None if either position is unavailable.
fn decoration_offset_logical(window: &Window) -> Option<(f64, f64)> {
    let scale = window.scale_factor();
    let inner_phys = window.inner_position().ok()?;
    let outer_phys = window.outer_position().ok()?;
    let inner_log = inner_phys.to_logical::<f64>(scale);
    let outer_log = outer_phys.to_logical::<f64>(scale);
    Some((inner_log.x - outer_log.x, inner_log.y - outer_log.y))
}

/// Initialize multi-viewport support following official ImGui backend pattern
pub fn init_multi_viewport_support(ctx: &mut Context, main_window: &Window) {
    let _context_guard = unsafe { CurrentContextGuard::bind(ctx.as_raw()) };

    install_platform_callbacks(ctx);

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

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

fn install_platform_callbacks(ctx: &mut Context) {
    let _context_guard = unsafe { CurrentContextGuard::bind(ctx.as_raw()) };

    // Set up platform callbacks using direct C API
    unsafe {
        let pio = ctx.platform_io_mut();
        let pio_sys = pio.as_raw_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; use out-parameter shims for all ImVec2 getters.
        pio.set_platform_get_window_pos_raw(Some(winit_get_window_pos_out));
        pio.set_platform_set_window_size_raw(Some(winit_set_window_size));
        pio.set_platform_get_window_size_raw(Some(winit_get_window_size_out));
        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.
        // ImGui will use FramebufferScale when available, falling back to
        // DisplayFramebufferScale otherwise. Install through the out-parameter shim to avoid the
        // struct-return callback ABI.
        pio.set_platform_get_window_framebuffer_scale_raw(Some(
            winit_get_window_framebuffer_scale_out,
        ));
        (*pio_sys).Platform_GetWindowDpiScale = Some(winit_get_window_dpi_scale);
        pio.set_platform_get_window_work_area_insets_raw(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 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() {
            // Winit reports monitor geometry in physical pixels. Dear ImGui expects
            // monitor rectangles in the same coordinate space as viewport Pos/Size.
            // Our multi-viewport backend uses logical screen coordinates, so convert.
            let scale_f64 = m.scale_factor();
            let scale = scale_f64 as f32;
            let pos_logical = m.position().to_logical::<f64>(scale_f64);
            let size_logical = m.size().to_logical::<f64>(scale_f64);

            let mut monitor = dear_imgui_rs::sys::ImGuiPlatformMonitor::default();
            monitor.MainPos = dear_imgui_rs::sys::ImVec2 {
                x: pos_logical.x as f32,
                y: pos_logical.y as f32,
            };
            monitor.MainSize = dear_imgui_rs::sys::ImVec2 {
                x: size_logical.width as f32,
                y: size_logical.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 scale_f64 = window.scale_factor();
            let scale = scale_f64 as f32;
            let size_logical = window.inner_size().to_logical::<f64>(scale_f64);
            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_logical.width as f32,
                y: size_logical.height as f32,
            };
            monitor.WorkPos = monitor.MainPos;
            monitor.WorkSize = monitor.MainSize;
            monitor.DpiScale = scale;
            out.push(monitor);
        }
        out
    };

    let pio = ctx.platform_io_mut().as_raw_mut();
    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 {
    let _context_guard = unsafe { CurrentContextGuard::bind(imgui_ctx.as_raw()) };

    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_ContextPtr(imgui_ctx.as_raw());
                    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;
                        }
                        if let Some(vd) = viewport_data_ref(vp) {
                            // 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 { .. } => {
                                            // Keep cached scales up-to-date immediately.
                                            let scale = window.scale_factor() as f32;
                                            if scale.is_finite() && scale > 0.0 {
                                                (*vp).DpiScale = scale;
                                                (*vp).FramebufferScale.x = scale;
                                                (*vp).FramebufferScale.y = scale;
                                            }
                                        }
                                        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, .. } => {
                                            // Mark the hovered viewport for Dear ImGui.
                                            imgui_ctx.io_mut().add_mouse_viewport_event(
                                                dear_imgui_rs::Id::from((*vp).ID),
                                            );
                                            // 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 { .. } => {
                                            {
                                                let io = imgui_ctx.io_mut();
                                                io.add_mouse_pos_event([-f32::MAX, -f32::MAX]);
                                                // Mouse left this platform window; clear hovered viewport.
                                                io.add_mouse_viewport_event(
                                                    dear_imgui_rs::Id::default(),
                                                );
                                            }
                                            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,
    }
}

/// Convenience helper: handle an event for both the main window and all ImGui-created viewports.
///
/// This mirrors the pattern used in `examples/02-docking/multi_viewport_wgpu.rs` and helps
/// avoid forgetting to route events to secondary viewports.
///
/// Usage:
///
/// ```ignore
/// let full = Event::WindowEvent { window_id, event: event.clone() };
/// let _ = multi_viewport::handle_event_with_multi_viewport(
///     &mut platform,
///     &mut imgui,
///     &main_window,
///     &full,
/// );
/// ```
#[cfg(feature = "multi-viewport")]
pub fn handle_event_with_multi_viewport<T>(
    platform: &mut crate::platform::WinitPlatform,
    imgui_ctx: &mut Context,
    main_window: &Window,
    event: &Event<T>,
) -> bool {
    let mut consumed = false;

    // Forward events that target the main window through the standard platform handler
    if let Event::WindowEvent { window_id, .. } = event {
        if *window_id == main_window.id() {
            if platform.handle_event(imgui_ctx, main_window, event) {
                consumed = true;
            }
        }
    }

    // Route events (including those for secondary windows) to ImGui viewports
    if route_event_to_viewports(imgui_ctx, event) {
        consumed = true;
    }

    consumed
}

/// Initialize the main viewport with proper ViewportData
fn init_main_viewport(ctx: &mut Context, main_window: &Window) {
    let _context_guard = unsafe { CurrentContextGuard::bind(ctx.as_raw()) };

    unsafe {
        let main_viewport = dear_imgui_rs::sys::igGetMainViewport();
        if main_viewport.is_null() {
            return;
        }

        let existing = (*main_viewport).PlatformUserData as *mut ViewportData;
        let vd = if existing.is_null() {
            let vd = Box::into_raw(Box::new(ViewportData::new()));
            register_viewport_data(vd);
            vd
        } else if is_winit_viewport_data(existing) {
            existing
        } else {
            panic!("main viewport PlatformUserData is already owned by another platform backend");
        };

        (*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;
    }
}

struct CurrentContextGuard {
    previous: *mut dear_imgui_rs::sys::ImGuiContext,
    target: *mut dear_imgui_rs::sys::ImGuiContext,
}

impl CurrentContextGuard {
    unsafe fn bind(target: *mut dear_imgui_rs::sys::ImGuiContext) -> Self {
        let previous = unsafe { dear_imgui_rs::sys::igGetCurrentContext() };
        if previous != target {
            unsafe { dear_imgui_rs::sys::igSetCurrentContext(target) };
        }
        Self { previous, target }
    }
}

impl Drop for CurrentContextGuard {
    fn drop(&mut self) {
        if self.previous != self.target {
            unsafe { dear_imgui_rs::sys::igSetCurrentContext(self.previous) };
        }
    }
}

unsafe fn clear_main_viewport_data_for_current_context() {
    unsafe {
        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;
            let owned_by_winit = is_winit_viewport_data(vd_ptr);
            if owned_by_winit {
                // Main window not owned by us: do not free the window itself
                (*vd_ptr).window = std::ptr::null_mut();
                drop_viewport_data(vd_ptr);
                vp.PlatformUserData = std::ptr::null_mut();
            }
            // Clear handle to avoid dangling pointer
            if vd_ptr.is_null() || owned_by_winit {
                vp.PlatformHandle = std::ptr::null_mut();
            }
        }
    }
}

/// Shutdown multi-viewport support for `ctx`.
pub fn shutdown_multi_viewport_support(ctx: &mut Context) {
    // Clean up any remaining viewports
    unsafe {
        let _context_guard = CurrentContextGuard::bind(ctx.as_raw());

        // The main viewport is owned by the application, not by winit. Clear its winit-owned
        // sidecar data before asking Dear ImGui to destroy platform windows so upstream shutdown
        // assertions don't depend on Platform_DestroyWindow being installed for the main viewport.
        clear_main_viewport_data_for_current_context();
        ctx.destroy_platform_windows();
        clear_main_viewport_data_for_current_context();

        ctx.platform_io_mut().clear_platform_handlers();
    }
}

fn register_viewport_data(ptr: *mut ViewportData) {
    if ptr.is_null() {
        return;
    }
    let ctx = unsafe { dear_imgui_rs::sys::igGetCurrentContext() };
    VIEWPORT_DATA.with(|items| {
        let mut items = items.borrow_mut();
        if !items
            .iter()
            .any(|(entry_ctx, entry_ptr)| *entry_ctx == ctx && *entry_ptr == ptr)
        {
            items.push((ctx, ptr));
        }
    });
}

fn unregister_viewport_data(ptr: *mut ViewportData) {
    if ptr.is_null() {
        return;
    }
    VIEWPORT_DATA.with(|items| {
        items
            .borrow_mut()
            .retain(|(_, entry_ptr)| *entry_ptr != ptr);
    });
}

fn is_winit_viewport_data(ptr: *mut ViewportData) -> bool {
    if ptr.is_null() {
        return false;
    }
    let ctx = unsafe { dear_imgui_rs::sys::igGetCurrentContext() };
    VIEWPORT_DATA.with(|items| {
        items
            .borrow()
            .iter()
            .any(|(entry_ctx, entry_ptr)| *entry_ctx == ctx && *entry_ptr == ptr)
    })
}

unsafe fn viewport_data_ref<'a>(
    vp: *const dear_imgui_rs::sys::ImGuiViewport,
) -> Option<&'a ViewportData> {
    if vp.is_null() {
        return None;
    }
    let ptr = unsafe { (*vp).PlatformUserData as *mut ViewportData };
    if is_winit_viewport_data(ptr) {
        unsafe { ptr.as_ref() }
    } else {
        None
    }
}

unsafe fn viewport_data_mut<'a>(
    vp: *mut dear_imgui_rs::sys::ImGuiViewport,
) -> Option<&'a mut ViewportData> {
    if vp.is_null() {
        return None;
    }
    let ptr = unsafe { (*vp).PlatformUserData as *mut ViewportData };
    if is_winit_viewport_data(ptr) {
        unsafe { ptr.as_mut() }
    } else {
        None
    }
}

unsafe fn drop_viewport_data(ptr: *mut ViewportData) {
    if !is_winit_viewport_data(ptr) {
        return;
    }
    unregister_viewport_data(ptr);
    unsafe {
        let _ = Box::from_raw(ptr);
    }
}

/// Store an `ActiveEventLoop` reference for viewport creation.
///
/// winit's `ActiveEventLoop` is only valid for the duration of the callback it is
/// passed into. Do **not** store it long-term. Call this right before invoking
/// `Context::update_platform_windows()` / `Context::render_platform_windows_default()`
/// (or any other ImGui call that may create viewports), and preferably clear it
/// afterwards via `set_event_loop_for_frame` or `clear_event_loop`.
pub fn set_event_loop(event_loop: &ActiveEventLoop) {
    EVENT_LOOP.with(|el| {
        *el.borrow_mut() = Some(event_loop as *const ActiveEventLoop);
    });
}

/// Clear any previously stored event loop pointer.
pub fn clear_event_loop() {
    EVENT_LOOP.with(|el| {
        *el.borrow_mut() = None;
    });
}

/// A guard that keeps the event loop pointer valid for the current callback.
///
/// Dropping the guard clears the stored pointer.
pub struct EventLoopFrameGuard;

impl Drop for EventLoopFrameGuard {
    fn drop(&mut self) {
        clear_event_loop();
    }
}

/// Set the event loop pointer for the duration of the current callback.
///
/// Recommended usage:
///
/// ```rust,no_run
/// # use dear_imgui_winit::multi_viewport;
/// # use winit::event_loop::ActiveEventLoop;
/// # fn on_redraw(event_loop: &ActiveEventLoop) {
/// let _guard = multi_viewport::set_event_loop_for_frame(event_loop);
/// // imgui.update_platform_windows();
/// // imgui.render_platform_windows_default();
/// # }
/// ```
pub fn set_event_loop_for_frame(event_loop: &ActiveEventLoop) -> EventLoopFrameGuard {
    set_event_loop(event_loop);
    EventLoopFrameGuard
}

// 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) {
    abort_on_panic("Platform_CreateWindow", || {
        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,
        };

        let vp_ref = unsafe { &mut *vp };
        let existing = vp_ref.PlatformUserData as *mut ViewportData;
        if is_winit_viewport_data(existing) {
            return;
        }
        if !existing.is_null() {
            panic!("viewport PlatformUserData is already owned by another platform backend");
        }

        // Create ViewportData
        let vd = Box::into_raw(Box::new(ViewportData::new()));
        register_viewport_data(vd);
        vp_ref.PlatformUserData = vd as *mut c_void;

        // Handle viewport flags
        let viewport_flags = vp_ref.Flags;
        // ImGui provides screen-space *logical* coordinates for Pos/Size, even with multi-viewport.
        // Winit expects logical positions/sizes and applies DPI scaling internally.
        let mut pos_x = vp_ref.Pos.x as f64;
        let mut pos_y = vp_ref.Pos.y as f64;
        if !pos_x.is_finite() {
            pos_x = 0.0;
        }
        if !pos_y.is_finite() {
            pos_y = 0.0;
        }
        let mut size_x = vp_ref.Size.x as f64;
        let mut size_y = vp_ref.Size.y as f64;
        if !size_x.is_finite() || size_x <= 0.0 {
            size_x = 128.0;
        }
        if !size_y.is_finite() || size_y <= 0.0 {
            size_y = 128.0;
        }

        let pos_logical = LogicalPosition::new(pos_x, pos_y);
        let size_logical = LogicalSize::new(size_x, size_y);
        let mut window_attrs = WindowAttributes::default()
            .with_title("ImGui Viewport")
            .with_inner_size(size_logical)
            .with_position(pos_logical)
            .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
                );
                // Ensure outer position matches ImGui expectation.
                //
                // ImGui platform coordinates are relative to the *client* origin, while winit only lets us
                // position by outer window coordinates. Adjust by decoration offset when available.
                let cur_frame = unsafe { dear_imgui_rs::sys::igGetFrameCount() };
                let outer_target = if let Some((dx, dy)) = decoration_offset_logical(&window) {
                    LogicalPosition::new(pos_logical.x - dx, pos_logical.y - dy)
                } else {
                    pos_logical
                };
                window.set_outer_position(winit::dpi::Position::Logical(outer_target));

                let window_ptr = Box::into_raw(Box::new(window));
                unsafe {
                    (*vd).window = window_ptr;
                    (*vd).window_owned = true;
                    (*vd).ignore_window_pos_event_frame = cur_frame;
                    (*vd).ignore_window_size_event_frame = cur_frame;
                }
                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;

                // Note: winit does not allow registering per-window event callbacks here.
                // The application must forward `Event::WindowEvent` to
                // `handle_event_with_multi_viewport` (or `route_event_to_viewports`)
                // so secondary viewport windows receive input and OS move/resize notifications.
            }
            Err(_) => {
                // Clean up ViewportData on failure
                unsafe {
                    drop_viewport_data(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) {
    abort_on_panic("Platform_DestroyWindow", || {
        if vp.is_null() {
            return;
        }

        let vp_ref = unsafe { &mut *vp };
        let vd_ptr = vp_ref.PlatformUserData as *mut ViewportData;
        if vd_ptr.is_null() {
            vp_ref.PlatformUserData = std::ptr::null_mut();
            vp_ref.PlatformHandle = std::ptr::null_mut();
            return;
        }
        if !is_winit_viewport_data(vd_ptr) {
            return;
        }

        unsafe {
            if (*vd_ptr).window_owned && !(*vd_ptr).window.is_null() {
                // Clean up the window.
                let _ = Box::from_raw((*vd_ptr).window);
            }
            (*vd_ptr).window = std::ptr::null_mut();

            // Drop the allocation backing `ViewportData`. Avoid creating an `&mut ViewportData`
            // reference and then freeing it while that reference is still live.
            drop_viewport_data(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) {
    abort_on_panic("Platform_ShowWindow", || {
        if vp.is_null() {
            return;
        }

        let vp_ref = unsafe { &*vp };
        if let Some(vd) = unsafe { viewport_data_ref(vp_ref) } {
            if let Some(window) = unsafe { vd.window.as_ref() } {
                window.set_visible(true);
            }
        }
    });
}

/// Get window position through an out-parameter to avoid MSVC small-aggregate returns.
unsafe extern "C" fn winit_get_window_pos_out(
    vp: *mut dear_imgui_rs::sys::ImGuiViewport,
    out_pos: *mut dear_imgui_rs::sys::ImVec2,
) {
    abort_on_panic("winit_get_window_pos_out", || {
        let mut r = dear_imgui_rs::sys::ImVec2 { x: 0.0, y: 0.0 };
        if !vp.is_null() {
            let vp_ref = &*vp;
            if let Some(vd) = viewport_data_ref(vp) {
                if let Some(window) = vd.window.as_ref() {
                    let scale = window.scale_factor();
                    if let Ok(pos_phys) = window.inner_position() {
                        let pos_logical = pos_phys.to_logical::<f64>(scale);
                        r.x = pos_logical.x as f32;
                        r.y = pos_logical.y as f32;
                    } else if let Ok(pos_phys) = window.outer_position() {
                        let pos_logical = pos_phys.to_logical::<f64>(scale);
                        r.x = pos_logical.x as f32;
                        r.y = pos_logical.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,
) {
    abort_on_panic("winit_set_window_pos", || {
        if vp.is_null() {
            return;
        }

        if let Some(vd) = unsafe { viewport_data_mut(vp) } {
            if let Some(window) = unsafe { vd.window.as_ref() } {
                // ImGui provides screen-space logical coordinates relative to client origin.
                // Convert to outer coordinates for winit by subtracting decoration offset.
                let desired_client = LogicalPosition::new(pos.x as f64, pos.y as f64);
                let outer_target = if let Some((dx, dy)) = decoration_offset_logical(window) {
                    LogicalPosition::new(desired_client.x - dx, desired_client.y - dy)
                } else {
                    desired_client
                };
                window.set_outer_position(winit::dpi::Position::Logical(outer_target));
                vd.ignore_window_pos_event_frame = unsafe { dear_imgui_rs::sys::igGetFrameCount() };
            }
        }
    });
}

/// Get window size through an out-parameter to avoid MSVC small-aggregate returns.
unsafe extern "C" fn winit_get_window_size_out(
    vp: *mut dear_imgui_rs::sys::ImGuiViewport,
    out_size: *mut dear_imgui_rs::sys::ImVec2,
) {
    abort_on_panic("winit_get_window_size_out", || {
        let mut r = dear_imgui_rs::sys::ImVec2 { x: 0.0, y: 0.0 };
        if !vp.is_null() {
            let vp_ref = &*vp;
            if let Some(vd) = viewport_data_ref(vp) {
                if let Some(window) = vd.window.as_ref() {
                    let size_phys = window.inner_size();
                    let size_logical: LogicalSize<f64> =
                        size_phys.to_logical(window.scale_factor());
                    r.x = size_logical.width as f32;
                    r.y = size_logical.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,
) {
    abort_on_panic("winit_set_window_size", || {
        if vp.is_null() {
            return;
        }

        if let Some(vd) = unsafe { viewport_data_mut(vp) } {
            if let Some(window) = unsafe { vd.window.as_ref() } {
                // ImGui provides inner size in logical pixels; pass through directly.
                let logical: LogicalSize<f64> = LogicalSize::new(size.x as f64, size.y as f64);
                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) {
    abort_on_panic("winit_set_window_focus", || {
        if vp.is_null() {
            return;
        }

        let vp_ref = unsafe { &*vp };
        if let Some(vd) = unsafe { viewport_data_ref(vp_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 {
    abort_on_panic("winit_get_window_focus", || {
        if vp.is_null() {
            return false;
        }

        let vp_ref = unsafe { &*vp };
        // Query from actual OS window if available (main or secondary)
        if let Some(vd) = unsafe { viewport_data_ref(vp_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 {
    abort_on_panic("Platform_GetWindowMinimized", || {
        if vp.is_null() {
            return false;
        }

        let vp_ref = unsafe { &*vp };
        // Query from actual OS window if available (main or secondary)
        if let Some(vd) = unsafe { viewport_data_ref(vp_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,
) {
    abort_on_panic("Platform_SetWindowTitle", || {
        if vp.is_null() || title.is_null() {
            return;
        }

        let vp_ref = unsafe { &*vp };
        if let Some(vd) = unsafe { viewport_data_ref(vp_ref) } {
            if let Some(window) = unsafe { vd.window.as_ref() } {
                let title = unsafe { CStr::from_ptr(title) }.to_string_lossy();
                window.set_title(title.as_ref());
            }
        }
    });
}

/// Get window framebuffer scale
unsafe extern "C" fn winit_get_window_framebuffer_scale_out(
    vp: *mut dear_imgui_rs::sys::ImGuiViewport,
    out_scale: *mut dear_imgui_rs::sys::ImVec2,
) {
    abort_on_panic("Platform_GetWindowFramebufferScale", || {
        if out_scale.is_null() {
            return;
        }

        let mut result = dear_imgui_rs::sys::ImVec2 { x: 1.0, y: 1.0 };
        if vp.is_null() {
            unsafe { *out_scale = result };
            return;
        }

        let vp_ref = unsafe { &*vp };
        if let Some(vd) = unsafe { viewport_data_mut(vp) } {
            // Always report actual framebuffer scale for this viewport, including the main one.
            // Dear ImGui relies on this to compute correct scaling when windows move between
            // viewports. Upstream backends (GLFW/SDL) do the same.
            if vd.window.is_null() {
                unsafe { *out_scale = result };
                return;
            }
            if let Some(window) = unsafe { vd.window.as_ref() } {
                let scale = window.scale_factor() as f32;
                if cfg!(feature = "mv-log") && (scale - vd.last_log_fb_scale).abs() > 0.01 {
                    mvlog!(
                        "[winit-mv] fb_scale changed id={} -> {:.2}",
                        vp_ref.ID,
                        scale
                    );
                    vd.last_log_fb_scale = scale;
                }
                result = dear_imgui_rs::sys::ImVec2 { x: scale, y: scale };
            }
        }
        unsafe { *out_scale = result };
    })
}

/// Get window DPI scale (float)
unsafe extern "C" fn winit_get_window_dpi_scale(vp: *mut dear_imgui_rs::sys::ImGuiViewport) -> f32 {
    abort_on_panic("Platform_GetWindowDpiScale", || {
        if vp.is_null() {
            return 1.0;
        }
        let vp_ref = &mut *vp;
        let mut scale = 1.0f32;
        if let Some(vd) = viewport_data_ref(vp_ref) {
            if let Some(window) = vd.window.as_ref() {
                scale = window.scale_factor() as f32;
            }
        }
        if !scale.is_finite() || scale <= 0.0 {
            scale = 1.0;
        }
        scale
    })
}

/// Notify viewport changed.
///
/// Dear ImGui calls this when a viewport changes monitor or ownership. We use it
/// for targeted debug output to diagnose DPI/scale transitions without per-frame spam.
unsafe extern "C" fn winit_on_changed_viewport(vp: *mut dear_imgui_rs::sys::ImGuiViewport) {
    abort_on_panic("Platform_OnChangedViewport", || {
        if vp.is_null() {
            return;
        }
        let vp_ref = &*vp;
        mvlog!(
            "[winit-mv] OnChangedViewport id={} pos=({:.1},{:.1}) size=({:.1},{:.1}) dpi_scale={:.2} fb_scale=({:.2},{:.2})",
            vp_ref.ID,
            vp_ref.Pos.x,
            vp_ref.Pos.y,
            vp_ref.Size.x,
            vp_ref.Size.y,
            vp_ref.DpiScale,
            vp_ref.FramebufferScale.x,
            vp_ref.FramebufferScale.y
        );
    });
}

/// Set window alpha (no-op for winit)
unsafe extern "C" fn winit_set_window_alpha(
    vp: *mut dear_imgui_rs::sys::ImGuiViewport,
    _alpha: f32,
) {
    abort_on_panic("Platform_SetWindowAlpha", || {
        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,
) {
    abort_on_panic("Platform_RenderWindow", || {
        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,
) {
    abort_on_panic("Platform_SwapBuffers", || {
        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 {
    abort_on_panic("Platform_CreateVkSurface", || {
        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) {
    abort_on_panic("Platform_UpdateWindow", || {
        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
    });
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_util::test_sync::lock_context;

    #[test]
    fn install_platform_callbacks_targets_passed_context() {
        let _guard = lock_context();

        let mut ctx_a = Context::create();
        let raw_a = ctx_a.as_raw();
        let pio_a = unsafe { dear_imgui_rs::sys::igGetPlatformIO_ContextPtr(raw_a) };

        unsafe {
            dear_imgui_rs::sys::igSetCurrentContext(std::ptr::null_mut());
        }

        let ctx_b = Context::create();
        let raw_b = ctx_b.as_raw();
        let pio_b = unsafe { dear_imgui_rs::sys::igGetPlatformIO_ContextPtr(raw_b) };

        install_platform_callbacks(&mut ctx_a);

        unsafe {
            assert_eq!(dear_imgui_rs::sys::igGetCurrentContext(), raw_b);

            assert!((*pio_a).Platform_CreateWindow.is_some());
            assert!((*pio_a).Platform_GetWindowPos.is_some());
            assert!((*pio_a).Platform_GetWindowSize.is_some());
            assert!((*pio_a).Platform_GetWindowFramebufferScale.is_some());
            assert!((*pio_a).Platform_GetWindowDpiScale.is_some());
            assert!((*pio_a).Platform_OnChangedViewport.is_some());

            assert!((*pio_b).Platform_CreateWindow.is_none());
            assert!((*pio_b).Platform_GetWindowPos.is_none());
            assert!((*pio_b).Platform_GetWindowSize.is_none());
            assert!((*pio_b).Platform_GetWindowFramebufferScale.is_none());
            assert!((*pio_b).Platform_GetWindowDpiScale.is_none());
            assert!((*pio_b).Platform_OnChangedViewport.is_none());

            dear_imgui_rs::sys::igSetCurrentContext(raw_a);
        }
        drop(ctx_a);
        unsafe {
            dear_imgui_rs::sys::igSetCurrentContext(raw_b);
        }
        drop(ctx_b);
    }

    #[test]
    fn shutdown_multi_viewport_support_targets_passed_context() {
        let _guard = lock_context();

        let mut ctx_a = Context::create();
        let raw_a = ctx_a.as_raw();
        let main_viewport_a = unsafe { dear_imgui_rs::sys::igGetMainViewport() };
        let vd_a = unsafe {
            let vd = Box::into_raw(Box::new(ViewportData::new()));
            register_viewport_data(vd);
            (*main_viewport_a).PlatformUserData = vd.cast();
            vd
        };

        unsafe {
            dear_imgui_rs::sys::igSetCurrentContext(std::ptr::null_mut());
        }

        let mut ctx_b = Context::create();
        let raw_b = ctx_b.as_raw();
        let main_viewport_b = unsafe { dear_imgui_rs::sys::igGetMainViewport() };
        let vd_b = unsafe {
            let vd = Box::into_raw(Box::new(ViewportData::new()));
            register_viewport_data(vd);
            (*main_viewport_b).PlatformUserData = vd.cast();
            vd
        };

        shutdown_multi_viewport_support(&mut ctx_a);

        unsafe {
            assert_eq!(dear_imgui_rs::sys::igGetCurrentContext(), raw_b);
            assert!((*main_viewport_a).PlatformUserData.is_null());
            assert!(!(*main_viewport_b).PlatformUserData.is_null());
            assert!(is_winit_viewport_data(vd_b));
            assert!(!std::ptr::eq(
                (*main_viewport_b).PlatformUserData.cast::<ViewportData>(),
                vd_a
            ));
        }

        shutdown_multi_viewport_support(&mut ctx_b);
        unsafe {
            assert_eq!(dear_imgui_rs::sys::igGetCurrentContext(), raw_b);
            assert!((*main_viewport_b).PlatformUserData.is_null());
            assert!(!is_winit_viewport_data(vd_b));
            dear_imgui_rs::sys::igSetCurrentContext(raw_a);
        }
        drop(ctx_a);
        unsafe {
            dear_imgui_rs::sys::igSetCurrentContext(raw_b);
        }
        drop(ctx_b);
    }
}