tuix_widgets/menus/
context_menu.rs

1use tuix_core::TreeExt;
2
3use crate::common::*;
4
5// Wrap a widget in a context menu to add a right-click menu to a widget
6pub struct ContextMenu {
7    context_menu: Entity,
8}
9
10impl ContextMenu {
11    pub fn new() -> Self {
12        Self {
13            context_menu: Entity::default(),
14        }
15    }
16}
17
18impl Widget for ContextMenu {
19    type Ret = (Entity, Entity);
20    type Data = ();
21    fn on_build(&mut self, state: &mut State, entity: Entity) -> Self::Ret {
22        self.context_menu = Element::new().build(state, entity, |builder| {
23            builder
24                .set_background_color(Color::red())
25                .set_visibility(Visibility::Invisible)
26        });
27        (entity, self.context_menu)
28    }
29
30    fn on_event(&mut self, state: &mut State, entity: Entity, event: &mut Event) {
31        if let Some(window_event) = event.message.downcast::<WindowEvent>() {
32            match window_event {
33                WindowEvent::MouseDown(button) => {
34                    if *button == MouseButton::Right {
35                        let px = state.mouse.right.pos_down.0
36                            - state
37                                .data
38                                .get_posx(entity.parent(&state.tree).unwrap());
39                        let py = state.mouse.right.pos_down.1
40                            - state
41                                .data
42                                .get_posy(entity.parent(&state.tree).unwrap());
43                        self.context_menu
44                            .set_left(state, Units::Pixels(px))
45                            .set_top(state, Units::Pixels(py))
46                            .set_visibility(state, Visibility::Visible);
47                    }
48                }
49
50                _ => {}
51            }
52        }
53    }
54}