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
//! Wrap panel is used to stack children widgets either in vertical or horizontal direction with overflow. See [`WrapPanel`]
//! docs for more info and usage examples.

#![warn(missing_docs)]
#![allow(clippy::reversed_empty_ranges)]

use crate::{
    core::{algebra::Vector2, math::Rect, pool::Handle},
    define_constructor,
    message::{MessageDirection, UiMessage},
    widget::{Widget, WidgetBuilder},
    BuildContext, Control, Orientation, UiNode, UserInterface,
};
use std::{
    any::{Any, TypeId},
    cell::RefCell,
    ops::{Deref, DerefMut, Range},
};

/// A set of possible [`WrapPanel`] widget messages.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WrapPanelMessage {
    /// The message is used to change orientation of the wrap panel.
    Orientation(Orientation),
}

impl WrapPanelMessage {
    define_constructor!(
        /// Creates [`WrapPanelMessage::Orientation`] message.
        WrapPanelMessage:Orientation => fn orientation(Orientation), layout: false
    );
}

/// Wrap panel is used to stack children widgets either in vertical or horizontal direction with overflow - every widget
/// that does not have enough space on current line, will automatically be placed on the next line (either vertical or
/// horizontal, depending on the orientation).
///
/// ## How to create
///
/// Use `WrapPanelBuilder` to create new wrap panel instance:
///
/// ```rust,no_run
/// # use fyrox_ui::{
/// #     core::pool::Handle,
/// #     widget::WidgetBuilder, wrap_panel::WrapPanelBuilder, BuildContext, Orientation, UiNode,
/// # };
/// #
/// fn create_wrap_panel(ctx: &mut BuildContext) -> Handle<UiNode> {
///     WrapPanelBuilder::new(WidgetBuilder::new())
///         .with_orientation(Orientation::Horizontal)
///         .build(ctx)
/// }
/// ```
///
/// All widgets, that needs to be arranged, should be direct children of the wrap panel. Use [`WidgetBuilder::with_children`]
/// or [`WidgetBuilder::with_child`] to add children nodes.
///
/// ## Orientation
///
/// Wrap panel can stack your widgets either in vertical or horizontal direction. Use `.with_orientation` while building
/// the panel to switch orientation to desired.
#[derive(Clone)]
pub struct WrapPanel {
    /// Base widget of the wrap panel.
    pub widget: Widget,
    /// Current orientation of the wrap panel.
    pub orientation: Orientation,
    /// Internal lines storage.
    pub lines: RefCell<Vec<Line>>,
}

crate::define_widget_deref!(WrapPanel);

/// Represents a single line (either vertical or horizontal) with arranged widgets.
#[derive(Clone)]
pub struct Line {
    /// Indices of the children widgets that belongs to this line.
    pub children: Range<usize>,
    /// Bounds of this line.
    pub bounds: Rect<f32>,
}

impl Default for Line {
    fn default() -> Self {
        Self {
            children: 0..0,
            bounds: Default::default(),
        }
    }
}

impl Control for WrapPanel {
    fn query_component(&self, type_id: TypeId) -> Option<&dyn Any> {
        if type_id == TypeId::of::<Self>() {
            Some(self)
        } else {
            None
        }
    }

    fn measure_override(&self, ui: &UserInterface, available_size: Vector2<f32>) -> Vector2<f32> {
        let mut measured_size: Vector2<f32> = Vector2::default();
        let mut line_size = Vector2::default();
        for child_handle in self.widget.children() {
            let child = ui.node(*child_handle);
            ui.measure_node(*child_handle, available_size);
            let desired = child.desired_size();
            match self.orientation {
                Orientation::Vertical => {
                    if line_size.y + desired.y > available_size.y {
                        // Commit column.
                        measured_size.y = measured_size.y.max(line_size.y);
                        measured_size.x += line_size.x;
                        line_size = Vector2::default();
                    }
                    line_size.x = line_size.x.max(desired.x);
                    line_size.y += desired.y;
                }
                Orientation::Horizontal => {
                    if line_size.x + desired.x > available_size.x {
                        // Commit row.
                        measured_size.x = measured_size.x.max(line_size.x);
                        measured_size.y += line_size.y;
                        line_size = Vector2::default();
                    }
                    line_size.x += desired.x;
                    line_size.y = line_size.y.max(desired.y);
                }
            }
        }

        // Commit rest.
        match self.orientation {
            Orientation::Vertical => {
                measured_size.y = measured_size.y.max(line_size.y);
                measured_size.x += line_size.x;
            }
            Orientation::Horizontal => {
                measured_size.x = measured_size.x.max(line_size.x);
                measured_size.y += line_size.y;
            }
        }

        measured_size
    }

