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