dear_imgui/widget/
progress.rs

1use crate::sys;
2use crate::ui::Ui;
3
4/// # Progress Bar Widgets
5impl Ui {
6    /// Creates a progress bar widget.
7    ///
8    /// The fraction should be between 0.0 (0%) and 1.0 (100%).
9    #[doc(alias = "ProgressBar")]
10    pub fn progress_bar(&self, fraction: f32) -> ProgressBar<'_> {
11        ProgressBar::new(self, fraction)
12    }
13
14    /// Creates a progress bar with overlay text.
15    #[doc(alias = "ProgressBar")]
16    pub fn progress_bar_with_overlay(
17        &self,
18        fraction: f32,
19        overlay: impl AsRef<str>,
20    ) -> ProgressBar<'_> {
21        ProgressBar::new(self, fraction).overlay_text(overlay)
22    }
23}
24
25/// Builder for a progress bar widget.
26///
27/// # Examples
28///
29/// ```no_run
30/// # use dear_imgui::*;
31/// # let mut ctx = Context::create();
32/// # let ui = ctx.frame();
33/// ui.progress_bar(0.6)
34///     .size([100.0, 12.0])
35///     .overlay_text("Progress!")
36///     .build();
37/// ```
38#[derive(Clone, Debug)]
39#[must_use]
40pub struct ProgressBar<'ui> {
41    fraction: f32,
42    size: [f32; 2],
43    overlay_text: Option<String>,
44    ui: &'ui Ui,
45}
46
47impl<'ui> ProgressBar<'ui> {
48    /// Creates a progress bar with a given fraction showing
49    /// the progress (0.0 = 0%, 1.0 = 100%).
50    ///
51    /// The progress bar will be automatically sized to fill the entire width of the window if no
52    /// custom size is specified.
53    #[inline]
54    #[doc(alias = "ProgressBar")]
55    pub fn new(ui: &'ui Ui, fraction: f32) -> Self {
56        ProgressBar {
57            fraction,
58            size: [-1.0, 0.0], // -1.0 means auto-size to fill width
59            overlay_text: None,
60            ui,
61        }
62    }
63
64    /// Sets an optional text that will be drawn over the progress bar.
65    pub fn overlay_text(mut self, overlay_text: impl AsRef<str>) -> Self {
66        self.overlay_text = Some(overlay_text.as_ref().to_string());
67        self
68    }
69
70    /// Sets the size of the progress bar.
71    ///
72    /// Negative values will automatically align to the end of the axis, zero will let the progress
73    /// bar choose a size, and positive values will use the given size.
74    #[inline]
75    pub fn size(mut self, size: impl Into<[f32; 2]>) -> Self {
76        self.size = size.into();
77        self
78    }
79
80    /// Sets the progress fraction (0.0 to 1.0)
81    pub fn fraction(mut self, fraction: f32) -> Self {
82        self.fraction = fraction;
83        self
84    }
85
86    /// Builds the progress bar
87    pub fn build(self) {
88        let size_vec: sys::ImVec2 = self.size.into();
89        let overlay_ptr = self
90            .overlay_text
91            .as_ref()
92            .map(|s| self.ui.scratch_txt(s))
93            .unwrap_or(std::ptr::null());
94
95        unsafe {
96            sys::igProgressBar(self.fraction, size_vec, overlay_ptr);
97        }
98    }
99}