    fn arrange_override(&self, ui: &UserInterface, final_size: Vector2<f32>) -> Vector2<f32> {
        // First pass - arrange lines.
        let mut lines = self.lines.borrow_mut();
        lines.clear();
        let mut line = Line::default();
        for child_handle in self.widget.children() {
            let child = ui.node(*child_handle);
            let desired = child.desired_size();
            match self.orientation {
                Orientation::Vertical => {
                    if line.bounds.h() + desired.y > final_size.y {
                        // Commit column.
                        lines.push(line.clone());
                        // Advance column.
                        line.bounds.position.x += line.bounds.w();
                        line.bounds.position.y = 0.0;
                        line.bounds.size.x = desired.x;
                        line.bounds.size.y = desired.y;
                        // Reset children.
                        line.children.start = line.children.end;
                        line.children.end = line.children.start + 1;
                    } else {
                        line.bounds.size.y += desired.y;
                        line.bounds.size.x = line.bounds.w().max(desired.x);
                        line.children.end += 1;
                    }
                }
                Orientation::Horizontal => {
                    if line.bounds.w() + desired.x > final_size.x {
                        // Commit row.
                        lines.push(line.clone());
                        // Advance row.
                        line.bounds.position.x = 0.0;
                        line.bounds.position.y += line.bounds.h();
                        line.bounds.size.x = desired.x;
                        line.bounds.size.y = desired.y;
                        // Reset children.
                        line.children.start = line.children.end;
                        line.children.end = line.children.start + 1;
                    } else {
                        line.bounds.size.x += desired.x;
                        line.bounds.size.y = line.bounds.h().max(desired.y);
                        line.children.end += 1;
                    }
                }
            }
        }

        // Commit rest.
        lines.push(line);

        // Second pass - arrange children of lines.
        let mut full_size = Vector2::default();
        for line in lines.iter() {
            let mut cursor = line.bounds.position;
            for child_index in line.children.clone() {
                let child_handle = self.children()[child_index];
                let child = ui.node(child_handle);
                let desired = child.desired_size();
                match self.orientation {
                    Orientation::Vertical => {
                        let child_bounds =
                            Rect::new(line.bounds.x(), cursor.y, line.bounds.w(), desired.y);
                        ui.arrange_node(child_handle, &child_bounds);
                        cursor.y += desired.y;
                    }
                    Orientation::Horizontal => {
                        let child_bounds =
                            Rect::new(cursor.x, line.bounds.y(), desired.x, line.bounds.h());
                        ui.arrange_node(child_handle, &child_bounds);
                        cursor.x += desired.x;
                    }
                }
            }
            match self.orientation {
                Orientation::Vertical => {
                    full_size.x += line.bounds.w();
                    full_size.y = final_size.y.max(line.bounds.h());
                }
                Orientation::Horizontal => {
                    full_size.x = final_size.x.max(line.bounds.w());
                    full_size.y += line.bounds.h();
                }
            }
        }

        full_size
    }

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

        if message.destination() == self.handle && message.direction() == MessageDirection::ToWidget
        {
            if let Some(WrapPanelMessage::Orientation(orientation)) = message.data() {
                if *orientation != self.orientation {
                    self.orientation = *orientation;
                    self.invalidate_layout();
                }
            }
        }
    }
}

/// Wrap panel builder creates [`WrapPanel`] widget and adds it to the user interface.
pub struct WrapPanelBuilder {
    widget_builder: WidgetBuilder,
    orientation: Option<Orientation>,
}

impl WrapPanelBuilder {
    /// Creates a new wrap panel builder.
    pub fn new(widget_builder: WidgetBuilder) -> Self {
        Self {
            widget_builder,
            orientation: None,
        }
    }

    /// Sets the desired orientation of the wrap panel.
    pub fn with_orientation(mut self, orientation: Orientation) -> Self {
        self.orientation = Some(orientation);
        self
    }

    /// Finishes wrap panel building and returns its instance.
    pub fn build_node(self) -> UiNode {
        let stack_panel = WrapPanel {
            widget: self.widget_builder.build(),
            orientation: self.orientation.unwrap_or(Orientation::Vertical),
            lines: Default::default(),
        };

        UiNode::new(stack_panel)
    }

    /// Finishes wrap panel building, adds it to the user interface and returns its handle.
    pub fn build(self, ui: &mut BuildContext) -> Handle<UiNode> {
        ui.add_node(self.build_node())
    }
}