dear-imgui-rs 0.12.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
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
//! Multi-select helpers (BeginMultiSelect/EndMultiSelect)
//!
//! This module provides a small, safe wrapper around Dear ImGui's multi-select
//! API introduced in 1.92 (`BeginMultiSelect` / `EndMultiSelect`), following
//! the "external storage" pattern described in the official docs:
//! https://github.com/ocornut/imgui/wiki/Multi-Select
//!
//! The main entry point is [`Ui::multi_select_indexed`], which:
//! - wraps `BeginMultiSelect()` / `EndMultiSelect()`
//! - wires `SetNextItemSelectionUserData()` for each item (index-based)
//! - applies selection requests to your storage using a simple trait.

#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::as_conversions
)]

use crate::Ui;
use crate::sys;
use std::collections::HashSet;

bitflags::bitflags! {
    /// Independent flags controlling multi-selection behavior.
    ///
    /// The click-selection policy, box-select mode, and scope are represented by
    /// [`MultiSelectClickPolicy`], [`MultiSelectBoxSelect`], and [`MultiSelectScopeKind`].
    #[repr(transparent)]
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    pub struct MultiSelectFlags: i32 {
        /// No flags.
        const NONE = sys::ImGuiMultiSelectFlags_None as i32;
        /// Single-selection scope. Ctrl/Shift range selection is disabled.
        const SINGLE_SELECT = sys::ImGuiMultiSelectFlags_SingleSelect as i32;
        /// Disable `Ctrl+A` "select all" shortcut.
        const NO_SELECT_ALL = sys::ImGuiMultiSelectFlags_NoSelectAll as i32;
        /// Disable range selection (Shift+click / Shift+arrow).
        const NO_RANGE_SELECT = sys::ImGuiMultiSelectFlags_NoRangeSelect as i32;
        /// Disable automatic selection of newly focused items.
        const NO_AUTO_SELECT = sys::ImGuiMultiSelectFlags_NoAutoSelect as i32;
        /// Disable automatic clearing of selection when focus moves within the scope.
        const NO_AUTO_CLEAR = sys::ImGuiMultiSelectFlags_NoAutoClear as i32;
        /// Disable automatic clearing when reselecting the same range.
        const NO_AUTO_CLEAR_ON_RESELECT =
            sys::ImGuiMultiSelectFlags_NoAutoClearOnReselect as i32;
        /// Disable drag-scrolling when box-selecting near edges of the scope.
        const BOX_SELECT_NO_SCROLL = sys::ImGuiMultiSelectFlags_BoxSelectNoScroll as i32;
        /// Clear selection when pressing Escape while the scope is focused.
        const CLEAR_ON_ESCAPE = sys::ImGuiMultiSelectFlags_ClearOnEscape as i32;
        /// Clear selection when clicking on empty space (void) inside the scope.
        const CLEAR_ON_CLICK_VOID = sys::ImGuiMultiSelectFlags_ClearOnClickVoid as i32;
        /// Disable default right-click behavior that selects item before opening a context menu.
        const NO_SELECT_ON_RIGHT_CLICK =
            sys::ImGuiMultiSelectFlags_NoSelectOnRightClick as i32;
    }
}

/// Box-selection geometry for multi-select scopes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MultiSelectBoxSelect {
    /// Same x-position/full-row items.
    OneDimensional,
    /// Arbitrary item layout, at a higher clipping cost.
    TwoDimensional,
}

impl MultiSelectBoxSelect {
    #[inline]
    const fn raw(self) -> i32 {
        match self {
            Self::OneDimensional => sys::ImGuiMultiSelectFlags_BoxSelect1d as i32,
            Self::TwoDimensional => sys::ImGuiMultiSelectFlags_BoxSelect2d as i32,
        }
    }
}

