dear-imgui-winit 0.3.0

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
//! 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 winit::dpi::{LogicalPosition, LogicalSize};
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) };
}

/// 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,
        }
    }
}

/// 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 = dear_imgui_rs::sys::igGetPlatformIO_Nil();

        (*pio).Platform_CreateWindow = Some(winit_create_window);
        (*pio).Platform_DestroyWindow = Some(winit_destroy_window);
        (*pio).Platform_ShowWindow = Some(winit_show_window);
        (*pio).Platform_SetWindowPos = Some(winit_set_window_pos);
        (*pio).Platform_GetWindowPos = Some(winit_get_window_pos);
        (*pio).Platform_SetWindowSize = Some(winit_set_window_size);
        (*pio).Platform_GetWindowSize = Some(winit_get_window_size);
        (*pio).Platform_SetWindowFocus = Some(winit_set_window_focus);
        (*pio).Platform_GetWindowFocus = Some(winit_get_window_focus);
        (*pio).Platform_GetWindowMinimized = Some(winit_get_window_minimized);
        (*pio).Platform_SetWindowTitle = Some(winit_set_window_title);
        (*pio).Platform_GetWindowFramebufferScale = Some(winit_get_window_framebuffer_scale);
        (*pio).Platform_UpdateWindow = Some(winit_update_window);

        // Set up monitors - this is required for multi-viewport
        setup_monitors();
    }

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

/// Set up monitors list for multi-viewport support
unsafe fn setup_monitors() {
    // For now, let's skip the monitor setup and see if ImGui can work without it
    // The assertion suggests ImGui expects monitors to be set up, but let's try a simpler approach

    // We'll let ImGui handle monitor detection internally
    // This is a temporary workaround to get basic multi-viewport working
}

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

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

/// 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) => {
            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;

            // 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.
            eprintln!("Warning: Event routing for viewport windows not yet implemented");
        }
        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
        unsafe {
            let _ = Box::from_raw(vd);
        }
    }
    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 {
    if vp.is_null() {
        return dear_imgui_rs::sys::ImVec2 { x: 0.0, y: 0.0 };
    }

    // Special handling for viewport ID 0 (main viewport or ImGui internal viewport)
    let vp_ref = unsafe { &*vp };
    let viewport_id = vp_ref.ID;
    if viewport_id == 0 {
        // Return safe default for main viewport
        return dear_imgui_rs::sys::ImVec2 { x: 0.0, y: 0.0 };
    }

    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(pos) = window.outer_position() {
                return dear_imgui_rs::sys::ImVec2 {
                    x: pos.x as f32,
                    y: pos.y as f32,
                };
            }
        }
    }

    dear_imgui_rs::sys::ImVec2 { x: 0.0, y: 0.0 }
}

/// 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() } {
            let position = LogicalPosition::new(pos.x as f64, pos.y as f64);
            window.set_outer_position(position);
            vd.ignore_window_pos_event_frame = 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 };
    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() } {
            let size = window.inner_size();
            return dear_imgui_rs::sys::ImVec2 {
                x: size.width as f32,
                y: size.height as f32,
            };
        }
    }

    dear_imgui_rs::sys::ImVec2 { x: 0.0, y: 0.0 }
}

/// 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() } {
            let new_size = LogicalSize::new(size.x as f64, size.y as f64);
            let _ = window.request_inner_size(new_size);
            vd.ignore_window_size_event_frame = 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 };
    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 };
    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 {
    if vp.is_null() {
        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 let Some(vd) = unsafe { vd_ptr.as_ref() } {
        if let Some(window) = unsafe { vd.window.as_ref() } {
            let scale = window.scale_factor() as f32;
            return dear_imgui_rs::sys::ImVec2 { x: scale, y: scale };
        }
    }

    dear_imgui_rs::sys::ImVec2 { x: 1.0, y: 1.0 }
}

/// 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() {}

    // 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
}