dear-imgui-rs 0.17.0

High-level Rust bindings to Dear ImGui v1.92.9b 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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
use super::super::color::ImColor32;
use super::super::counts::{
    DrawCornerFlags, DrawListFlags, DrawNgonSegmentCount, DrawSegmentCount, PolylineFlags,
};
use super::super::util::draw_list_counts;
use super::{DrawListMut, DrawListProvenance};
use crate::sys;

struct TestDrawList {
    shared: *mut sys::ImDrawListSharedData,
    raw: *mut sys::ImDrawList,
}

impl TestDrawList {
    fn new() -> Self {
        let shared = unsafe { sys::ImDrawListSharedData_ImDrawListSharedData() };
        assert!(!shared.is_null());
        let raw = unsafe { sys::ImDrawList_ImDrawList(shared) };
        assert!(!raw.is_null());
        Self { shared, raw }
    }

    fn draw_list(&self) -> DrawListMut<'static> {
        DrawListMut {
            draw_list: self.raw,
            ui: None,
            provenance: DrawListProvenance::Frame,
        }
    }

    fn borrowed_draw_list(&self) -> DrawListMut<'static> {
        DrawListMut::borrow_draw_list(self.raw);
        self.draw_list()
    }

    fn path_size(&self) -> i32 {
        unsafe { (*self.raw)._Path.Size }
    }

    fn clip_stack_size(&self) -> i32 {
        unsafe { (*self.raw)._ClipRectStack.Size }
    }
}

impl Drop for TestDrawList {
    fn drop(&mut self) {
        unsafe {
            sys::ImDrawList_destroy(self.raw);
            sys::ImDrawListSharedData_destroy(self.shared);
        }
    }
}

fn assert_panics_without_buffer_change(
    fixture: &TestDrawList,
    f: impl FnOnce(&DrawListMut<'static>),
) {
    let draw_list = fixture.draw_list();
    let before = draw_list_counts(fixture.raw);
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(&draw_list)));
    assert!(result.is_err());
    assert_eq!(draw_list_counts(fixture.raw), before);
}

#[test]
#[should_panic(
    expected = "A DrawListMut is already in use for this draw list; reuse the existing wrapper or drop it before acquiring another"
)]
fn draw_list_exclusive_use_guard_rejects_duplicate_wrapper() {
    let fixture = TestDrawList::new();
    let _first = fixture.borrowed_draw_list();
    let _duplicate = fixture.borrowed_draw_list();
}

#[test]
fn draw_list_exclusive_use_guard_allows_reacquisition_after_drop() {
    let fixture = TestDrawList::new();
    let first = fixture.borrowed_draw_list();
    drop(first);
    let reacquired = fixture.borrowed_draw_list();
    drop(reacquired);
}

#[test]
fn direct_draw_inputs_validate_before_ffi() {
    let fixture = TestDrawList::new();

    assert_panics_without_buffer_change(&fixture, |draw_list| {
        draw_list.add_line_h(f32::NAN, 1.0, 0.0, ImColor32::WHITE, 1.0);
    });
    assert_panics_without_buffer_change(&fixture, |draw_list| {
        draw_list.add_line_v(0.0, 0.0, 1.0, ImColor32::WHITE, 0.0);
    });
    assert_panics_without_buffer_change(&fixture, |draw_list| {
        draw_list.add_quad(
            [f32::NAN, 0.0],
            [1.0, 0.0],
            [1.0, 1.0],
            [0.0, 1.0],
            ImColor32::WHITE,
            1.0,
        );
    });
    assert_panics_without_buffer_change(&fixture, |draw_list| {
        draw_list.add_ellipse(
            [0.0, 0.0],
            [-1.0, 4.0],
            ImColor32::WHITE,
            0.0,
            DrawSegmentCount::AUTO,
            1.0,
        );
    });
    assert_panics_without_buffer_change(&fixture, |draw_list| {
        draw_list.add_bezier_quadratic(
            [0.0, 0.0],
            [1.0, 1.0],
            [2.0, 0.0],
            ImColor32::WHITE,
            1.0,
            DrawSegmentCount::count(0),
        );
    });
    assert_panics_without_buffer_change(&fixture, |draw_list| {
        draw_list.add_image_rounded(
            crate::texture::TextureId::new(1),
            [0.0, 0.0],
            [16.0, 16.0],
            [0.0, 0.0],
            [1.0, 1.0],
            ImColor32::WHITE,
            f32::INFINITY,
            DrawCornerFlags::ALL,
        );
    });
    assert_panics_without_buffer_change(&fixture, |draw_list| {
        draw_list.path_rect(
            [0.0, 0.0],
            [1.0, 1.0],
            1.0,
            DrawCornerFlags::from_bits_retain(sys::ImDrawFlags_Closed as u32),
        );
    });
}

