fyrox_ui/screen.rs
1// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in all
11// copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21//! Screen is a widget that always has the size of the screen of the UI in which it is used. See
22//! docs for [`Screen`] for more info and usage examples.
23
24#![warn(missing_docs)]
25
26use crate::{
27 core::{
28 algebra::Vector2, math::Rect, pool::Handle, reflect::prelude::*, type_traits::prelude::*,
29 uuid_provider, visitor::prelude::*,
30 },
31 message::UiMessage,
32 widget::{Widget, WidgetBuilder},
33 BuildContext, Control, UiNode, UserInterface,
34};
35use fyrox_graph::constructor::{ConstructorProvider, GraphNodeConstructor};
36use std::{
37 cell::Cell,
38 ops::{Deref, DerefMut},
39};
40
41/// Screen is a widget that always has the size of the screen of the UI in which it is used. It is
42/// main use case is to provide automatic layout functionality, that will always provide screen size
43/// to its children widgets. This is needed, because the root node of any UI is [`crate::canvas::Canvas`]
44/// which provides infinite bounds as a layout constraint, thus making it impossible for automatic
45/// fitting to the current screen size. For example, Screen widget could be used as a root node for
46/// [`crate::grid::Grid`] widget - in this case the grid instance will always have the size of the
47/// screen and will automatically shrink or expand when the screen size changes. It is ideal choice if
48/// you want to have some widgets always centered on screen (for example - crosshair, main menu of
49/// your game, etc.).
50///
51/// ## Example
52///
53/// The following examples creates a simple main menu of a game with just two buttons. The buttons
54/// will always be centered in the current screen bounds.
55///
56/// ```rust
57/// use fyrox_ui::{
58/// core::pool::Handle,
59/// button::ButtonBuilder,
60/// grid::{Column, GridBuilder, Row},
61/// screen::ScreenBuilder,
62/// stack_panel::StackPanelBuilder,
63/// widget::WidgetBuilder,
64/// BuildContext, UiNode,
65/// };
66///
67/// fn create_always_centered_game_menu(ctx: &mut BuildContext) -> Handle<UiNode> {
68/// // Screen widget will provide current screen size to its Grid widget as a layout constraint,
69/// // thus making it fit to the current screen bounds.
70/// ScreenBuilder::new(
71/// WidgetBuilder::new().with_child(
72/// GridBuilder::new(
73/// WidgetBuilder::new()
74/// .with_width(300.0)
75/// .with_height(400.0)
76/// .with_child(
77/// // Buttons will be stacked one on top of another.
78/// StackPanelBuilder::new(
79/// WidgetBuilder::new()
80/// .on_row(1)
81/// .on_column(1)
82/// .with_child(
83/// ButtonBuilder::new(WidgetBuilder::new())
84/// .with_text("New Game")
85/// .build(ctx),
86/// )
87/// .with_child(
88/// ButtonBuilder::new(WidgetBuilder::new())
89/// .with_text("Exit")
90/// .build(ctx),
91/// ),
92/// )
93/// .build(ctx),
94/// ),
95/// )
96/// // Split the grid into 3 rows and 3 columns. The center cell contain the stack panel
97/// // instance, that basically stacks main menu buttons one on top of another. The center
98/// // cell will also be always centered in screen bounds.
99/// .add_row(Row::stretch())
100/// .add_row(Row::auto())
101/// .add_row(Row::stretch())
102/// .add_column(Column::stretch())
103/// .add_column(Column::auto())
104/// .add_column(Column::stretch())
105/// .build(ctx),
106/// ),
107/// )
108/// .build(ctx)
109/// }
110/// ```
111#[derive(Default, Clone, Visit, Reflect, Debug, ComponentProvider)]
112pub struct Screen {
113 /// Base widget of the screen.
114 pub widget: Widget,
115 /// Last screen size.
116 #[visit(skip)]
117 #[reflect(hidden)]
118 pub last_screen_size: Cell<Vector2<f32>>,
119}
120
121impl ConstructorProvider<UiNode, UserInterface> for Screen {
122 fn constructor() -> GraphNodeConstructor<UiNode, UserInterface> {
123 GraphNodeConstructor::new::<Self>()
124 .with_variant("Screen", |ui| {
125 ScreenBuilder::new(WidgetBuilder::new().with_name("Screen"))
126 .build(&mut ui.build_ctx())
127 .into()
128 })
129 .with_group("Layout")
130 }
131}
132
133crate::define_widget_deref!(Screen);
134
135uuid_provider!(Screen = "3bc7649f-a1ba-49be-bc4e-e0624654e40c");
136
137impl Control for Screen {
138 fn measure_override(&self, ui: &UserInterface, _available_size: Vector2<f32>) -> Vector2<f32> {
139 for &child in self.children.iter() {
140 ui.measure_node(child, ui.screen_size());
141 }
142
143 ui.screen_size()
144 }
145
146 fn arrange_override(&self, ui: &UserInterface, _final_size: Vector2<f32>) -> Vector2<f32> {
147 let final_rect = Rect::new(0.0, 0.0, ui.screen_size().x, ui.screen_size().y);
148
149 for &child in self.children.iter() {
150 ui.arrange_node(child, &final_rect);
151 }
152
153 ui.screen_size()
154 }
155
156 fn update(&mut self, _dt: f32, ui: &mut UserInterface) {
157 if self.last_screen_size.get() != ui.screen_size {
158 self.invalidate_layout();
159 self.last_screen_size.set(ui.screen_size);
160 }
161 }
162
163 fn handle_routed_message(&mut self, ui: &mut UserInterface, message: &mut UiMessage) {
164 self.widget.handle_routed_message(ui, message);
165 }
166}
167
168/// Screen builder creates instances of [`Screen`] widgets and adds them to the user interface.
169pub struct ScreenBuilder {
170 widget_builder: WidgetBuilder,
171}
172
173impl ScreenBuilder {
174 /// Creates a new instance of the screen builder.
175 pub fn new(widget_builder: WidgetBuilder) -> Self {
176 Self { widget_builder }
177 }
178
179 /// Finishes building a [`Screen`] widget instance and adds it to the user interface, returning a
180 /// handle to the instance.
181 pub fn build(self, ctx: &mut BuildContext) -> Handle<UiNode> {
182 let screen = Screen {
183 widget: self.widget_builder.with_need_update(true).build(ctx),
184 last_screen_size: Cell::new(Default::default()),
185 };
186 ctx.add_node(UiNode::new(screen))
187 }
188}
189
190#[cfg(test)]
191mod test {
192 use crate::screen::ScreenBuilder;
193 use crate::{test::test_widget_deletion, widget::WidgetBuilder};
194
195 #[test]
196 fn test_deletion() {
197 test_widget_deletion(|ctx| ScreenBuilder::new(WidgetBuilder::new()).build(ctx));
198 }
199}