Skip to main content

dear_imgui_rs/widget/color/
button.rs

1use super::flags::{ColorButtonOptions, ColorInputMode};
2use super::validation::{assert_finite_color4, assert_non_negative_finite_vec2};
3use crate::sys;
4use crate::ui::Ui;
5use std::borrow::Cow;
6
7/// Builder for a color button widget
8#[derive(Debug)]
9#[must_use]
10pub struct ColorButton<'ui> {
11    ui: &'ui Ui,
12    desc_id: Cow<'ui, str>,
13    color: [f32; 4],
14    flags: ColorButtonOptions,
15    size: [f32; 2],
16}
17
18impl<'ui> ColorButton<'ui> {
19    /// Creates a new color button builder
20    pub fn new(ui: &'ui Ui, desc_id: impl Into<Cow<'ui, str>>, color: [f32; 4]) -> Self {
21        Self {
22            ui,
23            desc_id: desc_id.into(),
24            color,
25            flags: ColorButtonOptions::new(),
26            size: [0.0, 0.0],
27        }
28    }
29
30    /// Sets the flags for the color button
31    pub fn flags(mut self, flags: impl Into<ColorButtonOptions>) -> Self {
32        self.flags = flags.into();
33        self
34    }
35
36    /// Sets the input color space.
37    pub fn input_mode(mut self, mode: ColorInputMode) -> Self {
38        self.flags.input_mode = Some(mode);
39        self
40    }
41
42    /// Sets the size of the color button
43    pub fn size(mut self, size: [f32; 2]) -> Self {
44        self.size = size;
45        self
46    }
47
48    /// Builds the color button widget
49    pub fn build(self) -> bool {
50        self.flags.validate("ColorButton::build()");
51        assert_finite_color4("ColorButton::build()", "color", &self.color);
52        assert_non_negative_finite_vec2("ColorButton::build()", "size", self.size);
53        let desc_id_ptr = self.ui.scratch_txt(self.desc_id.as_ref());
54        let size_vec: sys::ImVec2 = self.size.into();
55
56        self.ui.run_with_bound_context(|| unsafe {
57            sys::igColorButton(
58                desc_id_ptr,
59                sys::ImVec4 {
60                    x: self.color[0],
61                    y: self.color[1],
62                    z: self.color[2],
63                    w: self.color[3],
64                },
65                self.flags.bits() as i32,
66                size_vec,
67            )
68        })
69    }
70}