fyrox-ui 0.36.2

Extendable UI library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

//! A visual element that is used to highlight standard states of interactive widgets. It has "pressed", "hover",
//! "selected", "normal" appearances. See [`Decorator`] docs for more info and usage examples.

#![warn(missing_docs)]

use crate::style::resource::StyleResourceExt;
use crate::style::{Style, StyledProperty};
use crate::widget::WidgetBuilder;
use crate::{
    border::{Border, BorderBuilder},
    brush::Brush,
    core::{
        algebra::Vector2, pool::Handle, reflect::prelude::*, type_traits::prelude::*,
        visitor::prelude::*,
    },
    define_constructor,
    draw::DrawingContext,
    message::{MessageDirection, UiMessage},
    widget::{Widget, WidgetMessage},
    BuildContext, Control, UiNode, UserInterface,
};
use fyrox_core::uuid_provider;
use fyrox_core::variable::InheritableVariable;
use fyrox_graph::constructor::{ConstructorProvider, GraphNodeConstructor};
use std::ops::{Deref, DerefMut};

/// A set of messages that is used to modify [`Decorator`] widgets state.
#[derive(Debug, Clone, PartialEq)]
pub enum DecoratorMessage {
    /// This message is used to switch a decorator in a `Selected` state or not.
    Select(bool),
    /// Sets a new brush for `Hovered` state.
    HoverBrush(StyledProperty<Brush>),
    /// Sets a new brush for `Normal` state.
    NormalBrush(StyledProperty<Brush>),
    /// Sets a new brush for `Pressed` state.
    PressedBrush(StyledProperty<Brush>),
    /// Sets a new brush for `Selected` state.
    SelectedBrush(StyledProperty<Brush>),
}

impl DecoratorMessage {
    define_constructor!(
        /// Creates a [`DecoratorMessage::Select`] message.
        DecoratorMessage:Select => fn select(bool), layout: false
    );
    define_constructor!(
        /// Creates a [`DecoratorMessage::HoverBrush`] message.
        DecoratorMessage:HoverBrush => fn hover_brush(StyledProperty<Brush>), layout: false
    );
    define_constructor!(
        /// Creates a [`DecoratorMessage::NormalBrush`] message.
        DecoratorMessage:NormalBrush => fn normal_brush(StyledProperty<Brush>), layout: false
    );
    define_constructor!(
        /// Creates a [`DecoratorMessage::PressedBrush`] message.
        DecoratorMessage:PressedBrush => fn pressed_brush(StyledProperty<Brush>), layout: false
    );
    define_constructor!(
        /// Creates a [`DecoratorMessage::SelectedBrush`] message.
        DecoratorMessage:SelectedBrush => fn selected_brush(StyledProperty<Brush>), layout: false
    );
}

/// A visual element that is used to highlight standard states of interactive widgets. It has "pressed", "hover",
/// "selected", "normal" appearances (only one can be active at a time):
///
/// - `Pressed` - enables on mouse down message.
/// - `Selected` - whether decorator selected or not.
/// - `Hovered` - mouse is over decorator.
/// - `Normal` - not selected, pressed, hovered.
///
/// This element is widely used to provide some generic visual behaviour for various widgets. For example it used
/// to decorate buttons - it has use of three of these states. When it is clicked - the decorator will be in `Pressed`
/// state, when hovered by a cursor - `Hovered`, otherwise it stays in `Normal` state.
///
/// ## Example
///
/// ```rust
/// # use fyrox_ui::{
/// #     border::BorderBuilder,
/// #     brush::Brush,
/// #     core::{color::Color, pool::Handle},
/// #     decorator::DecoratorBuilder,
/// #     widget::WidgetBuilder,
/// #     BuildContext, UiNode,
/// # };
/// fn create_decorator(ctx: &mut BuildContext) -> Handle<UiNode> {
///     DecoratorBuilder::new(BorderBuilder::new(WidgetBuilder::new()))
///         .with_hover_brush(Brush::Solid(Color::opaque(0, 255, 0)).into())
///         .build(ctx)
/// }
/// ```
#[derive(Default, Clone, Visit, Reflect, Debug, ComponentProvider)]
pub struct Decorator {
    /// Base widget of the decorator.
    #[component(include)]
    pub border: Border,
    /// Current brush used for `Normal` state.
    pub normal_brush: InheritableVariable<StyledProperty<Brush>>,
    /// Current brush used for `Hovered` state.
    pub hover_brush: InheritableVariable<StyledProperty<Brush>>,
    /// Current brush used for `Pressed` state.
    pub pressed_brush: InheritableVariable<StyledProperty<Brush>>,
    /// Current brush used for `Selected` state.
    pub selected_brush: InheritableVariable<StyledProperty<Brush>>,
    /// Whether the decorator is in `Selected` state or not.
    pub is_selected: InheritableVariable<bool>,
    /// Whether the decorator should react to mouse clicks and switch its state to `Pressed` or not.
    pub is_pressable: InheritableVariable<bool>,
}

