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                            dbg!(&context);
 418                            if let KeyMatch::Some(action) =
 419                                cx.match_keystroke(&global_id, &key_down.keystroke, context)
 420                            {
 421                                return Some(action);
 422                            }
 423                        }
 424
 425                        None
 426                    }),
 427                ));
 428
 429                cx.with_key_dispatch_context(stateful.dispatch_context.clone(), |cx| {
 430                    cx.with_key_listeners(mem::take(&mut stateful.key_listeners), f)
 431                })
 432            })
 433        } else {
 434            let stateless = self.as_stateless_mut();
 435            cx.with_key_dispatch_context(stateless.dispatch_context.clone(), |cx| {
 436                cx.with_key_listeners(mem::take(&mut stateless.key_listeners), f)
 437            })
 438        }
 439    }
 440
 441    fn refine_style(
 442        &self,
 443        style: &mut Style,
 444        bounds: Bounds<Pixels>,
 445        element_state: &InteractiveElementState,
 446        cx: &mut ViewContext<V>,
 447    ) {
 448        let mouse_position = cx.mouse_position();
 449        let stateless = self.as_stateless();
 450        if let Some(group_hover) = stateless.group_hover_style.as_ref() {
 451            if let Some(group_bounds) = GroupBounds::get(&group_hover.group, cx) {
 452                if group_bounds.contains_point(&mouse_position) {
 453                    style.refine(&group_hover.style);
 454                }
 455            }
 456        }
 457        if bounds.contains_point(&mouse_position) {
 458            style.refine(&stateless.hover_style);
 459        }
 460
 461        if let Some(drag) = cx.active_drag.take() {
 462            for (state_type, group_drag_style) in &self.as_stateless().group_drag_over_styles {
 463                if let Some(group_bounds) = GroupBounds::get(&group_drag_style.group, cx) {
 464                    if *state_type == drag.view.entity_type()
 465                        && group_bounds.contains_point(&mouse_position)
 466                    {
 467                        style.refine(&group_drag_style.style);
 468                    }
 469                }
 470            }
 471
 472            for (state_type, drag_over_style) in &self.as_stateless().drag_over_styles {
 473                if *state_type == drag.view.entity_type() && bounds.contains_point(&mouse_position)
 474                {
 475                    style.refine(drag_over_style);
 476                }
 477            }
 478
 479            cx.active_drag = Some(drag);
 480        }
 481
 482        if let Some(stateful) = self.as_stateful() {
 483            let active_state = element_state.active_state.lock();
 484            if active_state.group {
 485                if let Some(group_style) = stateful.group_active_style.as_ref() {
 486                    style.refine(&group_style.style);
 487                }
 488            }
 489            if active_state.element {
 490                style.refine(&stateful.active_style);
 491            }
 492        }
 493    }
 494
 495    fn paint(
 496        &mut self,
 497        bounds: Bounds<Pixels>,
 498        content_size: Size<Pixels>,
 499        overflow: Point<Overflow>,
 500        element_state: &mut InteractiveElementState,
 501        cx: &mut ViewContext<V>,
 502    ) {
 503        let stateless = self.as_stateless_mut();
 504        for listener in stateless.mouse_down_listeners.drain(..) {
 505            cx.on_mouse_event(move |state, event: &MouseDownEvent, phase, cx| {
 506                listener(state, event, &bounds, phase, cx);
 507            })
 508        }
 509
 510        for listener in stateless.mouse_up_listeners.drain(..) {
 511            cx.on_mouse_event(move |state, event: &MouseUpEvent, phase, cx| {
 512                listener(state, event, &bounds, phase, cx);
 513            })
 514        }
 515
 516        for listener in stateless.mouse_move_listeners.drain(..) {
 517            cx.on_mouse_event(move |state, event: &MouseMoveEvent, phase, cx| {
 518                listener(state, event, &bounds, phase, cx);
 519            })
 520        }
 521
 522        for listener in stateless.scroll_wheel_listeners.drain(..) {
 523            cx.on_mouse_event(move |state, event: &ScrollWheelEvent, phase, cx| {
 524                listener(state, event, &bounds, phase, cx);
 525            })
 526        }
 527
 528        let hover_group_bounds = stateless
 529            .group_hover_style
 530            .as_ref()
 531            .and_then(|group_hover| GroupBounds::get(&group_hover.group, cx));
 532
 533        if let Some(group_bounds) = hover_group_bounds {
 534            let hovered = group_bounds.contains_point(&cx.mouse_position());
 535            cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
 536                if phase == DispatchPhase::Capture {
 537                    if group_bounds.contains_point(&event.position) != hovered {
 538                        cx.notify();
 539                    }
 540                }
 541            });
 542        }
 543
 544        if stateless.hover_style.is_some()
 545            || (cx.active_drag.is_some() && !stateless.drag_over_styles.is_empty())
 546        {
 547            let hovered = bounds.contains_point(&cx.mouse_position());
 548            cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
 549                if phase == DispatchPhase::Capture {
 550                    if bounds.contains_point(&event.position) != hovered {
 551                        cx.notify();
 552                    }
 553                }
 554            });
 555        }
 556
 557        if cx.active_drag.is_some() {
 558            let drop_listeners = mem::take(&mut stateless.drop_listeners);
 559            cx.on_mouse_event(move |view, event: &MouseUpEvent, phase, cx| {
 560                if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
 561                    if let Some(drag_state_type) =
 562                        cx.active_drag.as_ref().map(|drag| drag.view.entity_type())
 563                    {
 564                        for (drop_state_type, listener) in &drop_listeners {
 565                            if *drop_state_type == drag_state_type {
 566                                let drag = cx
 567                                    .active_drag
 568                                    .take()
 569                                    .expect("checked for type drag state type above");
 570                                listener(view, drag.view.clone(), cx);
 571                                cx.notify();
 572                                cx.stop_propagation();
 573                            }
 574                        }
 575                    }
 576                }
 577            });
 578        }
 579
 580        if let Some(stateful) = self.as_stateful_mut() {
 581            let click_listeners = mem::take(&mut stateful.click_listeners);
 582            let drag_listener = mem::take(&mut stateful.drag_listener);
 583
 584            if !click_listeners.is_empty() || drag_listener.is_some() {
 585                let pending_mouse_down = element_state.pending_mouse_down.clone();
 586                let mouse_down = pending_mouse_down.lock().clone();
 587                if let Some(mouse_down) = mouse_down {
 588                    if let Some(drag_listener) = drag_listener {
 589                        let active_state = element_state.active_state.clone();
 590
 591                        cx.on_mouse_event(move |view_state, event: &MouseMoveEvent, phase, cx| {
 592                            if cx.active_drag.is_some() {
 593                                if phase == DispatchPhase::Capture {
 594                                    cx.notify();
 595                                }
 596                            } else if phase == DispatchPhase::Bubble
 597                                && bounds.contains_point(&event.position)
 598                                && (event.position - mouse_down.position).magnitude()
 599                                    > DRAG_THRESHOLD
 600                            {
 601                                *active_state.lock() = ActiveState::default();
 602                                let cursor_offset = event.position - bounds.origin;
 603                                let drag = drag_listener(view_state, cursor_offset, cx);
 604                                cx.active_drag = Some(drag);
 605                                cx.notify();
 606                                cx.stop_propagation();
 607                            }
 608                        });
 609                    }
 610
 611                    cx.on_mouse_event(move |view_state, event: &MouseUpEvent, phase, cx| {
 612                        if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position)
 613                        {
 614                            let mouse_click = ClickEvent {
 615                                down: mouse_down.clone(),
 616                                up: event.clone(),
 617                            };
 618                            for listener in &click_listeners {
 619                                listener(view_state, &mouse_click, cx);
 620                            }
 621                        }
 622                        *pending_mouse_down.lock() = None;
 623                    });
 624                } else {
 625                    cx.on_mouse_event(move |_state, event: &MouseDownEvent, phase, _cx| {
 626                        if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position)
 627                        {
 628                            *pending_mouse_down.lock() = Some(event.clone());
 629                        }
 630                    });
 631                }
 632            }
 633
 634            if let Some(hover_listener) = stateful.hover_listener.take() {
 635                let was_hovered = element_state.hover_state.clone();
 636                let has_mouse_down = element_state.pending_mouse_down.clone();
 637
 638                cx.on_mouse_event(move |view_state, event: &MouseMoveEvent, phase, cx| {
 639                    if phase != DispatchPhase::Bubble {
 640                        return;
 641                    }
 642                    let is_hovered =
 643                        bounds.contains_point(&event.position) && has_mouse_down.lock().is_none();
 644                    let mut was_hovered = was_hovered.lock();
 645
 646                    if is_hovered != was_hovered.clone() {
 647                        *was_hovered = is_hovered;
 648                        drop(was_hovered);
 649
 650                        hover_listener(view_state, is_hovered, cx);
 651                    }
 652                });
 653            }
 654
 655            if let Some(tooltip_builder) = stateful.tooltip_builder.take() {
 656                let active_tooltip = element_state.active_tooltip.clone();
 657                let pending_mouse_down = element_state.pending_mouse_down.clone();
 658
 659                cx.on_mouse_event(move |_, event: &MouseMoveEvent, phase, cx| {
 660                    if phase != DispatchPhase::Bubble {
 661                        return;
 662                    }
 663
 664                    let is_hovered = bounds.contains_point(&event.position)
 665                        && pending_mouse_down.lock().is_none();
 666                    if !is_hovered {
 667                        active_tooltip.lock().take();
 668                        return;
 669                    }
 670
 671                    if active_tooltip.lock().is_none() {
 672                        let task = cx.spawn({
 673                            let active_tooltip = active_tooltip.clone();
 674                            let tooltip_builder = tooltip_builder.clone();
 675
 676                            move |view, mut cx| async move {
 677                                cx.background_executor().timer(TOOLTIP_DELAY).await;
 678                                view.update(&mut cx, move |view_state, cx| {
 679                                    active_tooltip.lock().replace(ActiveTooltip {
 680                                        waiting: None,
 681                                        tooltip: Some(AnyTooltip {
 682                                            view: tooltip_builder(view_state, cx),
 683                                            cursor_offset: cx.mouse_position() + TOOLTIP_OFFSET,
 684                                        }),
 685                                    });
 686                                    cx.notify();
 687                                })
 688                                .ok();
 689                            }
 690                        });
 691                        active_tooltip.lock().replace(ActiveTooltip {
 692                            waiting: Some(task),
 693                            tooltip: None,
 694                        });
 695                    }
 696                });
 697
 698                if let Some(active_tooltip) = element_state.active_tooltip.lock().as_ref() {
 699                    if active_tooltip.tooltip.is_some() {
 700                        cx.active_tooltip = active_tooltip.tooltip.clone()
 701                    }
 702                }
 703            }
 704
 705            let active_state = element_state.active_state.clone();
 706            if active_state.lock().is_none() {
 707                let active_group_bounds = stateful
 708                    .group_active_style
 709                    .as_ref()
 710                    .and_then(|group_active| GroupBounds::get(&group_active.group, cx));
 711                cx.on_mouse_event(move |_view, down: &MouseDownEvent, phase, cx| {
 712                    if phase == DispatchPhase::Bubble {
 713                        let group = active_group_bounds
 714                            .map_or(false, |bounds| bounds.contains_point(&down.position));
 715                        let element = bounds.contains_point(&down.position);
 716                        if group || element {
 717                            *active_state.lock() = ActiveState { group, element };
 718                            cx.notify();
 719                        }
 720                    }
 721                });
 722            } else {
 723                cx.on_mouse_event(move |_, _: &MouseUpEvent, phase, cx| {
 724                    if phase == DispatchPhase::Capture {
 725                        *active_state.lock() = ActiveState::default();
 726                        cx.notify();
 727                    }
 728                });
 729            }
 730
 731            if overflow.x == Overflow::Scroll || overflow.y == Overflow::Scroll {
 732                let scroll_offset = element_state
 733                    .scroll_offset
 734                    .get_or_insert_with(Arc::default)
 735                    .clone();
 736                let line_height = cx.line_height();
 737                let scroll_max = (content_size - bounds.size).max(&Size::default());
 738
 739                cx.on_mouse_event(move |_, event: &ScrollWheelEvent, phase, cx| {
 740                    if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
 741                        let mut scroll_offset = scroll_offset.lock();
 742                        let old_scroll_offset = *scroll_offset;
 743                        let delta = event.delta.pixel_delta(line_height);
 744
 745                        if overflow.x == Overflow::Scroll {
 746                            scroll_offset.x =
 747                                (scroll_offset.x + delta.x).clamp(-scroll_max.width, px(0.));
 748                        }
 749
 750                        if overflow.y == Overflow::Scroll {
 751                            scroll_offset.y =
 752                                (scroll_offset.y + delta.y).clamp(-scroll_max.height, px(0.));
 753                        }
 754
 755                        if *scroll_offset != old_scroll_offset {
 756                            cx.notify();
 757                            cx.stop_propagation();
 758                        }
 759                    }
 760                });
 761            }
 762        }
 763    }
 764}
 765
 766#[derive(Deref, DerefMut)]
 767pub struct StatefulInteractivity<V> {
 768    pub id: ElementId,
 769    #[deref]
 770    #[deref_mut]
 771    stateless: StatelessInteractivity<V>,
 772    click_listeners: SmallVec<[ClickListener<V>; 2]>,
 773    active_style: StyleRefinement,
 774    group_active_style: Option<GroupStyle>,
 775    drag_listener: Option<DragListener<V>>,
 776    hover_listener: Option<HoverListener<V>>,
 777    tooltip_builder: Option<TooltipBuilder<V>>,
 778}
 779
 780impl<V: 'static> StatefulInteractivity<V> {
 781    pub fn new(id: ElementId, stateless: StatelessInteractivity<V>) -> Self {
 782        Self {
 783            id,
 784            stateless,
 785            click_listeners: SmallVec::new(),
 786            active_style: StyleRefinement::default(),
 787            group_active_style: None,
 788            drag_listener: None,
 789            hover_listener: None,
 790            tooltip_builder: None,
 791        }
 792    }
 793}
 794
 795impl<V: 'static> ElementInteractivity<V> for StatefulInteractivity<V> {
 796    fn as_stateful(&self) -> Option<&StatefulInteractivity<V>> {
 797        Some(self)
 798    }
 799
 800    fn as_stateful_mut(&mut self) -> Option<&mut StatefulInteractivity<V>> {
 801        Some(self)
 802    }
 803
 804    fn as_stateless(&self) -> &StatelessInteractivity<V> {
 805        &self.stateless
 806    }
 807
 808    fn as_stateless_mut(&mut self) -> &mut StatelessInteractivity<V> {
 809        &mut self.stateless
 810    }
 811}
 812
 813type DropListener<V> = dyn Fn(&mut V, AnyView, &mut ViewContext<V>) + 'static;
 814
 815pub struct StatelessInteractivity<V> {
 816    pub dispatch_context: DispatchContext,
 817    pub mouse_down_listeners: SmallVec<[MouseDownListener<V>; 2]>,
 818    pub mouse_up_listeners: SmallVec<[MouseUpListener<V>; 2]>,
 819    pub mouse_move_listeners: SmallVec<[MouseMoveListener<V>; 2]>,
 820    pub scroll_wheel_listeners: SmallVec<[ScrollWheelListener<V>; 2]>,
 821    pub key_listeners: SmallVec<[(TypeId, KeyListener<V>); 32]>,
 822    pub hover_style: StyleRefinement,
 823    pub group_hover_style: Option<GroupStyle>,
 824    drag_over_styles: SmallVec<[(TypeId, StyleRefinement); 2]>,
 825    group_drag_over_styles: SmallVec<[(TypeId, GroupStyle); 2]>,
 826    drop_listeners: SmallVec<[(TypeId, Box<DropListener<V>>); 2]>,
 827}
 828
 829impl<V> StatelessInteractivity<V> {
 830    pub fn into_stateful(self, id: impl Into<ElementId>) -> StatefulInteractivity<V> {
 831        StatefulInteractivity {
 832            id: id.into(),
 833            stateless: self,
 834            click_listeners: SmallVec::new(),
 835            drag_listener: None,
 836            hover_listener: None,
 837            tooltip_builder: None,
 838            active_style: StyleRefinement::default(),
 839            group_active_style: None,
 840        }
 841    }
 842}
 843
 844pub struct GroupStyle {
 845    pub group: SharedString,
 846    pub style: StyleRefinement,
 847}
 848
 849#[derive(Default)]
 850pub struct GroupBounds(HashMap<SharedString, SmallVec<[Bounds<Pixels>; 1]>>);
 851
 852impl GroupBounds {
 853    pub fn get(name: &SharedString, cx: &mut AppContext) -> Option<Bounds<Pixels>> {
 854        cx.default_global::<Self>()
 855            .0
 856            .get(name)
 857            .and_then(|bounds_stack| bounds_stack.last())
 858            .cloned()
 859    }
 860
 861    pub fn push(name: SharedString, bounds: Bounds<Pixels>, cx: &mut AppContext) {
 862        cx.default_global::<Self>()
 863            .0
 864            .entry(name)
 865            .or_default()
 866            .push(bounds);
 867    }
 868
 869    pub fn pop(name: &SharedString, cx: &mut AppContext) {
 870        cx.default_global::<Self>().0.get_mut(name).unwrap().pop();
 871    }
 872}
 873
 874#[derive(Copy, Clone, Default, Eq, PartialEq)]
 875struct ActiveState {
 876    pub group: bool,
 877    pub element: bool,
 878}
 879
 880impl ActiveState {
 881    pub fn is_none(&self) -> bool {
 882        !self.group && !self.element
 883    }
 884}
 885
 886#[derive(Default)]
 887pub struct InteractiveElementState {
 888    active_state: Arc<Mutex<ActiveState>>,
 889    hover_state: Arc<Mutex<bool>>,
 890    pending_mouse_down: Arc<Mutex<Option<MouseDownEvent>>>,
 891    scroll_offset: Option<Arc<Mutex<Point<Pixels>>>>,
 892    active_tooltip: Arc<Mutex<Option<ActiveTooltip>>>,
 893}
 894
 895struct ActiveTooltip {
 896    #[allow(unused)] // used to drop the task
 897    waiting: Option<Task<()>>,
 898    tooltip: Option<AnyTooltip>,
 899}
 900
 901impl InteractiveElementState {
 902    pub fn scroll_offset(&self) -> Option<Point<Pixels>> {
 903        self.scroll_offset
 904            .as_ref()
 905            .map(|offset| offset.lock().clone())
 906    }
 907
 908    pub fn track_scroll_offset(&mut self) -> Arc<Mutex<Point<Pixels>>> {
 909        self.scroll_offset
 910            .get_or_insert_with(|| Arc::new(Mutex::new(Default::default())))
 911            .clone()
 912    }
 913}
 914
 915impl<V> Default for StatelessInteractivity<V> {
 916    fn default() -> Self {
 917        Self {
 918            dispatch_context: DispatchContext::default(),
 919            mouse_down_listeners: SmallVec::new(),
 920            mouse_up_listeners: SmallVec::new(),
 921            mouse_move_listeners: SmallVec::new(),
 922            scroll_wheel_listeners: SmallVec::new(),
 923            key_listeners: SmallVec::new(),
 924            hover_style: StyleRefinement::default(),
 925            group_hover_style: None,
 926            drag_over_styles: SmallVec::new(),
 927            group_drag_over_styles: SmallVec::new(),
 928            drop_listeners: SmallVec::new(),
 929        }
 930    }
 931}
 932
 933impl<V: 'static> ElementInteractivity<V> for StatelessInteractivity<V> {
 934    fn as_stateful(&self) -> Option<&StatefulInteractivity<V>> {
 935        None
 936    }
 937
 938    fn as_stateful_mut(&mut self) -> Option<&mut StatefulInteractivity<V>> {
 939        None
 940    }
 941
 942    fn as_stateless(&self) -> &StatelessInteractivity<V> {
 943        self
 944    }
 945
 946    fn as_stateless_mut(&mut self) -> &mut StatelessInteractivity<V> {
 947        self
 948    }
 949}
 950
 951#[derive(Clone, Debug, Eq, PartialEq)]
 952pub struct KeyDownEvent {
 953    pub keystroke: Keystroke,
 954    pub is_held: bool,
 955}
 956
 957#[derive(Clone, Debug)]
 958pub struct KeyUpEvent {
 959    pub keystroke: Keystroke,
 960}
 961
 962#[derive(Clone, Debug, Default)]
 963pub struct ModifiersChangedEvent {
 964    pub modifiers: Modifiers,
 965}
 966
 967impl Deref for ModifiersChangedEvent {
 968    type Target = Modifiers;
 969
 970    fn deref(&self) -> &Self::Target {
 971        &self.modifiers
 972    }
 973}
 974
 975/// The phase of a touch motion event.
 976/// Based on the winit enum of the same name.
 977#[derive(Clone, Copy, Debug)]
 978pub enum TouchPhase {
 979    Started,
 980    Moved,
 981    Ended,
 982}
 983
 984#[derive(Clone, Debug, Default)]
 985pub struct MouseDownEvent {
 986    pub button: MouseButton,
 987    pub position: Point<Pixels>,
 988    pub modifiers: Modifiers,
 989    pub click_count: usize,
 990}
 991
 992#[derive(Clone, Debug, Default)]
 993pub struct MouseUpEvent {
 994    pub button: MouseButton,
 995    pub position: Point<Pixels>,
 996    pub modifiers: Modifiers,
 997    pub click_count: usize,
 998}
 999
