dear-imgui-rs 0.13.0

High-level Rust bindings to Dear ImGui v1.92.7 with docking, WGPU/GL backends, and extensions (ImPlot/ImPlot3D, ImNodes, ImGuizmo, file browser, reflection-based UI)
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
//! Legacy columns API
//!
//! Thin wrappers for the old Columns layout system. New code should prefer
//! the `table` API (`widget::table`) which supersedes Columns with more
//! features and better user experience.
//!
#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::as_conversions,
    clippy::unnecessary_cast
)]
use crate::Ui;
use crate::sys;
use bitflags::bitflags;

fn current_columns() -> *mut sys::ImGuiOldColumns {
    unsafe {
        let window = sys::igGetCurrentWindowRead();
        if window.is_null() {
            std::ptr::null_mut()
        } else {
            (*window).DC.CurrentColumns
        }
    }
}

fn assert_no_current_columns(caller: &str) {
    assert!(
        current_columns().is_null(),
        "{caller} cannot be called while another legacy columns layout is active"
    );
}

fn assert_current_columns(caller: &str) -> *mut sys::ImGuiOldColumns {
    let columns = current_columns();
    assert!(
        !columns.is_null(),
        "{caller} must be called inside a legacy columns layout"
    );
    columns
}

fn assert_columns_count(count: i32, caller: &str) {
    assert!(count >= 1, "{caller} count must be at least 1");
}

fn assert_finite_f32(caller: &str, name: &str, value: f32) {
    assert!(value.is_finite(), "{caller} {name} must be finite");
}

fn assert_non_negative_f32(caller: &str, name: &str, value: f32) {
    assert_finite_f32(caller, name, value);
    assert!(value >= 0.0, "{caller} {name} must be non-negative");
}

fn validate_old_column_flags(caller: &str, flags: OldColumnFlags) {
    let unsupported = flags.bits() & !OldColumnFlags::all().bits();
    assert!(
        unsupported == 0,
        "{caller} received unsupported ImGuiOldColumnFlags bits: 0x{unsupported:X}"
    );
}

fn resolve_column_index(column_index: i32, allow_trailing_offset: bool, caller: &str) -> i32 {
    let columns = assert_current_columns(caller);
    let column_index = if column_index < 0 {
        unsafe { (*columns).Current }
    } else {
        column_index
    };
    let upper_bound = unsafe {
        if allow_trailing_offset {
            (*columns).Count
        } else {
            (*columns).Count - 1
        }
    };
    assert!(
        (0..=upper_bound).contains(&column_index),
        "{caller} column index {column_index} is outside the allowed range 0..={upper_bound}"
    );
    column_index
}

bitflags! {
    /// Flags for old columns system
    #[repr(transparent)]
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct OldColumnFlags: i32 {
        /// No flags
        const NONE = sys::ImGuiOldColumnFlags_None as i32;
        /// Disable column dividers
        const NO_BORDER = sys::ImGuiOldColumnFlags_NoBorder as i32;
        /// Disable resizing columns by dragging dividers
        const NO_RESIZE = sys::ImGuiOldColumnFlags_NoResize as i32;
        /// Disable column width preservation when the total width changes
        const NO_PRESERVE_WIDTHS = sys::ImGuiOldColumnFlags_NoPreserveWidths as i32;
        /// Disable forcing columns to fit within window
        const NO_FORCE_WITHIN_WINDOW = sys::ImGuiOldColumnFlags_NoForceWithinWindow as i32;
        /// Restore pre-1.51 behavior of extending the parent window contents size
        const GROW_PARENT_CONTENTS_SIZE = sys::ImGuiOldColumnFlags_GrowParentContentsSize as i32;
    }
}

impl Default for OldColumnFlags {
    fn default() -> Self {
        OldColumnFlags::NONE
    }
}

/// # Columns
impl Ui {
    /// Creates columns layout.
    ///
    /// # Arguments
    /// * `count` - Number of columns (must be >= 1)
    /// * `id` - Optional ID for the columns (can be empty string)
    /// * `border` - Whether to draw borders between columns
    #[doc(alias = "Columns")]
    pub fn columns(&self, count: i32, id: impl AsRef<str>, border: bool) {
        assert_columns_count(count, "Ui::columns()");
        unsafe { sys::igColumns(count, self.scratch_txt(id), border) }
    }