/// Click-selection policy for multi-select scopes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MultiSelectClickPolicy {
    /// Apply selection on mouse down for unselected items and on mouse up for
    /// selected items.
    Auto,
    /// Apply selection on mouse down for any clicked item.
    ClickAlways,
    /// Apply selection on mouse release for unselected items.
    ClickRelease,
}

impl MultiSelectClickPolicy {
    #[inline]
    const fn raw(self) -> i32 {
        match self {
            Self::Auto => sys::ImGuiMultiSelectFlags_SelectOnAuto as i32,
            Self::ClickAlways => sys::ImGuiMultiSelectFlags_SelectOnClickAlways as i32,
            Self::ClickRelease => sys::ImGuiMultiSelectFlags_SelectOnClickRelease as i32,
        }
    }
}

/// Scope for box-select and clear-on-empty-click behavior.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MultiSelectScopeKind {
    /// Scope is the whole window.
    Window,
    /// Scope is the whole window and enables Dear ImGui's temporary X-axis navigation wrap helper.
    WindowWithNavWrapX,
    /// Scope is the rectangle between `BeginMultiSelect()` and `EndMultiSelect()`.
    Rect,
}

impl MultiSelectScopeKind {
    #[inline]
    const fn raw(self) -> i32 {
        match self {
            Self::Window => sys::ImGuiMultiSelectFlags_ScopeWindow as i32,
            Self::WindowWithNavWrapX => {
                (sys::ImGuiMultiSelectFlags_ScopeWindow | sys::ImGuiMultiSelectFlags_NavWrapX)
                    as i32
            }
            Self::Rect => sys::ImGuiMultiSelectFlags_ScopeRect as i32,
        }
    }
}

/// Complete multi-select options assembled from independent flags and an
/// optional single-choice policies.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct MultiSelectOptions {
    pub flags: MultiSelectFlags,
    pub click_policy: Option<MultiSelectClickPolicy>,
    pub box_select: Option<MultiSelectBoxSelect>,
    pub scope: Option<MultiSelectScopeKind>,
}

impl MultiSelectOptions {
    pub const fn new() -> Self {
        Self {
            flags: MultiSelectFlags::NONE,
            click_policy: None,
            box_select: None,
            scope: None,
        }
    }

    pub fn flags(mut self, flags: MultiSelectFlags) -> Self {
        self.flags = flags;
        self
    }

    pub fn click_policy(mut self, policy: MultiSelectClickPolicy) -> Self {
        self.click_policy = Some(policy);
        self
    }

    pub fn box_select(mut self, mode: MultiSelectBoxSelect) -> Self {
        self.box_select = Some(mode);
        self
    }

    pub fn scope(mut self, scope: MultiSelectScopeKind) -> Self {
        self.scope = Some(scope);
        self
    }

    pub fn bits(self) -> i32 {
        self.raw()
    }

    #[inline]
    pub(crate) fn raw(self) -> i32 {
        self.flags.bits()
            | self.click_policy.map_or(0, MultiSelectClickPolicy::raw)
            | self.box_select.map_or(0, MultiSelectBoxSelect::raw)
            | self.scope.map_or(0, MultiSelectScopeKind::raw)
    }
}

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

impl From<MultiSelectFlags> for MultiSelectOptions {
    fn from(flags: MultiSelectFlags) -> Self {
        Self::new().flags(flags)
    }
}

/// Selection container backed by Dear ImGui's `ImGuiSelectionBasicStorage`.
///
/// This stores a set of selected `ImGuiID` values using the optimized helper
/// provided by Dear ImGui. It is suitable when items are naturally identified
/// by stable IDs (e.g. table rows, tree nodes).
#[derive(Debug)]
pub struct BasicSelection {
    raw: *mut sys::ImGuiSelectionBasicStorage,
}

impl BasicSelection {
    /// Create an empty selection storage.
    pub fn new() -> Self {
        unsafe {
            let ptr = sys::ImGuiSelectionBasicStorage_ImGuiSelectionBasicStorage();
            if ptr.is_null() {
                panic!("ImGuiSelectionBasicStorage_ImGuiSelectionBasicStorage() returned null");
            }
            Self { raw: ptr }
        }
    }

