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
//! 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::{
    border::{Border, BorderBuilder},
    brush::Brush,
    core::{algebra::Vector2, pool::Handle},
    define_constructor,
    draw::DrawingContext,
    message::{MessageDirection, UiMessage},
    widget::{Widget, WidgetMessage},
    BuildContext, Control, NodeHandleMapping, UiNode, UserInterface, BRUSH_BRIGHT, BRUSH_DARKER,
    BRUSH_LIGHT, BRUSH_LIGHTER, BRUSH_LIGHTEST,
};
use std::{
    any::{Any, TypeId},
    ops::{Deref, DerefMut},
    sync::mpsc::Sender,
};

/// 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(Brush),
    /// Sets a new brush for `Normal` state.
    NormalBrush(Brush),
    /// Sets a new brush for `Pressed` state.
    PressedBrush(Brush),
    /// Sets a new brush for `Selected` state.
    SelectedBrush(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(Brush), layout: false
    );
    define_constructor!(
        /// Creates a [`DecoratorMessage::NormalBrush`] message.
        DecoratorMessage:NormalBrush => fn normal_brush(Brush), layout: false
    );
    define_constructor!(
        /// Creates a [`DecoratorMessage::PressedBrush`] message.
        DecoratorMessage:PressedBrush => fn pressed_brush(Brush), layout: false
    );
    define_constructor!(
        /// Creates a [`DecoratorMessage::SelectedBrush`] message.
        DecoratorMessage:SelectedBrush => fn selected_brush(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)))
///         .build(ctx)
/// }
/// ```
#[derive(Clone)]
pub struct Decorator {
    /// Base widget of the decorator.
    pub border: Border,
    /// Current brush used for `Normal` state.
    pub normal_brush: Brush,
    /// Current brush used for `Hovered` state.
    pub hover_brush: Brush,
    /// Current brush used for `Pressed` state.
    pub pressed_brush: Brush,
    /// Current brush used for `Selected` state.
    pub selected_brush: Brush,
    /// Whether the decorator is in `Selected` state or not.
    pub is_selected: bool,
    /// Whether the decorator should react to mouse clicks and switch its state to `Pressed` or not.
    pub is_pressable: bool,
}

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
    }
}

impl Control for Decorator {
    fn query_component(&self, type_id: TypeId) -> Option<&dyn Any> {
        self.border.query_component(type_id).or_else(|| {
            if type_id == TypeId::of::<Self>() {
                Some(self)
            } else {
                None
            }
        })
    }

    fn resolve(&mut self, node_map: &NodeHandleMapping) {
        self.border.resolve(node_map)
    }

    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, sender: &Sender<UiMessage>) {
        self.border.update(dt, sender)
    }

    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 = value;
                        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(),
                            ));
                        }
                    }
                }
                DecoratorMessage::HoverBrush(brush) => {
                    self.hover_brush = 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 = 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 = brush.clone();
                }
                DecoratorMessage::SelectedBrush(brush) => {
                    self.selected_brush = 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 => {
                        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(),
                            ));
                        }
                    }
                    WidgetMessage::MouseEnter => {
                        ui.send_message(WidgetMessage::background(
                            self.handle(),
                            MessageDirection::ToWidget,
                            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(),
                            ));
                        }
                    }
                    _ => {}
                }
            }
        }
    }
}

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

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

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

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

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

    /// Sets a desired brush for `Selected` state.
    pub fn with_selected_brush(mut self, brush: Brush) -> Self {
        self.selected_brush = 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, ui: &mut BuildContext) -> Handle<UiNode> {
        let normal_brush = self.normal_brush;
        let selected_brush = self.selected_brush;

        if self.border_builder.widget_builder.foreground.is_none() {
            self.border_builder.widget_builder.foreground = Some(BRUSH_DARKER);
        }

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

        if self.selected {
            border.set_background(selected_brush.clone());
        } else {
            border.set_background(normal_brush.clone());
        }

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