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
//! Layout, draw and interact with gui widgets.
//!
//! Requires the `gui` feature flag.

pub mod button;
pub mod label;

use std::{any::Any, collections::HashMap};

use miette::{Context, IntoDiagnostic, Result};
use taffy::{prelude::Size, style::Style, style_helpers::TaffyMaxContent, NodeId, TaffyTree};
use vek::{Extent2, Vec2};

/// Allow calling function on widgets in a simple way.
pub trait Widget {
    /// Update the widget layout position, defines how it must be drawn.
    fn update_layout(&mut self, location: Vec2<f64>, size: Extent2<f64>);

    /// Convert to [`Any`] so we can convert it back to the original type.
    fn as_any(&self) -> &dyn Any;

    /// Convert to mutable [`Any`] so we can convert it back to the original type.
    fn as_any_mut(&mut self) -> &mut dyn Any;
}

/// Reference to a widget after it has been constructed.
///
/// Can be passed to [`Gui::widget`] and [`Gui::widget_mut`] to get the original widget back in update and render functions.
pub trait WidgetRef: Into<NodeId> + From<NodeId> + Copy {
    /// The original widget that can be returned from this ref.
    type Widget: Widget;
}

/// Construct a GUI from a tree of widgets defined by the layout.
pub struct GuiBuilder {
    /// References to all widgets, so they can be updated.
    widgets: HashMap<NodeId, Box<dyn Widget>>,
    /// Taffy layout, will update the position and sizes of the widgets.
    layout: TaffyTree<()>,
    /// Root node.
    root: NodeId,
}

impl GuiBuilder {
    /// Start creating a GUI.
    ///
    /// # Arguments
    ///
    /// * `root_layout` - Layout for the root node. Size will be automatically set by the [`Widget::update_layout`] trait call.
    pub fn new(root_layout: Style) -> Self {
        let widgets = HashMap::new();
        let mut layout = TaffyTree::new();
        // This shouldn't fail
        let root = layout
            .new_leaf(root_layout)
            .expect("Error adding root node to layout");

        Self {
            widgets,
            layout,
            root,
        }
    }

    /// Register a widget.
    ///
    /// This will automatically update the widget size and location when it changes.
    /// The generic type passed must be reference type of the [`Widget`] passed, usually this is just the widget name with a `Ref` postfix.
    ///
    /// # Arguments
    ///
    /// * `widget` - Widget implementing the [`Widget`] trait.
    /// * `layout` - How the [`Widget`] behaves as a layout.
    /// * `parent` - Parent Taffy node the widget will be a child of.
    ///
    /// # Returns
    ///
    /// A Taffy node type that can be used to create a hierarchy of nodes.
    /// This can be used in the update or draw loop to get a reference to the widget itself.
    pub fn add_widget<W>(
        &mut self,
        widget: W::Widget,
        layout: Style,
        parent: impl Into<NodeId>,
    ) -> Result<W>
    where
        W: WidgetRef + 'static,
    {
        // Create a new Taffy layout node
        let node = self
            .layout
            .new_leaf(layout)
            .into_diagnostic()
            .wrap_err("Error adding new leaf to layout tree")?;

        // Insert the widget
        self.widgets.insert(node, Box::new(widget));

        // Attach the child to the parent
        self.layout
            .add_child(parent.into(), node)
            .into_diagnostic()
            .wrap_err("Error adding child layout node to parent")?;

        Ok(W::from(node))
    }

    /// Build the GUI.
    pub fn build(self) -> Gui {
        let Self {
            root,
            widgets,
            layout,
        } = self;

        Gui {
            widgets,
            layout,
            root,
        }
    }

    /// The root node so children can be added to it.
    pub fn root(&self) -> NodeId {
        self.root
    }
}

/// A GUI with a tree of widgets.
///
/// The GUI uses the [`taffy`](https://docs.rs/taffy) crate for layouts, where the size is defined as buffer pixels.
pub struct Gui {
    /// References to all widgets, so they can be updated.
    widgets: HashMap<NodeId, Box<dyn Widget>>,
    /// Taffy layout, will update the position and sizes of the widgets.
    layout: TaffyTree<()>,
    /// Root layout node.
    root: NodeId,
}

impl Gui {
    /// Get a reference to the boxed widget based on the node.
    pub fn widget<W>(&self, widget_node: W) -> Result<&W::Widget>
    where
        W: WidgetRef + 'static,
    {
        self.widgets
            .get(&widget_node.into())
            .ok_or_else(|| {
                miette::miette!(
            "Error getting the widget based on the node, are you sure you added it to the builder?"
        )
            })
            .and_then(|boxed| {
                boxed.as_any().downcast_ref::<W::Widget>().ok_or_else(|| {
                    miette::miette!(
                        "Error casting widget to original type, did you use the proper type?"
                    )
                })
            })
    }

    /// Get a mutable reference to the boxed widget based on the node.
    pub fn widget_mut<W>(&mut self, widget_node: W) -> Result<&mut W::Widget>
    where
        W: WidgetRef + 'static,
    {
        self.widgets
            .get_mut(&widget_node.into())
            .ok_or_else(|| {
                miette::miette!(
            "Error getting the widget based on the node, are you sure you added it to the builder?"
        )
            })
            .and_then(|boxed| {
                boxed
                    .as_any_mut()
                    .downcast_mut::<W::Widget>()
                    .ok_or_else(|| {
                        miette::miette!(
                            "Error casting widget to original type, did you use the proper type?"
                        )
                    })
            })
    }
}

impl Widget for Gui {
    fn update_layout(&mut self, location: Vec2<f64>, size: Extent2<f64>) {
        // Update root node layout
        let mut root_style = self.layout.style(self.root).unwrap().clone();
        root_style.size = Size::from_lengths(size.w as f32, size.h as f32);
        self.layout.set_style(self.root, root_style).unwrap();

        // Compute the new layout
        self.layout
            .compute_layout(self.root, Size::MAX_CONTENT)
            .expect("Computing layout failed");

        // Update all child widget layouts
        self.widgets
            .iter_mut()
            // We need to calculate the location recursively
            .map(|(node, widget)| {
                // Find the absolute location of this node by traversing the node tree
                let layout = self.layout.layout(*node).unwrap().location;
                let mut widget_location = Vec2::new(layout.x as f64, layout.y as f64);

                // Offset by the root offset
                widget_location += location;

                let mut previous_node = *node;
                while let Some(parent) = self.layout.parent(previous_node) {
                    let layout = self.layout.layout(parent).unwrap().location;
                    widget_location.x += layout.x as f64;
                    widget_location.y += layout.y as f64;

                    previous_node = parent;
                }

                (node, widget, widget_location)
            })
            // Update the layout of all widgets
            .for_each(|(node, widget, location)| {
                // The size is stored
                let size = self
                    .layout
                    .layout(*node)
                    .expect("Could not get layout for widget node")
                    .size;

                // Can't use iter_mut above because of mutable borrow
                widget.update_layout(location, Extent2::new(size.width, size.height).as_());
            });
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}