    /// Begin columns layout with advanced flags.
    ///
    /// # Arguments
    /// * `id` - ID for the columns
    /// * `count` - Number of columns (must be >= 1)
    /// * `flags` - Column flags
    #[doc(alias = "BeginColumns")]
    pub fn begin_columns(&self, id: impl AsRef<str>, count: i32, flags: OldColumnFlags) {
        assert_columns_count(count, "Ui::begin_columns()");
        validate_old_column_flags("Ui::begin_columns()", flags);
        assert_no_current_columns("Ui::begin_columns()");
        unsafe { sys::igBeginColumns(self.scratch_txt(id), count, flags.bits()) }
    }

    /// Begin columns layout with advanced flags and return a token that ends columns on drop.
    #[doc(alias = "BeginColumns")]
    pub fn begin_columns_token(
        &self,
        id: impl AsRef<str>,
        count: i32,
        flags: OldColumnFlags,
    ) -> ColumnsToken<'_> {
        self.begin_columns(id, count, flags);
        ColumnsToken { ui: self }
    }

    /// End columns layout.
    #[doc(alias = "EndColumns")]
    pub fn end_columns(&self) {
        assert_current_columns("Ui::end_columns()");
        unsafe { sys::igEndColumns() }
    }

    /// Switches to the next column.
    ///
    /// If the current row is finished, switches to first column of the next row
    #[doc(alias = "NextColumn")]
    pub fn next_column(&self) {
        unsafe { sys::igNextColumn() }
    }

    /// Returns the index of the current column
    #[doc(alias = "GetColumnIndex")]
    pub fn current_column_index(&self) -> i32 {
        unsafe { sys::igGetColumnIndex() }
    }

    /// Returns the width of the current column (in pixels)
    #[doc(alias = "GetColumnWidth")]
    pub fn current_column_width(&self) -> f32 {
        unsafe { sys::igGetColumnWidth(-1) }
    }

    /// Returns the width of the given column (in pixels)
    #[doc(alias = "GetColumnWidth")]
    pub fn column_width(&self, column_index: i32) -> f32 {
        let column_index = if current_columns().is_null() {
            column_index
        } else {
            resolve_column_index(column_index, false, "Ui::column_width()")
        };
        unsafe { sys::igGetColumnWidth(column_index) }
    }

    /// Sets the width of the current column (in pixels)
    #[doc(alias = "SetColumnWidth")]
    pub fn set_current_column_width(&self, width: f32) {
        assert_non_negative_f32("Ui::set_current_column_width()", "width", width);
        unsafe { sys::igSetColumnWidth(-1, width) };
    }

    /// Sets the width of the given column (in pixels)
    #[doc(alias = "SetColumnWidth")]
    pub fn set_column_width(&self, column_index: i32, width: f32) {
        let column_index = resolve_column_index(column_index, false, "Ui::set_column_width()");
        assert_non_negative_f32("Ui::set_column_width()", "width", width);
        unsafe { sys::igSetColumnWidth(column_index, width) };
    }

    /// Returns the offset of the current column (in pixels from the left side of the content region)
    #[doc(alias = "GetColumnOffset")]
    pub fn current_column_offset(&self) -> f32 {
        unsafe { sys::igGetColumnOffset(-1) }
    }

    /// Returns the offset of the given column (in pixels from the left side of the content region)
    #[doc(alias = "GetColumnOffset")]
    pub fn column_offset(&self, column_index: i32) -> f32 {
        let column_index = if current_columns().is_null() {
            column_index
        } else {
            resolve_column_index(column_index, true, "Ui::column_offset()")
        };
        unsafe { sys::igGetColumnOffset(column_index) }
    }

    /// Sets the offset of the current column (in pixels from the left side of the content region)
    #[doc(alias = "SetColumnOffset")]
    pub fn set_current_column_offset(&self, offset_x: f32) {
        assert_non_negative_f32("Ui::set_current_column_offset()", "offset_x", offset_x);
        unsafe { sys::igSetColumnOffset(-1, offset_x) };
    }

    /// Sets the offset of the given column (in pixels from the left side of the content region)
    #[doc(alias = "SetColumnOffset")]
    pub fn set_column_offset(&self, column_index: i32, offset_x: f32) {
        let column_index = resolve_column_index(column_index, true, "Ui::set_column_offset()");
        assert_non_negative_f32("Ui::set_column_offset()", "offset_x", offset_x);
        unsafe { sys::igSetColumnOffset(column_index, offset_x) };
    }

    /// Returns the current amount of columns
    #[doc(alias = "GetColumnsCount")]
    pub fn column_count(&self) -> i32 {
        unsafe { sys::igGetColumnsCount() }
    }

    // ============================================================================
    // Advanced column utilities
    // ============================================================================

    /// Push column clip rect for the given column index.
    /// This is useful for custom drawing within columns.
    #[doc(alias = "PushColumnClipRect")]
    pub fn push_column_clip_rect(&self, column_index: i32) {
        let column_index = resolve_column_index(column_index, false, "Ui::push_column_clip_rect()");
        unsafe { sys::igPushColumnClipRect(column_index) }
    }

    /// Push columns background for drawing.
    #[doc(alias = "PushColumnsBackground")]
    pub fn push_columns_background(&self) {
        assert_current_columns("Ui::push_columns_background()");
        unsafe { sys::igPushColumnsBackground() }
    }

    /// Pop columns background.
    #[doc(alias = "PopColumnsBackground")]
    pub fn pop_columns_background(&self) {
        assert_current_columns("Ui::pop_columns_background()");
        unsafe { sys::igPopColumnsBackground() }
    }

    /// Get columns ID for the given string ID and count.
    #[doc(alias = "GetColumnsID")]
    pub fn get_columns_id(&self, str_id: impl AsRef<str>, count: i32) -> u32 {
        assert_columns_count(count, "Ui::get_columns_id()");
        unsafe { sys::igGetColumnsID(self.scratch_txt(str_id), count) }
    }

    // ============================================================================
    // Column state utilities
    // ============================================================================

    /// Check if any column in the current legacy columns set is being resized.
    ///
    /// Returns `false` when the current window is not inside a legacy columns set.
    pub fn is_any_column_resizing(&self) -> bool {
        unsafe {
            let window = sys::igGetCurrentWindowRead();
            if window.is_null() {
                return false;
            }

            let columns = (*window).DC.CurrentColumns;
            if columns.is_null() {
                return false;
            }

            (*columns).IsBeingResized
        }
    }

    /// Get the total width of all columns.
    pub fn get_columns_total_width(&self) -> f32 {
        let count = self.column_count();
        if count <= 0 {
            return 0.0;
        }

        let mut total_width = 0.0;
        for i in 0..count {
            total_width += self.column_width(i);
        }
        total_width
    }

    /// Set all columns to equal width.
    pub fn set_columns_equal_width(&self) {
        let count = self.column_count();
        if count <= 1 {
            return;
        }

        let total_width = self.get_columns_total_width();
        let equal_width = total_width / count as f32;

        for i in 0..count {
            self.set_column_width(i, equal_width);
        }
    }

    /// Get column width as a percentage of total width.
    pub fn get_column_width_percentage(&self, column_index: i32) -> f32 {
        let total_width = self.get_columns_total_width();
        if total_width <= 0.0 {
            return 0.0;
        }

        let column_width = self.column_width(column_index);
        (column_width / total_width) * 100.0
    }

    /// Set column width as a percentage of total width.
    pub fn set_column_width_percentage(&self, column_index: i32, percentage: f32) {
        assert_non_negative_f32(
            "Ui::set_column_width_percentage()",
            "percentage",
            percentage,
        );
        let total_width = self.get_columns_total_width();
        if total_width <= 0.0 {
            return;
        }

        let new_width = (total_width * percentage) / 100.0;
        self.set_column_width(column_index, new_width);
    }
}

