mouse_event_handler.rs

  1use super::Padding;
  2use crate::{
  3    geometry::{
  4        rect::RectF,
  5        vector::{vec2f, Vector2F},
  6    },
  7    platform::CursorStyle,
  8    platform::MouseButton,
  9    scene::{
 10        CursorRegion, HandlerSet, MouseClick, MouseDown, MouseDownOut, MouseDrag, MouseHover,
 11        MouseMove, MouseMoveOut, MouseScrollWheel, MouseUp, MouseUpOut,
 12    },
 13    AnyElement, Element, EventContext, LayoutContext, MouseRegion, MouseState, SceneBuilder,
 14    SizeConstraint, View, ViewContext,
 15};
 16use serde_json::json;
 17use std::{marker::PhantomData, ops::Range};
 18
 19pub struct MouseEventHandler<Tag: 'static, V: View> {
 20    child: AnyElement<V>,
 21    region_id: usize,
 22    cursor_style: Option<CursorStyle>,
 23    handlers: HandlerSet,
 24    hoverable: bool,
 25    notify_on_hover: bool,
 26    notify_on_click: bool,
 27    above: bool,
 28    padding: Padding,
 29    _tag: PhantomData<Tag>,
 30}
 31
 32/// Element which provides a render_child callback with a MouseState and paints a mouse
 33/// region under (or above) it for easy mouse event handling.
 34impl<Tag, V: View> MouseEventHandler<Tag, V> {
 35    pub fn for_child(child: impl Element<V>, region_id: usize) -> Self {
 36        Self {
 37            child: child.into_any(),
 38            region_id,
 39            cursor_style: None,
 40            handlers: Default::default(),
 41            notify_on_hover: false,
 42            notify_on_click: false,
 43            hoverable: false,
 44            above: false,
 45            padding: Default::default(),
 46            _tag: PhantomData,
 47        }
 48    }
 49
 50    pub fn new<E, F>(region_id: usize, cx: &mut ViewContext<V>, render_child: F) -> Self
 51    where
 52        E: Element<V>,
 53        F: FnOnce(&mut MouseState, &mut ViewContext<V>) -> E,
 54    {
 55        let mut mouse_state = cx.mouse_state::<Tag>(region_id);
 56        let child = render_child(&mut mouse_state, cx).into_any();
 57        let notify_on_hover = mouse_state.accessed_hovered();
 58        let notify_on_click = mouse_state.accessed_clicked();
 59        Self {
 60            child,
 61            region_id,
 62            cursor_style: None,
 63            handlers: Default::default(),
 64            notify_on_hover,
 65            notify_on_click,
 66            hoverable: true,
 67            above: false,
 68            padding: Default::default(),
 69            _tag: PhantomData,
 70        }
 71    }
 72
 73    /// Modifies the MouseEventHandler to render the MouseRegion above the child element. Useful
 74    /// for drag and drop handling and similar events which should be captured before the child
 75    /// gets the opportunity
 76    pub fn above<D, F>(region_id: usize, cx: &mut ViewContext<V>, render_child: F) -> Self
 77    where
 78        D: Element<V>,
 79        F: FnOnce(&mut MouseState, &mut ViewContext<V>) -> D,
 80    {
 81        let mut handler = Self::new(region_id, cx, render_child);
 82        handler.above = true;
 83        handler
 84    }
 85
 86    pub fn with_cursor_style(mut self, cursor: CursorStyle) -> Self {
 87        self.cursor_style = Some(cursor);
 88        self
 89    }
 90
 91    pub fn capture_all(mut self) -> Self {
 92        self.handlers = HandlerSet::capture_all();
 93        self
 94    }
 95
 96    pub fn on_move(
 97        mut self,
 98        handler: impl Fn(MouseMove, &mut V, &mut EventContext<V>) + 'static,
 99    ) -> Self {
100        self.handlers = self.handlers.on_move(handler);
101        self
102    }
103
104    pub fn on_move_out(
105        mut self,
106        handler: impl Fn(MouseMoveOut, &mut V, &mut EventContext<V>) + 'static,
107    ) -> Self {
108        self.handlers = self.handlers.on_move_out(handler);
109        self
110    }
111
112    pub fn on_down(
113        mut self,
114        button: MouseButton,
115        handler: impl Fn(MouseDown, &mut V, &mut EventContext<V>) + 'static,
116    ) -> Self {
117        self.handlers = self.handlers.on_down(button, handler);
118        self
119    }
120
121    pub fn on_up(
122        mut self,
123        button: MouseButton,
124        handler: impl Fn(MouseUp, &mut V, &mut EventContext<V>) + 'static,
125    ) -> Self {
126        self.handlers = self.handlers.on_up(button, handler);
127        self
128    }
129
130    pub fn on_click(
131        mut self,
132        button: MouseButton,
133        handler: impl Fn(MouseClick, &mut V, &mut EventContext<V>) + 'static,
134    ) -> Self {
135        self.handlers = self.handlers.on_click(button, handler);
136        self
137    }
138
139    pub fn on_down_out(
140        mut self,
141        button: MouseButton,
142        handler: impl Fn(MouseDownOut, &mut V, &mut EventContext<V>) + 'static,
143    ) -> Self {
144        self.handlers = self.handlers.on_down_out(button, handler);
145        self
146    }
147
148    pub fn on_up_out(
149        mut self,
150        button: MouseButton,
151        handler: impl Fn(MouseUpOut, &mut V, &mut EventContext<V>) + 'static,
152    ) -> Self {
153        self.handlers = self.handlers.on_up_out(button, handler);
154        self
155    }
156
157    pub fn on_drag(
158        mut self,
159        button: MouseButton,
160        handler: impl Fn(MouseDrag, &mut V, &mut EventContext<V>) + 'static,
161    ) -> Self {
162        self.handlers = self.handlers.on_drag(button, handler);
163        self
164    }
165
166    pub fn on_hover(
167        mut self,
168        handler: impl Fn(MouseHover, &mut V, &mut EventContext<V>) + 'static,
169    ) -> Self {
170        self.handlers = self.handlers.on_hover(handler);
171        self
172    }
173
174    pub fn on_scroll(
175        mut self,
176        handler: impl Fn(MouseScrollWheel, &mut V, &mut EventContext<V>) + 'static,
177    ) -> Self {
178        self.handlers = self.handlers.on_scroll(handler);
179        self
180    }
181
182    pub fn with_hoverable(mut self, is_hoverable: bool) -> Self {
183        self.hoverable = is_hoverable;
184        self
185    }
186
187    pub fn with_padding(mut self, padding: Padding) -> Self {
188        self.padding = padding;
189        self
190    }
191
192    fn hit_bounds(&self, bounds: RectF) -> RectF {
193        RectF::from_points(
194            bounds.origin() - vec2f(self.padding.left, self.padding.top),
195            bounds.lower_right() + vec2f(self.padding.right, self.padding.bottom),
196        )
197        .round_out()
198    }
199
200    fn paint_regions(
201        &self,
202        scene: &mut SceneBuilder,
203        bounds: RectF,
204        visible_bounds: RectF,
205        cx: &mut ViewContext<V>,
206    ) {
207        let visible_bounds = visible_bounds.intersection(bounds).unwrap_or_default();
208        let hit_bounds = self.hit_bounds(visible_bounds);
209
210        if let Some(style) = self.cursor_style {
211            scene.push_cursor_region(CursorRegion {
212                bounds: hit_bounds,
213                style,
214            });
215        }
216        scene.push_mouse_region(
217            MouseRegion::from_handlers::<Tag>(
218                cx.view_id(),
219                self.region_id,
220                hit_bounds,
221                self.handlers.clone(),
222            )
223            .with_hoverable(self.hoverable)
224            .with_notify_on_hover(self.notify_on_hover)
225            .with_notify_on_click(self.notify_on_click),
226        );
227    }
228}
229
230impl<Tag, V: View> Element<V> for MouseEventHandler<Tag, V> {
231    type LayoutState = ();
232    type PaintState = ();
233
234    fn layout(
235        &mut self,
236        constraint: SizeConstraint,
237        view: &mut V,
238        cx: &mut LayoutContext<V>,
239    ) -> (Vector2F, Self::LayoutState) {
240        (self.child.layout(constraint, view, cx), ())
241    }
242
243    fn paint(
244        &mut self,
245        scene: &mut SceneBuilder,
246        bounds: RectF,
247        visible_bounds: RectF,
248        _: &mut Self::LayoutState,
249        view: &mut V,
250        cx: &mut ViewContext<V>,
251    ) -> Self::PaintState {
252        if self.above {
253            self.child
254                .paint(scene, bounds.origin(), visible_bounds, view, cx);
255
256            scene.paint_layer(None, |scene| {
257                self.paint_regions(scene, bounds, visible_bounds, cx);
258            });
259        } else {
260            self.paint_regions(scene, bounds, visible_bounds, cx);
261            self.child
262                .paint(scene, bounds.origin(), visible_bounds, view, cx);
263        }
264    }
265
266    fn rect_for_text_range(
267        &self,
268        range_utf16: Range<usize>,
269        _: RectF,
270        _: RectF,
271        _: &Self::LayoutState,
272        _: &Self::PaintState,
273        view: &V,
274        cx: &ViewContext<V>,
275    ) -> Option<RectF> {
276        self.child.rect_for_text_range(range_utf16, view, cx)
277    }
278
279    fn debug(
280        &self,
281        _: RectF,
282        _: &Self::LayoutState,
283        _: &Self::PaintState,
284        view: &V,
285        cx: &ViewContext<V>,
286    ) -> serde_json::Value {
287        json!({
288            "type": "MouseEventHandler",
289            "child": self.child.debug(view, cx),
290        })
291    }
292}