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
use std::{
    ops::{
        DerefMut,
        Deref,
    },
    rc::Rc,
};
use crate::{
    brush::Brush,
    border::BorderBuilder,
    popup::{PopupBuilder, Placement},
    message::{
        UiMessageData,
        WidgetMessage,
        PopupMessage,
        UiMessage,
        OsEvent,
        ButtonState,
        MenuMessage,
        MenuItemMessage,
    },
    stack_panel::StackPanelBuilder,
    node::UINode,
    Control,
    Orientation,
    widget::{Widget, WidgetBuilder},
    core::{
        pool::Handle,
        math::vec2::Vec2,
        color::Color,
    },
    VerticalAlignment,
    HorizontalAlignment,
    Thickness,
    grid::{GridBuilder, Row, Column},
    text::TextBuilder,
    BuildContext,
    UserInterface
};

pub struct Menu<M: 'static, C: 'static + Control<M, C>> {
    widget: Widget<M, C>,
    active: bool,
}

impl<M: 'static, C: 'static + Control<M, C>> Deref for Menu<M, C> {
    type Target = Widget<M, C>;

    fn deref(&self) -> &Self::Target {
        &self.widget
    }
}

impl<M: 'static, C: 'static + Control<M, C>> DerefMut for Menu<M, C> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.widget
    }
}

impl<M: 'static, C: 'static + Control<M, C>> Clone for Menu<M, C> {
    fn clone(&self) -> Self {
        Self {
            widget: self.widget.raw_copy(),
            active: self.active,
        }
    }
}

impl<M: 'static, C: 'static + Control<M, C>> Control<M, C> for Menu<M, C> {
    fn raw_copy(&self) -> UINode<M, C> {
        UINode::Menu(self.clone())
    }

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

        if let UiMessageData::Menu(msg) = &message.data {
            match msg {
                MenuMessage::Activate => {
                    if !self.active {
                        ui.push_picking_restriction(self.handle());
                        self.active = true;
                    }
                }
                MenuMessage::Deactivate => {
                    if self.active {
                        self.active = false;
                        ui.remove_picking_restriction(self.handle());

                        // Close descendant menu items.
                        let mut stack = self.children().to_vec();
                        while let Some(handle) = stack.pop() {
                            let node = ui.node(handle);
                            if let UINode::MenuItem(item) = node {
                                ui.send_message(UiMessage {
                                    handled: false,
                                    data: UiMessageData::MenuItem(MenuItemMessage::Close),
                                    destination: handle,
                                });
                                // We have to search in popup content too because menu shows its content
                                // in popup and content could be another menu item.
                                stack.push(item.popup);
                            }
                            // Continue depth search.
                            stack.extend_from_slice(node.children());
                        }
                    }
                }
            }
        }
    }

    fn handle_os_event(&mut self, _self_handle: Handle<UINode<M, C>>, ui: &mut UserInterface<M, C>, event: &OsEvent) {
        // Handle menu items close by clicking outside of menu item. We using
        // raw event here because we need to know the fact that mouse was clicked
        // and we do not care which element was clicked so we'll get here in any
        // case.
        if let OsEvent::MouseInput { state, .. } = event {
            if *state == ButtonState::Pressed && self.active {
                // TODO: Make picking more accurate - right now it works only with rects.
                let pos = ui.cursor_position();
                if !self.widget.screen_bounds().contains(pos.x, pos.y) {
                    // Also check if we clicked inside some descendant menu item - in this
                    // case we don't need to close menu.
                    let mut any_picked = false;
                    let mut stack = self.children().to_vec();
                    'depth_search: while let Some(handle) = stack.pop() {
                        let node = ui.node(handle);
                        if let UINode::MenuItem(item) = node {
                            if ui.node(item.popup).screen_bounds().contains(pos.x, pos.y) {
                                // Once we found that we clicked inside some descendant menu item
                                // we can immediately stop search - we don't want to close menu
                                // items popups in this case and can safely skip all stuff below.
                                any_picked = true;
                                break 'depth_search;
                            }
                            // We have to search in popup content too because menu shows its content
                            // in popup and content could be another menu item.
                            stack.push(item.popup);
                        }
                        // Continue depth search.
                        stack.extend_from_slice(node.children());
                    }

                    if !any_picked {
                        ui.send_message(UiMessage {
                            handled: false,
                            data: UiMessageData::Menu(MenuMessage::Deactivate),
                            destination: self.handle(),
                        });
                    }
                }
            }
        }
    }
}

