Skip to main content

dear_imgui_rs/widget/
selectable.rs

1//! Selectable items
2//!
3//! Clickable items that can be selected, typically used in lists. Supports
4//! span-full-width behavior and selection flags.
5//!
6#![allow(
7    clippy::cast_possible_truncation,
8    clippy::cast_sign_loss,
9    clippy::as_conversions
10)]
11use crate::Ui;
12use crate::sys;
13
14fn assert_non_negative_finite_vec2(caller: &str, name: &str, value: [f32; 2]) {
15    assert!(
16        value[0].is_finite() && value[1].is_finite(),
17        "{caller} {name} must contain finite values"
18    );
19    assert!(
20        value[0] >= 0.0 && value[1] >= 0.0,
21        "{caller} {name} must contain non-negative values"
22    );
23}
24
25fn validate_selectable_flags(caller: &str, flags: SelectableFlags) {
26    let unsupported = flags.bits() & !SelectableFlags::all().bits();
27    assert!(
28        unsupported == 0,
29        "{caller} received unsupported ImGuiSelectableFlags bits: 0x{unsupported:X}"
30    );
31}
32
33bitflags::bitflags! {
34    /// Flags for selectables
35    #[repr(transparent)]
36    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
37    pub struct SelectableFlags: i32 {
38        /// Clicking this don't close parent popup window
39        const NO_AUTO_CLOSE_POPUPS = sys::ImGuiSelectableFlags_NoAutoClosePopups as i32;
40        /// Selectable frame can span all columns (text will still fit in current column)
41        const SPAN_ALL_COLUMNS = sys::ImGuiSelectableFlags_SpanAllColumns as i32;
42        /// Generate press events on double clicks too
43        const ALLOW_DOUBLE_CLICK = sys::ImGuiSelectableFlags_AllowDoubleClick as i32;
44        /// Cannot be selected, display greyed out text
45        const DISABLED = sys::ImGuiSelectableFlags_Disabled as i32;
46        /// Hit testing to allow subsequent widgets to overlap this one
47        const ALLOW_OVERLAP = sys::ImGuiSelectableFlags_AllowOverlap as i32;
48        /// Display the selectable as highlighted, as if hovered.
49        const HIGHLIGHT = sys::ImGuiSelectableFlags_Highlight as i32;
50        /// Auto-select when moved into by navigation, unless Ctrl is held.
51        const SELECT_ON_NAV = sys::ImGuiSelectableFlags_SelectOnNav as i32;
52    }
53}
54
55impl Ui {
56    /// Constructs a new simple selectable.
57    ///
58    /// Use [selectable_config] for a builder with additional options.
59    ///
60    /// [selectable_config]: Self::selectable_config
61    #[doc(alias = "Selectable")]
62    pub fn selectable<T: AsRef<str>>(&self, label: T) -> bool {
63        self.selectable_config(label).build()
64    }
65
66    /// Constructs a new selectable builder.
67    #[doc(alias = "Selectable")]
68    pub fn selectable_config<T: AsRef<str>>(&self, label: T) -> Selectable<'_, T> {
69        Selectable {
70            label,
71            selected: false,
72            flags: SelectableFlags::empty(),
73            size: [0.0, 0.0],
74            ui: self,
75        }
76    }
77}
78
79/// Builder for a selectable widget.
80///
81/// Create this builder through [`Ui::selectable_config`]. The former direct constructor is
82/// intentionally unavailable so every builder is visibly tied to its owning `Ui`:
83///
84/// ```compile_fail
85/// # use dear_imgui_rs::{Context, Selectable};
86/// # let mut context = Context::create();
87/// # let ui = context.frame();
88/// let _ = Selectable::new("item", ui);
89/// ```
90#[derive(Clone, Debug)]
91#[must_use]
92pub struct Selectable<'ui, T> {
93    label: T,
94    selected: bool,
95    flags: SelectableFlags,
96    size: [f32; 2],
97    ui: &'ui Ui,
98}
99
100impl<'ui, T: AsRef<str>> Selectable<'ui, T> {
101    /// Replaces all current settings with the given flags
102    pub fn flags(mut self, flags: SelectableFlags) -> Self {
103        self.flags = flags;
104        self
105    }
106    /// Sets the selected state of the selectable
107    pub fn selected(mut self, selected: bool) -> Self {
108        self.selected = selected;
109        self
110    }
111    /// Enables/disables closing parent popup window on click.
112    ///
113    /// Default: enabled
114    pub fn close_popups(mut self, value: bool) -> Self {
115        self.flags
116            .set(SelectableFlags::NO_AUTO_CLOSE_POPUPS, !value);
117        self
118    }
119    /// Enables/disables full column span (text will still fit in the current column).
120    ///
121    /// Default: disabled
122    pub fn span_all_columns(mut self, value: bool) -> Self {
123        self.flags.set(SelectableFlags::SPAN_ALL_COLUMNS, value);
124        self
125    }
126    /// Enables/disables click event generation on double clicks.
127    ///
128    /// Default: disabled
129    pub fn allow_double_click(mut self, value: bool) -> Self {
130        self.flags.set(SelectableFlags::ALLOW_DOUBLE_CLICK, value);
131        self
132    }
133    /// Enables/disables the selectable.
134    ///
135    /// When disabled, it cannot be selected and the text uses the disabled text color.
136    ///
137    /// Default: disabled
138    pub fn disabled(mut self, value: bool) -> Self {
139        self.flags.set(SelectableFlags::DISABLED, value);
140        self
141    }
142    /// Sets the size of the selectable.
143    ///
144    /// For the X axis:
145    ///
146    /// - `> 0.0`: use given width
147    /// - `= 0.0`: use remaining width
148    ///
149    /// For the Y axis:
150    ///
151    /// - `> 0.0`: use given height
152    /// - `= 0.0`: use label height
153    pub fn size(mut self, size: impl Into<[f32; 2]>) -> Self {
154        self.size = size.into();
155        self
156    }
157
158    /// Builds the selectable.
159    ///
160    /// Returns true if the selectable was clicked.
161    pub fn build(self) -> bool {
162        validate_selectable_flags("Selectable::build()", self.flags);
163        assert_non_negative_finite_vec2("Selectable::build()", "size", self.size);
164        let size_vec = sys::ImVec2 {
165            x: self.size[0],
166            y: self.size[1],
167        };
168        self.ui.run_with_bound_context(|| unsafe {
169            sys::igSelectable_Bool(
170                self.ui.scratch_txt(self.label),
171                self.selected,
172                self.flags.bits(),
173                size_vec,
174            )
175        })
176    }
177
178    /// Builds the selectable using a mutable reference to selected state.
179    pub fn build_with_ref(self, selected: &mut bool) -> bool {
180        validate_selectable_flags("Selectable::build_with_ref()", self.flags);
181        assert_non_negative_finite_vec2("Selectable::build_with_ref()", "size", self.size);
182        let size_vec = sys::ImVec2 {
183            x: self.size[0],
184            y: self.size[1],
185        };
186        self.ui.run_with_bound_context(|| unsafe {
187            sys::igSelectable_BoolPtr(
188                self.ui.scratch_txt(self.label),
189                selected as *mut bool,
190                self.flags.bits(),
191                size_vec,
192            )
193        })
194    }
195}