fyrox-ui 1.0.1

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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
// 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.

//! Defines a clickable widget with arbitrary content. See [`Button`] dos for more info and examples.

#![warn(missing_docs)]

use crate::message::MessageData;
use crate::style::StyledProperty;
use crate::{
    border::BorderBuilder,
    core::{
        pool::Handle, reflect::prelude::*, type_traits::prelude::*, variable::InheritableVariable,
        visitor::prelude::*,
    },
    decorator::DecoratorBuilder,
    font::FontResource,
    message::{KeyCode, UiMessage},
    style::{resource::StyleResourceExt, Style},
    text::TextBuilder,
    widget::{Widget, WidgetBuilder, WidgetMessage},
    BuildContext, Control, HorizontalAlignment, Thickness, UiNode, UserInterface,
    VerticalAlignment,
};
use fyrox_core::pool::ObjectOrVariant;
use fyrox_graph::constructor::{ConstructorProvider, GraphNodeConstructor};
use std::cell::RefCell;

/// Messages that can be emitted by [`Button`] widget (or can be sent to the widget).
#[derive(Debug, Clone, PartialEq)]
pub enum ButtonMessage {
    /// Emitted by the button widget when it was clicked by any mouse button. Click event is a press with the following release
    /// of a mouse button withing the button bounds. This message can be only emitted, not sent. See [`Button`] docs
    /// for usage examples.
    Click,
    /// A message, that can be used to set new content of the button. See [`ButtonContent`] for usage examples.
    Content(ButtonContent),
    /// Click repetition interval (in seconds) of the button. The button will send [`ButtonMessage::Click`] with the
    /// desired period.
    RepeatInterval(f32),
    /// A flag, that defines whether the button should repeat click message when being hold or not.
    RepeatClicksOnHold(bool),
}
impl MessageData for ButtonMessage {}

/// Defines a clickable widget with arbitrary content. The content could be any kind of widget, usually it
/// is just a text or an image.
///
/// ## Examples
///
/// To create a simple button with text, you should do something like this:
///
/// ```rust
/// # use fyrox_ui::{
/// #     core::pool::Handle,
/// #     button::{ButtonBuilder, Button}, widget::WidgetBuilder, UiNode, UserInterface
/// # };
/// fn create_button(ui: &mut UserInterface) -> Handle<Button> {
///     ButtonBuilder::new(WidgetBuilder::new())
///         .with_text("Click me!")
///         .build(&mut ui.build_ctx())
/// }
/// ```
///
/// To do something when your button was clicked you need to "listen" to user interface messages from the
/// queue and check if there's [`ButtonMessage::Click`] message from your button:
///
/// ```rust
/// # use fyrox_ui::{button::ButtonMessage, core::pool::Handle, message::UiMessage, UiNode};
/// fn on_ui_message(message: &UiMessage) {
/// #   let your_button_handle = Handle::<UiNode>::NONE;
///     if let Some(ButtonMessage::Click) = message.data() {
///         if message.destination() == your_button_handle {
///             println!("{} button was clicked!", message.destination());
///         }
///     }
/// }
/// ```
#[derive(Default, Clone, Visit, Reflect, Debug, TypeUuidProvider, ComponentProvider)]
#[type_uuid(id = "2abcf12b-2f19-46da-b900-ae8890f7c9c6")]
#[reflect(derived_type = "UiNode")]
pub struct Button {
    /// Base widget of the button.
    pub widget: Widget,
    /// Current content holder of the button.
    pub decorator: InheritableVariable<Handle<UiNode>>,
    /// Current content of the button. It is attached to the content holder.
    pub content: InheritableVariable<Handle<UiNode>>,
    /// Click repetition interval (in seconds) of the button.
    #[visit(optional)]
    #[reflect(min_value = 0.0)]
    pub repeat_interval: InheritableVariable<f32>,
    /// Current clicks repetition timer.
    #[visit(optional)]
    #[reflect(hidden)]
    pub repeat_timer: RefCell<Option<f32>>,
    /// A flag, that defines whether the button should repeat click message when being
    /// hold or not. Default is `false` (disabled).
    #[visit(optional)]
    pub repeat_clicks_on_hold: InheritableVariable<bool>,
}

