interactive.rs

   1use crate::{
   2    div, point, px, Action, AnyDrag, AnyTooltip, AnyView, AppContext, BorrowWindow, Bounds,
   3    Component, DispatchContext, DispatchPhase, Div, Element, ElementId, FocusHandle, KeyMatch,
   4    Keystroke, Modifiers, Overflow, Pixels, Point, Render, SharedString, Size, Style,
   5    StyleRefinement, Task, View, ViewContext,
   6};
   7use collections::HashMap;
   8use derive_more::{Deref, DerefMut};
   9use parking_lot::Mutex;
  10use refineable::Refineable;
  11use smallvec::SmallVec;
  12use std::{
  13    any::{Any, TypeId},
  14    fmt::Debug,
  15    marker::PhantomData,
  16    mem,
  17    ops::Deref,
  18    path::PathBuf,
  19    sync::Arc,
  20    time::Duration,
  21};
  22
  23const DRAG_THRESHOLD: f64 = 2.;
  24const TOOLTIP_DELAY: Duration = Duration::from_millis(500);
  25const TOOLTIP_OFFSET: Point<Pixels> = Point::new(px(10.0), px(8.0));
  26
  27pub trait StatelessInteractive<V: 'static>: Element<V> {
  28    fn stateless_interactivity(&mut self) -> &mut StatelessInteractivity<V>;
  29
  30    fn hover(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
  31    where
  32        Self: Sized,
  33    {
  34        self.stateless_interactivity().hover_style = f(StyleRefinement::default());
  35        self
  36    }
  37
  38    fn group_hover(
  39        mut self,
  40        group_name: impl Into<SharedString>,
  41        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
  42    ) -> Self
  43    where
  44        Self: Sized,
  45    {
  46        self.stateless_interactivity().group_hover_style = Some(GroupStyle {
  47            group: group_name.into(),
  48            style: f(StyleRefinement::default()),
  49        });
  50        self
  51    }
  52
  53    fn on_mouse_down(
  54        mut self,
  55        button: MouseButton,
  56        handler: impl Fn(&mut V, &MouseDownEvent, &mut ViewContext<V>) + 'static,
  57    ) -> Self
  58    where
  59        Self: Sized,
  60    {
  61        self.stateless_interactivity()
  62            .mouse_down_listeners
  63            .push(Box::new(move |view, event, bounds, phase, cx| {
  64                if phase == DispatchPhase::Bubble
  65                    && event.button == button
  66                    && bounds.contains_point(&event.position)
  67                {
  68                    handler(view, event, cx)
  69                }
  70            }));
  71        self
  72    }
  73
  74    fn on_mouse_up(
  75        mut self,
  76        button: MouseButton,
  77        handler: impl Fn(&mut V, &MouseUpEvent, &mut ViewContext<V>) + 'static,
  78    ) -> Self
  79    where
  80        Self: Sized,
  81    {
  82        self.stateless_interactivity()
  83            .mouse_up_listeners
  84            .push(Box::new(move |view, event, bounds, phase, cx| {
  85                if phase == DispatchPhase::Bubble
  86                    && event.button == button
  87                    && bounds.contains_point(&event.position)
  88                {
  89                    handler(view, event, cx)
  90                }
  91            }));
  92        self
  93    }
  94
  95    fn on_mouse_down_out(
  96        mut self,
  97        button: MouseButton,
  98        handler: impl Fn(&mut V, &MouseDownEvent, &mut ViewContext<V>) + 'static,
  99    ) -> Self
 100    where
 101        Self: Sized,
 102    {
 103        self.stateless_interactivity()
 104            .mouse_down_listeners
 105            .push(Box::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 V, &MouseUpEvent, &mut ViewContext<V>) + 'static,
 120    ) -> Self
 121    where
 122        Self: Sized,
 123    {
 124        self.stateless_interactivity()
 125            .mouse_up_listeners
 126            .push(Box::new(move |view, event, bounds, phase, cx| {
 127                if phase == DispatchPhase::Capture
 128                    && event.button == button
 129                    && !bounds.contains_point(&event.position)
 130                {
 131                    handler(view, event, cx);
 132                }
 133            }));
 134        self
 135    }
 136
 137    fn on_mouse_move(
 138        mut self,
 139        handler: impl Fn(&mut V, &MouseMoveEvent, &mut ViewContext<V>) + 'static,
 140    ) -> Self
 141    where
 142        Self: Sized,
 143    {
 144        self.stateless_interactivity()
 145            .mouse_move_listeners
 146            .push(Box::new(move |view, event, bounds, phase, cx| {
 147                if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
 148                    handler(view, event, cx);
 149                }
 150            }));
 151        self
 152    }
 153
 154    fn on_scroll_wheel(
 155        mut self,
 156        handler: impl Fn(&mut V, &ScrollWheelEvent, &mut ViewContext<V>) + 'static,
 157    ) -> Self
 158    where
 159        Self: Sized,
 160    {
 161        self.stateless_interactivity()
 162            .scroll_wheel_listeners
 163            .push(Box::new(move |view, event, bounds, phase, cx| {
 164                if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
 165                    handler(view, event, cx);
 166                }
 167            }));
 168        self
 169    }
 170
 171    fn context<C>(mut self, context: C) -> Self
 172    where
 173        Self: Sized,
 174        C: TryInto<DispatchContext>,
 175        C::Error: Debug,
 176    {
 177        self.stateless_interactivity().dispatch_context =
 178            context.try_into().expect("invalid dispatch context");
 179        self
 180    }
 181
 182    /// Capture the given action, fires during the capture phase
 183    fn capture_action<A: 'static>(
 184        mut self,
 185        listener: impl Fn(&mut V, &A, &mut ViewContext<V>) + 'static,
 186    ) -> Self
 187    where
 188        Self: Sized,
 189    {
 190        self.stateless_interactivity().key_listeners.push((
 191            TypeId::of::<A>(),
 192            Box::new(move |view, action, _dipatch_context, phase, cx| {
 193                let action = action.downcast_ref().unwrap();
 194                if phase == DispatchPhase::Capture {
 195                    listener(view, action, cx)
 196                }
 197                None
 198            }),
 199        ));
 200        self
 201    }
 202
 203    /// Add a listener for the given action, fires during the bubble event phase
 204    fn on_action<A: 'static>(
 205        mut self,
 206        listener: impl Fn(&mut V, &A, &mut ViewContext<V>) + 'static,
 207    ) -> Self
 208    where
 209        Self: Sized,
 210    {
 211        self.stateless_interactivity().key_listeners.push((
 212            TypeId::of::<A>(),
 213            Box::new(move |view, action, _dispatch_context, phase, cx| {
 214                let action = action.downcast_ref().unwrap();
 215                if phase == DispatchPhase::Bubble {
 216                    listener(view, action, cx)
 217                }
 218
 219                None
 220            }),
 221        ));
 222        self
 223    }
 224
 225    fn on_key_down(
 226        mut self,
 227        listener: impl Fn(&mut V, &KeyDownEvent, DispatchPhase, &mut ViewContext<V>) + 'static,
 228    ) -> Self
 229    where
 230        Self: Sized,
 231    {
 232        self.stateless_interactivity().key_listeners.push((
 233            TypeId::of::<KeyDownEvent>(),
 234            Box::new(move |view, event, _, phase, cx| {
 235                let event = event.downcast_ref().unwrap();
 236                listener(view, event, phase, cx);
 237                None
 238            }),
 239        ));
 240        self
 241    }
 242
 243    fn on_key_up(
 244        mut self,
 245        listener: impl Fn(&mut V, &KeyUpEvent, DispatchPhase, &mut ViewContext<V>) + 'static,
 246    ) -> Self
 247    where
 248        Self: Sized,
 249    {
 250        self.stateless_interactivity().key_listeners.push((
 251            TypeId::of::<KeyUpEvent>(),
 252            Box::new(move |view, event, _, phase, cx| {
 253                let event = event.downcast_ref().unwrap();
 254                listener(view, event, phase, cx);
 255                None
 256            }),
 257        ));
 258        self
 259    }
 260
 261    fn drag_over<S: 'static>(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
 262    where
 263        Self: Sized,
 264    {
 265        self.stateless_interactivity()
 266            .drag_over_styles
 267            .push((TypeId::of::<S>(), f(StyleRefinement::default())));
 268        self
 269    }
 270
 271    fn group_drag_over<S: 'static>(
 272        mut self,
 273        group_name: impl Into<SharedString>,
 274        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
 275    ) -> Self
 276    where
 277        Self: Sized,
 278    {
 279        self.stateless_interactivity().group_drag_over_styles.push((
 280            TypeId::of::<S>(),
 281            GroupStyle {
 282                group: group_name.into(),
 283                style: f(StyleRefinement::default()),
 284            },
 285        ));
 286        self
 287    }
 288
 289    fn on_drop<W: 'static>(
 290        mut self,
 291        listener: impl Fn(&mut V, View<W>, &mut ViewContext<V>) + 'static,
 292    ) -> Self
 293    where
 294        Self: Sized,
 295    {
 296        self.stateless_interactivity().drop_listeners.push((
 297            TypeId::of::<W>(),
 298            Box::new(move |view, dragged_view, cx| {
 299                listener(view, dragged_view.downcast().unwrap(), cx);
 300            }),
 301        ));
 302        self
 303    }
 304}
 305
 306pub trait StatefulInteractive<V: 'static>: StatelessInteractive<V> {
 307    fn stateful_interactivity(&mut self) -> &mut StatefulInteractivity<V>;
 308
 309    fn active(mut self, f: impl FnOnce(StyleRefinement) -> StyleRefinement) -> Self
 310    where
 311        Self: Sized,
 312    {
 313        self.stateful_interactivity().active_style = f(StyleRefinement::default());
 314        self
 315    }
 316
 317    fn group_active(
 318        mut self,
 319        group_name: impl Into<SharedString>,
 320        f: impl FnOnce(StyleRefinement) -> StyleRefinement,
 321    ) -> Self
 322    where
 323        Self: Sized,
 324    {
 325        self.stateful_interactivity().group_active_style = Some(GroupStyle {
 326            group: group_name.into(),
 327            style: f(StyleRefinement::default()),
 328        });
 329        self
 330    }
 331
 332    fn on_click(
 333        mut self,
 334        listener: impl Fn(&mut V, &ClickEvent, &mut ViewContext<V>) + 'static,
 335    ) -> Self
 336    where
 337        Self: Sized,
 338    {
 339        self.stateful_interactivity()
 340            .click_listeners
 341            .push(Box::new(move |view, event, cx| listener(view, event, cx)));
 342        self
 343    }
 344
 345    fn on_drag<W>(
 346        mut self,
 347        listener: impl Fn(&mut V, &mut ViewContext<V>) -> View<W> + 'static,
 348    ) -> Self
 349    where
 350        Self: Sized,
 351        W: 'static + Render,
 352    {
 353        debug_assert!(
 354            self.stateful_interactivity().drag_listener.is_none(),
 355            "calling on_drag more than once on the same element is not supported"
 356        );
 357        self.stateful_interactivity().drag_listener =
 358            Some(Box::new(move |view_state, cursor_offset, cx| AnyDrag {
 359                view: listener(view_state, cx).into(),
 360                cursor_offset,
 361            }));
 362        self
 363    }
 364
 365    fn on_hover(mut self, listener: impl 'static + Fn(&mut V, bool, &mut ViewContext<V>)) -> Self
 366    where
 367        Self: Sized,
 368    {
 369        debug_assert!(
 370            self.stateful_interactivity().hover_listener.is_none(),
 371            "calling on_hover more than once on the same element is not supported"
 372        );
 373        self.stateful_interactivity().hover_listener = Some(Box::new(listener));
 374        self
 375    }
 376
 377    fn tooltip<W>(
 378        mut self,
 379        build_tooltip: impl Fn(&mut V, &mut ViewContext<V>) -> View<W> + 'static,
 380    ) -> Self
 381    where
 382        Self: Sized,
 383        W: 'static + Render,
 384    {
 385        debug_assert!(
 386            self.stateful_interactivity().tooltip_builder.is_none(),
 387            "calling tooltip more than once on the same element is not supported"
 388        );
 389        self.stateful_interactivity().tooltip_builder = Some(Arc::new(move |view_state, cx| {
 390            build_tooltip(view_state, cx).into()
 391        }));
 392
 393        self
 394    }
 395}
 396
 397pub trait ElementInteractivity<V: 'static>: 'static {
 398    fn as_stateless(&self) -> &StatelessInteractivity<V>;
 399    fn as_stateless_mut(&mut self) -> &mut StatelessInteractivity<V>;
 400    fn as_stateful(&self) -> Option<&StatefulInteractivity<V>>;
 401    fn as_stateful_mut(&mut self) -> Option<&mut StatefulInteractivity<V>>;
 402
 403    fn initialize<R>(
 404        &mut self,
 405        cx: &mut ViewContext<V>,
 406        f: impl FnOnce(&mut ViewContext<V>) -> R,
 407    ) -> R {
 408        if let Some(stateful) = self.as_stateful_mut() {
 409            cx.with_element_id(stateful.id.clone(), |global_id, cx| {
 410                // In addition to any key down/up listeners registered directly on the element,
 411                // we also add a key listener to match actions from the keymap.
 412                stateful.key_listeners.push((
 413                    TypeId::of::<KeyDownEvent>(),
 414                    Box::new(move |_, key_down, context, phase, cx| {
 415                        if phase == DispatchPhase::Bubble {
 416                            let key_down = key_down.downcast_ref::<KeyDownEvent>().unwrap();
 417                            if let KeyMatch::Some(action) =
 418                                cx.match_keystroke(&global_id, &key_down.keystroke, context)
 419                            {
 420                                return Some(action);
 421                            }
 422                        }
 423
 424                        None
 425                    }),
 426                ));
 427
 428                cx.with_key_dispatch_context(stateful.dispatch_context.clone(), |cx| {
 429                    cx.with_key_listeners(mem::take(&mut stateful.key_listeners), f)
 430                })
 431            })
 432        } else {
 433            let stateless = self.as_stateless_mut();
 434            cx.with_key_dispatch_context(stateless.dispatch_context.clone(), |cx| {
 435                cx.with_key_listeners(mem::take(&mut stateless.key_listeners), f)
 436            })
 437        }
 438    }
 439
 440    fn refine_style(
 441        &self,
 442        style: &mut Style,
 443        bounds: Bounds<Pixels>,
 444        element_state: &InteractiveElementState,
 445        cx: &mut ViewContext<V>,
 446    ) {
 447        let mouse_position = cx.mouse_position();
 448        let stateless = self.as_stateless();
 449        if let Some(group_hover) = stateless.group_hover_style.as_ref() {
 450            if let Some(group_bounds) = GroupBounds::get(&group_hover.group, cx) {
 451                if group_bounds.contains_point(&mouse_position) {
 452                    style.refine(&group_hover.style);
 453                }
 454            }
 455        }
 456        if bounds.contains_point(&mouse_position) {
 457            style.refine(&stateless.hover_style);
 458        }
 459
 460        if let Some(drag) = cx.active_drag.take() {
 461            for (state_type, group_drag_style) in &self.as_stateless().group_drag_over_styles {
 462                if let Some(group_bounds) = GroupBounds::get(&group_drag_style.group, cx) {
 463                    if *state_type == drag.view.entity_type()
 464                        && group_bounds.contains_point(&mouse_position)
 465                    {
 466                        style.refine(&group_drag_style.style);
 467                    }
 468                }
 469            }
 470
 471            for (state_type, drag_over_style) in &self.as_stateless().drag_over_styles {
 472                if *state_type == drag.view.entity_type() && bounds.contains_point(&mouse_position)
 473                {
 474                    style.refine(drag_over_style);
 475                }
 476            }
 477
 478            cx.active_drag = Some(drag);
 479        }
 480
 481        if let Some(stateful) = self.as_stateful() {
 482            let active_state = element_state.active_state.lock();
 483            if active_state.group {
 484                if let Some(group_style) = stateful.group_active_style.as_ref() {
 485                    style.refine(&group_style.style);
 486                }
 487            }
 488            if active_state.element {
 489                style.refine(&stateful.active_style);
 490            }
 491        }
 492    }
 493
 494    fn paint(
 495        &mut self,
 496        bounds: Bounds<Pixels>,
 497        content_size: Size<Pixels>,
 498        overflow: Point<Overflow>,
 499        element_state: &mut InteractiveElementState,
 500        cx: &mut ViewContext<V>,
 501    ) {
 502        let stateless = self.as_stateless_mut();
 503        for listener in stateless.mouse_down_listeners.drain(..) {
 504            cx.on_mouse_event(move |state, event: &MouseDownEvent, phase, cx| {
 505                listener(state, event, &bounds, phase, cx);
 506            })
 507        }
 508
 509        for listener in stateless.mouse_up_listeners.drain(..) {
 510            cx.on_mouse_event(move |state, event: &MouseUpEvent, phase, cx| {
 511                listener(state, event, &bounds, phase, cx);
 512            })
 513        }
 514
 515        for listener in stateless.mouse_move_listeners.drain(..) {
 516            cx.on_mouse_event(move |state, event: &MouseMoveEvent, phase, cx| {
 517                listener(state, event, &bounds, phase, cx);
 518            })
 519        }
 520
 521        for listener in stateless.scroll_wheel_listeners.drain(..) {
 522            cx.on_mouse_event(move |state, event: &ScrollWheelEvent, phase, cx| {
 523                listener(state, event, &bounds, phase, cx);
 524            })
 525        }
 526
 527        let hover_group_bounds = stateless
 528            .group_hover_style
 529            .as_ref()
 530            .and_then(|group_hover| GroupBounds::get(&group_hover.group, cx));
 531
 532        if let Some(group_bounds) = hover_group_bounds {
 533            let hovered = group_bounds.contains_point(&cx.mouse_position());
 534            cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
 535                if phase == DispatchPhase::Capture {
 536                    if group_bounds.contains_point(&event.position) != hovered {
 537                        cx.notify();
 538                    }
 539                }
 540            });
 541        }
 542
 543        if stateless.hover_style.is_some()
 544            || (cx.active_drag.is_some() && !stateless.drag_over_styles.is_empty())
 545        {
 546            let hovered = bounds.contains_point(&cx.mouse_position());
 547            cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
 548                if phase == DispatchPhase::Capture {
 549                    if bounds.contains_point(&event.position) != hovered {
 550                        cx.notify();
 551                    }
 552                }
 553            });
 554        }
 555
 556        if cx.active_drag.is_some() {
 557            let drop_listeners = mem::take(&mut stateless.drop_listeners);
 558            cx.on_mouse_event(move |view, event: &MouseUpEvent, phase, cx| {
 559                if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
 560                    if let Some(drag_state_type) =
 561                        cx.active_drag.as_ref().map(|drag| drag.view.entity_type())
 562                    {
 563                        for (drop_state_type, listener) in &drop_listeners {
 564                            if *drop_state_type == drag_state_type {
 565                                let drag = cx
 566                                    .active_drag
 567                                    .take()
 568                                    .expect("checked for type drag state type above");
 569                                listener(view, drag.view.clone(), cx);
 570                                cx.notify();
 571                                cx.stop_propagation();
 572                            }
 573                        }
 574                    }
 575                }
 576            });
 577        }
 578
 579        if let Some(stateful) = self.as_stateful_mut() {
 580            let click_listeners = mem::take(&mut stateful.click_listeners);
 581            let drag_listener = mem::take(&mut stateful.drag_listener);
 582
 583            if !click_listeners.is_empty() || drag_listener.is_some() {
 584                let pending_mouse_down = element_state.pending_mouse_down.clone();
 585                let mouse_down = pending_mouse_down.lock().clone();
 586                if let Some(mouse_down) = mouse_down {
 587                    if let Some(drag_listener) = drag_listener {
 588                        let active_state = element_state.active_state.clone();
 589
 590                        cx.on_mouse_event(move |view_state, event: &MouseMoveEvent, phase, cx| {
 591                            if cx.active_drag.is_some() {
 592                                if phase == DispatchPhase::Capture {
 593                                    cx.notify();
 594                                }
 595                            } else if phase == DispatchPhase::Bubble
 596                                && bounds.contains_point(&event.position)
 597                                && (event.position - mouse_down.position).magnitude()
 598                                    > DRAG_THRESHOLD
 599                            {
 600                                *active_state.lock() = ActiveState::default();
 601                                let cursor_offset = event.position - bounds.origin;
 602                                let drag = drag_listener(view_state, cursor_offset, cx);
 603                                cx.active_drag = Some(drag);
 604                                cx.notify();
 605                                cx.stop_propagation();
 606                            }
 607                        });
 608                    }
 609
 610                    cx.on_mouse_event(move |view_state, event: &MouseUpEvent, phase, cx| {
 611                        if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position)
 612                        {
 613                            let mouse_click = ClickEvent {
 614                                down: mouse_down.clone(),
 615                                up: event.clone(),
 616                            };
 617                            for listener in &click_listeners {
 618                                listener(view_state, &mouse_click, cx);
 619                            }
 620                        }
 621                        *pending_mouse_down.lock() = None;
 622                    });
 623                } else {
 624                    cx.on_mouse_event(move |_state, event: &MouseDownEvent, phase, _cx| {
 625                        if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position)
 626                        {
 627                            *pending_mouse_down.lock() = Some(event.clone());
 628                        }
 629                    });
 630                }
 631            }
 632
 633            if let Some(hover_listener) = stateful.hover_listener.take() {
 634                let was_hovered = element_state.hover_state.clone();
 635                let has_mouse_down = element_state.pending_mouse_down.clone();
 636
 637                cx.on_mouse_event(move |view_state, event: &MouseMoveEvent, phase, cx| {
 638                    if phase != DispatchPhase::Bubble {
 639                        return;
 640                    }
 641                    let is_hovered =
 642                        bounds.contains_point(&event.position) && has_mouse_down.lock().is_none();
 643                    let mut was_hovered = was_hovered.lock();
 644
 645                    if is_hovered != was_hovered.clone() {
 646                        *was_hovered = is_hovered;
 647                        drop(was_hovered);
 648
 649                        hover_listener(view_state, is_hovered, cx);
 650                    }
 651                });
 652            }
 653
 654            if let Some(tooltip_builder) = stateful.tooltip_builder.take() {
 655                let active_tooltip = element_state.active_tooltip.clone();
 656                let pending_mouse_down = element_state.pending_mouse_down.clone();
 657
 658                cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
 659                    if phase != DispatchPhase::Bubble {
 660                        return;
 661                    }
 662
 663                    let is_hovered = bounds.contains_point(&event.position)
 664                        && pending_mouse_down.lock().is_none();
 665                    if !is_hovered {
 666                        active_tooltip.lock().take();
 667                        return;
 668                    }
 669
 670                    if active_tooltip.lock().is_none() {
 671                        let task = cx.spawn({
 672                            let active_tooltip = active_tooltip.clone();
 673                            let tooltip_builder = tooltip_builder.clone();
 674
 675                            move |view, mut cx| async move {
 676                                cx.background_executor().timer(TOOLTIP_DELAY).await;
 677                                view.update(&mut cx, move |view_state, cx| {
 678                                    active_tooltip.lock().replace(ActiveTooltip {
 679                                        waiting: None,
 680                                        tooltip: Some(AnyTooltip {
 681                                            view: tooltip_builder(view_state, cx),
 682                                            cursor_offset: cx.mouse_position() + TOOLTIP_OFFSET,
 683                                        }),
 684                                    });
 685                                    cx.notify();
 686                                })
 687                                .ok();
 688                            }
 689                        });
 690                        active_tooltip.lock().replace(ActiveTooltip {
 691                            waiting: Some(task),
 692                            tooltip: None,
 693                        });
 694                    }
 695                });
 696
 697                if let Some(active_tooltip) = element_state.active_tooltip.lock().as_ref() {
 698                    if active_tooltip.tooltip.is_some() {
 699                        cx.active_tooltip = active_tooltip.tooltip.clone()
 700                    }
 701                }
 702            }
 703
 704            let active_state = element_state.active_state.clone();
 705            if active_state.lock().is_none() {
 706                let active_group_bounds = stateful
 707                    .group_active_style
 708                    .as_ref()
 709                    .and_then(|group_active| GroupBounds::get(&group_active.group, cx));
 710                cx.on_mouse_event(move |_view, down: &MouseDownEvent, phase, cx| {
 711                    if phase == DispatchPhase::Bubble {
 712                        let group = active_group_bounds
 713                            .map_or(false, |bounds| bounds.contains_point(&down.position));
 714                        let element = bounds.contains_point(&down.position);
 715                        if group || element {
 716                            *active_state.lock() = ActiveState { group, element };
 717                            cx.notify();
 718                        }
 719                    }
 720                });
 721            } else {
 722                cx.on_mouse_event(move |_, _: &MouseUpEvent, phase, cx| {
 723                    if phase == DispatchPhase::Capture {
 724                        *active_state.lock() = ActiveState::default();
 725                        cx.notify();
 726                    }
 727                });
 728            }
 729
 730            if overflow.x == Overflow::Scroll || overflow.y == Overflow::Scroll {
 731                let scroll_offset = element_state
 732                    .scroll_offset
 733                    .get_or_insert_with(Arc::default)
 734                    .clone();
 735                let line_height = cx.line_height();
 736                let scroll_max = (content_size - bounds.size).max(&Size::default());
 737
 738                cx.on_mouse_event(move |_, event: &ScrollWheelEvent, phase, cx| {
 739                    if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
 740                        let mut scroll_offset = scroll_offset.lock();
 741                        let old_scroll_offset = *scroll_offset;
 742                        let delta = event.delta.pixel_delta(line_height);
 743
 744                        if overflow.x == Overflow::Scroll {
 745                            scroll_offset.x =
 746                                (scroll_offset.x + delta.x).clamp(-scroll_max.width, px(0.));
 747                        }
 748
 749                        if overflow.y == Overflow::Scroll {
 750                            scroll_offset.y =
 751                                (scroll_offset.y + delta.y).clamp(-scroll_max.height, px(0.));
 752                        }
 753
 754                        if *scroll_offset != old_scroll_offset {
 755                            cx.notify();
 756                            cx.stop_propagation();
 757                        }
 758                    }
 759                });
 760            }
 761        }
 762    }
 763}
 764
 765#[derive(Deref, DerefMut)]
 766pub struct StatefulInteractivity<V> {
 767    pub id: ElementId,
 768    #[deref]
 769    #[deref_mut]
 770    stateless: StatelessInteractivity<V>,
 771    click_listeners: SmallVec<[ClickListener<V>; 2]>,
 772    active_style: StyleRefinement,
 773    group_active_style: Option<GroupStyle>,
 774    drag_listener: Option<DragListener<V>>,
 775    hover_listener: Option<HoverListener<V>>,
 776    tooltip_builder: Option<TooltipBuilder<V>>,
 777}
 778
 779impl<V: 'static> StatefulInteractivity<V> {
 780    pub fn new(id: ElementId, stateless: StatelessInteractivity<V>) -> Self {
 781        Self {
 782            id,
 783            stateless,
 784            click_listeners: SmallVec::new(),
 785            active_style: StyleRefinement::default(),
 786            group_active_style: None,
 787            drag_listener: None,
 788            hover_listener: None,
 789            tooltip_builder: None,
 790        }
 791    }
 792}
 793
 794impl<V: 'static> ElementInteractivity<V> for StatefulInteractivity<V> {
 795    fn as_stateful(&self) -> Option<&StatefulInteractivity<V>> {
 796        Some(self)
 797    }
 798
 799    fn as_stateful_mut(&mut self) -> Option<&mut StatefulInteractivity<V>> {
 800        Some(self)
 801    }
 802
 803    fn as_stateless(&self) -> &StatelessInteractivity<V> {
 804        &self.stateless
 805    }
 806
 807    fn as_stateless_mut(&mut self) -> &mut StatelessInteractivity<V> {
 808        &mut self.stateless
 809    }
 810}
 811
 812type DropListener<V> = dyn Fn(&mut V, AnyView, &mut ViewContext<V>) + 'static;
 813
 814pub struct StatelessInteractivity<V> {
 815    pub dispatch_context: DispatchContext,
 816    pub mouse_down_listeners: SmallVec<[MouseDownListener<V>; 2]>,
 817    pub mouse_up_listeners: SmallVec<[MouseUpListener<V>; 2]>,
 818    pub mouse_move_listeners: SmallVec<[MouseMoveListener<V>; 2]>,
 819    pub scroll_wheel_listeners: SmallVec<[ScrollWheelListener<V>; 2]>,
 820    pub key_listeners: SmallVec<[(TypeId, KeyListener<V>); 32]>,
 821    pub hover_style: StyleRefinement,
 822    pub group_hover_style: Option<GroupStyle>,
 823    drag_over_styles: SmallVec<[(TypeId, StyleRefinement); 2]>,
 824    group_drag_over_styles: SmallVec<[(TypeId, GroupStyle); 2]>,
 825    drop_listeners: SmallVec<[(TypeId, Box<DropListener<V>>); 2]>,
 826}
 827
 828impl<V> StatelessInteractivity<V> {
 829    pub fn into_stateful(self, id: impl Into<ElementId>) -> StatefulInteractivity<V> {
 830        StatefulInteractivity {
 831            id: id.into(),
 832            stateless: self,
 833            click_listeners: SmallVec::new(),
 834            drag_listener: None,
 835            hover_listener: None,
 836            tooltip_builder: None,
 837            active_style: StyleRefinement::default(),
 838            group_active_style: None,
 839        }
 840    }
 841}
 842
 843pub struct GroupStyle {
 844    pub group: SharedString,
 845    pub style: StyleRefinement,
 846}
 847
 848#[derive(Default)]
 849pub struct GroupBounds(HashMap<SharedString, SmallVec<[Bounds<Pixels>; 1]>>);
 850
 851impl GroupBounds {
 852    pub fn get(name: &SharedString, cx: &mut AppContext) -> Option<Bounds<Pixels>> {
 853        cx.default_global::<Self>()
 854            .0
 855            .get(name)
 856            .and_then(|bounds_stack| bounds_stack.last())
 857            .cloned()
 858    }
 859
 860    pub fn push(name: SharedString, bounds: Bounds<Pixels>, cx: &mut AppContext) {
 861        cx.default_global::<Self>()
 862            .0
 863            .entry(name)
 864            .or_default()
 865            .push(bounds);
 866    }
 867
 868    pub fn pop(name: &SharedString, cx: &mut AppContext) {
 869        cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
 870    }
 871}
 872
 873#[derive(Copy, Clone, Default, Eq, PartialEq)]
 874struct ActiveState {
 875    pub group: bool,
 876    pub element: bool,
 877}
 878
 879impl ActiveState {
 880    pub fn is_none(&self) -> bool {
 881        !self.group && !self.element
 882    }
 883}
 884
 885#[derive(Default)]
 886pub struct InteractiveElementState {
 887    active_state: Arc<Mutex<ActiveState>>,
 888    hover_state: Arc<Mutex<bool>>,
 889    pending_mouse_down: Arc<Mutex<Option<MouseDownEvent>>>,
 890    scroll_offset: Option<Arc<Mutex<Point<Pixels>>>>,
 891    active_tooltip: Arc<Mutex<Option<ActiveTooltip>>>,
 892}
 893
 894struct ActiveTooltip {
 895    #[allow(unused)] // used to drop the task
 896    waiting: Option<Task<()>>,
 897    tooltip: Option<AnyTooltip>,
 898}
 899
 900impl InteractiveElementState {
 901    pub fn scroll_offset(&self) -> Option<Point<Pixels>> {
 902        self.scroll_offset
 903            .as_ref()
 904            .map(|offset| offset.lock().clone())
 905    }
 906
 907    pub fn track_scroll_offset(&mut self) -> Arc<Mutex<Point<Pixels>>> {
 908        self.scroll_offset
 909            .get_or_insert_with(|| Arc::new(Mutex::new(Default::default())))
 910            .clone()
 911    }
 912}
 913
 914impl<V> Default for StatelessInteractivity<V> {
 915    fn default() -> Self {
 916        Self {
 917            dispatch_context: DispatchContext::default(),
 918            mouse_down_listeners: SmallVec::new(),
 919            mouse_up_listeners: SmallVec::new(),
 920            mouse_move_listeners: SmallVec::new(),
 921            scroll_wheel_listeners: SmallVec::new(),
 922            key_listeners: SmallVec::new(),
 923            hover_style: StyleRefinement::default(),
 924            group_hover_style: None,
 925            drag_over_styles: SmallVec::new(),
 926            group_drag_over_styles: SmallVec::new(),
 927            drop_listeners: SmallVec::new(),
 928        }
 929    }
 930}
 931
 932impl<V: 'static> ElementInteractivity<V> for StatelessInteractivity<V> {
 933    fn as_stateful(&self) -> Option<&StatefulInteractivity<V>> {
 934        None
 935    }
 936
 937    fn as_stateful_mut(&mut self) -> Option<&mut StatefulInteractivity<V>> {
 938        None
 939    }
 940
 941    fn as_stateless(&self) -> &StatelessInteractivity<V> {
 942        self
 943    }
 944
 945    fn as_stateless_mut(&mut self) -> &mut StatelessInteractivity<V> {
 946        self
 947    }
 948}
 949
 950#[derive(Clone, Debug, Eq, PartialEq)]
 951pub struct KeyDownEvent {
 952    pub keystroke: Keystroke,
 953    pub is_held: bool,
 954}
 955
 956#[derive(Clone, Debug)]
 957pub struct KeyUpEvent {
 958    pub keystroke: Keystroke,
 959}
 960
 961#[derive(Clone, Debug, Default)]
 962pub struct ModifiersChangedEvent {
 963    pub modifiers: Modifiers,
 964}
 965
 966impl Deref for ModifiersChangedEvent {
 967    type Target = Modifiers;
 968
 969    fn deref(&self) -> &Self::Target {
 970        &self.modifiers
 971    }
 972}
 973
 974/// The phase of a touch motion event.
 975/// Based on the winit enum of the same name.
 976#[derive(Clone, Copy, Debug)]
 977pub enum TouchPhase {
 978    Started,
 979    Moved,
 980    Ended,
 981}
 982
 983#[derive(Clone, Debug, Default)]
 984pub struct MouseDownEvent {
 985    pub button: MouseButton,
 986    pub position: Point<Pixels>,
 987    pub modifiers: Modifiers,
 988    pub click_count: usize,
 989}
 990
 991#[derive(Clone, Debug, Default)]
 992pub struct MouseUpEvent {
 993    pub button: MouseButton,
 994    pub position: Point<Pixels>,
 995    pub modifiers: Modifiers,
 996    pub click_count: usize,
 997}
 998
 999#[derive(Clone, Debug, Default)]