    /// Return the number of selected items.
    pub fn len(&self) -> usize {
        unsafe {
            let size = (*self.raw).Size;
            if size <= 0 { 0 } else { size as usize }
        }
    }

    /// Returns true if the selection is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Clear the selection set.
    pub fn clear(&mut self) {
        unsafe {
            sys::ImGuiSelectionBasicStorage_Clear(self.raw);
        }
    }

    /// Returns true if the given id is selected.
    pub fn contains(&self, id: crate::Id) -> bool {
        unsafe { sys::ImGuiSelectionBasicStorage_Contains(self.raw, id.raw()) }
    }

    /// Set selection state for a given id.
    pub fn set_selected(&mut self, id: crate::Id, selected: bool) {
        unsafe {
            sys::ImGuiSelectionBasicStorage_SetItemSelected(self.raw, id.raw(), selected);
        }
    }

    /// Iterate over selected ids.
    pub fn iter(&self) -> BasicSelectionIter<'_> {
        BasicSelectionIter {
            storage: self,
            it: std::ptr::null_mut(),
        }
    }

    /// Expose raw pointer for internal helpers.
    pub(crate) fn as_raw(&self) -> *mut sys::ImGuiSelectionBasicStorage {
        self.raw
    }
}

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

impl Drop for BasicSelection {
    fn drop(&mut self) {
        unsafe {
            if !self.raw.is_null() {
                sys::ImGuiSelectionBasicStorage_destroy(self.raw);
                self.raw = std::ptr::null_mut();
            }
        }
    }
}

/// Iterator over selected ids stored in [`BasicSelection`].
pub struct BasicSelectionIter<'a> {
    storage: &'a BasicSelection,
    it: *mut std::os::raw::c_void,
}

impl<'a> Iterator for BasicSelectionIter<'a> {
    type Item = crate::Id;

    fn next(&mut self) -> Option<Self::Item> {
        unsafe {
            let mut out_id: sys::ImGuiID = 0;
            let has_next = sys::ImGuiSelectionBasicStorage_GetNextSelectedItem(
                self.storage.as_raw(),
                &mut self.it,
                &mut out_id,
            );
            if has_next {
                Some(crate::Id::from(out_id))
            } else {
                None
            }
        }
    }
}

/// Index-based selection storage for multi-select helpers.
///
/// Implement this trait for your selection container (e.g. `Vec<bool>`,
/// `Vec<MyItem { selected: bool }>` or a custom type) to use
/// [`Ui::multi_select_indexed`].
pub trait MultiSelectIndexStorage {
    /// Total number of items in the selection scope.
    fn len(&self) -> usize;

    /// Returns `true` if the selection scope is empty.
    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns whether item at `index` is currently selected.
    fn is_selected(&self, index: usize) -> bool;

    /// Updates selection state for item at `index`.
    fn set_selected(&mut self, index: usize, selected: bool);

    /// Optional hint for current selection size.
    ///
    /// If provided, this is forwarded to `BeginMultiSelect()` to improve the
    /// behavior of shortcuts such as `ImGuiMultiSelectFlags_ClearOnEscape`.
    /// When `None` (default), the size is treated as "unknown".
    fn selected_count_hint(&self) -> Option<usize> {
        None
    }
}

impl MultiSelectIndexStorage for Vec<bool> {
    fn len(&self) -> usize {
        self.len()
    }

    fn is_selected(&self, index: usize) -> bool {
        self.get(index).copied().unwrap_or(false)
    }

    fn set_selected(&mut self, index: usize, selected: bool) {
        if index < self.len() {
            self[index] = selected;
        }
    }

    fn selected_count_hint(&self) -> Option<usize> {
        // For typical lists this is cheap enough; callers with large datasets
        // can implement the trait manually with a more efficient counter.
        Some(self.iter().filter(|&&b| b).count())
    }
}