impl Button {
    /// A name of style property, that defines corner radius of a button.
    pub const CORNER_RADIUS: &'static str = "Button.CornerRadius";
    /// A name of style property, that defines border thickness of a button.
    pub const BORDER_THICKNESS: &'static str = "Button.BorderThickness";

    /// Returns a style of the widget. This style contains only widget-specific properties.
    pub fn style() -> Style {
        Style::default()
            .with(Self::CORNER_RADIUS, 4.0f32)
            .with(Self::BORDER_THICKNESS, Thickness::uniform(1.0))
    }
}

impl ConstructorProvider<UiNode, UserInterface> for Button {
    fn constructor() -> GraphNodeConstructor<UiNode, UserInterface> {
        GraphNodeConstructor::new::<Self>()
            .with_variant("Button", |ui| {
                ButtonBuilder::new(
                    WidgetBuilder::new()
                        .with_width(100.0)
                        .with_height(20.0)
                        .with_name("Button"),
                )
                .build(&mut ui.build_ctx())
                .to_base()
                .into()
            })
            .with_group("Input")
    }
}

crate::define_widget_deref!(Button);

impl Control for Button {
    fn update(&mut self, dt: f32, ui: &mut UserInterface) {
        let mut repeat_timer = self.repeat_timer.borrow_mut();
        if let Some(repeat_timer) = &mut *repeat_timer {
            *repeat_timer -= dt;
            if *repeat_timer <= 0.0 {
                ui.post(self.handle(), ButtonMessage::Click);
                *repeat_timer = *self.repeat_interval;
            }
        }
    }

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

        if let Some(msg) = message.data::<WidgetMessage>() {
            if message.destination() == self.handle()
                || self.has_descendant(message.destination(), ui)
            {
                match msg {
                    WidgetMessage::MouseDown { .. }
                    | WidgetMessage::TouchStarted { .. }
                    | WidgetMessage::TouchMoved { .. } => {
                        // The only way to avoid a `MouseLeave` message is by capturing the currently picked node.
                        // Capturing any other node will change the picked node and be considered leaving,
                        // which would affect the decorator.
                        ui.capture_mouse(message.destination());
                        message.set_handled(true);
                        if *self.repeat_clicks_on_hold {
                            self.repeat_timer.replace(Some(*self.repeat_interval));
                        }
                    }
                    WidgetMessage::MouseUp { .. } | WidgetMessage::TouchEnded { .. } => {
                        // Do the click only if the mouse is still within the button and the event hasn't been handled.
                        // The event might be handled if there is a child button within this button, as with the
                        // close button on a tab.
                        if self.screen_bounds().contains(ui.cursor_position()) && !message.handled()
                        {
                            ui.post(self.handle(), ButtonMessage::Click);
                        }
                        ui.release_mouse_capture();
                        message.set_handled(true);
                        self.repeat_timer.replace(None);
                    }
                    WidgetMessage::KeyDown(key_code) => {
                        if !message.handled()
                            && (*key_code == KeyCode::Enter
                                || *key_code == KeyCode::NumpadEnter
                                || *key_code == KeyCode::Space)
                        {
                            ui.post(self.handle, ButtonMessage::Click);
                            message.set_handled(true);
                        }
                    }
                    _ => (),
                }
            }
        } else if let Some(msg) = message.data_for::<ButtonMessage>(self.handle()) {
            match msg {
                ButtonMessage::Click => (),
                ButtonMessage::Content(content) => {
                    if self.content.is_some() {
                        ui.send(*self.content, WidgetMessage::Remove);
                    }
                    self.content
                        .set_value_and_mark_modified(content.build(&mut ui.build_ctx()));
                    ui.send(*self.content, WidgetMessage::LinkWith(*self.decorator));
                }
                ButtonMessage::RepeatInterval(interval) => {
                    if *self.repeat_interval != *interval {
                        *self.repeat_interval = *interval;
                        ui.try_send_response(message);
                    }
                }
                ButtonMessage::RepeatClicksOnHold(repeat_clicks) => {
                    if *self.repeat_clicks_on_hold != *repeat_clicks {
                        *self.repeat_clicks_on_hold = *repeat_clicks;
                        ui.try_send_response(message);
                    }
                }
            }
        }
    }
}

