fyrox_ui/
popup.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
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
//! Popup is used to display other widgets in floating panel, that could lock input in self bounds. See [`Popup`] docs
//! for more info and usage examples.

#![warn(missing_docs)]

use crate::{
    border::BorderBuilder,
    core::{
        algebra::Vector2, math::Rect, pool::Handle, reflect::prelude::*, type_traits::prelude::*,
        uuid_provider, variable::InheritableVariable, visitor::prelude::*,
    },
    define_constructor,
    message::{ButtonState, KeyCode, MessageDirection, OsEvent, UiMessage},
    widget::{Widget, WidgetBuilder, WidgetMessage},
    BuildContext, Control, RestrictionEntry, Thickness, UiNode, UserInterface, BRUSH_DARKEST,
    BRUSH_PRIMARY,
};
use fyrox_graph::BaseSceneGraph;
use std::ops::{Deref, DerefMut};

/// A set of messages for [`Popup`] widget.
#[derive(Debug, Clone, PartialEq)]
pub enum PopupMessage {
    /// Used to open a [`Popup`] widgets. Use [`PopupMessage::open`] to create the message.
    Open,
    /// Used to close a [`Popup`] widgets. Use [`PopupMessage::close`] to create the message.
    Close,
    /// Used to change the content of a [`Popup`] widgets. Use [`PopupMessage::content`] to create the message.
    Content(Handle<UiNode>),
    /// Used to change popup's placement. Use [`PopupMessage::placement`] to create the message.
    Placement(Placement),
    /// Used to adjust position of a popup widget, so it will be on screen. Use [`PopupMessage::adjust_position`] to create
    /// the message.
    AdjustPosition,
    /// Used to set the owner of a Popup. The owner will receive Event messages.
    Owner(Handle<UiNode>),
    /// Sent by the Popup to its owner when handling messages from the Popup's children.
    RelayedMessage(UiMessage),
}

impl PopupMessage {
    define_constructor!(
        /// Creates [`PopupMessage::Open`] message.
        PopupMessage:Open => fn open(), layout: false
    );
    define_constructor!(
        /// Creates [`PopupMessage::Close`] message.
        PopupMessage:Close => fn close(), layout: false
    );
    define_constructor!(
        /// Creates [`PopupMessage::Content`] message.
        PopupMessage:Content => fn content(Handle<UiNode>), layout: false
    );
    define_constructor!(
        /// Creates [`PopupMessage::Placement`] message.
        PopupMessage:Placement => fn placement(Placement), layout: false
    );
    define_constructor!(
        /// Creates [`PopupMessage::AdjustPosition`] message.
        PopupMessage:AdjustPosition => fn adjust_position(), layout: true
    );
    define_constructor!(
        /// Creates [`PopupMessage::Owner`] message.
        PopupMessage:Owner => fn owner(Handle<UiNode>), layout: false
    );
    define_constructor!(
        /// Creates [`PopupMessage::RelayedMessage`] message.
        PopupMessage:RelayedMessage => fn relayed_message(UiMessage), layout: false
    );
}

/// Defines a method of popup placement.
#[derive(Copy, Clone, PartialEq, Debug, Visit, Reflect)]
pub enum Placement {
    /// A popup should be placed relative to given widget at the left top corner of the widget screen bounds.
    /// Widget handle could be [`Handle::NONE`], in this case the popup will be placed at the left top corner of the screen.
    LeftTop(Handle<UiNode>),

    /// A popup should be placed relative to given widget at the right top corner of the widget screen bounds.
    /// Widget handle could be [`Handle::NONE`], in this case the popup will be placed at the right top corner of the screen.
    RightTop(Handle<UiNode>),

    /// A popup should be placed relative to given widget at the center of the widget screen bounds.
    /// Widget handle could be [`Handle::NONE`], in this case the popup will be placed at the center of the screen.
    Center(Handle<UiNode>),

    /// A popup should be placed relative to given widget at the left bottom corner of the widget screen bounds.
    /// Widget handle could be [`Handle::NONE`], in this case the popup will be placed at the left bottom corner of the screen.
    LeftBottom(Handle<UiNode>),

    /// A popup should be placed relative to given widget at the right bottom corner of the widget screen bounds.
    /// Widget handle could be [`Handle::NONE`], in this case the popup will be placed at the right bottom corner of the screen.
    RightBottom(Handle<UiNode>),

    /// A popup should be placed at the cursor position. The widget handle could be either [`Handle::NONE`] or a handle of a
    /// widget that is directly behind the cursor.
    Cursor(Handle<UiNode>),

