interactive.rs

  1use crate::{
  2    point, px, Action, AppContext, BorrowWindow, Bounds, DispatchContext, DispatchPhase, Element,
  3    ElementId, FocusHandle, KeyMatch, Keystroke, Modifiers, Overflow, Pixels, Point, SharedString,
  4    Size, Style, 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        content_size: Size<Pixels>,
379        overflow: Point<Overflow>,
380        element_state: &mut InteractiveElementState,
381        cx: &mut ViewContext<V>,
382    ) {
383        let stateless = self.as_stateless();
384        for listener in stateless.mouse_down_listeners.iter().cloned() {
385            cx.on_mouse_event(move |state, event: &MouseDownEvent, phase, cx| {
386                listener(state, event, &bounds, phase, cx);
387            })
388        }
389
390        for listener in stateless.mouse_up_listeners.iter().cloned() {
391            cx.on_mouse_event(move |state, event: &MouseUpEvent, phase, cx| {
392                listener(state, event, &bounds, phase, cx);
393            })
394        }
395
396        for listener in stateless.mouse_move_listeners.iter().cloned() {
397            cx.on_mouse_event(move |state, event: &MouseMoveEvent, phase, cx| {
398                listener(state, event, &bounds, phase, cx);
399            })
400        }
401
402        for listener in stateless.scroll_wheel_listeners.iter().cloned() {
403            cx.on_mouse_event(move |state, event: &ScrollWheelEvent, phase, cx| {
404                listener(state, event, &bounds, phase, cx);
405            })
406        }
407
408        let hover_group_bounds = stateless
409            .group_hover_style
410            .as_ref()
411            .and_then(|group_hover| GroupBounds::get(&group_hover.group, cx));
412
413        if let Some(group_bounds) = hover_group_bounds {
414            paint_hover_listener(group_bounds, cx);
415        }
416
417        if stateless.hover_style.is_some() {
418            paint_hover_listener(bounds, cx);
419        }
420
421        if let Some(stateful) = self.as_stateful() {
422            let click_listeners = stateful.mouse_click_listeners.clone();
423
424            let pending_click = element_state.pending_click.clone();
425            let mouse_down = pending_click.lock().clone();
426            if let Some(mouse_down) = mouse_down {
427                cx.on_mouse_event(move |state, event: &MouseUpEvent, phase, cx| {
428                    if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
429                        let mouse_click = MouseClickEvent {
430                            down: mouse_down.clone(),
431                            up: event.clone(),
432                        };
433                        for listener in &click_listeners {
434                            listener(state, &mouse_click, cx);
435                        }
436                    }
437
438                    *pending_click.lock() = None;
439                });
440            } else {
441                cx.on_mouse_event(move |_state, event: &MouseDownEvent, phase, _cx| {
442                    if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
443                        *pending_click.lock() = Some(event.clone());
444                    }
445                });
446            }
447
448            let active_state = element_state.active_state.clone();
449            if active_state.lock().is_none() {
450                let active_group_bounds = stateful
451                    .group_active_style
452                    .as_ref()
453                    .and_then(|group_active| GroupBounds::get(&group_active.group, cx));
454                cx.on_mouse_event(move |_view, down: &MouseDownEvent, phase, cx| {
455                    if phase == DispatchPhase::Bubble {
456                        let group = active_group_bounds
457                            .map_or(false, |bounds| bounds.contains_point(&down.position));
458                        let element = bounds.contains_point(&down.position);
459                        if group || element {
460                            *active_state.lock() = ActiveState { group, element };
461                            cx.notify();
462                        }
463                    }
464                });
465            } else {
466                cx.on_mouse_event(move |_, _: &MouseUpEvent, phase, cx| {
467                    if phase == DispatchPhase::Capture {
468                        *active_state.lock() = ActiveState::default();
469                        cx.notify();
470                    }
471                });
472            }
473
474            if overflow.x == Overflow::Scroll || overflow.y == Overflow::Scroll {
475                let scroll_offset = element_state
476                    .scroll_offset
477                    .get_or_insert_with(Arc::default)
478                    .clone();
479                let line_height = cx.line_height();
480                let scroll_max = (content_size - bounds.size).max(&Size::default());
481
482                cx.on_mouse_event(move |_, event: &ScrollWheelEvent, _, cx| {
483                    if bounds.contains_point(&event.position) {
484                        let mut scroll_offset = scroll_offset.lock();
485                        let delta = event.delta.pixel_delta(line_height);
486
487                        if overflow.x == Overflow::Scroll {
488                            scroll_offset.x =
489                                (scroll_offset.x - delta.x).clamp(px(0.), scroll_max.width);
490                        }
491
492                        if overflow.y == Overflow::Scroll {
493                            scroll_offset.y =
494                                (scroll_offset.y - delta.y).clamp(px(0.), scroll_max.height);
495                        }
496
497                        cx.notify();
498                    }
499                });
500            }
501        }
502    }
503}
504
505fn paint_hover_listener<V>(bounds: Bounds<Pixels>, cx: &mut ViewContext<V>)
506where
507    V: 'static + Send + Sync,
508{
509    let hovered = bounds.contains_point(&cx.mouse_position());
510    cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
511        if phase == DispatchPhase::Capture {
512            if bounds.contains_point(&event.position) != hovered {
513                cx.notify();
514            }
515        }
516    });
517}
518
519#[derive(Deref, DerefMut)]
520pub struct StatefulInteraction<V: 'static + Send + Sync> {
521    pub id: ElementId,
522    #[deref]
523    #[deref_mut]
524    stateless: StatelessInteraction<V>,
525    pub mouse_click_listeners: SmallVec<[MouseClickListener<V>; 2]>,
526    pub active_style: StyleRefinement,
527    pub group_active_style: Option<GroupStyle>,
528}
529
530impl<V> ElementInteraction<V> for StatefulInteraction<V>
531where
532    V: 'static + Send + Sync,
533{
534    fn as_stateful(&self) -> Option<&StatefulInteraction<V>> {
535        Some(self)
536    }
537
538    fn as_stateful_mut(&mut self) -> Option<&mut StatefulInteraction<V>> {
539        Some(self)
540    }
541
542    fn as_stateless(&self) -> &StatelessInteraction<V> {
543        &self.stateless
544    }
545
546    fn as_stateless_mut(&mut self) -> &mut StatelessInteraction<V> {
547        &mut self.stateless
548    }
549}
550
551impl<V> From<ElementId> for StatefulInteraction<V>
552where
553    V: 'static + Send + Sync,
554{
555    fn from(id: ElementId) -> Self {
556        Self {
557            id,
558            stateless: StatelessInteraction::default(),
559            mouse_click_listeners: SmallVec::new(),
560            active_style: StyleRefinement::default(),
561            group_active_style: None,
562        }
563    }
564}
565
566pub struct StatelessInteraction<V> {
567    pub dispatch_context: DispatchContext,
568    pub mouse_down_listeners: SmallVec<[MouseDownListener<V>; 2]>,
569    pub mouse_up_listeners: SmallVec<[MouseUpListener<V>; 2]>,
570    pub mouse_move_listeners: SmallVec<[MouseMoveListener<V>; 2]>,
571    pub scroll_wheel_listeners: SmallVec<[ScrollWheelListener<V>; 2]>,
572    pub key_listeners: SmallVec<[(TypeId, KeyListener<V>); 32]>,
573    pub hover_style: StyleRefinement,
574    pub group_hover_style: Option<GroupStyle>,
575}
576
577impl<V> StatelessInteraction<V>
578where
579    V: 'static + Send + Sync,
580{
581    pub fn into_stateful(self, id: impl Into<ElementId>) -> StatefulInteraction<V> {
582        StatefulInteraction {
583            id: id.into(),
584            stateless: self,
585            mouse_click_listeners: SmallVec::new(),
586            active_style: StyleRefinement::default(),
587            group_active_style: None,
588        }
589    }
590}
591
592pub struct GroupStyle {
593    pub group: SharedString,
594    pub style: StyleRefinement,
595}
596
597#[derive(Default)]
598pub struct GroupBounds(HashMap<SharedString, SmallVec<[Bounds<Pixels>; 1]>>);
599
600impl GroupBounds {
601    pub fn get(name: &SharedString, cx: &mut AppContext) -> Option<Bounds<Pixels>> {
602        cx.default_global::<Self>()
603            .0
604            .get(name)
605            .and_then(|bounds_stack| bounds_stack.last())
606            .cloned()
607    }
608
609    pub fn push(name: SharedString, bounds: Bounds<Pixels>, cx: &mut AppContext) {
610        cx.default_global::<Self>()
611            .0
612            .entry(name)
613            .or_default()
614            .push(bounds);
615    }
616
617    pub fn pop(name: &SharedString, cx: &mut AppContext) {
618        cx.default_global::<GroupBounds>()
619            .0
620            .get_mut(name)
621            .unwrap()
622            .pop();
623    }
624}
625
626#[derive(Copy, Clone, Default, Eq, PartialEq)]
627struct ActiveState {
628    pub group: bool,
629    pub element: bool,
630}
631
632impl ActiveState {
633    pub fn is_none(&self) -> bool {
634        !self.group && !self.element
635    }
636}
637
638#[derive(Default)]
639pub struct InteractiveElementState {
640    active_state: Arc<Mutex<ActiveState>>,
641    pending_click: Arc<Mutex<Option<MouseDownEvent>>>,
642    scroll_offset: Option<Arc<Mutex<Point<Pixels>>>>,
643}
644
645impl InteractiveElementState {
646    pub fn scroll_offset(&self) -> Option<Point<Pixels>> {
647        self.scroll_offset
648            .as_ref()
649            .map(|offset| offset.lock().clone())
650    }
651}
652
653impl<V> Default for StatelessInteraction<V> {
654    fn default() -> Self {
655        Self {
656            dispatch_context: DispatchContext::default(),
657            mouse_down_listeners: SmallVec::new(),
658            mouse_up_listeners: SmallVec::new(),
659            mouse_move_listeners: SmallVec::new(),
660            scroll_wheel_listeners: SmallVec::new(),
661            key_listeners: SmallVec::new(),
662            hover_style: StyleRefinement::default(),
663            group_hover_style: None,
664        }
665    }
666}
667
668impl<V> ElementInteraction<V> for StatelessInteraction<V>
669where
670    V: 'static + Send + Sync,
671{
672    fn as_stateful(&self) -> Option<&StatefulInteraction<V>> {
673        None
674    }
675
676    fn as_stateful_mut(&mut self) -> Option<&mut StatefulInteraction<V>> {
677        None
678    }
679
680    fn as_stateless(&self) -> &StatelessInteraction<V> {
681        self
682    }
683
684    fn as_stateless_mut(&mut self) -> &mut StatelessInteraction<V> {
685        self
686    }
687}
688
689#[derive(Clone, Debug, Eq, PartialEq)]
690pub struct KeyDownEvent {
691    pub keystroke: Keystroke,
692    pub is_held: bool,
693}
694
695#[derive(Clone, Debug)]
696pub struct KeyUpEvent {
697    pub keystroke: Keystroke,
698}
699
700#[derive(Clone, Debug, Default)]
701pub struct ModifiersChangedEvent {
702    pub modifiers: Modifiers,
703}
704
705impl Deref for ModifiersChangedEvent {
706    type Target = Modifiers;
707
708    fn deref(&self) -> &Self::Target {
709        &self.modifiers
710    }
711}
712
713/// The phase of a touch motion event.
714/// Based on the winit enum of the same name.
715#[derive(Clone, Copy, Debug)]
716pub enum TouchPhase {
717    Started,
718    Moved,
719    Ended,
720}
721
722#[derive(Clone, Debug, Default)]
723pub struct MouseDownEvent {
724    pub button: MouseButton,
725    pub position: Point<Pixels>,
726    pub modifiers: Modifiers,
727    pub click_count: usize,
728}
729
730#[derive(Clone, Debug, Default)]
731pub struct MouseUpEvent {
732    pub button: MouseButton,
733    pub position: Point<Pixels>,
734    pub modifiers: Modifiers,
735    pub click_count: usize,
736}
737
738#[derive(Clone, Debug, Default)]
739pub struct MouseClickEvent {
740    pub down: MouseDownEvent,
741    pub up: MouseUpEvent,
742}
743
744#[derive(Hash, PartialEq, Eq, Copy, Clone, Debug)]
745pub enum MouseButton {
746    Left,
747    Right,
748    Middle,
749    Navigate(NavigationDirection),
750}
751
752impl MouseButton {
753    pub fn all() -> Vec<Self> {
754        vec![
755            MouseButton::Left,
756            MouseButton::Right,
757            MouseButton::Middle,
758            MouseButton::Navigate(NavigationDirection::Back),
759            MouseButton::Navigate(NavigationDirection::Forward),
760        ]
761    }
762}
763
764impl Default for MouseButton {
765    fn default() -> Self {
766        Self::Left
767    }
768}
769
770#[derive(Hash, PartialEq, Eq, Copy, Clone, Debug)]
771pub enum NavigationDirection {
772    Back,
773    Forward,
774}
775
776impl Default for NavigationDirection {
777    fn default() -> Self {
778        Self::Back
779    }
780}
781
782#[derive(Clone, Debug, Default)]
783pub struct MouseMoveEvent {
784    pub position: Point<Pixels>,
785    pub pressed_button: Option<MouseButton>,
786    pub modifiers: Modifiers,
787}
788
789#[derive(Clone, Debug)]
790pub struct ScrollWheelEvent {
791    pub position: Point<Pixels>,
792    pub delta: ScrollDelta,
793    pub modifiers: Modifiers,
794    pub touch_phase: TouchPhase,
795}
796
797impl Deref for ScrollWheelEvent {
798    type Target = Modifiers;
799
800    fn deref(&self) -> &Self::Target {
801        &self.modifiers
802    }
803}
804
805#[derive(Clone, Copy, Debug)]
806pub enum ScrollDelta {
807    Pixels(Point<Pixels>),
808    Lines(Point<f32>),
809}
810
811impl Default for ScrollDelta {
812    fn default() -> Self {
813        Self::Lines(Default::default())
814    }
815}
816
817impl ScrollDelta {
818    pub fn precise(&self) -> bool {
819        match self {
820            ScrollDelta::Pixels(_) => true,
821            ScrollDelta::Lines(_) => false,
822        }
823    }
824
825    pub fn pixel_delta(&self, line_height: Pixels) -> Point<Pixels> {
826        match self {
827            ScrollDelta::Pixels(delta) => *delta,
828            ScrollDelta::Lines(delta) => point(line_height * delta.x, line_height * delta.y),
829        }
830    }
831}
832
833#[derive(Clone, Debug, Default)]
834pub struct MouseExitEvent {
835    pub position: Point<Pixels>,
836    pub pressed_button: Option<MouseButton>,
837    pub modifiers: Modifiers,
838}
839
840impl Deref for MouseExitEvent {
841    type Target = Modifiers;
842
843    fn deref(&self) -> &Self::Target {
844        &self.modifiers
845    }
846}
847
848#[derive(Clone, Debug)]
849pub enum InputEvent {
850    KeyDown(KeyDownEvent),
851    KeyUp(KeyUpEvent),
852    ModifiersChanged(ModifiersChangedEvent),
853    MouseDown(MouseDownEvent),
854    MouseUp(MouseUpEvent),
855    MouseMoved(MouseMoveEvent),
856    MouseExited(MouseExitEvent),
857    ScrollWheel(ScrollWheelEvent),
858}
859
860impl InputEvent {
861    pub fn position(&self) -> Option<Point<Pixels>> {
862        match self {
863            InputEvent::KeyDown { .. } => None,
864            InputEvent::KeyUp { .. } => None,
865            InputEvent::ModifiersChanged { .. } => None,
866            InputEvent::MouseDown(event) => Some(event.position),
867            InputEvent::MouseUp(event) => Some(event.position),
868            InputEvent::MouseMoved(event) => Some(event.position),
869            InputEvent::MouseExited(event) => Some(event.position),
870            InputEvent::ScrollWheel(event) => Some(event.position),
871        }
872    }
873
874    pub fn mouse_event<'a>(&'a self) -> Option<&'a dyn Any> {
875        match self {
876            InputEvent::KeyDown { .. } => None,
877            InputEvent::KeyUp { .. } => None,
878            InputEvent::ModifiersChanged { .. } => None,
879            InputEvent::MouseDown(event) => Some(event),
880            InputEvent::MouseUp(event) => Some(event),
881            InputEvent::MouseMoved(event) => Some(event),
882            InputEvent::MouseExited(event) => Some(event),
883            InputEvent::ScrollWheel(event) => Some(event),
884        }
885    }
886
887    pub fn keyboard_event<'a>(&'a self) -> Option<&'a dyn Any> {
888        match self {
889            InputEvent::KeyDown(event) => Some(event),
890            InputEvent::KeyUp(event) => Some(event),
891            InputEvent::ModifiersChanged(event) => Some(event),
892            InputEvent::MouseDown(_) => None,
893            InputEvent::MouseUp(_) => None,
894            InputEvent::MouseMoved(_) => None,
895            InputEvent::MouseExited(_) => None,
896            InputEvent::ScrollWheel(_) => None,
897        }
898    }
899}
900
901pub struct FocusEvent {
902    pub blurred: Option<FocusHandle>,
903    pub focused: Option<FocusHandle>,
904}
905
906pub type MouseDownListener<V> = Arc<
907    dyn Fn(&mut V, &MouseDownEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>)
908        + Send
909        + Sync
910        + 'static,
911>;
912pub type MouseUpListener<V> = Arc<
913    dyn Fn(&mut V, &MouseUpEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>)
914        + Send
915        + Sync
916        + 'static,
917>;
918pub type MouseClickListener<V> =
919    Arc<dyn Fn(&mut V, &MouseClickEvent, &mut ViewContext<V>) + Send + Sync + 'static>;
920
921pub type MouseMoveListener<V> = Arc<
922    dyn Fn(&mut V, &MouseMoveEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>)
923        + Send
924        + Sync
925        + 'static,
926>;
927
928pub type ScrollWheelListener<V> = Arc<
929    dyn Fn(&mut V, &ScrollWheelEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>)
930        + Send
931        + Sync
932        + 'static,
933>;
934
935pub type KeyListener<V> = Arc<
936    dyn Fn(
937            &mut V,
938            &dyn Any,
939            &[&DispatchContext],
940            DispatchPhase,
941            &mut ViewContext<V>,
942        ) -> Option<Box<dyn Action>>
943        + Send
944        + Sync
945        + 'static,
946>;