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