mouse_event_handler.rs

  1use std::ops::DerefMut;
  2
  3use crate::{
  4    geometry::{rect::RectF, vector::Vector2F},
  5    platform::CursorStyle,
  6    CursorStyleHandle, DebugContext, Element, ElementBox, ElementStateHandle, ElementStateId,
  7    Event, EventContext, LayoutContext, MutableAppContext, PaintContext, SizeConstraint,
  8};
  9use serde_json::json;
 10
 11pub struct MouseEventHandler {
 12    state: ElementStateHandle<MouseState>,
 13    child: ElementBox,
 14    cursor_style: Option<CursorStyle>,
 15    mouse_down_handler: Option<Box<dyn FnMut(&mut EventContext)>>,
 16    click_handler: Option<Box<dyn FnMut(&mut EventContext)>>,
 17    drag_handler: Option<Box<dyn FnMut(Vector2F, &mut EventContext)>>,
 18}
 19
 20#[derive(Default)]
 21pub struct MouseState {
 22    pub hovered: bool,
 23    pub clicked: bool,
 24    prev_drag_position: Option<Vector2F>,
 25    cursor_style_handle: Option<CursorStyleHandle>,
 26}
 27
 28impl MouseEventHandler {
 29    pub fn new<Tag, F, C, Id>(id: Id, cx: &mut C, render_child: F) -> Self
 30    where
 31        Tag: 'static,
 32        F: FnOnce(&MouseState, &mut C) -> ElementBox,
 33        C: DerefMut<Target = MutableAppContext>,
 34        Id: Into<ElementStateId>,
 35    {
 36        let state_handle = cx.element_state::<Tag, _>(id.into());
 37        let child = state_handle.update(cx, |state, cx| render_child(state, cx));
 38        Self {
 39            state: state_handle,
 40            child,
 41            cursor_style: None,
 42            mouse_down_handler: None,
 43            click_handler: None,
 44            drag_handler: None,
 45        }
 46    }
 47
 48    pub fn with_cursor_style(mut self, cursor: CursorStyle) -> Self {
 49        self.cursor_style = Some(cursor);
 50        self
 51    }
 52
 53    pub fn on_mouse_down(mut self, handler: impl FnMut(&mut EventContext) + 'static) -> Self {
 54        self.mouse_down_handler = Some(Box::new(handler));
 55        self
 56    }
 57
 58    pub fn on_click(mut self, handler: impl FnMut(&mut EventContext) + 'static) -> Self {
 59        self.click_handler = Some(Box::new(handler));
 60        self
 61    }
 62
 63    pub fn on_drag(mut self, handler: impl FnMut(Vector2F, &mut EventContext) + 'static) -> Self {
 64        self.drag_handler = Some(Box::new(handler));
 65        self
 66    }
 67}
 68
 69impl Element for MouseEventHandler {
 70    type LayoutState = ();
 71    type PaintState = ();
 72
 73    fn layout(
 74        &mut self,
 75        constraint: SizeConstraint,
 76        cx: &mut LayoutContext,
 77    ) -> (Vector2F, Self::LayoutState) {
 78        (self.child.layout(constraint, cx), ())
 79    }
 80
 81    fn paint(
 82        &mut self,
 83        bounds: RectF,
 84        _: &mut Self::LayoutState,
 85        cx: &mut PaintContext,
 86    ) -> Self::PaintState {
 87        self.child.paint(bounds.origin(), cx);
 88    }
 89
 90    fn dispatch_event(
 91        &mut self,
 92        event: &Event,
 93        bounds: RectF,
 94        _: &mut Self::LayoutState,
 95        _: &mut Self::PaintState,
 96        cx: &mut EventContext,
 97    ) -> bool {
 98        let cursor_style = self.cursor_style;
 99        let mouse_down_handler = self.mouse_down_handler.as_mut();
100        let click_handler = self.click_handler.as_mut();
101        let drag_handler = self.drag_handler.as_mut();
102
103        let handled_in_child = self.child.dispatch_event(event, cx);
104
105        self.state.update(cx, |state, cx| match event {
106            Event::MouseMoved {
107                position,
108                left_mouse_down,
109            } => {
110                if !left_mouse_down {
111                    let mouse_in = bounds.contains_point(*position);
112                    if state.hovered != mouse_in {
113                        state.hovered = mouse_in;
114                        if let Some(cursor_style) = cursor_style {
115                            if !state.clicked {
116                                if state.hovered {
117                                    state.cursor_style_handle =
118                                        Some(cx.set_cursor_style(cursor_style));
119                                } else {
120                                    state.cursor_style_handle = None;
121                                }
122                            }
123                        }
124                        cx.notify();
125                        return true;
126                    }
127                }
128                handled_in_child
129            }
130            Event::LeftMouseDown { position, .. } => {
131                if !handled_in_child && bounds.contains_point(*position) {
132                    state.clicked = true;
133                    state.prev_drag_position = Some(*position);
134                    cx.notify();
135                    if let Some(handler) = mouse_down_handler {
136                        handler(cx);
137                    }
138                    true
139                } else {
140                    handled_in_child
141                }
142            }
143            Event::LeftMouseUp { position, .. } => {
144                state.prev_drag_position = None;
145                if !handled_in_child && state.clicked {
146                    state.clicked = false;
147                    if !state.hovered {
148                        state.cursor_style_handle = None;
149                    }
150                    cx.notify();
151                    if let Some(handler) = click_handler {
152                        if bounds.contains_point(*position) {
153                            handler(cx);
154                        }
155                    }
156                    true
157                } else {
158                    handled_in_child
159                }
160            }
161            Event::LeftMouseDragged { position, .. } => {
162                if !handled_in_child && state.clicked {
163                    let prev_drag_position = state.prev_drag_position.replace(*position);
164                    if let Some((handler, prev_position)) = drag_handler.zip(prev_drag_position) {
165                        let delta = *position - prev_position;
166                        if !delta.is_zero() {
167                            (handler)(delta, cx);
168                        }
169                    }
170                    true
171                } else {
172                    handled_in_child
173                }
174            }
175            _ => handled_in_child,
176        })
177    }
178
179    fn debug(
180        &self,
181        _: RectF,
182        _: &Self::LayoutState,
183        _: &Self::PaintState,
184        cx: &DebugContext,
185    ) -> serde_json::Value {
186        json!({
187            "type": "MouseEventHandler",
188            "child": self.child.debug(cx),
189        })
190    }
191}