mouse_event_handler.rs

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