fyrox_ui/progress_bar.rs
1// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in all
11// copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21//! Progress bar is used to show a bar that fills in from left to right according to the progress value. It is used to
22//! show progress for long actions. See [`ProgressBar`] widget docs for more info and usage examples.
23
24#![warn(missing_docs)]
25
26use crate::style::resource::StyleResourceExt;
27use crate::style::Style;
28use crate::{
29 border::BorderBuilder,
30 canvas::CanvasBuilder,
31 core::{
32 algebra::Vector2, pool::Handle, reflect::prelude::*, type_traits::prelude::*,
33 visitor::prelude::*,
34 },
35 message::UiMessage,
36 widget::{Widget, WidgetBuilder, WidgetMessage},
37 BuildContext, Control, UiNode, UserInterface,
38};
39
40use crate::message::MessageData;
41use fyrox_core::uuid_provider;
42use fyrox_core::variable::InheritableVariable;
43use fyrox_graph::constructor::{ConstructorProvider, GraphNodeConstructor};
44
45/// A set of messages that can be used to modify the state of a progress bar.
46#[derive(Debug, Clone, PartialEq)]
47pub enum ProgressBarMessage {
48 /// A message, that is used to set progress of the progress bar.
49 Progress(f32),
50}
51impl MessageData for ProgressBarMessage {}
52
53/// Progress bar is used to show a bar that fills in from left to right according to the progress value. It is used to
54/// show progress for long actions.
55///
56/// ## Example
57///
58/// ```rust
59/// # use fyrox_ui::{
60/// # core::pool::Handle, progress_bar::ProgressBarBuilder, widget::WidgetBuilder, BuildContext,
61/// # UiNode,
62/// # };
63/// # use fyrox_ui::progress_bar::ProgressBar;
64///
65/// fn create_progress_bar(ctx: &mut BuildContext) -> Handle<ProgressBar> {
66/// ProgressBarBuilder::new(WidgetBuilder::new())
67/// // Keep mind, that the progress is "normalized", which means that it is defined on
68/// // [0..1] range, where 0 - no progress at all, 1 - maximum progress.
69/// .with_progress(0.25)
70/// .build(ctx)
71/// }
72/// ```
73///
74/// ## Style
75///
76/// It is possible to specify custom indicator (the part that shows the progress) and the back of
77/// the progress bar. Use [`ProgressBarBuilder::with_indicator`] and [`ProgressBarBuilder::with_body`]
78/// methods respectively. These methods can accept any widget, but usually it is a
79/// [`crate::border::Border`], [`crate::image::Image`], [`crate::nine_patch::NinePatch`] widgets.
80///
81/// ## Changing progress
82///
83/// To change progress of a progress bar all you need is to send [`ProgressBarMessage::Progress`] to it:
84///
85/// ```rust
86/// # use fyrox_ui::{
87/// # core::pool::Handle, message::MessageDirection, progress_bar::ProgressBarMessage, UiNode,
88/// # UserInterface,
89/// # };
90/// fn change_progress(progress_bar: Handle<UiNode>, ui: &UserInterface) {
91/// ui.send(progress_bar, ProgressBarMessage::Progress(0.33));
92/// }
93/// ```
94#[derive(Default, Clone, Debug, Visit, Reflect, ComponentProvider)]
95#[reflect(derived_type = "UiNode")]
96pub struct ProgressBar {
97 /// Base widget of the progress bar.
98 pub widget: Widget,
99 /// Current progress of the progress bar.
100 pub progress: InheritableVariable<f32>,
101 /// Handle of a widget that is used to show the progress.
102 pub indicator: InheritableVariable<Handle<UiNode>>,
103 /// Container widget of the bar of the progress bar.
104 pub body: InheritableVariable<Handle<UiNode>>,
105}
106
107impl ConstructorProvider<UiNode, UserInterface> for ProgressBar {
108 fn constructor() -> GraphNodeConstructor<UiNode, UserInterface> {
109 GraphNodeConstructor::new::<Self>()
110 .with_variant("Progress Bar", |ui| {
111 ProgressBarBuilder::new(WidgetBuilder::new().with_name("Progress Bar"))
112 .build(&mut ui.build_ctx())
113 .to_base()
114 .into()
115 })
116 .with_group("Visual")
117 }
118}
119
120crate::define_widget_deref!(ProgressBar);
121
122uuid_provider!(ProgressBar = "d6ebb853-d945-46bc-86db-4c8b5d5faf8e");
123
124impl Control for ProgressBar {
125 fn arrange_override(&self, ui: &UserInterface, final_size: Vector2<f32>) -> Vector2<f32> {
126 let size = self.widget.arrange_override(ui, final_size);
127
128 let width = size.x * *self.progress;
129 ui.send(*self.indicator, WidgetMessage::Width(width));
130 ui.send(*self.indicator, WidgetMessage::Height(size.y));
131
132 size
133 }
134
135 fn handle_routed_message(&mut self, ui: &mut UserInterface, message: &mut UiMessage) {
136 self.widget.handle_routed_message(ui, message);
137
138 if message.destination() == self.handle {
139 if let Some(&ProgressBarMessage::Progress(progress)) =
140 message.data::<ProgressBarMessage>()
141 {
142 if progress != *self.progress {
143 self.set_progress(progress);
144 self.invalidate_layout();
145 }
146 }
147 }
148 }
149}
150
151impl ProgressBar {
152 fn set_progress(&mut self, progress: f32) {
153 self.progress
154 .set_value_and_mark_modified(progress.clamp(0.0, 1.0));
155 }
156}
157
158/// Progress bar builder creates progress bar instances and adds them to the UI.
159pub struct ProgressBarBuilder {
160 widget_builder: WidgetBuilder,
161 body: Option<Handle<UiNode>>,
162 indicator: Option<Handle<UiNode>>,
163 progress: f32,
164}
165
166impl ProgressBarBuilder {
167 /// Creates new builder instance.
168 pub fn new(widget_builder: WidgetBuilder) -> Self {
169 Self {
170 widget_builder,
171 body: None,
172 indicator: None,
173 progress: 0.0,
174 }
175 }
176
177 /// Sets the desired body of the progress bar, which is used to wrap the indicator (bar).
178 pub fn with_body(mut self, body: Handle<UiNode>) -> Self {
179 self.body = Some(body);
180 self
181 }
182
183 /// Sets the desired indicator widget, that will be used to show the progress.
184 pub fn with_indicator(mut self, indicator: Handle<UiNode>) -> Self {
185 self.indicator = Some(indicator);
186 self
187 }
188
189 /// Sets the desired progress value. The input value will be clamped to `[0..1]` range.
190 pub fn with_progress(mut self, progress: f32) -> Self {
191 self.progress = progress.clamp(0.0, 1.0);
192 self
193 }
194
195 /// Finishes progress bar creation and adds the new instance to the user interface.
196 pub fn build(self, ctx: &mut BuildContext) -> Handle<ProgressBar> {
197 let body = self.body.unwrap_or_else(|| {
198 BorderBuilder::new(WidgetBuilder::new())
199 .build(ctx)
200 .to_base()
201 });
202
203 let indicator = self.indicator.unwrap_or_else(|| {
204 BorderBuilder::new(
205 WidgetBuilder::new().with_background(ctx.style.property(Style::BRUSH_BRIGHTEST)),
206 )
207 .build(ctx)
208 .to_base()
209 });
210
211 let canvas = CanvasBuilder::new(WidgetBuilder::new().with_child(indicator)).build(ctx);
212
213 ctx.link(canvas, body);
214
215 let progress_bar = ProgressBar {
216 widget: self.widget_builder.with_child(body).build(ctx),
217 progress: self.progress.into(),
218 indicator: indicator.into(),
219 body: body.into(),
220 };
221
222 ctx.add(progress_bar)
223 }
224}
225
226#[cfg(test)]
227mod test {
228 use crate::progress_bar::ProgressBarBuilder;
229 use crate::{test::test_widget_deletion, widget::WidgetBuilder};
230
231 #[test]
232 fn test_deletion() {
233 test_widget_deletion(|ctx| ProgressBarBuilder::new(WidgetBuilder::new()).build(ctx));
234 }
235}