impl ConstructorProvider<UiNode, UserInterface> for Decorator {
    fn constructor() -> GraphNodeConstructor<UiNode, UserInterface> {
        GraphNodeConstructor::new::<Self>()
            .with_variant("Decorator", |ui| {
                DecoratorBuilder::new(BorderBuilder::new(
                    WidgetBuilder::new().with_name("Decorator"),
                ))
                .build(&mut ui.build_ctx())
                .into()
            })
            .with_group("Visual")
    }
}

impl Deref for Decorator {
    type Target = Widget;

    fn deref(&self) -> &Self::Target {
        &self.border
    }
}

impl DerefMut for Decorator {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.border
    }
}

uuid_provider!(Decorator = "bb4b60aa-c657-4ed6-8db6-d7f374397c73");

impl Control for Decorator {
    fn measure_override(&self, ui: &UserInterface, available_size: Vector2<f32>) -> Vector2<f32> {
        self.border.measure_override(ui, available_size)
    }

    fn arrange_override(&self, ui: &UserInterface, final_size: Vector2<f32>) -> Vector2<f32> {
        self.border.arrange_override(ui, final_size)
    }

    fn draw(&self, drawing_context: &mut DrawingContext) {
        self.border.draw(drawing_context)
    }

    fn update(&mut self, dt: f32, ui: &mut UserInterface) {
        self.border.update(dt, ui)
    }

    fn handle_routed_message(&mut self, ui: &mut UserInterface, message: &mut UiMessage) {
        self.border.handle_routed_message(ui, message);

        if let Some(msg) = message.data::<DecoratorMessage>() {
            match msg {
                &DecoratorMessage::Select(value) => {
                    if *self.is_selected != value {
                        self.is_selected.set_value_and_mark_modified(value);

                        ui.send_message(WidgetMessage::background(
                            self.handle(),
                            MessageDirection::ToWidget,
                            if *self.is_selected {
                                (*self.selected_brush).clone()
                            } else {
                                (*self.normal_brush).clone()
                            },
                        ));
                    }
                }
                DecoratorMessage::HoverBrush(brush) => {
                    self.hover_brush.set_value_and_mark_modified(brush.clone());
                    if self.is_mouse_directly_over {
                        ui.send_message(WidgetMessage::background(
                            self.handle(),
                            MessageDirection::ToWidget,
                            (*self.hover_brush).clone(),
                        ));
                    }
                }
                DecoratorMessage::NormalBrush(brush) => {
                    self.normal_brush.set_value_and_mark_modified(brush.clone());
                    if !*self.is_selected && !self.is_mouse_directly_over {
                        ui.send_message(WidgetMessage::background(
                            self.handle(),
                            MessageDirection::ToWidget,
                            (*self.normal_brush).clone(),
                        ));
                    }
                }
                DecoratorMessage::PressedBrush(brush) => {
                    self.pressed_brush
                        .set_value_and_mark_modified(brush.clone());
                }
                DecoratorMessage::SelectedBrush(brush) => {
                    self.selected_brush
                        .set_value_and_mark_modified(brush.clone());
                    if *self.is_selected {
                        ui.send_message(WidgetMessage::background(
                            self.handle(),
                            MessageDirection::ToWidget,
                            (*self.selected_brush).clone(),
                        ));
                    }
                }
            }
        } else if let Some(msg) = message.data::<WidgetMessage>() {
            if message.destination() == self.handle()
                || self.has_descendant(message.destination(), ui)
            {
                match msg {
                    WidgetMessage::MouseLeave => {
                        ui.send_message(WidgetMessage::background(
                            self.handle(),
                            MessageDirection::ToWidget,
                            if *self.is_selected {
                                (*self.selected_brush).clone()
                            } else {
                                (*self.normal_brush).clone()
                            },
                        ));
                    }
                    WidgetMessage::MouseEnter => {
                        ui.send_message(WidgetMessage::background(
                            self.handle(),
                            MessageDirection::ToWidget,
                            if *self.is_selected {
                                (*self.selected_brush).clone()
                            } else {
                                (*self.hover_brush).clone()
                            },
                        ));
                    }
                    WidgetMessage::MouseDown { .. } if *self.is_pressable => {
                        ui.send_message(WidgetMessage::background(
                            self.handle(),
                            MessageDirection::ToWidget,
                            (*self.pressed_brush).clone(),
                        ));
                    }
                    WidgetMessage::MouseUp { .. } => {
                        if *self.is_selected {
                            ui.send_message(WidgetMessage::background(
                                self.handle(),
                                MessageDirection::ToWidget,
                                (*self.selected_brush).clone(),
                            ));
                        } else {
                            ui.send_message(WidgetMessage::background(
                                self.handle(),
                                MessageDirection::ToWidget,
                                (*self.normal_brush).clone(),
                            ));
                        }
                    }
                    _ => {}
                }
            }

            if message.destination() == self.handle() {
                if let WidgetMessage::Style(style) = msg {
                    self.normal_brush.update(style);
                    self.hover_brush.update(style);
                    self.pressed_brush.update(style);
                    self.selected_brush.update(style);
                }
            }
        }
    }
}