    /// A popup should be placed at given screen-space position.
    Position {
        /// Screen-space position.
        position: Vector2<f32>,

        /// A handle of the node that is located behind the given position. Could be [`Handle::NONE`] if there is nothing behind
        /// given position.
        target: Handle<UiNode>,
    },
}

impl Default for Placement {
    fn default() -> Self {
        Self::LeftTop(Default::default())
    }
}

impl Placement {
    /// Returns a handle of the node to which this placement corresponds to.
    pub fn target(&self) -> Handle<UiNode> {
        match self {
            Placement::LeftTop(target)
            | Placement::RightTop(target)
            | Placement::Center(target)
            | Placement::LeftBottom(target)
            | Placement::RightBottom(target)
            | Placement::Cursor(target)
            | Placement::Position { target, .. } => *target,
        }
    }
}

/// Popup is used to display other widgets in floating panel, that could lock input in self bounds.
///
/// ## How to create
///
/// A simple popup with a button could be created using the following code:
///
/// ```rust
/// # use fyrox_ui::{
/// #     button::ButtonBuilder, core::pool::Handle, popup::PopupBuilder, widget::WidgetBuilder,
/// #     BuildContext, UiNode,
/// # };
/// fn create_popup_with_button(ctx: &mut BuildContext) -> Handle<UiNode> {
///     PopupBuilder::new(WidgetBuilder::new())
///         .with_content(
///             ButtonBuilder::new(WidgetBuilder::new())
///                 .with_text("Click Me!")
///                 .build(ctx),
///         )
///         .build(ctx)
/// }
/// ```
///
/// Keep in mind, that the popup is closed by default. You need to open it explicitly by sending a [`PopupMessage::Open`] to it,
/// otherwise you won't see it:
///
/// ```rust
/// # use fyrox_ui::{
/// #     button::ButtonBuilder,
/// #     core::pool::Handle,
/// #     message::MessageDirection,
/// #     popup::{Placement, PopupBuilder, PopupMessage},
/// #     widget::WidgetBuilder,
/// #     UiNode, UserInterface,
/// # };
/// fn create_popup_with_button_and_open_it(ui: &mut UserInterface) -> Handle<UiNode> {
///     let popup = PopupBuilder::new(WidgetBuilder::new())
///         .with_content(
///             ButtonBuilder::new(WidgetBuilder::new())
///                 .with_text("Click Me!")
///                 .build(&mut ui.build_ctx()),
///         )
///         .build(&mut ui.build_ctx());
///
///     // Open the popup explicitly.
///     ui.send_message(PopupMessage::open(popup, MessageDirection::ToWidget));
///
///     popup
/// }
/// ```
///
/// ## Placement
///
/// Since popups are usually used to show useful context-specific information (like context menus, drop-down lists, etc.), they're usually
/// open above some other widget with specific alignment (right, left, center, etc.).
///
/// ```rust
/// # use fyrox_ui::{
/// #     button::ButtonBuilder,
/// #     core::pool::Handle,
/// #     message::MessageDirection,
/// #     popup::{Placement, PopupBuilder, PopupMessage},
/// #     widget::WidgetBuilder,
/// #     UiNode, UserInterface,
/// # };
/// fn create_popup_with_button_and_open_it(ui: &mut UserInterface) -> Handle<UiNode> {
///     let popup = PopupBuilder::new(WidgetBuilder::new())
///         .with_content(
///             ButtonBuilder::new(WidgetBuilder::new())
///                 .with_text("Click Me!")
///                 .build(&mut ui.build_ctx()),
///         )
///         // Set the placement. For simplicity it is just a cursor position with Handle::NONE as placement target.
///         .with_placement(Placement::Cursor(Handle::NONE))
///         .build(&mut ui.build_ctx());
///
///     // Open the popup explicitly at the current placement.
///     ui.send_message(PopupMessage::open(popup, MessageDirection::ToWidget));
///
///     popup
/// }
/// ```
///
/// The example uses [`Placement::Cursor`] with [`Handle::NONE`] placement target for simplicity reasons, however in
/// the real-world usages this handle must be a handle of some widget that is located under the popup. It is very
/// important to specify it correctly, otherwise you will lost the built-in ability to fetch the actual placement target.
/// For example, imagine that you're building your own custom [`crate::dropdown_list::DropdownList`] widget and the popup
/// is used to display content of the list. In this case you could specify the placement target like this:
///
/// ```rust
/// # use fyrox_ui::{
/// #     button::ButtonBuilder,
/// #     core::pool::Handle,
/// #     message::MessageDirection,
/// #     popup::{Placement, PopupBuilder, PopupMessage},
/// #     widget::WidgetBuilder,
/// #     UiNode, UserInterface,
/// # };
/// fn create_popup_with_button_and_open_it(
///     dropdown_list: Handle<UiNode>,
///     ui: &mut UserInterface,
/// ) -> Handle<UiNode> {
///     let popup = PopupBuilder::new(WidgetBuilder::new())
///         .with_content(
///             ButtonBuilder::new(WidgetBuilder::new())
///                 .with_text("Click Me!")
///                 .build(&mut ui.build_ctx()),
///         )
///         // Set the placement to the dropdown list.
///         .with_placement(Placement::LeftBottom(dropdown_list))
///         .build(&mut ui.build_ctx());
///
///     // Open the popup explicitly at the current placement.
///     ui.send_message(PopupMessage::open(popup, MessageDirection::ToWidget));
///
///     popup
/// }
/// ```
///
/// In this case, the popup will open at the left bottom corner of the dropdown list automatically. Placement target is also
/// useful to build context menus, especially for lists with multiple items. Each item in the list usually have the same context
/// menu, and this is ideal use case for popups, since the single context menu can be shared across multiple list items. To find
/// which item cause the context menu to open, catch [`PopupMessage::Placement`] and extract the node handle - this will be your
/// actual item.
///
/// ## Opening mode
///
/// By default, when you click outside of your popup it will automatically close. It is pretty common behaviour in the UI, you
/// can see it almost everytime you use context menus in various apps. There are cases when this behaviour is undesired and it
/// can be turned off:
///
/// ```rust
/// # use fyrox_ui::{
/// #     button::ButtonBuilder, core::pool::Handle, popup::PopupBuilder, widget::WidgetBuilder,
/// #     BuildContext, UiNode,
/// # };
/// fn create_popup_with_button(ctx: &mut BuildContext) -> Handle<UiNode> {
///     PopupBuilder::new(WidgetBuilder::new())
///         .with_content(
///             ButtonBuilder::new(WidgetBuilder::new())
///                 .with_text("Click Me!")
///                 .build(ctx),
///         )
///         // This forces the popup to stay open when clicked outside of its bounds
///         .stays_open(true)
///         .build(ctx)
/// }
/// ```
///
/// ## Smart placement
///
/// Popup widget can automatically adjust its position to always remain on screen, which is useful for tooltips, dropdown lists,
/// etc. To enable this option, use [`PopupBuilder::with_smart_placement`] with `true` as the first argument.
#[derive(Default, Clone, Visit, Debug, Reflect, ComponentProvider)]
pub struct Popup {
    /// Base widget of the popup.
    pub widget: Widget,
    /// Current placement of the popup.
    pub placement: InheritableVariable<Placement>,
    /// A flag, that defines whether the popup will stay open if a user click outside of its bounds.
    pub stays_open: InheritableVariable<bool>,
    /// A flag, that defines whether the popup is open or not.
    pub is_open: InheritableVariable<bool>,
    /// Current content of the popup.
    pub content: InheritableVariable<Handle<UiNode>>,
    /// Background widget of the popup. It is used as a container for the content.
    pub body: InheritableVariable<Handle<UiNode>>,
    /// Smart placement prevents the popup from going outside of the screen bounds. It is usually used for tooltips,
    /// dropdown lists, etc. to prevent the content from being outside of the screen.
    pub smart_placement: InheritableVariable<bool>,
    /// The destination for Event messages that relay messages from the children of this popup.
    pub owner: Handle<UiNode>,
}

