Skip to main content

dear_imgui_rs/widget/
list_box.rs

1//! List boxes
2//!
3//! Classic list-box widget and builder for fixed-height item selection.
4//!
5use std::borrow::Cow;
6
7use crate::Ui;
8use crate::sys;
9
10fn assert_finite_vec2(caller: &str, name: &str, value: [f32; 2]) {
11    assert!(
12        value[0].is_finite() && value[1].is_finite(),
13        "{caller} {name} must contain finite values"
14    );
15}
16
17/// # List Box Widgets
18impl Ui {
19    /// Constructs a new list box builder.
20    pub fn list_box_config<T: AsRef<str>>(&self, label: T) -> ListBox<T> {
21        ListBox::new(label)
22    }
23}
24
25/// Builder for a list box widget
26#[derive(Clone, Debug)]
27#[must_use]
28pub struct ListBox<T> {
29    label: T,
30    size: [f32; 2],
31}
32
33impl<T: AsRef<str>> ListBox<T> {
34    /// Constructs a new list box builder.
35    #[doc(alias = "ListBoxHeaderVec2", alias = "ListBoxHeaderInt")]
36    pub fn new(label: T) -> ListBox<T> {
37        ListBox {
38            label,
39            size: [0.0, 0.0],
40        }
41    }
42
43    /// Sets the list box size based on the given width and height
44    /// If width or height are 0 or smaller, a default value is calculated
45    /// Helper to calculate the size of a listbox and display a label on the right.
46    /// Tip: To have a list filling the entire window width, PushItemWidth(-1) and pass an non-visible label e.g. "##empty"
47    ///
48    /// Default: [0.0, 0.0], in which case the combobox calculates a sensible width and height
49    #[inline]
50    pub fn size(mut self, size: impl Into<[f32; 2]>) -> Self {
51        self.size = size.into();
52        self
53    }
54    /// Creates a list box and starts appending to it.
55    ///
56    /// Returns `Some(ListBoxToken)` if the list box is open. After content has been
57    /// rendered, the token must be ended by calling `.end()`.
58    ///
59    /// Returns `None` if the list box is not open and no content should be rendered.
60    #[must_use]
61    #[doc(alias = "BeginListBox", alias = "ListBox")]
62    pub fn begin(self, ui: &Ui) -> Option<ListBoxToken<'_>> {
63        assert_finite_vec2("ListBox::begin()", "size", self.size);
64        let size_vec = sys::ImVec2 {
65            x: self.size[0],
66            y: self.size[1],
67        };
68        let label_ptr = ui.scratch_txt(self.label);
69        let should_render =
70            ui.run_with_bound_context(|| unsafe { sys::igBeginListBox(label_ptr, size_vec) });
71        if should_render {
72            Some(ListBoxToken::new(ui))
73        } else {
74            None
75        }
76    }
77    /// Creates a list box and runs a closure to construct the list contents.
78    /// Returns the result of the closure, if it is called.
79    ///
80    /// Note: the closure is not called if the list box is not open.
81    pub fn build<R, F: FnOnce() -> R>(self, ui: &Ui, f: F) -> Option<R> {
82        self.begin(ui).map(|_list| f())
83    }
84}
85
86/// Tracks a list box that can be ended by calling `.end()`
87/// or by dropping
88#[doc(alias = "EndListBox")]
89pub struct ListBoxToken<'ui> {
90    _ui: &'ui Ui,
91}
92
93impl<'ui> ListBoxToken<'ui> {
94    /// Creates a new list box token
95    pub fn new(ui: &'ui Ui) -> Self {
96        Self { _ui: ui }
97    }
98
99    /// Ends the list box
100    pub fn end(self) {
101        // The drop implementation will handle the actual ending
102    }
103}
104
105impl<'ui> Drop for ListBoxToken<'ui> {
106    fn drop(&mut self) {
107        self._ui
108            .run_with_bound_context(|| unsafe { sys::igEndListBox() });
109    }
110}
111
112/// # Convenience functions
113impl<T: AsRef<str>> ListBox<T> {
114    /// Builds a simple list box for choosing from a slice of values
115    pub fn build_simple<V, L>(
116        self,
117        ui: &Ui,
118        current_item: &mut usize,
119        items: &[V],
120        label_fn: &L,
121    ) -> bool
122    where
123        for<'b> L: Fn(&'b V) -> Cow<'b, str>,
124    {
125        let mut result = false;
126        let lb = self;
127        if let Some(_cb) = lb.begin(ui) {
128            for (idx, item) in items.iter().enumerate() {
129                let text = label_fn(item);
130                let selected = idx == *current_item;
131                if ui.selectable_config(&text).selected(selected).build() {
132                    *current_item = idx;
133                    result = true;
134                }
135            }
136        }
137        result
138    }
139
140    /// Builds a simple list box for choosing from a slice of values using an `i32` index.
141    ///
142    /// This is useful when you want to represent \"no selection\" with `-1`, matching Dear ImGui's
143    /// list-box patterns that use an `int*` index.
144    pub fn build_simple_i32<V, L>(
145        self,
146        ui: &Ui,
147        current_item: &mut i32,
148        items: &[V],
149        label_fn: &L,
150    ) -> bool
151    where
152        for<'b> L: Fn(&'b V) -> Cow<'b, str>,
153    {
154        let mut result = false;
155        let lb = self;
156        if let Some(_cb) = lb.begin(ui) {
157            for (idx, item) in items.iter().enumerate() {
158                if idx > i32::MAX as usize {
159                    break;
160                }
161                let idx_i32 = idx as i32;
162                let text = label_fn(item);
163                let selected = idx_i32 == *current_item;
164                if ui.selectable_config(&text).selected(selected).build() {
165                    *current_item = idx_i32;
166                    result = true;
167                }
168            }
169        }
170        result
171    }
172}