interactive.rs

  1use crate::{
  2    point, Action, AppContext, BorrowWindow, Bounds, DispatchContext, DispatchPhase, Element,
  3    ElementId, FocusHandle, KeyMatch, Keystroke, Modifiers, Pixels, Point, SharedString, Style,
  4    StyleRefinement, ViewContext,
  5};
  6use collections::HashMap;
  7use derive_more::{Deref, DerefMut};
  8use parking_lot::Mutex;
  9use refineable::Refineable;
 10use smallvec::SmallVec;
 11use std::{
 12    any::{Any, TypeId},
 13    fmt::Debug,
 14    ops::Deref,
 15    sync::Arc,
 16};
 17
 18pub trait StatelessInteractive: Element {
 19    fn stateless_interactivity(&mut self) -> &mut StatelessInteraction<Self::ViewState>;
 20
 21    fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
 22    where
 23        Self: Sized,
 24    {
 25        self.stateless_interactivity().hover_style = f(StyleRefinement::default());
 26        self
 27    }
 28
 29    fn group_hover(
 30        mut self,
 31        group_name: impl Into<SharedString>,
 32        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
 33    ) -> Self
 34    where
 35        Self: Sized,
 36    {
 37        self.stateless_interactivity().group_hover_style = Some(GroupStyle {
 38            group: group_name.into(),
 39            style: f(StyleRefinement::default()),
 40        });
 41        self
 42    }
 43
 44    fn on_mouse_down(
 45        mut self,
 46        button: MouseButton,
 47        handler: impl Fn(&mut Self::ViewState, &MouseDownEvent, &mut ViewContext<Self::ViewState>)
 48            + Send
 49            + Sync
 50            + 'static,
 51    ) -> Self
 52    where
 53        Self: Sized,
 54    {
 55        self.stateless_interactivity()
 56            .mouse_down_listeners
 57            .push(Arc::new(move |view, event, bounds, phase, cx| {
 58                if phase == DispatchPhase::Bubble
 59                    && event.button == button
 60                    && bounds.contains_point(&event.position)
 61                {
 62                    handler(view, event, cx)
 63                }
 64            }));
 65        self
 66    }
 67
 68    fn on_mouse_up(
 69        mut self,
 70        button: MouseButton,
 71        handler: impl Fn(&mut Self::ViewState, &MouseUpEvent, &mut ViewContext<Self::ViewState>)
 72            + Send
 73            + Sync
 74            + 'static,
 75    ) -> Self
 76    where
 77        Self: Sized,
 78    {
 79        self.stateless_interactivity()
 80            .mouse_up_listeners
 81            .push(Arc::new(move |view, event, bounds, phase, cx| {
 82                if phase == DispatchPhase::Bubble
 83                    && event.button == button
 84                    && bounds.contains_point(&event.position)
 85                {
 86                    handler(view, event, cx)
 87                }
 88            }));
 89        self
 90    }
 91
 92    fn on_mouse_down_out(
 93        mut self,
 94        button: MouseButton,
 95        handler: impl Fn(&mut Self::ViewState, &MouseDownEvent, &mut ViewContext<Self::ViewState>)
 96            + Send
 97            + Sync
 98            + 'static,
 99    ) -> Self
100    where
101        Self: Sized,
102    {
103        self.stateless_interactivity()
104            .mouse_down_listeners
105            .push(Arc::new(move |view, event, bounds, phase, cx| {
106                if phase == DispatchPhase::Capture
107                    && event.button == button
108                    && !bounds.contains_point(&event.position)
109                {
110                    handler(view, event, cx)
111                }
112            }));
113        self
114    }
115
116    fn on_mouse_up_out(
117        mut self,
118        button: MouseButton,
119        handler: impl Fn(&mut Self::ViewState, &MouseUpEvent, &mut ViewContext<Self::ViewState>)
120            + Send
121            + Sync
122            + 'static,
123    ) -> Self
124    where
125        Self: Sized,
126    {
127        self.stateless_interactivity()
128            .mouse_up_listeners
129            .push(Arc::new(move |view, event, bounds, phase, cx| {
130                if phase == DispatchPhase::Capture
131                    && event.button == button
132                    && !bounds.contains_point(&event.position)
133                {
134                    handler(view, event, cx);
135                }
136            }));
137        self
138    }
139
140    fn on_mouse_move(
141        mut self,
142        handler: impl Fn(&mut Self::ViewState, &MouseMoveEvent, &mut ViewContext<Self::ViewState>)
143            + Send
144            + Sync
145            + 'static,
146    ) -> Self
147    where
148        Self: Sized,
149    {
150        self.stateless_interactivity()
151            .mouse_move_listeners
152            .push(Arc::new(move |view, event, bounds, phase, cx| {
153                if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
154                    handler(view, event, cx);
155                }
156            }));
157        self
158    }
159
160    fn on_scroll_wheel(
161        mut self,
162        handler: impl Fn(&mut Self::ViewState, &ScrollWheelEvent, &mut ViewContext<Self::ViewState>)
163            + Send
164            + Sync
165            + 'static,
166    ) -> Self
167    where
168        Self: Sized,
169    {
170        self.stateless_interactivity()
171            .scroll_wheel_listeners
172            .push(Arc::new(move |view, event, bounds, phase, cx| {
173                if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
174                    handler(view, event, cx);
175                }
176            }));
177        self
178    }
179
180    fn context<C>(mut self, context: C) -> Self
181    where
182        Self: Sized,
183        C: TryInto<DispatchContext>,
184        C::Error: Debug,
185    {
186        self.stateless_interactivity().dispatch_context =
187            context.try_into().expect("invalid dispatch context");
188        self
189    }
190
191    fn on_action<A: 'static>(
192        mut self,
193        listener: impl Fn(&mut Self::ViewState, &A, DispatchPhase, &mut ViewContext<Self::ViewState>)
194            + Send
195            + Sync
196            + 'static,
197    ) -> Self
198    where
199        Self: Sized,
200    {
201        self.stateless_interactivity().key_listeners.push((
202            TypeId::of::<A>(),
203            Arc::new(move |view, event, _, phase, cx| {
204                let event = event.downcast_ref().unwrap();
205                listener(view, event, phase, cx);
206                None
207            }),
208        ));
209        self
210    }
211
212    fn on_key_down(
213        mut self,
214        listener: impl Fn(
215                &mut Self::ViewState,
216                &KeyDownEvent,
217                DispatchPhase,
218                &mut ViewContext<Self::ViewState>,
219            ) + Send
220            + Sync
221            + 'static,
222    ) -> Self
223    where
224        Self: Sized,
225    {
226        self.stateless_interactivity().key_listeners.push((
227            TypeId::of::<KeyDownEvent>(),
228            Arc::new(move |view, event, _, phase, cx| {
229                let event = event.downcast_ref().unwrap();
230                listener(view, event, phase, cx);
231                None
232            }),
233        ));
234        self
235    }
236
237    fn on_key_up(
238        mut self,
239        listener: impl Fn(&mut Self::ViewState, &KeyUpEvent, DispatchPhase, &mut ViewContext<Self::ViewState>)
240            + Send
241            + Sync
242            + 'static,
243    ) -> Self
244    where
245        Self: Sized,
246    {
247        self.stateless_interactivity().key_listeners.push((
248            TypeId::of::<KeyUpEvent>(),
249            Arc::new(move |view, event, _, phase, cx| {
250                let event = event.downcast_ref().unwrap();
251                listener(view, event, phase, cx);
252                None
253            }),
254        ));
255        self
256    }
257}
258
259pub trait StatefulInteractive: StatelessInteractive {
260    fn stateful_interactivity(&mut self) -> &mut StatefulInteraction<Self::ViewState>;
261
262    fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
263    where
264        Self: Sized,
265    {
266        self.stateful_interactivity().active_style = f(StyleRefinement::default());
267        self
268    }
269
270    fn group_active(
271        mut self,
272        group_name: impl Into<SharedString>,
273        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
274    ) -> Self
275    where
276        Self: Sized,
277    {
278        self.stateful_interactivity().group_active_style = Some(GroupStyle {
279            group: group_name.into(),
280            style: f(StyleRefinement::default()),
281        });
282        self
283    }
284
285    fn on_click(
286        mut self,
287        handler: impl Fn(&mut Self::ViewState, &MouseClickEvent, &mut ViewContext<Self::ViewState>)
288            + Send
289            + Sync
290            + 'static,
291    ) -> Self
292    where
293        Self: Sized,
294    {
295        self.stateful_interactivity()
296            .mouse_click_listeners
297            .push(Arc::new(move |view, event, cx| handler(view, event, cx)));
298        self
299    }
300}
301
302pub trait ElementInteraction<V: 'static + Send + Sync>: 'static + Send + Sync {
303    fn as_stateless(&self) -> &StatelessInteraction<V>;
304    fn as_stateless_mut(&mut self) -> &mut StatelessInteraction<V>;
305    fn as_stateful(&self) -> Option<&StatefulInteraction<V>>;
306    fn as_stateful_mut(&mut self) -> Option<&mut StatefulInteraction<V>>;
307
308    fn initialize<R>(
309        &mut self,
310        cx: &mut ViewContext<V>,
311        f: impl FnOnce(&mut ViewContext<V>) -> R,
312    ) -> R {
313        if let Some(stateful) = self.as_stateful_mut() {
314            cx.with_element_id(stateful.id.clone(), |global_id, cx| {
315                stateful.key_listeners.push((
316                    TypeId::of::<KeyDownEvent>(),
317                    Arc::new(move |_, key_down, context, phase, cx| {
318                        if phase == DispatchPhase::Bubble {
319                            let key_down = key_down.downcast_ref::<KeyDownEvent>().unwrap();
320                            if let KeyMatch::Some(action) =
321                                cx.match_keystroke(&global_id, &key_down.keystroke, context)
322                            {
323                                return Some(action);
324                            }
325                        }
326
327                        None
328                    }),
329                ));
330                let result = stateful.stateless.initialize(cx, f);
331                stateful.key_listeners.pop();
332                result
333            })
334        } else {
335            let stateless = self.as_stateless();
336            cx.with_key_dispatch_context(stateless.dispatch_context.clone(), |cx| {
337                cx.with_key_listeners(&stateless.key_listeners, f)
338            })
339        }
340    }
341
342    fn refine_style(
343        &self,
344        style: &mut Style,
345        bounds: Bounds<Pixels>,
346        element_state: &InteractiveElementState,
347        cx: &mut ViewContext<V>,
348    ) {
349        let mouse_position = cx.mouse_position();
350        let stateless = self.as_stateless();
351        if let Some(group_hover) = stateless.group_hover_style.as_ref() {
352            if let Some(group_bounds) = GroupBounds::get(&group_hover.group, cx) {
353                if group_bounds.contains_point(&mouse_position) {
354                    style.refine(&group_hover.style);
355                }
356            }
357        }
358        if bounds.contains_point(&mouse_position) {
359            style.refine(&stateless.hover_style);
360        }
361
362        if let Some(stateful) = self.as_stateful() {
363            let active_state = element_state.active_state.lock();
364            if active_state.group {
365                if let Some(group_style) = stateful.group_active_style.as_ref() {
366                    style.refine(&group_style.style);
367                }
368            }
369            if active_state.element {
370                style.refine(&stateful.active_style);
371            }
372        }
373    }
374
375    fn paint(
376        &mut self,
377        bounds: Bounds<Pixels>,
378        element_state: &InteractiveElementState,
379        cx: &mut ViewContext<V>,
380    ) {
381        let stateless = self.as_stateless();
382        for listener in stateless.mouse_down_listeners.iter().cloned() {
383            cx.on_mouse_event(move |state, event: &MouseDownEvent, phase, cx| {
384                listener(state, event, &bounds, phase, cx);
385            })
386        }
387
388        for listener in stateless.mouse_up_listeners.iter().cloned() {
389            cx.on_mouse_event(move |state, event: &MouseUpEvent, phase, cx| {
390                listener(state, event, &bounds, phase, cx);
391            })
392        }
393
394        for listener in stateless.mouse_move_listeners.iter().cloned() {
395            cx.on_mouse_event(move |state, event: &MouseMoveEvent, phase, cx| {
396                listener(state, event, &bounds, phase, cx);
397            })
398        }
399
400        for listener in stateless.scroll_wheel_listeners.iter().cloned() {
401            cx.on_mouse_event(move |state, event: &ScrollWheelEvent, phase, cx| {
402                listener(state, event, &bounds, phase, cx);
403            })
404        }
405
406        let hover_group_bounds = stateless
407            .group_hover_style
408            .as_ref()
409            .and_then(|group_hover| GroupBounds::get(&group_hover.group, cx));
410
411        if let Some(group_bounds) = hover_group_bounds {
412            paint_hover_listener(group_bounds, cx);
413        }
414
415        if stateless.hover_style.is_some() {
416            paint_hover_listener(bounds, cx);
417        }
418
419        if let Some(stateful) = self.as_stateful() {
420            let click_listeners = stateful.mouse_click_listeners.clone();
421
422            let pending_click = element_state.pending_click.clone();
423            let mouse_down = pending_click.lock().clone();
424            if let Some(mouse_down) = mouse_down {
425                cx.on_mouse_event(move |state, event: &MouseUpEvent, phase, cx| {
426                    if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
427                        let mouse_click = MouseClickEvent {
428                            down: mouse_down.clone(),
429                            up: event.clone(),
430                        };
431                        for listener in &click_listeners {
432                            listener(state, &mouse_click, cx);
433                        }
434                    }
435
436                    *pending_click.lock() = None;
437                });
438            } else {
439                cx.on_mouse_event(move |_state, event: &MouseDownEvent, phase, _cx| {
440                    if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
441                        *pending_click.lock() = Some(event.clone());
442                    }
443                });
444            }
445
446            let active_state = element_state.active_state.clone();
447            if active_state.lock().is_none() {
448                let active_group_bounds = stateful
449                    .group_active_style
450                    .as_ref()
451                    .and_then(|group_active| GroupBounds::get(&group_active.group, cx));
452                cx.on_mouse_event(move |_view, down: &MouseDownEvent, phase, cx| {
453                    if phase == DispatchPhase::Bubble {
454                        let group = active_group_bounds
455                            .map_or(false, |bounds| bounds.contains_point(&down.position));
456                        let element = bounds.contains_point(&down.position);
457                        if group || element {
458                            *active_state.lock() = ActiveState { group, element };
459                            cx.notify();
460                        }
461                    }
462                });
463            } else {
464                cx.on_mouse_event(move |_, _: &MouseUpEvent, phase, cx| {
465                    if phase == DispatchPhase::Capture {
466                        *active_state.lock() = ActiveState::default();
467                        cx.notify();
468                    }
469                });
470            }
471        }
472    }
473}
474
475fn paint_hover_listener<V>(bounds: Bounds<Pixels>, cx: &mut ViewContext<V>)
476where
477    V: 'static + Send + Sync,
478{
479    let hovered = bounds.contains_point(&cx.mouse_position());
480    cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
481        if phase == DispatchPhase::Capture {
482            if bounds.contains_point(&event.position) != hovered {
483                cx.notify();
484            }
485        }
486    });
487}
488
489#[derive(Deref, DerefMut)]
490pub struct StatefulInteraction<V: 'static + Send + Sync> {
491    pub id: ElementId,
492    #[deref]
493    #[deref_mut]
494    stateless: StatelessInteraction<V>,
495    pub mouse_click_listeners: SmallVec<[MouseClickListener<V>; 2]>,
496    pub active_style: StyleRefinement,
497    pub group_active_style: Option<GroupStyle>,
498}
499
500impl<V> ElementInteraction<V> for StatefulInteraction<V>
501where
502    V: 'static + Send + Sync,
503{
504    fn as_stateful(&self) -> Option<&StatefulInteraction<V>> {
505        Some(self)
506    }
507
508    fn as_stateful_mut(&mut self) -> Option<&mut StatefulInteraction<V>> {
509        Some(self)
510    }
511
512    fn as_stateless(&self) -> &StatelessInteraction<V> {
513        &self.stateless
514    }
515
516    fn as_stateless_mut(&mut self) -> &mut StatelessInteraction<V> {
517        &mut self.stateless
518    }
519}
520
521impl<V> From<ElementId> for StatefulInteraction<V>
522where
523    V: 'static + Send + Sync,
524{
525    fn from(id: ElementId) -> Self {
526        Self {
527            id,
528            stateless: StatelessInteraction::default(),
529            mouse_click_listeners: SmallVec::new(),
530            active_style: StyleRefinement::default(),
531            group_active_style: None,
532        }
533    }
534}
535
536pub struct StatelessInteraction<V> {
537    pub dispatch_context: DispatchContext,
538    pub mouse_down_listeners: SmallVec<[MouseDownListener<V>; 2]>,
539    pub mouse_up_listeners: SmallVec<[MouseUpListener<V>; 2]>,
540    pub mouse_move_listeners: SmallVec<[MouseMoveListener<V>; 2]>,
541    pub scroll_wheel_listeners: SmallVec<[ScrollWheelListener<V>; 2]>,
542    pub key_listeners: SmallVec<[(TypeId, KeyListener<V>); 32]>,
543    pub hover_style: StyleRefinement,
544    pub group_hover_style: Option<GroupStyle>,
545}
546
547pub struct GroupStyle {
548    pub group: SharedString,
549    pub style: StyleRefinement,
550}
551
552#[derive(Default)]
553pub struct GroupBounds(HashMap<SharedString, SmallVec<[Bounds<Pixels>; 1]>>);
554
555impl GroupBounds {
556    pub fn get(name: &SharedString, cx: &mut AppContext) -> Option<Bounds<Pixels>> {
557        cx.default_global::<Self>()
558            .0
559            .get(name)
560            .and_then(|bounds_stack| bounds_stack.last())
561            .cloned()
562    }
563
564    pub fn push(name: SharedString, bounds: Bounds<Pixels>, cx: &mut AppContext) {
565        cx.default_global::<Self>()
566            .0
567            .entry(name)
568            .or_default()
569            .push(bounds);
570    }
571
572    pub fn pop(name: &SharedString, cx: &mut AppContext) {
573        cx.default_global::<GroupBounds>()
574            .0
575            .get_mut(name)
576            .unwrap()
577            .pop();
578    }
579}
580
581#[derive(Copy, Clone, Default, Eq, PartialEq)]
582struct ActiveState {
583    pub group: bool,
584    pub element: bool,
585}
586
587impl ActiveState {
588    pub fn is_none(&self) -> bool {
589        !self.group && !self.element
590    }
591}
592
593#[derive(Default)]
594pub struct InteractiveElementState {
595    active_state: Arc<Mutex<ActiveState>>,
596    pending_click: Arc<Mutex<Option<MouseDownEvent>>>,
597}
598
599impl<V> Default for StatelessInteraction<V> {
600    fn default() -> Self {
601        Self {
602            dispatch_context: DispatchContext::default(),
603            mouse_down_listeners: SmallVec::new(),
604            mouse_up_listeners: SmallVec::new(),
605            mouse_move_listeners: SmallVec::new(),
606            scroll_wheel_listeners: SmallVec::new(),
607            key_listeners: SmallVec::new(),
608            hover_style: StyleRefinement::default(),
609            group_hover_style: None,
610        }
611    }
612}
613
614impl<V> ElementInteraction<V> for StatelessInteraction<V>
615where
616    V: 'static + Send + Sync,
617{
618    fn as_stateful(&self) -> Option<&StatefulInteraction<V>> {
619        None
620    }
621
622    fn as_stateful_mut(&mut self) -> Option<&mut StatefulInteraction<V>> {
623        None
624    }
625
626    fn as_stateless(&self) -> &StatelessInteraction<V> {
627        self
628    }
629
630    fn as_stateless_mut(&mut self) -> &mut StatelessInteraction<V> {
631        self
632    }
633}
634
635#[derive(Clone, Debug, Eq, PartialEq)]
636pub struct KeyDownEvent {
637    pub keystroke: Keystroke,
638    pub is_held: bool,
639}
640
641#[derive(Clone, Debug)]
642pub struct KeyUpEvent {
643    pub keystroke: Keystroke,
644}
645
646#[derive(Clone, Debug, Default)]
647pub struct ModifiersChangedEvent {
648    pub modifiers: Modifiers,
649}
650
651impl Deref for ModifiersChangedEvent {
652    type Target = Modifiers;
653
654    fn deref(&self) -> &Self::Target {
655        &self.modifiers
656    }
657}
658
659/// The phase of a touch motion event.
660/// Based on the winit enum of the same name.
661#[derive(Clone, Copy, Debug)]
662pub enum TouchPhase {
663    Started,
664    Moved,
665    Ended,
666}
667
668#[derive(Clone, Debug, Default)]
669pub struct MouseDownEvent {
670    pub button: MouseButton,
671    pub position: Point<Pixels>,
672    pub modifiers: Modifiers,
673    pub click_count: usize,
674}
675
676#[derive(Clone, Debug, Default)]
677pub struct MouseUpEvent {
678    pub button: MouseButton,
679    pub position: Point<Pixels>,
680    pub modifiers: Modifiers,
681    pub click_count: usize,
682}
683
684#[derive(Clone, Debug, Default)]
685pub struct MouseClickEvent {
686    pub down: MouseDownEvent,
687    pub up: MouseUpEvent,
688}
689
690#[derive(Hash, PartialEq, Eq, Copy, Clone, Debug)]
691pub enum MouseButton {
692    Left,
693    Right,
694    Middle,
695    Navigate(NavigationDirection),
696}
697
698impl MouseButton {
699    pub fn all() -> Vec<Self> {
700        vec![
701            MouseButton::Left,
702            MouseButton::Right,
703            MouseButton::Middle,
704            MouseButton::Navigate(NavigationDirection::Back),
705            MouseButton::Navigate(NavigationDirection::Forward),
706        ]
707    }
708}
709
710impl Default for MouseButton {
711    fn default() -> Self {
712        Self::Left
713    }
714}
715
716#[derive(Hash, PartialEq, Eq, Copy, Clone, Debug)]
717pub enum NavigationDirection {
718    Back,
719    Forward,
720}
721
722impl Default for NavigationDirection {
723    fn default() -> Self {
724        Self::Back
725    }
726}
727
728#[derive(Clone, Debug, Default)]
729pub struct MouseMoveEvent {
730    pub position: Point<Pixels>,
731    pub pressed_button: Option<MouseButton>,
732    pub modifiers: Modifiers,
733}
734
735#[derive(Clone, Debug)]
736pub struct ScrollWheelEvent {
737    pub position: Point<Pixels>,
738    pub delta: ScrollDelta,
739    pub modifiers: Modifiers,
740    pub touch_phase: TouchPhase,
741}
742
743impl Deref for ScrollWheelEvent {
744    type Target = Modifiers;
745
746    fn deref(&self) -> &Self::Target {
747        &self.modifiers
748    }
749}
750
751#[derive(Clone, Copy, Debug)]
752pub enum ScrollDelta {
753    Pixels(Point<Pixels>),
754    Lines(Point<f32>),
755}
756
757impl Default for ScrollDelta {
758    fn default() -> Self {
759        Self::Lines(Default::default())
760    }
761}
762
763impl ScrollDelta {
764    pub fn precise(&self) -> bool {
765        match self {
766            ScrollDelta::Pixels(_) => true,
767            ScrollDelta::Lines(_) => false,
768        }
769    }
770
771    pub fn pixel_delta(&self, line_height: Pixels) -> Point<Pixels> {
772        match self {
773            ScrollDelta::Pixels(delta) => *delta,
774            ScrollDelta::Lines(delta) => point(line_height * delta.x, line_height * delta.y),
775        }
776    }
777}
778
779#[derive(Clone, Debug, Default)]
780pub struct MouseExitEvent {
781    pub position: Point<Pixels>,
782    pub pressed_button: Option<MouseButton>,
783    pub modifiers: Modifiers,
784}
785
786impl Deref for MouseExitEvent {
787    type Target = Modifiers;
788
789    fn deref(&self) -> &Self::Target {
790        &self.modifiers
791    }
792}
793
794#[derive(Clone, Debug)]
795pub enum InputEvent {
796    KeyDown(KeyDownEvent),
797    KeyUp(KeyUpEvent),
798    ModifiersChanged(ModifiersChangedEvent),
799    MouseDown(MouseDownEvent),
800    MouseUp(MouseUpEvent),
801    MouseMoved(MouseMoveEvent),
802    MouseExited(MouseExitEvent),
803    ScrollWheel(ScrollWheelEvent),
804}
805
806impl InputEvent {
807    pub fn position(&self) -> Option<Point<Pixels>> {
808        match self {
809            InputEvent::KeyDown { .. } => None,
810            InputEvent::KeyUp { .. } => None,
811            InputEvent::ModifiersChanged { .. } => None,
812            InputEvent::MouseDown(event) => Some(event.position),
813            InputEvent::MouseUp(event) => Some(event.position),
814            InputEvent::MouseMoved(event) => Some(event.position),
815            InputEvent::MouseExited(event) => Some(event.position),
816            InputEvent::ScrollWheel(event) => Some(event.position),
817        }
818    }
819
820    pub fn mouse_event<'a>(&'a self) -> Option<&'a dyn Any> {
821        match self {
822            InputEvent::KeyDown { .. } => None,
823            InputEvent::KeyUp { .. } => None,
824            InputEvent::ModifiersChanged { .. } => None,
825            InputEvent::MouseDown(event) => Some(event),
826            InputEvent::MouseUp(event) => Some(event),
827            InputEvent::MouseMoved(event) => Some(event),
828            InputEvent::MouseExited(event) => Some(event),
829            InputEvent::ScrollWheel(event) => Some(event),
830        }
831    }
832
833    pub fn keyboard_event<'a>(&'a self) -> Option<&'a dyn Any> {
834        match self {
835            InputEvent::KeyDown(event) => Some(event),
836            InputEvent::KeyUp(event) => Some(event),
837            InputEvent::ModifiersChanged(event) => Some(event),
838            InputEvent::MouseDown(_) => None,
839            InputEvent::MouseUp(_) => None,
840            InputEvent::MouseMoved(_) => None,
841            InputEvent::MouseExited(_) => None,
842            InputEvent::ScrollWheel(_) => None,
843        }
844    }
845}
846
847pub struct FocusEvent {
848    pub blurred: Option<FocusHandle>,
849    pub focused: Option<FocusHandle>,
850}
851
852pub type MouseDownListener<V> = Arc<
853    dyn Fn(&mut V, &MouseDownEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>)
854        + Send
855        + Sync
856        + 'static,
857>;
858pub type MouseUpListener<V> = Arc<
859    dyn Fn(&mut V, &MouseUpEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>)
860        + Send
861        + Sync
862        + 'static,
863>;
864pub type MouseClickListener<V> =
865    Arc<dyn Fn(&mut V, &MouseClickEvent, &mut ViewContext<V>) + Send + Sync + 'static>;
866
867pub type MouseMoveListener<V> = Arc<
868    dyn Fn(&mut V, &MouseMoveEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>)
869        + Send
870        + Sync
871        + 'static,
872>;
873
874pub type ScrollWheelListener<V> = Arc<
875    dyn Fn(&mut V, &ScrollWheelEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>)
876        + Send
877        + Sync
878        + 'static,
879>;
880
881pub type KeyListener<V> = Arc<
882    dyn Fn(
883            &mut V,
884            &dyn Any,
885            &[&DispatchContext],
886            DispatchPhase,
887            &mut ViewContext<V>,
888        ) -> Option<Box<dyn Action>>
889        + Send
890        + Sync
891        + 'static,
892>;