crate::define_widget_deref!(Popup);

fn adjust_placement_position(
    node_screen_bounds: Rect<f32>,
    screen_size: Vector2<f32>,
) -> Vector2<f32> {
    let mut new_position = node_screen_bounds.position;
    let right_bottom = node_screen_bounds.right_bottom_corner();
    if right_bottom.x > screen_size.x {
        new_position.x -= right_bottom.x - screen_size.x;
    }
    if right_bottom.y > screen_size.y {
        new_position.y -= right_bottom.y - screen_size.y;
    }
    new_position
}

impl Popup {
    fn left_top_placement(&self, ui: &UserInterface, target: Handle<UiNode>) -> Vector2<f32> {
        ui.try_get(target)
            .map(|n| n.screen_position())
            .unwrap_or_default()
    }

    fn right_top_placement(&self, ui: &UserInterface, target: Handle<UiNode>) -> Vector2<f32> {
        ui.try_get(target)
            .map(|n| n.screen_position() + Vector2::new(n.actual_global_size().x, 0.0))
            .unwrap_or_else(|| {
                Vector2::new(ui.screen_size().x - self.widget.actual_global_size().x, 0.0)
            })
    }

    fn center_placement(&self, ui: &UserInterface, target: Handle<UiNode>) -> Vector2<f32> {
        ui.try_get(target)
            .map(|n| n.screen_position() + n.actual_global_size().scale(0.5))
            .unwrap_or_else(|| (ui.screen_size - self.widget.actual_global_size()).scale(0.5))
    }