impl MultiSelectIndexStorage for &mut [bool] {
    fn len(&self) -> usize {
        (**self).len()
    }

    fn is_selected(&self, index: usize) -> bool {
        self.get(index).copied().unwrap_or(false)
    }

    fn set_selected(&mut self, index: usize, selected: bool) {
        if index < self.len() {
            self[index] = selected;
        }
    }

    fn selected_count_hint(&self) -> Option<usize> {
        Some(self.iter().filter(|&&b| b).count())
    }
}

/// Index-based selection storage backed by a key slice + `HashSet` of selected keys.
///
/// This is convenient when your application stores selection as a set of
/// arbitrary keys (e.g. `HashSet<u32>` or `HashSet<MyId>`), but you still
/// want to drive a multi-select scope using contiguous indices.
pub struct KeySetSelection<'a, K>
where
    K: Eq + std::hash::Hash + Copy,
{
    keys: &'a [K],
    selected: &'a mut HashSet<K>,
}

impl<'a, K> KeySetSelection<'a, K>
where
    K: Eq + std::hash::Hash + Copy,
{
    /// Create a new index-based view over a key slice and a selection set.
    ///
    /// - `keys`: stable index->key mapping (e.g. your backing array).
    /// - `selected`: set of currently selected keys.
    pub fn new(keys: &'a [K], selected: &'a mut HashSet<K>) -> Self {
        Self { keys, selected }
    }
}

impl<'a, K> MultiSelectIndexStorage for KeySetSelection<'a, K>
where
    K: Eq + std::hash::Hash + Copy,
{
    fn len(&self) -> usize {
        self.keys.len()
    }

    fn is_selected(&self, index: usize) -> bool {
        self.keys
            .get(index)
            .map(|k| self.selected.contains(k))
            .unwrap_or(false)
    }

    fn set_selected(&mut self, index: usize, selected: bool) {
        if let Some(&key) = self.keys.get(index) {
            if selected {
                self.selected.insert(key);
            } else {
                self.selected.remove(&key);
            }
        }
    }

    fn selected_count_hint(&self) -> Option<usize> {
        Some(self.selected.len())
    }
}

/// Apply `ImGuiMultiSelectIO` requests to index-based selection storage.
///
/// This mirrors `ImGuiSelectionExternalStorage::ApplyRequests` from Dear ImGui,
/// but operates on the safe [`MultiSelectIndexStorage`] trait instead of relying
/// on C callbacks.
unsafe fn apply_multi_select_requests_indexed<S: MultiSelectIndexStorage>(
    ms_io: *mut sys::ImGuiMultiSelectIO,
    storage: &mut S,
) {
    unsafe {
        if ms_io.is_null() {
            return;
        }

        let io_ref: &mut sys::ImGuiMultiSelectIO = &mut *ms_io;
        let items_count = usize::try_from(io_ref.ItemsCount).unwrap_or(0);

        let requests = &mut io_ref.Requests;
        if requests.Data.is_null() || requests.Size <= 0 {
            return;
        }

        let len = match usize::try_from(requests.Size) {
            Ok(len) => len,
            Err(_) => return,
        };
        let slice = std::slice::from_raw_parts_mut(requests.Data, len);

        for req in slice {
            if req.Type == sys::ImGuiSelectionRequestType_SetAll {
                for idx in 0..items_count {
                    storage.set_selected(idx, req.Selected);
                }
            } else if req.Type == sys::ImGuiSelectionRequestType_SetRange {
                let first = req.RangeFirstItem as i32;
                let last = req.RangeLastItem as i32;
                if first < 0 || last < first {
                    continue;
                }
                let last_clamped = std::cmp::min(last as usize, items_count.saturating_sub(1));
                for idx in first as usize..=last_clamped {
                    storage.set_selected(idx, req.Selected);
                }
            }
        }
    }
}