#[test]
fn path_inputs_validate_before_path_mutation() {
    let fixture = TestDrawList::new();
    let draw_list = fixture.draw_list();

    draw_list.path_line_to([1.0, 1.0]);
    let path_size = fixture.path_size();

    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        draw_list.path_line_to([f32::NAN, 2.0]);
    }));
    assert!(result.is_err());
    assert_eq!(fixture.path_size(), path_size);

    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        draw_list.path_arc_to([0.0, 0.0], -1.0, 0.0, 1.0, DrawSegmentCount::AUTO);
    }));
    assert!(result.is_err());
    assert_eq!(fixture.path_size(), path_size);

    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        draw_list.path_arc_to_fast([0.0, 0.0], 1.0, 0, 13);
    }));
    assert!(result.is_err());
    assert_eq!(fixture.path_size(), path_size);

    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        draw_list.path_bezier_quadratic_curve_to(
            [2.0, 2.0],
            [3.0, 3.0],
            DrawSegmentCount::count(0),
        );
    }));
    assert!(result.is_err());
    assert_eq!(fixture.path_size(), path_size);

    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        draw_list.path_stroke(
            ImColor32::WHITE,
            PolylineFlags::from_bits_retain(sys::ImDrawFlags_RoundCornersTopLeft as u32),
            1.0,
        );
    }));
    assert!(result.is_err());
    assert_eq!(fixture.path_size(), path_size);

    draw_list.path_clear();
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        draw_list.path_bezier_cubic_curve_to(
            [2.0, 2.0],
            [3.0, 3.0],
            [4.0, 4.0],
            DrawSegmentCount::AUTO,
        );
    }));
    assert!(result.is_err());
    assert_eq!(fixture.path_size(), 0);
}

#[test]
fn builder_inputs_validate_before_ffi() {
    let fixture = TestDrawList::new();

    assert_panics_without_buffer_change(&fixture, |draw_list| {
        let _ = draw_list
            .add_line([0.0, 0.0], [1.0, 1.0], ImColor32::WHITE)
            .thickness(0.0);
    });
    assert_panics_without_buffer_change(&fixture, |draw_list| {
        let _ = draw_list.add_circle([0.0, 0.0], -1.0, ImColor32::WHITE);
    });
    assert_panics_without_buffer_change(&fixture, |draw_list| {
        let _ = draw_list
            .add_rect([0.0, 0.0], [1.0, 1.0], ImColor32::WHITE)
            .rounding(f32::NAN);
    });
    assert_panics_without_buffer_change(&fixture, |draw_list| {
        let _ = draw_list.add_polyline(vec![[0.0, 0.0], [f32::INFINITY, 1.0]], ImColor32::WHITE);
    });
    assert_panics_without_buffer_change(&fixture, |draw_list| {
        let _ = draw_list
            .add_bezier_curve(
                [0.0, 0.0],
                [1.0, 1.0],
                [2.0, 1.0],
                [3.0, 0.0],
                ImColor32::WHITE,
            )
            .num_segments(DrawSegmentCount::count(i32::MAX as usize + 1));
    });
}

#[test]
fn draw_segment_counts_reject_invalid_values_before_ffi() {
    assert!(DrawNgonSegmentCount::new(2).is_none());
    assert!(DrawNgonSegmentCount::new(3).is_some());
    assert!(DrawNgonSegmentCount::new(i32::MAX as usize + 1).is_none());

    assert_eq!(DrawSegmentCount::AUTO.get(), None);
    assert_eq!(
        DrawSegmentCount::new(3).and_then(DrawSegmentCount::get),
        Some(3)
    );
    assert_eq!(DrawSegmentCount::new(0), None);
    assert_eq!(DrawSegmentCount::new(i32::MAX as usize + 1), None);

    assert!(std::panic::catch_unwind(|| DrawSegmentCount::count(0)).is_err());
    assert!(std::panic::catch_unwind(|| DrawSegmentCount::count(i32::MAX as usize + 1)).is_err());
}

#[test]
fn primitive_reserve_counts_reject_overflow_before_ffi() {
    let fixture = TestDrawList::new();

    assert_panics_without_buffer_change(&fixture, |draw_list| unsafe {
        draw_list.prim_reserve(i32::MAX as usize + 1, 0);
    });
    assert_panics_without_buffer_change(&fixture, |draw_list| unsafe {
        draw_list.prim_reserve(0, i32::MAX as usize + 1);
    });
    assert_panics_without_buffer_change(&fixture, |draw_list| unsafe {
        draw_list.prim_unreserve(i32::MAX as usize + 1, 0);
    });
    assert_panics_without_buffer_change(&fixture, |draw_list| unsafe {
        draw_list.prim_unreserve(0, i32::MAX as usize + 1);
    });
}