    fn left_bottom_placement(&self, ui: &UserInterface, target: Handle<UiNode>) -> Vector2<f32> {
        ui.try_get(target)
            .map(|n| n.screen_position() + Vector2::new(0.0, n.actual_global_size().y))
            .unwrap_or_else(|| {
                Vector2::new(0.0, ui.screen_size().y - self.widget.actual_global_size().y)
            })
    }

    fn right_bottom_placement(&self, ui: &UserInterface, target: Handle<UiNode>) -> Vector2<f32> {
        ui.try_get(target)
            .map(|n| n.screen_position() + n.actual_global_size())
            .unwrap_or_else(|| ui.screen_size - self.widget.actual_global_size())
    }
}

uuid_provider!(Popup = "1c641540-59eb-4ccd-a090-2173dab02245");

impl Control for Popup {
    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::<PopupMessage>() {
            if message.destination() == self.handle() {
                match msg {
                    PopupMessage::Open => {
                        if !*self.is_open {
                            self.is_open.set_value_and_mark_modified(true);
                            ui.send_message(WidgetMessage::visibility(
                                self.handle(),
                                MessageDirection::ToWidget,
                                true,
                            ));
                            ui.push_picking_restriction(RestrictionEntry {
                                handle: self.handle(),
                                stop: false,
                            });
                            ui.send_message(WidgetMessage::topmost(
                                self.handle(),
                                MessageDirection::ToWidget,
                            ));
                            let position = match *self.placement {
                                Placement::LeftTop(target) => self.left_top_placement(ui, target),
                                Placement::RightTop(target) => self.right_top_placement(ui, target),
                                Placement::Center(target) => self.center_placement(ui, target),
                                Placement::LeftBottom(target) => {
                                    self.left_bottom_placement(ui, target)
                                }
                                Placement::RightBottom(target) => {
                                    self.right_bottom_placement(ui, target)
                                }
                                Placement::Cursor(_) => ui.cursor_position(),
                                Placement::Position { position, .. } => position,
                            };

                            ui.send_message(WidgetMessage::desired_position(
                                self.handle(),
                                MessageDirection::ToWidget,
                                ui.screen_to_root_canvas_space(position),
                            ));
                            ui.send_message(WidgetMessage::focus(
                                if self.content.is_some() {
                                    *self.content
                                } else {
                                    self.handle
                                },
                                MessageDirection::ToWidget,
                            ));
                            if *self.smart_placement {
                                ui.send_message(PopupMessage::adjust_position(
                                    self.handle,
                                    MessageDirection::ToWidget,
                                ));
                            }
                        }
                    }
                    PopupMessage::Close => {
                        if *self.is_open {
                            self.is_open.set_value_and_mark_modified(false);
                            ui.send_message(WidgetMessage::visibility(
                                self.handle(),
                                MessageDirection::ToWidget,
                                false,
                            ));
                            ui.remove_picking_restriction(self.handle());

                            if let Some(top) = ui.top_picking_restriction() {
                                ui.send_message(WidgetMessage::focus(
                                    top.handle,
                                    MessageDirection::ToWidget,
                                ));
                            }

                            if ui.captured_node() == self.handle() {
                                ui.release_mouse_capture();
                            }
                        }
                    }
                    PopupMessage::Content(content) => {
                        if self.content.is_some() {
                            ui.send_message(WidgetMessage::remove(
                                *self.content,
                                MessageDirection::ToWidget,
                            ));
                        }
                        self.content.set_value_and_mark_modified(*content);

                        ui.send_message(WidgetMessage::link(
                            *self.content,
                            MessageDirection::ToWidget,
                            *self.body,
                        ));
                    }
                    PopupMessage::Placement(placement) => {
                        self.placement.set_value_and_mark_modified(*placement);
                        self.invalidate_layout();
                    }
                    PopupMessage::AdjustPosition => {
                        let new_position =
                            adjust_placement_position(self.screen_bounds(), ui.screen_size());

                        if new_position != self.screen_position() {
                            ui.send_message(WidgetMessage::desired_position(
                                self.handle,
                                MessageDirection::ToWidget,
                                ui.screen_to_root_canvas_space(new_position),
                            ));
                        }
                    }
                    PopupMessage::Owner(owner) => {
                        self.owner = *owner;
                    }
                    PopupMessage::RelayedMessage(_) => (),
                }
            }
        } else if let Some(WidgetMessage::KeyDown(key)) = message.data() {
            if !message.handled() && *key == KeyCode::Escape {
                ui.send_message(PopupMessage::close(self.handle, MessageDirection::ToWidget));
                message.set_handled(true);
            }
        }
        if ui.is_valid_handle(self.owner) && !message.handled() {
            ui.send_message(PopupMessage::relayed_message(
                self.owner,
                MessageDirection::ToWidget,
                message.clone(),
            ));
        }
    }

    fn handle_os_event(
        &mut self,
        self_handle: Handle<UiNode>,
        ui: &mut UserInterface,
        event: &OsEvent,
    ) {
        if let OsEvent::MouseInput { state, .. } = event {
            if let Some(top_restriction) = ui.top_picking_restriction() {
                if *state == ButtonState::Pressed
                    && top_restriction.handle == self_handle
                    && *self.is_open
                {
                    let pos = ui.cursor_position();
                    if !self.widget.screen_bounds().contains(pos) && !*self.stays_open {
                        ui.send_message(PopupMessage::close(
                            self.handle(),
                            MessageDirection::ToWidget,
                        ));
                    }
                }
            }
        }
    }
}