#[derive(Copy, Clone, PartialOrd, PartialEq, Hash)]
enum MenuItemPlacement {
    Bottom,
    Right,
}

pub struct MenuItem<M: 'static, C: 'static + Control<M, C>> {
    widget: Widget<M, C>,
    items: Vec<Handle<UINode<M, C>>>,
    popup: Handle<UINode<M, C>>,
    back: Handle<UINode<M, C>>,
    placement: MenuItemPlacement,
}

impl<M: 'static, C: 'static + Control<M, C>> Deref for MenuItem<M, C> {
    type Target = Widget<M, C>;

    fn deref(&self) -> &Self::Target {
        &self.widget
    }
}

impl<M: 'static, C: 'static + Control<M, C>> DerefMut for MenuItem<M, C> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.widget
    }
}

impl<M: 'static, C: 'static + Control<M, C>> Clone for MenuItem<M, C> {
    fn clone(&self) -> Self {
        Self {
            widget: self.widget.raw_copy(),
            items: self.items.clone(),
            popup: self.popup,
            back: self.back,
            placement: self.placement,
        }
    }
}

// MenuItem uses popup to show its content, popup can be top-most only if it is
// direct child of root canvas of UI. This fact adds some complications to search
// of parent menu - we can't just traverse the tree because popup is not a child
// of menu item, instead we trying to fetch handle to parent menu item from popup's
// user data and continue up-search until we find menu.
fn find_menu<M: 'static, C: 'static + Control<M, C>>(from: Handle<UINode<M, C>>, ui: &UserInterface<M, C>) -> Handle<UINode<M, C>> {
    let mut handle = from;
    loop {
        let popup = ui.find_by_criteria_up(handle, |n| {
            if let UINode::Popup(_) = n { true } else { false }
        });
        if popup.is_none() {
            // Maybe we have Menu as parent for MenuItem.
            return ui.find_by_criteria_up(handle, |n| {
                if let UINode::Menu(_) = n { true } else { false }
            });
        } else {
            // Continue search from parent menu item of popup.
            if let UINode::Popup(popup) = ui.node(popup) {
                handle = *popup.user_data_ref::<Handle<UINode<M, C>>>();
            } else {
                unreachable!();
            }
        }
    }
}

impl<M: 'static, C: 'static + Control<M, C>> Control<M, C> for MenuItem<M, C> {
    fn raw_copy(&self) -> UINode<M, C> {
        UINode::MenuItem(self.clone())
    }

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