1000#[derive(Clone, Debug, Default)]
1001pub struct ClickEvent {
1002    pub down: MouseDownEvent,
1003    pub up: MouseUpEvent,
1004}
1005
1006pub struct Drag<S, R, V, E>
1007where
1008    R: Fn(&mut V, &mut ViewContext<V>) -> E,
1009    V: 'static,
1010    E: Component<()>,
1011{
1012    pub state: S,
1013    pub render_drag_handle: R,
1014    view_type: PhantomData<V>,
1015}
1016
1017impl<S, R, V, E> Drag<S, R, V, E>
1018where
1019    R: Fn(&mut V, &mut ViewContext<V>) -> E,
1020    V: 'static,
1021    E: Component<()>,
1022{
1023    pub fn new(state: S, render_drag_handle: R) -> Self {
1024        Drag {
1025            state,
1026            render_drag_handle,
1027            view_type: PhantomData,
1028        }
1029    }
1030}
1031
1032// impl<S, R, V, E> Render for Drag<S, R, V, E> {
1033//     // fn render(&mut self, cx: ViewContext<Self>) ->
1034// }
1035
1036#[derive(Hash, PartialEq, Eq, Copy, Clone, Debug)]
1037pub enum MouseButton {
1038    Left,
1039    Right,
1040    Middle,
1041    Navigate(NavigationDirection),
1042}
1043
1044impl MouseButton {
1045    pub fn all() -> Vec<Self> {
1046        vec![
1047            MouseButton::Left,
1048            MouseButton::Right,
1049            MouseButton::Middle,
1050            MouseButton::Navigate(NavigationDirection::Back),
1051            MouseButton::Navigate(NavigationDirection::Forward),
1052        ]
1053    }
1054}
1055
1056impl Default for MouseButton {
1057    fn default() -> Self {
1058        Self::Left
1059    }
1060}
1061
1062#[derive(Hash, PartialEq, Eq, Copy, Clone, Debug)]
1063pub enum NavigationDirection {
1064    Back,
1065    Forward,
1066}
1067
1068impl Default for NavigationDirection {
1069    fn default() -> Self {
1070        Self::Back
1071    }
1072}
1073
1074#[derive(Clone, Debug, Default)]
1075pub struct MouseMoveEvent {
1076    pub position: Point<Pixels>,
1077    pub pressed_button: Option<MouseButton>,
1078    pub modifiers: Modifiers,
1079}
1080
1081#[derive(Clone, Debug)]
1082pub struct ScrollWheelEvent {
1083    pub position: Point<Pixels>,
1084    pub delta: ScrollDelta,
1085    pub modifiers: Modifiers,
1086    pub touch_phase: TouchPhase,
1087}
1088
1089impl Deref for ScrollWheelEvent {
1090    type Target = Modifiers;
1091
1092    fn deref(&self) -> &Self::Target {
1093        &self.modifiers
1094    }
1095}
1096
1097#[derive(Clone, Copy, Debug)]
1098pub enum ScrollDelta {
1099    Pixels(Point<Pixels>),
1100    Lines(Point<f32>),
1101}
1102
1103impl Default for ScrollDelta {
1104    fn default() -> Self {
1105        Self::Lines(Default::default())
1106    }
1107}
1108
1109impl ScrollDelta {
1110    pub fn precise(&self) -> bool {
1111        match self {
1112            ScrollDelta::Pixels(_) => true,
1113            ScrollDelta::Lines(_) => false,
1114        }
1115    }
1116
1117    pub fn pixel_delta(&self, line_height: Pixels) -> Point<Pixels> {
1118        match self {
1119            ScrollDelta::Pixels(delta) => *delta,
1120            ScrollDelta::Lines(delta) => point(line_height * delta.x, line_height * delta.y),
1121        }
1122    }
1123}
1124
1125#[derive(Clone, Debug, Default)]
1126pub struct MouseExitEvent {
1127    pub position: Point<Pixels>,
1128    pub pressed_button: Option<MouseButton>,
1129    pub modifiers: Modifiers,
1130}
1131
1132impl Deref for MouseExitEvent {
1133    type Target = Modifiers;
1134
1135    fn deref(&self) -> &Self::Target {
1136        &self.modifiers
1137    }
1138}
1139
1140#[derive(Debug, Clone, Default)]
1141pub struct ExternalPaths(pub(crate) SmallVec<[PathBuf; 2]>);
1142
1143impl Render for ExternalPaths {
1144    type Element = Div<Self>;
1145
1146    fn render(&mut self, _: &mut ViewContext<Self>) -> Self::Element {
1147        div() // Intentionally left empty because the platform will render icons for the dragged files
1148    }
1149}
1150
1151#[derive(Debug, Clone)]
1152pub enum FileDropEvent {
1153    Entered {
1154        position: Point<Pixels>,
1155        files: ExternalPaths,
1156    },
1157    Pending {
1158        position: Point<Pixels>,
1159    },
1160    Submit {
1161        position: Point<Pixels>,
1162    },
1163    Exited,
1164}
1165
1166#[derive(Clone, Debug)]
1167pub enum InputEvent {
1168    KeyDown(KeyDownEvent),
1169    KeyUp(KeyUpEvent),
1170    ModifiersChanged(ModifiersChangedEvent),
1171    MouseDown(MouseDownEvent),
1172    MouseUp(MouseUpEvent),
1173    MouseMove(MouseMoveEvent),
1174    MouseExited(MouseExitEvent),
1175    ScrollWheel(ScrollWheelEvent),
1176    FileDrop(FileDropEvent),
1177}
1178
1179impl InputEvent {
1180    pub fn position(&self) -> Option<Point<Pixels>> {
1181        match self {
1182            InputEvent::KeyDown { .. } => None,
1183            InputEvent::KeyUp { .. } => None,
1184            InputEvent::ModifiersChanged { .. } => None,
1185            InputEvent::MouseDown(event) => Some(event.position),
1186            InputEvent::MouseUp(event) => Some(event.position),
1187            InputEvent::MouseMove(event) => Some(event.position),
1188            InputEvent::MouseExited(event) => Some(event.position),
1189            InputEvent::ScrollWheel(event) => Some(event.position),
1190            InputEvent::FileDrop(FileDropEvent::Exited) => None,
1191            InputEvent::FileDrop(
1192                FileDropEvent::Entered { position, .. }
1193                | FileDropEvent::Pending { position, .. }
1194                | FileDropEvent::Submit { position, .. },
1195            ) => Some(*position),
1196        }
1197    }
1198
1199    pub fn mouse_event<'a>(&'a self) -> Option<&'a dyn Any> {
1200        match self {
1201            InputEvent::KeyDown { .. } => None,
1202            InputEvent::KeyUp { .. } => None,
1203            InputEvent::ModifiersChanged { .. } => None,
1204            InputEvent::MouseDown(event) => Some(event),
1205            InputEvent::MouseUp(event) => Some(event),
1206            InputEvent::MouseMove(event) => Some(event),
1207            InputEvent::MouseExited(event) => Some(event),
1208            InputEvent::ScrollWheel(event) => Some(event),
1209            InputEvent::FileDrop(event) => Some(event),
1210        }
1211    }
1212
1213    pub fn keyboard_event<'a>(&'a self) -> Option<&'a dyn Any> {
1214        match self {
1215            InputEvent::KeyDown(event) => Some(event),
1216            InputEvent::KeyUp(event) => Some(event),
1217            InputEvent::ModifiersChanged(event) => Some(event),
1218            InputEvent::MouseDown(_) => None,
1219            InputEvent::MouseUp(_) => None,
1220            InputEvent::MouseMove(_) => None,
1221            InputEvent::MouseExited(_) => None,
1222            InputEvent::ScrollWheel(_) => None,
1223            InputEvent::FileDrop(_) => None,
1224        }
1225    }
1226}
1227
1228pub struct FocusEvent {
1229    pub blurred: Option<FocusHandle>,
1230    pub focused: Option<FocusHandle>,
1231}
1232
1233pub type MouseDownListener<V> = Box<
1234    dyn Fn(&mut V, &MouseDownEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
1235>;
1236pub type MouseUpListener<V> = Box<
1237    dyn Fn(&mut V, &MouseUpEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
1238>;
1239
1240pub type MouseMoveListener<V> = Box<
1241    dyn Fn(&mut V, &MouseMoveEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
1242>;
1243
1244pub type ScrollWheelListener<V> = Box<
1245    dyn Fn(&mut V, &ScrollWheelEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>)
1246        + 'static,
1247>;
1248
1249pub type ClickListener<V> = Box<dyn Fn(&mut V, &ClickEvent, &mut ViewContext<V>) + 'static>;
1250
1251pub(crate) type DragListener<V> =
1252    Box<dyn Fn(&mut V, Point<Pixels>, &mut ViewContext<V>) -> AnyDrag + 'static>;
1253
1254pub(crate) type HoverListener<V> = Box<dyn Fn(&mut V, bool, &mut ViewContext<V>) + 'static>;
1255
1256pub(crate) type TooltipBuilder<V> = Arc<dyn Fn(&mut V, &mut ViewContext<V>) -> AnyView + 'static>;
1257
1258pub type KeyListener<V> = Box<
1259    dyn Fn(
1260            &mut V,
1261            &dyn Any,
1262            &[&DispatchContext],
1263            DispatchPhase,
1264            &mut ViewContext<V>,
1265        ) -> Option<Box<dyn Action>>
1266        + 'static,
1267>;
1268
1269#[cfg(test)]
1270mod test {
1271    use crate::{
1272        self as gpui, div, Div, FocusHandle, KeyBinding, Keystroke, ParentElement, Render,
1273        StatefulInteractivity, StatelessInteractive, TestAppContext, VisualContext,
1274    };
1275
1276    struct TestView {
1277        saw_key_down: bool,
1278        saw_action: bool,
1279        focus_handle: FocusHandle,
1280    }
1281
1282    actions!(TestAction);
1283
1284    impl Render for TestView {
1285        type Element = Div<Self, StatefulInteractivity<Self>>;
1286
1287        fn render(&mut self, _: &mut gpui::ViewContext<Self>) -> Self::Element {
1288            div().id("testview").child(
1289                div()
1290                    .on_key_down(|this: &mut TestView, _, _, _| this.saw_key_down = true)
1291                    .on_action(|this: &mut TestView, _: &TestAction, _| this.saw_action = true)
1292                    .track_focus(&self.focus_handle),
1293            )
1294        }
1295    }
1296
1297    #[gpui::test]
1298    fn test_on_events(cx: &mut TestAppContext) {
1299        let window = cx.update(|cx| {
1300            cx.open_window(Default::default(), |cx| {
1301                cx.build_view(|cx| TestView {
1302                    saw_key_down: false,
1303                    saw_action: false,
1304                    focus_handle: cx.focus_handle(),
1305                })
1306            })
1307        });
1308
1309        cx.update(|cx| {
1310            cx.bind_keys(vec![KeyBinding::new("ctrl-g", TestAction, None)]);
1311        });
1312
1313        window
1314            .update(cx, |test_view, cx| cx.focus(&test_view.focus_handle))
1315            .unwrap();
1316
1317        cx.dispatch_keystroke(*window, Keystroke::parse("space").unwrap(), false);
1318        cx.dispatch_keystroke(*window, Keystroke::parse("ctrl-g").unwrap(), false);
1319
1320        window
1321            .update(cx, |test_view, _| {
1322                assert!(test_view.saw_key_down || test_view.saw_action);
1323                assert!(test_view.saw_key_down);
1324                assert!(test_view.saw_action);
1325            })
1326            .unwrap();
1327    }
1328}