fyrox_ui/
rect.rs

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
//! Rect editor widget is used to show and edit [`Rect`] values. It shows four numeric fields: two for top left corner
//! of a rect, two for its size. See [`RectEditor`] docs for more info and usage examples.

#![warn(missing_docs)]

use crate::{
    core::{
        algebra::Vector2, math::Rect, pool::Handle, reflect::prelude::*, type_traits::prelude::*,
        visitor::prelude::*,
    },
    define_constructor,
    grid::{Column, GridBuilder, Row},
    message::{MessageDirection, UiMessage},
    numeric::NumericType,
    text::TextBuilder,
    vec::{VecEditorBuilder, VecEditorMessage},
    widget::{Widget, WidgetBuilder},
    BuildContext, Control, Thickness, UiNode, UserInterface, VerticalAlignment,
};
use fyrox_core::variable::InheritableVariable;
use std::{
    fmt::Debug,
    ops::{Deref, DerefMut},
};

/// A set of possible messages, that can be used to either modify or fetch the state of a [`RectEditor`] widget.
#[derive(Debug, Clone, PartialEq)]
pub enum RectEditorMessage<T>
where
    T: NumericType,
{
    /// A message, that can be used to either modify or fetch the current value of a [`RectEditor`] widget.
    Value(Rect<T>),
}

impl<T: NumericType> RectEditorMessage<T> {
    define_constructor!(
        /// Creates [`RectEditorMessage::Value`] message.
        RectEditorMessage:Value => fn value(Rect<T>), layout: false
    );
}

/// Rect editor widget is used to show and edit [`Rect`] values. It shows four numeric fields: two for top left corner
/// of a rect, two for its size.
///
/// ## Example
///
/// Rect editor can be created using [`RectEditorBuilder`], like so:
///
/// ```rust
/// # use fyrox_ui::{
/// #     core::{math::Rect, pool::Handle},
/// #     rect::RectEditorBuilder,
/// #     widget::WidgetBuilder,
/// #     BuildContext, UiNode,
/// # };
/// #
/// fn create_rect_editor(ctx: &mut BuildContext) -> Handle<UiNode> {
///     RectEditorBuilder::new(WidgetBuilder::new())
///         .with_value(Rect::new(0, 0, 10, 20))
///         .build(ctx)
/// }
/// ```
///
/// ## Value
///
/// To change the value of a rect editor, use [`RectEditorMessage::Value`] message:
///
/// ```rust
/// # use fyrox_ui::{
/// #     core::{math::Rect, pool::Handle},
/// #     message::MessageDirection,
/// #     rect::RectEditorMessage,
/// #     UiNode, UserInterface,
/// # };
/// #
/// fn change_value(rect_editor: Handle<UiNode>, ui: &UserInterface) {
///     ui.send_message(RectEditorMessage::value(
///         rect_editor,
///         MessageDirection::ToWidget,
///         Rect::new(20, 20, 60, 80),
///     ));
/// }
/// ```
///
/// To "catch" the moment when the value of a rect editor has changed, listen to the same message, but check its direction:
///
/// ```rust
/// # use fyrox_ui::{
/// #     core::pool::Handle,
/// #     message::{MessageDirection, UiMessage},
/// #     rect::RectEditorMessage,
/// #     UiNode,
/// # };
/// #
/// fn fetch_value(rect_editor: Handle<UiNode>, message: &UiMessage) {
///     if let Some(RectEditorMessage::Value(value)) = message.data::<RectEditorMessage<u32>>() {
///         if message.destination() == rect_editor
///             && message.direction() == MessageDirection::FromWidget
///         {
///             println!("The new value is: {:?}", value)
///         }
///     }
/// }
/// ```
#[derive(Default, Debug, Clone, Visit, Reflect, ComponentProvider)]
pub struct RectEditor<T>
where
    T: NumericType,
{
    /// Base widget of the rect editor.
    pub widget: Widget,
    /// A handle to a widget, that is used to show/edit position part of the rect.
    pub position: InheritableVariable<Handle<UiNode>>,
    /// A handle to a widget, that is used to show/edit size part of the rect.
    pub size: InheritableVariable<Handle<UiNode>>,
    /// Current value of the rect editor.
    pub value: InheritableVariable<Rect<T>>,
}