        match &message.data {
            UiMessageData::Widget(msg) => {
                match msg {
                    WidgetMessage::MouseDown { .. } => {
                        let menu = find_menu(self.parent(), ui);
                        if menu.is_some() {
                            // Activate menu so it user will be able to open submenus by
                            // mouse hover.
                            ui.send_message(UiMessage {
                                handled: false,
                                data: UiMessageData::Menu(MenuMessage::Activate),
                                destination: menu,
                            });

                            ui.send_message(UiMessage {
                                handled: false,
                                data: UiMessageData::MenuItem(MenuItemMessage::Open),
                                destination: self.handle(),
                            });
                        }
                    }
                    WidgetMessage::MouseUp { .. } => {
                        if !message.handled {
                            ui.send_message(UiMessage {
                                handled: false,
                                data: UiMessageData::MenuItem(MenuItemMessage::Click),
                                destination: self.handle(),
                            });
                            if self.items.is_empty() {
                                let menu = find_menu(self.parent(), ui);
                                if menu.is_some() {
                                    ui.send_message(UiMessage {
                                        handled: false,
                                        data: UiMessageData::Menu(MenuMessage::Deactivate),
                                        destination: menu,
                                    });
                                }
                            }
                            message.handled = true;
                        }
                    }
                    WidgetMessage::MouseLeave => {
                        ui.send_message(WidgetMessage::background(self.back, Brush::Solid(Color::opaque(50, 50, 50))));
                    }
                    WidgetMessage::MouseEnter => {
                        ui.send_message(WidgetMessage::background(self.back, Brush::Solid(Color::opaque(130, 130, 130))));

                        // While parent menu active it is possible to open submenus
                        // by simple mouse hover.
                        let menu = find_menu(self.parent(), ui);
                        if menu.is_some() {
                            if let UINode::Menu(menu) = ui.node(menu) {
                                if menu.active {
                                    ui.send_message(UiMessage {
                                        handled: false,
                                        data: UiMessageData::MenuItem(MenuItemMessage::Open),
                                        destination: self.handle(),
                                    });
                                }
                            }
                        }
                    }
                    _ => {}
                }
            }
            UiMessageData::MenuItem(msg) => {
                match msg {
                    MenuItemMessage::Open => {
                        if !self.items.is_empty() {
                            let position = match self.placement {
                                MenuItemPlacement::Bottom => {
                                    self.screen_position + Vec2::new(0.0, self.actual_size().y)
                                }
                                MenuItemPlacement::Right => {
                                    self.screen_position + Vec2::new(self.actual_size().x, 0.0)
                                }
                            };

                            // Open popup.
                            ui.send_message(UiMessage {
                                handled: false,
                                data: UiMessageData::Popup(PopupMessage::Placement(Placement::Position(position))),
                                destination: self.popup,
                            });
                            ui.send_message(UiMessage {
                                handled: false,
                                data: UiMessageData::Popup(PopupMessage::Open),
                                destination: self.popup,
                            });
                        }
                    }
                    MenuItemMessage::Close => {
                        ui.send_message(UiMessage {
                            handled: false,
                            data: UiMessageData::Popup(PopupMessage::Close),
                            destination: self.popup,
                        });
                    }
                    MenuItemMessage::Click => {}
                }
            }
            _ => {}
        }
    }

    fn preview_message(&mut self, ui: &mut UserInterface<M, C>, message: &mut UiMessage<M, C>) {
        // We need to check if some new menu item opened and then close other not in
        // direct chain of menu items until to menu.
        if message.destination != self.handle() {
            if let UiMessageData::MenuItem(msg) = &message.data {
                if let MenuItemMessage::Open = msg {
                    let mut found = false;
                    let mut handle = message.destination;
                    while handle.is_some() {
                        if handle == self.handle() {
                            found = true;
                            break;
                        } else {
                            let node = ui.node(handle);
                            if let UINode::Popup(popup) = node {
                                // Once we found popup in chain, we must extract handle
                                // of parent menu item to continue search.
                                handle = *popup.user_data_ref::<Handle<UINode<M, C>>>();
                            } else {
                                handle = node.parent();
                            }
                        }
                    }

                    if !found {
                        ui.send_message(UiMessage {
                            handled: false,
                            data: UiMessageData::MenuItem(MenuItemMessage::Close),
                            destination: self.handle(),
                        });
                    }
                }
            }
        }
    }
}

pub struct MenuBuilder<M: 'static, C: 'static + Control<M, C>> {
    widget_builder: WidgetBuilder<M, C>,
    items: Vec<Handle<UINode<M, C>>>,
}

impl<M: 'static, C: 'static + Control<M, C>> MenuBuilder<M, C> {
    pub fn new(widget_builder: WidgetBuilder<M, C>) -> Self {
        Self {
            widget_builder,
            items: Default::default(),
        }
    }

    pub fn with_items(mut self, items: Vec<Handle<UINode<M, C>>>) -> Self {
        self.items = items;
        self
    }

    pub fn build(self, ctx: &mut BuildContext<M, C>) -> Handle<UINode<M, C>> {
        for &item in self.items.iter() {
            if let UINode::MenuItem(item) = &mut ctx[item] {
                item.placement = MenuItemPlacement::Bottom;
            }
        }

        let back = BorderBuilder::new(WidgetBuilder::new()
            .with_child(StackPanelBuilder::new(WidgetBuilder::new()
                .with_children(&self.items))
                .with_orientation(Orientation::Horizontal)
                .build(ctx)))
            .build(ctx);

        let menu = Menu {
            widget: self.widget_builder
                .with_child(back)
                .build(),
            active: false,
        };

        ctx.add_node(UINode::Menu(menu))
    }
}

