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