fyrox_ui/canvas.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//! Canvas widget allows its children to have an arbitrary position on an imaginable infinite plane, it also
22//! gives the children constraints of infinite size, which forces them to take all the desired size. See
23//! [`Canvas`] docs for more info and usage examples.
24
25#![warn(missing_docs)]
26
27use crate::{
28 core::{
29 algebra::Vector2, math::Rect, pool::Handle, reflect::prelude::*, type_traits::prelude::*,
30 visitor::prelude::*,
31 },
32 message::UiMessage,
33 widget::{Widget, WidgetBuilder},
34 BuildContext, Control, UiNode, UserInterface,
35};
36use fyrox_graph::constructor::{ConstructorProvider, GraphNodeConstructor};
37use std::ops::{Deref, DerefMut};
38
39/// Canvas widget allows its children to have an arbitrary position on an imaginable infinite plane, it also
40/// gives the children constraints of infinite size, which forces them to take all the desired size. This widget
41/// could be used when you need to have an ability to put widgets at arbitrary positions. Canvas widget is the
42/// root widget of the widget hierarchy used in `fyrox-ui`.
43///
44/// ## Examples
45///
46/// A instance of [`Canvas`] widget can be created using [`CanvasBuilder`] with a set of children widgets provided
47/// to [`WidgetBuilder`]:
48///
49/// ```rust
50/// # use fyrox_ui::{
51/// # button::ButtonBuilder, canvas::CanvasBuilder, core::pool::Handle, text::TextBuilder,
52/// # widget::WidgetBuilder, BuildContext, UiNode,
53/// # };
54/// #
55/// fn create_canvas(ctx: &mut BuildContext) -> Handle<UiNode> {
56/// CanvasBuilder::new(
57/// WidgetBuilder::new()
58/// .with_child(
59/// ButtonBuilder::new(WidgetBuilder::new())
60/// .with_text("Click me!")
61/// .build(ctx),
62/// )
63/// .with_child(
64/// TextBuilder::new(WidgetBuilder::new())
65/// .with_text("Some text")
66/// .build(ctx),
67/// ),
68/// )
69/// .build(ctx)
70/// }
71/// ```
72#[derive(Default, Clone, Visit, Reflect, Debug, TypeUuidProvider, ComponentProvider)]
73#[type_uuid(id = "6b843a36-53da-467b-b85e-2380fe891ca1")]
74pub struct Canvas {
75 /// Base widget of the canvas.
76 pub widget: Widget,
77}
78
79impl ConstructorProvider<UiNode, UserInterface> for Canvas {
80 fn constructor() -> GraphNodeConstructor<UiNode, UserInterface> {
81 GraphNodeConstructor::new::<Self>()
82 .with_variant("Canvas", |ui| {
83 CanvasBuilder::new(WidgetBuilder::new().with_name("Canvas"))
84 .build(&mut ui.build_ctx())
85 .into()
86 })
87 .with_group("Layout")
88 }
89}
90
91crate::define_widget_deref!(Canvas);
92
93impl Control for Canvas {
94 fn measure_override(&self, ui: &UserInterface, _available_size: Vector2<f32>) -> Vector2<f32> {
95 let size_for_child = Vector2::new(f32::INFINITY, f32::INFINITY);
96
97 for child_handle in self.widget.children() {
98 ui.measure_node(*child_handle, size_for_child);
99 }
100
101 Vector2::default()
102 }
103
104 fn arrange_override(&self, ui: &UserInterface, final_size: Vector2<f32>) -> Vector2<f32> {
105 for &child_handle in self.widget.children() {
106 let child = ui.nodes.borrow(child_handle);
107 ui.arrange_node(
108 child_handle,
109 &Rect::new(
110 child.desired_local_position().x,
111 child.desired_local_position().y,
112 child.desired_size().x,
113 child.desired_size().y,
114 ),
115 );
116 }
117
118 final_size
119 }
120
121 fn handle_routed_message(&mut self, ui: &mut UserInterface, message: &mut UiMessage) {
122 self.widget.handle_routed_message(ui, message);
123 }
124}
125
126/// Canvas builder creates new [`Canvas`] widget instances and adds them to the user interface.
127pub struct CanvasBuilder {
128 widget_builder: WidgetBuilder,
129}
130
131impl CanvasBuilder {
132 /// Creates new builder instance.
133 pub fn new(widget_builder: WidgetBuilder) -> Self {
134 Self { widget_builder }
135 }
136
137 /// Finishes canvas widget building and adds the instance to the user interface and returns its handle.
138 pub fn build(self, ctx: &mut BuildContext) -> Handle<UiNode> {
139 let canvas = Canvas {
140 widget: self.widget_builder.build(ctx),
141 };
142 ctx.add_node(UiNode::new(canvas))
143 }
144}
145
146#[cfg(test)]
147mod test {
148 use crate::canvas::CanvasBuilder;
149 use crate::{test::test_widget_deletion, widget::WidgetBuilder};
150
151 #[test]
152 fn test_deletion() {
153 test_widget_deletion(|ctx| CanvasBuilder::new(WidgetBuilder::new()).build(ctx));
154 }
155}