pub enum MenuItemContent<'a, 'b, M: 'static, C: 'static + Control<M, C>> {
    /// Empty menu item.
    None,
    /// Quick-n-dirty way of building elements. It can cover most of use
    /// cases - it builds classic menu item:
    ///   _____________________
    ///  |    |      |        |
    ///  |icon| text |shortcut|
    ///  |____|______|________|
    Text {
        text: &'a str,
        shortcut: &'b str,
        icon: Handle<UINode<M, C>>,
    },
    /// Allows to put any node into menu item. It allows to customize menu
    /// item how needed - i.e. put image in it, or other user control.
    Node(Handle<UINode<M, C>>),
}

impl<'a, 'b, M: 'static, C: 'static + Control<M, C>> MenuItemContent<'a, 'b, M, C> {
    pub fn text_with_shortcut(text: &'a str, shortcut: &'b str) -> Self {
        MenuItemContent::Text {
            text,
            shortcut,
            icon: Default::default(),
        }
    }

    pub fn text(text: &'a str) -> Self {
        MenuItemContent::Text {
            text,
            shortcut: "",
            icon: Default::default(),
        }
    }
}

pub struct MenuItemBuilder<'a, 'b, M: 'static, C: 'static + Control<M, C>> {
    widget_builder: WidgetBuilder<M, C>,
    items: Vec<Handle<UINode<M, C>>>,
    content: MenuItemContent<'a, 'b, M, C>,
}

impl<'a, 'b, M: 'static, C: 'static + Control<M, C>> MenuItemBuilder<'a, 'b, M, C> {
    pub fn new(widget_builder: WidgetBuilder<M, C>) -> Self {
        Self {
            widget_builder,
            items: Default::default(),
            content: MenuItemContent::None,
        }
    }

    pub fn with_content(mut self, content: MenuItemContent<'a, 'b, M, C>) -> Self {
        self.content = content;
        self
    }

    pub fn with_items(mut self, items: Vec<Handle<UINode<M, C>>>) -> Self {
        self.items = items;
        self
    }

    pub fn build(self, ctx: &mut BuildContext<M, C>) -> Handle<UINode<M, C>> {
        let content = match self.content {
            MenuItemContent::None => Handle::NONE,
            MenuItemContent::Text { text, shortcut, icon } => {
                GridBuilder::new(WidgetBuilder::new()
                    .with_child(icon)
                    .with_child(TextBuilder::new(WidgetBuilder::new()
                        .with_vertical_alignment(VerticalAlignment::Center)
                        .with_margin(Thickness::uniform(1.0))
                        .on_column(1))
                        .with_text(text)
                        .build(ctx))
                    .with_child(TextBuilder::new(WidgetBuilder::new()
                        .with_vertical_alignment(VerticalAlignment::Center)
                        .with_horizontal_alignment(HorizontalAlignment::Right)
                        .with_margin(Thickness::uniform(1.0))
                        .on_column(2))
                        .with_text(shortcut)
                        .build(ctx)))
                    .add_row(Row::stretch())
                    .add_column(Column::auto())
                    .add_column(Column::stretch())
                    .add_column(Column::auto())
                    .build(ctx)
            }
            MenuItemContent::Node(node) => node,
        };

        let back = BorderBuilder::new(WidgetBuilder::new()
            .with_child(content))
            .build(ctx);

        let popup = PopupBuilder::new(WidgetBuilder::new()
            .with_min_size(Vec2::new(10.0, 10.0)))
            .with_content(StackPanelBuilder::new(WidgetBuilder::new()
                .with_children(&self.items))
                .build(ctx))
            // We'll manually control if popup is either open or closed.
            .stays_open(true)
            .build(ctx);

        let menu = MenuItem {
            widget: self.widget_builder
                .with_child(back)
                .build(),
            popup,
            items: self.items,
            back,
            placement: MenuItemPlacement::Right,
        };

        let handle = ctx.add_node(UINode::MenuItem(menu));

        // "Link" popup with its parent menu item.
        if let UINode::Popup(popup) = &mut ctx[popup] {
            popup.user_data = Some(Rc::new(handle));
        }

        handle
    }
}