/// RAII wrapper around `BeginMultiSelect()` / `EndMultiSelect()` for advanced users.
///
/// This gives direct, but scoped, access to the underlying `ImGuiMultiSelectIO`
/// struct. It does not perform any selection updates by itself; you are expected
/// to call helper methods or use the raw IO to drive your own storage.
pub struct MultiSelectScope<'ui> {
    ms_io_begin: *mut sys::ImGuiMultiSelectIO,
    items_count: i32,
    _marker: std::marker::PhantomData<&'ui Ui>,
}

impl<'ui> MultiSelectScope<'ui> {
    fn new(
        flags: impl Into<MultiSelectOptions>,
        selection_size: Option<i32>,
        items_count: usize,
    ) -> Self {
        let options = flags.into();
        let selection_size_i32 = selection_size.unwrap_or(-1);
        let items_count_i32 = i32::try_from(items_count).unwrap_or(i32::MAX);
        let ms_io_begin =
            unsafe { sys::igBeginMultiSelect(options.raw(), selection_size_i32, items_count_i32) };
        Self {
            ms_io_begin,
            items_count: items_count_i32,
            _marker: std::marker::PhantomData,
        }
    }

    /// Access the IO struct returned by `BeginMultiSelect()`.
    pub fn begin_io(&self) -> &sys::ImGuiMultiSelectIO {
        unsafe { &*self.ms_io_begin }
    }

    /// Mutable access to the IO struct returned by `BeginMultiSelect()`.
    pub fn begin_io_mut(&mut self) -> &mut sys::ImGuiMultiSelectIO {
        unsafe { &mut *self.ms_io_begin }
    }

    /// Apply selection requests from `BeginMultiSelect()` to index-based storage.
    pub fn apply_begin_requests_indexed<S: MultiSelectIndexStorage>(&mut self, storage: &mut S) {
        unsafe {
            apply_multi_select_requests_indexed(self.ms_io_begin, storage);
        }
    }

    /// Finalize the multi-select scope and return an IO view for the end state.
    ///
    /// This calls `EndMultiSelect()` and returns a `MultiSelectEnd` wrapper
    /// that can be used to apply the final selection requests.
    pub fn end(self) -> MultiSelectEnd<'ui> {
        let ms_io_end = unsafe { sys::igEndMultiSelect() };
        MultiSelectEnd {
            ms_io_end,
            items_count: self.items_count,
            _marker: std::marker::PhantomData,
        }
    }
}

/// IO view returned after calling `EndMultiSelect()` via [`MultiSelectScope::end`].
pub struct MultiSelectEnd<'ui> {
    ms_io_end: *mut sys::ImGuiMultiSelectIO,
    items_count: i32,
    _marker: std::marker::PhantomData<&'ui Ui>,
}

impl<'ui> MultiSelectEnd<'ui> {
    /// Access the IO struct returned by `EndMultiSelect()`.
    pub fn io(&self) -> &sys::ImGuiMultiSelectIO {
        unsafe { &*self.ms_io_end }
    }

    /// Mutable access to the IO struct returned by `EndMultiSelect()`.
    pub fn io_mut(&mut self) -> &mut sys::ImGuiMultiSelectIO {
        unsafe { &mut *self.ms_io_end }
    }

    /// Apply selection requests from `EndMultiSelect()` to index-based storage.
    pub fn apply_requests_indexed<S: MultiSelectIndexStorage>(&mut self, storage: &mut S) {
        unsafe {
            apply_multi_select_requests_indexed(self.ms_io_end, storage);
        }
    }

    /// Apply selection requests from `EndMultiSelect()` to a [`BasicSelection`].
    pub fn apply_requests_basic<G>(&mut self, selection: &mut BasicSelection, mut id_at_index: G)
    where
        G: FnMut(usize) -> crate::Id,
    {
        unsafe {
            apply_multi_select_requests_basic(
                self.ms_io_end,
                selection,
                self.items_count as usize,
                &mut id_at_index,
            );
        }
    }
}