/// Popup widget builder is used to create [`Popup`] widget instances and add them to the user interface.
pub struct PopupBuilder {
    widget_builder: WidgetBuilder,
    placement: Placement,
    stays_open: bool,
    content: Handle<UiNode>,
    smart_placement: bool,
    owner: Handle<UiNode>,
}

impl PopupBuilder {
    /// Creates new builder instance.
    pub fn new(widget_builder: WidgetBuilder) -> Self {
        Self {
            widget_builder,
            placement: Placement::Cursor(Default::default()),
            stays_open: false,
            content: Default::default(),
            smart_placement: true,
            owner: Default::default(),
        }
    }

    /// Sets the desired popup placement.
    pub fn with_placement(mut self, placement: Placement) -> Self {
        self.placement = placement;
        self
    }

    /// Enables or disables smart placement.
    pub fn with_smart_placement(mut self, smart_placement: bool) -> Self {
        self.smart_placement = smart_placement;
        self
    }

    /// Defines whether to keep the popup open when user clicks outside of its content or not.
    pub fn stays_open(mut self, value: bool) -> Self {
        self.stays_open = value;
        self
    }

    /// Sets the content of the popup.
    pub fn with_content(mut self, content: Handle<UiNode>) -> Self {
        self.content = content;
        self
    }

    /// Sets the desired owner of the popup, to which the popup will relay its own messages.
    pub fn with_owner(mut self, owner: Handle<UiNode>) -> Self {
        self.owner = owner;
        self
    }

    /// Builds the popup widget, but does not add it to the user interface. Could be useful if you're making your
    /// own derived version of the popup.
    pub fn build_popup(self, ctx: &mut BuildContext) -> Popup {
        let body = BorderBuilder::new(
            WidgetBuilder::new()
                .with_background(BRUSH_PRIMARY)
                .with_foreground(BRUSH_DARKEST)
                .with_child(self.content),
        )
        .with_stroke_thickness(Thickness::uniform(1.0))
        .build(ctx);

        Popup {
            widget: self
                .widget_builder
                .with_child(body)
                .with_visibility(false)
                .with_handle_os_events(true)
                .build(),
            placement: self.placement.into(),
            stays_open: self.stays_open.into(),
            is_open: false.into(),
            content: self.content.into(),
            smart_placement: self.smart_placement.into(),
            body: body.into(),
            owner: self.owner,
        }
    }

    /// Finishes building the [`Popup`] instance and adds to the user interface and returns its handle.
    pub fn build(self, ctx: &mut BuildContext) -> Handle<UiNode> {
        let popup = self.build_popup(ctx);
        ctx.add_node(UiNode::new(popup))
    }
}