/// Creates [`Decorator`] widget instances and adds them to the user interface.
pub struct DecoratorBuilder {
    border_builder: BorderBuilder,
    normal_brush: Option<StyledProperty<Brush>>,
    hover_brush: Option<StyledProperty<Brush>>,
    pressed_brush: Option<StyledProperty<Brush>>,
    selected_brush: Option<StyledProperty<Brush>>,
    pressable: bool,
    selected: bool,
}

impl DecoratorBuilder {
    /// Creates a new decorator builder.
    pub fn new(border_builder: BorderBuilder) -> Self {
        Self {
            normal_brush: None,
            hover_brush: None,
            pressed_brush: None,
            selected_brush: None,
            pressable: true,
            selected: false,
            border_builder,
        }
    }

    /// Sets a desired brush for `Normal` state.
    pub fn with_normal_brush(mut self, brush: StyledProperty<Brush>) -> Self {
        self.normal_brush = Some(brush);
        self
    }

    /// Sets a desired brush for `Hovered` state.
    pub fn with_hover_brush(mut self, brush: StyledProperty<Brush>) -> Self {
        self.hover_brush = Some(brush);
        self
    }

    /// Sets a desired brush for `Pressed` state.
    pub fn with_pressed_brush(mut self, brush: StyledProperty<Brush>) -> Self {
        self.pressed_brush = Some(brush);
        self
    }

    /// Sets a desired brush for `Selected` state.
    pub fn with_selected_brush(mut self, brush: StyledProperty<Brush>) -> Self {
        self.selected_brush = Some(brush);
        self
    }

    /// Sets whether the decorator is pressable or not.
    pub fn with_pressable(mut self, pressable: bool) -> Self {
        self.pressable = pressable;
        self
    }

    /// Sets whether the decorator is selected or not.
    pub fn with_selected(mut self, selected: bool) -> Self {
        self.selected = selected;
        self
    }

    /// Finishes decorator instance building.
    pub fn build(mut self, ctx: &mut BuildContext) -> Handle<UiNode> {
        let normal_brush = self
            .normal_brush
            .unwrap_or_else(|| ctx.style.property::<Brush>(Style::BRUSH_LIGHT));
        let hover_brush = self
            .hover_brush
            .unwrap_or_else(|| ctx.style.property::<Brush>(Style::BRUSH_LIGHTER));
        let pressed_brush = self
            .pressed_brush
            .unwrap_or_else(|| ctx.style.property::<Brush>(Style::BRUSH_LIGHTEST));
        let selected_brush = self
            .selected_brush
            .unwrap_or_else(|| ctx.style.property::<Brush>(Style::BRUSH_BRIGHT));

        if self.border_builder.widget_builder.foreground.is_none() {
            let brush = ctx.style.property(Style::BRUSH_DARKER);
            self.border_builder.widget_builder.foreground = Some(brush);
        }

        let mut border = self.border_builder.build_border(ctx);

        if self.selected {
            *border.background = selected_brush.clone();
        } else {
            *border.background = normal_brush.clone();
        }

        let node = UiNode::new(Decorator {
            border,
            normal_brush: normal_brush.into(),
            hover_brush: hover_brush.into(),
            pressed_brush: pressed_brush.into(),
            selected_brush: selected_brush.into(),
            is_selected: self.selected.into(),
            is_pressable: self.pressable.into(),
        });
        ctx.add_node(node)
    }
}

#[cfg(test)]
mod test {
    use crate::border::BorderBuilder;
    use crate::decorator::DecoratorBuilder;
    use crate::{test::test_widget_deletion, widget::WidgetBuilder};

    #[test]
    fn test_deletion() {
        test_widget_deletion(|ctx| {
            DecoratorBuilder::new(BorderBuilder::new(WidgetBuilder::new())).build(ctx)
        });
    }
}