/// Possible button content. In general, button widget can contain any type of widget inside. This enum contains
/// a special shortcuts for most commonly used cases - button with the default font, button with custom font, or
/// button with any widget.
#[derive(Debug, Clone, PartialEq)]
pub enum ButtonContent {
    /// A shortcut to create a [crate::text::Text] widget as the button content. It is the same as creating Text
    /// widget yourself, but much shorter.
    Text {
        /// Text of the button.
        text: String,
        /// Optional font of the button. If [`None`], the default font will be used.
        font: Option<FontResource>,
        /// Font size of the text. Default is 14.0 (defined by default style of the crate).
        size: Option<StyledProperty<f32>>,
    },
    /// Arbitrary widget handle. It could be any widget handle, for example, a handle of [`crate::image::Image`]
    /// widget.
    Node(Handle<UiNode>),
}

impl ButtonContent {
    /// Creates [`ButtonContent::Text`] with default font.
    pub fn text<S: AsRef<str>>(s: S) -> Self {
        Self::Text {
            text: s.as_ref().to_owned(),
            font: None,
            size: None,
        }
    }

    /// Creates [`ButtonContent::Text`] with custom font.
    pub fn text_with_font<S: AsRef<str>>(s: S, font: FontResource) -> Self {
        Self::Text {
            text: s.as_ref().to_owned(),
            font: Some(font),
            size: None,
        }
    }

    /// Creates [`ButtonContent::Text`] with custom font and size.
    pub fn text_with_font_size<S: AsRef<str>>(
        s: S,
        font: FontResource,
        size: StyledProperty<f32>,
    ) -> Self {
        Self::Text {
            text: s.as_ref().to_owned(),
            font: Some(font),
            size: Some(size),
        }
    }

    /// Creates [`ButtonContent::Node`].
    pub fn node(node: Handle<UiNode>) -> Self {
        Self::Node(node)
    }

    fn build(&self, ctx: &mut BuildContext) -> Handle<UiNode> {
        match self {
            Self::Text { text, font, size } => TextBuilder::new(WidgetBuilder::new())
                .with_text(text)
                .with_horizontal_text_alignment(HorizontalAlignment::Center)
                .with_vertical_text_alignment(VerticalAlignment::Center)
                .with_font(font.clone().unwrap_or_else(|| ctx.default_font()))
                .with_font_size(
                    size.clone()
                        .unwrap_or_else(|| ctx.style.property(Style::FONT_SIZE)),
                )
                .build(ctx)
                .to_base(),
            Self::Node(node) => *node,
        }
    }
}

/// Button builder is used to create [`Button`] widget instances.
pub struct ButtonBuilder {
    widget_builder: WidgetBuilder,
    content: Option<ButtonContent>,
    back: Option<Handle<UiNode>>,
    repeat_interval: f32,
    repeat_clicks_on_hold: bool,
}

fn make_decorator_builder(ctx: &mut BuildContext) -> DecoratorBuilder {
    DecoratorBuilder::new(
        BorderBuilder::new(WidgetBuilder::new())
            .with_pad_by_corner_radius(false)
            .with_corner_radius(ctx.style.property(Button::CORNER_RADIUS))
            .with_stroke_thickness(ctx.style.property(Button::BORDER_THICKNESS)),
    )
}

impl ButtonBuilder {
    /// Creates a new button builder with a widget builder instance.
    pub fn new(widget_builder: WidgetBuilder) -> Self {
        Self {
            widget_builder,
            content: None,
            back: None,
            repeat_interval: 0.1,
            repeat_clicks_on_hold: false,
        }
    }

    /// Sets the content of the button to be [`ButtonContent::Text`] (text with the default font).
    pub fn with_text(mut self, text: &str) -> Self {
        self.content = Some(ButtonContent::text(text));
        self
    }