impl<T> Deref for RectEditor<T>
where
    T: NumericType,
{
    type Target = Widget;

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

impl<T> DerefMut for RectEditor<T>
where
    T: NumericType,
{
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.widget
    }
}

impl<T> TypeUuidProvider for RectEditor<T>
where
    T: NumericType,
{
    fn type_uuid() -> Uuid {
        combine_uuids(
            uuid!("5a3daf9d-f33b-494b-b111-eb55721dc7ac"),
            T::type_uuid(),
        )
    }
}

impl<T> Control for RectEditor<T>
where
    T: NumericType,
{
    fn handle_routed_message(&mut self, ui: &mut UserInterface, message: &mut UiMessage) {
        self.widget.handle_routed_message(ui, message);

        if let Some(RectEditorMessage::Value(value)) = message.data::<RectEditorMessage<T>>() {
            if message.destination() == self.handle
                && message.direction() == MessageDirection::ToWidget
                && *value != *self.value
            {
                self.value.set_value_and_mark_modified(*value);

                ui.send_message(message.reverse());
            }
        } else if let Some(VecEditorMessage::Value(value)) =
            message.data::<VecEditorMessage<T, 2>>()
        {
            if message.direction() == MessageDirection::FromWidget {
                if message.destination() == *self.position {
                    if self.value.position != *value {
                        ui.send_message(RectEditorMessage::value(
                            self.handle,
                            MessageDirection::ToWidget,
                            Rect::new(value.x, value.y, self.value.size.x, self.value.size.y),
                        ));
                    }
                } else if message.destination() == *self.size && self.value.size != *value {
                    ui.send_message(RectEditorMessage::value(
                        self.handle,
                        MessageDirection::ToWidget,
                        Rect::new(
                            self.value.position.x,
                            self.value.position.y,
                            value.x,
                            value.y,
                        ),
                    ));
                }
            }
        }
    }
}

/// Rect editor builder creates [`RectEditor`] widget instances and adds them to the user interface.
pub struct RectEditorBuilder<T>
where
    T: NumericType,
{
    widget_builder: WidgetBuilder,
    value: Rect<T>,
}

fn create_field<T: NumericType>(
    ctx: &mut BuildContext,
    name: &str,
    value: Vector2<T>,
    row: usize,
) -> (Handle<UiNode>, Handle<UiNode>) {
    let editor;
    let grid = GridBuilder::new(
        WidgetBuilder::new()
            .with_margin(Thickness::left(10.0))
            .on_row(row)
            .with_child(
                TextBuilder::new(WidgetBuilder::new())
                    .with_text(name)
                    .with_vertical_text_alignment(VerticalAlignment::Center)
                    .build(ctx),
            )
            .with_child({
                editor = VecEditorBuilder::new(WidgetBuilder::new().on_column(1))
                    .with_value(value)
                    .build(ctx);
                editor
            }),
    )
    .add_column(Column::strict(70.0))
    .add_column(Column::stretch())
    .add_row(Row::stretch())
    .build(ctx);
    (grid, editor)
}

impl<T> RectEditorBuilder<T>
where
    T: NumericType,
{
    /// Creates new rect editor builder instance.
    pub fn new(widget_builder: WidgetBuilder) -> Self {
        Self {
            widget_builder,
            value: Default::default(),
        }
    }

    /// Sets the desired value.
    pub fn with_value(mut self, value: Rect<T>) -> Self {
        self.value = value;
        self
    }

    /// Finished rect editor widget building and adds it to the user interface.
    pub fn build(self, ctx: &mut BuildContext) -> Handle<UiNode> {
        let (position_grid, position) = create_field(ctx, "Position", self.value.position, 0);
        let (size_grid, size) = create_field(ctx, "Size", self.value.size, 1);
        let node = RectEditor {
            widget: self
                .widget_builder
                .with_child(
                    GridBuilder::new(
                        WidgetBuilder::new()
                            .with_child(position_grid)
                            .with_child(size_grid),
                    )
                    .add_row(Row::stretch())
                    .add_row(Row::stretch())
                    .add_column(Column::stretch())
                    .build(ctx),
                )
                .build(),
            value: self.value.into(),
            position: position.into(),
            size: size.into(),
        };

        ctx.add_node(UiNode::new(node))
    }
}