1000pub struct ClickEvent {
1001    pub down: MouseDownEvent,
1002    pub up: MouseUpEvent,
1003}
1004
1005pub struct Drag<S, R, V, E>
1006where
1007    R: Fn(&mut V, &mut ViewContext<V>) -> E,
1008    V: 'static,
1009    E: Component<()>,
1010{
1011    pub state: S,
1012    pub render_drag_handle: R,
1013    view_type: PhantomData<V>,
1014}
1015
1016impl<S, R, V, E> Drag<S, R, V, E>
1017where
1018    R: Fn(&mut V, &mut ViewContext<V>) -> E,
1019    V: 'static,
1020    E: Component<()>,
1021{
1022    pub fn new(state: S, render_drag_handle: R) -> Self {
1023        Drag {
1024            state,
1025            render_drag_handle,
1026            view_type: PhantomData,
1027        }
1028    }
1029}
1030
1031// impl<S, R, V, E> Render for Drag<S, R, V, E> {
1032//     // fn render(&mut self, cx: ViewContext<Self>) ->
1033// }
1034
1035#[derive(Hash, PartialEq, Eq, Copy, Clone, Debug)]
1036pub enum MouseButton {
1037    Left,
1038    Right,
1039    Middle,
1040    Navigate(NavigationDirection),
1041}
1042
1043impl MouseButton {
1044    pub fn all() -> Vec<Self> {
1045        vec![
1046            MouseButton::Left,
1047            MouseButton::Right,
1048            MouseButton::Middle,
1049            MouseButton::Navigate(NavigationDirection::Back),
1050            MouseButton::Navigate(NavigationDirection::Forward),
1051        ]
1052    }
1053}
1054
1055impl Default for MouseButton {
1056    fn default() -> Self {
1057        Self::Left
1058    }
1059}
1060
1061#[derive(Hash, PartialEq, Eq, Copy, Clone, Debug)]
1062pub enum NavigationDirection {
1063    Back,
1064    Forward,
1065}
1066
1067impl Default for NavigationDirection {
1068    fn default() -> Self {
1069        Self::Back
1070    }
1071}
1072
1073#[derive(Clone, Debug, Default)]
1074pub struct MouseMoveEvent {
1075    pub position: Point<Pixels>,
1076    pub pressed_button: Option<MouseButton>,
1077    pub modifiers: Modifiers,
1078}
1079
1080#[derive(Clone, Debug)]
1081pub struct ScrollWheelEvent {
1082    pub position: Point<Pixels>,
1083    pub delta: ScrollDelta,
1084    pub modifiers: Modifiers,
1085    pub touch_phase: TouchPhase,
1086}
1087
1088impl Deref for ScrollWheelEvent {
1089    type Target = Modifiers;
1090
1091    fn deref(&self) -> &Self::Target {
1092        &self.modifiers
1093    }
1094}
1095
1096#[derive(Clone, Copy, Debug)]
1097pub enum ScrollDelta {
1098    Pixels(Point<Pixels>),
1099    Lines(Point<f32>),
1100}
1101
1102impl Default for ScrollDelta {
1103    fn default() -> Self {
1104        Self::Lines(Default::default())
1105    }
1106}
1107
1108impl ScrollDelta {
1109    pub fn precise(&self) -> bool {
1110        match self {
1111            ScrollDelta::Pixels(_) => true,
1112            ScrollDelta::Lines(_) => false,
1113        }
1114    }
1115
1116    pub fn pixel_delta(&self, line_height: Pixels) -> Point<Pixels> {
1117        match self {
1118            ScrollDelta::Pixels(delta) => *delta,
1119            ScrollDelta::Lines(delta) => point(line_height * delta.x, line_height * delta.y),
1120        }
1121    }
1122}
1123
1124#[derive(Clone, Debug, Default)]
1125pub struct MouseExitEvent {
1126    pub position: Point<Pixels>,
1127    pub pressed_button: Option<MouseButton>,
1128    pub modifiers: Modifiers,
1129}
1130
1131impl Deref for MouseExitEvent {
1132    type Target = Modifiers;
1133
1134    fn deref(&self) -> &Self::Target {
1135        &self.modifiers
1136    }
1137}
1138
1139#[derive(Debug, Clone, Default)]
1140pub struct ExternalPaths(pub(crate) SmallVec<[PathBuf; 2]>);
1141
1142impl Render for ExternalPaths {
1143    type Element = Div<Self>;
1144
1145    fn render(&mut self, _: &mut ViewContext<Self>) -> Self::Element {
1146        div() // Intentionally left empty because the platform will render icons for the dragged files
1147    }
1148}
1149
1150#[derive(Debug, Clone)]
1151pub enum FileDropEvent {
1152    Entered {
1153        position: Point<Pixels>,
1154        files: ExternalPaths,
1155    },
1156    Pending {
1157        position: Point<Pixels>,
1158    },
1159    Submit {
1160        position: Point<Pixels>,
1161    },
1162    Exited,
1163}
1164
1165#[derive(Clone, Debug)]
1166pub enum InputEvent {
1167    KeyDown(KeyDownEvent),
1168    KeyUp(KeyUpEvent),
1169    ModifiersChanged(ModifiersChangedEvent),
1170    MouseDown(MouseDownEvent),
1171    MouseUp(MouseUpEvent),
1172    MouseMove(MouseMoveEvent),
1173    MouseExited(MouseExitEvent),
1174    ScrollWheel(ScrollWheelEvent),
1175    FileDrop(FileDropEvent),
1176}
1177
1178impl InputEvent {
1179    pub fn position(&self) -> Option<Point<Pixels>> {
1180        match self {
1181            InputEvent::KeyDown { .. } => None,
1182            InputEvent::KeyUp { .. } => None,
1183            InputEvent::ModifiersChanged { .. } => None,
1184            InputEvent::MouseDown(event) => Some(event.position),
1185            InputEvent::MouseUp(event) => Some(event.position),
1186            InputEvent::MouseMove(event) => Some(event.position),
1187            InputEvent::MouseExited(event) => Some(event.position),
1188            InputEvent::ScrollWheel(event) => Some(event.position),
1189            InputEvent::FileDrop(FileDropEvent::Exited) => None,
1190            InputEvent::FileDrop(
1191                FileDropEvent::Entered { position, .. }
1192                | FileDropEvent::Pending { position, .. }
1193                | FileDropEvent::Submit { position, .. },
1194            ) => Some(*position),
1195        }
1196    }
1197
1198    pub fn mouse_event<'a>(&'a self) -> Option<&'a dyn Any> {
1199        match self {
1200            InputEvent::KeyDown { .. } => None,
1201            InputEvent::KeyUp { .. } => None,
1202            InputEvent::ModifiersChanged { .. } => None,
1203            InputEvent::MouseDown(event) => Some(event),
1204            InputEvent::MouseUp(event) => Some(event),
1205            InputEvent::MouseMove(event) => Some(event),
1206            InputEvent::MouseExited(event) => Some(event),
1207            InputEvent::ScrollWheel(event) => Some(event),
1208            InputEvent::FileDrop(event) => Some(event),
1209        }
1210    }
1211
1212    pub fn keyboard_event<'a>(&'a self) -> Option<&'a dyn Any> {
1213        match self {
1214            InputEvent::KeyDown(event) => Some(event),
1215            InputEvent::KeyUp(event) => Some(event),
1216            InputEvent::ModifiersChanged(event) => Some(event),
1217            InputEvent::MouseDown(_) => None,
1218            InputEvent::MouseUp(_) => None,
1219            InputEvent::MouseMove(_) => None,
1220            InputEvent::MouseExited(_) => None,
1221            InputEvent::ScrollWheel(_) => None,
1222            InputEvent::FileDrop(_) => None,
1223        }
1224    }
1225}
1226
1227pub struct FocusEvent {
1228    pub blurred: Option<FocusHandle>,
1229    pub focused: Option<FocusHandle>,
1230}
1231
1232pub type MouseDownListener<V> = Box<
1233    dyn Fn(&mut V, &MouseDownEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
1234>;
1235pub type MouseUpListener<V> = Box<
1236    dyn Fn(&mut V, &MouseUpEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
1237>;
1238
1239pub type MouseMoveListener<V> = Box<
1240    dyn Fn(&mut V, &MouseMoveEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
1241>;
1242
1243pub type ScrollWheelListener<V> = Box<
1244    dyn Fn(&mut V, &ScrollWheelEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>)
1245        + 'static,
1246>;
1247
1248pub type ClickListener<V> = Box<dyn Fn(&mut V, &ClickEvent, &mut ViewContext<V>) + 'static>;
1249
1250pub(crate) type DragListener<V> =
1251    Box<dyn Fn(&mut V, Point<Pixels>, &mut ViewContext<V>) -> AnyDrag + 'static>;
1252
1253pub(crate) type HoverListener<V> = Box<dyn Fn(&mut V, bool, &mut ViewContext<V>) + 'static>;
1254
1255pub(crate) type TooltipBuilder<V> = Arc<dyn Fn(&mut V, &mut ViewContext<V>) -> AnyView + 'static>;
1256
1257pub type KeyListener<V> = Box<
1258    dyn Fn(
1259            &mut V,
1260            &dyn Any,
1261            &[&DispatchContext],
1262            DispatchPhase,
1263            &mut ViewContext<V>,
1264        ) -> Option<Box<dyn Action>>
1265        + 'static,
1266>;
1267
1268#[cfg(test)]
1269mod test {
1270    use crate::{
1271        self as gpui, div, Div, FocusHandle, KeyBinding, Keystroke, ParentElement, Render,
1272        StatefulInteractivity, StatelessInteractive, TestAppContext, VisualContext,
1273    };
1274
1275    struct TestView {
1276        saw_key_down: bool,
1277        saw_action: bool,
1278        focus_handle: FocusHandle,
1279    }
1280
1281    actions!(TestAction);
1282
1283    impl Render for TestView {
1284        type Element = Div<Self, StatefulInteractivity<Self>>;
1285
1286        fn render(&mut self, _: &mut gpui::ViewContext<Self>) -> Self::Element {
1287            div().id("testview").child(
1288                div()
1289                    .on_key_down(|this: &mut TestView, _, _, _| this.saw_key_down = true)
1290                    .on_action(|this: &mut TestView, _: &TestAction, _| this.saw_action = true)
1291                    .track_focus(&self.focus_handle),
1292            )
1293        }
1294    }
1295
1296    #[gpui::test]
1297    fn test_on_events(cx: &mut TestAppContext) {
1298        let window = cx.update(|cx| {
1299            cx.open_window(Default::default(), |cx| {
1300                cx.build_view(|cx| TestView {
1301                    saw_key_down: false,
1302                    saw_action: false,
1303                    focus_handle: cx.focus_handle(),
1304                })
1305            })
1306        });
1307
1308        cx.update(|cx| {
1309            cx.bind_keys(vec![KeyBinding::new("ctrl-g", TestAction, None)]);
1310        });
1311
1312        window
1313            .update(cx, |test_view, cx| cx.focus(&test_view.focus_handle))
1314            .unwrap();
1315
1316        cx.dispatch_keystroke(*window, Keystroke::parse("space").unwrap(), false);
1317        cx.dispatch_keystroke(*window, Keystroke::parse("ctrl-g").unwrap(), false);
1318
1319        window
1320            .update(cx, |test_view, _| {
1321                assert!(test_view.saw_key_down || test_view.saw_action);
1322                assert!(test_view.saw_key_down);
1323                assert!(test_view.saw_action);
1324            })
1325            .unwrap();
1326    }
1327}