impl Ui {
    /// Low-level entry point: begin a multi-select scope and return a RAII wrapper.
    ///
    /// This is the closest safe wrapper to the raw `BeginMultiSelect()` /
    /// `EndMultiSelect()` pair. It does not drive any selection storage by
    /// itself; use `begin_io()` / `end().io()` and the helper methods to
    /// implement custom patterns.
    pub fn begin_multi_select_raw(
        &self,
        flags: impl Into<MultiSelectOptions>,
        selection_size: Option<i32>,
        items_count: usize,
    ) -> MultiSelectScope<'_> {
        MultiSelectScope::new(flags, selection_size, items_count)
    }
    /// Multi-select helper for index-based storage.
    ///
    /// This wraps `BeginMultiSelect()` / `EndMultiSelect()` and applies
    /// selection requests to an index-addressable selection container.
    ///
    /// Typical usage:
    ///
    /// ```no_run
    /// # use dear_imgui_rs::*;
    /// # let mut ctx = Context::create();
    /// # let ui = ctx.frame();
    /// let mut selected = vec![false; 128];
    ///
    /// ui.multi_select_indexed(&mut selected, MultiSelectOptions::new(), |ui, idx, is_selected| {
    ///     ui.text(format!(
    ///         "{} {}",
    ///         if is_selected { "[x]" } else { "[ ]" },
    ///         idx
    ///     ));
    /// });
    /// ```
    ///
    /// Notes:
    /// - `storage.len()` defines `items_count`.
    /// - This helper uses the "external storage" pattern where selection is
    ///   stored entirely on the application side.
    /// - Per-item selection toggles can be queried via
    ///   [`Ui::is_item_toggled_selection`].
    pub fn multi_select_indexed<S, F>(
        &self,
        storage: &mut S,
        flags: impl Into<MultiSelectOptions>,
        mut render_item: F,
    ) where
        S: MultiSelectIndexStorage,
        F: FnMut(&Ui, usize, bool),
    {
        let options = flags.into();
        let items_count = storage.len();
        let selection_size_i32 = storage
            .selected_count_hint()
            .and_then(|n| i32::try_from(n).ok())
            .unwrap_or(-1);

        // Begin multi-select scope.
        let ms_io_begin = unsafe {
            sys::igBeginMultiSelect(options.raw(), selection_size_i32, items_count as i32)
        };

        // Apply SetAll requests (if any) before submitting items.
        unsafe {
            apply_multi_select_requests_indexed(ms_io_begin, storage);
        }

        // Submit items: for each index we set SelectionUserData and let user
        // draw widgets, passing the current selection state as `is_selected`.
        for idx in 0..items_count {
            unsafe {
                sys::igSetNextItemSelectionUserData(idx as sys::ImGuiSelectionUserData);
            }
            let is_selected = storage.is_selected(idx);
            render_item(self, idx, is_selected);
        }

        // End scope and apply requests generated during item submission.
        let ms_io_end = unsafe { sys::igEndMultiSelect() };
        unsafe {
            apply_multi_select_requests_indexed(ms_io_end, storage);
        }
    }

    /// Multi-select helper for index-based storage inside an active table.
    ///
    /// This is a convenience wrapper over [`Ui::multi_select_indexed`] that
    /// automatically advances table rows and starts each row at column 0.
    ///
    /// It expects to be called between `BeginTable`/`EndTable`.
    pub fn table_multi_select_indexed<S, F>(
        &self,
        storage: &mut S,
        flags: impl Into<MultiSelectOptions>,
        mut build_row: F,
    ) where
        S: MultiSelectIndexStorage,
        F: FnMut(&Ui, usize, bool),
    {
        let options = flags.into();
        let row_count = storage.len();
        let selection_size_i32 = storage
            .selected_count_hint()
            .and_then(|n| i32::try_from(n).ok())
            .unwrap_or(-1);

        let ms_io_begin =
            unsafe { sys::igBeginMultiSelect(options.raw(), selection_size_i32, row_count as i32) };

        unsafe {
            apply_multi_select_requests_indexed(ms_io_begin, storage);
        }

        for row in 0..row_count {
            unsafe {
                sys::igSetNextItemSelectionUserData(row as sys::ImGuiSelectionUserData);
            }
            // Start a new table row and move to first column.
            self.table_next_row();
            self.table_next_column();

            let is_selected = storage.is_selected(row);
            build_row(self, row, is_selected);
        }

        let ms_io_end = unsafe { sys::igEndMultiSelect() };
        unsafe {
            apply_multi_select_requests_indexed(ms_io_end, storage);
        }
    }

    /// Multi-select helper using [`BasicSelection`] as underlying storage.
    ///
    /// This variant is suitable when items are naturally identified by `ImGuiID`
    /// (e.g. stable ids for rows or tree nodes).
    ///
    /// - `items_count`: number of items in the scope.
    /// - `id_at_index`: maps `[0, items_count)` to the corresponding item id.
    /// - `render_item`: called once per index to emit widgets for that item.
    pub fn multi_select_basic<G, F>(
        &self,
        selection: &mut BasicSelection,
        flags: impl Into<MultiSelectOptions>,
        items_count: usize,
        mut id_at_index: G,
        mut render_item: F,
    ) where
        G: FnMut(usize) -> crate::Id,
        F: FnMut(&Ui, usize, crate::Id, bool),
    {
        let options = flags.into();
        let selection_size_i32 = i32::try_from(selection.len()).unwrap_or(-1);

        let ms_io_begin = unsafe {
            sys::igBeginMultiSelect(options.raw(), selection_size_i32, items_count as i32)
        };

        unsafe {
            apply_multi_select_requests_basic(
                ms_io_begin,
                selection,
                items_count,
                &mut id_at_index,
            );
        }

        for idx in 0..items_count {
            unsafe {
                sys::igSetNextItemSelectionUserData(idx as sys::ImGuiSelectionUserData);
            }
            let id = id_at_index(idx);
            let is_selected = selection.contains(id);
            render_item(self, idx, id, is_selected);
        }

        let ms_io_end = unsafe { sys::igEndMultiSelect() };
        unsafe {
            apply_multi_select_requests_basic(ms_io_end, selection, items_count, &mut id_at_index);
        }
    }
}