#[test]
fn raw_callback_copy_inputs_validate_before_ffi() {
    unsafe extern "C" fn callback(
        _parent_list: *const sys::ImDrawList,
        _command: *const sys::ImDrawCmd,
    ) {
    }

    let fixture = TestDrawList::new();
    assert_panics_without_buffer_change(&fixture, |draw_list| unsafe {
        draw_list.add_callback(callback, std::ptr::null_mut(), 1);
    });
    assert_panics_without_buffer_change(&fixture, |draw_list| unsafe {
        draw_list.add_callback(callback, std::ptr::dangling_mut(), 1usize << 31);
    });
}

#[test]
fn raw_callback_data_modes_preserve_borrow_or_copy_semantics() {
    unsafe extern "C" fn callback(
        _parent_list: *const sys::ImDrawList,
        _command: *const sys::ImDrawCmd,
    ) {
    }

    let fixture = TestDrawList::new();
    let draw_list = fixture.draw_list();
    draw_list.add_draw_cmd();

    let mut borrowed = 41_u8;
    let borrowed_ptr = std::ptr::from_mut(&mut borrowed).cast();
    unsafe {
        draw_list.add_callback(callback, borrowed_ptr, 0);
    }

    let mut copied = [3_u8, 1, 4, 1, 5];
    unsafe {
        draw_list.add_callback(callback, copied.as_mut_ptr().cast(), copied.len());

        let commands = std::slice::from_raw_parts(
            (*fixture.raw).CmdBuffer.Data,
            usize::try_from((*fixture.raw).CmdBuffer.Size).unwrap(),
        );
        assert_eq!(commands[0].UserCallbackData, borrowed_ptr);
        assert_eq!(commands[0].UserCallbackDataSize, 0);
        assert_eq!(commands[0].UserCallbackDataOffset, -1);

        assert!(commands[1].UserCallbackData.is_null());
        assert_eq!(commands[1].UserCallbackDataSize, copied.len() as i32);
        assert_eq!(commands[1].UserCallbackDataOffset, 0);
        let copied_storage = std::slice::from_raw_parts(
            (*fixture.raw)._CallbacksDataBuf.Data,
            usize::try_from((*fixture.raw)._CallbacksDataBuf.Size).unwrap(),
        );
        assert_eq!(copied_storage, copied);
    }
}

#[test]
fn standard_sampler_commands_are_safe_and_preserve_order() {
    unsafe extern "C" fn linear(
        _parent_list: *const sys::ImDrawList,
        _command: *const sys::ImDrawCmd,
    ) {
    }
    unsafe extern "C" fn nearest(
        _parent_list: *const sys::ImDrawList,
        _command: *const sys::ImDrawCmd,
    ) {
    }

    let mut context = crate::Context::create();
    let binding = context.binding();
    context.io_mut().set_display_size([128.0, 128.0]);
    context.io_mut().set_delta_time(1.0 / 60.0);
    context
        .font_atlas()
        .try_claim_legacy_renderer()
        .expect("legacy renderer font atlas should be available")
        .build();
    unsafe {
        context
            .platform_io_mut()
            .set_draw_callback_set_sampler_linear_raw(Some(linear));
        context
            .platform_io_mut()
            .set_draw_callback_set_sampler_nearest_raw(Some(nearest));
    }

    {
        let ui = context.frame();
        ui.window("standard sampler commands")
            .size([96.0, 96.0], crate::Condition::Always)
            .build(|| {
                let draw_list = ui.get_window_draw_list();
                draw_list.set_sampler_nearest();
                draw_list
                    .add_rect([8.0, 8.0], [24.0, 24.0], ImColor32::WHITE)
                    .filled(true)
                    .build();
                draw_list.set_sampler_linear();
                draw_list
                    .add_rect([32.0, 8.0], [48.0, 24.0], ImColor32::WHITE)
                    .filled(true)
                    .build();
            });
    }
    let frame = context.render_legacy();
    let commands = binding.with_bound_context(|| {
        frame
            .draw_data()
            .draw_lists()
            .flat_map(|list| list.commands())
            .filter(|command| {
                matches!(
                    command,
                    crate::render::DrawCmd::SetSamplerLinear
                        | crate::render::DrawCmd::SetSamplerNearest
                )
            })
            .collect::<Vec<_>>()
    });

    assert_eq!(commands.len(), 2);
    assert!(matches!(
        commands[0],
        crate::render::DrawCmd::SetSamplerNearest
    ));
    assert!(matches!(
        commands[1],
        crate::render::DrawCmd::SetSamplerLinear
    ));
}