    /// Sets the content of the button to be [`ButtonContent::Text`] (text with a custom font).
    pub fn with_text_and_font(mut self, text: &str, font: FontResource) -> Self {
        self.content = Some(ButtonContent::text_with_font(text, font));
        self
    }

    /// Sets the content of the button to be [`ButtonContent::Text`] (text with a custom font and size).
    pub fn with_text_and_font_size(
        mut self,
        text: &str,
        font: FontResource,
        size: StyledProperty<f32>,
    ) -> Self {
        self.content = Some(ButtonContent::text_with_font_size(text, font, size));
        self
    }

    /// Sets the content of the button to be [`ButtonContent::Node`] (arbitrary widget handle).
    pub fn with_content(mut self, node: Handle<impl ObjectOrVariant<UiNode>>) -> Self {
        self.content = Some(ButtonContent::Node(node.to_base()));
        self
    }

    /// Specifies the widget that will be used as a content holder of the button. By default, it is an
    /// instance of [`crate::decorator::Decorator`] widget. Usually, this widget should respond to mouse
    /// events to highlight button state (hovered, pressed, etc.)
    pub fn with_back(mut self, decorator: Handle<impl ObjectOrVariant<UiNode>>) -> Self {
        self.back = Some(decorator.to_base());
        self
    }

    /// Sets a new decorator background with `ok` style (green color by default).
    pub fn with_ok_back(mut self, ctx: &mut BuildContext) -> Self {
        self.back = Some(
            make_decorator_builder(ctx)
                .with_ok_style(ctx)
                .build(ctx)
                .to_base(),
        );
        self
    }

    /// Sets a new decorator background with `cancel` style (red color by default).
    pub fn with_cancel_back(mut self, ctx: &mut BuildContext) -> Self {
        self.back = Some(
            make_decorator_builder(ctx)
                .with_cancel_style(ctx)
                .build(ctx)
                .to_base(),
        );
        self
    }

    /// Set the flag, that defines whether the button should repeat click message when being hold or not.
    /// Default is `false` (disabled).
    pub fn with_repeat_clicks_on_hold(mut self, repeat: bool) -> Self {
        self.repeat_clicks_on_hold = repeat;
        self
    }

    /// Sets the desired click repetition interval (in seconds) of the button. Default is 0.1s
    pub fn with_repeat_interval(mut self, interval: f32) -> Self {
        self.repeat_interval = interval;
        self
    }

    /// Finishes building a button.
    pub fn build_button(self, ctx: &mut BuildContext) -> Button {
        let content = self.content.map(|c| c.build(ctx)).unwrap_or_default();
        let back = self.back.unwrap_or_else(|| {
            make_decorator_builder(ctx)
                .with_normal_brush(ctx.style.property(Style::BRUSH_LIGHT))
                .with_hover_brush(ctx.style.property(Style::BRUSH_LIGHTER))
                .with_pressed_brush(ctx.style.property(Style::BRUSH_LIGHTEST))
                .build(ctx)
                .to_base()
        });

        if content.is_some() {
            ctx.link(content, back);
        }

        Button {
            widget: self
                .widget_builder
                .with_accepts_input(true)
                .with_need_update(true)
                .with_child(back)
                .build(ctx),
            decorator: back.into(),
            content: content.into(),
            repeat_interval: self.repeat_interval.into(),
            repeat_clicks_on_hold: self.repeat_clicks_on_hold.into(),
            repeat_timer: Default::default(),
        }
    }

    /// Finishes building a button.
    pub fn build_node(self, ctx: &mut BuildContext) -> UiNode {
        UiNode::new(self.build_button(ctx))
    }

    /// Finishes button build and adds to the user interface and returns its handle.
    pub fn build(self, ctx: &mut BuildContext) -> Handle<Button> {
        let node = self.build_button(ctx);
        ctx.add(node)
    }
}

#[cfg(test)]
mod test {
    use crate::button::ButtonBuilder;
    use crate::{test::test_widget_deletion, widget::WidgetBuilder};

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