/// Apply multi-select requests to a `BasicSelection` using an index→id mapping.
unsafe fn apply_multi_select_requests_basic<G>(
    ms_io: *mut sys::ImGuiMultiSelectIO,
    selection: &mut BasicSelection,
    items_count: usize,
    id_at_index: &mut G,
) where
    G: FnMut(usize) -> crate::Id,
{
    unsafe {
        if ms_io.is_null() {
            return;
        }

        let io_ref: &mut sys::ImGuiMultiSelectIO = &mut *ms_io;
        let requests = &mut io_ref.Requests;
        if requests.Data.is_null() || requests.Size <= 0 {
            return;
        }

        let len = match usize::try_from(requests.Size) {
            Ok(len) => len,
            Err(_) => return,
        };
        let slice = std::slice::from_raw_parts_mut(requests.Data, len);

        for req in slice {
            if req.Type == sys::ImGuiSelectionRequestType_SetAll {
                for idx in 0..items_count {
                    let id = id_at_index(idx);
                    selection.set_selected(id, req.Selected);
                }
            } else if req.Type == sys::ImGuiSelectionRequestType_SetRange {
                let first = req.RangeFirstItem as i32;
                let last = req.RangeLastItem as i32;
                if first < 0 || last < first {
                    continue;
                }
                let last_clamped = std::cmp::min(last as usize, items_count.saturating_sub(1));
                for idx in first as usize..=last_clamped {
                    let id = id_at_index(idx);
                    selection.set_selected(id, req.Selected);
                }
            }
        }
    }
}