#[test]
fn standard_sampler_commands_validate_backend_support_before_ffi() {
    let mut context = crate::Context::create();
    context.io_mut().set_display_size([128.0, 128.0]);
    context.io_mut().set_delta_time(1.0 / 60.0);
    context
        .font_atlas()
        .try_claim_legacy_renderer()
        .expect("legacy renderer font atlas should be available")
        .build();

    let ui = context.frame();
    let draw_list = ui.get_window_draw_list();
    let before = draw_list_counts(draw_list.draw_list);
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        draw_list.set_sampler_nearest();
    }));

    assert!(result.is_err());
    assert_eq!(draw_list_counts(draw_list.draw_list), before);
}

#[test]
fn text_and_clip_inputs_validate_before_ffi() {
    let mut ctx = crate::Context::create();
    {
        let io = ctx.io_mut();
        io.set_display_size([128.0, 128.0]);
        io.set_delta_time(1.0 / 60.0);
    }
    ctx.font_atlas()
        .try_claim_legacy_renderer()
        .expect("legacy renderer font atlas should be available")
        .build();
    let _ = ctx.set_ini_filename::<std::path::PathBuf>(None);

    let ui = ctx.frame();
    let draw_list = ui.get_window_draw_list();
    let raw_draw_list = draw_list.draw_list;
    let font = ui.current_font();
    let before = draw_list_counts(raw_draw_list);
    let clip_stack_size = unsafe { (*raw_draw_list)._ClipRectStack.Size };

    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        draw_list.add_text([f32::NAN, 0.0], ImColor32::WHITE, "hello");
    }));
    assert!(result.is_err());
    assert_eq!(draw_list_counts(raw_draw_list), before);

    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        draw_list.add_text_with_font(font, -1.0, [0.0, 0.0], ImColor32::WHITE, "hello", 0.0, None);
    }));
    assert!(result.is_err());
    assert_eq!(draw_list_counts(raw_draw_list), before);

    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let _ = draw_list.push_clip_rect([f32::NAN, 0.0], [1.0, 1.0], false);
    }));
    assert!(result.is_err());
    assert_eq!(
        unsafe { (*raw_draw_list)._ClipRectStack.Size },
        clip_stack_size
    );
}

#[test]
fn raw_draw_list_clip_helper_reads_stack_without_mutation() {
    let fixture = TestDrawList::new();
    let before = fixture.clip_stack_size();
    let draw_list = fixture.draw_list();

    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        let _ = draw_list.push_clip_rect([0.0, 0.0], [f32::INFINITY, 1.0], false);
    }));

    assert!(result.is_err());
    assert_eq!(fixture.clip_stack_size(), before);
}

#[test]
fn text_no_pixel_snap_scope_restores_only_its_flag() {
    let fixture = TestDrawList::new();
    let draw_list = fixture.draw_list();
    unsafe {
        (*fixture.raw).Flags = DrawListFlags::ANTI_ALIASED_FILL.bits();
    }

    draw_list.with_text_no_pixel_snap(|| {
        let flags = DrawListFlags::from_bits_retain(unsafe { (*fixture.raw).Flags });
        assert!(flags.contains(DrawListFlags::TEXT_NO_PIXEL_SNAP));
        assert!(flags.contains(DrawListFlags::ANTI_ALIASED_FILL));

        unsafe {
            (*fixture.raw).Flags |= DrawListFlags::ALLOW_VTX_OFFSET.bits();
        }
    });

    let flags = DrawListFlags::from_bits_retain(unsafe { (*fixture.raw).Flags });
    assert!(!flags.contains(DrawListFlags::TEXT_NO_PIXEL_SNAP));
    assert!(flags.contains(DrawListFlags::ANTI_ALIASED_FILL));
    assert!(flags.contains(DrawListFlags::ALLOW_VTX_OFFSET));
}

#[test]
fn text_no_pixel_snap_scope_is_nested_and_panic_safe() {
    let fixture = TestDrawList::new();
    let draw_list = fixture.draw_list();

    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        draw_list.with_text_no_pixel_snap(|| {
            assert!(
                DrawListFlags::from_bits_retain(unsafe { (*fixture.raw).Flags })
                    .contains(DrawListFlags::TEXT_NO_PIXEL_SNAP)
            );
            draw_list.with_text_no_pixel_snap(|| {
                assert!(
                    DrawListFlags::from_bits_retain(unsafe { (*fixture.raw).Flags })
                        .contains(DrawListFlags::TEXT_NO_PIXEL_SNAP)
                );
                panic!("forced panic inside text flag scope");
            });
        });
    }));

    assert!(result.is_err());
    assert!(
        !DrawListFlags::from_bits_retain(unsafe { (*fixture.raw).Flags })
            .contains(DrawListFlags::TEXT_NO_PIXEL_SNAP)
    );
}