/// Token representing an active columns layout.
#[must_use]
pub struct ColumnsToken<'ui> {
    ui: &'ui Ui,
}

impl Drop for ColumnsToken<'_> {
    fn drop(&mut self) {
        self.ui.end_columns();
    }
}

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

    fn setup_context() -> crate::Context {
        let mut ctx = crate::Context::create();
        let _ = ctx.font_atlas_mut().build();
        ctx.io_mut().set_display_size([128.0, 128.0]);
        ctx.io_mut().set_delta_time(1.0 / 60.0);
        ctx
    }

    #[test]
    fn is_any_column_resizing_reads_current_columns_state() {
        let mut ctx = setup_context();
        let ui = ctx.frame();

        ui.window("columns_resize_test").build(|| {
            assert!(!ui.is_any_column_resizing());

            let _columns = ui.begin_columns_token("legacy_columns", 2, OldColumnFlags::NONE);
            let window = unsafe { crate::sys::igGetCurrentWindowRead() };
            assert!(!window.is_null());

            let columns = unsafe { (*window).DC.CurrentColumns };
            assert!(!columns.is_null());
            assert!(!ui.is_any_column_resizing());

            unsafe {
                (*columns).IsBeingResized = true;
            }

            assert!(ui.is_any_column_resizing());
        });
    }

    #[test]
    fn columns_reject_invalid_counts_and_nested_layouts() {
        let mut ctx = setup_context();
        let ui = ctx.frame();

        ui.window("columns_invalid_counts").build(|| {
            assert!(
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    ui.columns(0, "bad_columns", true);
                }))
                .is_err()
            );
            assert!(
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    let _columns = ui.begin_columns_token("bad_columns", 0, OldColumnFlags::NONE);
                }))
                .is_err()
            );

            let _columns = ui.begin_columns_token("outer_columns", 2, OldColumnFlags::NONE);
            assert!(
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    let _nested = ui.begin_columns_token("nested_columns", 2, OldColumnFlags::NONE);
                }))
                .is_err()
            );
        });
    }

    #[test]
    fn columns_reject_out_of_range_indices_before_ffi() {
        let mut ctx = setup_context();
        let ui = ctx.frame();

        ui.window("columns_index_bounds").build(|| {
            let _columns = ui.begin_columns_token("legacy_columns", 2, OldColumnFlags::NONE);

            assert!(
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    let _ = ui.column_width(2);
                }))
                .is_err()
            );
            assert!(
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    ui.set_column_width(2, 10.0);
                }))
                .is_err()
            );
            assert!(
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    let _ = ui.column_offset(3);
                }))
                .is_err()
            );
            assert!(
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    ui.push_column_clip_rect(2);
                }))
                .is_err()
            );
        });
    }

    #[test]
    fn columns_reject_invalid_flags_and_numeric_inputs_before_ffi() {
        let mut ctx = setup_context();
        let ui = ctx.frame();

        ui.window("columns_numeric_bounds").build(|| {
            assert!(
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    let _columns = ui.begin_columns_token(
                        "bad_flags",
                        2,
                        OldColumnFlags::from_bits_retain(1 << 16),
                    );
                }))
                .is_err()
            );

            let _columns = ui.begin_columns_token("legacy_columns", 2, OldColumnFlags::NONE);
            ui.set_current_column_width(32.0);
            ui.set_current_column_offset(0.0);
            ui.set_column_width(1, 16.0);
            ui.set_column_offset(1, 8.0);
            ui.set_column_width_percentage(1, 25.0);

            ui.set_current_column_width(0.0);
            assert!(
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    ui.set_column_width(1, f32::NAN);
                }))
                .is_err()
            );
            assert!(
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    ui.set_current_column_offset(-1.0);
                }))
                .is_err()
            );
            assert!(
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    ui.set_column_offset(1, f32::INFINITY);
                }))
                .is_err()
            );
            assert!(
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    ui.set_column_width_percentage(1, -1.0);
                }))
                .is_err()
            );
        });
    }
}